2323#include < DbgHelp.h>
2424#endif
2525
26+ #include " swift/Runtime/Mutex.h"
27+
2628using namespace swift ;
2729
2830int swift::lookupSymbol (const void *address, SymbolInfo *info) {
@@ -38,36 +40,52 @@ int swift::lookupSymbol(const void *address, SymbolInfo *info) {
3840 info->symbolAddress = dli_saddr;
3941 return 1 ;
4042#elif defined(_WIN32)
41- static const constexpr size_t kSymbolMaxNameLen = 1024 ;
42- static bool bInitialized = false ;
43+ return _swift_withWin32DbgHelpLibrary ([&] ( bool isInitialized) {
44+ static const constexpr size_t kSymbolMaxNameLen = 1024 ;
4345
44- if (bInitialized == false ) {
45- if (SymInitialize (GetCurrentProcess (), /* UserSearchPath=*/ NULL ,
46- /* fInvadeProcess=*/ TRUE ) == FALSE )
46+ if (!isInitialized) {
4747 return 0 ;
48- bInitialized = true ;
49- }
48+ }
5049
51- char buffer[sizeof (SYMBOL_INFO) + kSymbolMaxNameLen ];
52- PSYMBOL_INFO pSymbol = reinterpret_cast <PSYMBOL_INFO>(buffer);
53- pSymbol->SizeOfStruct = sizeof (SYMBOL_INFO);
54- pSymbol->MaxNameLen = kSymbolMaxNameLen ;
50+ char buffer[sizeof (SYMBOL_INFO) + kSymbolMaxNameLen ];
51+ PSYMBOL_INFO pSymbol = reinterpret_cast <PSYMBOL_INFO>(buffer);
52+ pSymbol->SizeOfStruct = sizeof (SYMBOL_INFO);
53+ pSymbol->MaxNameLen = kSymbolMaxNameLen ;
5554
56- DWORD64 dwDisplacement = 0 ;
55+ DWORD64 dwDisplacement = 0 ;
5756
58- if (SymFromAddr (GetCurrentProcess (), reinterpret_cast <const DWORD64>(address),
59- &dwDisplacement, pSymbol) == FALSE )
60- return 0 ;
57+ if (SymFromAddr (GetCurrentProcess (),
58+ reinterpret_cast <const DWORD64>(address),
59+ &dwDisplacement, pSymbol) == FALSE ) {
60+ return 0 ;
61+ }
6162
62- info->fileName = NULL ;
63- info->baseAddress = reinterpret_cast <void *>(pSymbol->ModBase );
64- info->symbolName .reset (_strdup (pSymbol->Name ));
65- info->symbolAddress = reinterpret_cast <void *>(pSymbol->Address );
63+ info->fileName = NULL ;
64+ info->baseAddress = reinterpret_cast <void *>(pSymbol->ModBase );
65+ info->symbolName .reset (_strdup (pSymbol->Name ));
66+ info->symbolAddress = reinterpret_cast <void *>(pSymbol->Address );
6667
67- return 1 ;
68+ return 1 ;
69+ });
6870#else
6971 return 0 ;
7072#endif // defined(__CYGWIN__) || defined(_WIN32)
7173}
7274
75+ #if defined(_WIN32)
76+ static StaticMutex mutex;
77+ static bool isDbgHelpInitialized = false ;
78+
79+ void swift::_swift_withWin32DbgHelpLibrary (
80+ const std::function<void (bool /* isInitialized */ )>& body) {
81+ mutex.withLock ([&body] () {
82+ if (!isDbgHelpInitialized) {
83+ SymSetOptions (SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS);
84+ isDbgHelpInitialized = SymInitialize (GetCurrentProcess (), nullptr , true );
85+ }
86+ body (isDbgHelpInitialized);
87+ });
88+ }
89+ #endif
90+
7391#endif // !defined(__ELF__) && !defined(__MACH__)
0 commit comments