sanitizer_symbolizer_libcdep.cpp 17 KB

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