@@ -278,14 +278,52 @@ static int vsinstrument_exec(PyObject *m)
278278 return -1 ;
279279 }
280280
281- // We ensure the DLL is loaded already before loading it again, but
282- // use LoadLibraryW to increment the reference count to ensure it does not
283- // get freed on us.
284- if (!GetModuleHandleW (L"DiagnosticsHub.InstrumentationCollector.dll" )) {
285- PyErr_SetString (PyExc_RuntimeError , "VS tracing must be launched from Diagnostics Hub" );
281+ #if defined(_M_IX86 )
282+ const wchar_t * const subpath = L"\\x86\\" ;
283+ #elif defined(_M_AMD64 )
284+ const wchar_t * const subpath = L"\\amd64\\" ;
285+ #elif defined(_M_ARM64 )
286+ const wchar_t * const subpath = L"\\arm64\\" ;
287+ #else
288+ #error Unsupported architecture
289+ #endif
290+
291+ DWORD cchPath = GetEnvironmentVariableW (L"DIAGHUB_INSTR_COLLECTOR_ROOT" , NULL , 0 );
292+ if (!cchPath ) {
293+ PyErr_SetFromWindowsErr (0 );
294+ return -1 ;
295+ }
296+ DWORD cchName = GetEnvironmentVariableW (L"DIAGHUB_INSTR_RUNTIME_NAME" , NULL , 0 );
297+ if (!cchName ) {
298+ PyErr_SetFromWindowsErr (0 );
299+ return -1 ;
300+ }
301+ cchPath = cchPath + cchName + (DWORD )wcslen (subpath );
302+ wchar_t * path = (wchar_t * )PyMem_Malloc (cchPath * sizeof (wchar_t ));
303+ if (!path ) {
304+ PyErr_NoMemory ();
305+ return -1 ;
306+ }
307+
308+ DWORD cch = GetEnvironmentVariable (L"DIAGHUB_INSTR_COLLECTOR_ROOT" , path , cchPath );
309+ if (!cch ) {
310+ PyErr_SetFromWindowsErr (0 );
286311 return -1 ;
287312 }
288- state -> hModule = LoadLibraryW (L"DiagnosticsHub.InstrumentationCollector.dll" );
313+ while (cch > 0 && path [cch - 1 ] == L'\\' ) {
314+ -- cch ;
315+ }
316+ wcscpy_s (& path [cch ], cchPath - cch , subpath );
317+ cch += (DWORD )wcslen (subpath );
318+
319+ if (!GetEnvironmentVariable (L"DIAGHUB_INSTR_RUNTIME_NAME" , & path [cch ], cchPath - cch )) {
320+ PyMem_Free (path );
321+ PyErr_SetFromWindowsErr (0 );
322+ return -1 ;
323+ }
324+
325+ state -> hModule = LoadLibraryW (path );
326+ PyMem_Free (path );
289327 if (!state -> hModule ) {
290328 PyErr_SetFromWindowsErr (0 );
291329 return -1 ;
@@ -314,6 +352,17 @@ static int vsinstrument_exec(PyObject *m)
314352 // Allowed to be absent
315353 state -> WriteMark = (Stub_Write_Mark )GetProcAddress (state -> hModule , "Stub_Write_Mark" );
316354
355+ BOOL (* childAttach )() = (BOOL (* )())GetProcAddress (state -> hModule , "ChildAttach" );
356+ if (!childAttach ) {
357+ PyErr_SetFromWindowsErr (0 );
358+ return -1 ;
359+ }
360+
361+ if (!(* childAttach )()) {
362+ PyErr_SetString (PyExc_RuntimeError , "Failed to attach to profiler" );
363+ return -1 ;
364+ }
365+
317366 return 0 ;
318367}
319368
0 commit comments