Stack unwinding on HP-UX and Linux

蹲街弑〆低调 提交于 2019-12-07 05:42:16

问题


I need to get the stack information of my C application in certain points. I've read the documentation and searched the Net but still cannot figure out how I can do it. Can you point to a simple process explanation? Or, even better, to an example of stack unwinding. I need it for HP-UX (Itanium) and Linux.


回答1:


Check out linux/stacktrace.h

Here is an API reference:

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

Should work on all Linux kernels

Here is an alternative example in C from

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));

}



回答2:


You want to look at libunwind - this is a cross-platform library developed originally by HP for unwinding Itanium stack traces (which are particularly complex); but has subsequently been expanded to many other platforms; including both x86-Linux and Itanium-HPUX.

From the libunwind(3) man page; here is an example of using libunwind to write a typical 'show backtrace' function:

#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);
  }
}



回答3:


This shoulw work for HPUX itanium: http://docs.hp.com/en/B9106-90012/unwind.5.html

For simple stack trace, try U_STACK_TRACE().



来源:https://stackoverflow.com/questions/975108/stack-unwinding-on-hp-ux-and-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!