forked from google/makani
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacktrace.cc
70 lines (62 loc) · 1.97 KB
/
backtrace.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2020 Makani Technologies LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "common/backtrace.h"
#include <cxxabi.h>
#define UNW_LOCAL_ONLY // Only need local unwinding.
#include <libunwind.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// This is taken from
// http://eli.thegreenplace.net/2015/programmatic-access-to-the-call-stack-in-c/
void PrintBacktrace() {
unw_cursor_t cursor;
unw_context_t context;
// Initialize cursor to current frame for local unwinding.
unw_getcontext(&context);
unw_init_local(&cursor, &context);
// Unwind frames one by one, going up the frame stack.
while (unw_step(&cursor) > 0) {
unw_word_t offset, pc;
unw_get_reg(&cursor, UNW_REG_IP, &pc);
if (pc == 0) {
break;
}
printf("0x%lx:", pc);
char sym[256];
if (unw_get_proc_name(&cursor, sym, sizeof(sym), &offset) == 0) {
char* nameptr = sym;
int status;
char* demangled = abi::__cxa_demangle(sym, nullptr, nullptr, &status);
if (status == 0) {
nameptr = demangled;
}
printf(" %s+0x%lx\n", nameptr, offset);
free(demangled);
} else {
printf(" -- error: unable to obtain symbol name for this frame\n");
}
}
}
static void BacktraceHandler(int sig) {
printf("%s\n", strsignal(sig));
PrintBacktrace();
exit(1);
}
void InstallBacktraceHandler(const std::vector<int>& signals) {
for (int sig : signals) {
signal(sig, BacktraceHandler);
}
}