Remove always defined FEATURE_CORECLR
[platform/upstream/coreclr.git] / src / debug / di / cordb.cpp
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 //*****************************************************************************
5 // CorDB.cpp
6 // 
7
8 //
9 // Dll* routines for entry points, and support for COM framework.  The class
10 // factory and other routines live in this module.
11 //
12 //*****************************************************************************
13 #include "stdafx.h"
14 #include "classfactory.h"
15 #include "corsym.h"
16 #include "contract.h"
17 #include "metadataexports.h"
18 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
19 #include "dbgtransportsession.h"
20 #include "dbgtransportmanager.h"
21 #endif // FEATURE_DBGIPC_TRANSPORT_DI
22
23 //********** Globals. *********************************************************
24 #ifndef FEATURE_PAL
25 HINSTANCE       g_hInst;                // Instance handle to this piece of code.
26 #endif
27
28 //-----------------------------------------------------------------------------
29 // SxS Versioning story for Mscordbi (ICorDebug + friends)
30 //-----------------------------------------------------------------------------
31
32 //-----------------------------------------------------------------------------
33 // In v1.0, we declared that mscordbi was a "shared" component, which means
34 // that we promised to provide it from now until the end of time. So every CLR implementation
35 // needs an Mscordbi that implements the everett guids for CorDebug + CorPublish.
36 //
37 // This works fine for CorPublish, which is truly shared.
38 // CorDebug however is "versioned" not "shared" - each version of the CLR has its own disjoint copy.
39 //
40 // Thus creating a CorDebug object requires a version parameter.
41 // CoCreateInstance doesn't have a the version param, so we use the new (v2.0+)
42 // shim interface CreateDebuggingInterfaceFromVersion.
43 //
44 // ** So in summary: **
45 // - Dlls don't do self-registration; they're registered by setup using .vrg files.
46 // - All CLR versions (past + future) must have the same registry footprint w.r.t mscordbi.
47 //     This just means that all CLRs have the same mscordbi.vrg file.
48 // - CorDebug is in fact versioned and each CLR version has its own copy.
49 // - In v1.0/1.1, CorDebug was a CoClass. In v2.0+, it is not a CoClass and is created via the
50 //     CreateDebuggingInterfaceFromVersion shim API, which takes a version parameter.
51 // - CorDebug must be SxS. V1.1 must only get the V1.1 version, and V2.0 must only get the V2.0 version.
52 //     V1.1: Clients will cocreate to get CorDebug. v1.1 will be the only mscordbi!DllGetClassObject
53 //           that provides a CorDebug, so CoCreateInstance will guarantee getting a v1.1 object.
54 //     V2.0: Clients use the new version-aware shim API, so it's not an issue.
55 //
56 // ** Preparing for Life in a Single-CLR world: **
57 // In Orcas (v3), we expect to run on single-CLR. There will only be 1 mscordbi, and it will service all versions.
58 // For whidbey (v2), we want to be able to flip a knob and pretend to be orcas (for testing purposes).
59 //
60 // Here's how to do that:
61 // - copy whidbey mscordbi & dac over the everett mscordbi.
62 // - When VS cocreates w/ the everett-guid, it will load the mscordbi on the everett path (
63 //   which will be whidbey dll), and ask for the everett guid.
64 // - re-add CorDebug to the g_CoClasses list.
65
66
67 //********** Locals. **********************************************************
68
69
70 //********** Code. ************************************************************
71
72
73 //*****************************************************************************
74 // Standard public helper to create a Cordb object (ICorDebug instance).
75 // This is used by the shim to get the Cordb object out of this module.
76 // This is the creation path for V2.0+ for CorDebug using the in-process debugging
77 // architecture (ICorDebug).  In CLR v4+ debugger may choose to use the out-of-process
78 // architecture to get an ICorDebugProcess directly (IClrDebugging::OpenVirtualProcess).
79 //
80 // This was used by the Mix07 release of Silverlight, but it didn't properly support versioning
81 // and we no longer support it's debugger protocol so we require callers to use 
82 // code:CoreCLRCreateCordbObject instead.
83 // 
84 // This is also still used on Mac - multi-instance debugging and debugger
85 // versioning isn't really implemented there yet.  This probably needs to change.
86 //*****************************************************************************
87 STDAPI CreateCordbObject(int iDebuggerVersion, IUnknown ** ppCordb)
88 {
89
90     if (ppCordb == NULL)
91     {
92         return E_INVALIDARG;
93     }
94     if (iDebuggerVersion != CorDebugVersion_2_0 && iDebuggerVersion != CorDebugVersion_4_0)
95     {
96         return E_INVALIDARG;
97     }
98
99     return Cordb::CreateObject((CorDebugInterfaceVersion)iDebuggerVersion, IID_ICorDebug, (void **) ppCordb);
100 }
101
102 //
103 // Public API.  
104 // Telesto Creation path - only way to debug multi-instance.  
105 // This supercedes code:CreateCordbObject
106 // 
107 // Arguments:
108 //    iDebuggerVersion - version of ICorDebug interfaces that the debugger is requesting
109 //    pid - pid of debuggee that we're attaching to.
110 //    hmodTargetCLR - module handle to clr in target pid that we're attaching to.
111 //    ppCordb - (out) the resulting ICorDebug object.
112 //
113 // Notes:
114 //    It's inconsistent that this takes a (handle, pid) but hands back an ICorDebug instead of an ICorDebugProcess.
115 //    Callers will need to call *ppCordb->DebugActiveProcess(pid).
116 STDAPI CoreCLRCreateCordbObject(int iDebuggerVersion, DWORD pid, HMODULE hmodTargetCLR, IUnknown ** ppCordb)
117 {
118     if (ppCordb == NULL)
119     {
120         return E_INVALIDARG;
121     }
122     if ((iDebuggerVersion < CorDebugVersion_2_0) ||
123         (iDebuggerVersion > CorDebugLatestVersion))
124     {
125         return E_INVALIDARG;
126     }
127
128     //
129     // Create the ICorDebug object
130     // 
131     RSExtSmartPtr<ICorDebug> pCordb;
132     Cordb::CreateObject((CorDebugInterfaceVersion)iDebuggerVersion, IID_ICorDebug, (void **) &pCordb);
133
134     // @dbgtodo - we should stash the pid and validate that it's the same pid we're attaching to in ICorDebug::DebugActiveProcess.
135     
136     //
137     // Associate it with the target instance
138     //
139     HRESULT hr = static_cast<Cordb*>(pCordb.GetValue())->SetTargetCLR(hmodTargetCLR);
140     if (FAILED(hr))
141     {
142         return hr;
143     }
144
145     //
146     // Assign to out parameter.
147     // 
148     hr = pCordb->QueryInterface(IID_IUnknown, (void**) ppCordb);
149
150     // Implicit release of pUnk, pCordb
151     return hr;
152 }
153
154
155
156
157
158 //*****************************************************************************
159 // The main dll entry point for this module.  This routine is called by the
160 // OS when the dll gets loaded.  Control is simply deferred to the main code.
161 //*****************************************************************************
162 BOOL WINAPI DbgDllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
163 {
164     // Save off the instance handle for later use.
165     switch (dwReason)
166     {
167
168         case DLL_PROCESS_ATTACH:
169         {
170 #ifndef FEATURE_PAL
171             g_hInst = hInstance;
172 #else
173             int err = PAL_InitializeDLL();
174             if(err != 0)
175             {
176                 return FALSE;
177             }
178 #endif
179
180 #if defined(_DEBUG)
181             static int BreakOnDILoad = -1;
182             if (BreakOnDILoad == -1)
183                 BreakOnDILoad = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_BreakOnDILoad);
184
185             if (BreakOnDILoad)
186             {
187                 _ASSERTE(!"DI Loaded");
188             }
189 #endif
190
191 #if defined(LOGGING)
192             {
193                 PathString rcFile;
194                 WszGetModuleFileName(hInstance, rcFile);
195                 LOG((LF_CORDB, LL_INFO10000,
196                     "DI::DbgDllMain: load right side support from file '%s'\n",
197                      rcFile.GetUnicode()));
198             }
199 #endif
200
201 #ifdef RSCONTRACTS
202             // alloc a TLS slot
203             DbgRSThread::s_TlsSlot = TlsAlloc();
204             _ASSERTE(DbgRSThread::s_TlsSlot != TLS_OUT_OF_INDEXES);
205 #endif
206
207 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
208             g_pDbgTransportTarget = new (nothrow) DbgTransportTarget();
209             if (g_pDbgTransportTarget == NULL)
210                 return FALSE;
211
212             if (FAILED(g_pDbgTransportTarget->Init()))
213                 return FALSE;
214 #endif // FEATURE_DBGIPC_TRANSPORT_DI
215         }
216         break;
217
218         case DLL_THREAD_DETACH:
219         {
220 #ifdef STRESS_LOG
221             StressLog::ThreadDetach((ThreadStressLog*) ClrFlsGetValue(TlsIdx_StressLog));
222 #endif
223
224 #ifdef RSCONTRACTS
225             // DbgRSThread are lazily created when we call GetThread(),
226             // So we don't need to do anything in DLL_THREAD_ATTACH,
227             // But this is our only chance to destroy the thread object.
228             DbgRSThread * p = DbgRSThread::GetThread();
229
230             p->Destroy();
231 #endif
232         }
233         break;
234
235         case DLL_PROCESS_DETACH:
236         {
237 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
238             if (g_pDbgTransportTarget != NULL)
239             {
240                 g_pDbgTransportTarget->Shutdown();
241                 delete g_pDbgTransportTarget;
242                 g_pDbgTransportTarget = NULL;
243             }
244 #endif // FEATURE_DBGIPC_TRANSPORT_DI
245             
246 #ifdef RSCONTRACTS
247             TlsFree(DbgRSThread::s_TlsSlot);
248             DbgRSThread::s_TlsSlot = TLS_OUT_OF_INDEXES;
249 #endif
250         }
251         break;
252     }
253
254     return TRUE;
255 }
256
257
258 // The obsolete v1 CLSID - see comment above for details.
259 static const GUID CLSID_CorDebug_V1 = {0x6fef44d0,0x39e7,0x4c77, { 0xbe,0x8e,0xc9,0xf8,0xcf,0x98,0x86,0x30}};
260
261 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
262
263 // GUID for pipe-based debugging (Unix platforms)
264 const GUID CLSID_CorDebug_Telesto = {0x8bd1daae, 0x188e, 0x42f4, {0xb0, 0x09, 0x08, 0xfa, 0xfd, 0x17, 0x81, 0x3b}};
265
266 // The debug engine needs to implement an internal Visual Studio debugger interface (defined by the CPDE)
267 // which augments launch and attach requests so that we can obtain information from the port supplier (the
268 // network address of the target in our case). See RSPriv.h for the definition of the interface. (We have to
269 // hard code the IID and interface definition because VS does not export it, but it's not much of an issue
270 // since COM interfaces are completely immutable).
271 const GUID IID_IDebugRemoteCorDebug = {0x83C91210, 0xA34F, 0x427c, {0xB3, 0x5F, 0x79, 0xC3, 0x99, 0x5B, 0x3C, 0x14}};
272 #endif // FEATURE_DBGIPC_TRANSPORT_DI
273
274 //*****************************************************************************
275 // Called by COM to get a class factory for a given CLSID.  If it is one we
276 // support, instantiate a class factory object and prepare for create instance.
277 //*****************************************************************************
278 STDAPI DllGetClassObjectInternal(               // Return code.
279     REFCLSID    rclsid,                 // The class to desired.
280     REFIID      riid,                   // Interface wanted on class factory.
281     LPVOID FAR  *ppv)                   // Return interface pointer here.
282 {
283     HRESULT         hr;
284     CClassFactory   *pClassFactory;         // To create class factory object.
285     PFN_CREATE_OBJ  pfnCreateObject = NULL;
286
287
288 #if defined(FEATURE_DBG_PUBLISH)
289     if (rclsid == CLSID_CorpubPublish)
290     {
291         pfnCreateObject = CorpubPublish::CreateObject;
292     }
293     else
294 #endif
295 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
296     if (rclsid == CLSID_CorDebug_Telesto)
297     {
298         pfnCreateObject = Cordb::CreateObjectTelesto;
299     }
300 #else  // !FEATURE_DBGIPC_TRANSPORT_DI
301     if(rclsid == CLSID_CorDebug_V1)
302     {
303         if (0) // if (IsSingleCLR())
304         {
305             // Don't allow creating backwards objects until we ensure that the v2.0 Right-side
306             // is backwards compat. This may involve using CordbProcess::SupportsVersion to conditionally
307             // emulate old behavior.
308             // If emulating V1.0, QIs for V2.0 interfaces should fail.
309             _ASSERTE(!"Ensure that V2.0 RS is backwards compat");
310             pfnCreateObject = Cordb::CreateObjectV1;
311         }
312     }
313 #endif // FEATURE_DBGIPC_TRANSPORT_DI
314
315     if (pfnCreateObject == NULL)
316         return (CLASS_E_CLASSNOTAVAILABLE);
317
318     // Allocate the new factory object.  The ref count is set to 1 in the constructor.
319     pClassFactory = new (nothrow) CClassFactory(pfnCreateObject);
320     if (!pClassFactory)
321         return (E_OUTOFMEMORY);
322
323     // Pick the v-table based on the caller's request.
324     hr = pClassFactory->QueryInterface(riid, ppv);
325
326     // Always release the local reference, if QI failed it will be
327     // the only one and the object gets freed.
328     pClassFactory->Release();
329
330     return hr;
331 }
332
333 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
334 // In V2 we started hiding DllGetClassObject because activation was no longer performed through COM directly
335 // (we went through the shim). CoreCLR doesn't have a shim and we go back to the COM model so we re-expose
336 // DllGetClassObject to make that work.
337
338 STDAPI DllGetClassObject(               // Return code.
339     REFCLSID    rclsid,                 // The class to desired.
340     REFIID      riid,                   // Interface wanted on class factory.
341     LPVOID FAR  *ppv)                   // Return interface pointer here.
342 {
343     return DllGetClassObjectInternal(rclsid, riid, ppv);
344 }
345 #endif // FEATURE_DBGIPC_TRANSPORT_DI
346
347
348 //*****************************************************************************
349 //
350 //********** Class factory code.
351 //
352 //*****************************************************************************
353
354
355 //*****************************************************************************
356 // QueryInterface is called to pick a v-table on the co-class.
357 //*****************************************************************************
358 HRESULT STDMETHODCALLTYPE CClassFactory::QueryInterface(
359     REFIID      riid,
360     void        **ppvObject)
361 {
362     HRESULT     hr;
363
364     // Avoid confusion.
365     *ppvObject = NULL;
366
367     // Pick the right v-table based on the IID passed in.
368     if (riid == IID_IUnknown)
369         *ppvObject = (IUnknown *) this;
370     else if (riid == IID_IClassFactory)
371         *ppvObject = (IClassFactory *) this;
372
373     // If successful, add a reference for out pointer and return.
374     if (*ppvObject)
375     {
376         hr = S_OK;
377         AddRef();
378     }
379     else
380         hr = E_NOINTERFACE;
381     return (hr);
382 }
383
384
385 //*****************************************************************************
386 // CreateInstance is called to create a new instance of the coclass for which
387 // this class was created in the first place.  The returned pointer is the
388 // v-table matching the IID if there.
389 //*****************************************************************************
390 HRESULT STDMETHODCALLTYPE CClassFactory::CreateInstance(
391     IUnknown    *pUnkOuter,
392     REFIID      riid,
393     void        **ppvObject)
394 {
395     HRESULT     hr;
396
397     // Avoid confusion.
398     *ppvObject = NULL;
399     _ASSERTE(m_pfnCreateObject);
400
401     // Aggregation is not supported by these objects.
402     if (pUnkOuter)
403         return (CLASS_E_NOAGGREGATION);
404
405     // Ask the object to create an instance of itself, and check the iid.
406     hr = (*m_pfnCreateObject)(riid, ppvObject);
407     return (hr);
408 }
409
410
411 HRESULT STDMETHODCALLTYPE CClassFactory::LockServer(
412     BOOL        fLock)
413 {
414 //<TODO>@todo: hook up lock server logic.</TODO>
415     return (S_OK);
416 }
417
418
419 //*****************************************************************************
420 // This helper provides access to the instance handle of the loaded image.
421 //*****************************************************************************
422 #ifndef FEATURE_PAL
423 HINSTANCE GetModuleInst()
424 {
425     return g_hInst;
426 }
427 #endif
428
429
430 //-----------------------------------------------------------------------------
431 // Substitute for mscoree
432 // 
433 // Notes:
434 //    Mscordbi does not link with mscoree, provide a stub implementation. 
435 //    Callers are in dead-code paths, but we still need to provide a stub. Ideally, we'd factor
436 //    out the callers too and then we wouldn't need an E_NOTIMPL stub.
437 STDAPI GetRequestedRuntimeInfo(LPCWSTR pExe, 
438                                LPCWSTR pwszVersion, 
439                                LPCWSTR pConfigurationFile, 
440                                DWORD startupFlags, 
441                                DWORD runtimeInfoFlags, 
442                                __out_ecount_opt(dwDirectory) LPWSTR pDirectory, 
443                                DWORD dwDirectory, 
444                                DWORD *dwDirectoryLength, 
445                                __out_ecount_opt(cchBuffer)   LPWSTR pVersion, 
446                                DWORD cchBuffer, 
447                                DWORD* dwlength)
448 {
449     _ASSERTE(!"GetRequestedRuntimeInfo not impl");
450     return E_NOTIMPL;
451 }
452
453 //-----------------------------------------------------------------------------
454 // Replacement for legacy shim API GetCORRequiredVersion(...) used in linked libraries.
455 // Used in code:TiggerStorage::GetDefaultVersion#CallTo_CLRRuntimeHostInternal_GetImageVersionString.
456 // 
457 // Notes:
458 //   Mscordbi does not statically link to mscoree.dll.
459 //   This is used in EnC for IMetadataEmit2::GetSaveSize to computer size of header.
460 //   see code:TiggerStorage::GetDefaultVersion.
461 //   
462 //   Implemented by returning the version we're built for.  Mscordbi.dll has a tight coupling with
463 //   the CLR version, so this will match exactly the build version we're debugging.  
464 //   One potential caveat is that the build version doesn't necessarily match the install string
465 //   (eg. we may install as "v4.0.x86chk" but that's not captured in the build version).  But this should
466 //   be internal scenarios only, and shouldn't actually matter here.  If it did, we could instead get
467 //   the last components of the directory name the current mscordbi.dll is located in.
468 //     
469 HRESULT 
470 CLRRuntimeHostInternal_GetImageVersionString(
471     __out_ecount_part(*pcchBuffer, *pcchBuffer) LPWSTR wszBuffer, 
472     DWORD *pcchBuffer)
473 {
474     // Construct the cannoncial version string we're built as - eg. "v4.0.1234"
475     const WCHAR k_wszBuiltFor[] = W("v") VER_PRODUCTVERSION_NO_QFE_STR_L;
476
477     // Copy our buffer in
478     HRESULT hr = HRESULT_FROM_WIN32(wcscpy_s(wszBuffer, *pcchBuffer, k_wszBuiltFor));
479
480     // Hand out length regardless of success - like GetCORRequiredVersion
481     *pcchBuffer = _countof(k_wszBuiltFor);
482
483     return hr;
484 } // CLRRuntimeHostInternal_GetImageVersionString
485
486
487 #ifdef _TARGET_ARM_
488 BOOL
489 DbiGetThreadContext(HANDLE hThread,
490     DT_CONTEXT *lpContext)
491 {
492     // if we aren't local debugging this isn't going to work
493 #if !defined(_ARM_) || defined(FEATURE_DBGIPC_TRANSPORT_DI)
494     _ASSERTE(!"Can't use local GetThreadContext remotely, this needed to go to datatarget");
495     return FALSE;
496 #else
497     BOOL res = FALSE;
498     if (((ULONG)lpContext) & ~0x10)
499     {
500         CONTEXT *ctx = (CONTEXT*)_aligned_malloc(sizeof(CONTEXT), 16);
501         if (ctx)
502         {
503             ctx->ContextFlags = lpContext->ContextFlags;
504             if (::GetThreadContext(hThread, ctx))
505             {
506                 *lpContext = *(DT_CONTEXT*)ctx;
507                 res = TRUE;
508             }
509
510             _aligned_free(ctx);
511         }
512         else
513         {
514             // malloc does not set the last error, but the caller of GetThreadContext
515             // will expect it to be set on failure.
516             SetLastError(ERROR_OUTOFMEMORY);
517         }
518     }
519     else
520     {
521         res = ::GetThreadContext(hThread, (CONTEXT*)lpContext);
522     }
523     
524     return res;
525 #endif
526 }
527
528 BOOL
529 DbiSetThreadContext(HANDLE hThread,
530     const DT_CONTEXT *lpContext)
531 {
532 #if !defined(_ARM_) || defined(FEATURE_DBGIPC_TRANSPORT_DI)
533     _ASSERTE(!"Can't use local GetThreadContext remotely, this needed to go to datatarget");
534     return FALSE;
535 #else
536     BOOL res = FALSE;
537     if (((ULONG)lpContext) & ~0x10)
538     {
539         CONTEXT *ctx = (CONTEXT*)_aligned_malloc(sizeof(CONTEXT), 16);
540         if (ctx)
541         {
542             *ctx = *(CONTEXT*)lpContext;
543             res = ::SetThreadContext(hThread, ctx);
544             _aligned_free(ctx);
545         }   
546         else
547         {
548             // malloc does not set the last error, but the caller of SetThreadContext
549             // will expect it to be set on failure.
550             SetLastError(ERROR_OUTOFMEMORY);
551         }
552     }
553     else
554     {
555         res = ::SetThreadContext(hThread, (CONTEXT*)lpContext);
556     }
557     
558     return res;
559 #endif
560 }
561 #endif