如何使用带有行号信息的gcc获取C ++的堆栈跟踪?

时间:2011-01-08 22:15:56

标签: c++ linux gcc stack-trace

我们使用像宏这样的专有assert中的堆栈跟踪来捕获开发人员的错误 - 当捕获到错误时,会打印堆栈跟踪。

我发现gcc的backtrace() / backtrace_symbols()对方法不足:

  1. 名称被破坏
  2. 无行信息
  3. 第一个问题可以通过abi::__cxa_demangle来解决。

    然而,第二个问题更加艰难。我找到了replacement for backtrace_symbols()。 这比gcc的backtrace_symbols()更好,因为它可以检索行号(如果使用-g编译),并且不需要使用-rdynamic进行编译。

    Hoverer代码是GNU许可的,所以我不能在商业代码中使用它。

    任何提案?

    P.S。

    gdb能够打印传递给函数的参数。      可能要求的东西已经太多了:)

    PS 2

    Similar question(感谢nobar)

14 个答案:

答案 0 :(得分:36)

所以你想要一个独立函数打印一个堆栈跟踪,它具有gdb堆栈跟踪所具有的所有功能,并且不会终止你的应用程序。答案是在非交互模式下自动启动gdb,以执行您想要的任务。

这是通过使用fork()在子进程中执行gdb,并在应用程序等待它完成时编写脚本来显示堆栈跟踪来完成的。这可以在不使用核心转储且不中止应用程序的情况下执行。我从这个问题中学到了如何做到这一点:How it's better to invoke gdb from program to print it's stacktrace?

使用该问题发布的示例并不像我所写的那样对我有用,所以这是我的“固定”版本(我在Ubuntu 9.04上运行它)。

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

void print_trace() {
    char pid_buf[30];
    sprintf(pid_buf, "%d", getpid());
    char name_buf[512];
    name_buf[readlink("/proc/self/exe", name_buf, 511)]=0;
    int child_pid = fork();
    if (!child_pid) {           
        dup2(2,1); // redirect output to stderr
        fprintf(stdout,"stack trace for %s pid=%s\n",name_buf,pid_buf);
        execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL);
        abort(); /* If gdb failed to start */
    } else {
        waitpid(child_pid,NULL,0);
    }
}

如引用的问题所示,gdb提供了您可以使用的其他选项。例如,使用“bt full”而不是“bt”会生成更详细的报告(局部变量包含在输出中)。 gdb的联机帮助页很简单,但可以使用完整的文档here

由于这是基于gdb,因此输出包括 demangled names line-number 函数参数,甚至可选局部变量。此外,gdb是线程感知的,因此您应该能够提取一些特定于线程的元数据。

这是我用这种方法看到的堆栈跟踪的一个例子。

0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6
[Current thread is 0 (process 15573)]
#0  0x00007f97e1fc2925 in waitpid () from /lib/libc.so.6
#1  0x0000000000400bd5 in print_trace () at ./demo3b.cpp:496
2  0x0000000000400c09 in recursive (i=2) at ./demo3b.cpp:636
3  0x0000000000400c1a in recursive (i=1) at ./demo3b.cpp:646
4  0x0000000000400c1a in recursive (i=0) at ./demo3b.cpp:646
5  0x0000000000400c46 in main (argc=1, argv=0x7fffe3b2b5b8) at ./demo3b.cpp:70

注意:我发现这与valgrind的使用不兼容(可能是由于Valgrind使用虚拟机)。当您在gdb会话中运行程序时,它也不起作用(不能将“ptrace”的第二个实例应用于进程)。

答案 1 :(得分:28)

不久前I answered a similar question。您应该查看方法#4上可用的源代码,它还可以打印行号和文件名。

  • 方法#4:

我在方法#3上做了一些小改进来打印行号。这也可以复制到方法#2上。

基本上,它使用 addr2line 将地址转换为文件名和行号。

下面的源代码打印所有本地功能的行号。如果调用另一个库中的函数,您可能会看到几个??:0而不是文件名。

