1 //===-- sanitizer_symbolizer_posix_libcdep.cc -----------------------------===//
2 //
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
5 //
6 //===----------------------------------------------------------------------===//
7 //
8 // This file is shared between AddressSanitizer and ThreadSanitizer
9 // run-time libraries.
10 // POSIX-specific implementation of symbolizer parts.
11 //===----------------------------------------------------------------------===//
12
13 #include "sanitizer_platform.h"
14 #if SANITIZER_POSIX
15 #include "sanitizer_allocator_internal.h"
16 #include "sanitizer_common.h"
17 #include "sanitizer_file.h"
18 #include "sanitizer_flags.h"
19 #include "sanitizer_internal_defs.h"
20 #include "sanitizer_linux.h"
21 #include "sanitizer_placement_new.h"
22 #include "sanitizer_posix.h"
23 #include "sanitizer_procmaps.h"
24 #include "sanitizer_symbolizer_internal.h"
25 #include "sanitizer_symbolizer_libbacktrace.h"
26 #include "sanitizer_symbolizer_mac.h"
27
28 #include <dlfcn.h> // for dlsym()
29 #include <errno.h>
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <sys/wait.h>
33 #include <unistd.h>
34
35 #if SANITIZER_MAC
36 #include <util.h> // for forkpty()
37 #endif // SANITIZER_MAC
38
39 // C++ demangling function, as required by Itanium C++ ABI. This is weak,
40 // because we do not require a C++ ABI library to be linked to a program
41 // using sanitizers; if it's not present, we'll just use the mangled name.
42 namespace __cxxabiv1 {
43 extern "C" SANITIZER_WEAK_ATTRIBUTE
44 char *__cxa_demangle(const char *mangled, char *buffer,
45 size_t *length, int *status);
46 }
47
48 namespace __sanitizer {
49
50 // Attempts to demangle the name via __cxa_demangle from __cxxabiv1.
DemangleCXXABI(const char * name)51 const char *DemangleCXXABI(const char *name) {
52 // FIXME: __cxa_demangle aggressively insists on allocating memory.
53 // There's not much we can do about that, short of providing our
54 // own demangler (libc++abi's implementation could be adapted so that
55 // it does not allocate). For now, we just call it anyway, and we leak
56 // the returned value.
57 if (&__cxxabiv1::__cxa_demangle)
58 if (const char *demangled_name =
59 __cxxabiv1::__cxa_demangle(name, 0, 0, 0))
60 return demangled_name;
61
62 return name;
63 }
64
65 // As of now, there are no headers for the Swift runtime. Once they are
66 // present, we will weakly link since we do not require Swift runtime to be
67 // linked.
68 typedef char *(*swift_demangle_ft)(const char *mangledName,
69 size_t mangledNameLength, char *outputBuffer,
70 size_t *outputBufferSize, uint32_t flags);
71 static swift_demangle_ft swift_demangle_f;
72
73 // This must not happen lazily at symbolication time, because dlsym uses
74 // malloc and thread-local storage, which is not a good thing to do during
75 // symbolication.
InitializeSwiftDemangler()76 static void InitializeSwiftDemangler() {
77 swift_demangle_f = (swift_demangle_ft)dlsym(RTLD_DEFAULT, "swift_demangle");
78 }
79
80 // Attempts to demangle a Swift name. The demangler will return nullptr if a
81 // non-Swift name is passed in.
DemangleSwift(const char * name)82 const char *DemangleSwift(const char *name) {
83 if (!name) return nullptr;
84
85 // Check if we are dealing with a Swift mangled name first.
86 if (name[0] != '_' || name[1] != 'T') {
87 return nullptr;
88 }
89
90 if (swift_demangle_f)
91 return swift_demangle_f(name, internal_strlen(name), 0, 0, 0);
92
93 return nullptr;
94 }
95
DemangleSwiftAndCXX(const char * name)96 const char *DemangleSwiftAndCXX(const char *name) {
97 if (!name) return nullptr;
98 if (const char *swift_demangled_name = DemangleSwift(name))
99 return swift_demangled_name;
100 return DemangleCXXABI(name);
101 }
102
CreateTwoHighNumberedPipes(int * infd_,int * outfd_)103 static bool CreateTwoHighNumberedPipes(int *infd_, int *outfd_) {
104 int *infd = NULL;
105 int *outfd = NULL;
106 // The client program may close its stdin and/or stdout and/or stderr
107 // thus allowing socketpair to reuse file descriptors 0, 1 or 2.
108 // In this case the communication between the forked processes may be
109 // broken if either the parent or the child tries to close or duplicate
110 // these descriptors. The loop below produces two pairs of file
111 // descriptors, each greater than 2 (stderr).
112 int sock_pair[5][2];
113 for (int i = 0; i < 5; i++) {
114 if (pipe(sock_pair[i]) == -1) {
115 for (int j = 0; j < i; j++) {
116 internal_close(sock_pair[j][0]);
117 internal_close(sock_pair[j][1]);
118 }
119 return false;
120 } else if (sock_pair[i][0] > 2 && sock_pair[i][1] > 2) {
121 if (infd == NULL) {
122 infd = sock_pair[i];
123 } else {
124 outfd = sock_pair[i];
125 for (int j = 0; j < i; j++) {
126 if (sock_pair[j] == infd) continue;
127 internal_close(sock_pair[j][0]);
128 internal_close(sock_pair[j][1]);
129 }
130 break;
131 }
132 }
133 }
134 CHECK(infd);
135 CHECK(outfd);
136 infd_[0] = infd[0];
137 infd_[1] = infd[1];
138 outfd_[0] = outfd[0];
139 outfd_[1] = outfd[1];
140 return true;
141 }
142
StartSymbolizerSubprocess()143 bool SymbolizerProcess::StartSymbolizerSubprocess() {
144 if (!FileExists(path_)) {
145 if (!reported_invalid_path_) {
146 Report("WARNING: invalid path to external symbolizer!\n");
147 reported_invalid_path_ = true;
148 }
149 return false;
150 }
151
152 int pid = -1;
153
154 int infd[2];
155 internal_memset(&infd, 0, sizeof(infd));
156 int outfd[2];
157 internal_memset(&outfd, 0, sizeof(outfd));
158 if (!CreateTwoHighNumberedPipes(infd, outfd)) {
159 Report("WARNING: Can't create a socket pair to start "
160 "external symbolizer (errno: %d)\n", errno);
161 return false;
162 }
163
164 if (use_forkpty_) {
165 #if SANITIZER_MAC
166 fd_t fd = kInvalidFd;
167
168 // forkpty redirects stdout and stderr into a single stream, so we would
169 // receive error messages as standard replies. To avoid that, let's dup
170 // stderr and restore it in the child.
171 int saved_stderr = dup(STDERR_FILENO);
172 CHECK_GE(saved_stderr, 0);
173
174 // We only need one pipe, for stdin of the child.
175 close(outfd[0]);
176 close(outfd[1]);
177
178 // Use forkpty to disable buffering in the new terminal.
179 pid = internal_forkpty(&fd);
180 if (pid == -1) {
181 // forkpty() failed.
182 Report("WARNING: failed to fork external symbolizer (errno: %d)\n",
183 errno);
184 return false;
185 } else if (pid == 0) {
186 // Child subprocess.
187
188 // infd[0] is the child's reading end.
189 close(infd[1]);
190
191 // Set up stdin to read from the pipe.
192 CHECK_GE(dup2(infd[0], STDIN_FILENO), 0);
193 close(infd[0]);
194
195 // Restore stderr.
196 CHECK_GE(dup2(saved_stderr, STDERR_FILENO), 0);
197 close(saved_stderr);
198
199 const char *argv[kArgVMax];
200 GetArgV(path_, argv);
201 execv(path_, const_cast<char **>(&argv[0]));
202 internal__exit(1);
203 }
204
205 // Input for the child, infd[1] is our writing end.
206 output_fd_ = infd[1];
207 close(infd[0]);
208
209 // Continue execution in parent process.
210 input_fd_ = fd;
211
212 close(saved_stderr);
213
214 // Disable echo in the new terminal, disable CR.
215 struct termios termflags;
216 tcgetattr(fd, &termflags);
217 termflags.c_oflag &= ~ONLCR;
218 termflags.c_lflag &= ~ECHO;
219 tcsetattr(fd, TCSANOW, &termflags);
220 #else // SANITIZER_MAC
221 UNIMPLEMENTED();
222 #endif // SANITIZER_MAC
223 } else {
224 const char *argv[kArgVMax];
225 GetArgV(path_, argv);
226 pid = StartSubprocess(path_, argv, /* stdin */ outfd[0],
227 /* stdout */ infd[1]);
228 if (pid < 0) {
229 internal_close(infd[0]);
230 internal_close(outfd[1]);
231 return false;
232 }
233
234 input_fd_ = infd[0];
235 output_fd_ = outfd[1];
236 }
237
238 CHECK_GT(pid, 0);
239
240 // Check that symbolizer subprocess started successfully.
241 SleepForMillis(kSymbolizerStartupTimeMillis);
242 if (!IsProcessRunning(pid)) {
243 // Either waitpid failed, or child has already exited.
244 Report("WARNING: external symbolizer didn't start up correctly!\n");
245 return false;
246 }
247
248 return true;
249 }
250
251 class Addr2LineProcess : public SymbolizerProcess {
252 public:
Addr2LineProcess(const char * path,const char * module_name)253 Addr2LineProcess(const char *path, const char *module_name)
254 : SymbolizerProcess(path), module_name_(internal_strdup(module_name)) {}
255
module_name() const256 const char *module_name() const { return module_name_; }
257
258 private:
GetArgV(const char * path_to_binary,const char * (& argv)[kArgVMax]) const259 void GetArgV(const char *path_to_binary,
260 const char *(&argv)[kArgVMax]) const override {
261 int i = 0;
262 argv[i++] = path_to_binary;
263 argv[i++] = "-iCfe";
264 argv[i++] = module_name_;
265 argv[i++] = nullptr;
266 }
267
268 bool ReachedEndOfOutput(const char *buffer, uptr length) const override;
269
ReadFromSymbolizer(char * buffer,uptr max_length)270 bool ReadFromSymbolizer(char *buffer, uptr max_length) override {
271 if (!SymbolizerProcess::ReadFromSymbolizer(buffer, max_length))
272 return false;
273 // The returned buffer is empty when output is valid, but exceeds
274 // max_length.
275 if (*buffer == '\0')
276 return true;
277 // We should cut out output_terminator_ at the end of given buffer,
278 // appended by addr2line to mark the end of its meaningful output.
279 // We cannot scan buffer from it's beginning, because it is legal for it
280 // to start with output_terminator_ in case given offset is invalid. So,
281 // scanning from second character.
282 char *garbage = internal_strstr(buffer + 1, output_terminator_);
283 // This should never be NULL since buffer must end up with
284 // output_terminator_.
285 CHECK(garbage);
286 // Trim the buffer.
287 garbage[0] = '\0';
288 return true;
289 }
290
291 const char *module_name_; // Owned, leaked.
292 static const char output_terminator_[];
293 };
294
295 const char Addr2LineProcess::output_terminator_[] = "??\n??:0\n";
296
ReachedEndOfOutput(const char * buffer,uptr length) const297 bool Addr2LineProcess::ReachedEndOfOutput(const char *buffer,
298 uptr length) const {
299 const size_t kTerminatorLen = sizeof(output_terminator_) - 1;
300 // Skip, if we read just kTerminatorLen bytes, because Addr2Line output
301 // should consist at least of two pairs of lines:
302 // 1. First one, corresponding to given offset to be symbolized
303 // (may be equal to output_terminator_, if offset is not valid).
304 // 2. Second one for output_terminator_, itself to mark the end of output.
305 if (length <= kTerminatorLen) return false;
306 // Addr2Line output should end up with output_terminator_.
307 return !internal_memcmp(buffer + length - kTerminatorLen,
308 output_terminator_, kTerminatorLen);
309 }
310
311 class Addr2LinePool : public SymbolizerTool {
312 public:
Addr2LinePool(const char * addr2line_path,LowLevelAllocator * allocator)313 explicit Addr2LinePool(const char *addr2line_path,
314 LowLevelAllocator *allocator)
315 : addr2line_path_(addr2line_path), allocator_(allocator),
316 addr2line_pool_(16) {}
317
SymbolizePC(uptr addr,SymbolizedStack * stack)318 bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
319 if (const char *buf =
320 SendCommand(stack->info.module, stack->info.module_offset)) {
321 ParseSymbolizePCOutput(buf, stack);
322 return true;
323 }
324 return false;
325 }
326
SymbolizeData(uptr addr,DataInfo * info)327 bool SymbolizeData(uptr addr, DataInfo *info) override {
328 return false;
329 }
330
331 private:
SendCommand(const char * module_name,uptr module_offset)332 const char *SendCommand(const char *module_name, uptr module_offset) {
333 Addr2LineProcess *addr2line = 0;
334 for (uptr i = 0; i < addr2line_pool_.size(); ++i) {
335 if (0 ==
336 internal_strcmp(module_name, addr2line_pool_[i]->module_name())) {
337 addr2line = addr2line_pool_[i];
338 break;
339 }
340 }
341 if (!addr2line) {
342 addr2line =
343 new(*allocator_) Addr2LineProcess(addr2line_path_, module_name);
344 addr2line_pool_.push_back(addr2line);
345 }
346 CHECK_EQ(0, internal_strcmp(module_name, addr2line->module_name()));
347 char buffer[kBufferSize];
348 internal_snprintf(buffer, kBufferSize, "0x%zx\n0x%zx\n",
349 module_offset, dummy_address_);
350 return addr2line->SendCommand(buffer);
351 }
352
353 static const uptr kBufferSize = 64;
354 const char *addr2line_path_;
355 LowLevelAllocator *allocator_;
356 InternalMmapVector<Addr2LineProcess*> addr2line_pool_;
357 static const uptr dummy_address_ =
358 FIRST_32_SECOND_64(UINT32_MAX, UINT64_MAX);
359 };
360
361 #if SANITIZER_SUPPORTS_WEAK_HOOKS
362 extern "C" {
363 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
364 bool __sanitizer_symbolize_code(const char *ModuleName, u64 ModuleOffset,
365 char *Buffer, int MaxLength);
366 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
367 bool __sanitizer_symbolize_data(const char *ModuleName, u64 ModuleOffset,
368 char *Buffer, int MaxLength);
369 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
370 void __sanitizer_symbolize_flush();
371 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
372 int __sanitizer_symbolize_demangle(const char *Name, char *Buffer,
373 int MaxLength);
374 } // extern "C"
375
376 class InternalSymbolizer : public SymbolizerTool {
377 public:
get(LowLevelAllocator * alloc)378 static InternalSymbolizer *get(LowLevelAllocator *alloc) {
379 if (__sanitizer_symbolize_code != 0 &&
380 __sanitizer_symbolize_data != 0) {
381 return new(*alloc) InternalSymbolizer();
382 }
383 return 0;
384 }
385
SymbolizePC(uptr addr,SymbolizedStack * stack)386 bool SymbolizePC(uptr addr, SymbolizedStack *stack) override {
387 bool result = __sanitizer_symbolize_code(
388 stack->info.module, stack->info.module_offset, buffer_, kBufferSize);
389 if (result) ParseSymbolizePCOutput(buffer_, stack);
390 return result;
391 }
392
SymbolizeData(uptr addr,DataInfo * info)393 bool SymbolizeData(uptr addr, DataInfo *info) override {
394 bool result = __sanitizer_symbolize_data(info->module, info->module_offset,
395 buffer_, kBufferSize);
396 if (result) {
397 ParseSymbolizeDataOutput(buffer_, info);
398 info->start += (addr - info->module_offset); // Add the base address.
399 }
400 return result;
401 }
402
Flush()403 void Flush() override {
404 if (__sanitizer_symbolize_flush)
405 __sanitizer_symbolize_flush();
406 }
407
Demangle(const char * name)408 const char *Demangle(const char *name) override {
409 if (__sanitizer_symbolize_demangle) {
410 for (uptr res_length = 1024;
411 res_length <= InternalSizeClassMap::kMaxSize;) {
412 char *res_buff = static_cast<char*>(InternalAlloc(res_length));
413 uptr req_length =
414 __sanitizer_symbolize_demangle(name, res_buff, res_length);
415 if (req_length > res_length) {
416 res_length = req_length + 1;
417 InternalFree(res_buff);
418 continue;
419 }
420 return res_buff;
421 }
422 }
423 return name;
424 }
425
426 private:
InternalSymbolizer()427 InternalSymbolizer() { }
428
429 static const int kBufferSize = 16 * 1024;
430 char buffer_[kBufferSize];
431 };
432 #else // SANITIZER_SUPPORTS_WEAK_HOOKS
433
434 class InternalSymbolizer : public SymbolizerTool {
435 public:
get(LowLevelAllocator * alloc)436 static InternalSymbolizer *get(LowLevelAllocator *alloc) { return 0; }
437 };
438
439 #endif // SANITIZER_SUPPORTS_WEAK_HOOKS
440
PlatformDemangle(const char * name)441 const char *Symbolizer::PlatformDemangle(const char *name) {
442 return DemangleSwiftAndCXX(name);
443 }
444
PlatformPrepareForSandboxing()445 void Symbolizer::PlatformPrepareForSandboxing() {}
446
ChooseExternalSymbolizer(LowLevelAllocator * allocator)447 static SymbolizerTool *ChooseExternalSymbolizer(LowLevelAllocator *allocator) {
448 const char *path = common_flags()->external_symbolizer_path;
449 const char *binary_name = path ? StripModuleName(path) : "";
450 if (path && path[0] == '\0') {
451 VReport(2, "External symbolizer is explicitly disabled.\n");
452 return nullptr;
453 } else if (!internal_strcmp(binary_name, "llvm-symbolizer")) {
454 VReport(2, "Using llvm-symbolizer at user-specified path: %s\n", path);
455 return new(*allocator) LLVMSymbolizer(path, allocator);
456 } else if (!internal_strcmp(binary_name, "atos")) {
457 #if SANITIZER_MAC
458 VReport(2, "Using atos at user-specified path: %s\n", path);
459 return new(*allocator) AtosSymbolizer(path, allocator);
460 #else // SANITIZER_MAC
461 Report("ERROR: Using `atos` is only supported on Darwin.\n");
462 Die();
463 #endif // SANITIZER_MAC
464 } else if (!internal_strcmp(binary_name, "addr2line")) {
465 VReport(2, "Using addr2line at user-specified path: %s\n", path);
466 return new(*allocator) Addr2LinePool(path, allocator);
467 } else if (path) {
468 Report("ERROR: External symbolizer path is set to '%s' which isn't "
469 "a known symbolizer. Please set the path to the llvm-symbolizer "
470 "binary or other known tool.\n", path);
471 Die();
472 }
473
474 // Otherwise symbolizer program is unknown, let's search $PATH
475 CHECK(path == nullptr);
476 #if SANITIZER_MAC
477 if (const char *found_path = FindPathToBinary("atos")) {
478 VReport(2, "Using atos found at: %s\n", found_path);
479 return new(*allocator) AtosSymbolizer(found_path, allocator);
480 }
481 #endif // SANITIZER_MAC
482 if (const char *found_path = FindPathToBinary("llvm-symbolizer")) {
483 VReport(2, "Using llvm-symbolizer found at: %s\n", found_path);
484 return new(*allocator) LLVMSymbolizer(found_path, allocator);
485 }
486 if (common_flags()->allow_addr2line) {
487 if (const char *found_path = FindPathToBinary("addr2line")) {
488 VReport(2, "Using addr2line found at: %s\n", found_path);
489 return new(*allocator) Addr2LinePool(found_path, allocator);
490 }
491 }
492 return nullptr;
493 }
494
ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> * list,LowLevelAllocator * allocator)495 static void ChooseSymbolizerTools(IntrusiveList<SymbolizerTool> *list,
496 LowLevelAllocator *allocator) {
497 if (!common_flags()->symbolize) {
498 VReport(2, "Symbolizer is disabled.\n");
499 return;
500 }
501 if (IsAllocatorOutOfMemory()) {
502 VReport(2, "Cannot use internal symbolizer: out of memory\n");
503 } else if (SymbolizerTool *tool = InternalSymbolizer::get(allocator)) {
504 VReport(2, "Using internal symbolizer.\n");
505 list->push_back(tool);
506 return;
507 }
508 if (SymbolizerTool *tool = LibbacktraceSymbolizer::get(allocator)) {
509 VReport(2, "Using libbacktrace symbolizer.\n");
510 list->push_back(tool);
511 return;
512 }
513
514 if (SymbolizerTool *tool = ChooseExternalSymbolizer(allocator)) {
515 list->push_back(tool);
516 }
517
518 #if SANITIZER_MAC
519 VReport(2, "Using dladdr symbolizer.\n");
520 list->push_back(new(*allocator) DlAddrSymbolizer());
521 #endif // SANITIZER_MAC
522 }
523
PlatformInit()524 Symbolizer *Symbolizer::PlatformInit() {
525 IntrusiveList<SymbolizerTool> list;
526 list.clear();
527 ChooseSymbolizerTools(&list, &symbolizer_allocator_);
528 return new(symbolizer_allocator_) Symbolizer(list);
529 }
530
LateInitialize()531 void Symbolizer::LateInitialize() {
532 Symbolizer::GetOrInit();
533 InitializeSwiftDemangler();
534 }
535
536 } // namespace __sanitizer
537
538 #endif // SANITIZER_POSIX
539