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