侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

浅谈Linux系统中的异常堆栈跟踪的简单实现

linux  /  管理员 发布于 7年前   230

在Linux中做C/C++开发经常会遇到一些不可预知的问题导致程序崩溃,同时崩溃后也没留下任何代码运行痕迹,因此,堆栈跟踪技术就显得非要重要了。本文将简单介绍Linux中C/C++程序运行时堆栈获取,首先来看backtrace系列函数――使用范围适合于没有安装GDB或者想要快速理清楚函数调用顺序的情况 ,头文件execinfo.h

int backtrace (void **buffer, int size);

该函数用来获取当前线程的调用堆栈,获取的信息将会被存放在buffer中,它是一个指针数组。参数size用来指定buffer中可以保存多少个void* 元素。函数返回值是实际获取的指针个数,最大不超过size大小在buffer中的指针实际是从堆栈中获取的返回地址,每一个堆栈框架有一个返回地址。注意某些编译器的优化选项对获取正确的调用堆栈有干扰,另外内联函数没有堆栈框架;删除框架指针也会使无法正确解析堆栈内容。

char **backtrace_symbols (void *const *buffer, int size);

该函数将从backtrace函数获取的信息转化为一个字符串数组。参数buffer是从backtrace函数获取的数组指针,size是该数组中的元素个数(backtrace的返回值),函数返回值是一个指向字符串数组的指针,它的大小同buffer相同。每个字符串包含了一个相对于buffer中对应元素的可打印信息。它包括函数名,函数的偏移地址和实际的返回地址。backtrace_symbols生成的字符串都是malloc出来的,但是不要最后一个一个的free,因为backtrace_symbols会根据backtrace给出的callstack层数,一次性的将malloc出来一块内存释放,所以,只需要在最后free返回指针就OK了。

void backtrace_symbols_fd (void *const *buffer, int size, int fd);  

该函数与backtrace_symbols函数具有相同的功能,不同的是它不会给调用者返回字符串数组,而是将结果写入文件描述符为fd的文件中,每个函数对应一行。它不需要调用malloc函数,因此适用于有可能调用该函数会失败的情况。


在C++程序中还需要关注一下函数:

/*** 用于将backtrace_symbols函数所返回的字符串解析成对应的函数名,便于理解* 头文件  cxxabi.h* 名字空间abi* @param mangled_name A NUL-terminated character string containing the name to be demangled.* @param output_buffer  A region of memory, allocated with malloc, of *length bytes, into which the demangled name is stored. If output_buffer is not long enough, it is expanded using realloc. *     output_buffer may instead be NULL; in that case, the demangled name is placed in a region of memory allocated with malloc. * @param length  If length is non-NULL, the length of the buffer containing the demangled name is placed in *length.* @param status  *status is set to one of the following values:*        0: The demangling operation succeeded.*       -1: A memory allocation failiure occurred.*       -2: Mangled_name is not a valid name under the C++ ABI mangling rules.*       -3: One of the arguments is invalid.*/char *__cxa_demangle (const char *mangled_name, char *output_buffer, size_t *length, int *status);

接下来一步一步的讲解如何使用以上这些函数来获取程序的堆栈

 一、第一版代码如下

#define MAX_FRAMES 100void GetStackTrace (std::string* stack){  void* addresses[MAX_FRAMES];  int size = backtrace (addresses, MAX_FRAMES);  std::unique_ptr<char*, void(*)(void*)> symbols {    backtrace_symbols (addresses, size),    std::free  };  for (int i = 0; i < size; ++i) {    stack->append (symbols.get()[i]);    stack->append ("\n");  }}void TestFunc (std::string& stack, int value){  while (--value);  GetStackTrace (&stack);}int main(int argc, char* argv[]){  std::string stack;  TestFunc (stack, 5);  std::cout << stack << std::endl;  return 0;}

编译成可执行文件StackTrace后执行输出如下结果:

./StackTrace(_Z13GetStackTracePSs+0x27) [0x4035d5]
./StackTrace(_Z8TestFuncRSsi+0x2a) [0x4036e6]
./StackTrace(main+0x2d) [0x403715]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7f7302027de5]
./StackTrace() [0x403139]

从输出的结果中可以得知程序的调用过程,但是看起来比较难以理解。让我们来稍微改动一下GetStackTrace函数。

二、进阶版代码,在第一点中的代码基础上改动

