欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

在Linux与Windows上获取当前堆栈信息的方法

程序员文章站 2024-01-15 22:09:04
在编写稳定可靠的软件服务时经常用到输出堆栈信息,以便用户/开发者获取准确的运行信息。常用在日志输出,错误报告,异常检测。 在linux有比较简便的函数获取堆栈信息:...

在编写稳定可靠的软件服务时经常用到输出堆栈信息,以便用户/开发者获取准确的运行信息。常用在日志输出,错误报告,异常检测。

在linux有比较简便的函数获取堆栈信息:

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


void handler(int sig) {
 void *array[5];
 size_t size;

 // get void*'s for all entries on the stack
 size = backtrace(array, 5);

 // print out all the frames to stderr
 fprintf(stderr, "error: signal %d:\n", sig);
 char** msgs = backtrace_symbols(array, size);
 for(int i=1;i<size && msgs[i];++i)
 printf("[%d] %s\n", i, msgs[i]);
 exit(1);
}

void baz() {
 int *foo = (int*)-1; // make a bad pointer
 printf("%d\n", *foo);  // causes segfault
}

void bar() { baz(); }
void foo() { bar(); }


int main(int argc, char **argv) {
 signal(sigsegv, handler); // install our handler
 foo(); // this will call foo, bar, and baz. baz segfaults.
}

以上代码从参考的*中稍作修改而来。核心就是backtrace与backtrace_symbols两个函数。

windows下推荐用stackwalker这个开源代码,支持x86,amd64,ia64。

如果你需要一个最简的代码,那么下面是我抽取出来的代码,明显比linux要复杂一些。(win的很多功能实现起来要复杂一些,当然也有很多功能实现要比linux简单很多。)

我会做一些讲解,在后面。

#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <dbghelp.h>
#include <tlhelp32.h>

using namespace std;

handle ph;

void baz()
{
 int* v = 0;
 *v = 0;
}
void bar()
{
 baz();
}

void foo(){
 __try {
  bar();
 }
 __except(exception_execute_handler) {
  auto sire = syminitialize(ph, 0, false);
  sire = symsetoptions(symgetoptions() | symopt_load_lines | symopt_fail_critical_errors);
  context ctx = { 0 };
  ctx.contextflags = context_full;
  rtlcapturecontext(&ctx);
  stackframe64 sf = { 0 };
 #ifdef _m_ix86 // ignore ia64
  auto imagetype = image_file_machine_i386;
  sf.addrpc.offset = ctx.eip;
  sf.addrpc.mode = addrmodeflat;
  sf.addrframe.offset = ctx.ebp;
  sf.addrframe.mode = addrmodeflat;
  sf.addrstack.offset = ctx.esp;
  sf.addrstack.mode = addrmodeflat;
 #elif _m_x64
  auto imagetype = image_file_machine_amd64;
  sf.addrpc.offset = ctx.rip;
  sf.addrpc.mode = addrmodeflat;
  sf.addrframe.offset = ctx.rsp;
  sf.addrframe.mode = addrmodeflat;
  sf.addrstack.offset = ctx.rsp;
  sf.addrstack.mode = addrmodeflat;
 #endif

  moduleentry32 me;
  auto snap = createtoolhelp32snapshot(th32cs_snapmodule, getcurrentprocessid());
  auto info = module32first(snap, &me);
  while (info) {
   auto dw = symloadmodule64(ph, 0, me.szexepath, me.szmodule, (dword64)me.modbaseaddr, me.modbasesize);
   if (!module32next(snap, &me))break;
  }
  closehandle(snap);
  auto thread = getcurrentthread();

  pimagehlp_symbol64 sym = (imagehlp_symbol64 *)malloc(sizeof(imagehlp_symbol64) + 100);
  if (!sym)
   return;
  memset(sym, 0, sizeof(imagehlp_symbol64) + 100);
  sym->sizeofstruct = sizeof(imagehlp_symbol64);
  sym->maxnamelength = 100;

  imagehlp_line64 line = { 0 };
  line.sizeofstruct = sizeof(line);
  for (;;) {
   auto result = stackwalk(imagetype, ph, thread, &sf, &ctx, 0, symfunctiontableaccess64, symgetmodulebase64, 0);
   if (result) {
    dword64 offset = 0;
    dword offset_for_line = 0;
    char und_fullname[100];

    if (sf.addrpc.offset != 0) {
     if (symgetsymfromaddr64(ph, sf.addrpc.offset, &offset, sym)) {
      undecoratesymbolname(sym->name, und_fullname, 100, undname_complete);
      cout << und_fullname;
     }

     if (symgetlinefromaddr64(ph, sf.addrpc.offset, &offset_for_line, &line)) {
      cout << " " << line.filename << "(" << line.linenumber << ")";
     }
     cout << endl;
    }
   }
   else
    break;
  }
  symcleanup(ph);
 }
}
int main()
{
 ph = getcurrentprocess();
 foo();
 return 0;
}

编译请链接dbghelp.lib

核心就是stackwalk与symgetsymfromaddr64,symgetlinefromaddr64。

stackwalk用于获取下一层堆栈。

symgetsymfromaddr64用于获取当前函数名。

symgetlinefromaddr64用于获取函数所在文件及行号。

为了这三个函数正常工作,还要初始化符号相关功能(syminitialize),取得当前线程描述表(rtlcapturecontext),加载用到的模块(symloadmodule64)。

用到了<dbghelp.h> <tlhelp32.h>这两个头文件。

上面代码执行后会在控制台输出堆栈信息。

这篇在linux与windows上获取当前堆栈信息的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。