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. const char *module_name = nullptr;
  78. uptr module_offset;
  79. ModuleArch arch;
  80. SymbolizedStack *res = SymbolizedStack::New(addr);
  81. if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
  82. &arch))
  83. return res;
  84. // Always fill data about module name and offset.
  85. res->info.FillModuleInfo(module_name, module_offset, arch);
  86. for (auto &tool : tools_) {
  87. SymbolizerScope sym_scope(this);
  88. if (tool.SymbolizePC(addr, res)) {
  89. return res;
  90. }
  91. }
  92. return res;
  93. }
  94. bool Symbolizer::SymbolizeData(uptr addr, DataInfo *info) {
  95. Lock l(&mu_);
  96. const char *module_name = nullptr;
  97. uptr module_offset;
  98. ModuleArch arch;
  99. if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
  100. &arch))
  101. return false;
  102. info->Clear();
  103. info->module = internal_strdup(module_name);
  104. info->module_offset = module_offset;
  105. info->module_arch = arch;
  106. for (auto &tool : tools_) {
  107. SymbolizerScope sym_scope(this);
  108. if (tool.SymbolizeData(addr, info)) {
  109. return true;
  110. }
  111. }
  112. return true;
  113. }
  114. bool Symbolizer::SymbolizeFrame(uptr addr, FrameInfo *info) {
  115. Lock l(&mu_);
  116. const char *module_name = nullptr;
  117. if (!FindModuleNameAndOffsetForAddress(
  118. addr, &module_name, &info->module_offset, &info->module_arch))
  119. return false;
  120. info->module = internal_strdup(module_name);
  121. for (auto &tool : tools_) {
  122. SymbolizerScope sym_scope(this);
  123. if (tool.SymbolizeFrame(addr, info)) {
  124. return true;
  125. }
  126. }
  127. return true;
  128. }
  129. bool Symbolizer::GetModuleNameAndOffsetForPC(uptr pc, const char **module_name,
  130. uptr *module_address) {
  131. Lock l(&mu_);
  132. const char *internal_module_name = nullptr;
  133. ModuleArch arch;
  134. if (!FindModuleNameAndOffsetForAddress(pc, &internal_module_name,
  135. module_address, &arch))
  136. return false;
  137. if (module_name)
  138. *module_name = module_names_.GetOwnedCopy(internal_module_name);
  139. return true;
  140. }
  141. void Symbolizer::Flush() {
  142. Lock l(&mu_);
  143. for (auto &tool : tools_) {
  144. SymbolizerScope sym_scope(this);
  145. tool.Flush();
  146. }
  147. }
  148. const char *Symbolizer::Demangle(const char *name) {
  149. Lock l(&mu_);
  150. for (auto &tool : tools_) {
  151. SymbolizerScope sym_scope(this);
  152. if (const char *demangled = tool.Demangle(name))
  153. return demangled;
  154. }
  155. return PlatformDemangle(name);
  156. }
  157. bool Symbolizer::FindModuleNameAndOffsetForAddress(uptr address,
  158. const char **module_name,
  159. uptr *module_offset,
  160. ModuleArch *module_arch) {
  161. const LoadedModule *module = FindModuleForAddress(address);
  162. if (!module)
  163. return false;
  164. *module_name = module->full_name();
  165. *module_offset = address - module->base_address();
  166. *module_arch = module->arch();
  167. return true;
  168. }
  169. void Symbolizer::RefreshModules() {
  170. modules_.init();
  171. fallback_modules_.fallbackInit();
  172. RAW_CHECK(modules_.size() > 0);
  173. modules_fresh_ = true;
  174. }
  175. static const LoadedModule *SearchForModule(const ListOfModules &modules,
  176. uptr address) {
  177. for (uptr i = 0; i < modules.size(); i++) {
  178. if (modules[i].containsAddress(address)) {
  179. return &modules[i];
  180. }
  181. }
  182. return nullptr;
  183. }
  184. const LoadedModule *Symbolizer::FindModuleForAddress(uptr address) {
  185. bool modules_were_reloaded = false;
  186. if (!modules_fresh_) {
  187. RefreshModules();
  188. modules_were_reloaded = true;
  189. }
  190. const LoadedModule *module = SearchForModule(modules_, address);
  191. if (module) return module;
  192. // dlopen/dlclose interceptors invalidate the module list, but when
  193. // interception is disabled, we need to retry if the lookup fails in
  194. // case the module list changed.
  195. #if !SANITIZER_INTERCEPT_DLOPEN_DLCLOSE
  196. if (!modules_were_reloaded) {
  197. RefreshModules();
  198. module = SearchForModule(modules_, address);
  199. if (module) return module;
  200. }
  201. #endif
  202. if (fallback_modules_.size()) {
  203. module = SearchForModule(fallback_modules_, address);
  204. }
  205. return module;
  206. }
  207. // For now we assume the following protocol:
  208. // For each request of the form
  209. // <module_name> <module_offset>
  210. // passed to STDIN, external symbolizer prints to STDOUT response:
  211. // <function_name>
  212. // <file_name>:<line_number>:<column_number>
  213. // <function_name>
  214. // <file_name>:<line_number>:<column_number>
  215. // ...
  216. // <empty line>
  217. class LLVMSymbolizerProcess final : public SymbolizerProcess {
  218. public:
  219. explicit LLVMSymbolizerProcess(const char *path)
  220. : SymbolizerProcess(path, /*use_posix_spawn=*/SANITIZER_MAC) {}
  221. private:
  222. bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
  223. // Empty line marks the end of llvm-symbolizer output.
  224. return length >= 2 && buffer[length - 1] == '\n' &&
  225. buffer[length - 2] == '\n';
  226. }
  227. // When adding a new architecture, don't forget to also update
  228. // script/asan_symbolize.py and sanitizer_common.h.
  229. void GetArgV(const char *path_to_binary,
  230. const char *(&argv)[kArgVMax]) const override {
  231. #if defined(__x86_64h__)
  232. const char* const kSymbolizerArch = "--default-arch=x86_64h";
  233. #elif defined(__x86_64__)
  234. const char* const kSymbolizerArch = "--default-arch=x86_64";
  235. #elif defined(__i386__)
  236. const char* const kSymbolizerArch = "--default-arch=i386";
  237. #elif SANITIZER_RISCV64
  238. const char *const kSymbolizerArch = "--default-arch=riscv64";
  239. #elif defined(__aarch64__)
  240. const char* const kSymbolizerArch = "--default-arch=arm64";
  241. #elif defined(__arm__)
  242. const char* const kSymbolizerArch = "--default-arch=arm";
  243. #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
  244. const char* const kSymbolizerArch = "--default-arch=powerpc64";
  245. #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  246. const char* const kSymbolizerArch = "--default-arch=powerpc64le";
  247. #elif defined(__s390x__)
  248. const char* const kSymbolizerArch = "--default-arch=s390x";
  249. #elif defined(__s390__)
  250. const char* const kSymbolizerArch = "--default-arch=s390";
  251. #else
  252. const char* const kSymbolizerArch = "--default-arch=unknown";
  253. #endif
  254. const char *const inline_flag = common_flags()->symbolize_inline_frames
  255. ? "--inlines"
  256. : "--no-inlines";
  257. int i = 0;
  258. argv[i++] = path_to_binary;
  259. argv[i++] = inline_flag;
  260. argv[i++] = kSymbolizerArch;
  261. argv[i++] = nullptr;
  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