HP-UX和Linux上的堆栈展开

5

我需要在特定的点获取C应用程序的堆栈信息。我已经阅读了文档并搜索了互联网,但仍然无法弄清楚如何做到这一点。您能指出一个简单的过程说明吗?或者,更好的是,提供一个堆栈展开的示例。我需要它适用于HP-UX(Itanium)和Linux。

3个回答

4

请查看linux/stacktrace.h

这里提供了API参考:

http://www.cs.cmu.edu/afs/cs/Web/People/tekkotsu/dox/StackTrace_8h.html

可在所有Linux内核上使用

以下是C语言的替代示例,来源于:

http://www.linuxjournal.com/article/6391

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

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

  trace_size = backtrace(trace, 16);
  messages = backtrace_symbols(trace, trace_size);
  printf("[bt] Execution path:\n");
  for (i=0; i<trace_size; ++i)
    printf("[bt] %s\n", messages[i]);
}


int func_low(int p1, int p2) {

  p1 = p1 - p2;
  show_stackframe();

  return 2*p1;
}

int func_high(int p1, int p2) {

  p1 = p1 + p2;
  show_stackframe();

  return 2*p1;
}


int test(int p1) {
  int res;

  if (p1<10)
    res = 5+func_low(p1, 2*p1);
  else
    res = 5+func_high(p1, 2*p1);
  return res;
}



int main() {

  printf("First call: %d\n\n", test(27));
  printf("Second call: %d\n", test(4));

}

我不知道那个API的存在,太有用了! - Jamie
不过这对于 HP-UX 无效。 - DaveR

3
你需要查看 libunwind - 这是一个跨平台库,最初由惠普开发用于展开Itanium堆栈跟踪(这些跟踪特别复杂); 但后来已扩展到许多其他平台,包括x86-Linux和Itanium-HPUX。
从libunwind(3)手册页中,以下是使用libunwind编写典型的“显示回溯”函数示例:
#define UNW_LOCAL_ONLY
#include <libunwind.h>

void show_backtrace (void) {
  unw_cursor_t cursor; unw_context_t uc;
  unw_word_t ip, sp;

  unw_getcontext(&uc);
  unw_init_local(&cursor, &uc);
  while (unw_step(&cursor) > 0) {
    unw_get_reg(&cursor, UNW_REG_IP, &ip);
    unw_get_reg(&cursor, UNW_REG_SP, &sp);
    printf ("ip = %lx, sp = %lx\n", (long) ip, (long) sp);
  }
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接