在Linux中做C/C++開發(fā)經(jīng)常會遇到一些不可預(yù)知的問題導(dǎo)致程序崩潰,同時崩潰后也沒留下任何代碼運行痕跡,因此,堆棧跟蹤技術(shù)就顯得非要重要了。本文將簡單介紹Linux中C/C++程序運行時堆棧獲取,首先來看backtrace系列函數(shù)――使用范圍適合于沒有安裝GDB或者想要快速理清楚函數(shù)調(diào)用順序的情況 ,頭文件execinfo.h
int backtrace (void **buffer, int size);
該函數(shù)用來獲取當(dāng)前線程的調(diào)用堆棧,獲取的信息將會被存放在buffer中,它是一個指針數(shù)組。參數(shù)size用來指定buffer中可以保存多少個void* 元素。函數(shù)返回值是實際獲取的指針個數(shù),最大不超過size大小在buffer中的指針實際是從堆棧中獲取的返回地址,每一個堆棧框架有一個返回地址。注意某些編譯器的優(yōu)化選項對獲取正確的調(diào)用堆棧有干擾,另外內(nèi)聯(lián)函數(shù)沒有堆棧框架;刪除框架指針也會使無法正確解析堆棧內(nèi)容。
char **backtrace_symbols (void *const *buffer, int size);
該函數(shù)將從backtrace函數(shù)獲取的信息轉(zhuǎn)化為一個字符串?dāng)?shù)組。參數(shù)buffer是從backtrace函數(shù)獲取的數(shù)組指針,size是該數(shù)組中的元素個數(shù)(backtrace的返回值),函數(shù)返回值是一個指向字符串?dāng)?shù)組的指針,它的大小同buffer相同。每個字符串包含了一個相對于buffer中對應(yīng)元素的可打印信息。它包括函數(shù)名,函數(shù)的偏移地址和實際的返回地址。backtrace_symbols生成的字符串都是malloc出來的,但是不要最后一個一個的free,因為backtrace_symbols會根據(jù)backtrace給出的callstack層數(shù),一次性的將malloc出來一塊內(nèi)存釋放,所以,只需要在最后free返回指針就OK了。
void backtrace_symbols_fd (void *const *buffer, int size, int fd);
該函數(shù)與backtrace_symbols函數(shù)具有相同的功能,不同的是它不會給調(diào)用者返回字符串?dāng)?shù)組,而是將結(jié)果寫入文件描述符為fd的文件中,每個函數(shù)對應(yīng)一行。它不需要調(diào)用malloc函數(shù),因此適用于有可能調(diào)用該函數(shù)會失敗的情況。
在C++程序中還需要關(guān)注一下函數(shù):
/*** 用于將backtrace_symbols函數(shù)所返回的字符串解析成對應(yīng)的函數(shù)名,便于理解* 頭文件 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);
接下來一步一步的講解如何使用以上這些函數(shù)來獲取程序的堆棧
一、第一版代碼如下
#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;}
新聞熱點
疑難解答