#include <stdio.h>
#include <signal.h>
#include <stdio.h>
#include <signal.h>
#include <execinfo.h>

void bt_sighandler(int sig, struct sigcontext ctx) {

  void *trace[16];
  char **messages = (char **)NULL;
  int i, trace_size = 0;

  if (sig == SIGSEGV)
    printf("Got signal %d, faulty address is %p, "
           "from %p\n", sig, ctx.cr2, ctx.eip);
  else
    printf("Got signal %d\n", sig);

  trace_size = backtrace(trace, 16);
  /* overwrite sigaction with caller's address */
  trace[1] = (void *)ctx.eip;
  messages = backtrace_symbols(trace, trace_size);
  /* skip first stack frame (points here) */
  printf("[bt] Execution path:\n");
  for (i=1; i<trace_size; ++i)
  {
    printf("[bt] #%d %s\n", i, messages[i]);

    /* find first occurence of '(' or ' ' in message[i] and assume
     * everything before that is the file name. (Don't go beyond 0 though
     * (string terminator)*/
    size_t p = 0;
    while(messages[i][p] != '(' && messages[i][p] != ' '
            && messages[i][p] != 0)
        ++p;

    char syscom[256];
    sprintf(syscom,"addr2line %p -e %.*s", trace[i], p, messages[i]);
        //last parameter is the file name of the symbol
    system(syscom);
  }

  exit(0);
}


int func_a(int a, char b) {

  char *p = (char *)0xdeadbeef;

  a = a + b;
  *p = 10;  /* CRASH here!! */

  return 2*a;
}


int func_b() {

  int res, a = 5;

  res = 5 + func_a(a, 't');

  return res;
}


int main() {

  /* Install our signal handler */
  struct sigaction sa;

  sa.sa_handler = (void *)bt_sighandler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;

  sigaction(SIGSEGV, &sa, NULL);
  sigaction(SIGUSR1, &sa, NULL);
  /* ... add any other signal here */

  /* Do something */
  printf("%d\n", func_b());
}

此代码应编译为:gcc sighandler.c -o sighandler -rdynamic

程序输出:

Got signal 11, faulty address is 0xdeadbeef, from 0x8048975
[bt] Execution path:
[bt] #1 ./sighandler(func_a+0x1d) [0x8048975]
/home/karl/workspace/stacktrace/sighandler.c:44
[bt] #2 ./sighandler(func_b+0x20) [0x804899f]
/home/karl/workspace/stacktrace/sighandler.c:54
[bt] #3 ./sighandler(main+0x6c) [0x8048a16]
/home/karl/workspace/stacktrace/sighandler.c:74
[bt] #4 /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe6) [0x3fdbd6]
??:0
[bt] #5 ./sighandler() [0x8048781]
??:0

答案 2 :(得分:11)

How to generate a stacktrace when my gcc C++ app crashes处对基本相同的问题进行了深入的讨论。提供了许多建议,包括有关如何在运行时生成堆栈跟踪的大量讨论。

来自该线程的

My personal favorite answer启用core dumps允许您在崩溃时查看完整的应用程序状态(包括函数参数,行号和没有咒骂的名字)。这种方法的另一个好处是它不仅适用于断言,还适用于分段错误未处理的异常

不同的Linux shell使用不同的命令来启用核心转储,但您可以在应用程序代码中使用类似的东西来执行此操作...

#include <sys/resource.h>
...
struct rlimit core_limit = { RLIM_INFINITY, RLIM_INFINITY };
assert( setrlimit( RLIMIT_CORE, &core_limit ) == 0 ); // enable core dumps for debug builds

崩溃后,运行您最喜欢的调试器来检查程序状态。

$ kdbg executable core

这是一些示例输出......

alt text

也可以在命令行从核心转储中提取堆栈跟踪。

