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