win32_backtrace.h (1470B)
1 #pragma once 2 3 #include <windows.h> 4 #include <errno.h> 5 6 #pragma warning( push ) 7 #pragma warning( disable : 4091 ) 8 #include <dbghelp.h> 9 #pragma warning( pop ) 10 11 inline void print_backtrace_and_abort() { 12 { 13 int error = errno; 14 printf( "errno = %d: %s\n", error, strerror( error ) ); 15 } 16 { 17 DWORD error = GetLastError(); 18 char buf[ 1024 ]; 19 FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 20 MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), buf, sizeof( buf ), NULL ); 21 printf( "GetLastError = %d: %s", error, buf ); 22 } 23 24 const int max_symbol_len = 1024; 25 26 HANDLE process = GetCurrentProcess(); 27 SymInitialize( process, NULL, TRUE ); 28 29 void * stack[ 128 ]; 30 WORD num_frames = CaptureStackBackTrace( 0, 128, stack, NULL ); 31 32 for( WORD i = 0; i < num_frames; i++ ) { 33 char symbol_mem[ sizeof( SYMBOL_INFO ) + max_symbol_len * sizeof( TCHAR ) ]; 34 SYMBOL_INFO * symbol = ( SYMBOL_INFO * ) symbol_mem; 35 symbol->MaxNameLen = max_symbol_len; 36 symbol->SizeOfStruct = sizeof( SYMBOL_INFO ); 37 38 DWORD64 addr64 = DWORD64( stack[ i ] ); 39 SymFromAddr( process, addr64, NULL, symbol ); 40 41 IMAGEHLP_LINE64 line; 42 DWORD col; 43 line.SizeOfStruct = sizeof( line ); 44 BOOL has_file_info = SymGetLineFromAddr64( process, addr64, &col, &line ); 45 46 if( has_file_info ) { 47 printf( "%s (%s:%d - 0x%08I64x)\n", symbol->Name, line.FileName, line.LineNumber, symbol->Address ); 48 } 49 else { 50 printf( "%s (0x%08I64x)\n", symbol->Name, symbol->Address ); 51 } 52 } 53 54 __debugbreak(); 55 }