$ ( CMDFILE=$(mktemp); echo "bt" >${CMDFILE}; gdb 2>/dev/null --batch -x ${CMDFILE} temp.exe core )
Core was generated by `./temp.exe'.
Program terminated with signal 6, Aborted.
[New process 22857]
#0  0x00007f4189be5fb5 in raise () from /lib/libc.so.6
#0  0x00007f4189be5fb5 in raise () from /lib/libc.so.6
#1  0x00007f4189be7bc3 in abort () from /lib/libc.so.6
#2  0x00007f4189bdef09 in __assert_fail () from /lib/libc.so.6
#3  0x00000000004007e8 in recursive (i=5) at ./demo1.cpp:18
#4  0x00000000004007f3 in recursive (i=4) at ./demo1.cpp:19
#5  0x00000000004007f3 in recursive (i=3) at ./demo1.cpp:19
#6  0x00000000004007f3 in recursive (i=2) at ./demo1.cpp:19
#7  0x00000000004007f3 in recursive (i=1) at ./demo1.cpp:19
#8  0x00000000004007f3 in recursive (i=0) at ./demo1.cpp:19
#9  0x0000000000400849 in main (argc=1, argv=0x7fff2483bd98) at ./demo1.cpp:26

答案 3 :(得分:6)

使用google glog库。它有新的BSD许可证。

它包含stacktrace.h文件中的GetStackTrace函数。

修改

我在这里http://blog.bigpixel.ro/2010/09/09/stack-unwinding-stack-trace-with-gcc/发现有一个名为addr2line的实用程序可以将程序地址转换为文件名和行号。

http://linuxcommand.org/man_pages/addr2line1.html

答案 4 :(得分:6)

由于GPL许可代码旨在帮助您在开发过程中,您可以不将其包含在最终产品中。 GPL限制您分发与非GPL兼容代码链接的GPL许可证代码。只要您在内部使用GPL代码,就应该没问题。

答案 5 :(得分:5)

这是另一种方法。 debug_assert ()宏以编程方式设置条件断点。如果您在调试器中运行,则在断言表达式为false时将触发断点 - 并且您可以分析实时堆栈(程序不会终止)。如果您没有在调试器中运行,则失败的debug_assert()会导致程序中止,您将获得可以分析堆栈的核心转储(请参阅我之前的回答)。

与普通断言相比,此方法的优点是可以在触发debug_assert后(在调试器中运行时)继续运行程序。换句话说,debug_assert()比assert()稍微灵活一些。

   #include <iostream>
   #include <cassert>
   #include <sys/resource.h> 

// note: The assert expression should show up in
// stack trace as parameter to this function
void debug_breakpoint( char const * expression )
   {
   asm("int3"); // x86 specific
   }

#ifdef NDEBUG
   #define debug_assert( expression )
#else
// creates a conditional breakpoint
   #define debug_assert( expression ) \
      do { if ( !(expression) ) debug_breakpoint( #expression ); } while (0)
#endif

void recursive( int i=0 )
   {
   debug_assert( i < 5 );
   if ( i < 10 ) recursive(i+1);
   }

int main( int argc, char * argv[] )
   {
   rlimit core_limit = { RLIM_INFINITY, RLIM_INFINITY };
   setrlimit( RLIMIT_CORE, &core_limit ); // enable core dumps
   recursive();
   }

注意:有时在调试器中设置“条件断点”可能会很慢。通过以编程方式建立断点,此方法的性能应与正常的assert()相当。

注意:正如所写,这是针对Intel x86架构的 - 其他处理器可能有不同的指令来生成断点。

答案 6 :(得分:4)

有点晚了,但您可以使用libbfb来获取symsnarf.c中的refdbg之类的文件名和亚麻布。 libbfb由addr2linegdb

内部使用

答案 7 :(得分:2)

解决方案之一是在失败的断言处理程序中使用“bt”-script启动gdb。集成这样的gdb-starting并不是很容易,但是它会给你回溯和args和demangle名称(或者你可以通过c ++ filt programm传递gdb输出)。

两个程序(gdb和c ++ filt)都不会链接到您的应用程序中,因此GPL不会要求您开源完整的应用程序。

可以与backtrace-symbols一起使用的相同方法(执行GPL程序)。只需生成%eip的ascii列表和exec文件的映射(/ proc / self / maps)并将其传递给单独的二进制文件。

答案 8 :(得分:2)

您可以使用DeathHandler - 小型C ++课程,它可以为您提供一切可靠的服务。

答案 9 :(得分:1)

我认为行号与当前的eip值有关,对吧?

解决方案1:
然后你可以使用类似GetThreadContext()的东西,除了你正在使用linux。我用Google搜索了一下,找到了类似的东西,ptrace()

  

ptrace()系统调用提供了一个   父进程可以用来表示   观察并控制执行   另一个过程,并检查和   改变其核心形象和注册。 [...]   父母可以通过启动跟踪   调用fork(2)并拥有   结果孩子做了一个PTRACE_TRACEME,   跟随(通常)由执行官(3)。   或者,父母可以开始   跟踪现有流程的使用   PTRACE_ATTACH。

现在我在想,你可以做一个'主'程序来检查发送给它的孩子的信号,这是你正在处理的真实程序。在fork()之后,它会调用waitid()

  

所有这些系统调用都习惯了   等待孩子的状态变化   调用过程,并获得   关于孩子的信息   国家已经改变了。

如果捕获了SIGSEGV(或类似的东西),请调用ptrace()以获取eip的值。

PS:我从来没有使用过这些系统调用(实际上,我以前从未见过它们),所以我不知道是否有可能无法帮助你。至少我希望这些链接很有用。 ;)

解决方案2: 第一个解决方案非常复杂,对吗?我提出了一个更简单的方法:使用signal()捕获您感兴趣的信号并调用一个简单的函数来读取存储在堆栈中的eip值:

...
signal(SIGSEGV, sig_handler);
...

void sig_handler(int signum)
{
    int eip_value;

    asm {
        push eax;
        mov eax, [ebp - 4]
        mov eip_value, eax
        pop eax
    }

    // now you have the address of the
    // **next** instruction after the
    // SIGSEGV was received
}

asm语法是Borland的语法,只需将其调整为GAS即可。 ;)

答案 10 :(得分:1)

这是我的第三个答案 - 仍然试图利用核心转储。

在问题中,“断言式”宏是否应该终止应用程序(assert的方式)或者它们应该在生成堆栈跟踪后继续执行,这一点并不完全清楚。

在这个答案中,我正在解决你想要显示堆栈跟踪并继续执行的情况。我在下面写了 coredump ()函数来生成核心转储,自动从中提取堆栈跟踪,然后继续执行程序。

用法与assert()的用法相同。当然,区别在于assert()终止了程序,但 coredump_assert ()却没有。

   #include <iostream>
   #include <sys/resource.h> 
   #include <cstdio>
   #include <cstdlib>
   #include <boost/lexical_cast.hpp>
   #include <string>
   #include <sys/wait.h>
   #include <unistd.h>

   std::string exename;

// expression argument is for diagnostic purposes (shows up in call-stack)
void coredump( char const * expression )
   {

   pid_t childpid = fork();

   if ( childpid == 0 ) // child process generates core dump
      {
      rlimit core_limit = { RLIM_INFINITY, RLIM_INFINITY };
      setrlimit( RLIMIT_CORE, &core_limit ); // enable core dumps
      abort(); // terminate child process and generate core dump
      }

// give each core-file a unique name
   if ( childpid > 0 ) waitpid( childpid, 0, 0 );
   static int count=0;
   using std::string;
   string pid = boost::lexical_cast<string>(getpid());
   string newcorename = "core-"+boost::lexical_cast<string>(count++)+"."+pid;
   string rawcorename = "core."+boost::lexical_cast<string>(childpid);
   int rename_rval = rename(rawcorename.c_str(),newcorename.c_str()); // try with core.PID
   if ( rename_rval == -1 ) rename_rval = rename("core",newcorename.c_str()); // try with just core
   if ( rename_rval == -1 ) std::cerr<<"failed to capture core file\n";

  #if 1 // optional: dump stack trace and delete core file
   string cmd = "( CMDFILE=$(mktemp); echo 'bt' >${CMDFILE}; gdb 2>/dev/null --batch -x ${CMDFILE} "+exename+" "+newcorename+" ; unlink ${CMDFILE} )";
   int system_rval = system( ("bash -c '"+cmd+"'").c_str() );
   if ( system_rval == -1 ) std::cerr.flush(), perror("system() failed during stack trace"), fflush(stderr);
   unlink( newcorename.c_str() );
  #endif

   }

#ifdef NDEBUG
   #define coredump_assert( expression ) ((void)(expression))
#else
   #define coredump_assert( expression ) do { if ( !(expression) ) { coredump( #expression ); } } while (0)
#endif

void recursive( int i=0 )
   {
   coredump_assert( i < 2 );
   if ( i < 4 ) recursive(i+1);
   }

int main( int argc, char * argv[] )
   {
   exename = argv[0]; // this is used to generate the stack trace
   recursive();
   }

当我运行程序时,它会显示三个堆栈跟踪...

Core was generated by `./temp.exe'.                                         
Program terminated with signal 6, Aborted.
[New process 24251]
#0  0x00007f2818ac9fb5 in raise () from /lib/libc.so.6
#0  0x00007f2818ac9fb5 in raise () from /lib/libc.so.6
#1  0x00007f2818acbbc3 in abort () from /lib/libc.so.6
#2  0x0000000000401a0e in coredump (expression=0x403303 "i < 2") at ./demo3.cpp:29
#3  0x0000000000401f5f in recursive (i=2) at ./demo3.cpp:60
#4  0x0000000000401f70 in recursive (i=1) at ./demo3.cpp:61
#5  0x0000000000401f70 in recursive (i=0) at ./demo3.cpp:61
#6  0x0000000000401f8b in main (argc=1, argv=0x7fffc229eb98) at ./demo3.cpp:66
Core was generated by `./temp.exe'.
Program terminated with signal 6, Aborted.
[New process 24259]
#0  0x00007f2818ac9fb5 in raise () from /lib/libc.so.6
#0  0x00007f2818ac9fb5 in raise () from /lib/libc.so.6
#1  0x00007f2818acbbc3 in abort () from /lib/libc.so.6
#2  0x0000000000401a0e in coredump (expression=0x403303 "i < 2") at ./demo3.cpp:29
#3  0x0000000000401f5f in recursive (i=3) at ./demo3.cpp:60
#4  0x0000000000401f70 in recursive (i=2) at ./demo3.cpp:61
#5  0x0000000000401f70 in recursive (i=1) at ./demo3.cpp:61
#6  0x0000000000401f70 in recursive (i=0) at ./demo3.cpp:61
#7  0x0000000000401f8b in main (argc=1, argv=0x7fffc229eb98) at ./demo3.cpp:66
Core was generated by `./temp.exe'.
Program terminated with signal 6, Aborted.
[New process 24267]
#0  0x00007f2818ac9fb5 in raise () from /lib/libc.so.6
#0  0x00007f2818ac9fb5 in raise () from /lib/libc.so.6
#1  0x00007f2818acbbc3 in abort () from /lib/libc.so.6
#2  0x0000000000401a0e in coredump (expression=0x403303 "i < 2") at ./demo3.cpp:29
#3  0x0000000000401f5f in recursive (i=4) at ./demo3.cpp:60
#4  0x0000000000401f70 in recursive (i=3) at ./demo3.cpp:61
#5  0x0000000000401f70 in recursive (i=2) at ./demo3.cpp:61
#6  0x0000000000401f70 in recursive (i=1) at ./demo3.cpp:61
#7  0x0000000000401f70 in recursive (i=0) at ./demo3.cpp:61
#8  0x0000000000401f8b in main (argc=1, argv=0x7fffc229eb98) at ./demo3.cpp:66

