1 //===-- sanitizer_symbolizer_posix_libcdep.cc -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries.
12 // POSIX-specific implementation of symbolizer parts.
13 //===----------------------------------------------------------------------===//
15 #include "sanitizer_platform.h"
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_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"
29 #include <dlfcn.h> // for dlsym()
37 #include <util.h> // for forkpty()
38 #endif // SANITIZER_MAC
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);
49 namespace __sanitizer {
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;
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
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;
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
77 static void InitializeSwiftDemangler() {
78 swift_demangle_f = (swift_demangle_ft)dlsym(RTLD_DEFAULT, "swift_demangle");
81 // Attempts to demangle a Swift name. The demangler will return nullptr if a
82 // non-Swift name is passed in.
83 const char *DemangleSwift(const char *name) {
84 if (!name) return nullptr;
86 // Check if we are dealing with a Swift mangled name first.
87 if (name[0] != '_' || name[1] != 'T') {
92 return swift_demangle_f(name, internal_strlen(name), 0, 0, 0);
97 const char *DemangleSwiftAndCXX(const char *name) {
98 if (!name) return nullptr;
99 if (const char *swift_demangled_name = DemangleSwift(name))
100 return swift_demangled_name;
101 return DemangleCXXABI(name);
104 static bool CreateTwoHighNumberedPipes(int *infd_, int *outfd_) {
107 // The client program may close its stdin and/or stdout and/or stderr
108 // thus allowing socketpair to reuse file descriptors 0, 1 or 2.
109 // In this case the communication between the forked processes may be
110 // broken if either the parent or the child tries to close or duplicate
111 // these descriptors. The loop below produces two pairs of file
112 // descriptors, each greater than 2 (stderr).
114 for (int i = 0; i < 5; i++) {
115 if (pipe(sock_pair[i]) == -1) {
116 for (int j = 0; j < i; j++) {
117 internal_close(sock_pair[j][0]);
118 internal_close(sock_pair[j][1]);
121 } else if (sock_pair[i][0] > 2 && sock_pair[i][1] > 2) {
125 outfd = sock_pair[i];
126 for (int j = 0; j < i; j++) {
127 if (sock_pair[j] == infd) continue;
128 internal_close(sock_pair[j][0]);
129 internal_close(sock_pair[j][1]);
139 outfd_[0] = outfd[0];
140 outfd_[1] = outfd[1];
144 bool SymbolizerProcess::StartSymbolizerSubprocess() {
145 if (!FileExists(path_)) {
146 if (!reported_invalid_path_) {
147 Report("WARNING: invalid path to external symbolizer!\n");
148 reported_invalid_path_ = true;
156 internal_memset(&infd, 0, sizeof(infd));
158 internal_memset(&outfd, 0, sizeof(outfd));
159 if (!CreateTwoHighNumberedPipes(infd, outfd)) {
160 Report("WARNING: Can't create a socket pair to start "
161 "external symbolizer (errno: %d)\n", errno);
167 fd_t fd = kInvalidFd;
169 // forkpty redirects stdout and stderr into a single stream, so we would
170 // receive error messages as standard replies. To avoid that, let's dup
171 // stderr and restore it in the child.
172 int saved_stderr = dup(STDERR_FILENO);
173 CHECK_GE(saved_stderr, 0);
175 // We only need one pipe, for stdin of the child.
179 // Use forkpty to disable buffering in the new terminal.
180 pid = internal_forkpty(&fd);
183 Report("WARNING: failed to fork external symbolizer (errno: %d)\n",
186 } else if (pid == 0) {
189 // infd[0] is the child's reading end.
192 // Set up stdin to read from the pipe.
193 CHECK_GE(dup2(infd[0], STDIN_FILENO), 0);
197 CHECK_GE(dup2(saved_stderr, STDERR_FILENO), 0);
200 const char *argv[kArgVMax];
201 GetArgV(path_, argv);
202 execv(path_, const_cast<char **>(&argv[0]));
206 // Input for the child, infd[1] is our writing end.
207 output_fd_ = infd[1];
210 // Continue execution in parent process.
215 // Disable echo in the new terminal, disable CR.
216 struct termios termflags;
217 tcgetattr(fd, &termflags);
218 termflags.c_oflag &= ~ONLCR;
219 termflags.c_lflag &= ~ECHO;
220 tcsetattr(fd, TCSANOW, &termflags);
221 #else // SANITIZER_MAC
223 #endif // SANITIZER_MAC
225 const char *argv[kArgVMax];
226 GetArgV(path_, argv);
227 pid = StartSubprocess(path_, argv, /* stdin */ outfd[0],
228 /* stdout */ infd[1]);
230 internal_close(infd[0]);
231 internal_close(outfd[1]);
236 output_fd_ = outfd[1];
241 // Check that symbolizer subprocess started successfully.
242 SleepForMillis(kSymbolizerStartupTimeMillis);
243 if (!IsProcessRunning(pid)) {
244 // Either waitpid failed, or child has already exited.
245 Report("WARNING: external symbolizer didn't start up correctly!\n");
252 class Addr2LineProcess : public SymbolizerProcess {
254 Addr2LineProcess(const char *path, const char *module_name)
255 : SymbolizerProcess(path), module_name_(internal_strdup(module_name)) {}
257 const char *module_name() const { return module_name_; }
260 void GetArgV(const char *path_to_binary,
261 const char *(&argv)[kArgVMax]) const override {
263 argv[i++] = path_to_binary;
265 argv[i++] = module_name_;
269 bool ReachedEndOfOutput(const char *buffer, uptr length) const override;
271 bool ReadFromSymbolizer(char *buffer, uptr max_length) override {
272 if (!SymbolizerProcess::ReadFromSymbolizer(buffer, max_length))
274 // We should cut out output_terminator_ at the end of given buffer,
275 // appended by addr2line to mark the end of its meaningful output.
276 // We cannot scan buffer from it's beginning, because it is legal for it
277 // to start with output_terminator_ in case given offset is invalid. So,
278 // scanning from second character.
279 char *garbage = internal_strstr(buffer + 1, output_terminator_);
280 // This should never be NULL since buffer must end up with
281 // output_terminator_.
288 const char *module_name_; // Owned, leaked.
289 static const char output_terminator_[];
292 const char Addr2LineProcess::output_terminator_[] = "??\n??:0\n";
294 bool Addr2LineProcess::ReachedEndOfOutput(const char *buffer,
296 const size_t kTerminatorLen = sizeof(output_terminator_) - 1;
297 // Skip, if we read just kTerminatorLen bytes, because Addr2Line output
298 // should consist at least of two pairs of lines:
299 // 1. First one, corresponding to given offset to be symbolized
300 // (may be equal to output_terminator_, if offset is not valid).
301 // 2. Second one for output_terminator_, itself to mark the end of output.
302 if (length <= kTerminatorLen) return false;
303 // Addr2Line output should end up with output_terminator_.
304 return !internal_memcmp(buffer + length - kTerminatorLen,
305 output_terminator_, kTerminatorLen);
308 class Addr2LinePool : public SymbolizerTool {
310 explicit Addr2LinePool(const char *addr2line_path,
311 LowLevelAllocator *allocator)
312 : addr2line_path_(addr2line_path), allocator_(allocator),
313 addr2line_pool_(16) {}
315 bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
316 if (const char *buf =
317 SendCommand(stack->info.module, stack->info.module_offset)) {
318 ParseSymbolizePCOutput(buf, stack);
324 bool SymbolizeData(uptr addr, DataInfo *info) override {
329 const char *SendCommand(const char *module_name, uptr module_offset) {
330 Addr2LineProcess *addr2line = 0;
331 for (uptr i = 0; i < addr2line_pool_.size(); ++i) {
333 internal_strcmp(module_name, addr2line_pool_[i]->module_name())) {
334 addr2line = addr2line_pool_[i];
340 new(*allocator_) Addr2LineProcess(addr2line_path_, module_name);
341 addr2line_pool_.push_back(addr2line);
343 CHECK_EQ(0, internal_strcmp(module_name, addr2line->module_name()));
344 char buffer[kBufferSize];
345 internal_snprintf(buffer, kBufferSize, "0x%zx\n0x%zx\n",
346 module_offset, dummy_address_);
347 return addr2line->SendCommand(buffer);
350 static const uptr kBufferSize = 64;
351 const char *addr2line_path_;
352 LowLevelAllocator *allocator_;
353 InternalMmapVector<Addr2LineProcess*> addr2line_pool_;
354 static const uptr dummy_address_ =
355 FIRST_32_SECOND_64(UINT32_MAX, UINT64_MAX);
358 #if SANITIZER_SUPPORTS_WEAK_HOOKS
360 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
361 bool __sanitizer_symbolize_code(const char *ModuleName, u64 ModuleOffset,
362 char *Buffer, int MaxLength);
363 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
364 bool __sanitizer_symbolize_data(const char *ModuleName, u64 ModuleOffset,
365 char *Buffer, int MaxLength);
366 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
367 void __sanitizer_symbolize_flush();
368 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
369 int __sanitizer_symbolize_demangle(const char *Name, char *Buffer,
373 class InternalSymbolizer : public SymbolizerTool {
375 static InternalSymbolizer *get(LowLevelAllocator *alloc) {
376 if (__sanitizer_symbolize_code != 0 &&
377 __sanitizer_symbolize_data != 0) {
378 return new(*alloc) InternalSymbolizer();
383 bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
384 bool result = __sanitizer_symbolize_code(
385 stack->info.module, stack->info.module_offset, buffer_, kBufferSize);
386 if (result) ParseSymbolizePCOutput(buffer_, stack);
390 bool SymbolizeData(uptr addr, DataInfo *info) override {
391 bool result = __sanitizer_symbolize_data(info->module, info->module_offset,
392 buffer_, kBufferSize);
394 ParseSymbolizeDataOutput(buffer_, info);
395 info->start += (addr - info->module_offset); // Add the base address.
400 void Flush() override {
401 if (__sanitizer_symbolize_flush)
402 __sanitizer_symbolize_flush();
405 const char *Demangle(const char *name) override {
406 if (__sanitizer_symbolize_demangle) {
407 for (uptr res_length = 1024;
408 res_length <= InternalSizeClassMap::kMaxSize;) {
409 char *res_buff = static_cast<char*>(InternalAlloc(res_length));
411 __sanitizer_symbolize_demangle(name, res_buff, res_length);
412 if (req_length > res_length) {
413 res_length = req_length + 1;
414 InternalFree(res_buff);
424 InternalSymbolizer() { }
426 static const int kBufferSize = 16 * 1024;
427 static const int kMaxDemangledNameSize = 1024;
428 char buffer_[kBufferSize];
430 #else // SANITIZER_SUPPORTS_WEAK_HOOKS
432 class InternalSymbolizer : public SymbolizerTool {
434 static InternalSymbolizer *get(LowLevelAllocator *alloc) { return 0; }
437 #endif // SANITIZER_SUPPORTS_WEAK_HOOKS
439 const char *Symbolizer::PlatformDemangle(const char *name) {
440 return DemangleSwiftAndCXX(name);
443 void Symbolizer::PlatformPrepareForSandboxing() {}
445 static SymbolizerTool *ChooseExternalSymbolizer(LowLevelAllocator *allocator) {
446 const char *path = common_flags()->external_symbolizer_path;
447 const char *binary_name = path ? StripModuleName(path) : "";
448 if (path && path[0] == '\0') {
449 VReport(2, "External symbolizer is explicitly disabled.\n");
451 } else if (!internal_strcmp(binary_name, "llvm-symbolizer")) {
452 VReport(2, "Using llvm-symbolizer at user-specified path: %s\n", path);
453 return new(*allocator) LLVMSymbolizer(path, allocator);
454 } else if (!internal_strcmp(binary_name, "atos")) {
456 VReport(2, "Using atos at user-specified path: %s\n", path);
457 return new(*allocator) AtosSymbolizer(path, allocator);
458 #else // SANITIZER_MAC
459 Report("ERROR: Using `atos` is only supported on Darwin.\n");
461 #endif // SANITIZER_MAC
462 } else if (!internal_strcmp(binary_name, "addr2line")) {
463 VReport(2, "Using addr2line at user-specified path: %s\n", path);
464 return new(*allocator) Addr2LinePool(path, allocator);
466 Report("ERROR: External symbolizer path is set to '%s' which isn't "
467 "a known symbolizer. Please set the path to the llvm-symbolizer "
468 "binary or other known tool.\n", path);
472 // Otherwise symbolizer program is unknown, let's search $PATH
473 CHECK(path == nullptr);
474 if (const char *found_path = FindPathToBinary("llvm-symbolizer")) {
475 VReport(2, "Using llvm-symbolizer found at: %s\n", found_path);
476 return new(*allocator) LLVMSymbolizer(found_path, allocator);
479 if (const char *found_path = FindPathToBinary("atos")) {
480 VReport(2, "Using atos found at: %s\n", found_path);
481 return new(*allocator) AtosSymbolizer(found_path, allocator);
483 #endif // SANITIZER_MAC
484 if (common_flags()->allow_addr2line) {
485 if (const char *found_path = FindPathToBinary("addr2line")) {
486 VReport(2, "Using addr2line found at: %s\n", found_path);
487 return new(*allocator) Addr2LinePool(found_path, allocator);
493 static void ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> *list,
494 LowLevelAllocator *allocator) {
495 if (!common_flags()->symbolize) {
496 VReport(2, "Symbolizer is disabled.\n");
499 if (IsReportingOOM()) {
500 VReport(2, "Cannot use internal symbolizer: out of memory\n");
501 } else if (SymbolizerTool *tool = InternalSymbolizer::get(allocator)) {
502 VReport(2, "Using internal symbolizer.\n");
503 list->push_back(tool);
506 if (SymbolizerTool *tool = LibbacktraceSymbolizer::get(allocator)) {
507 VReport(2, "Using libbacktrace symbolizer.\n");
508 list->push_back(tool);
512 if (SymbolizerTool *tool = ChooseExternalSymbolizer(allocator)) {
513 list->push_back(tool);
517 VReport(2, "Using dladdr symbolizer.\n");
518 list->push_back(new(*allocator) DlAddrSymbolizer());
519 #endif // SANITIZER_MAC
522 Symbolizer *Symbolizer::PlatformInit() {
523 IntrusiveList<SymbolizerTool> list;
525 ChooseSymbolizerTools(&list, &symbolizer_allocator_);
526 return new(symbolizer_allocator_) Symbolizer(list);
529 void Symbolizer::LateInitialize() {
530 Symbolizer::GetOrInit();
531 InitializeSwiftDemangler();
534 } // namespace __sanitizer
536 #endif // SANITIZER_POSIX