1 //===-- sanitizer_symbolizer_libcdep.cc -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file is shared between AddressSanitizer and ThreadSanitizer
11 // run-time libraries.
12 //===----------------------------------------------------------------------===//
14 #include "sanitizer_allocator_internal.h"
15 #include "sanitizer_internal_defs.h"
16 #include "sanitizer_symbolizer_internal.h"
18 namespace __sanitizer {
20 Symbolizer *Symbolizer::GetOrInit() {
21 SpinMutexLock l(&init_mu_);
24 symbolizer_ = PlatformInit();
29 // See sanitizer_symbolizer_fuchsia.cc.
30 #if !SANITIZER_FUCHSIA
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++;
42 const char *ExtractInt(const char *str, const char *delims, int *result) {
44 const char *ret = ExtractToken(str, delims, &buff);
46 *result = (int)internal_atoll(buff);
52 const char *ExtractUptr(const char *str, const char *delims, uptr *result) {
54 const char *ret = ExtractToken(str, delims, &buff);
56 *result = (uptr)internal_atoll(buff);
62 const char *ExtractTokenUpToDelimiter(const char *str, const char *delimiter,
64 const char *found_delimiter = internal_strstr(str, delimiter);
66 found_delimiter ? found_delimiter - str : internal_strlen(str);
67 *result = (char *)InternalAlloc(prefix_len + 1);
68 internal_memcpy(*result, str, prefix_len);
69 (*result)[prefix_len] = '\0';
70 const char *prefix_end = str + prefix_len;
71 if (*prefix_end != '\0') prefix_end += internal_strlen(delimiter);
75 SymbolizedStack *Symbolizer::SymbolizePC(uptr addr) {
76 BlockingMutexLock l(&mu_);
77 const char *module_name;
80 SymbolizedStack *res = SymbolizedStack::New(addr);
81 if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
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)) {
95 bool Symbolizer::SymbolizeData(uptr addr, DataInfo *info) {
96 BlockingMutexLock l(&mu_);
97 const char *module_name;
100 if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
104 info->module = internal_strdup(module_name);
105 info->module_offset = module_offset;
106 info->module_arch = arch;
107 for (auto &tool : tools_) {
108 SymbolizerScope sym_scope(this);
109 if (tool.SymbolizeData(addr, info)) {
116 bool Symbolizer::GetModuleNameAndOffsetForPC(uptr pc, const char **module_name,
117 uptr *module_address) {
118 BlockingMutexLock l(&mu_);
119 const char *internal_module_name = nullptr;
121 if (!FindModuleNameAndOffsetForAddress(pc, &internal_module_name,
122 module_address, &arch))
126 *module_name = module_names_.GetOwnedCopy(internal_module_name);
130 void Symbolizer::Flush() {
131 BlockingMutexLock l(&mu_);
132 for (auto &tool : tools_) {
133 SymbolizerScope sym_scope(this);
138 const char *Symbolizer::Demangle(const char *name) {
139 BlockingMutexLock l(&mu_);
140 for (auto &tool : tools_) {
141 SymbolizerScope sym_scope(this);
142 if (const char *demangled = tool.Demangle(name))
145 return PlatformDemangle(name);
148 void Symbolizer::PrepareForSandboxing() {
149 BlockingMutexLock l(&mu_);
150 PlatformPrepareForSandboxing();
153 bool Symbolizer::FindModuleNameAndOffsetForAddress(uptr address,
154 const char **module_name,
156 ModuleArch *module_arch) {
157 const LoadedModule *module = FindModuleForAddress(address);
158 if (module == nullptr)
160 *module_name = module->full_name();
161 *module_offset = address - module->base_address();
162 *module_arch = module->arch();
166 void Symbolizer::RefreshModules() {
168 fallback_modules_.fallbackInit();
169 RAW_CHECK(modules_.size() > 0);
170 modules_fresh_ = true;
173 static const LoadedModule *SearchForModule(const ListOfModules &modules,
175 for (uptr i = 0; i < modules.size(); i++) {
176 if (modules[i].containsAddress(address)) {
183 const LoadedModule *Symbolizer::FindModuleForAddress(uptr address) {
184 bool modules_were_reloaded = false;
185 if (!modules_fresh_) {
187 modules_were_reloaded = true;
189 const LoadedModule *module = SearchForModule(modules_, address);
190 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) {
198 module = SearchForModule(modules_, address);
199 if (module) return module;
203 if (fallback_modules_.size()) {
204 module = SearchForModule(fallback_modules_, address);
209 // For now we assume the following protocol:
210 // For each request of the form
211 // <module_name> <module_offset>
212 // passed to STDIN, external symbolizer prints to STDOUT response:
214 // <file_name>:<line_number>:<column_number>
216 // <file_name>:<line_number>:<column_number>
219 class LLVMSymbolizerProcess : public SymbolizerProcess {
221 explicit LLVMSymbolizerProcess(const char *path) : SymbolizerProcess(path) {}
224 bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
225 // Empty line marks the end of llvm-symbolizer output.
226 return length >= 2 && buffer[length - 1] == '\n' &&
227 buffer[length - 2] == '\n';
230 // When adding a new architecture, don't forget to also update
231 // script/asan_symbolize.py and sanitizer_common.h.
232 void GetArgV(const char *path_to_binary,
233 const char *(&argv)[kArgVMax]) const override {
234 #if defined(__x86_64h__)
235 const char* const kSymbolizerArch = "--default-arch=x86_64h";
236 #elif defined(__x86_64__)
237 const char* const kSymbolizerArch = "--default-arch=x86_64";
238 #elif defined(__i386__)
239 const char* const kSymbolizerArch = "--default-arch=i386";
240 #elif defined(__aarch64__)
241 const char* const kSymbolizerArch = "--default-arch=arm64";
242 #elif defined(__arm__)
243 const char* const kSymbolizerArch = "--default-arch=arm";
244 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
245 const char* const kSymbolizerArch = "--default-arch=powerpc64";
246 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
247 const char* const kSymbolizerArch = "--default-arch=powerpc64le";
248 #elif defined(__s390x__)
249 const char* const kSymbolizerArch = "--default-arch=s390x";
250 #elif defined(__s390__)
251 const char* const kSymbolizerArch = "--default-arch=s390";
253 const char* const kSymbolizerArch = "--default-arch=unknown";
256 const char *const inline_flag = common_flags()->symbolize_inline_frames
258 : "--inlining=false";
260 argv[i++] = path_to_binary;
261 argv[i++] = inline_flag;
262 argv[i++] = kSymbolizerArch;
267 LLVMSymbolizer::LLVMSymbolizer(const char *path, LowLevelAllocator *allocator)
268 : symbolizer_process_(new(*allocator) LLVMSymbolizerProcess(path)) {}
270 // Parse a <file>:<line>[:<column>] buffer. The file path may contain colons on
271 // Windows, so extract tokens from the right hand side first. The column info is
273 static const char *ParseFileLineInfo(AddressInfo *info, const char *str) {
274 char *file_line_info = 0;
275 str = ExtractToken(str, "\n", &file_line_info);
276 CHECK(file_line_info);
278 if (uptr size = internal_strlen(file_line_info)) {
279 char *back = file_line_info + size - 1;
280 for (int i = 0; i < 2; ++i) {
281 while (back > file_line_info && IsDigit(*back)) --back;
282 if (*back != ':' || !IsDigit(back[1])) break;
283 info->column = info->line;
284 info->line = internal_atoll(back + 1);
285 // Truncate the string at the colon to keep only filename.
289 ExtractToken(file_line_info, "", &info->file);
292 InternalFree(file_line_info);
296 // Parses one or more two-line strings in the following format:
298 // <file_name>:<line_number>[:<column_number>]
299 // Used by LLVMSymbolizer, Addr2LinePool and InternalSymbolizer, since all of
300 // them use the same output format.
301 void ParseSymbolizePCOutput(const char *str, SymbolizedStack *res) {
302 bool top_frame = true;
303 SymbolizedStack *last = res;
305 char *function_name = 0;
306 str = ExtractToken(str, "\n", &function_name);
307 CHECK(function_name);
308 if (function_name[0] == '\0') {
309 // There are no more frames.
310 InternalFree(function_name);
313 SymbolizedStack *cur;
318 cur = SymbolizedStack::New(res->info.address);
319 cur->info.FillModuleInfo(res->info.module, res->info.module_offset,
320 res->info.module_arch);
325 AddressInfo *info = &cur->info;
326 info->function = function_name;
327 str = ParseFileLineInfo(info, str);
329 // Functions and filenames can be "??", in which case we write 0
330 // to address info to mark that names are unknown.
331 if (0 == internal_strcmp(info->function, "??")) {
332 InternalFree(info->function);
335 if (0 == internal_strcmp(info->file, "??")) {
336 InternalFree(info->file);
342 // Parses a two-line string in the following format:
344 // <start_address> <size>
345 // Used by LLVMSymbolizer and InternalSymbolizer.
346 void ParseSymbolizeDataOutput(const char *str, DataInfo *info) {
347 str = ExtractToken(str, "\n", &info->name);
348 str = ExtractUptr(str, " ", &info->start);
349 str = ExtractUptr(str, "\n", &info->size);
352 bool LLVMSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {
353 AddressInfo *info = &stack->info;
354 const char *buf = FormatAndSendCommand(
355 /*is_data*/ false, info->module, info->module_offset, info->module_arch);
357 ParseSymbolizePCOutput(buf, stack);
363 bool LLVMSymbolizer::SymbolizeData(uptr addr, DataInfo *info) {
364 const char *buf = FormatAndSendCommand(
365 /*is_data*/ true, info->module, info->module_offset, info->module_arch);
367 ParseSymbolizeDataOutput(buf, info);
368 info->start += (addr - info->module_offset); // Add the base address.
374 const char *LLVMSymbolizer::FormatAndSendCommand(bool is_data,
375 const char *module_name,
379 const char *is_data_str = is_data ? "DATA " : "";
380 if (arch == kModuleArchUnknown) {
381 if (internal_snprintf(buffer_, kBufferSize, "%s\"%s\" 0x%zx\n", is_data_str,
383 module_offset) >= static_cast<int>(kBufferSize)) {
384 Report("WARNING: Command buffer too small");
388 if (internal_snprintf(buffer_, kBufferSize, "%s\"%s:%s\" 0x%zx\n",
389 is_data_str, module_name, ModuleArchToString(arch),
390 module_offset) >= static_cast<int>(kBufferSize)) {
391 Report("WARNING: Command buffer too small");
395 return symbolizer_process_->SendCommand(buffer_);
398 SymbolizerProcess::SymbolizerProcess(const char *path, bool use_forkpty)
400 input_fd_(kInvalidFd),
401 output_fd_(kInvalidFd),
403 failed_to_start_(false),
404 reported_invalid_path_(false),
405 use_forkpty_(use_forkpty) {
407 CHECK_NE(path_[0], '\0');
410 static bool IsSameModule(const char* path) {
411 if (const char* ProcessName = GetProcessName()) {
412 if (const char* SymbolizerName = StripModuleName(path)) {
413 return !internal_strcmp(ProcessName, SymbolizerName);
419 const char *SymbolizerProcess::SendCommand(const char *command) {
420 if (failed_to_start_)
422 if (IsSameModule(path_)) {
423 Report("WARNING: Symbolizer was blocked from starting itself!\n");
424 failed_to_start_ = true;
427 for (; times_restarted_ < kMaxTimesRestarted; times_restarted_++) {
428 // Start or restart symbolizer if we failed to send command to it.
429 if (const char *res = SendCommandImpl(command))
433 if (!failed_to_start_) {
434 Report("WARNING: Failed to use and restart external symbolizer!\n");
435 failed_to_start_ = true;
440 const char *SymbolizerProcess::SendCommandImpl(const char *command) {
441 if (input_fd_ == kInvalidFd || output_fd_ == kInvalidFd)
443 if (!WriteToSymbolizer(command, internal_strlen(command)))
445 if (!ReadFromSymbolizer(buffer_, kBufferSize))
450 bool SymbolizerProcess::Restart() {
451 if (input_fd_ != kInvalidFd)
452 CloseFile(input_fd_);
453 if (output_fd_ != kInvalidFd)
454 CloseFile(output_fd_);
455 return StartSymbolizerSubprocess();
458 bool SymbolizerProcess::ReadFromSymbolizer(char *buffer, uptr max_length) {
464 bool success = ReadFromFile(input_fd_, buffer + read_len,
465 max_length - read_len - 1, &just_read);
466 // We can't read 0 bytes, as we don't expect external symbolizer to close
468 if (!success || just_read == 0) {
469 Report("WARNING: Can't read from symbolizer at fd %d\n", input_fd_);
472 read_len += just_read;
473 if (ReachedEndOfOutput(buffer, read_len))
475 if (read_len + 1 == max_length) {
476 Report("WARNING: Symbolizer buffer too small\n");
481 buffer[read_len] = '\0';
485 bool SymbolizerProcess::WriteToSymbolizer(const char *buffer, uptr length) {
489 bool success = WriteToFile(output_fd_, buffer, length, &write_len);
490 if (!success || write_len != length) {
491 Report("WARNING: Can't write to symbolizer at fd %d\n", output_fd_);
497 #endif // !SANITIZER_FUCHSIA
499 } // namespace __sanitizer