答案 11 :(得分:1)

我必须在有很多约束的生产环境中执行此操作,所以我想解释一下已经发布的方法的优缺点。

  1. 附加GDB

+非常简单而强大

-对于大型程序来说很慢,因为GDB坚持将整个地址加载到#数据库行中,而不是懒惰地

-干扰信号处理。附加GDB时,它会拦截SIGINT(ctrl-c)之类的信号,这将导致程序卡在GDB交互式提示中?如果其他某个程序例行发送此类信号。也许有一些解决方法,但这在我的情况下使GDB无法使用。如果您只想在程序崩溃时打印一次调用堆栈,而不是多次打印,则仍然可以使用它。

  1. addr2line。这是另一种不使用backtrace_symbols的解决方案。

+不从堆中分配,这在信号处理程序内部是不安全的

+无需解析backtrace_symbols的输出

-无法在没有dladdr1的MacOS上运行。您可以改用_dyld_get_image_vmaddr_slide,它返回与link_map :: l_addr相同的偏移量。

-需要添加负偏移量,否则转换后的行号将增加1。 backtrace_symbols为您做到这一点

#include <execinfo.h>
#include <link.h>
#include <stdlib.h>
#include <stdio.h>

// converts a function's address in memory to its VMA address in the executable file. VMA is what addr2line expects
size_t ConvertToVMA(size_t addr)
{
  Dl_info info;
  link_map* link_map;
  dladdr1((void*)addr,&info,(void**)&link_map,RTLD_DL_LINKMAP);
  return addr-link_map->l_addr;
}

