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