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 //*****************************************************************************
9 // Dll* routines for entry points, and support for COM framework. The class
10 // factory and other routines live in this module.
12 //*****************************************************************************
14 #include "classfactory.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
23 //********** Globals. *********************************************************
25 HINSTANCE g_hInst; // Instance handle to this piece of code.
28 //-----------------------------------------------------------------------------
29 // SxS Versioning story for Mscordbi (ICorDebug + friends)
30 //-----------------------------------------------------------------------------
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.
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.
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.
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.
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).
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.
67 //********** Locals. **********************************************************
70 //********** Code. ************************************************************
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).
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.
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)
89 #if !defined(FEATURE_DBGIPC_TRANSPORT_DI) && !defined(FEATURE_CORESYSTEM)
90 // This API should not be called for Windows CoreCLR unless we are doing interop-debugging
91 // (which is only supported internally). Use code:CoreCLRCreateCordbObject instead.
92 if (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_DbgEnableMixedModeDebugging) == 0)
94 _ASSERTE(!"Deprecated entry point CreateCordbObject() is called on Windows CoreCLR\n");
97 #endif // !defined(FEATURE_DBGIPC_TRANSPORT_DI) && !defined(FEATURE_CORESYSTEM)
103 if (iDebuggerVersion != CorDebugVersion_2_0 && iDebuggerVersion != CorDebugVersion_4_0)
108 return Cordb::CreateObject((CorDebugInterfaceVersion)iDebuggerVersion, IID_ICorDebug, (void **) ppCordb);
113 // Telesto Creation path - only way to debug multi-instance.
114 // This supercedes code:CreateCordbObject
117 // iDebuggerVersion - version of ICorDebug interfaces that the debugger is requesting
118 // pid - pid of debuggee that we're attaching to.
119 // hmodTargetCLR - module handle to clr in target pid that we're attaching to.
120 // ppCordb - (out) the resulting ICorDebug object.
123 // It's inconsistent that this takes a (handle, pid) but hands back an ICorDebug instead of an ICorDebugProcess.
124 // Callers will need to call *ppCordb->DebugActiveProcess(pid).
125 STDAPI CoreCLRCreateCordbObject(int iDebuggerVersion, DWORD pid, HMODULE hmodTargetCLR, IUnknown ** ppCordb)
131 if ((iDebuggerVersion < CorDebugVersion_2_0) ||
132 (iDebuggerVersion > CorDebugLatestVersion))
138 // Create the ICorDebug object
140 RSExtSmartPtr<ICorDebug> pCordb;
141 Cordb::CreateObject((CorDebugInterfaceVersion)iDebuggerVersion, IID_ICorDebug, (void **) &pCordb);
143 // @dbgtodo - we should stash the pid and validate that it's the same pid we're attaching to in ICorDebug::DebugActiveProcess.
146 // Associate it with the target instance
148 HRESULT hr = static_cast<Cordb*>(pCordb.GetValue())->SetTargetCLR(hmodTargetCLR);
155 // Assign to out parameter.
157 hr = pCordb->QueryInterface(IID_IUnknown, (void**) ppCordb);
159 // Implicit release of pUnk, pCordb
167 //*****************************************************************************
168 // The main dll entry point for this module. This routine is called by the
169 // OS when the dll gets loaded. Control is simply deferred to the main code.
170 //*****************************************************************************
171 BOOL WINAPI DbgDllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
173 // Save off the instance handle for later use.
177 case DLL_PROCESS_ATTACH:
182 int err = PAL_InitializeDLL();
190 static int BreakOnDILoad = -1;
191 if (BreakOnDILoad == -1)
192 BreakOnDILoad = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_BreakOnDILoad);
196 _ASSERTE(!"DI Loaded");
203 WszGetModuleFileName(hInstance, rcFile);
204 LOG((LF_CORDB, LL_INFO10000,
205 "DI::DbgDllMain: load right side support from file '%s'\n",
206 rcFile.GetUnicode()));
212 DbgRSThread::s_TlsSlot = TlsAlloc();
213 _ASSERTE(DbgRSThread::s_TlsSlot != TLS_OUT_OF_INDEXES);
216 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
217 g_pDbgTransportTarget = new (nothrow) DbgTransportTarget();
218 if (g_pDbgTransportTarget == NULL)
221 if (FAILED(g_pDbgTransportTarget->Init()))
223 #endif // FEATURE_DBGIPC_TRANSPORT_DI
227 case DLL_THREAD_DETACH:
230 StressLog::ThreadDetach((ThreadStressLog*) ClrFlsGetValue(TlsIdx_StressLog));
234 // DbgRSThread are lazily created when we call GetThread(),
235 // So we don't need to do anything in DLL_THREAD_ATTACH,
236 // But this is our only chance to destroy the thread object.
237 DbgRSThread * p = DbgRSThread::GetThread();
244 case DLL_PROCESS_DETACH:
246 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
247 if (g_pDbgTransportTarget != NULL)
249 g_pDbgTransportTarget->Shutdown();
250 delete g_pDbgTransportTarget;
251 g_pDbgTransportTarget = NULL;
253 #endif // FEATURE_DBGIPC_TRANSPORT_DI
256 TlsFree(DbgRSThread::s_TlsSlot);
257 DbgRSThread::s_TlsSlot = TLS_OUT_OF_INDEXES;
267 // The obsolete v1 CLSID - see comment above for details.
268 static const GUID CLSID_CorDebug_V1 = {0x6fef44d0,0x39e7,0x4c77, { 0xbe,0x8e,0xc9,0xf8,0xcf,0x98,0x86,0x30}};
270 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
272 // GUID for pipe-based debugging (Unix platforms)
273 const GUID CLSID_CorDebug_Telesto = {0x8bd1daae, 0x188e, 0x42f4, {0xb0, 0x09, 0x08, 0xfa, 0xfd, 0x17, 0x81, 0x3b}};
275 // The debug engine needs to implement an internal Visual Studio debugger interface (defined by the CPDE)
276 // which augments launch and attach requests so that we can obtain information from the port supplier (the
277 // network address of the target in our case). See RSPriv.h for the definition of the interface. (We have to
278 // hard code the IID and interface definition because VS does not export it, but it's not much of an issue
279 // since COM interfaces are completely immutable).
280 const GUID IID_IDebugRemoteCorDebug = {0x83C91210, 0xA34F, 0x427c, {0xB3, 0x5F, 0x79, 0xC3, 0x99, 0x5B, 0x3C, 0x14}};
281 #endif // FEATURE_DBGIPC_TRANSPORT_DI
283 //*****************************************************************************
284 // Called by COM to get a class factory for a given CLSID. If it is one we
285 // support, instantiate a class factory object and prepare for create instance.
286 //*****************************************************************************
287 STDAPI DllGetClassObjectInternal( // Return code.
288 REFCLSID rclsid, // The class to desired.
289 REFIID riid, // Interface wanted on class factory.
290 LPVOID FAR *ppv) // Return interface pointer here.
293 CClassFactory *pClassFactory; // To create class factory object.
294 PFN_CREATE_OBJ pfnCreateObject = NULL;
297 #if defined(FEATURE_DBG_PUBLISH)
298 if (rclsid == CLSID_CorpubPublish)
300 pfnCreateObject = CorpubPublish::CreateObject;
304 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
305 if (rclsid == CLSID_CorDebug_Telesto)
307 pfnCreateObject = Cordb::CreateObjectTelesto;
309 #else // !FEATURE_DBGIPC_TRANSPORT_DI
310 if(rclsid == CLSID_CorDebug_V1)
312 if (0) // if (IsSingleCLR())
314 // Don't allow creating backwards objects until we ensure that the v2.0 Right-side
315 // is backwards compat. This may involve using CordbProcess::SupportsVersion to conditionally
316 // emulate old behavior.
317 // If emulating V1.0, QIs for V2.0 interfaces should fail.
318 _ASSERTE(!"Ensure that V2.0 RS is backwards compat");
319 pfnCreateObject = Cordb::CreateObjectV1;
322 #endif // FEATURE_DBGIPC_TRANSPORT_DI
324 if (pfnCreateObject == NULL)
325 return (CLASS_E_CLASSNOTAVAILABLE);
327 // Allocate the new factory object. The ref count is set to 1 in the constructor.
328 pClassFactory = new (nothrow) CClassFactory(pfnCreateObject);
330 return (E_OUTOFMEMORY);
332 // Pick the v-table based on the caller's request.
333 hr = pClassFactory->QueryInterface(riid, ppv);
335 // Always release the local reference, if QI failed it will be
336 // the only one and the object gets freed.
337 pClassFactory->Release();
342 #if defined(FEATURE_DBGIPC_TRANSPORT_DI)
343 // In V2 we started hiding DllGetClassObject because activation was no longer performed through COM directly
344 // (we went through the shim). CoreCLR doesn't have a shim and we go back to the COM model so we re-expose
345 // DllGetClassObject to make that work.
347 STDAPI DllGetClassObject( // Return code.
348 REFCLSID rclsid, // The class to desired.
349 REFIID riid, // Interface wanted on class factory.
350 LPVOID FAR *ppv) // Return interface pointer here.
352 return DllGetClassObjectInternal(rclsid, riid, ppv);
354 #endif // FEATURE_DBGIPC_TRANSPORT_DI
357 //*****************************************************************************
359 //********** Class factory code.
361 //*****************************************************************************
364 //*****************************************************************************
365 // QueryInterface is called to pick a v-table on the co-class.
366 //*****************************************************************************
367 HRESULT STDMETHODCALLTYPE CClassFactory::QueryInterface(
376 // Pick the right v-table based on the IID passed in.
377 if (riid == IID_IUnknown)
378 *ppvObject = (IUnknown *) this;
379 else if (riid == IID_IClassFactory)
380 *ppvObject = (IClassFactory *) this;
382 // If successful, add a reference for out pointer and return.
394 //*****************************************************************************
395 // CreateInstance is called to create a new instance of the coclass for which
396 // this class was created in the first place. The returned pointer is the
397 // v-table matching the IID if there.
398 //*****************************************************************************
399 HRESULT STDMETHODCALLTYPE CClassFactory::CreateInstance(
408 _ASSERTE(m_pfnCreateObject);
410 // Aggregation is not supported by these objects.
412 return (CLASS_E_NOAGGREGATION);
414 // Ask the object to create an instance of itself, and check the iid.
415 hr = (*m_pfnCreateObject)(riid, ppvObject);
420 HRESULT STDMETHODCALLTYPE CClassFactory::LockServer(
423 //<TODO>@todo: hook up lock server logic.</TODO>
428 //*****************************************************************************
429 // This helper provides access to the instance handle of the loaded image.
430 //*****************************************************************************
432 HINSTANCE GetModuleInst()
439 //-----------------------------------------------------------------------------
440 // Substitute for mscoree
443 // Mscordbi does not link with mscoree, provide a stub implementation.
444 // Callers are in dead-code paths, but we still need to provide a stub. Ideally, we'd factor
445 // out the callers too and then we wouldn't need an E_NOTIMPL stub.
446 STDAPI GetRequestedRuntimeInfo(LPCWSTR pExe,
448 LPCWSTR pConfigurationFile,
450 DWORD runtimeInfoFlags,
451 __out_ecount_opt(dwDirectory) LPWSTR pDirectory,
453 DWORD *dwDirectoryLength,
454 __out_ecount_opt(cchBuffer) LPWSTR pVersion,
458 _ASSERTE(!"GetRequestedRuntimeInfo not impl");
462 //-----------------------------------------------------------------------------
463 // Replacement for legacy shim API GetCORRequiredVersion(...) used in linked libraries.
464 // Used in code:TiggerStorage::GetDefaultVersion#CallTo_CLRRuntimeHostInternal_GetImageVersionString.
467 // Mscordbi does not statically link to mscoree.dll.
468 // This is used in EnC for IMetadataEmit2::GetSaveSize to computer size of header.
469 // see code:TiggerStorage::GetDefaultVersion.
471 // Implemented by returning the version we're built for. Mscordbi.dll has a tight coupling with
472 // the CLR version, so this will match exactly the build version we're debugging.
473 // One potential caveat is that the build version doesn't necessarily match the install string
474 // (eg. we may install as "v4.0.x86chk" but that's not captured in the build version). But this should
475 // be internal scenarios only, and shouldn't actually matter here. If it did, we could instead get
476 // the last components of the directory name the current mscordbi.dll is located in.
479 CLRRuntimeHostInternal_GetImageVersionString(
480 __out_ecount_part(*pcchBuffer, *pcchBuffer) LPWSTR wszBuffer,
483 // Construct the cannoncial version string we're built as - eg. "v4.0.1234"
484 const WCHAR k_wszBuiltFor[] = W("v") VER_PRODUCTVERSION_NO_QFE_STR_L;
486 // Copy our buffer in
487 HRESULT hr = HRESULT_FROM_WIN32(wcscpy_s(wszBuffer, *pcchBuffer, k_wszBuiltFor));
489 // Hand out length regardless of success - like GetCORRequiredVersion
490 *pcchBuffer = _countof(k_wszBuiltFor);
493 } // CLRRuntimeHostInternal_GetImageVersionString
498 DbiGetThreadContext(HANDLE hThread,
499 DT_CONTEXT *lpContext)
501 // if we aren't local debugging this isn't going to work
502 #if !defined(_ARM_) || defined(FEATURE_DBGIPC_TRANSPORT_DI) || defined(__ANDROID__)
503 _ASSERTE(!"Can't use local GetThreadContext remotely, this needed to go to datatarget");
507 if (((ULONG)lpContext) & ~0x10)
509 CONTEXT *ctx = (CONTEXT*)_aligned_malloc(sizeof(CONTEXT), 16);
512 ctx->ContextFlags = lpContext->ContextFlags;
513 if (::GetThreadContext(hThread, ctx))
515 *lpContext = *(DT_CONTEXT*)ctx;
523 // malloc does not set the last error, but the caller of GetThreadContext
524 // will expect it to be set on failure.
525 SetLastError(ERROR_OUTOFMEMORY);
530 res = ::GetThreadContext(hThread, (CONTEXT*)lpContext);
538 DbiSetThreadContext(HANDLE hThread,
539 const DT_CONTEXT *lpContext)
541 #if !defined(_ARM_) || defined(FEATURE_DBGIPC_TRANSPORT_DI) || defined(__ANDROID__)
542 _ASSERTE(!"Can't use local GetThreadContext remotely, this needed to go to datatarget");
546 if (((ULONG)lpContext) & ~0x10)
548 CONTEXT *ctx = (CONTEXT*)_aligned_malloc(sizeof(CONTEXT), 16);
551 *ctx = *(CONTEXT*)lpContext;
552 res = ::SetThreadContext(hThread, ctx);
557 // malloc does not set the last error, but the caller of SetThreadContext
558 // will expect it to be set on failure.
559 SetLastError(ERROR_OUTOFMEMORY);
564 res = ::SetThreadContext(hThread, (CONTEXT*)lpContext);