2 * Copyright (C) Volition, Inc. 1999. All rights reserved.
4 * All source code herein is the property of Volition, Inc. You may not sell
5 * or otherwise commercially exploit the source or things you created based on
10 * $Logfile: /Freespace2/code/ExceptionHandler/ExceptionHandler.cpp $
15 * Main file for dealing with exception handling
18 * Revision 1.4 2002/06/09 04:41:16 relnev
19 * added copyright header
21 * Revision 1.3 2002/05/26 20:22:48 theoddone33
22 * Most of network/ works
24 * Revision 1.2 2002/05/07 03:16:43 theoddone33
25 * The Great Newline Fix
27 * Revision 1.1.1.1 2002/05/03 03:28:08 root
31 * 1 6/29/99 7:42p Dave
33 * 3 1/19/99 9:07a Allender
34 * removed compiler warning pragma's since we are already ignoring them in
37 * 2 1/18/99 4:34p Allender
38 * added the exception handler routines from Game Developer for structured
39 * exception handling in vsdk code
44 // Copyright © 1998 Bruce Dawson.
46 This source file contains the exception handler for recording error
47 information after crashes. See exceptionhandler.h for information
59 // --------------------
63 // --------------------
65 #define SIXTYFOURK (64*ONEK)
66 #define ONEM (ONEK*ONEK)
67 #define ONEG (ONEK*ONEK*ONEK)
69 // --------------------
73 // --------------------
76 // --------------------
80 // --------------------
83 // --------------------
87 // --------------------
90 // --------------------
94 // --------------------
97 // --------------------
101 // --------------------
103 const int NumCodeBytes = 16; // Number of code bytes to record.
104 const int MaxStackDump = 2048; // Maximum number of DWORDS in stack dumps.
105 const int StackColumns = 8; // Number of columns in stack dump.
107 // --------------------
109 // Internal Functions
111 // --------------------
113 // hprintf behaves similarly to printf, with a few vital differences.
114 // It uses wvsprintf to do the formatting, which is a system routine,
115 // thus avoiding C run time interactions. For similar reasons it
116 // uses WriteFile rather than fwrite.
117 // The one limitation that this imposes is that wvsprintf, and
118 // therefore hprintf, cannot handle floating point numbers.
119 static void hprintf(HANDLE LogFile, char* Format, ...)
124 char buffer[2000]; // wvsprintf never prints more than one K.
127 va_start( arglist, Format);
128 wvsprintf(buffer, Format, arglist);
132 WriteFile(LogFile, buffer, lstrlen(buffer), &NumBytes, 0);
136 // Print the specified FILETIME to output in a human readable format,
137 // without using the C run time.
138 static void PrintTime(char *output, FILETIME TimeToPrint)
144 if (FileTimeToLocalFileTime(&TimeToPrint, &TimeToPrint) &&
145 FileTimeToDosDateTime(&TimeToPrint, &Date, &Time))
147 // What a silly way to print out the file date/time. Oh well,
148 // it works, and I'm not aware of a cleaner way to do it.
149 wsprintf(output, "%d/%d/%d %02d:%02d:%02d",
150 (Date / 32) & 15, Date & 31, (Date / 512) + 1980,
151 (Time / 2048), (Time / 32) & 63, (Time & 31) * 2);
158 // Print information about a code module (DLL or EXE) such as its size,
159 // location, time stamp, etc.
160 static void ShowModuleInfo(HANDLE LogFile, HINSTANCE ModuleHandle)
165 char ModName[MAX_PATH];
167 if (GetModuleFileName(ModuleHandle, ModName, sizeof(ModName)) > 0) {
168 // If GetModuleFileName returns greater than zero then this must
169 // be a valid code module address. Therefore we can try to walk
170 // our way through its structures to find the link time stamp.
171 IMAGE_DOS_HEADER *DosHeader = (IMAGE_DOS_HEADER*)ModuleHandle;
172 if (IMAGE_DOS_SIGNATURE != DosHeader->e_magic) {
176 IMAGE_NT_HEADERS *NTHeader = (IMAGE_NT_HEADERS*)((char *)DosHeader + DosHeader->e_lfanew);
177 if (IMAGE_NT_SIGNATURE != NTHeader->Signature) {
181 // Open the code module file so that we can get its file date
183 HANDLE ModuleFile = CreateFile(ModName, GENERIC_READ,
184 FILE_SHARE_READ, 0, OPEN_EXISTING,
185 FILE_ATTRIBUTE_NORMAL, 0);
186 char TimeBuffer[100] = "";
188 if (ModuleFile != INVALID_HANDLE_VALUE) {
189 FileSize = GetFileSize(ModuleFile, 0);
190 FILETIME LastWriteTime;
191 if (GetFileTime(ModuleFile, 0, 0, &LastWriteTime)) {
192 wsprintf(TimeBuffer, " - file date is ");
193 PrintTime(TimeBuffer + lstrlen(TimeBuffer), LastWriteTime);
195 CloseHandle(ModuleFile);
197 hprintf(LogFile, "%s, loaded at 0x%08x - %d bytes - %08x%s\r\n",
198 ModName, ModuleHandle, FileSize,
199 NTHeader->FileHeader.TimeDateStamp, TimeBuffer);
202 // Handle any exceptions by continuing from this point.
203 __except(EXCEPTION_EXECUTE_HANDLER)
209 // Scan memory looking for code modules (DLLs or EXEs). VirtualQuery is used
210 // to find all the blocks of address space that were reserved or committed,
211 // and ShowModuleInfo will display module information if they are code
214 static void RecordModuleList(HANDLE LogFile)
219 hprintf(LogFile, "\r\n"
220 "\tModule list: names, addresses, sizes, time stamps "
221 "and file times:\r\n");
222 SYSTEM_INFO SystemInfo;
223 GetSystemInfo(&SystemInfo);
224 const size_t PageSize = SystemInfo.dwPageSize;
225 // Set NumPages to the number of pages in the 4GByte address space,
226 // while being careful to avoid overflowing ints.
227 const size_t NumPages = 4 * size_t(ONEG / PageSize);
229 void *LastAllocationBase = 0;
230 while (pageNum < NumPages) {
231 MEMORY_BASIC_INFORMATION MemInfo;
232 if (VirtualQuery((void *)(pageNum * PageSize), &MemInfo, sizeof(MemInfo))) {
233 if (MemInfo.RegionSize > 0) {
235 // Adjust the page number to skip over this block of memory.
236 pageNum += MemInfo.RegionSize / PageSize;
237 if (MemInfo.State == MEM_COMMIT && MemInfo.AllocationBase > LastAllocationBase) {
238 // Look for new blocks of committed memory, and try
239 // recording their module names - this will fail
240 // gracefully if they aren't code modules.
241 LastAllocationBase = MemInfo.AllocationBase;
242 ShowModuleInfo(LogFile, (HINSTANCE)LastAllocationBase);
245 pageNum += SIXTYFOURK / PageSize;
248 // If VirtualQuery fails we advance by 64K because that is the
249 // granularity of address space doled out by VirtualAlloc().
250 pageNum += SIXTYFOURK / PageSize;
256 // Record information about the user's system, such as processor type, amount
259 static void RecordSystemInformation(HANDLE LogFile)
264 FILETIME CurrentTime;
265 GetSystemTimeAsFileTime(&CurrentTime);
266 char TimeBuffer[100];
267 PrintTime(TimeBuffer, CurrentTime);
268 hprintf(LogFile, "Error occurred at %s.\r\n", TimeBuffer);
269 char ModuleName[MAX_PATH];
270 if (GetModuleFileName(0, ModuleName, sizeof(ModuleName)) <= 0) {
271 lstrcpy(ModuleName, "Unknown");
274 DWORD UserNameSize = sizeof(UserName);
275 if (!GetUserName(UserName, &UserNameSize)) {
276 lstrcpy(UserName, "Unknown");
278 hprintf(LogFile, "%s, run by %s.\r\n", ModuleName, UserName);
280 SYSTEM_INFO SystemInfo;
281 GetSystemInfo(&SystemInfo);
282 hprintf(LogFile, "%d processor(s), type %d.\r\n",
283 SystemInfo.dwNumberOfProcessors, SystemInfo.dwProcessorType);
285 MEMORYSTATUS MemInfo;
286 MemInfo.dwLength = sizeof(MemInfo);
287 GlobalMemoryStatus(&MemInfo);
288 // Print out the amount of physical memory, rounded up.
289 hprintf(LogFile, "%d MBytes physical memory.\r\n", (MemInfo.dwTotalPhys +
294 // Translate the exception code into something human readable.
296 static const char *GetExceptionDescription(DWORD ExceptionCode)
298 struct ExceptionNames
304 ExceptionNames ExceptionMap[] =
306 {0x40010005, "a Control-C"},
307 {0x40010008, "a Control-Break"},
308 {0x80000002, "a Datatype Misalignment"},
309 {0x80000003, "a Breakpoint"},
310 {0xc0000005, "an Access Violation"},
311 {0xc0000006, "an In Page Error"},
312 {0xc0000017, "a No Memory"},
313 {0xc000001d, "an Illegal Instruction"},
314 {0xc0000025, "a Noncontinuable Exception"},
315 {0xc0000026, "an Invalid Disposition"},
316 {0xc000008c, "a Array Bounds Exceeded"},
317 {0xc000008d, "a Float Denormal Operand"},
318 {0xc000008e, "a Float Divide by Zero"},
319 {0xc000008f, "a Float Inexact Result"},
320 {0xc0000090, "a Float Invalid Operation"},
321 {0xc0000091, "a Float Overflow"},
322 {0xc0000092, "a Float Stack Check"},
323 {0xc0000093, "a Float Underflow"},
324 {0xc0000094, "an Integer Divide by Zero"},
325 {0xc0000095, "an Integer Overflow"},
326 {0xc0000096, "a Privileged Instruction"},
327 {0xc00000fD, "a Stack Overflow"},
328 {0xc0000142, "a DLL Initialization Failed"},
329 {0xe06d7363, "a Microsoft C++ Exception"},
332 for (int i = 0; i < sizeof(ExceptionMap) / sizeof(ExceptionMap[0]); i++) {
333 if (ExceptionCode == ExceptionMap[i].ExceptionCode) {
334 return ExceptionMap[i].ExceptionName;
338 return "Unknown exception type";
341 static char* GetFilePart(char *source)
343 char *result = strrchr(source, '\\');
352 // --------------------
354 // External Functions
356 // --------------------
359 // Entry point into the main exception handling routine. This routine is put into an except()
360 // statment at the beginning of a thread and is called anytime that there is a program exception
361 // The data is stored in a file called ErrorLog.txt in the data directory.
363 // data: pointer to the exception data
364 // Message: Any message that should be printed out in the error log file
369 int __cdecl RecordExceptionInfo(PEXCEPTION_POINTERS data, const char *Message)
371 static bool BeenHere = false;
373 // Going recursive! That must mean this routine crashed!
375 return EXCEPTION_CONTINUE_SEARCH;
380 char ModuleName[MAX_PATH];
381 char FileName[MAX_PATH] = "Unknown";
382 // Create a filename to record the error information to.
383 // Storing it in the executable directory works well.
384 if (GetModuleFileName(0, ModuleName, sizeof(ModuleName)) <= 0) {
388 char *FilePart = GetFilePart(ModuleName);
390 // Extract the file name portion and remove it's file extension. We'll
391 // use that name shortly.
392 lstrcpy(FileName, FilePart);
393 char *lastperiod = strrchr(FileName, '.');
398 // Replace the executable filename with our error log file name.
399 lstrcpy(FilePart, "errorlog.txt");
400 HANDLE LogFile = CreateFile(ModuleName, GENERIC_WRITE, 0, 0,
401 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, 0);
402 if (LogFile == INVALID_HANDLE_VALUE) {
403 OutputDebugString("Error creating exception report");
404 return EXCEPTION_CONTINUE_SEARCH;
407 // Append to the error log.
408 SetFilePointer(LogFile, 0, 0, FILE_END);
409 // Print out some blank lines to separate this error log from any previous ones.
410 hprintf(LogFile, "\r\n\r\n\r\n\r\n");
411 PEXCEPTION_RECORD Exception = data->ExceptionRecord;
412 PCONTEXT Context = data->ContextRecord;
414 char CrashModulePathName[MAX_PATH];
415 char *CrashModuleFileName = "Unknown";
416 MEMORY_BASIC_INFORMATION MemInfo;
417 // VirtualQuery can be used to get the allocation base associated with a
418 // code address, which is the same as the ModuleHandle. This can be used
419 // to get the filename of the module that the crash happened in.
420 if (VirtualQuery((void*)Context->Eip, &MemInfo, sizeof(MemInfo)) && GetModuleFileName((HINSTANCE)MemInfo.AllocationBase, CrashModulePathName, sizeof(CrashModulePathName)) > 0) {
421 CrashModuleFileName = GetFilePart(CrashModulePathName);
424 // Print out the beginning of the error log in a Win95 error window
425 // compatible format.
426 hprintf(LogFile, "%s caused %s in module %s at %04x:%08x.\r\n",
427 FileName, GetExceptionDescription(Exception->ExceptionCode),
428 CrashModuleFileName, Context->SegCs, Context->Eip);
429 hprintf(LogFile, "Exception handler called in %s.\r\n", Message);
430 RecordSystemInformation(LogFile);
431 // If the exception was an access violation, print out some additional
432 // information, to the error log and the debugger.
433 if (Exception->ExceptionCode == STATUS_ACCESS_VIOLATION && Exception->NumberParameters >= 2) {
434 char DebugMessage[1000];
435 const char* readwrite = "Read from";
436 if (Exception->ExceptionInformation[0]) {
437 readwrite = "Write to";
440 wsprintf(DebugMessage, "%s location %08x caused an access violation.\r\n", readwrite, Exception->ExceptionInformation[1]);
443 // The VisualC++ debugger doesn't actually tell you whether a read
444 // or a write caused the access violation, nor does it tell what
445 // address was being read or written. So I fixed that.
446 OutputDebugString("Exception handler: ");
447 OutputDebugString(DebugMessage);
450 hprintf(LogFile, "%s", DebugMessage);
453 // Print out the register values in a Win95 error window compatible format.
454 hprintf(LogFile, "\r\n");
455 hprintf(LogFile, "Registers:\r\n");
456 hprintf(LogFile, "EAX=%08x CS=%04x EIP=%08x EFLGS=%08x\r\n",
457 Context->Eax, Context->SegCs, Context->Eip, Context->EFlags);
458 hprintf(LogFile, "EBX=%08x SS=%04x ESP=%08x EBP=%08x\r\n",
459 Context->Ebx, Context->SegSs, Context->Esp, Context->Ebp);
460 hprintf(LogFile, "ECX=%08x DS=%04x ESI=%08x FS=%04x\r\n",
461 Context->Ecx, Context->SegDs, Context->Esi, Context->SegFs);
462 hprintf(LogFile, "EDX=%08x ES=%04x EDI=%08x GS=%04x\r\n",
463 Context->Edx, Context->SegEs, Context->Edi, Context->SegGs);
464 hprintf(LogFile, "Bytes at CS:EIP:\r\n");
466 // Print out the bytes of code at the instruction pointer. Since the
467 // crash may have been caused by an instruction pointer that was bad,
468 // this code needs to be wrapped in an exception handler, in case there
469 // is no memory to read. If the dereferencing of code[] fails, the
470 // exception handler will print '??'.
471 unsigned char *code = (unsigned char*)Context->Eip;
472 for (int codebyte = 0; codebyte < NumCodeBytes; codebyte++) {
474 hprintf(LogFile, "%02x ", code[codebyte]);
477 __except(EXCEPTION_EXECUTE_HANDLER) {
478 hprintf(LogFile, "?? ");
482 // Time to print part or all of the stack to the error log. This allows
483 // us to figure out the call stack, parameters, local variables, etc.
484 hprintf(LogFile, "\r\n"
487 // Esp contains the bottom of the stack, or at least the bottom of
488 // the currently used area.
489 DWORD* pStack = (DWORD *)Context->Esp;
493 // Load the top (highest address) of the stack from the
494 // thread information block. It will be found there in
495 // Win9x and Windows NT.
499 if (pStackTop > pStack + MaxStackDump) {
500 pStackTop = pStack + MaxStackDump;
504 // Too many calls to WriteFile can take a long time, causing
505 // confusing delays when programs crash. Therefore I implemented
506 // simple buffering for the stack dumping code instead of calling
508 char buffer[1000] = "";
509 const int safetyzone = 50;
510 char* nearend = buffer + sizeof(buffer) - safetyzone;
511 char* output = buffer;
512 while (pStack + 1 <= pStackTop) {
513 if ((Count % StackColumns) == 0) {
514 output += wsprintf(output, "%08x: ", pStack);
518 if ((++Count % StackColumns) == 0 || pStack + 2 > pStackTop) {
522 output += wsprintf(output, "%08x%s", *pStack, Suffix);
524 // Check for when the buffer is almost full, and flush it to disk.
525 if (output > nearend) {
526 hprintf(LogFile, "%s", buffer);
531 // Print out any final characters from the cache.
532 hprintf(LogFile, "%s", buffer);
534 __except(EXCEPTION_EXECUTE_HANDLER) {
535 hprintf(LogFile, "Exception encountered during stack dump.\r\n");
538 RecordModuleList(LogFile);
540 CloseHandle(LogFile);
541 // Return the magic value which tells Win32 that this handler didn't
542 // actually handle the exception - so that things will proceed as per
544 return EXCEPTION_CONTINUE_SEARCH;