sanitizer_symbolizer_win.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. //===-- sanitizer_symbolizer_win.cpp --------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is shared between AddressSanitizer and ThreadSanitizer
  10. // run-time libraries.
  11. // Windows-specific implementation of symbolizer parts.
  12. //===----------------------------------------------------------------------===//
  13. #include "sanitizer_platform.h"
  14. #if SANITIZER_WINDOWS
  15. #include "sanitizer_dbghelp.h"
  16. #include "sanitizer_symbolizer_internal.h"
  17. namespace __sanitizer {
  18. decltype(::StackWalk64) *StackWalk64;
  19. decltype(::SymCleanup) *SymCleanup;
  20. decltype(::SymFromAddr) *SymFromAddr;
  21. decltype(::SymFunctionTableAccess64) *SymFunctionTableAccess64;
  22. decltype(::SymGetLineFromAddr64) *SymGetLineFromAddr64;
  23. decltype(::SymGetModuleBase64) *SymGetModuleBase64;
  24. decltype(::SymGetSearchPathW) *SymGetSearchPathW;
  25. decltype(::SymInitialize) *SymInitialize;
  26. decltype(::SymSetOptions) *SymSetOptions;
  27. decltype(::SymSetSearchPathW) *SymSetSearchPathW;
  28. decltype(::UnDecorateSymbolName) *UnDecorateSymbolName;
  29. namespace {
  30. class WinSymbolizerTool final : public SymbolizerTool {
  31. public:
  32. // The constructor is provided to avoid synthesized memsets.
  33. WinSymbolizerTool() {}
  34. bool SymbolizePC(uptr addr, SymbolizedStack *stack) override;
  35. bool SymbolizeData(uptr addr, DataInfo *info) override {
  36. return false;
  37. }
  38. const char *Demangle(const char *name) override;
  39. };
  40. bool is_dbghelp_initialized = false;
  41. bool TrySymInitialize() {
  42. SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME | SYMOPT_LOAD_LINES);
  43. return SymInitialize(GetCurrentProcess(), 0, TRUE);
  44. // FIXME: We don't call SymCleanup() on exit yet - should we?
  45. }
  46. } // namespace
  47. // Initializes DbgHelp library, if it's not yet initialized. Calls to this
  48. // function should be synchronized with respect to other calls to DbgHelp API
  49. // (e.g. from WinSymbolizerTool).
  50. void InitializeDbgHelpIfNeeded() {
  51. if (is_dbghelp_initialized)
  52. return;
  53. HMODULE dbghelp = LoadLibraryA("dbghelp.dll");
  54. CHECK(dbghelp && "failed to load dbghelp.dll");
  55. #define DBGHELP_IMPORT(name) \
  56. do { \
  57. name = \
  58. reinterpret_cast<decltype(::name) *>(GetProcAddress(dbghelp, #name)); \
  59. CHECK(name != nullptr); \
  60. } while (0)
  61. DBGHELP_IMPORT(StackWalk64);
  62. DBGHELP_IMPORT(SymCleanup);
  63. DBGHELP_IMPORT(SymFromAddr);
  64. DBGHELP_IMPORT(SymFunctionTableAccess64);
  65. DBGHELP_IMPORT(SymGetLineFromAddr64);
  66. DBGHELP_IMPORT(SymGetModuleBase64);
  67. DBGHELP_IMPORT(SymGetSearchPathW);
  68. DBGHELP_IMPORT(SymInitialize);
  69. DBGHELP_IMPORT(SymSetOptions);
  70. DBGHELP_IMPORT(SymSetSearchPathW);
  71. DBGHELP_IMPORT(UnDecorateSymbolName);
  72. #undef DBGHELP_IMPORT
  73. if (!TrySymInitialize()) {
  74. // OK, maybe the client app has called SymInitialize already.
  75. // That's a bit unfortunate for us as all the DbgHelp functions are
  76. // single-threaded and we can't coordinate with the app.
  77. // FIXME: Can we stop the other threads at this point?
  78. // Anyways, we have to reconfigure stuff to make sure that SymInitialize
  79. // has all the appropriate options set.
  80. // Cross our fingers and reinitialize DbgHelp.
  81. Report("*** WARNING: Failed to initialize DbgHelp! ***\n");
  82. Report("*** Most likely this means that the app is already ***\n");
  83. Report("*** using DbgHelp, possibly with incompatible flags. ***\n");
  84. Report("*** Due to technical reasons, symbolization might crash ***\n");
  85. Report("*** or produce wrong results. ***\n");
  86. SymCleanup(GetCurrentProcess());
  87. TrySymInitialize();
  88. }
  89. is_dbghelp_initialized = true;
  90. // When an executable is run from a location different from the one where it
  91. // was originally built, we may not see the nearby PDB files.
  92. // To work around this, let's append the directory of the main module
  93. // to the symbol search path. All the failures below are not fatal.
  94. const size_t kSymPathSize = 2048;
  95. static wchar_t path_buffer[kSymPathSize + 1 + MAX_PATH];
  96. if (!SymGetSearchPathW(GetCurrentProcess(), path_buffer, kSymPathSize)) {
  97. Report("*** WARNING: Failed to SymGetSearchPathW ***\n");
  98. return;
  99. }
  100. size_t sz = wcslen(path_buffer);
  101. if (sz) {
  102. CHECK_EQ(0, wcscat_s(path_buffer, L";"));
  103. sz++;
  104. }
  105. DWORD res = GetModuleFileNameW(NULL, path_buffer + sz, MAX_PATH);
  106. if (res == 0 || res == MAX_PATH) {
  107. Report("*** WARNING: Failed to getting the EXE directory ***\n");
  108. return;
  109. }
  110. // Write the zero character in place of the last backslash to get the
  111. // directory of the main module at the end of path_buffer.
  112. wchar_t *last_bslash = wcsrchr(path_buffer + sz, L'\\');
  113. CHECK_NE(last_bslash, 0);
  114. *last_bslash = L'\0';
  115. if (!SymSetSearchPathW(GetCurrentProcess(), path_buffer)) {
  116. Report("*** WARNING: Failed to SymSetSearchPathW\n");
  117. return;
  118. }
  119. }
  120. bool WinSymbolizerTool::SymbolizePC(uptr addr, SymbolizedStack *frame) {
  121. InitializeDbgHelpIfNeeded();
  122. // See https://docs.microsoft.com/en-us/windows/win32/debug/retrieving-symbol-information-by-address
  123. InternalMmapVector<char> buffer(sizeof(SYMBOL_INFO) +
  124. MAX_SYM_NAME * sizeof(CHAR));
  125. PSYMBOL_INFO symbol = (PSYMBOL_INFO)&buffer[0];
  126. symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
  127. symbol->MaxNameLen = MAX_SYM_NAME;
  128. DWORD64 offset = 0;
  129. BOOL got_objname = SymFromAddr(GetCurrentProcess(),
  130. (DWORD64)addr, &offset, symbol);
  131. if (!got_objname)
  132. return false;
  133. DWORD unused;
  134. IMAGEHLP_LINE64 line_info;
  135. line_info.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
  136. BOOL got_fileline = SymGetLineFromAddr64(GetCurrentProcess(), (DWORD64)addr,
  137. &unused, &line_info);
  138. frame->info.function = internal_strdup(symbol->Name);
  139. frame->info.function_offset = (uptr)offset;
  140. if (got_fileline) {
  141. frame->info.file = internal_strdup(line_info.FileName);
  142. frame->info.line = line_info.LineNumber;
  143. }
  144. // Only consider this a successful symbolization attempt if we got file info.
  145. // Otherwise, try llvm-symbolizer.
  146. return got_fileline;
  147. }
  148. const char *WinSymbolizerTool::Demangle(const char *name) {
  149. CHECK(is_dbghelp_initialized);
  150. static char demangle_buffer[1000];
  151. if (name[0] == '\01' &&
  152. UnDecorateSymbolName(name + 1, demangle_buffer, sizeof(demangle_buffer),
  153. UNDNAME_NAME_ONLY))
  154. return demangle_buffer;
  155. else
  156. return name;
  157. }
  158. const char *Symbolizer::PlatformDemangle(const char *name) {
  159. return name;
  160. }
  161. namespace {
  162. struct ScopedHandle {
  163. ScopedHandle() : h_(nullptr) {}
  164. explicit ScopedHandle(HANDLE h) : h_(h) {}
  165. ~ScopedHandle() {
  166. if (h_)
  167. ::CloseHandle(h_);
  168. }
  169. HANDLE get() { return h_; }
  170. HANDLE *receive() { return &h_; }
  171. HANDLE release() {
  172. HANDLE h = h_;
  173. h_ = nullptr;
  174. return h;
  175. }
  176. HANDLE h_;
  177. };
  178. } // namespace
  179. bool SymbolizerProcess::StartSymbolizerSubprocess() {
  180. // Create inherited pipes for stdin and stdout.
  181. ScopedHandle stdin_read, stdin_write;
  182. ScopedHandle stdout_read, stdout_write;
  183. SECURITY_ATTRIBUTES attrs;
  184. attrs.nLength = sizeof(SECURITY_ATTRIBUTES);
  185. attrs.bInheritHandle = TRUE;
  186. attrs.lpSecurityDescriptor = nullptr;
  187. if (!::CreatePipe(stdin_read.receive(), stdin_write.receive(), &attrs, 0) ||
  188. !::CreatePipe(stdout_read.receive(), stdout_write.receive(), &attrs, 0)) {
  189. VReport(2, "WARNING: %s CreatePipe failed (error code: %d)\n",
  190. SanitizerToolName, path_, GetLastError());
  191. return false;
  192. }
  193. // Don't inherit the writing end of stdin or the reading end of stdout.
  194. if (!SetHandleInformation(stdin_write.get(), HANDLE_FLAG_INHERIT, 0) ||
  195. !SetHandleInformation(stdout_read.get(), HANDLE_FLAG_INHERIT, 0)) {
  196. VReport(2, "WARNING: %s SetHandleInformation failed (error code: %d)\n",
  197. SanitizerToolName, path_, GetLastError());
  198. return false;
  199. }
  200. // Compute the command line. Wrap double quotes around everything.
  201. const char *argv[kArgVMax];
  202. GetArgV(path_, argv);
  203. InternalScopedString command_line;
  204. for (int i = 0; argv[i]; i++) {
  205. const char *arg = argv[i];
  206. int arglen = internal_strlen(arg);
  207. // Check that tool command lines are simple and that complete escaping is
  208. // unnecessary.
  209. CHECK(!internal_strchr(arg, '"') && "quotes in args unsupported");
  210. CHECK(!internal_strstr(arg, "\\\\") &&
  211. "double backslashes in args unsupported");
  212. CHECK(arglen > 0 && arg[arglen - 1] != '\\' &&
  213. "args ending in backslash and empty args unsupported");
  214. command_line.append("\"%s\" ", arg);
  215. }
  216. VReport(3, "Launching symbolizer command: %s\n", command_line.data());
  217. // Launch llvm-symbolizer with stdin and stdout redirected.
  218. STARTUPINFOA si;
  219. memset(&si, 0, sizeof(si));
  220. si.cb = sizeof(si);
  221. si.dwFlags |= STARTF_USESTDHANDLES;
  222. si.hStdInput = stdin_read.get();
  223. si.hStdOutput = stdout_write.get();
  224. PROCESS_INFORMATION pi;
  225. memset(&pi, 0, sizeof(pi));
  226. if (!CreateProcessA(path_, // Executable
  227. command_line.data(), // Command line
  228. nullptr, // Process handle not inheritable
  229. nullptr, // Thread handle not inheritable
  230. TRUE, // Set handle inheritance to TRUE
  231. 0, // Creation flags
  232. nullptr, // Use parent's environment block
  233. nullptr, // Use parent's starting directory
  234. &si, &pi)) {
  235. VReport(2, "WARNING: %s failed to create process for %s (error code: %d)\n",
  236. SanitizerToolName, path_, GetLastError());
  237. return false;
  238. }
  239. // Process creation succeeded, so transfer handle ownership into the fields.
  240. input_fd_ = stdout_read.release();
  241. output_fd_ = stdin_write.release();
  242. // The llvm-symbolizer process is responsible for quitting itself when the
  243. // stdin pipe is closed, so we don't need these handles. Close them to prevent
  244. // leaks. If we ever want to try to kill the symbolizer process from the
  245. // parent, we'll want to hang on to these handles.
  246. CloseHandle(pi.hProcess);
  247. CloseHandle(pi.hThread);
  248. return true;
  249. }
  250. static void ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> *list,
  251. LowLevelAllocator *allocator) {
  252. if (!common_flags()->symbolize) {
  253. VReport(2, "Symbolizer is disabled.\n");
  254. return;
  255. }
  256. // Add llvm-symbolizer.
  257. const char *user_path = common_flags()->external_symbolizer_path;
  258. if (user_path && internal_strchr(user_path, '%')) {
  259. char *new_path = (char *)InternalAlloc(kMaxPathLength);
  260. SubstituteForFlagValue(user_path, new_path, kMaxPathLength);
  261. user_path = new_path;
  262. }
  263. const char *path =
  264. user_path ? user_path : FindPathToBinary("llvm-symbolizer.exe");
  265. if (path) {
  266. VReport(2, "Using llvm-symbolizer at %spath: %s\n",
  267. user_path ? "user-specified " : "", path);
  268. list->push_back(new(*allocator) LLVMSymbolizer(path, allocator));
  269. } else {
  270. if (user_path && user_path[0] == '\0') {
  271. VReport(2, "External symbolizer is explicitly disabled.\n");
  272. } else {
  273. VReport(2, "External symbolizer is not present.\n");
  274. }
  275. }
  276. // Add the dbghelp based symbolizer.
  277. list->push_back(new(*allocator) WinSymbolizerTool());
  278. }
  279. Symbolizer *Symbolizer::PlatformInit() {
  280. IntrusiveList<SymbolizerTool> list;
  281. list.clear();
  282. ChooseSymbolizerTools(&list, &symbolizer_allocator_);
  283. return new(symbolizer_allocator_) Symbolizer(list);
  284. }
  285. void Symbolizer::LateInitialize() {
  286. Symbolizer::GetOrInit()->LateInitializeTools();
  287. }
  288. } // namespace __sanitizer
  289. #endif // _WIN32