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