簡體   English   中英

在HP-UX和Linux上進行堆棧展開

[英]Stack unwinding on HP-UX and Linux

我需要在某些點獲取我的C應用程序的堆棧信息。 我已經閱讀了文檔並搜索了網絡,但仍然無法弄清楚我是如何做到的。 你能指出一個簡單的過程解釋嗎? 或者,甚至更好,以堆棧展開為例。 我需要它用於HP-UX(Itanium)和Linux。

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

}

您想要查看libunwind - 這是一個最初由HP開發的用於展開Itanium堆棧跟蹤(特別復雜)的跨平台庫; 但隨后又擴展到許多其他平台; 包括x86-Linux和Itanium-HPUX。

從libunwind(3)手冊頁; 這是一個使用libunwind編寫典型的“show backtrace”函數的示例:

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

這適用於HPUX itanium: http//docs.hp.com/en/B9106-90012/unwind.5.html

對於簡單的堆棧跟蹤,請嘗試U_STACK_TRACE()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM