DumpException.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // ExceptionHandler.cpp Version 1.5
  2. //
  3. // Copyright 1998 Bruce Dawson
  4. //
  5. // This source file contains the exception handler for recording error
  6. // information after crashes. See ExceptionHandler.h for information
  7. // on how to hook it in.
  8. //
  9. // Author: Bruce Dawson
  10. // brucedawson@cygnus-software.com
  11. //
  12. // Latest Modified by: Xiel
  13. //
  14. // Modified by: Hans Dietrich
  15. // hdietrich2@hotmail.com
  16. //
  17. // Version 1.5 - remove TChar support, change log file's name
  18. // Version 1.4: - Added invocation of XCrashReport.exe
  19. //
  20. // Version 1.3: - Added minidump output
  21. //
  22. // Version 1.1: - reformatted output for XP-like error report
  23. // - added ascii output to stack dump
  24. //
  25. // A paper by the original author can be found at:
  26. // http://www.cygnus-software.com/papers/release_debugging.html
  27. //
  28. ///////////////////////////////////////////////////////////////////////////////
  29. // Disable warnings generated by the Windows header files.
  30. #pragma warning(disable : 4514)
  31. #pragma warning(disable : 4201)
  32. #include "precompile.h"
  33. #include "DumpException.h"
  34. #include <dbghelp.h>
  35. #include "modCheck.h"
  36. const int NumCodeBytes = 16; // Number of code bytes to record.
  37. const int MaxStackDump = 3072; // Maximum number of DWORDS in stack dumps.
  38. const int StackColumns = 4; // Number of columns in stack dump.
  39. #define ONEK 1024
  40. #define SIXTYFOURK (64*ONEK)
  41. #define ONEM (ONEK*ONEK)
  42. #define ONEG (ONEK*ONEK*ONEK)
  43. ///////////////////////////////////////////////////////////////////////////////
  44. // lstrrchr (avoid the C Runtime )
  45. static CHAR * lstrrchr(LPCSTR string, int ch)
  46. {
  47. CHAR *start = (CHAR *)string;
  48. while (*string++) /* find end of string */
  49. ;
  50. /* search towards front */
  51. while (--string != start && *string != (CHAR) ch)
  52. ;
  53. if (*string == (CHAR) ch) /* char found ? */
  54. return (CHAR *)string;
  55. return NULL;
  56. }
  57. ///////////////////////////////////////////////////////////////////////////////
  58. // hflush
  59. static void hflush(HANDLE LogFile)
  60. {
  61. if (toolkit_getResource()->hprintf_index > 0)
  62. {
  63. DWORD NumBytes;
  64. WriteFile(LogFile, toolkit_getResource()->hprintf_buffer, lstrlenA(toolkit_getResource()->hprintf_buffer), &NumBytes, 0);
  65. toolkit_getResource()->hprintf_index = 0;
  66. }
  67. }
  68. ///////////////////////////////////////////////////////////////////////////////
  69. // hprintf
  70. static void hprintf(HANDLE LogFile, LPCSTR Format, ...)
  71. {
  72. va_list arglist;
  73. if (toolkit_getResource()->hprintf_index > (HPRINTF_BUFFER_SIZE-1024))
  74. {
  75. DWORD NumBytes;
  76. WriteFile(LogFile, toolkit_getResource()->hprintf_buffer, lstrlenA(toolkit_getResource()->hprintf_buffer), &NumBytes, 0);
  77. toolkit_getResource()->hprintf_index = 0;
  78. }
  79. va_start( arglist, Format);
  80. toolkit_getResource()->hprintf_index += wvsprintfA(&(toolkit_getResource()->hprintf_buffer[toolkit_getResource()->hprintf_index]), Format, arglist);
  81. va_end( arglist);
  82. }
  83. ///////////////////////////////////////////////////////////////////////////////
  84. // FormatTime
  85. //
  86. // Format the specified FILETIME to output in a human readable format,
  87. // without using the C run time.
  88. static void FormatTime(LPSTR output, FILETIME TimeToPrint)
  89. {
  90. WORD Date, Time;
  91. output[0] = '\0';
  92. if (FileTimeToLocalFileTime(&TimeToPrint, &TimeToPrint) &&
  93. FileTimeToDosDateTime(&TimeToPrint, &Date, &Time))
  94. {
  95. wsprintfA(output, "%d/%d/%d %02d:%02d:%02d",
  96. (Date / 32) & 15, Date & 31, (Date / 512) + 1980,
  97. (Time >> 11), (Time >> 5) & 0x3F, (Time & 0x1F) * 2);
  98. }
  99. }
  100. ///////////////////////////////////////////////////////////////////////////////
  101. // DumpModuleInfo
  102. //
  103. // Print information about a code module (DLL or EXE) such as its size,
  104. // location, time stamp, etc.
  105. static BOOL DumpModuleInfo(HANDLE LogFile, HINSTANCE ModuleHandle, int nModuleNo)
  106. {
  107. BOOL rc = FALSE;
  108. CHAR szModName[MAX_PATH*2];
  109. ZeroMemory(szModName, sizeof(szModName));
  110. __try
  111. {
  112. if (GetModuleFileNameA(ModuleHandle, szModName, sizeof(szModName)-2) > 0)
  113. {
  114. IMAGE_NT_HEADERS *NTHeader;
  115. IMAGE_DOS_HEADER *DosHeader;
  116. HANDLE ModuleFile;
  117. CHAR TimeBuffer[100];
  118. DWORD FileSize = 0;
  119. // If GetModuleFileName returns greater than zero then this must
  120. // be a valid code module address. Therefore we can try to walk
  121. // our way through its structures to find the link time stamp.
  122. DosHeader = (IMAGE_DOS_HEADER*)ModuleHandle;
  123. if (IMAGE_DOS_SIGNATURE != DosHeader->e_magic)
  124. return FALSE;
  125. NTHeader = (IMAGE_NT_HEADERS*)((CHAR *)DosHeader
  126. + DosHeader->e_lfanew);
  127. if (IMAGE_NT_SIGNATURE != NTHeader->Signature)
  128. return FALSE;
  129. // open the code module file so that we can get its file date and size
  130. ModuleFile = CreateFileA(szModName, GENERIC_READ,
  131. FILE_SHARE_READ, 0, OPEN_EXISTING,
  132. FILE_ATTRIBUTE_NORMAL, 0);
  133. TimeBuffer[0] = '\0';
  134. if (ModuleFile != INVALID_HANDLE_VALUE)
  135. {
  136. FILETIME LastWriteTime;
  137. FileSize = GetFileSize(ModuleFile, 0);
  138. if (GetFileTime(ModuleFile, 0, 0, &LastWriteTime))
  139. {
  140. FormatTime(TimeBuffer, LastWriteTime);
  141. }
  142. CloseHandle(ModuleFile);
  143. }
  144. hprintf(LogFile, "Module %d\r\n", nModuleNo);
  145. hprintf(LogFile, "%s\r\n", szModName);
  146. hprintf(LogFile, "Image Base: 0x%08x Image Size: 0x%08x\r\n",
  147. NTHeader->OptionalHeader.ImageBase,
  148. NTHeader->OptionalHeader.SizeOfImage),
  149. hprintf(LogFile, "Checksum: 0x%08x Time Stamp: 0x%08x\r\n",
  150. NTHeader->OptionalHeader.CheckSum,
  151. NTHeader->FileHeader.TimeDateStamp);
  152. hprintf(LogFile, "File Size: %-10d File Time: %s\r\n",
  153. FileSize, TimeBuffer);
  154. hprintf(LogFile, "Version Information:\r\n");
  155. hprintf(LogFile, "\r\n");
  156. rc = TRUE;
  157. }
  158. }
  159. // Handle any exceptions by continuing from this point.
  160. __except(EXCEPTION_EXECUTE_HANDLER)
  161. {
  162. }
  163. return rc;
  164. }
  165. ///////////////////////////////////////////////////////////////////////////////
  166. // DumpModuleList
  167. //
  168. // Scan memory looking for code modules (DLLs or EXEs). VirtualQuery is used
  169. // to find all the blocks of address space that were reserved or committed,
  170. // and ShowModuleInfo will display module information if they are code
  171. // modules.
  172. static void DumpModuleList(HANDLE LogFile)
  173. {
  174. size_t pageNum;
  175. size_t NumPages;
  176. size_t PageSize;
  177. void *LastAllocationBase;
  178. SYSTEM_INFO SystemInfo;
  179. int nModuleNo;
  180. GetSystemInfo(&SystemInfo);
  181. PageSize = SystemInfo.dwPageSize;
  182. // Set NumPages to the number of pages in the 4GByte address space,
  183. // while being careful to avoid overflowing ints
  184. NumPages = 4 * ((size_t)(ONEG / PageSize));
  185. pageNum = 0;
  186. LastAllocationBase = 0;
  187. nModuleNo = 1;
  188. while (pageNum < NumPages)
  189. {
  190. MEMORY_BASIC_INFORMATION MemInfo;
  191. if (VirtualQuery((void *)(pageNum * PageSize), &MemInfo,
  192. sizeof(MemInfo)))
  193. {
  194. if (MemInfo.RegionSize > 0)
  195. {
  196. // Adjust the page number to skip over this block of memory
  197. pageNum += MemInfo.RegionSize / PageSize;
  198. if (MemInfo.State == MEM_COMMIT && MemInfo.AllocationBase >
  199. LastAllocationBase)
  200. {
  201. // Look for new blocks of committed memory, and try
  202. // recording their module names - this will fail
  203. // gracefully if they aren't code modules
  204. LastAllocationBase = MemInfo.AllocationBase;
  205. if (DumpModuleInfo(LogFile,
  206. (HINSTANCE)LastAllocationBase,
  207. nModuleNo))
  208. {
  209. nModuleNo++;
  210. }
  211. }
  212. }
  213. else
  214. pageNum += SIXTYFOURK / PageSize;
  215. }
  216. else
  217. pageNum += SIXTYFOURK / PageSize;
  218. // If VirtualQuery fails we advance by 64K because that is the
  219. // granularity of address space doled out by VirtualAlloc()
  220. }
  221. }
  222. ///////////////////////////////////////////////////////////////////////////////
  223. // DumpSystemInformation
  224. //
  225. // Record information about the user's system, such as processor type, amount
  226. // of memory, etc.
  227. static void DumpSystemInformation(HANDLE LogFile)
  228. {
  229. FILETIME CurrentTime;
  230. CHAR szTimeBuffer[100];
  231. CHAR szUserName[200];
  232. long crashID;
  233. DWORD UserNameSize;
  234. SYSTEM_INFO SystemInfo;
  235. CHAR szModuleName[MAX_PATH*2];
  236. MEMORYSTATUS MemInfo;;
  237. GetSystemTimeAsFileTime(&CurrentTime);
  238. FormatTime(szTimeBuffer, CurrentTime);
  239. crashID = CurrentTime.dwLowDateTime;
  240. ZeroMemory(toolkit_getResource()->szCrashID, sizeof(toolkit_getResource()->szCrashID));
  241. _ltoa_s( crashID, toolkit_getResource()->szCrashID, 20, 16 );
  242. hprintf(LogFile, "\r\nCRASH REFERENCE CODE: %s\r\n\r\n", toolkit_getResource()->szCrashID );
  243. hprintf(LogFile, "Error occurred at %s.\r\n", szTimeBuffer);
  244. ZeroMemory(szModuleName, sizeof(szModuleName));
  245. if (GetModuleFileNameA(0, szModuleName, _countof(szModuleName)-2) <= 0)
  246. lstrcpyA(szModuleName, "Unknown");
  247. ZeroMemory(szUserName, sizeof(szUserName));
  248. UserNameSize = _countof(szUserName)-2;
  249. if (!GetUserNameA(szUserName, &UserNameSize))
  250. lstrcpyA(szUserName, "Unknown");
  251. hprintf(LogFile, "%s, run by %s.\r\n", szModuleName, szUserName);
  252. GetSystemInfo(&SystemInfo);
  253. hprintf(LogFile, "%d processor(s), type %d.\r\n",
  254. SystemInfo.dwNumberOfProcessors, SystemInfo.dwProcessorType);
  255. MemInfo.dwLength = sizeof(MemInfo);
  256. GlobalMemoryStatus(&MemInfo);
  257. // Print out info on memory, rounded up.
  258. hprintf(LogFile, "%d%% memory in use.\r\n", MemInfo.dwMemoryLoad);
  259. hprintf(LogFile, "%d MBytes physical memory.\r\n", (MemInfo.dwTotalPhys +
  260. ONEM - 1) / ONEM);
  261. hprintf(LogFile, "%d MBytes physical memory free.\r\n",
  262. (MemInfo.dwAvailPhys + ONEM - 1) / ONEM);
  263. hprintf(LogFile, "%d MBytes paging file.\r\n", (MemInfo.dwTotalPageFile +
  264. ONEM - 1) / ONEM);
  265. hprintf(LogFile, "%d MBytes paging file free.\r\n",
  266. (MemInfo.dwAvailPageFile + ONEM - 1) / ONEM);
  267. hprintf(LogFile, "%d MBytes user address space.\r\n",
  268. (MemInfo.dwTotalVirtual + ONEM - 1) / ONEM);
  269. hprintf(LogFile, "%d MBytes user address space free.\r\n",
  270. (MemInfo.dwAvailVirtual + ONEM - 1) / ONEM);
  271. }
  272. ///////////////////////////////////////////////////////////////////////////////
  273. // GetExceptionDescription
  274. //
  275. // Translate the exception code into something human readable
  276. static const CHAR *GetExceptionDescription(DWORD ExceptionCode)
  277. {
  278. int i;
  279. struct ExceptionNames
  280. {
  281. DWORD ExceptionCode;
  282. CHAR * ExceptionName;
  283. };
  284. struct ExceptionNames ExceptionMap[] =
  285. {
  286. {0x40010005, "a Control-C"},
  287. {0x40010008, "a Control-Break"},
  288. {0x80000002, "a Datatype Misalignment"},
  289. {0x80000003, "a Breakpoint"},
  290. {0xc0000005, "an Access Violation"},
  291. {0xc0000006, "an In Page Error"},
  292. {0xc0000017, "a No Memory"},
  293. {0xc000001d, "an Illegal Instruction"},
  294. {0xc0000025, "a Noncontinuable Exception"},
  295. {0xc0000026, "an Invalid Disposition"},
  296. {0xc000008c, "a Array Bounds Exceeded"},
  297. {0xc000008d, "a Float Denormal Operand"},
  298. {0xc000008e, "a Float Divide by Zero"},
  299. {0xc000008f, "a Float Inexact Result"},
  300. {0xc0000090, "a Float Invalid Operation"},
  301. {0xc0000091, "a Float Overflow"},
  302. {0xc0000092, "a Float Stack Check"},
  303. {0xc0000093, "a Float Underflow"},
  304. {0xc0000094, "an Integer Divide by Zero"},
  305. {0xc0000095, "an Integer Overflow"},
  306. {0xc0000096, "a Privileged Instruction"},
  307. {0xc00000fD, "a Stack Overflow"},
  308. {0xc0000142, "a DLL Initialization Failed"},
  309. {0xe06d7363, "a Microsoft C++ Exception"},
  310. };
  311. for (i = 0; i < sizeof(ExceptionMap) / sizeof(ExceptionMap[0]); i++)
  312. if (ExceptionCode == ExceptionMap[i].ExceptionCode)
  313. return ExceptionMap[i].ExceptionName;
  314. return "an Unknown exception type";
  315. }
  316. ///////////////////////////////////////////////////////////////////////////////
  317. // GetFilePart
  318. static CHAR * GetFilePart(LPCSTR source)
  319. {
  320. CHAR *result = lstrrchr(source, '\\');
  321. if (result)
  322. result++;
  323. else
  324. result = (CHAR *)source;
  325. return result;
  326. }
  327. ///////////////////////////////////////////////////////////////////////////////
  328. // DumpStack
  329. static void DumpStack(HANDLE LogFile, DWORD *pStack)
  330. {
  331. hprintf(LogFile, "\r\n\r\nStack:\r\n");
  332. __try
  333. {
  334. // Esp contains the bottom of the stack, or at least the bottom of
  335. // the currently used area.
  336. DWORD* pStackTop;
  337. DWORD* pStackStart;
  338. int Count;
  339. int nDwordsPrinted;
  340. __asm
  341. {
  342. // Load the top (highest address) of the stack from the
  343. // thread information block. It will be found there in
  344. // Win9x and Windows NT.
  345. mov eax, fs:[4]
  346. mov pStackTop, eax
  347. }
  348. if (pStackTop > pStack + MaxStackDump)
  349. pStackTop = pStack + MaxStackDump;
  350. Count = 0;
  351. pStackStart = pStack;
  352. nDwordsPrinted = 0;
  353. while (pStack + 1 <= pStackTop)
  354. {
  355. if ((Count % StackColumns) == 0)
  356. {
  357. pStackStart = pStack;
  358. nDwordsPrinted = 0;
  359. hprintf(LogFile, "0x%08x: ", pStack);
  360. }
  361. if ((++Count % StackColumns) == 0 || pStack + 2 > pStackTop)
  362. {
  363. int n, i;
  364. hprintf(LogFile, "%08x ", *pStack);
  365. nDwordsPrinted++;
  366. n = nDwordsPrinted;
  367. while (n < 4)
  368. {
  369. hprintf(LogFile, " ");
  370. n++;
  371. }
  372. for (i = 0; i < nDwordsPrinted; i++)
  373. {
  374. int j;
  375. DWORD dwStack = *pStackStart;
  376. for (j = 0; j < 4; j++)
  377. {
  378. char c = (char)(dwStack & 0xFF);
  379. if (c < 0x20 || c > 0x7E)
  380. c = '.';
  381. hprintf(LogFile, "%c", c);
  382. dwStack = dwStack >> 8;
  383. }
  384. pStackStart++;
  385. }
  386. hprintf(LogFile, "\r\n");
  387. }
  388. else
  389. {
  390. hprintf(LogFile, "%08x ", *pStack);
  391. nDwordsPrinted++;
  392. }
  393. pStack++;
  394. }
  395. hprintf(LogFile, "\r\n");
  396. }
  397. __except(EXCEPTION_EXECUTE_HANDLER)
  398. {
  399. hprintf(LogFile, "Exception encountered during stack dump.\r\n");
  400. }
  401. }
  402. ///////////////////////////////////////////////////////////////////////////////
  403. // DumpRegisters
  404. static void DumpRegisters(HANDLE LogFile, PCONTEXT Context)
  405. {
  406. // Print out the register values in an XP error window compatible format.
  407. hprintf(LogFile, "\r\n");
  408. hprintf(LogFile, "Context:\r\n");
  409. hprintf(LogFile, "EDI: 0x%08x ESI: 0x%08x EAX: 0x%08x\r\n",
  410. Context->Edi, Context->Esi, Context->Eax);
  411. hprintf(LogFile, "EBX: 0x%08x ECX: 0x%08x EDX: 0x%08x\r\n",
  412. Context->Ebx, Context->Ecx, Context->Edx);
  413. hprintf(LogFile, "EIP: 0x%08x EBP: 0x%08x SegCs: 0x%08x\r\n",
  414. Context->Eip, Context->Ebp, Context->SegCs);
  415. hprintf(LogFile, "EFlags: 0x%08x ESP: 0x%08x SegSs: 0x%08x\r\n",
  416. Context->EFlags, Context->Esp, Context->SegSs);
  417. }
  418. ///////////////////////////////////////////////////////////////////////////////
  419. ///////////////////////////////////////////////////////////////////////////////
  420. //
  421. // RecordExceptionInfo
  422. //
  423. ///////////////////////////////////////////////////////////////////////////////
  424. ///////////////////////////////////////////////////////////////////////////////
  425. TOOLKIT_API int __cdecl DumpExceptionInfo(PEXCEPTION_POINTERS pExceptPtrs, HANDLE hLogFile)
  426. {
  427. PEXCEPTION_RECORD Exception = pExceptPtrs->ExceptionRecord;
  428. PCONTEXT Context = pExceptPtrs->ContextRecord;
  429. CHAR *pszCrashModuleFileName;
  430. CHAR szCrashModulePathName[MAX_PATH*2];
  431. MEMORY_BASIC_INFORMATION MemInfo;
  432. BYTE * code;
  433. int codebyte;
  434. DWORD* pStack;
  435. ZeroMemory(szCrashModulePathName, sizeof(szCrashModulePathName));
  436. pszCrashModuleFileName = "Unknown";
  437. // VirtualQuery can be used to get the allocation base associated with a
  438. // code address, which is the same as the ModuleHandle. This can be used
  439. // to get the filename of the module that the crash happened in.
  440. if (VirtualQuery((void*)Context->Eip, &MemInfo, sizeof(MemInfo)) &&
  441. (GetModuleFileNameA((HINSTANCE)MemInfo.AllocationBase,
  442. szCrashModulePathName,
  443. sizeof(szCrashModulePathName)-2) > 0))
  444. {
  445. pszCrashModuleFileName = GetFilePart(szCrashModulePathName);
  446. }
  447. // Print out the beginning of the error log in a Win95 error window
  448. // compatible format.
  449. hprintf(hLogFile, "caused %s (0x%08x) \r\nin module %s at %04x:%08x.\r\n\r\n",
  450. GetExceptionDescription(Exception->ExceptionCode),
  451. Exception->ExceptionCode,
  452. pszCrashModuleFileName, Context->SegCs, Context->Eip);
  453. hprintf(hLogFile, "Exception handler called.\r\n");
  454. DumpSystemInformation(hLogFile);
  455. // If the exception was an access violation, print out some additional
  456. // information, to the error log and the debugger.
  457. if (Exception->ExceptionCode == STATUS_ACCESS_VIOLATION &&
  458. Exception->NumberParameters >= 2)
  459. {
  460. CHAR szDebugMessage[1000];
  461. const CHAR* readwrite = "Read from";
  462. if (Exception->ExceptionInformation[0])
  463. readwrite = "Write to";
  464. wsprintfA(szDebugMessage, "%s location %08x caused an access violation.\r\n",
  465. readwrite, Exception->ExceptionInformation[1]);
  466. hprintf(hLogFile, "%s", szDebugMessage);
  467. }
  468. DumpRegisters(hLogFile, Context);
  469. // Print out the bytes of code at the instruction pointer. Since the
  470. // crash may have been caused by an instruction pointer that was bad,
  471. // this code needs to be wrapped in an exception handler, in case there
  472. // is no memory to read. If the dereferencing of code[] fails, the
  473. // exception handler will print '??'.
  474. hprintf(hLogFile, "\r\nBytes at CS:EIP:\r\n");
  475. code = (BYTE *)Context->Eip;
  476. for (codebyte = 0; codebyte < NumCodeBytes; codebyte++)
  477. {
  478. __try
  479. {
  480. hprintf(hLogFile, "%02x ", code[codebyte]);
  481. }
  482. __except(EXCEPTION_EXECUTE_HANDLER)
  483. {
  484. hprintf(hLogFile, "?? ");
  485. }
  486. }
  487. // Time to print part or all of the stack to the error log. This allows
  488. // us to figure out the call stack, parameters, local variables, etc.
  489. // Esp contains the bottom of the stack, or at least the bottom of
  490. // the currently used area
  491. pStack = (DWORD *)Context->Esp;
  492. DumpStack(hLogFile, pStack);
  493. DumpModuleList(hLogFile);
  494. hflush(hLogFile);
  495. return EXCEPTION_EXECUTE_HANDLER;
  496. }