void PrintCallStack()
{
  void *callstack[128];
  int frame_count = backtrace(callstack, sizeof(callstack)/sizeof(callstack[0]));
  for (int i = 0; i < frame_count; i++)
  {
    char location[1024];
    Dl_info info;
    if(dladdr(callstack[i],&info))
    {
      char command[256];
      size_t VMA_addr=ConvertToVMA((size_t)callstack[i]);
      //if(i!=crash_depth)
        VMA_addr-=1;    // https://stackoverflow.com/questions/11579509/wrong-line-numbers-from-addr2line/63841497#63841497
      snprintf(command,sizeof(command),"addr2line -e %s -Ci %zx",info.dli_fname,VMA_addr);
      system(command);
    }
  }
}

void Foo()
{
  PrintCallStack();
}

int main()
{
  Foo();
  return 0;
}

我还想澄清backtrace和backtrace_symbols生成的地址以及addr2line的预期地址。 enter image description here addr2line需要Foo VMA ,或者,如果您使用的是--section = .text,则Foo file -text file 。 backtrace返回Foo mem 。 backtrace_symbols在某处生成Foo VMA 。 我在其他几篇文章中犯的一个大错误是假设VMA base = 0或Foo VMA = Foo file = Foo mem -ELF mem ,易于计算。 这通常是可行的,但对于某些编译器(例如,链接程序脚本),请使用VMA base >0。例如,在Ubuntu 16(0x400000)上使用GCC 5.4,在MacOS(0x100000000)上使用clang 11。 对于共享库,它始终为0。似乎VMAbase仅对非位置无关代码有意义。否则,它对EXE在内存中的加载位置没有影响。

