在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系統中的異常堆棧跟蹤的簡單實現就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答