]> icculus.org git repositories - taylor/freespace2.git/blob - src/exceptionhandler/exceptionhandler.cpp
added copyright header
[taylor/freespace2.git] / src / exceptionhandler / exceptionhandler.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
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
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/ExceptionHandler/ExceptionHandler.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Main file for dealing with exception handling
16  *
17  * $Log$
18  * Revision 1.4  2002/06/09 04:41:16  relnev
19  * added copyright header
20  *
21  * Revision 1.3  2002/05/26 20:22:48  theoddone33
22  * Most of network/ works
23  *
24  * Revision 1.2  2002/05/07 03:16:43  theoddone33
25  * The Great Newline Fix
26  *
27  * Revision 1.1.1.1  2002/05/03 03:28:08  root
28  * Initial import.
29  *
30  * 
31  * 1     6/29/99 7:42p Dave
32  * 
33  * 3     1/19/99 9:07a Allender
34  * removed compiler warning pragma's since we are already ignoring them in
35  * vtypes.h
36  * 
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
40  *
41  * $NoKeywords: $
42  */
43
44 // Copyright © 1998 Bruce Dawson.
45 /*
46 This source file contains the exception handler for recording error
47 information after crashes. See exceptionhandler.h for information
48 on how to hook it in.
49 */
50
51
52 #ifndef PLAT_UNIX
53 #include <windows.h>
54 #else
55 #include <stdarg.h>
56 #include "pstypes.h"
57 #endif
58
59 // --------------------
60 //
61 // Defines
62 //
63 // --------------------
64 #define ONEK                    1024
65 #define SIXTYFOURK              (64*ONEK)
66 #define ONEM                    (ONEK*ONEK)
67 #define ONEG                    (ONEK*ONEK*ONEK) 
68
69 // --------------------
70 //
71 // Enumerated Types
72 //
73 // --------------------
74
75
76 // --------------------
77 //
78 // Structures
79 //
80 // --------------------
81
82
83 // --------------------
84 //
85 // Classes
86 //
87 // --------------------
88
89
90 // --------------------
91 //
92 // Global Variables
93 //
94 // --------------------
95
96
97 // --------------------
98 //
99 // Local Variables
100 //
101 // --------------------
102
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.
106
107 // --------------------
108 //
109 // Internal Functions
110 //
111 // --------------------
112
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, ...)
120 {
121 #ifdef PLAT_UNIX
122         STUB_FUNCTION;
123 #else
124         char buffer[2000];      // wvsprintf never prints more than one K.
125
126         va_list arglist;
127         va_start( arglist, Format);
128         wvsprintf(buffer, Format, arglist);
129         va_end( arglist);
130
131         DWORD NumBytes;
132         WriteFile(LogFile, buffer, lstrlen(buffer), &NumBytes, 0);
133 #endif
134 }
135
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)
139 {
140 #ifdef PLAT_UNIX
141         STUB_FUNCTION;
142 #else
143         WORD Date, Time;
144         if (FileTimeToLocalFileTime(&TimeToPrint, &TimeToPrint) &&
145                                 FileTimeToDosDateTime(&TimeToPrint, &Date, &Time))
146         {
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);
152         } else {
153                 output[0] = 0;
154         }
155 #endif
156 }
157
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)
161 {
162 #ifdef PLAT_UNIX
163         STUB_FUNCTION;
164 #else
165         char ModName[MAX_PATH];
166         __try {
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) {
173                     return;
174                         }
175
176                         IMAGE_NT_HEADERS *NTHeader = (IMAGE_NT_HEADERS*)((char *)DosHeader + DosHeader->e_lfanew);
177                         if (IMAGE_NT_SIGNATURE != NTHeader->Signature) {
178                     return;
179                         }
180
181                         // Open the code module file so that we can get its file date
182                         // and size.
183                         HANDLE ModuleFile = CreateFile(ModName, GENERIC_READ, 
184                                                 FILE_SHARE_READ, 0, OPEN_EXISTING,
185                                                 FILE_ATTRIBUTE_NORMAL, 0);
186                         char TimeBuffer[100] = "";
187                         DWORD FileSize = 0;
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);
194                                 }
195                                 CloseHandle(ModuleFile);
196                         }
197                         hprintf(LogFile, "%s, loaded at 0x%08x - %d bytes - %08x%s\r\n",
198                                                 ModName, ModuleHandle, FileSize,
199                                                 NTHeader->FileHeader.TimeDateStamp, TimeBuffer);
200                 }
201         }
202         // Handle any exceptions by continuing from this point.
203         __except(EXCEPTION_EXECUTE_HANDLER)
204         {
205         }
206 #endif
207 }
208
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
212 // modules.
213
214 static void RecordModuleList(HANDLE LogFile)
215 {
216 #ifdef PLAT_UNIX
217         STUB_FUNCTION;
218 #else
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);
228         size_t pageNum = 0;
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) {
234
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);
243                                 }
244                         } else {
245                                 pageNum += SIXTYFOURK / PageSize;
246                         }
247                 } else {
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;
251                 }
252         }
253 #endif
254 }
255
256 // Record information about the user's system, such as processor type, amount
257 // of memory, etc.
258
259 static void RecordSystemInformation(HANDLE LogFile)
260 {
261 #ifdef PLAT_UNIX
262         STUB_FUNCTION;
263 #else
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");
272         }
273         char    UserName[200];
274         DWORD UserNameSize = sizeof(UserName);
275         if (!GetUserName(UserName, &UserNameSize)) {
276                 lstrcpy(UserName, "Unknown");
277         }
278         hprintf(LogFile, "%s, run by %s.\r\n", ModuleName, UserName);
279
280         SYSTEM_INFO     SystemInfo;
281         GetSystemInfo(&SystemInfo);
282         hprintf(LogFile, "%d processor(s), type %d.\r\n",
283                                 SystemInfo.dwNumberOfProcessors, SystemInfo.dwProcessorType);
284
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 +
290                                 ONEM - 1) / ONEM);
291 #endif
292 }
293
294 // Translate the exception code into something human readable.
295
296 static const char *GetExceptionDescription(DWORD ExceptionCode)
297 {
298         struct ExceptionNames
299         {
300                 DWORD   ExceptionCode;
301                 char*   ExceptionName;
302         };
303
304         ExceptionNames ExceptionMap[] =
305         {
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"},
330         };
331
332         for (int i = 0; i < sizeof(ExceptionMap) / sizeof(ExceptionMap[0]); i++) {
333                 if (ExceptionCode == ExceptionMap[i].ExceptionCode) {
334                         return ExceptionMap[i].ExceptionName;
335                 }
336         }
337
338         return "Unknown exception type";
339 }
340
341 static char* GetFilePart(char *source)
342 {
343         char *result = strrchr(source, '\\');
344         if (result) {
345                 result++;
346         } else {
347                 result = source;
348         }
349         return result;
350 }
351
352 // --------------------
353 //
354 // External Functions
355 //
356 // --------------------
357
358
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.
362 //
363 // data:                        pointer to the exception data
364 // Message:             Any message     that should be printed out in the error log file
365 //
366 // returns: 
367 //
368 #ifndef PLAT_UNIX
369 int __cdecl RecordExceptionInfo(PEXCEPTION_POINTERS data, const char *Message)
370 {
371         static bool BeenHere = false;
372
373         // Going recursive! That must mean this routine crashed!
374         if (BeenHere) {
375                 return EXCEPTION_CONTINUE_SEARCH;
376         }
377
378         BeenHere = true;
379
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) {
385                 ModuleName[0] = 0;
386         }
387
388         char *FilePart = GetFilePart(ModuleName);
389
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, '.');
394         if (lastperiod) {
395                 lastperiod[0] = 0;
396         }
397
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;
405         }
406
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;
413
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);
422         }
423
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";
438                 }
439
440                 wsprintf(DebugMessage, "%s location %08x caused an access violation.\r\n", readwrite, Exception->ExceptionInformation[1]);
441
442 #ifdef  _DEBUG
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);
448 #endif
449
450                 hprintf(LogFile, "%s", DebugMessage);
451         }
452
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");
465
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++) {
473                 __try {
474                         hprintf(LogFile, "%02x ", code[codebyte]);
475
476                 }
477                 __except(EXCEPTION_EXECUTE_HANDLER) {
478                         hprintf(LogFile, "?? ");
479                 }
480         }
481
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"
485                                          "Stack dump:\r\n");
486         __try {
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;
490                 DWORD* pStackTop;
491                 __asm
492                 {
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.
496                         mov     eax, fs:[4]
497                         mov pStackTop, eax
498                 }
499                 if (pStackTop > pStack + MaxStackDump) {
500                         pStackTop = pStack + MaxStackDump;
501                 }
502
503                 int Count = 0;
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
507                 // hprintf directly.
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);
515                         }
516
517                         char *Suffix = " ";
518                         if ((++Count % StackColumns) == 0 || pStack + 2 > pStackTop) {
519                                 Suffix = "\r\n";
520                         }
521
522                         output += wsprintf(output, "%08x%s", *pStack, Suffix);
523                         pStack++;
524                         // Check for when the buffer is almost full, and flush it to disk.
525                         if (output > nearend) {
526                                 hprintf(LogFile, "%s", buffer);
527                                 buffer[0] = 0;
528                                 output = buffer;
529                         }
530                 }
531                 // Print out any final characters from the cache.
532                 hprintf(LogFile, "%s", buffer);
533         }
534         __except(EXCEPTION_EXECUTE_HANDLER) {
535                 hprintf(LogFile, "Exception encountered during stack dump.\r\n");
536         }
537
538         RecordModuleList(LogFile);
539
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
543         // normal.
544         return EXCEPTION_CONTINUE_SEARCH;
545 }
546 #endif
547