此外,karlphillip或karlphillip都不需要使用-rdynamic进行编译。这将增加二进制文件的大小,尤其是对于大型C ++程序或共享库,动态符号表中的无用条目永远不会被导入

答案 12 :(得分:0)

这是我的解决方法:

#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>
#include <zconf.h>
#include "regex"

std::string getexepath() {
    char result[PATH_MAX];
    ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
    return std::string(result, (count > 0) ? count : 0);
}

std::string sh(std::string cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer.data(), 128, pipe.get()) != nullptr) {
            result += buffer.data();
        }
    }
    return result;
}


void print_backtrace(void) {
    void *bt[1024];
    int bt_size;
    char **bt_syms;
    int i;

    bt_size = backtrace(bt, 1024);
    bt_syms = backtrace_symbols(bt, bt_size);
    std::regex re("\\[(.+)\\]");
    auto exec_path = getexepath();
    for (i = 1; i < bt_size; i++) {
        std::string sym = bt_syms[i];
        std::smatch ms;
        if (std::regex_search(sym, ms, re)) {
            std::string addr = ms[1];
            std::string cmd = "addr2line -e " + exec_path + " -f -C " + addr;
            auto r = sh(cmd);
            std::regex re2("\\n$");
            auto r2 = std::regex_replace(r, re2, "");
            std::cout << r2 << std::endl;
        }
    }
    free(bt_syms);
}

