我想存储从系统启动到系统崩溃的调用函数地址或名称。当这些函数在程序执行期间被调用时,有没有办法从硬件寄存器中检索它们?

最佳答案

gcc documentation开始:
生成用于进入和退出函数的仪器调用。在函数输入和函数退出之前,下面的剖析函数调用当前函数的地址和它的调用站点。(在某些平台上,内置的返回地址在当前函数之外不起作用,因此调用位置信息可能不可用于分析函数。)

     void __cyg_profile_func_enter (void *this_fn,
                                     void *call_site);
     void __cyg_profile_func_exit  (void *this_fn,
                                     void *call_site);

例子:
#include <stdio.h>

void __cyg_profile_func_enter(void * this_fn, void * call_site)
{
  fprintf(stderr, "enter: %p %p\n", this_fn, call_site);
}

void __cyg_profile_func_exit(void * this_fn, void * call_site)
{
  fprintf(stderr, " exit: %p %p\n", this_fn, call_site);
}

void foo(void);
void bar(void);

void foo(void)
{
  bar();

  return;
}

void bar(void)
{
  return;
}

int main(void)
{
  bar();
  foo();

  return 0;
}

使用以下方法编译和链接:
gcc -finstrument-functions -finstrument-functions-exclude-function-list=__cyg_profile_func_enter,__cyg_profile_func_exit -Wall -g -o main main.c

预期产出将类似于:
enter: 0x400665 0x7fcfedaf6c8d
enter: 0x400643 0x400681
 exit: 0x400643 0x400681
enter: 0x40061c 0x400686
enter: 0x400643 0x400633
 exit: 0x400643 0x400633
 exit: 0x40061c 0x400686
 exit: 0x400665 0x7fcfedaf6c8d

07-24 09:45
查看更多