]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_libcdep.cc
Upgrade Unbound to 1.6.0. More to follow.
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_symbolizer_libcdep.cc
1 //===-- sanitizer_symbolizer_libcdep.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 //===----------------------------------------------------------------------===//
13
14 #include "sanitizer_allocator_internal.h"
15 #include "sanitizer_internal_defs.h"
16 #include "sanitizer_symbolizer_internal.h"
17
18 namespace __sanitizer {
19
20 Symbolizer *Symbolizer::GetOrInit() {
21   SpinMutexLock l(&init_mu_);
22   if (symbolizer_)
23     return symbolizer_;
24   symbolizer_ = PlatformInit();
25   CHECK(symbolizer_);
26   return symbolizer_;
27 }
28
29 // See sanitizer_symbolizer_fuchsia.cc.
30 #if !SANITIZER_FUCHSIA
31
32 const char *ExtractToken(const char *str, const char *delims, char **result) {
33   uptr prefix_len = internal_strcspn(str, delims);
34   *result = (char*)InternalAlloc(prefix_len + 1);
35   internal_memcpy(*result, str, prefix_len);
36   (*result)[prefix_len] = '\0';
37   const char *prefix_end = str + prefix_len;
38   if (*prefix_end != '\0') prefix_end++;
39   return prefix_end;
40 }
41
42 const char *ExtractInt(const char *str, const char *delims, int *result) {
43   char *buff;
44   const char *ret = ExtractToken(str, delims, &buff);
45   if (buff != 0) {
46     *result = (int)internal_atoll(buff);
47   }
48   InternalFree(buff);
49   return ret;
50 }
51
52 const char *ExtractUptr(const char *str, const char *delims, uptr *result) {
53   char *buff;
54   const char *ret = ExtractToken(str, delims, &buff);
55   if (buff != 0) {
56     *result = (uptr)internal_atoll(buff);
57   }
58   InternalFree(buff);
59   return ret;
60 }
61
62 const char *ExtractTokenUpToDelimiter(const char *str, const char *delimiter,
63                                       char **result) {
64   const char *found_delimiter = internal_strstr(str, delimiter);
65   uptr prefix_len =
66       found_delimiter ? found_delimiter - str : internal_strlen(str);
67   *result = (char *)InternalAlloc(prefix_len + 1);
68   internal_memcpy(*result, str, prefix_len);
69   (*result)[prefix_len] = '\0';
70   const char *prefix_end = str + prefix_len;
71   if (*prefix_end != '\0') prefix_end += internal_strlen(delimiter);
72   return prefix_end;
73 }
74
75 SymbolizedStack *Symbolizer::SymbolizePC(uptr addr) {
76   BlockingMutexLock l(&mu_);
77   const char *module_name;
78   uptr module_offset;
79   ModuleArch arch;
80   SymbolizedStack *res = SymbolizedStack::New(addr);
81   if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
82                                          &arch))
83     return res;
84   // Always fill data about module name and offset.
85   res->info.FillModuleInfo(module_name, module_offset, arch);
86   for (auto &tool : tools_) {
87     SymbolizerScope sym_scope(this);
88     if (tool.SymbolizePC(addr, res)) {
89       return res;
90     }
91   }
92   return res;
93 }
94
95 bool Symbolizer::SymbolizeData(uptr addr, DataInfo *info) {
96   BlockingMutexLock l(&mu_);
97   const char *module_name;
98   uptr module_offset;
99   ModuleArch arch;
100   if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
101                                          &arch))
102     return false;
103   info->Clear();
104   info->module = internal_strdup(module_name);
105   info->module_offset = module_offset;
106   info->module_arch = arch;
107   for (auto &tool : tools_) {
108     SymbolizerScope sym_scope(this);
109     if (tool.SymbolizeData(addr, info)) {
110       return true;
111     }
112   }
113   return true;
114 }
115
116 bool Symbolizer::GetModuleNameAndOffsetForPC(uptr pc, const char **module_name,
117                                              uptr *module_address) {
118   BlockingMutexLock l(&mu_);
119   const char *internal_module_name = nullptr;
120   ModuleArch arch;
121   if (!FindModuleNameAndOffsetForAddress(pc, &internal_module_name,
122                                          module_address, &arch))
123     return false;
124
125   if (module_name)
126     *module_name = module_names_.GetOwnedCopy(internal_module_name);
127   return true;
128 }
129
130 void Symbolizer::Flush() {
131   BlockingMutexLock l(&mu_);
132   for (auto &tool : tools_) {
133     SymbolizerScope sym_scope(this);
134     tool.Flush();
135   }
136 }
137
138 const char *Symbolizer::Demangle(const char *name) {
139   BlockingMutexLock l(&mu_);
140   for (auto &tool : tools_) {
141     SymbolizerScope sym_scope(this);
142     if (const char *demangled = tool.Demangle(name))
143       return demangled;
144   }
145   return PlatformDemangle(name);
146 }
147
148 void Symbolizer::PrepareForSandboxing() {
149   BlockingMutexLock l(&mu_);
150   PlatformPrepareForSandboxing();
151 }
152
153 bool Symbolizer::FindModuleNameAndOffsetForAddress(uptr address,
154                                                    const char **module_name,
155                                                    uptr *module_offset,
156                                                    ModuleArch *module_arch) {
157   const LoadedModule *module = FindModuleForAddress(address);
158   if (module == nullptr)
159     return false;
160   *module_name = module->full_name();
161   *module_offset = address - module->base_address();
162   *module_arch = module->arch();
163   return true;
164 }
165
166 void Symbolizer::RefreshModules() {
167   modules_.init();
168   fallback_modules_.fallbackInit();
169   RAW_CHECK(modules_.size() > 0);
170   modules_fresh_ = true;
171 }
172
173 static const LoadedModule *SearchForModule(const ListOfModules &modules,
174                                            uptr address) {
175   for (uptr i = 0; i < modules.size(); i++) {
176     if (modules[i].containsAddress(address)) {
177       return &modules[i];
178     }
179   }
180   return nullptr;
181 }
182
183 const LoadedModule *Symbolizer::FindModuleForAddress(uptr address) {
184   bool modules_were_reloaded = false;
185   if (!modules_fresh_) {
186     RefreshModules();
187     modules_were_reloaded = true;
188   }
189   const LoadedModule *module = SearchForModule(modules_, address);
190   if (module) return module;
191
192   // dlopen/dlclose interceptors invalidate the module list, but when
193   // interception is disabled, we need to retry if the lookup fails in
194   // case the module list changed.
195 #if !SANITIZER_INTERCEPT_DLOPEN_DLCLOSE
196   if (!modules_were_reloaded) {
197     RefreshModules();
198     module = SearchForModule(modules_, address);
199     if (module) return module;
200   }
201 #endif
202
203   if (fallback_modules_.size()) {
204     module = SearchForModule(fallback_modules_, address);
205   }
206   return module;
207 }
208
209 // For now we assume the following protocol:
210 // For each request of the form
211 //   <module_name> <module_offset>
212 // passed to STDIN, external symbolizer prints to STDOUT response:
213 //   <function_name>
214 //   <file_name>:<line_number>:<column_number>
215 //   <function_name>
216 //   <file_name>:<line_number>:<column_number>
217 //   ...
218 //   <empty line>
219 class LLVMSymbolizerProcess : public SymbolizerProcess {
220  public:
221   explicit LLVMSymbolizerProcess(const char *path) : SymbolizerProcess(path) {}
222
223  private:
224   bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
225     // Empty line marks the end of llvm-symbolizer output.
226     return length >= 2 && buffer[length - 1] == '\n' &&
227            buffer[length - 2] == '\n';
228   }
229
230   // When adding a new architecture, don't forget to also update
231   // script/asan_symbolize.py and sanitizer_common.h.
232   void GetArgV(const char *path_to_binary,
233                const char *(&argv)[kArgVMax]) const override {
234 #if defined(__x86_64h__)
235     const char* const kSymbolizerArch = "--default-arch=x86_64h";
236 #elif defined(__x86_64__)
237     const char* const kSymbolizerArch = "--default-arch=x86_64";
238 #elif defined(__i386__)
239     const char* const kSymbolizerArch = "--default-arch=i386";
240 #elif defined(__aarch64__)
241     const char* const kSymbolizerArch = "--default-arch=arm64";
242 #elif defined(__arm__)
243     const char* const kSymbolizerArch = "--default-arch=arm";
244 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
245     const char* const kSymbolizerArch = "--default-arch=powerpc64";
246 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
247     const char* const kSymbolizerArch = "--default-arch=powerpc64le";
248 #elif defined(__s390x__)
249     const char* const kSymbolizerArch = "--default-arch=s390x";
250 #elif defined(__s390__)
251     const char* const kSymbolizerArch = "--default-arch=s390";
252 #else
253     const char* const kSymbolizerArch = "--default-arch=unknown";
254 #endif
255
256     const char *const inline_flag = common_flags()->symbolize_inline_frames
257                                         ? "--inlining=true"
258                                         : "--inlining=false";
259     int i = 0;
260     argv[i++] = path_to_binary;
261     argv[i++] = inline_flag;
262     argv[i++] = kSymbolizerArch;
263     argv[i++] = nullptr;
264   }
265 };
266
267 LLVMSymbolizer::LLVMSymbolizer(const char *path, LowLevelAllocator *allocator)
268     : symbolizer_process_(new(*allocator) LLVMSymbolizerProcess(path)) {}
269
270 // Parse a <file>:<line>[:<column>] buffer. The file path may contain colons on
271 // Windows, so extract tokens from the right hand side first. The column info is
272 // also optional.
273 static const char *ParseFileLineInfo(AddressInfo *info, const char *str) {
274   char *file_line_info = 0;
275   str = ExtractToken(str, "\n", &file_line_info);
276   CHECK(file_line_info);
277
278   if (uptr size = internal_strlen(file_line_info)) {
279     char *back = file_line_info + size - 1;
280     for (int i = 0; i < 2; ++i) {
281       while (back > file_line_info && IsDigit(*back)) --back;
282       if (*back != ':' || !IsDigit(back[1])) break;
283       info->column = info->line;
284       info->line = internal_atoll(back + 1);
285       // Truncate the string at the colon to keep only filename.
286       *back = '\0';
287       --back;
288     }
289     ExtractToken(file_line_info, "", &info->file);
290   }
291
292   InternalFree(file_line_info);
293   return str;
294 }
295
296 // Parses one or more two-line strings in the following format:
297 //   <function_name>
298 //   <file_name>:<line_number>[:<column_number>]
299 // Used by LLVMSymbolizer, Addr2LinePool and InternalSymbolizer, since all of
300 // them use the same output format.
301 void ParseSymbolizePCOutput(const char *str, SymbolizedStack *res) {
302   bool top_frame = true;
303   SymbolizedStack *last = res;
304   while (true) {
305     char *function_name = 0;
306     str = ExtractToken(str, "\n", &function_name);
307     CHECK(function_name);
308     if (function_name[0] == '\0') {
309       // There are no more frames.
310       InternalFree(function_name);
311       break;
312     }
313     SymbolizedStack *cur;
314     if (top_frame) {
315       cur = res;
316       top_frame = false;
317     } else {
318       cur = SymbolizedStack::New(res->info.address);
319       cur->info.FillModuleInfo(res->info.module, res->info.module_offset,
320                                res->info.module_arch);
321       last->next = cur;
322       last = cur;
323     }
324
325     AddressInfo *info = &cur->info;
326     info->function = function_name;
327     str = ParseFileLineInfo(info, str);
328
329     // Functions and filenames can be "??", in which case we write 0
330     // to address info to mark that names are unknown.
331     if (0 == internal_strcmp(info->function, "??")) {
332       InternalFree(info->function);
333       info->function = 0;
334     }
335     if (0 == internal_strcmp(info->file, "??")) {
336       InternalFree(info->file);
337       info->file = 0;
338     }
339   }
340 }
341
342 // Parses a two-line string in the following format:
343 //   <symbol_name>
344 //   <start_address> <size>
345 // Used by LLVMSymbolizer and InternalSymbolizer.
346 void ParseSymbolizeDataOutput(const char *str, DataInfo *info) {
347   str = ExtractToken(str, "\n", &info->name);
348   str = ExtractUptr(str, " ", &info->start);
349   str = ExtractUptr(str, "\n", &info->size);
350 }
351
352 bool LLVMSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {
353   AddressInfo *info = &stack->info;
354   const char *buf = FormatAndSendCommand(
355       /*is_data*/ false, info->module, info->module_offset, info->module_arch);
356   if (buf) {
357     ParseSymbolizePCOutput(buf, stack);
358     return true;
359   }
360   return false;
361 }
362
363 bool LLVMSymbolizer::SymbolizeData(uptr addr, DataInfo *info) {
364   const char *buf = FormatAndSendCommand(
365       /*is_data*/ true, info->module, info->module_offset, info->module_arch);
366   if (buf) {
367     ParseSymbolizeDataOutput(buf, info);
368     info->start += (addr - info->module_offset); // Add the base address.
369     return true;
370   }
371   return false;
372 }
373
374 const char *LLVMSymbolizer::FormatAndSendCommand(bool is_data,
375                                                  const char *module_name,
376                                                  uptr module_offset,
377                                                  ModuleArch arch) {
378   CHECK(module_name);
379   const char *is_data_str = is_data ? "DATA " : "";
380   if (arch == kModuleArchUnknown) {
381     if (internal_snprintf(buffer_, kBufferSize, "%s\"%s\" 0x%zx\n", is_data_str,
382                           module_name,
383                           module_offset) >= static_cast<int>(kBufferSize)) {
384       Report("WARNING: Command buffer too small");
385       return nullptr;
386     }
387   } else {
388     if (internal_snprintf(buffer_, kBufferSize, "%s\"%s:%s\" 0x%zx\n",
389                           is_data_str, module_name, ModuleArchToString(arch),
390                           module_offset) >= static_cast<int>(kBufferSize)) {
391       Report("WARNING: Command buffer too small");
392       return nullptr;
393     }
394   }
395   return symbolizer_process_->SendCommand(buffer_);
396 }
397
398 SymbolizerProcess::SymbolizerProcess(const char *path, bool use_forkpty)
399     : path_(path),
400       input_fd_(kInvalidFd),
401       output_fd_(kInvalidFd),
402       times_restarted_(0),
403       failed_to_start_(false),
404       reported_invalid_path_(false),
405       use_forkpty_(use_forkpty) {
406   CHECK(path_);
407   CHECK_NE(path_[0], '\0');
408 }
409
410 static bool IsSameModule(const char* path) {
411   if (const char* ProcessName = GetProcessName()) {
412     if (const char* SymbolizerName = StripModuleName(path)) {
413       return !internal_strcmp(ProcessName, SymbolizerName);
414     }
415   }
416   return false;
417 }
418
419 const char *SymbolizerProcess::SendCommand(const char *command) {
420   if (failed_to_start_)
421     return nullptr;
422   if (IsSameModule(path_)) {
423     Report("WARNING: Symbolizer was blocked from starting itself!\n");
424     failed_to_start_ = true;
425     return nullptr;
426   }
427   for (; times_restarted_ < kMaxTimesRestarted; times_restarted_++) {
428     // Start or restart symbolizer if we failed to send command to it.
429     if (const char *res = SendCommandImpl(command))
430       return res;
431     Restart();
432   }
433   if (!failed_to_start_) {
434     Report("WARNING: Failed to use and restart external symbolizer!\n");
435     failed_to_start_ = true;
436   }
437   return 0;
438 }
439
440 const char *SymbolizerProcess::SendCommandImpl(const char *command) {
441   if (input_fd_ == kInvalidFd || output_fd_ == kInvalidFd)
442       return 0;
443   if (!WriteToSymbolizer(command, internal_strlen(command)))
444       return 0;
445   if (!ReadFromSymbolizer(buffer_, kBufferSize))
446       return 0;
447   return buffer_;
448 }
449
450 bool SymbolizerProcess::Restart() {
451   if (input_fd_ != kInvalidFd)
452     CloseFile(input_fd_);
453   if (output_fd_ != kInvalidFd)
454     CloseFile(output_fd_);
455   return StartSymbolizerSubprocess();
456 }
457
458 bool SymbolizerProcess::ReadFromSymbolizer(char *buffer, uptr max_length) {
459   if (max_length == 0)
460     return true;
461   uptr read_len = 0;
462   while (true) {
463     uptr just_read = 0;
464     bool success = ReadFromFile(input_fd_, buffer + read_len,
465                                 max_length - read_len - 1, &just_read);
466     // We can't read 0 bytes, as we don't expect external symbolizer to close
467     // its stdout.
468     if (!success || just_read == 0) {
469       Report("WARNING: Can't read from symbolizer at fd %d\n", input_fd_);
470       return false;
471     }
472     read_len += just_read;
473     if (ReachedEndOfOutput(buffer, read_len))
474       break;
475     if (read_len + 1 == max_length) {
476       Report("WARNING: Symbolizer buffer too small\n");
477       read_len = 0;
478       break;
479     }
480   }
481   buffer[read_len] = '\0';
482   return true;
483 }
484
485 bool SymbolizerProcess::WriteToSymbolizer(const char *buffer, uptr length) {
486   if (length == 0)
487     return true;
488   uptr write_len = 0;
489   bool success = WriteToFile(output_fd_, buffer, length, &write_len);
490   if (!success || write_len != length) {
491     Report("WARNING: Can't write to symbolizer at fd %d\n", output_fd_);
492     return false;
493   }
494   return true;
495 }
496
497 #endif  // !SANITIZER_FUCHSIA
498
499 }  // namespace __sanitizer