1 //===-- backtrace_linux_libc.cpp --------------------------------*- C++ -*-===//
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 #include <assert.h>
10 #include <execinfo.h>
11 #include <stddef.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <string.h>
15 
16 #include "gwp_asan/optional/backtrace.h"
17 #include "gwp_asan/options.h"
18 
19 namespace {
20 size_t Backtrace(uintptr_t *TraceBuffer, size_t Size) {
21   static_assert(sizeof(uintptr_t) == sizeof(void *), "uintptr_t is not void*");
22 
23   return backtrace(reinterpret_cast<void **>(TraceBuffer), Size);
24 }
25 
26 static void PrintBacktrace(uintptr_t *Trace, size_t TraceLength,
27                            gwp_asan::crash_handler::Printf_t Printf) {
28   if (TraceLength == 0) {
29     Printf("  <not found (does your allocator support backtracing?)>\n\n");
30     return;
31   }
32 
33   char **BacktraceSymbols =
34       backtrace_symbols(reinterpret_cast<void **>(Trace), TraceLength);
35 
36   for (size_t i = 0; i < TraceLength; ++i) {
37     if (!BacktraceSymbols)
38       Printf("  #%zu %p\n", i, Trace[i]);
39     else
40       Printf("  #%zu %s\n", i, BacktraceSymbols[i]);
41   }
42 
43   Printf("\n");
44   if (BacktraceSymbols)
45     free(BacktraceSymbols);
46 }
47 } // anonymous namespace
48 
49 namespace gwp_asan {
50 namespace options {
51 Backtrace_t getBacktraceFunction() { return Backtrace; }
52 crash_handler::PrintBacktrace_t getPrintBacktraceFunction() {
53   return PrintBacktrace;
54 }
55 } // namespace options
56 } // namespace gwp_asan
57