void DemangleSymbol (std::string* symbol){  size_t size = 0;  int status = -4;  char temp[256] = {'\0'};  //first, try to demangle a c++ name  if (1 == sscanf (symbol->c_str (), "%*[^(]%*[^_]%[^)+]", temp)) {    std::unique_ptr<char, void(*)(void*)> demangled {      abi::__cxa_demangle (temp, NULL, &size, &status),      std::free    };    if (demangled.get ()) {      symbol->clear ();      symbol->append (demangled.get ());      return;    }  }  //if that didn't work, try to get a regular c symbol  if (1 == sscanf(symbol->c_str (), "%255s", temp)) {    symbol->clear ();    symbol->append (temp);  }}void GetStackTrace (std::string* stack){  void* addresses[MAX_FRAMES];  int size = backtrace (addresses, MAX_FRAMES);  std::unique_ptr<char*, void(*)(void*)> symbols {    backtrace_symbols (addresses, size),    std::free  };  for (int i = 0; i < size; ++i) {    std::string demangled (symbols.get()[i]);    DemangleSymbol (&demangled);    stack->append (demangled);    stack->append ("\n");  }}

该版本通过__cxa_demangle来将backtrace_symbols返回的字符串逐个解析成可以方便看懂的字符串,由于__cxa_demangle只能解析_Z13GetStackTracePSs这样的字符串,所以使用sscanf来简单的截取backtrace_symbols函数返回的数据,当然,现在已不这么提倡使用sscanf函数了。编译成可执行文件StackTrace后执行输出如下结果:

GetStackTrace(std::string*)
TestFunc(std::string&, int)
./StackTrace(main+0x2d)
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)
./StackTrace()

从输出的结果中可以得知程序的调用过程,但是少了一些其他的信息,让我们来改动一下DemangleSymbol函数

三、进进介版代码,在第一,第二点的代码基础上改动

// The prefix used for mangled symbols, per the Itanium C++ ABI:// http://www.codesourcery.com/cxx-abi/abi.html#manglingconst char kMangledSymbolPrefix[] = "_Z";// Characters that can be used for symbols, generated by Ruby:// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).joinconst char kSymbolCharacters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";// Demangles C++ symbols in the given text. Example:// "out/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"// =>// "out/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"void DemangleSymbol (std::string* symbol){  std::string::size_type search_from = 0;  while (search_from < symbol->size ()) {    // Look for the start of a mangled symbol from search_from    std::string::size_type mangled_start = symbol->find (kMangledSymbolPrefix, search_from);    if (mangled_start == std::string::npos) {      break; // Mangled symbol not found    }    // Look for the end of the mangled symbol    std::string::size_type mangled_end = symbol->find_first_not_of (kSymbolCharacters, mangled_start);    if (mangled_end == std::string::npos) {      mangled_end = symbol->size ();    }    std::string mangled_symbol = std::move (symbol->substr (mangled_start, mangled_end - mangled_start));    // Try to demangle the mangled symbol candidate    int status = -4; // some arbitrary value to eliminate the compiler warning    std::unique_ptr<char, void(*)(void*)> demangled_symbol {      abi::__cxa_demangle (mangled_symbol.c_str (), nullptr, 0, &status),      std::free    };    // 0 Demangling is success    if (0 == status) {      // Remove the mangled symbol      symbol->erase (mangled_start, mangled_end - mangled_start);      // Insert the demangled symbol      symbol->insert (mangled_start, demangled_symbol.get ());      // Next time, we will start right after the demangled symbol      search_from = mangled_start + strlen (demangled_symbol.get ());    }    else {      // Failed to demangle. Retry after the "_Z" we just found      search_from = mangled_start + 2;    }  }}

该版本的DemangleSymbol函数与第二版的DemangleSymbol函数稍有改动,该版本主要是找到_Z13GetStackTracePSs这样的字符串给__cxa_demangle函数解析,最后将解析后的内容替换掉原来的内容,编译成可执行文件StackTrace后执行输出结果入下:

./StackTrace(GetStackTrace(std::string*)+0x27) [0x403720]
./StackTrace(TestFunc(std::string&, int)+0x2a) [0x4038c0]
./StackTrace(main+0x2d) [0x4038ef]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5) [0x7fb9d560bde5]
./StackTrace() [0x403279]

以上输出结果在代码调试中能给我们带来很多的信息,但是还是少了一些辅助信息,例如:文件名、函数所在文件的代码行、进程或者线程号(这个在多线中很重要)。更多内容可以参考开源项目libunwind或者google-coredumper。

以上这篇浅谈Linux系统中的异常堆栈跟踪的简单实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    在VMware虚拟机官方下载,学习地址
    下一条:
    linux中通过文件描述符获取文件绝对路径的方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Linux系统中使用Iptables实现流量转发功能流程步骤(0个评论)
    • vim学习笔记-入门级需要了解的一些快捷键(0个评论)
    • 在centos7系统中实现分区并格式化挂载一块硬盘到/data目录流程步骤(0个评论)
    • 在Linux系统种查看某一个进程所占用的内存命令(0个评论)
    • Linux中grep命令中的10种高级用法浅析(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-11
    • 2017-07
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2021-02
    • 2021-03
    • 2021-04
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-03
    • 2022-04
    • 2022-08
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-06
    • 2023-07
    • 2023-10
    • 2023-12
    • 2024-01
    • 2024-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客