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

在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++程序中还需要关注一下函数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 用于将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);

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

一、第一版代码如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#define MAX_FRAMES 100
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) {
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函数。

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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 didnt 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函数

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// The prefix used for mangled symbols, per the Itanium C++ ABI:
// http://www.codesourcery.com/cxx-abi/abi.html#mangling
const 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 + [_]).join
const 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系统中的异常堆栈跟踪的简单实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:Nginx的正则表达式详解

2023-4-12 3:23:58

建站知识

小知识:Nginx服务器https配置的方法示例

2023-4-12 3:33:11

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索