1 //===-- sanitizer_symbolizer_posix_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 // POSIX-specific implementation of symbolizer parts.
13 //===----------------------------------------------------------------------===//
14 
15 #include "sanitizer_platform.h"
16 #if SANITIZER_POSIX
17 #include "sanitizer_allocator_internal.h"
18 #include "sanitizer_common.h"
19 #include "sanitizer_flags.h"
20 #include "sanitizer_internal_defs.h"
21 #include "sanitizer_linux.h"
22 #include "sanitizer_placement_new.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_symbolizer_internal.h"
25 #include "sanitizer_symbolizer_libbacktrace.h"
26 #include "sanitizer_symbolizer_mac.h"
27 
28 #include <unistd.h>
29 
30 // C++ demangling function, as required by Itanium C++ ABI. This is weak,
31 // because we do not require a C++ ABI library to be linked to a program
32 // using sanitizers; if it's not present, we'll just use the mangled name.
33 namespace __cxxabiv1 {
34   extern "C" SANITIZER_WEAK_ATTRIBUTE
35   char *__cxa_demangle(const char *mangled, char *buffer,
36                                   size_t *length, int *status);
37 }
38 
39 namespace __sanitizer {
40 
41 // Attempts to demangle the name via __cxa_demangle from __cxxabiv1.
DemangleCXXABI(const char * name)42 const char *DemangleCXXABI(const char *name) {
43   // FIXME: __cxa_demangle aggressively insists on allocating memory.
44   // There's not much we can do about that, short of providing our
45   // own demangler (libc++abi's implementation could be adapted so that
46   // it does not allocate). For now, we just call it anyway, and we leak
47   // the returned value.
48   if (__cxxabiv1::__cxa_demangle)
49     if (const char *demangled_name =
50           __cxxabiv1::__cxa_demangle(name, 0, 0, 0))
51       return demangled_name;
52 
53   return name;
54 }
55 
56 // Parses one or more two-line strings in the following format:
57 //   <function_name>
58 //   <file_name>:<line_number>[:<column_number>]
59 // Used by LLVMSymbolizer, Addr2LinePool and InternalSymbolizer, since all of
60 // them use the same output format.
ParseSymbolizePCOutput(const char * str,SymbolizedStack * res)61 static void ParseSymbolizePCOutput(const char *str, SymbolizedStack *res) {
62   bool top_frame = true;
63   SymbolizedStack *last = res;
64   while (true) {
65     char *function_name = 0;
66     str = ExtractToken(str, "\n", &function_name);
67     CHECK(function_name);
68     if (function_name[0] == '\0') {
69       // There are no more frames.
70       break;
71     }
72     SymbolizedStack *cur;
73     if (top_frame) {
74       cur = res;
75       top_frame = false;
76     } else {
77       cur = SymbolizedStack::New(res->info.address);
78       cur->info.FillModuleInfo(res->info.module, res->info.module_offset);
79       last->next = cur;
80       last = cur;
81     }
82 
83     AddressInfo *info = &cur->info;
84     info->function = function_name;
85     // Parse <file>:<line>:<column> buffer.
86     char *file_line_info = 0;
87     str = ExtractToken(str, "\n", &file_line_info);
88     CHECK(file_line_info);
89     const char *line_info = ExtractToken(file_line_info, ":", &info->file);
90     line_info = ExtractInt(line_info, ":", &info->line);
91     line_info = ExtractInt(line_info, "", &info->column);
92     InternalFree(file_line_info);
93 
94     // Functions and filenames can be "??", in which case we write 0
95     // to address info to mark that names are unknown.
96     if (0 == internal_strcmp(info->function, "??")) {
97       InternalFree(info->function);
98       info->function = 0;
99     }
100     if (0 == internal_strcmp(info->file, "??")) {
101       InternalFree(info->file);
102       info->file = 0;
103     }
104   }
105 }
106 
107 // Parses a two-line string in the following format:
108 //   <symbol_name>
109 //   <start_address> <size>
110 // Used by LLVMSymbolizer and InternalSymbolizer.
ParseSymbolizeDataOutput(const char * str,DataInfo * info)111 static void ParseSymbolizeDataOutput(const char *str, DataInfo *info) {
112   str = ExtractToken(str, "\n", &info->name);
113   str = ExtractUptr(str, " ", &info->start);
114   str = ExtractUptr(str, "\n", &info->size);
115 }
116 
117 // For now we assume the following protocol:
118 // For each request of the form
119 //   <module_name> <module_offset>
120 // passed to STDIN, external symbolizer prints to STDOUT response:
121 //   <function_name>
122 //   <file_name>:<line_number>:<column_number>
123 //   <function_name>
124 //   <file_name>:<line_number>:<column_number>
125 //   ...
126 //   <empty line>
127 class LLVMSymbolizerProcess : public SymbolizerProcess {
128  public:
LLVMSymbolizerProcess(const char * path)129   explicit LLVMSymbolizerProcess(const char *path) : SymbolizerProcess(path) {}
130 
131  private:
ReachedEndOfOutput(const char * buffer,uptr length) const132   bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
133     // Empty line marks the end of llvm-symbolizer output.
134     return length >= 2 && buffer[length - 1] == '\n' &&
135            buffer[length - 2] == '\n';
136   }
137 
ExecuteWithDefaultArgs(const char * path_to_binary) const138   void ExecuteWithDefaultArgs(const char *path_to_binary) const override {
139 #if defined(__x86_64__)
140     const char* const kSymbolizerArch = "--default-arch=x86_64";
141 #elif defined(__i386__)
142     const char* const kSymbolizerArch = "--default-arch=i386";
143 #elif defined(__powerpc64__) && defined(__BIG_ENDIAN__)
144     const char* const kSymbolizerArch = "--default-arch=powerpc64";
145 #elif defined(__powerpc64__) && defined(__LITTLE_ENDIAN__)
146     const char* const kSymbolizerArch = "--default-arch=powerpc64le";
147 #else
148     const char* const kSymbolizerArch = "--default-arch=unknown";
149 #endif
150 
151     const char *const inline_flag = common_flags()->symbolize_inline_frames
152                                         ? "--inlining=true"
153                                         : "--inlining=false";
154     execl(path_to_binary, path_to_binary, inline_flag, kSymbolizerArch,
155           (char *)0);
156   }
157 };
158 
159 class LLVMSymbolizer : public SymbolizerTool {
160  public:
LLVMSymbolizer(const char * path,LowLevelAllocator * allocator)161   explicit LLVMSymbolizer(const char *path, LowLevelAllocator *allocator)
162       : symbolizer_process_(new(*allocator) LLVMSymbolizerProcess(path)) {}
163 
SymbolizePC(uptr addr,SymbolizedStack * stack)164   bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
165     if (const char *buf = SendCommand(/*is_data*/ false, stack->info.module,
166                                       stack->info.module_offset)) {
167       ParseSymbolizePCOutput(buf, stack);
168       return true;
169     }
170     return false;
171   }
172 
SymbolizeData(uptr addr,DataInfo * info)173   bool SymbolizeData(uptr addr, DataInfo *info) override {
174     if (const char *buf =
175             SendCommand(/*is_data*/ true, info->module, info->module_offset)) {
176       ParseSymbolizeDataOutput(buf, info);
177       info->start += (addr - info->module_offset);  // Add the base address.
178       return true;
179     }
180     return false;
181   }
182 
183  private:
SendCommand(bool is_data,const char * module_name,uptr module_offset)184   const char *SendCommand(bool is_data, const char *module_name,
185                           uptr module_offset) {
186     CHECK(module_name);
187     internal_snprintf(buffer_, kBufferSize, "%s\"%s\" 0x%zx\n",
188                       is_data ? "DATA " : "", module_name, module_offset);
189     return symbolizer_process_->SendCommand(buffer_);
190   }
191 
192   LLVMSymbolizerProcess *symbolizer_process_;
193   static const uptr kBufferSize = 16 * 1024;
194   char buffer_[kBufferSize];
195 };
196 
197 class Addr2LineProcess : public SymbolizerProcess {
198  public:
Addr2LineProcess(const char * path,const char * module_name)199   Addr2LineProcess(const char *path, const char *module_name)
200       : SymbolizerProcess(path), module_name_(internal_strdup(module_name)) {}
201 
module_name() const202   const char *module_name() const { return module_name_; }
203 
204  private:
ReachedEndOfOutput(const char * buffer,uptr length) const205   bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
206     // Output should consist of two lines.
207     int num_lines = 0;
208     for (uptr i = 0; i < length; ++i) {
209       if (buffer[i] == '\n')
210         num_lines++;
211       if (num_lines >= 2)
212         return true;
213     }
214     return false;
215   }
216 
ExecuteWithDefaultArgs(const char * path_to_binary) const217   void ExecuteWithDefaultArgs(const char *path_to_binary) const override {
218     execl(path_to_binary, path_to_binary, "-Cfe", module_name_, (char *)0);
219   }
220 
221   const char *module_name_;  // Owned, leaked.
222 };
223 
224 class Addr2LinePool : public SymbolizerTool {
225  public:
Addr2LinePool(const char * addr2line_path,LowLevelAllocator * allocator)226   explicit Addr2LinePool(const char *addr2line_path,
227                          LowLevelAllocator *allocator)
228       : addr2line_path_(addr2line_path), allocator_(allocator),
229         addr2line_pool_(16) {}
230 
SymbolizePC(uptr addr,SymbolizedStack * stack)231   bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
232     if (const char *buf =
233             SendCommand(stack->info.module, stack->info.module_offset)) {
234       ParseSymbolizePCOutput(buf, stack);
235       return true;
236     }
237     return false;
238   }
239 
SymbolizeData(uptr addr,DataInfo * info)240   bool SymbolizeData(uptr addr, DataInfo *info) override {
241     return false;
242   }
243 
244  private:
SendCommand(const char * module_name,uptr module_offset)245   const char *SendCommand(const char *module_name, uptr module_offset) {
246     Addr2LineProcess *addr2line = 0;
247     for (uptr i = 0; i < addr2line_pool_.size(); ++i) {
248       if (0 ==
249           internal_strcmp(module_name, addr2line_pool_[i]->module_name())) {
250         addr2line = addr2line_pool_[i];
251         break;
252       }
253     }
254     if (!addr2line) {
255       addr2line =
256           new(*allocator_) Addr2LineProcess(addr2line_path_, module_name);
257       addr2line_pool_.push_back(addr2line);
258     }
259     CHECK_EQ(0, internal_strcmp(module_name, addr2line->module_name()));
260     char buffer_[kBufferSize];
261     internal_snprintf(buffer_, kBufferSize, "0x%zx\n", module_offset);
262     return addr2line->SendCommand(buffer_);
263   }
264 
265   static const uptr kBufferSize = 32;
266   const char *addr2line_path_;
267   LowLevelAllocator *allocator_;
268   InternalMmapVector<Addr2LineProcess*> addr2line_pool_;
269 };
270 
271 #if SANITIZER_SUPPORTS_WEAK_HOOKS
272 extern "C" {
273 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
274 bool __sanitizer_symbolize_code(const char *ModuleName, u64 ModuleOffset,
275                                 char *Buffer, int MaxLength);
276 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
277 bool __sanitizer_symbolize_data(const char *ModuleName, u64 ModuleOffset,
278                                 char *Buffer, int MaxLength);
279 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
280 void __sanitizer_symbolize_flush();
281 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
282 int __sanitizer_symbolize_demangle(const char *Name, char *Buffer,
283                                    int MaxLength);
284 }  // extern "C"
285 
286 class InternalSymbolizer : public SymbolizerTool {
287  public:
get(LowLevelAllocator * alloc)288   static InternalSymbolizer *get(LowLevelAllocator *alloc) {
289     if (__sanitizer_symbolize_code != 0 &&
290         __sanitizer_symbolize_data != 0) {
291       return new(*alloc) InternalSymbolizer();
292     }
293     return 0;
294   }
295 
SymbolizePC(uptr addr,SymbolizedStack * stack)296   bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
297     bool result = __sanitizer_symbolize_code(
298         stack->info.module, stack->info.module_offset, buffer_, kBufferSize);
299     if (result) ParseSymbolizePCOutput(buffer_, stack);
300     return result;
301   }
302 
SymbolizeData(uptr addr,DataInfo * info)303   bool SymbolizeData(uptr addr, DataInfo *info) override {
304     bool result = __sanitizer_symbolize_data(info->module, info->module_offset,
305                                              buffer_, kBufferSize);
306     if (result) {
307       ParseSymbolizeDataOutput(buffer_, info);
308       info->start += (addr - info->module_offset);  // Add the base address.
309     }
310     return result;
311   }
312 
Flush()313   void Flush() override {
314     if (__sanitizer_symbolize_flush)
315       __sanitizer_symbolize_flush();
316   }
317 
Demangle(const char * name)318   const char *Demangle(const char *name) override {
319     if (__sanitizer_symbolize_demangle) {
320       for (uptr res_length = 1024;
321            res_length <= InternalSizeClassMap::kMaxSize;) {
322         char *res_buff = static_cast<char*>(InternalAlloc(res_length));
323         uptr req_length =
324             __sanitizer_symbolize_demangle(name, res_buff, res_length);
325         if (req_length > res_length) {
326           res_length = req_length + 1;
327           InternalFree(res_buff);
328           continue;
329         }
330         return res_buff;
331       }
332     }
333     return name;
334   }
335 
336  private:
InternalSymbolizer()337   InternalSymbolizer() { }
338 
339   static const int kBufferSize = 16 * 1024;
340   static const int kMaxDemangledNameSize = 1024;
341   char buffer_[kBufferSize];
342 };
343 #else  // SANITIZER_SUPPORTS_WEAK_HOOKS
344 
345 class InternalSymbolizer : public SymbolizerTool {
346  public:
get(LowLevelAllocator * alloc)347   static InternalSymbolizer *get(LowLevelAllocator *alloc) { return 0; }
348 };
349 
350 #endif  // SANITIZER_SUPPORTS_WEAK_HOOKS
351 
PlatformDemangle(const char * name)352 const char *Symbolizer::PlatformDemangle(const char *name) {
353   return DemangleCXXABI(name);
354 }
355 
PlatformPrepareForSandboxing()356 void Symbolizer::PlatformPrepareForSandboxing() {
357 #if SANITIZER_LINUX && !SANITIZER_ANDROID
358   // Cache /proc/self/exe on Linux.
359   CacheBinaryName();
360 #endif
361 }
362 
ChooseExternalSymbolizer(LowLevelAllocator * allocator)363 static SymbolizerTool *ChooseExternalSymbolizer(LowLevelAllocator *allocator) {
364   const char *path = common_flags()->external_symbolizer_path;
365   const char *binary_name = path ? StripModuleName(path) : "";
366   if (path && path[0] == '\0') {
367     VReport(2, "External symbolizer is explicitly disabled.\n");
368     return nullptr;
369   } else if (!internal_strcmp(binary_name, "llvm-symbolizer")) {
370     VReport(2, "Using llvm-symbolizer at user-specified path: %s\n", path);
371     return new(*allocator) LLVMSymbolizer(path, allocator);
372   } else if (!internal_strcmp(binary_name, "atos")) {
373 #if SANITIZER_MAC
374     VReport(2, "Using atos at user-specified path: %s\n", path);
375     return new(*allocator) AtosSymbolizer(path, allocator);
376 #else  // SANITIZER_MAC
377     Report("ERROR: Using `atos` is only supported on Darwin.\n");
378     Die();
379 #endif  // SANITIZER_MAC
380   } else if (!internal_strcmp(binary_name, "addr2line")) {
381     VReport(2, "Using addr2line at user-specified path: %s\n", path);
382     return new(*allocator) Addr2LinePool(path, allocator);
383   } else if (path) {
384     Report("ERROR: External symbolizer path is set to '%s' which isn't "
385            "a known symbolizer. Please set the path to the llvm-symbolizer "
386            "binary or other known tool.\n", path);
387     Die();
388   }
389 
390   // Otherwise symbolizer program is unknown, let's search $PATH
391   CHECK(path == nullptr);
392   if (const char *found_path = FindPathToBinary("llvm-symbolizer")) {
393     VReport(2, "Using llvm-symbolizer found at: %s\n", found_path);
394     return new(*allocator) LLVMSymbolizer(found_path, allocator);
395   }
396 #if SANITIZER_MAC
397   if (const char *found_path = FindPathToBinary("atos")) {
398     VReport(2, "Using atos found at: %s\n", found_path);
399     return new(*allocator) AtosSymbolizer(found_path, allocator);
400   }
401 #endif  // SANITIZER_MAC
402   if (common_flags()->allow_addr2line) {
403     if (const char *found_path = FindPathToBinary("addr2line")) {
404       VReport(2, "Using addr2line found at: %s\n", found_path);
405       return new(*allocator) Addr2LinePool(found_path, allocator);
406     }
407   }
408   return nullptr;
409 }
410 
ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> * list,LowLevelAllocator * allocator)411 static void ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> *list,
412                                   LowLevelAllocator *allocator) {
413   if (!common_flags()->symbolize) {
414     VReport(2, "Symbolizer is disabled.\n");
415     return;
416   }
417   if (SymbolizerTool *tool = InternalSymbolizer::get(allocator)) {
418     VReport(2, "Using internal symbolizer.\n");
419     list->push_back(tool);
420     return;
421   }
422   if (SymbolizerTool *tool = LibbacktraceSymbolizer::get(allocator)) {
423     VReport(2, "Using libbacktrace symbolizer.\n");
424     list->push_back(tool);
425     return;
426   }
427 
428   if (SymbolizerTool *tool = ChooseExternalSymbolizer(allocator)) {
429     list->push_back(tool);
430   } else {
431     VReport(2, "No internal or external symbolizer found.\n");
432   }
433 
434 #if SANITIZER_MAC
435   VReport(2, "Using dladdr symbolizer.\n");
436   list->push_back(new(*allocator) DlAddrSymbolizer());
437 #endif  // SANITIZER_MAC
438 }
439 
PlatformInit()440 Symbolizer *Symbolizer::PlatformInit() {
441   IntrusiveList<SymbolizerTool> list;
442   list.clear();
443   ChooseSymbolizerTools(&list, &symbolizer_allocator_);
444   return new(symbolizer_allocator_) Symbolizer(list);
445 }
446 
447 }  // namespace __sanitizer
448 
449 #endif  // SANITIZER_POSIX
450