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