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 const char *ExtractToken(const char *str, const char *delims, char **result) {
21 uptr prefix_len = internal_strcspn(str, delims);
22 *result = (char*)InternalAlloc(prefix_len + 1);
23 internal_memcpy(*result, str, prefix_len);
24 (*result)[prefix_len] = '\0';
25 const char *prefix_end = str + prefix_len;
26 if (*prefix_end != '\0') prefix_end++;
30 const char *ExtractInt(const char *str, const char *delims, int *result) {
32 const char *ret = ExtractToken(str, delims, &buff);
34 *result = (int)internal_atoll(buff);
40 const char *ExtractUptr(const char *str, const char *delims, uptr *result) {
42 const char *ret = ExtractToken(str, delims, &buff);
44 *result = (uptr)internal_atoll(buff);
50 const char *ExtractTokenUpToDelimiter(const char *str, const char *delimiter,
52 const char *found_delimiter = internal_strstr(str, delimiter);
54 found_delimiter ? found_delimiter - str : internal_strlen(str);
55 *result = (char *)InternalAlloc(prefix_len + 1);
56 internal_memcpy(*result, str, prefix_len);
57 (*result)[prefix_len] = '\0';
58 const char *prefix_end = str + prefix_len;
59 if (*prefix_end != '\0') prefix_end += internal_strlen(delimiter);
63 SymbolizedStack *Symbolizer::SymbolizePC(uptr addr) {
64 BlockingMutexLock l(&mu_);
65 const char *module_name;
68 SymbolizedStack *res = SymbolizedStack::New(addr);
69 if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
72 // Always fill data about module name and offset.
73 res->info.FillModuleInfo(module_name, module_offset, arch);
74 for (auto &tool : tools_) {
75 SymbolizerScope sym_scope(this);
76 if (tool.SymbolizePC(addr, res)) {
83 bool Symbolizer::SymbolizeData(uptr addr, DataInfo *info) {
84 BlockingMutexLock l(&mu_);
85 const char *module_name;
88 if (!FindModuleNameAndOffsetForAddress(addr, &module_name, &module_offset,
92 info->module = internal_strdup(module_name);
93 info->module_offset = module_offset;
94 info->module_arch = arch;
95 for (auto &tool : tools_) {
96 SymbolizerScope sym_scope(this);
97 if (tool.SymbolizeData(addr, info)) {
104 bool Symbolizer::GetModuleNameAndOffsetForPC(uptr pc, const char **module_name,
105 uptr *module_address) {
106 BlockingMutexLock l(&mu_);
107 const char *internal_module_name = nullptr;
109 if (!FindModuleNameAndOffsetForAddress(pc, &internal_module_name,
110 module_address, &arch))
114 *module_name = module_names_.GetOwnedCopy(internal_module_name);
118 void Symbolizer::Flush() {
119 BlockingMutexLock l(&mu_);
120 for (auto &tool : tools_) {
121 SymbolizerScope sym_scope(this);
126 const char *Symbolizer::Demangle(const char *name) {
127 BlockingMutexLock l(&mu_);
128 for (auto &tool : tools_) {
129 SymbolizerScope sym_scope(this);
130 if (const char *demangled = tool.Demangle(name))
133 return PlatformDemangle(name);
136 void Symbolizer::PrepareForSandboxing() {
137 BlockingMutexLock l(&mu_);
138 PlatformPrepareForSandboxing();
141 bool Symbolizer::FindModuleNameAndOffsetForAddress(uptr address,
142 const char **module_name,
144 ModuleArch *module_arch) {
145 const LoadedModule *module = FindModuleForAddress(address);
146 if (module == nullptr)
148 *module_name = module->full_name();
149 *module_offset = address - module->base_address();
150 *module_arch = module->arch();
154 const LoadedModule *Symbolizer::FindModuleForAddress(uptr address) {
155 bool modules_were_reloaded = false;
156 if (!modules_fresh_) {
158 RAW_CHECK(modules_.size() > 0);
159 modules_fresh_ = true;
160 modules_were_reloaded = true;
162 for (uptr i = 0; i < modules_.size(); i++) {
163 if (modules_[i].containsAddress(address)) {
167 // Reload the modules and look up again, if we haven't tried it yet.
168 if (!modules_were_reloaded) {
169 // FIXME: set modules_fresh_ from dlopen()/dlclose() interceptors.
170 // It's too aggressive to reload the list of modules each time we fail
171 // to find a module for a given address.
172 modules_fresh_ = false;
173 return FindModuleForAddress(address);
178 Symbolizer *Symbolizer::GetOrInit() {
179 SpinMutexLock l(&init_mu_);
182 symbolizer_ = PlatformInit();
187 // For now we assume the following protocol:
188 // For each request of the form
189 // <module_name> <module_offset>
190 // passed to STDIN, external symbolizer prints to STDOUT response:
192 // <file_name>:<line_number>:<column_number>
194 // <file_name>:<line_number>:<column_number>
197 class LLVMSymbolizerProcess : public SymbolizerProcess {
199 explicit LLVMSymbolizerProcess(const char *path) : SymbolizerProcess(path) {}
202 bool ReachedEndOfOutput(const char *buffer, uptr length) const override {
203 // Empty line marks the end of llvm-symbolizer output.
204 return length >= 2 && buffer[length - 1] == '\n' &&
205 buffer[length - 2] == '\n';
208 // When adding a new architecture, don't forget to also update
209 // script/asan_symbolize.py and sanitizer_common.h.
210 void GetArgV(const char *path_to_binary,
211 const char *(&argv)[kArgVMax]) const override {
212 #if defined(__x86_64h__)
213 const char* const kSymbolizerArch = "--default-arch=x86_64h";
214 #elif defined(__x86_64__)
215 const char* const kSymbolizerArch = "--default-arch=x86_64";
216 #elif defined(__i386__)
217 const char* const kSymbolizerArch = "--default-arch=i386";
218 #elif defined(__aarch64__)
219 const char* const kSymbolizerArch = "--default-arch=arm64";
220 #elif defined(__arm__)
221 const char* const kSymbolizerArch = "--default-arch=arm";
222 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
223 const char* const kSymbolizerArch = "--default-arch=powerpc64";
224 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
225 const char* const kSymbolizerArch = "--default-arch=powerpc64le";
226 #elif defined(__s390x__)
227 const char* const kSymbolizerArch = "--default-arch=s390x";
228 #elif defined(__s390__)
229 const char* const kSymbolizerArch = "--default-arch=s390";
231 const char* const kSymbolizerArch = "--default-arch=unknown";
234 const char *const inline_flag = common_flags()->symbolize_inline_frames
236 : "--inlining=false";
238 argv[i++] = path_to_binary;
239 argv[i++] = inline_flag;
240 argv[i++] = kSymbolizerArch;
245 LLVMSymbolizer::LLVMSymbolizer(const char *path, LowLevelAllocator *allocator)
246 : symbolizer_process_(new(*allocator) LLVMSymbolizerProcess(path)) {}
248 // Parse a <file>:<line>[:<column>] buffer. The file path may contain colons on
249 // Windows, so extract tokens from the right hand side first. The column info is
251 static const char *ParseFileLineInfo(AddressInfo *info, const char *str) {
252 char *file_line_info = 0;
253 str = ExtractToken(str, "\n", &file_line_info);
254 CHECK(file_line_info);
256 if (uptr size = internal_strlen(file_line_info)) {
257 char *back = file_line_info + size - 1;
258 for (int i = 0; i < 2; ++i) {
259 while (back > file_line_info && IsDigit(*back)) --back;
260 if (*back != ':' || !IsDigit(back[1])) break;
261 info->column = info->line;
262 info->line = internal_atoll(back + 1);
263 // Truncate the string at the colon to keep only filename.
267 ExtractToken(file_line_info, "", &info->file);
270 InternalFree(file_line_info);
274 // Parses one or more two-line strings in the following format:
276 // <file_name>:<line_number>[:<column_number>]
277 // Used by LLVMSymbolizer, Addr2LinePool and InternalSymbolizer, since all of
278 // them use the same output format.
279 void ParseSymbolizePCOutput(const char *str, SymbolizedStack *res) {
280 bool top_frame = true;
281 SymbolizedStack *last = res;
283 char *function_name = 0;
284 str = ExtractToken(str, "\n", &function_name);
285 CHECK(function_name);
286 if (function_name[0] == '\0') {
287 // There are no more frames.
288 InternalFree(function_name);
291 SymbolizedStack *cur;
296 cur = SymbolizedStack::New(res->info.address);
297 cur->info.FillModuleInfo(res->info.module, res->info.module_offset,
298 res->info.module_arch);
303 AddressInfo *info = &cur->info;
304 info->function = function_name;
305 str = ParseFileLineInfo(info, str);
307 // Functions and filenames can be "??", in which case we write 0
308 // to address info to mark that names are unknown.
309 if (0 == internal_strcmp(info->function, "??")) {
310 InternalFree(info->function);
313 if (0 == internal_strcmp(info->file, "??")) {
314 InternalFree(info->file);
320 // Parses a two-line string in the following format:
322 // <start_address> <size>
323 // Used by LLVMSymbolizer and InternalSymbolizer.
324 void ParseSymbolizeDataOutput(const char *str, DataInfo *info) {
325 str = ExtractToken(str, "\n", &info->name);
326 str = ExtractUptr(str, " ", &info->start);
327 str = ExtractUptr(str, "\n", &info->size);
330 bool LLVMSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) {
331 AddressInfo *info = &stack->info;
332 const char *buf = FormatAndSendCommand(
333 /*is_data*/ false, info->module, info->module_offset, info->module_arch);
335 ParseSymbolizePCOutput(buf, stack);
341 bool LLVMSymbolizer::SymbolizeData(uptr addr, DataInfo *info) {
342 const char *buf = FormatAndSendCommand(
343 /*is_data*/ true, info->module, info->module_offset, info->module_arch);
345 ParseSymbolizeDataOutput(buf, info);
346 info->start += (addr - info->module_offset); // Add the base address.
352 const char *LLVMSymbolizer::FormatAndSendCommand(bool is_data,
353 const char *module_name,
357 const char *is_data_str = is_data ? "DATA " : "";
358 if (arch == kModuleArchUnknown) {
359 if (internal_snprintf(buffer_, kBufferSize, "%s\"%s\" 0x%zx\n", is_data_str,
361 module_offset) >= static_cast<int>(kBufferSize)) {
362 Report("WARNING: Command buffer too small");
366 if (internal_snprintf(buffer_, kBufferSize, "%s\"%s:%s\" 0x%zx\n",
367 is_data_str, module_name, ModuleArchToString(arch),
368 module_offset) >= static_cast<int>(kBufferSize)) {
369 Report("WARNING: Command buffer too small");
373 return symbolizer_process_->SendCommand(buffer_);
376 SymbolizerProcess::SymbolizerProcess(const char *path, bool use_forkpty)
378 input_fd_(kInvalidFd),
379 output_fd_(kInvalidFd),
381 failed_to_start_(false),
382 reported_invalid_path_(false),
383 use_forkpty_(use_forkpty) {
385 CHECK_NE(path_[0], '\0');
388 static bool IsSameModule(const char* path) {
389 if (const char* ProcessName = GetProcessName()) {
390 if (const char* SymbolizerName = StripModuleName(path)) {
391 return !internal_strcmp(ProcessName, SymbolizerName);
397 const char *SymbolizerProcess::SendCommand(const char *command) {
398 if (failed_to_start_)
400 if (IsSameModule(path_)) {
401 Report("WARNING: Symbolizer was blocked from starting itself!\n");
402 failed_to_start_ = true;
405 for (; times_restarted_ < kMaxTimesRestarted; times_restarted_++) {
406 // Start or restart symbolizer if we failed to send command to it.
407 if (const char *res = SendCommandImpl(command))
411 if (!failed_to_start_) {
412 Report("WARNING: Failed to use and restart external symbolizer!\n");
413 failed_to_start_ = true;
418 const char *SymbolizerProcess::SendCommandImpl(const char *command) {
419 if (input_fd_ == kInvalidFd || output_fd_ == kInvalidFd)
421 if (!WriteToSymbolizer(command, internal_strlen(command)))
423 if (!ReadFromSymbolizer(buffer_, kBufferSize))
428 bool SymbolizerProcess::Restart() {
429 if (input_fd_ != kInvalidFd)
430 CloseFile(input_fd_);
431 if (output_fd_ != kInvalidFd)
432 CloseFile(output_fd_);
433 return StartSymbolizerSubprocess();
436 bool SymbolizerProcess::ReadFromSymbolizer(char *buffer, uptr max_length) {
442 bool success = ReadFromFile(input_fd_, buffer + read_len,
443 max_length - read_len - 1, &just_read);
444 // We can't read 0 bytes, as we don't expect external symbolizer to close
446 if (!success || just_read == 0) {
447 Report("WARNING: Can't read from symbolizer at fd %d\n", input_fd_);
450 read_len += just_read;
451 if (ReachedEndOfOutput(buffer, read_len))
453 if (read_len + 1 == max_length) {
454 Report("WARNING: Symbolizer buffer too small");
459 buffer[read_len] = '\0';
463 bool SymbolizerProcess::WriteToSymbolizer(const char *buffer, uptr length) {
467 bool success = WriteToFile(output_fd_, buffer, length, &write_len);
468 if (!success || write_len != length) {
469 Report("WARNING: Can't write to symbolizer at fd %d\n", output_fd_);
475 } // namespace __sanitizer