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