1 //===-- sanitizer_symbolizer_libcdep.cc -----------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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_symbolizer_internal.h"
17 namespace __sanitizer {
19 Symbolizer *Symbolizer::GetOrInit() {
20 SpinMutexLock l(&init_mu_);
23 symbolizer_ = PlatformInit();
28 // See sanitizer_symbolizer_markup.cc.
29 #if !SANITIZER_SYMBOLIZER_MARKUP
31 const char *ExtractToken(const char *str, const char *delims, char **result) {
32 uptr prefix_len = internal_strcspn(str, delims);
33 *result = (char*)InternalAlloc(prefix_len + 1);
34 internal_memcpy(*result, str, prefix_len);
35 (*result)[prefix_len] = '\0';
36 const char *prefix_end = str + prefix_len;
37 if (*prefix_end != '\0') prefix_end++;
41 const char *ExtractInt(const char *str, const char *delims, int *result) {
43 const char *ret = ExtractToken(str, delims, &buff);
45 *result = (int)internal_atoll(buff);
51 const char *ExtractUptr(const char *str, const char *delims, uptr *result) {
53 const char *ret = ExtractToken(str, delims, &buff);
55 *result = (uptr)internal_atoll(buff);
61 const char *ExtractSptr(const char *str, const char *delims, sptr *result) {
63 const char *ret = ExtractToken(str, delims, &buff);
65 *result = (sptr)internal_atoll(buff);
71 const char *ExtractTokenUpToDelimiter(const char *str, const char *delimiter,
73 const char *found_delimiter = internal_strstr(str, delimiter);
75 found_delimiter ? found_delimiter - str : internal_strlen(str);
76 *result = (char *)InternalAlloc(prefix_len + 1);
77 internal_memcpy(*result, str, prefix_len);
78 (*result)[prefix_len] = '\0';
79 const char *prefix_end = str + prefix_len;
80 if (*prefix_end != '\0') prefix_end += internal_strlen(delimiter);
84 SymbolizedStack *Symbolizer::SymbolizePC(uptr addr) {
85 BlockingMutexLock l(&mu_);
86 const char *module_name;
89 SymbolizedStack *res = SymbolizedStack::New(addr);
90 if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
93 // Always fill data about module name and offset.
94 res->info.FillModuleInfo(module_name, module_offset, arch);
95 for (auto &tool : tools_) {
96 SymbolizerScope sym_scope(this);
97 if (tool.SymbolizePC(addr, res)) {
104 bool Symbolizer::SymbolizeData(uptr addr, DataInfo *info) {
105 BlockingMutexLock l(&mu_);
106 const char *module_name;
109 if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
113 info->module = internal_strdup(module_name);
114 info->module_offset = module_offset;
115 info->module_arch = arch;
116 for (auto &tool : tools_) {
117 SymbolizerScope sym_scope(this);
118 if (tool.SymbolizeData(addr, info)) {
125 bool Symbolizer::SymbolizeFrame(uptr addr, FrameInfo *info) {
126 BlockingMutexLock l(&mu_);
127 const char *module_name;
128 if (!FindModuleNameAndOffsetForAddress(
129 addr, &module_name, &info->module_offset, &info->module_arch))
131 info->module = internal_strdup(module_name);
132 for (auto &tool : tools_) {
133 SymbolizerScope sym_scope(this);
134 if (tool.SymbolizeFrame(addr, info)) {
141 bool Symbolizer::GetModuleNameAndOffsetForPC(uptr pc, const char **module_name,
142 uptr *module_address) {
143 BlockingMutexLock l(&mu_);
144 const char *internal_module_name = nullptr;
146 if (!FindModuleNameAndOffsetForAddress(pc, &internal_module_name,
147 module_address, &arch))
151 *module_name = module_names_.GetOwnedCopy(internal_module_name);
155 void Symbolizer::Flush() {
156 BlockingMutexLock l(&mu_);
157 for (auto &tool : tools_) {
158 SymbolizerScope sym_scope(this);
163 const char *Symbolizer::Demangle(const char *name) {
164 BlockingMutexLock l(&mu_);
165 for (auto &tool : tools_) {
166 SymbolizerScope sym_scope(this);
167 if (const char *demangled = tool.Demangle(name))
170 return PlatformDemangle(name);
173 bool Symbolizer::FindModuleNameAndOffsetForAddress(uptr address,
174 const char **module_name,
176 ModuleArch *module_arch) {
177 const LoadedModule *module = FindModuleForAddress(address);
178 if (module == nullptr)
180 *module_name = module->full_name();
181 *module_offset = address - module->base_address();
182 *module_arch = module->arch();
186 void Symbolizer::RefreshModules() {
188 fallback_modules_.fallbackInit();
189 RAW_CHECK(modules_.size() > 0);
190 modules_fresh_ = true;
193 static const LoadedModule *SearchForModule(const ListOfModules &modules,
195 for (uptr i = 0; i < modules.size(); i++) {
196 if (modules[i].containsAddress(address)) {
203 const LoadedModule *Symbolizer::FindModuleForAddress(uptr address) {
204 bool modules_were_reloaded = false;
205 if (!modules_fresh_) {
207 modules_were_reloaded = true;
209 const LoadedModule *module = SearchForModule(modules_, address);
210 if (module) return module;
212 // dlopen/dlclose interceptors invalidate the module list, but when
213 // interception is disabled, we need to retry if the lookup fails in
214 // case the module list changed.
215 #if !SANITIZER_INTERCEPT_DLOPEN_DLCLOSE
216 if (!modules_were_reloaded) {
218 module = SearchForModule(modules_, address);
219 if (module) return module;
223 if (fallback_modules_.size()) {
224 module = SearchForModule(fallback_modules_, address);
229 // For now we assume the following protocol:
230 // For each request of the form
231 // <module_name> <module_offset>
232 // passed to STDIN, external symbolizer prints to STDOUT response:
234 // <file_name>:<line_number>:<column_number>
236 // <file_name>:<line_number>:<column_number>
239 class LLVMSymbolizerProcess : public SymbolizerProcess {
241 explicit LLVMSymbolizerProcess(const char *path) : SymbolizerProcess(path) {}
244 bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
245 // Empty line marks the end of llvm-symbolizer output.
246 return length >= 2 && buffer[length - 1] == '\n' &&
247 buffer[length - 2] == '\n';
250 // When adding a new architecture, don't forget to also update
251 // script/asan_symbolize.py and sanitizer_common.h.
252 void GetArgV(const char *path_to_binary,
253 const char *(&argv)[kArgVMax]) const override {
254 #if defined(__x86_64h__)
255 const char* const kSymbolizerArch = "--default-arch=x86_64h";
256 #elif defined(__x86_64__)
257 const char* const kSymbolizerArch = "--default-arch=x86_64";
258 #elif defined(__i386__)
259 const char* const kSymbolizerArch = "--default-arch=i386";
260 #elif defined(__aarch64__)
261 const char* const kSymbolizerArch = "--default-arch=arm64";
262 #elif defined(__arm__)
263 const char* const kSymbolizerArch = "--default-arch=arm";
264 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
265 const char* const kSymbolizerArch = "--default-arch=powerpc64";
266 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
267 const char* const kSymbolizerArch = "--default-arch=powerpc64le";
268 #elif defined(__s390x__)
269 const char* const kSymbolizerArch = "--default-arch=s390x";
270 #elif defined(__s390__)
271 const char* const kSymbolizerArch = "--default-arch=s390";
273 const char* const kSymbolizerArch = "--default-arch=unknown";
276 const char *const inline_flag = common_flags()->symbolize_inline_frames
278 : "--inlining=false";
280 argv[i++] = path_to_binary;
281 argv[i++] = inline_flag;
282 argv[i++] = kSymbolizerArch;
287 LLVMSymbolizer::LLVMSymbolizer(const char *path, LowLevelAllocator *allocator)
288 : symbolizer_process_(new(*allocator) LLVMSymbolizerProcess(path)) {}
290 // Parse a <file>:<line>[:<column>] buffer. The file path may contain colons on
291 // Windows, so extract tokens from the right hand side first. The column info is
293 static const char *ParseFileLineInfo(AddressInfo *info, const char *str) {
294 char *file_line_info = 0;
295 str = ExtractToken(str, "\n", &file_line_info);
296 CHECK(file_line_info);
298 if (uptr size = internal_strlen(file_line_info)) {
299 char *back = file_line_info + size - 1;
300 for (int i = 0; i < 2; ++i) {
301 while (back > file_line_info && IsDigit(*back)) --back;
302 if (*back != ':' || !IsDigit(back[1])) break;
303 info->column = info->line;
304 info->line = internal_atoll(back + 1);
305 // Truncate the string at the colon to keep only filename.
309 ExtractToken(file_line_info, "", &info->file);
312 InternalFree(file_line_info);
316 // Parses one or more two-line strings in the following format:
318 // <file_name>:<line_number>[:<column_number>]
319 // Used by LLVMSymbolizer, Addr2LinePool and InternalSymbolizer, since all of
320 // them use the same output format.
321 void ParseSymbolizePCOutput(const char *str, SymbolizedStack *res) {
322 bool top_frame = true;
323 SymbolizedStack *last = res;
325 char *function_name = 0;
326 str = ExtractToken(str, "\n", &function_name);
327 CHECK(function_name);
328 if (function_name[0] == '\0') {
329 // There are no more frames.
330 InternalFree(function_name);
333 SymbolizedStack *cur;
338 cur = SymbolizedStack::New(res->info.address);
339 cur->info.FillModuleInfo(res->info.module, res->info.module_offset,
340 res->info.module_arch);
345 AddressInfo *info = &cur->info;
346 info->function = function_name;
347 str = ParseFileLineInfo(info, str);
349 // Functions and filenames can be "??", in which case we write 0
350 // to address info to mark that names are unknown.
351 if (0 == internal_strcmp(info->function, "??")) {
352 InternalFree(info->function);
355 if (0 == internal_strcmp(info->file, "??")) {
356 InternalFree(info->file);
362 // Parses a two-line string in the following format:
364 // <start_address> <size>
365 // Used by LLVMSymbolizer and InternalSymbolizer.
366 void ParseSymbolizeDataOutput(const char *str, DataInfo *info) {
367 str = ExtractToken(str, "\n", &info->name);
368 str = ExtractUptr(str, " ", &info->start);
369 str = ExtractUptr(str, "\n", &info->size);
372 static void ParseSymbolizeFrameOutput(const char *str,
373 InternalMmapVector<LocalInfo> *locals) {
374 if (internal_strncmp(str, "??", 2) == 0)
379 str = ExtractToken(str, "\n", &local.function_name);
380 str = ExtractToken(str, "\n", &local.name);
383 str = ParseFileLineInfo(&addr, str);
384 local.decl_file = addr.file;
385 local.decl_line = addr.line;
387 local.has_frame_offset = internal_strncmp(str, "??", 2) != 0;
388 str = ExtractSptr(str, " ", &local.frame_offset);
390 local.has_size = internal_strncmp(str, "??", 2) != 0;
391 str = ExtractUptr(str, " ", &local.size);
393 local.has_tag_offset = internal_strncmp(str, "??", 2) != 0;
394 str = ExtractUptr(str, "\n", &local.tag_offset);
396 locals->push_back(local);
400 bool LLVMSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {
401 AddressInfo *info = &stack->info;
402 const char *buf = FormatAndSendCommand(
403 "CODE", info->module, info->module_offset, info->module_arch);
405 ParseSymbolizePCOutput(buf, stack);
411 bool LLVMSymbolizer::SymbolizeData(uptr addr, DataInfo *info) {
412 const char *buf = FormatAndSendCommand(
413 "DATA", info->module, info->module_offset, info->module_arch);
415 ParseSymbolizeDataOutput(buf, info);
416 info->start += (addr - info->module_offset); // Add the base address.
422 bool LLVMSymbolizer::SymbolizeFrame(uptr addr, FrameInfo *info) {
423 const char *buf = FormatAndSendCommand(
424 "FRAME", info->module, info->module_offset, info->module_arch);
426 ParseSymbolizeFrameOutput(buf, &info->locals);
432 const char *LLVMSymbolizer::FormatAndSendCommand(const char *command_prefix,
433 const char *module_name,
437 if (arch == kModuleArchUnknown) {
438 if (internal_snprintf(buffer_, kBufferSize, "%s \"%s\" 0x%zx\n",
439 command_prefix, module_name,
440 module_offset) >= static_cast<int>(kBufferSize)) {
441 Report("WARNING: Command buffer too small");
445 if (internal_snprintf(buffer_, kBufferSize, "%s \"%s:%s\" 0x%zx\n",
446 command_prefix, module_name, ModuleArchToString(arch),
447 module_offset) >= static_cast<int>(kBufferSize)) {
448 Report("WARNING: Command buffer too small");
452 return symbolizer_process_->SendCommand(buffer_);
455 SymbolizerProcess::SymbolizerProcess(const char *path, bool use_forkpty)
457 input_fd_(kInvalidFd),
458 output_fd_(kInvalidFd),
460 failed_to_start_(false),
461 reported_invalid_path_(false),
462 use_forkpty_(use_forkpty) {
464 CHECK_NE(path_[0], '\0');
467 static bool IsSameModule(const char* path) {
468 if (const char* ProcessName = GetProcessName()) {
469 if (const char* SymbolizerName = StripModuleName(path)) {
470 return !internal_strcmp(ProcessName, SymbolizerName);
476 const char *SymbolizerProcess::SendCommand(const char *command) {
477 if (failed_to_start_)
479 if (IsSameModule(path_)) {
480 Report("WARNING: Symbolizer was blocked from starting itself!\n");
481 failed_to_start_ = true;
484 for (; times_restarted_ < kMaxTimesRestarted; times_restarted_++) {
485 // Start or restart symbolizer if we failed to send command to it.
486 if (const char *res = SendCommandImpl(command))
490 if (!failed_to_start_) {
491 Report("WARNING: Failed to use and restart external symbolizer!\n");
492 failed_to_start_ = true;
497 const char *SymbolizerProcess::SendCommandImpl(const char *command) {
498 if (input_fd_ == kInvalidFd || output_fd_ == kInvalidFd)
500 if (!WriteToSymbolizer(command, internal_strlen(command)))
502 if (!ReadFromSymbolizer(buffer_, kBufferSize))
507 bool SymbolizerProcess::Restart() {
508 if (input_fd_ != kInvalidFd)
509 CloseFile(input_fd_);
510 if (output_fd_ != kInvalidFd)
511 CloseFile(output_fd_);
512 return StartSymbolizerSubprocess();
515 bool SymbolizerProcess::ReadFromSymbolizer(char *buffer, uptr max_length) {
521 bool success = ReadFromFile(input_fd_, buffer + read_len,
522 max_length - read_len - 1, &just_read);
523 // We can't read 0 bytes, as we don't expect external symbolizer to close
525 if (!success || just_read == 0) {
526 Report("WARNING: Can't read from symbolizer at fd %d\n", input_fd_);
529 read_len += just_read;
530 if (ReachedEndOfOutput(buffer, read_len))
532 if (read_len + 1 == max_length) {
533 Report("WARNING: Symbolizer buffer too small\n");
538 buffer[read_len] = '\0';
542 bool SymbolizerProcess::WriteToSymbolizer(const char *buffer, uptr length) {
546 bool success = WriteToFile(output_fd_, buffer, length, &write_len);
547 if (!success || write_len != length) {
548 Report("WARNING: Can't write to symbolizer at fd %d\n", output_fd_);
554 #endif // !SANITIZER_SYMBOLIZER_MARKUP
556 } // namespace __sanitizer