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