1 //===-- sanitizer_symbolizer_posix_libcdep.cc -----------------------------===//
3 // This file is distributed under the University of Illinois Open Source
4 // License. See LICENSE.TXT for details.
6 //===----------------------------------------------------------------------===//
8 // This file is shared between AddressSanitizer and ThreadSanitizer
10 // POSIX-specific implementation of symbolizer parts.
11 //===----------------------------------------------------------------------===//
13 #include "sanitizer_platform.h"
15 #include "sanitizer_allocator_internal.h"
16 #include "sanitizer_common.h"
17 #include "sanitizer_flags.h"
18 #include "sanitizer_internal_defs.h"
19 #include "sanitizer_linux.h"
20 #include "sanitizer_placement_new.h"
21 #include "sanitizer_posix.h"
22 #include "sanitizer_procmaps.h"
23 #include "sanitizer_symbolizer_internal.h"
24 #include "sanitizer_symbolizer_libbacktrace.h"
25 #include "sanitizer_symbolizer_mac.h"
27 #include <dlfcn.h> // for dlsym()
35 #include <util.h> // for forkpty()
36 #endif // SANITIZER_MAC
38 // C++ demangling function, as required by Itanium C++ ABI. This is weak,
39 // because we do not require a C++ ABI library to be linked to a program
40 // using sanitizers; if it's not present, we'll just use the mangled name.
41 namespace __cxxabiv1
{
42 extern "C" SANITIZER_WEAK_ATTRIBUTE
43 char *__cxa_demangle(const char *mangled
, char *buffer
,
44 size_t *length
, int *status
);
47 namespace __sanitizer
{
49 // Attempts to demangle the name via __cxa_demangle from __cxxabiv1.
50 const char *DemangleCXXABI(const char *name
) {
51 // FIXME: __cxa_demangle aggressively insists on allocating memory.
52 // There's not much we can do about that, short of providing our
53 // own demangler (libc++abi's implementation could be adapted so that
54 // it does not allocate). For now, we just call it anyway, and we leak
55 // the returned value.
56 if (__cxxabiv1::__cxa_demangle
)
57 if (const char *demangled_name
=
58 __cxxabiv1::__cxa_demangle(name
, 0, 0, 0))
59 return demangled_name
;
64 // As of now, there are no headers for the Swift runtime. Once they are
65 // present, we will weakly link since we do not require Swift runtime to be
67 typedef char *(*swift_demangle_ft
)(const char *mangledName
,
68 size_t mangledNameLength
, char *outputBuffer
,
69 size_t *outputBufferSize
, uint32_t flags
);
70 static swift_demangle_ft swift_demangle_f
;
72 // This must not happen lazily at symbolication time, because dlsym uses
73 // malloc and thread-local storage, which is not a good thing to do during
75 static void InitializeSwiftDemangler() {
76 swift_demangle_f
= (swift_demangle_ft
)dlsym(RTLD_DEFAULT
, "swift_demangle");
79 // Attempts to demangle a Swift name. The demangler will return nullptr if a
80 // non-Swift name is passed in.
81 const char *DemangleSwift(const char *name
) {
82 if (!name
) return nullptr;
84 // Check if we are dealing with a Swift mangled name first.
85 if (name
[0] != '_' || name
[1] != 'T') {
90 return swift_demangle_f(name
, internal_strlen(name
), 0, 0, 0);
95 const char *DemangleSwiftAndCXX(const char *name
) {
96 if (!name
) return nullptr;
97 if (const char *swift_demangled_name
= DemangleSwift(name
))
98 return swift_demangled_name
;
99 return DemangleCXXABI(name
);
102 bool SymbolizerProcess::StartSymbolizerSubprocess() {
103 if (!FileExists(path_
)) {
104 if (!reported_invalid_path_
) {
105 Report("WARNING: invalid path to external symbolizer!\n");
106 reported_invalid_path_
= true;
114 fd_t fd
= kInvalidFd
;
116 // forkpty redirects stdout and stderr into a single stream, so we would
117 // receive error messages as standard replies. To avoid that, let's dup
118 // stderr and restore it in the child.
119 int saved_stderr
= dup(STDERR_FILENO
);
120 CHECK_GE(saved_stderr
, 0);
122 // Use forkpty to disable buffering in the new terminal.
123 pid
= internal_forkpty(&fd
);
126 Report("WARNING: failed to fork external symbolizer (errno: %d)\n",
129 } else if (pid
== 0) {
133 CHECK_GE(dup2(saved_stderr
, STDERR_FILENO
), 0);
136 const char *argv
[kArgVMax
];
137 GetArgV(path_
, argv
);
138 execv(path_
, const_cast<char **>(&argv
[0]));
142 // Continue execution in parent process.
143 input_fd_
= output_fd_
= fd
;
147 // Disable echo in the new terminal, disable CR.
148 struct termios termflags
;
149 tcgetattr(fd
, &termflags
);
150 termflags
.c_oflag
&= ~ONLCR
;
151 termflags
.c_lflag
&= ~ECHO
;
152 tcsetattr(fd
, TCSANOW
, &termflags
);
153 #else // SANITIZER_MAC
155 #endif // SANITIZER_MAC
159 // The client program may close its stdin and/or stdout and/or stderr
160 // thus allowing socketpair to reuse file descriptors 0, 1 or 2.
161 // In this case the communication between the forked processes may be
162 // broken if either the parent or the child tries to close or duplicate
163 // these descriptors. The loop below produces two pairs of file
164 // descriptors, each greater than 2 (stderr).
166 for (int i
= 0; i
< 5; i
++) {
167 if (pipe(sock_pair
[i
]) == -1) {
168 for (int j
= 0; j
< i
; j
++) {
169 internal_close(sock_pair
[j
][0]);
170 internal_close(sock_pair
[j
][1]);
172 Report("WARNING: Can't create a socket pair to start "
173 "external symbolizer (errno: %d)\n", errno
);
175 } else if (sock_pair
[i
][0] > 2 && sock_pair
[i
][1] > 2) {
179 outfd
= sock_pair
[i
];
180 for (int j
= 0; j
< i
; j
++) {
181 if (sock_pair
[j
] == infd
) continue;
182 internal_close(sock_pair
[j
][0]);
183 internal_close(sock_pair
[j
][1]);
192 const char *argv
[kArgVMax
];
193 GetArgV(path_
, argv
);
194 pid
= StartSubprocess(path_
, argv
, /* stdin */ outfd
[0],
195 /* stdout */ infd
[1]);
197 internal_close(infd
[0]);
198 internal_close(outfd
[1]);
203 output_fd_
= outfd
[1];
206 // Check that symbolizer subprocess started successfully.
207 SleepForMillis(kSymbolizerStartupTimeMillis
);
208 if (!IsProcessRunning(pid
)) {
209 // Either waitpid failed, or child has already exited.
210 Report("WARNING: external symbolizer didn't start up correctly!\n");
217 class Addr2LineProcess
: public SymbolizerProcess
{
219 Addr2LineProcess(const char *path
, const char *module_name
)
220 : SymbolizerProcess(path
), module_name_(internal_strdup(module_name
)) {}
222 const char *module_name() const { return module_name_
; }
225 void GetArgV(const char *path_to_binary
,
226 const char *(&argv
)[kArgVMax
]) const override
{
228 argv
[i
++] = path_to_binary
;
230 argv
[i
++] = module_name_
;
234 bool ReachedEndOfOutput(const char *buffer
, uptr length
) const override
;
236 bool ReadFromSymbolizer(char *buffer
, uptr max_length
) override
{
237 if (!SymbolizerProcess::ReadFromSymbolizer(buffer
, max_length
))
239 // We should cut out output_terminator_ at the end of given buffer,
240 // appended by addr2line to mark the end of its meaningful output.
241 // We cannot scan buffer from it's beginning, because it is legal for it
242 // to start with output_terminator_ in case given offset is invalid. So,
243 // scanning from second character.
244 char *garbage
= internal_strstr(buffer
+ 1, output_terminator_
);
245 // This should never be NULL since buffer must end up with
246 // output_terminator_.
253 const char *module_name_
; // Owned, leaked.
254 static const char output_terminator_
[];
257 const char Addr2LineProcess::output_terminator_
[] = "??\n??:0\n";
259 bool Addr2LineProcess::ReachedEndOfOutput(const char *buffer
,
261 const size_t kTerminatorLen
= sizeof(output_terminator_
) - 1;
262 // Skip, if we read just kTerminatorLen bytes, because Addr2Line output
263 // should consist at least of two pairs of lines:
264 // 1. First one, corresponding to given offset to be symbolized
265 // (may be equal to output_terminator_, if offset is not valid).
266 // 2. Second one for output_terminator_, itself to mark the end of output.
267 if (length
<= kTerminatorLen
) return false;
268 // Addr2Line output should end up with output_terminator_.
269 return !internal_memcmp(buffer
+ length
- kTerminatorLen
,
270 output_terminator_
, kTerminatorLen
);
273 class Addr2LinePool
: public SymbolizerTool
{
275 explicit Addr2LinePool(const char *addr2line_path
,
276 LowLevelAllocator
*allocator
)
277 : addr2line_path_(addr2line_path
), allocator_(allocator
),
278 addr2line_pool_(16) {}
280 bool SymbolizePC(uptr addr
, SymbolizedStack
*stack
) override
{
281 if (const char *buf
=
282 SendCommand(stack
->info
.module
, stack
->info
.module_offset
)) {
283 ParseSymbolizePCOutput(buf
, stack
);
289 bool SymbolizeData(uptr addr
, DataInfo
*info
) override
{
294 const char *SendCommand(const char *module_name
, uptr module_offset
) {
295 Addr2LineProcess
*addr2line
= 0;
296 for (uptr i
= 0; i
< addr2line_pool_
.size(); ++i
) {
298 internal_strcmp(module_name
, addr2line_pool_
[i
]->module_name())) {
299 addr2line
= addr2line_pool_
[i
];
305 new(*allocator_
) Addr2LineProcess(addr2line_path_
, module_name
);
306 addr2line_pool_
.push_back(addr2line
);
308 CHECK_EQ(0, internal_strcmp(module_name
, addr2line
->module_name()));
309 char buffer
[kBufferSize
];
310 internal_snprintf(buffer
, kBufferSize
, "0x%zx\n0x%zx\n",
311 module_offset
, dummy_address_
);
312 return addr2line
->SendCommand(buffer
);
315 static const uptr kBufferSize
= 64;
316 const char *addr2line_path_
;
317 LowLevelAllocator
*allocator_
;
318 InternalMmapVector
<Addr2LineProcess
*> addr2line_pool_
;
319 static const uptr dummy_address_
=
320 FIRST_32_SECOND_64(UINT32_MAX
, UINT64_MAX
);
323 #if SANITIZER_SUPPORTS_WEAK_HOOKS
325 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
326 bool __sanitizer_symbolize_code(const char *ModuleName
, u64 ModuleOffset
,
327 char *Buffer
, int MaxLength
);
328 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
329 bool __sanitizer_symbolize_data(const char *ModuleName
, u64 ModuleOffset
,
330 char *Buffer
, int MaxLength
);
331 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
332 void __sanitizer_symbolize_flush();
333 SANITIZER_INTERFACE_ATTRIBUTE SANITIZER_WEAK_ATTRIBUTE
334 int __sanitizer_symbolize_demangle(const char *Name
, char *Buffer
,
338 class InternalSymbolizer
: public SymbolizerTool
{
340 static InternalSymbolizer
*get(LowLevelAllocator
*alloc
) {
341 if (__sanitizer_symbolize_code
!= 0 &&
342 __sanitizer_symbolize_data
!= 0) {
343 return new(*alloc
) InternalSymbolizer();
348 bool SymbolizePC(uptr addr
, SymbolizedStack
*stack
) override
{
349 bool result
= __sanitizer_symbolize_code(
350 stack
->info
.module
, stack
->info
.module_offset
, buffer_
, kBufferSize
);
351 if (result
) ParseSymbolizePCOutput(buffer_
, stack
);
355 bool SymbolizeData(uptr addr
, DataInfo
*info
) override
{
356 bool result
= __sanitizer_symbolize_data(info
->module
, info
->module_offset
,
357 buffer_
, kBufferSize
);
359 ParseSymbolizeDataOutput(buffer_
, info
);
360 info
->start
+= (addr
- info
->module_offset
); // Add the base address.
365 void Flush() override
{
366 if (__sanitizer_symbolize_flush
)
367 __sanitizer_symbolize_flush();
370 const char *Demangle(const char *name
) override
{
371 if (__sanitizer_symbolize_demangle
) {
372 for (uptr res_length
= 1024;
373 res_length
<= InternalSizeClassMap::kMaxSize
;) {
374 char *res_buff
= static_cast<char*>(InternalAlloc(res_length
));
376 __sanitizer_symbolize_demangle(name
, res_buff
, res_length
);
377 if (req_length
> res_length
) {
378 res_length
= req_length
+ 1;
379 InternalFree(res_buff
);
389 InternalSymbolizer() { }
391 static const int kBufferSize
= 16 * 1024;
392 static const int kMaxDemangledNameSize
= 1024;
393 char buffer_
[kBufferSize
];
395 #else // SANITIZER_SUPPORTS_WEAK_HOOKS
397 class InternalSymbolizer
: public SymbolizerTool
{
399 static InternalSymbolizer
*get(LowLevelAllocator
*alloc
) { return 0; }
402 #endif // SANITIZER_SUPPORTS_WEAK_HOOKS
404 const char *Symbolizer::PlatformDemangle(const char *name
) {
405 return DemangleSwiftAndCXX(name
);
408 void Symbolizer::PlatformPrepareForSandboxing() {}
410 static SymbolizerTool
*ChooseExternalSymbolizer(LowLevelAllocator
*allocator
) {
411 const char *path
= common_flags()->external_symbolizer_path
;
412 const char *binary_name
= path
? StripModuleName(path
) : "";
413 if (path
&& path
[0] == '\0') {
414 VReport(2, "External symbolizer is explicitly disabled.\n");
416 } else if (!internal_strcmp(binary_name
, "llvm-symbolizer")) {
417 VReport(2, "Using llvm-symbolizer at user-specified path: %s\n", path
);
418 return new(*allocator
) LLVMSymbolizer(path
, allocator
);
419 } else if (!internal_strcmp(binary_name
, "atos")) {
421 VReport(2, "Using atos at user-specified path: %s\n", path
);
422 return new(*allocator
) AtosSymbolizer(path
, allocator
);
423 #else // SANITIZER_MAC
424 Report("ERROR: Using `atos` is only supported on Darwin.\n");
426 #endif // SANITIZER_MAC
427 } else if (!internal_strcmp(binary_name
, "addr2line")) {
428 VReport(2, "Using addr2line at user-specified path: %s\n", path
);
429 return new(*allocator
) Addr2LinePool(path
, allocator
);
431 Report("ERROR: External symbolizer path is set to '%s' which isn't "
432 "a known symbolizer. Please set the path to the llvm-symbolizer "
433 "binary or other known tool.\n", path
);
437 // Otherwise symbolizer program is unknown, let's search $PATH
438 CHECK(path
== nullptr);
439 if (const char *found_path
= FindPathToBinary("llvm-symbolizer")) {
440 VReport(2, "Using llvm-symbolizer found at: %s\n", found_path
);
441 return new(*allocator
) LLVMSymbolizer(found_path
, allocator
);
444 if (const char *found_path
= FindPathToBinary("atos")) {
445 VReport(2, "Using atos found at: %s\n", found_path
);
446 return new(*allocator
) AtosSymbolizer(found_path
, allocator
);
448 #endif // SANITIZER_MAC
449 if (common_flags()->allow_addr2line
) {
450 if (const char *found_path
= FindPathToBinary("addr2line")) {
451 VReport(2, "Using addr2line found at: %s\n", found_path
);
452 return new(*allocator
) Addr2LinePool(found_path
, allocator
);
458 static void ChooseSymbolizerTools(IntrusiveList
<SymbolizerTool
> *list
,
459 LowLevelAllocator
*allocator
) {
460 if (!common_flags()->symbolize
) {
461 VReport(2, "Symbolizer is disabled.\n");
464 if (IsReportingOOM()) {
465 VReport(2, "Cannot use internal symbolizer: out of memory\n");
466 } else if (SymbolizerTool
*tool
= InternalSymbolizer::get(allocator
)) {
467 VReport(2, "Using internal symbolizer.\n");
468 list
->push_back(tool
);
471 if (SymbolizerTool
*tool
= LibbacktraceSymbolizer::get(allocator
)) {
472 VReport(2, "Using libbacktrace symbolizer.\n");
473 list
->push_back(tool
);
477 if (SymbolizerTool
*tool
= ChooseExternalSymbolizer(allocator
)) {
478 list
->push_back(tool
);
482 VReport(2, "Using dladdr symbolizer.\n");
483 list
->push_back(new(*allocator
) DlAddrSymbolizer());
484 #endif // SANITIZER_MAC
487 Symbolizer
*Symbolizer::PlatformInit() {
488 IntrusiveList
<SymbolizerTool
> list
;
490 ChooseSymbolizerTools(&list
, &symbolizer_allocator_
);
491 return new(symbolizer_allocator_
) Symbolizer(list
);
494 void Symbolizer::LateInitialize() {
495 Symbolizer::GetOrInit();
496 InitializeSwiftDemangler();
499 } // namespace __sanitizer
501 #endif // SANITIZER_POSIX