]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/compiler-rt/lib/sanitizer_common/sanitizer_symbolizer_posix_libcdep.cc
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / compiler-rt / lib / sanitizer_common / sanitizer_symbolizer_posix_libcdep.cc
1 //===-- sanitizer_symbolizer_posix_libcdep.cc -----------------------------===//
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 // POSIX-specific implementation of symbolizer parts.
12 //===----------------------------------------------------------------------===//
13
14 #include "sanitizer_platform.h"
15 #if SANITIZER_POSIX
16 #include "sanitizer_allocator_internal.h"
17 #include "sanitizer_common.h"
18 #include "sanitizer_file.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_posix.h"
24 #include "sanitizer_procmaps.h"
25 #include "sanitizer_symbolizer_internal.h"
26 #include "sanitizer_symbolizer_libbacktrace.h"
27 #include "sanitizer_symbolizer_mac.h"
28
29 #include <dlfcn.h>   // for dlsym()
30 #include <errno.h>
31 #include <stdint.h>
32 #include <stdlib.h>
33 #include <sys/wait.h>
34 #include <unistd.h>
35
36 #if SANITIZER_MAC
37 #include <util.h>  // for forkpty()
38 #endif  // SANITIZER_MAC
39
40 // C++ demangling function, as required by Itanium C++ ABI. This is weak,
41 // because we do not require a C++ ABI library to be linked to a program
42 // using sanitizers; if it's not present, we'll just use the mangled name.
43 namespace __cxxabiv1 {
44   extern "C" SANITIZER_WEAK_ATTRIBUTE
45   char *__cxa_demangle(const char *mangled, char *buffer,
46                                   size_t *length, int *status);
47 }
48
49 namespace __sanitizer {
50
51 // Attempts to demangle the name via __cxa_demangle from __cxxabiv1.
52 const char *DemangleCXXABI(const char *name) {
53   // FIXME: __cxa_demangle aggressively insists on allocating memory.
54   // There's not much we can do about that, short of providing our
55   // own demangler (libc++abi's implementation could be adapted so that
56   // it does not allocate). For now, we just call it anyway, and we leak
57   // the returned value.
58   if (&__cxxabiv1::__cxa_demangle)
59     if (const char *demangled_name =
60           __cxxabiv1::__cxa_demangle(name, 0, 0, 0))
61       return demangled_name;
62
63   return name;
64 }
65
66 // As of now, there are no headers for the Swift runtime. Once they are
67 // present, we will weakly link since we do not require Swift runtime to be
68 // linked.
69 typedef char *(*swift_demangle_ft)(const char *mangledName,
70                                    size_t mangledNameLength, char *outputBuffer,
71                                    size_t *outputBufferSize, uint32_t flags);
72 static swift_demangle_ft swift_demangle_f;
73
74 // This must not happen lazily at symbolication time, because dlsym uses
75 // malloc and thread-local storage, which is not a good thing to do during
76 // symbolication.
77 static void InitializeSwiftDemangler() {
78   swift_demangle_f = (swift_demangle_ft)dlsym(RTLD_DEFAULT, "swift_demangle");
79   (void)dlerror(); // Cleanup error message in case of failure
80 }
81
82 // Attempts to demangle a Swift name. The demangler will return nullptr if a
83 // non-Swift name is passed in.
84 const char *DemangleSwift(const char *name) {
85   if (!name) return nullptr;
86
87   // Check if we are dealing with a Swift mangled name first.
88   if (name[0] != '_' || name[1] != 'T') {
89     return nullptr;
90   }
91
92   if (swift_demangle_f)
93     return swift_demangle_f(name, internal_strlen(name), 0, 0, 0);
94
95   return nullptr;
96 }
97
98 const char *DemangleSwiftAndCXX(const char *name) {
99   if (!name) return nullptr;
100   if (const char *swift_demangled_name = DemangleSwift(name))
101     return swift_demangled_name;
102   return DemangleCXXABI(name);
103 }
104
105 static bool CreateTwoHighNumberedPipes(int *infd_, int *outfd_) {
106   int *infd = NULL;
107   int *outfd = NULL;
108   // The client program may close its stdin and/or stdout and/or stderr
109   // thus allowing socketpair to reuse file descriptors 0, 1 or 2.
110   // In this case the communication between the forked processes may be
111   // broken if either the parent or the child tries to close or duplicate
112   // these descriptors. The loop below produces two pairs of file
113   // descriptors, each greater than 2 (stderr).
114   int sock_pair[5][2];
115   for (int i = 0; i < 5; i++) {
116     if (pipe(sock_pair[i]) == -1) {
117       for (int j = 0; j < i; j++) {
118         internal_close(sock_pair[j][0]);
119         internal_close(sock_pair[j][1]);
120       }
121       return false;
122     } else if (sock_pair[i][0] > 2 && sock_pair[i][1] > 2) {
123       if (infd == NULL) {
124         infd = sock_pair[i];
125       } else {
126         outfd = sock_pair[i];
127         for (int j = 0; j < i; j++) {
128           if (sock_pair[j] == infd) continue;
129           internal_close(sock_pair[j][0]);
130           internal_close(sock_pair[j][1]);
131         }
132         break;
133       }
134     }
135   }
136   CHECK(infd);
137   CHECK(outfd);
138   infd_[0] = infd[0];
139   infd_[1] = infd[1];
140   outfd_[0] = outfd[0];
141   outfd_[1] = outfd[1];
142   return true;
143 }
144
145 bool SymbolizerProcess::StartSymbolizerSubprocess() {
146   if (!FileExists(path_)) {
147     if (!reported_invalid_path_) {
148       Report("WARNING: invalid path to external symbolizer!\n");
149       reported_invalid_path_ = true;
150     }
151     return false;
152   }
153
154   int pid = -1;
155
156   int infd[2];
157   internal_memset(&infd, 0, sizeof(infd));
158   int outfd[2];
159   internal_memset(&outfd, 0, sizeof(outfd));
160   if (!CreateTwoHighNumberedPipes(infd, outfd)) {
161     Report("WARNING: Can't create a socket pair to start "
162            "external symbolizer (errno: %d)\n", errno);
163     return false;
164   }
165
166   if (use_forkpty_) {
167 #if SANITIZER_MAC
168     fd_t fd = kInvalidFd;
169
170     // forkpty redirects stdout and stderr into a single stream, so we would
171     // receive error messages as standard replies. To avoid that, let's dup
172     // stderr and restore it in the child.
173     int saved_stderr = dup(STDERR_FILENO);
174     CHECK_GE(saved_stderr, 0);
175
176     // We only need one pipe, for stdin of the child.
177     close(outfd[0]);
178     close(outfd[1]);
179
180     // Use forkpty to disable buffering in the new terminal.
181     pid = internal_forkpty(&fd);
182     if (pid == -1) {
183       // forkpty() failed.
184       Report("WARNING: failed to fork external symbolizer (errno: %d)\n",
185              errno);
186       return false;
187     } else if (pid == 0) {
188       // Child subprocess.
189
190       // infd[0] is the child's reading end.
191       close(infd[1]);
192
193       // Set up stdin to read from the pipe.
194       CHECK_GE(dup2(infd[0], STDIN_FILENO), 0);
195       close(infd[0]);
196
197       // Restore stderr.
198       CHECK_GE(dup2(saved_stderr, STDERR_FILENO), 0);
199       close(saved_stderr);
200
201       const char *argv[kArgVMax];
202       GetArgV(path_, argv);
203       execv(path_, const_cast<char **>(&argv[0]));
204       internal__exit(1);
205     }
206
207     // Input for the child, infd[1] is our writing end.
208     output_fd_ = infd[1];
209     close(infd[0]);
210
211     // Continue execution in parent process.
212     input_fd_ = fd;
213
214     close(saved_stderr);
215
216     // Disable echo in the new terminal, disable CR.
217     struct termios termflags;
218     tcgetattr(fd, &termflags);
219     termflags.c_oflag &= ~ONLCR;
220     termflags.c_lflag &= ~ECHO;
221     tcsetattr(fd, TCSANOW, &termflags);
222 #else  // SANITIZER_MAC
223     UNIMPLEMENTED();
224 #endif  // SANITIZER_MAC
225   } else {
226     const char *argv[kArgVMax];
227     GetArgV(path_, argv);
228     pid = StartSubprocess(path_, argv, /* stdin */ outfd[0],
229                           /* stdout */ infd[1]);
230     if (pid < 0) {
231       internal_close(infd[0]);
232       internal_close(outfd[1]);
233       return false;
234     }
235
236     input_fd_ = infd[0];
237     output_fd_ = outfd[1];
238   }
239
240   CHECK_GT(pid, 0);
241
242   // Check that symbolizer subprocess started successfully.
243   SleepForMillis(kSymbolizerStartupTimeMillis);
244   if (!IsProcessRunning(pid)) {
245     // Either waitpid failed, or child has already exited.
246     Report("WARNING: external symbolizer didn't start up correctly!\n");
247     return false;
248   }
249
250   return true;
251 }
252
253 class Addr2LineProcess : public SymbolizerProcess {
254  public:
255   Addr2LineProcess(const char *path, const char *module_name)
256       : SymbolizerProcess(path), module_name_(internal_strdup(module_name)) {}
257
258   const char *module_name() const { return module_name_; }
259
260  private:
261   void GetArgV(const char *path_to_binary,
262                const char *(&argv)[kArgVMax]) const override {
263     int i = 0;
264     argv[i++] = path_to_binary;
265     argv[i++] = "-iCfe";
266     argv[i++] = module_name_;
267     argv[i++] = nullptr;
268   }
269
270   bool ReachedEndOfOutput(const char *buffer, uptr length) const override;
271
272   bool ReadFromSymbolizer(char *buffer, uptr max_length) override {
273     if (!SymbolizerProcess::ReadFromSymbolizer(buffer, max_length))
274       return false;
275     // The returned buffer is empty when output is valid, but exceeds
276     // max_length.
277     if (*buffer == '\0')
278       return true;
279     // We should cut out output_terminator_ at the end of given buffer,
280     // appended by addr2line to mark the end of its meaningful output.
281     // We cannot scan buffer from it's beginning, because it is legal for it
282     // to start with output_terminator_ in case given offset is invalid. So,
283     // scanning from second character.
284     char *garbage = internal_strstr(buffer + 1, output_terminator_);
285     // This should never be NULL since buffer must end up with
286     // output_terminator_.
287     CHECK(garbage);
288     // Trim the buffer.
289     garbage[0] = '\0';
290     return true;
291   }
292
293   const char *module_name_;  // Owned, leaked.
294   static const char output_terminator_[];
295 };
296
297 const char Addr2LineProcess::output_terminator_[] = "??\n??:0\n";
298
299 bool Addr2LineProcess::ReachedEndOfOutput(const char *buffer,
300                                           uptr length) const {
301   const size_t kTerminatorLen = sizeof(output_terminator_) - 1;
302   // Skip, if we read just kTerminatorLen bytes, because Addr2Line output
303   // should consist at least of two pairs of lines:
304   // 1. First one, corresponding to given offset to be symbolized
305   // (may be equal to output_terminator_, if offset is not valid).
306   // 2. Second one for output_terminator_, itself to mark the end of output.
307   if (length <= kTerminatorLen) return false;
308   // Addr2Line output should end up with output_terminator_.
309   return !internal_memcmp(buffer + length - kTerminatorLen,
310                           output_terminator_, kTerminatorLen);
311 }
312
313 class Addr2LinePool : public SymbolizerTool {
314  public:
315   explicit Addr2LinePool(const char *addr2line_path,
316                          LowLevelAllocator *allocator)
317       : addr2line_path_(addr2line_path), allocator_(allocator) {
318     addr2line_pool_.reserve(16);
319   }
320
321   bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
322     if (const char *buf =
323             SendCommand(stack->info.module, stack->info.module_offset)) {
324       ParseSymbolizePCOutput(buf, stack);
325       return true;
326     }
327     return false;
328   }
329
330   bool SymbolizeData(uptr addr, DataInfo *info) override {
331     return false;
332   }
333
334  private:
335   const char *SendCommand(const char *module_name, uptr module_offset) {
336     Addr2LineProcess *addr2line = 0;
337     for (uptr i = 0; i < addr2line_pool_.size(); ++i) {
338       if (0 ==
339           internal_strcmp(module_name, addr2line_pool_[i]->module_name())) {
340         addr2line = addr2line_pool_[i];
341         break;
342       }
343     }
344     if (!addr2line) {
345       addr2line =
346           new(*allocator_) Addr2LineProcess(addr2line_path_, module_name);
347       addr2line_pool_.push_back(addr2line);
348     }
349     CHECK_EQ(0, internal_strcmp(module_name, addr2line->module_name()));
350     char buffer[kBufferSize];
351     internal_snprintf(buffer, kBufferSize, "0x%zx\n0x%zx\n",
352                       module_offset, dummy_address_);
353     return addr2line->SendCommand(buffer);
354   }
355
356   static const uptr kBufferSize = 64;
357   const char *addr2line_path_;
358   LowLevelAllocator *allocator_;
359   InternalMmapVector<Addr2LineProcess*> addr2line_pool_;
360   static const uptr dummy_address_ =
361       FIRST_32_SECOND_64(UINT32_MAX, UINT64_MAX);
362 };
363
364 #if SANITIZER_SUPPORTS_WEAK_HOOKS
365 extern "C" {
366 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
367 bool __sanitizer_symbolize_code(const char *ModuleName, u64 ModuleOffset,
368                                 char *Buffer, int MaxLength);
369 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
370 bool __sanitizer_symbolize_data(const char *ModuleName, u64 ModuleOffset,
371                                 char *Buffer, int MaxLength);
372 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
373 void __sanitizer_symbolize_flush();
374 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
375 int __sanitizer_symbolize_demangle(const char *Name, char *Buffer,
376                                    int MaxLength);
377 }  // extern "C"
378
379 class InternalSymbolizer : public SymbolizerTool {
380  public:
381   static InternalSymbolizer *get(LowLevelAllocator *alloc) {
382     if (__sanitizer_symbolize_code != 0 &&
383         __sanitizer_symbolize_data != 0) {
384       return new(*alloc) InternalSymbolizer();
385     }
386     return 0;
387   }
388
389   bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
390     bool result = __sanitizer_symbolize_code(
391         stack->info.module, stack->info.module_offset, buffer_, kBufferSize);
392     if (result) ParseSymbolizePCOutput(buffer_, stack);
393     return result;
394   }
395
396   bool SymbolizeData(uptr addr, DataInfo *info) override {
397     bool result = __sanitizer_symbolize_data(info->module, info->module_offset,
398                                              buffer_, kBufferSize);
399     if (result) {
400       ParseSymbolizeDataOutput(buffer_, info);
401       info->start += (addr - info->module_offset);  // Add the base address.
402     }
403     return result;
404   }
405
406   void Flush() override {
407     if (__sanitizer_symbolize_flush)
408       __sanitizer_symbolize_flush();
409   }
410
411   const char *Demangle(const char *name) override {
412     if (__sanitizer_symbolize_demangle) {
413       for (uptr res_length = 1024;
414            res_length <= InternalSizeClassMap::kMaxSize;) {
415         char *res_buff = static_cast<char*>(InternalAlloc(res_length));
416         uptr req_length =
417             __sanitizer_symbolize_demangle(name, res_buff, res_length);
418         if (req_length > res_length) {
419           res_length = req_length + 1;
420           InternalFree(res_buff);
421           continue;
422         }
423         return res_buff;
424       }
425     }
426     return name;
427   }
428
429  private:
430   InternalSymbolizer() { }
431
432   static const int kBufferSize = 16 * 1024;
433   char buffer_[kBufferSize];
434 };
435 #else  // SANITIZER_SUPPORTS_WEAK_HOOKS
436
437 class InternalSymbolizer : public SymbolizerTool {
438  public:
439   static InternalSymbolizer *get(LowLevelAllocator *alloc) { return 0; }
440 };
441
442 #endif  // SANITIZER_SUPPORTS_WEAK_HOOKS
443
444 const char *Symbolizer::PlatformDemangle(const char *name) {
445   return DemangleSwiftAndCXX(name);
446 }
447
448 static SymbolizerTool *ChooseExternalSymbolizer(LowLevelAllocator *allocator) {
449   const char *path = common_flags()->external_symbolizer_path;
450   const char *binary_name = path ? StripModuleName(path) : "";
451   if (path && path[0] == '\0') {
452     VReport(2, "External symbolizer is explicitly disabled.\n");
453     return nullptr;
454   } else if (!internal_strcmp(binary_name, "llvm-symbolizer")) {
455     VReport(2, "Using llvm-symbolizer at user-specified path: %s\n", path);
456     return new(*allocator) LLVMSymbolizer(path, allocator);
457   } else if (!internal_strcmp(binary_name, "atos")) {
458 #if SANITIZER_MAC
459     VReport(2, "Using atos at user-specified path: %s\n", path);
460     return new(*allocator) AtosSymbolizer(path, allocator);
461 #else  // SANITIZER_MAC
462     Report("ERROR: Using `atos` is only supported on Darwin.\n");
463     Die();
464 #endif  // SANITIZER_MAC
465   } else if (!internal_strcmp(binary_name, "addr2line")) {
466     VReport(2, "Using addr2line at user-specified path: %s\n", path);
467     return new(*allocator) Addr2LinePool(path, allocator);
468   } else if (path) {
469     Report("ERROR: External symbolizer path is set to '%s' which isn't "
470            "a known symbolizer. Please set the path to the llvm-symbolizer "
471            "binary or other known tool.\n", path);
472     Die();
473   }
474
475   // Otherwise symbolizer program is unknown, let's search $PATH
476   CHECK(path == nullptr);
477 #if SANITIZER_MAC
478   if (const char *found_path = FindPathToBinary("atos")) {
479     VReport(2, "Using atos found at: %s\n", found_path);
480     return new(*allocator) AtosSymbolizer(found_path, allocator);
481   }
482 #endif  // SANITIZER_MAC
483   if (const char *found_path = FindPathToBinary("llvm-symbolizer")) {
484     VReport(2, "Using llvm-symbolizer found at: %s\n", found_path);
485     return new(*allocator) LLVMSymbolizer(found_path, allocator);
486   }
487   if (common_flags()->allow_addr2line) {
488     if (const char *found_path = FindPathToBinary("addr2line")) {
489       VReport(2, "Using addr2line found at: %s\n", found_path);
490       return new(*allocator) Addr2LinePool(found_path, allocator);
491     }
492   }
493   return nullptr;
494 }
495
496 static void ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> *list,
497                                   LowLevelAllocator *allocator) {
498   if (!common_flags()->symbolize) {
499     VReport(2, "Symbolizer is disabled.\n");
500     return;
501   }
502   if (IsAllocatorOutOfMemory()) {
503     VReport(2, "Cannot use internal symbolizer: out of memory\n");
504   } else if (SymbolizerTool *tool = InternalSymbolizer::get(allocator)) {
505     VReport(2, "Using internal symbolizer.\n");
506     list->push_back(tool);
507     return;
508   }
509   if (SymbolizerTool *tool = LibbacktraceSymbolizer::get(allocator)) {
510     VReport(2, "Using libbacktrace symbolizer.\n");
511     list->push_back(tool);
512     return;
513   }
514
515   if (SymbolizerTool *tool = ChooseExternalSymbolizer(allocator)) {
516     list->push_back(tool);
517   }
518
519 #if SANITIZER_MAC
520   VReport(2, "Using dladdr symbolizer.\n");
521   list->push_back(new(*allocator) DlAddrSymbolizer());
522 #endif  // SANITIZER_MAC
523 }
524
525 Symbolizer *Symbolizer::PlatformInit() {
526   IntrusiveList<SymbolizerTool> list;
527   list.clear();
528   ChooseSymbolizerTools(&list, &symbolizer_allocator_);
529   return new(symbolizer_allocator_) Symbolizer(list);
530 }
531
532 void Symbolizer::LateInitialize() {
533   Symbolizer::GetOrInit();
534   InitializeSwiftDemangler();
535 }
536
537 }  // namespace __sanitizer
538
539 #endif  // SANITIZER_POSIX