void test_m() {
    print_backtrace();
}

int main() {
    test_m();
    return 0;
}

输出:

/home/roroco/Dropbox/c/ro-c/cmake-build-debug/ex/test_backtrace_with_line_number
test_m()
/home/roroco/Dropbox/c/ro-c/ex/test_backtrace_with_line_number.cpp:57
main
/home/roroco/Dropbox/c/ro-c/ex/test_backtrace_with_line_number.cpp:61
??
??:0

“ ??”和“ ??:0”,因为此跟踪记录在libc中,而不在我的源文件中

答案 13 :(得分:0)

AFAICS到目前为止提供的所有解决方案都不会打印共享库中的函数名称和行号。这就是我所需要的,因此我更改了karlphillip的解决方案(以及类似问题的其他一些答案),以使用/ proc / id / maps解析共享库地址。

#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h>
#include <string.h>
#include <execinfo.h>
#include <stdbool.h>

struct Region { // one mapped file, for example a shared library
    uintptr_t start;
    uintptr_t end;
    char* path;
};

static struct Region* getRegions(int* size) { 
// parse /proc/self/maps and get list of mapped files 
    FILE* file;
    int allocated = 10;
    *size = 0;
    struct Region* res;
    uintptr_t regionStart = 0x00000000;
    uintptr_t regionEnd = 0x00000000;
    char* regionPath = "";
    uintmax_t matchedStart;
    uintmax_t matchedEnd;
    char* matchedPath;

    res = (struct Region*)malloc(sizeof(struct Region) * allocated);
    file = fopen("/proc/self/maps", "r");
    while (!feof(file)) {
        fscanf(file, "%jx-%jx %*s %*s %*s %*s%*[ ]%m[^\n]\n",  &matchedStart, &matchedEnd, &matchedPath);
        bool bothNull = matchedPath == 0x0 && regionPath == 0x0;
        bool similar = matchedPath && regionPath && !strcmp(matchedPath, regionPath);
        if(bothNull || similar) {
            free(matchedPath);
            regionEnd = matchedEnd;
        } else {
            if(*size == allocated) {
                allocated *= 2;
                res = (struct Region*)realloc(res, sizeof(struct Region) * allocated);
            }

            res[*size].start = regionStart;
            res[*size].end = regionEnd;
            res[*size].path = regionPath;
            (*size)++;
            regionStart = matchedStart;
            regionEnd = matchedEnd;
            regionPath = matchedPath;
        }
    }
    return res;
}

struct SemiResolvedAddress {
    char* path;
    uintptr_t offset;
};
static struct SemiResolvedAddress semiResolve(struct Region* regions, int regionsNum, uintptr_t address) {
// convert address from our address space to
// address suitable fo addr2line 
    struct Region* region;
    struct SemiResolvedAddress res = {"", address};
    for(region = regions; region < regions+regionsNum; region++) {
        if(address >= region->start && address < region->end) {
            res.path = region->path;
            res.offset = address - region->start;
        }
    }
    return res;
}

void printStacktraceWithLines(unsigned int max_frames)
{
    int regionsNum;
    fprintf(stderr, "stack trace:\n");

    // storage array for stack trace address data
    void* addrlist[max_frames+1];

    // retrieve current stack addresses
    int addrlen = backtrace(addrlist, sizeof(addrlist) / sizeof(void*));
    if (addrlen == 0) {
        fprintf(stderr, "  <empty, possibly corrupt>\n");
        return;
    }
    struct Region* regions = getRegions(&regionsNum); 
    for (int i = 1; i < addrlen; i++)
    {
        struct SemiResolvedAddress hres =
                semiResolve(regions, regionsNum, (uintptr_t)(addrlist[i]));
        char syscom[256];
        sprintf(syscom, "addr2line -C -f -p -a -e %s 0x%jx", hres.path, (intmax_t)(hres.offset));
        system(syscom);
    }
    free(regions);
}