11 #include <linux/prctl.h>
13 #include <sys/prctl.h>
22 static inline std::string get_stack_trace() {
24 sprintf(pid_buf,
"%d", getpid());
26 name_buf[readlink(
"/proc/self/exe", name_buf, 511)] = 0;
27 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
29 std::string gdb_cmd =
"/usr/bin/gdb -batch -quiet -ex bt " +
30 std::string(name_buf) +
" " + std::string(pid_buf) +
33 FILE *child_f = popen(gdb_cmd.c_str(),
"r");
38 while ((c = getc(child_f)) != EOF)
47 inline int get_stack_depth(
void) {
48 auto stack = get_stack_trace();
49 return std::count(stack.begin(), stack.end(),
'\n');
53 static inline void print_trace(
bool start_gdb =
true) {
55 sprintf(pid_buf,
"%d", getpid());
57 name_buf[readlink(
"/proc/self/exe", name_buf, 511)] = 0;
58 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
59 int child_pid = fork();
63 execl(
"/usr/bin/gdb",
"gdb",
"-quiet",
"-ex",
"bt", name_buf, pid_buf,
66 execl(
"/usr/bin/gdb",
"gdb",
"-batch",
"-quiet",
"-ex",
"bt", name_buf,
71 waitpid(child_pid, NULL, 0);