原理介紹:使用nstd工具進行進程崩潰時內存和堆棧轉儲。shell
編譯Release版本時打開調試選項,將exe和pdb文件一塊兒發佈。session
2.使用批處理命令設置Windows系統在進程崩潰時調用的調試器爲ntsd工具
@reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug" /v "Auto" /t REG_SZ /d "1" /f
該批處理指令,設置AeDebug調用前是否須要彈消息框確認?默認爲0,設置1表示自動處理不彈確認框。若是你們安裝過Visual Studio,可能都遇到過下列彈框:
spa
這就是VS設置了AeDebug調試器後,遇到進程崩潰,而後彈框確認是否要附加到該進程進行調試的過程。.net
而後設置ntsd的調試轉儲指令:
線程
@reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug" /v "Debugger" /t REG_SZ /d "D:\Dump\ntsd.exe -p %%ld -e %%ld -g -c \".dump /ma /u D:\Dump\dump.dmp; .logopen /t D:\Dump\dump.txt; .time; .echo Process Status:; ^|; .echo Thread Status:; ^~; .echo Stack Status:; kpn; .logclose; q\"" /f
我把的ntsd程序拷貝到d:\dump目錄。debug
-p %%ld 傳入進程ID,-c 執行dump指令:echo 打印線程信息,線程堆棧,最後再退出。調試
批處理安裝腳本和ntsd程序我都已經打好包了,能夠到這裏下載。code
3.下面經過一個實例來演示下效果:orm
#include <stdio.h> void test2() { int a = 1; int b = 0; int c = a/b; } void test1() { test2(); } int main(int argc, char** argv) { test1(); return 0; }
經過除0錯誤來構造一次崩潰,test1和test2是爲了演示調用堆棧。
經過本方法抓取的堆棧文本以下:
Opened log file 'D:\Dump\dump_22d4_2014-09-30_15-15-33-062.txt' Debug session time: Tue Sep 30 15:15:33.063 2014 (GMT+8) System Uptime: 2 days 3:35:54.545 Process Uptime: 0 days 0:00:00.923 Kernel time: 0 days 0:00:00.015 User time: 0 days 0:00:00.000 Process Status: . 0 id: 3854 attach name: D:\test\CoreDump\DumpExampleNormalStack.exe Thread Status: . 0 Id: 3854.3138 Suspend: 1 Teb: 7ffdf000 Unfrozen Stack Status: *** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\SYSTEM32\ntdll.dll - # ChildEBP RetAddr 00 002dfb2c 01321038 DumpExampleNormalStack!test2(void)+0x18 01 002dfb34 01321048 DumpExampleNormalStack!test1(void)+0x8 02 002dfb3c 01321159 DumpExampleNormalStack!main(int argc = 1, char ** argv = 0x003ea488)+0x8 *** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\system32\kernel32.dll - 03 002dfb84 76e2ee1c DumpExampleNormalStack!__tmainCRTStartup(void)+0xfe WARNING: Stack unwind information not available. Following frames may be wrong. 04 002dfb90 77ba37eb kernel32!BaseThreadInitThunk+0x12 05 002dfbd0 77ba37be ntdll!RtlInitializeExceptionChain+0xef 06 002dfbe8 00000000 ntdll!RtlInitializeExceptionChain+0xc2 Closing open log file D:\Dump\dump_22d4_2014-09-30_15-15-33-062.txt
切記:在Release版本中須要把調試選項打開,並且生成的pdb文件和exe要放在同一目錄下。
批處理安裝腳本和ntsd程序我都已經打好包了,能夠到這裏下載。