/
i_crash.cpp
3353 lines (2987 loc) · 90.9 KB
/
i_crash.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** i_crash.cpp
** Gathers exception information when the program crashes.
**
**---------------------------------------------------------------------------
** Copyright 2002-2006 Randy Heit
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
** 1. Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** 2. Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** 3. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.s
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
// HEADER FILES ------------------------------------------------------------
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <winnt.h>
#include <richedit.h>
#include <winuser.h>
#include <tlhelp32.h>
#ifndef _M_IX86
#include <winternl.h>
#endif
#ifndef __GNUC__
#if _MSC_VER
#pragma warning(disable:4091) // this silences a warning for a bogus definition in the Windows 8.1 SDK.
#endif
#include <dbghelp.h>
#if _MSC_VER
#pragma warning(default:4091)
#endif
#endif
#include <commctrl.h>
#include <commdlg.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <setupapi.h>
#include <uxtheme.h>
#include <shellapi.h>
#include <uxtheme.h>
#include <stddef.h>
#define USE_WINDOWS_DWORD
#include "doomtype.h"
#include "resource.h"
#include "version.h"
#include "m_swap.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <zlib.h>
// MACROS ------------------------------------------------------------------
#define REMOTE_HOST "localhost"
#define REMOTE_PORT "80"
#define UPLOAD_URI "/test.php"
#define UPLOAD_BOUNDARY "Von-DnrNbJl0 P9d_BD;cEEsQVWpYMq0pbZ6NUmYHus;yIbFbkgB?.N=YC5O=BGZm+Rab5"
#define DBGHELP_URI "/msredist/dbghelp.dl_"
#define UPLOAD_AGENT GAMENAME "/" VERSIONSTR " (" GAMESIG ")"
// Time, in milliseconds, to wait for a send() or recv() to complete.
#define TIMEOUT 60000
// Maximum number of files that might appear in a crash report.
#define MAX_FILES 5
#ifndef __BIG_ENDIAN__
#define MAKE_ID(a,b,c,d) ((a)|((b)<<8)|((c)<<16)|((d)<<24))
#else
#define MAKE_ID(a,b,c,d) ((d)|((c)<<8)|((b)<<16)|((a)<<24))
#endif
#define ZIP_LOCALFILE MAKE_ID('P','K',3,4)
#define ZIP_CENTRALFILE MAKE_ID('P','K',1,2)
#define ZIP_ENDOFDIR MAKE_ID('P','K',5,6)
// DBGHELP.H ---------------------------------------------------------------
// w32api does not include dbghelp.h, so if I don't include these here,
// a person using GCC will need to download the Platform SDK, grab dbghelp.h
// from it, and edit it so it works with GCC.
#ifdef __GNUC__
typedef enum _MINIDUMP_TYPE
{
MiniDumpNormal
// Other types omitted.
} MINIDUMP_TYPE;
typedef struct _MINIDUMP_EXCEPTION_INFORMATION {
DWORD ThreadId;
PEXCEPTION_POINTERS ExceptionPointers;
BOOL ClientPointers;
} MINIDUMP_EXCEPTION_INFORMATION, *PMINIDUMP_EXCEPTION_INFORMATION;
typedef struct _MINIDUMP_USER_STREAM_INFORMATION {
ULONG UserStreamCount;
void *UserStreamArray; // Not really void *
} MINIDUMP_USER_STREAM_INFORMATION, *PMINIDUMP_USER_STREAM_INFORMATION;
typedef BOOL (WINAPI * MINIDUMP_CALLBACK_ROUTINE) (
IN PVOID CallbackParam,
IN CONST void *CallbackInput, // Not really void *
IN OUT void *CallbackOutput // Not really void *
);
typedef struct _MINIDUMP_CALLBACK_INFORMATION {
MINIDUMP_CALLBACK_ROUTINE CallbackRoutine;
PVOID CallbackParam;
} MINIDUMP_CALLBACK_INFORMATION, *PMINIDUMP_CALLBACK_INFORMATION;
#endif
// Dbghelp.dll is loaded at runtime so we don't create any needless
// dependencies on it.
typedef BOOL (WINAPI *THREADWALK) (HANDLE, LPTHREADENTRY32);
typedef BOOL (WINAPI *MODULEWALK) (HANDLE, LPMODULEENTRY32);
typedef HANDLE (WINAPI *CREATESNAPSHOT) (DWORD, DWORD);
typedef BOOL (WINAPI *WRITEDUMP) (HANDLE, DWORD, HANDLE, int,
PMINIDUMP_EXCEPTION_INFORMATION,
PMINIDUMP_USER_STREAM_INFORMATION,
PMINIDUMP_CALLBACK_INFORMATION);
// TYPES -------------------------------------------------------------------
#ifdef _M_X64
typedef PRUNTIME_FUNCTION (WINAPI *RTLLOOKUPFUNCTIONENTRY)
(ULONG64 ControlPc, PULONG64 ImageBase, void *HistoryTable);
#endif
// Damn Microsoft for doing Get/SetWindowLongPtr half-assed. Instead of
// giving them proper prototypes under Win32, they are just macros for
// Get/SetWindowLong, meaning they take LONGs and not LONG_PTRs.
#ifdef _WIN64
typedef LONG_PTR WLONG_PTR;
#else
typedef LONG WLONG_PTR;
#endif
namespace zip
{
#pragma pack(push,1)
struct LocalFileHeader
{
DWORD Magic; // 0
BYTE VersionToExtract[2]; // 4
WORD Flags; // 6
WORD Method; // 8
WORD ModTime; // 10
WORD ModDate; // 12
DWORD CRC32; // 14
DWORD CompressedSize; // 18
DWORD UncompressedSize; // 22
WORD NameLength; // 26
WORD ExtraLength; // 28
};
struct CentralDirectoryEntry
{
DWORD Magic;
BYTE VersionMadeBy[2];
BYTE VersionToExtract[2];
WORD Flags;
WORD Method;
WORD ModTime;
WORD ModDate;
DWORD CRC32;
DWORD CompressedSize;
DWORD UncompressedSize;
WORD NameLength;
WORD ExtraLength;
WORD CommentLength;
WORD StartingDiskNumber;
WORD InternalAttributes;
DWORD ExternalAttributes;
DWORD LocalHeaderOffset;
};
struct EndOfCentralDirectory
{
DWORD Magic;
WORD DiskNumber;
WORD FirstDisk;
WORD NumEntries;
WORD NumEntriesOnAllDisks;
DWORD DirectorySize;
DWORD DirectoryOffset;
WORD ZipCommentLength;
};
#pragma pack(pop)
}
struct TarFile
{
HANDLE File;
const char *Filename;
int ZipOffset;
DWORD UncompressedSize;
DWORD CompressedSize;
DWORD CRC32;
bool Deflated;
};
struct MiniDumpThreadData
{
HANDLE File;
WRITEDUMP pMiniDumpWriteDump;
MINIDUMP_EXCEPTION_INFORMATION *Exceptor;
};
// EXTERNAL FUNCTION PROTOTYPES --------------------------------------------
// PUBLIC FUNCTION PROTOTYPES ----------------------------------------------
void I_FlushBufferedConsoleStuff();
// PRIVATE FUNCTION PROTOTYPES ---------------------------------------------
static void AddFile (HANDLE file, const char *filename);
static void CloseTarFiles ();
static HANDLE MakeZip ();
static void AddZipFile (HANDLE ziphandle, TarFile *whichfile, short dosdate, short dostime);
static HANDLE CreateTempFile ();
static void DumpBytes (HANDLE file, BYTE *address);
static void AddStackInfo (HANDLE file, void *dumpaddress, DWORD code, CONTEXT *ctxt);
static void StackWalk (HANDLE file, void *dumpaddress, DWORD *topOfStack, DWORD *jump, CONTEXT *ctxt);
static void AddToolHelp (HANDLE file);
static HANDLE WriteTextReport ();
static DWORD WINAPI WriteMiniDumpInAnotherThread (LPVOID lpParam);
static INT_PTR CALLBACK DetailsDlgProc (HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
static void SetEditControl (HWND control, HWND sizedisplay, int filenum);
static BOOL UploadReport (HANDLE report, bool gziped);
// EXTERNAL DATA DECLARATIONS ----------------------------------------------
extern HINSTANCE g_hInst;
// PUBLIC DATA DEFINITIONS -------------------------------------------------
EXCEPTION_POINTERS CrashPointers;
// PRIVATE DATA DEFINITIONS ------------------------------------------------
static HRESULT (__stdcall *pEnableThemeDialogTexture) (HWND hwnd, DWORD dwFlags);
static const char PostHeader[] =
"POST " UPLOAD_URI " HTTP/1.1\r\n"
"Host: " REMOTE_HOST "\r\n"
"Connection: Close\r\n"
"User-Agent: " UPLOAD_AGENT "\r\n"
"Expect: 100-continue\r\n"
"Content-Type: multipart/form-data; boundary=\"" UPLOAD_BOUNDARY "\"\r\n"
"Content-Length: %lu\r\n"
"\r\n";
static const char MultipartInfoHeader[] =
"\r\n--" UPLOAD_BOUNDARY "\r\n"
"Content-Transfer-Encoding: 7bit\r\n"
"Content-Disposition: form-data; name=\"Info\"\r\n"
"\r\n";
static const char MultipartUserSummaryHeader[] =
"\r\n--" UPLOAD_BOUNDARY "\r\n"
"Content-Transfer-Encoding: 8bit\r\n"
"Content-Disposition: form-data; name=\"UserSummary\"\r\n"
"\r\n";
static const char MultipartBinaryHeader[] =
"\r\n--" UPLOAD_BOUNDARY "\r\n"
"Content-Transfer-Encoding: binary\r\n"
"Content-Disposition: form-data; name=\"reportfile\"; filename=\"itdidcrash.tar";
static const char MultipartHeaderGZip[] =
".gz\"\r\n"
"Content-Type: application/x-tar-gz\r\n"
"\r\n";
static const char MultipartHeaderNoGZip[] =
"\"\r\n"
"Content-Type: application/x-tar\r\n"
"\r\n";
static const char MultipartFooter[] =
"\r\n--" UPLOAD_BOUNDARY "--\r\n\r\n";
static const char DbgHelpRequest[] =
"GET " DBGHELP_URI " HTTP/1.1\r\n"
"Host: " REMOTE_HOST "\r\n"
"Connection: Close\r\n"
"User-Agent: " UPLOAD_AGENT "\r\n"
"\r\n";
static TarFile TarFiles[MAX_FILES];
static int NumFiles;
static HANDLE DbgProcess;
static DWORD DbgProcessID;
static DWORD DbgThreadID;
static DWORD CrashCode;
static PVOID CrashAddress;
static bool NeedDbgHelp;
static char CrashSummary[256];
static WNDPROC StdStaticProc;
// CODE --------------------------------------------------------------------
//==========================================================================
//
// SafeReadMemory
//
// Returns true if the memory was succussfully read and false if not.
//
//==========================================================================
static bool SafeReadMemory (const void *base, void *buffer, size_t len)
{
#ifdef __GNUC__
// GCC version: Test the memory beforehand and hope it doesn't become
// unreadable while we read it. GCC is the only Windows compiler (that
// I know of) that can't do SEH.
if (IsBadReadPtr (base, len))
{
return false;
}
memcpy (buffer, base, len);
return true;
#else
// Non-GCC version: Use SEH to catch any bad reads immediately when
// they happen instead of trying to catch them beforehand.
bool success = false;
__try
{
memcpy (buffer, base, len);
success = true;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
return success;
#endif
}
//==========================================================================
//
// GetTopOfStack
//
// Given a pointer to some address on the stack, returns a pointer to
// the top of the stack.
//
//==========================================================================
DWORD *GetTopOfStack (void *top)
{
MEMORY_BASIC_INFORMATION memInfo;
if (VirtualQuery (top, &memInfo, sizeof(memInfo)))
{
return (DWORD *)((BYTE *)memInfo.BaseAddress + memInfo.RegionSize);
}
else
{
return NULL;
}
}
//==========================================================================
//
// WriteMyMiniDump
//
// Writes a minidump if dbghelp.dll is present and adds it to the tarball.
// Otherwise, it just returns INVALID_HANDLE_VALUE.
//
//==========================================================================
static HANDLE WriteMyMiniDump (void)
{
MINIDUMP_EXCEPTION_INFORMATION exceptor = { DbgThreadID, &CrashPointers, FALSE };
char dbghelpPath[MAX_PATH+12], *bs;
WRITEDUMP pMiniDumpWriteDump;
HANDLE file;
BOOL good = FALSE;
HMODULE dbghelp = NULL;
// Make sure dbghelp.dll and MiniDumpWriteDump are available
// Try loading from the application directory first, then from the search path.
GetModuleFileName (NULL, dbghelpPath, MAX_PATH);
dbghelpPath[MAX_PATH] = 0;
bs = strrchr (dbghelpPath, '\\');
if (bs != NULL)
{
strcpy (bs + 1, "dbghelp.dll");
dbghelp = LoadLibrary (dbghelpPath);
}
if (dbghelp == NULL)
{
dbghelp = LoadLibrary ("dbghelp.dll");
if (dbghelp == NULL)
{
NeedDbgHelp = true;
return INVALID_HANDLE_VALUE;
}
}
pMiniDumpWriteDump = (WRITEDUMP)GetProcAddress (dbghelp, "MiniDumpWriteDump");
if (pMiniDumpWriteDump != NULL)
{
file = CreateTempFile ();
if (file != INVALID_HANDLE_VALUE)
{
if (CrashPointers.ExceptionRecord->ExceptionCode != EXCEPTION_STACK_OVERFLOW)
{
good = pMiniDumpWriteDump (DbgProcess, DbgProcessID, file,
#if 1
MiniDumpNormal
#else
MiniDumpWithDataSegs|MiniDumpWithIndirectlyReferencedMemory|MiniDumpWithPrivateReadWriteMemory
#endif
, &exceptor, NULL, NULL);
}
else
{
MiniDumpThreadData dumpdata = { file, pMiniDumpWriteDump, &exceptor };
DWORD id;
HANDLE thread = CreateThread (NULL, 0, WriteMiniDumpInAnotherThread,
&dumpdata, 0, &id);
WaitForSingleObject (thread, INFINITE);
if (GetExitCodeThread (thread, &id))
{
good = id;
}
}
}
}
else
{
NeedDbgHelp = true;
}
return good ? file : INVALID_HANDLE_VALUE;
}
//==========================================================================
//
// WriteMiniDumpInAnotherThread
//
// When a stack overflow occurs, there isn't enough room left on the stack
// for MiniDumpWriteDump to do its thing, so we create a new thread with
// a new stack to do the work.
//
//==========================================================================
static DWORD WINAPI WriteMiniDumpInAnotherThread (LPVOID lpParam)
{
MiniDumpThreadData *dumpdata = (MiniDumpThreadData *)lpParam;
return dumpdata->pMiniDumpWriteDump (DbgProcess, DbgProcessID,
dumpdata->File, MiniDumpNormal, dumpdata->Exceptor, NULL, NULL);
}
//==========================================================================
//
// Writef
//
// Like printf, but for Win32 file HANDLEs.
//
//==========================================================================
void Writef (HANDLE file, const char *format, ...)
{
char buffer[1024];
va_list args;
DWORD len;
va_start (args, format);
len = vsprintf (buffer, format, args);
va_end (args);
WriteFile (file, buffer, len, &len, NULL);
}
//==========================================================================
//
// WriteLogFileStreamer
//
// The callback function to stream a Rich Edit's contents to a file.
//
//==========================================================================
static DWORD CALLBACK WriteLogFileStreamer(DWORD_PTR cookie, LPBYTE buffer, LONG cb, LONG *pcb)
{
DWORD didwrite;
LONG p, pp;
// Replace gray foreground color with black.
static const char *badfg = "\\red223\\green223\\blue223;";
// 4321098 765432109 876543210
// 2 1 0
for (p = pp = 0; p < cb; ++p)
{
if (buffer[p] == badfg[pp])
{
++pp;
if (pp == 25)
{
buffer[p - 1] = buffer[p - 2] = buffer[p - 3] =
buffer[p - 9] = buffer[p -10] = buffer[p -11] =
buffer[p -18] = buffer[p -19] = buffer[p -20] = '0';
break;
}
}
else
{
pp = 0;
}
}
if (!WriteFile((HANDLE)cookie, buffer, cb, &didwrite, NULL))
{
return 1;
}
*pcb = didwrite;
return 0;
}
//==========================================================================
//
// WriteLogFile
//
// Writes the contents of a Rich Edit control to a file.
//
//==========================================================================
HANDLE WriteLogFile(HWND edit)
{
HANDLE file;
file = CreateTempFile();
if (file != INVALID_HANDLE_VALUE)
{
EDITSTREAM streamer = { (DWORD_PTR)file, 0, WriteLogFileStreamer };
SendMessage(edit, EM_STREAMOUT, SF_RTF, (LPARAM)&streamer);
}
return file;
}
//==========================================================================
//
// CreateCrashLog
//
// Creates all the files needed for a crash report.
//
//==========================================================================
void CreateCrashLog (char *custominfo, DWORD customsize, HWND richlog)
{
// Do not collect information more than once.
if (NumFiles != 0)
{
return;
}
DbgThreadID = GetCurrentThreadId();
DbgProcessID = GetCurrentProcessId();
DbgProcess = GetCurrentProcess();
CrashCode = CrashPointers.ExceptionRecord->ExceptionCode;
CrashAddress = CrashPointers.ExceptionRecord->ExceptionAddress;
AddFile (WriteTextReport(), "report.txt");
AddFile (WriteMyMiniDump(), "minidump.mdmp");
// Copy app-specific information out of the crashing process's memory
// and into a new temporary file.
if (customsize != 0)
{
HANDLE file = CreateTempFile();
DWORD wrote;
if (file != INVALID_HANDLE_VALUE)
{
BYTE buffer[512];
DWORD left;
for (;; customsize -= left, custominfo += left)
{
left = customsize > 512 ? 512 : customsize;
if (left == 0)
{
break;
}
if (SafeReadMemory (custominfo, buffer, left))
{
WriteFile (file, buffer, left, &wrote, NULL);
}
else
{
Writef (file, "Failed reading remaining %lu bytes\r\n", customsize);
break;
}
}
AddFile (file, "local.txt");
}
}
if (richlog != NULL)
{
I_FlushBufferedConsoleStuff();
AddFile (WriteLogFile(richlog), "log.rtf");
}
CloseHandle (DbgProcess);
}
//==========================================================================
//
// WriteTextReport
//
// This is the classic plain-text report ZDoom has generated since it
// added crash gathering abilities in 2002.
//
//==========================================================================
HANDLE WriteTextReport ()
{
HANDLE file;
static const struct
{
DWORD Code; const char *Text;
}
exceptions[] =
{
{ EXCEPTION_ACCESS_VIOLATION, "Access Violation" },
{ EXCEPTION_ARRAY_BOUNDS_EXCEEDED, "Array Bounds Exceeded" },
{ EXCEPTION_BREAKPOINT, "Breakpoint" },
{ EXCEPTION_DATATYPE_MISALIGNMENT, "Data Type Misalignment" },
{ EXCEPTION_FLT_DENORMAL_OPERAND, "Floating Point Denormal Operand." },
{ EXCEPTION_FLT_DIVIDE_BY_ZERO, "Floating Point Divide By Zero" },
{ EXCEPTION_FLT_INEXACT_RESULT, "Floating Point Inexact Result" },
{ EXCEPTION_FLT_INVALID_OPERATION, "Floating Point Invalid Operation" },
{ EXCEPTION_FLT_OVERFLOW, "Floating Point Overflow" },
{ EXCEPTION_FLT_STACK_CHECK, "Floating Point Stack Check" },
{ EXCEPTION_FLT_UNDERFLOW, "Floating Point Underflow" },
{ EXCEPTION_ILLEGAL_INSTRUCTION, "Illegal Instruction" },
{ EXCEPTION_IN_PAGE_ERROR, "In Page Error" },
{ EXCEPTION_INT_DIVIDE_BY_ZERO, "Integer Divide By Zero" },
{ EXCEPTION_INT_OVERFLOW, "Integer Overflow" },
{ EXCEPTION_INVALID_DISPOSITION, "Invalid Disposition" },
{ EXCEPTION_NONCONTINUABLE_EXCEPTION, "Noncontinuable Exception" },
{ EXCEPTION_PRIV_INSTRUCTION, "Priviledged Instruction" },
{ EXCEPTION_SINGLE_STEP, "Single Step" },
{ EXCEPTION_STACK_OVERFLOW, "Stack Overflow" }
};
static const char eflagsBits[][2] =
{
{ 'C','F' }, // Carry Flag
{ 'x','1' }, // Always one
{ 'P','F' }, // Parity Flag
{ 'x','0' }, // Always zero
{ 'A','F' }, // Auxilliary Carry Flag
{ 'x','0' }, // Always zero
{ 'Z','F' }, // Zero Flag
{ 'S','F' }, // Sign Flag
{ 'T','F' }, // Trap Flag
{ 'I','F' }, // Interrupt Enable Flag
{ 'D','F' }, // Direction Flag
{ 'O','F' }, // Overflow Flag
{ 'x','x' }, // IOPL low bit
{ 'x','x' }, // IOPL high bit
{ 'N','T' }, // Nested Task
{ 'x','0' }, // Always zero
{ 'R','F' }, // Resume Flag
{ 'V','M' }, // Virtual-8086 Mode
{ 'A','C' }, // Alignment Check
{ 'V','I' }, // Virtual Interrupt Flag
{ 'V','P' } // Virtual Interrupt Pending
};
int i, j;
file = CreateTempFile ();
if (file == INVALID_HANDLE_VALUE)
{
return file;
}
OSVERSIONINFO verinfo = { sizeof(verinfo) };
GetVersionEx (&verinfo);
for (i = 0; (size_t)i < sizeof(exceptions)/sizeof(exceptions[0]); ++i)
{
if (exceptions[i].Code == CrashPointers.ExceptionRecord->ExceptionCode)
{
break;
}
}
j = mysnprintf (CrashSummary, countof(CrashSummary), "Code: %08lX", CrashPointers.ExceptionRecord->ExceptionCode);
if ((size_t)i < sizeof(exceptions)/sizeof(exceptions[0]))
{
j += mysnprintf (CrashSummary + j, countof(CrashSummary) - j, " (%s", exceptions[i].Text);
if (CrashPointers.ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
{
// Pre-NT kernels do not seem to provide this information.
if (verinfo.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS)
{
j += mysnprintf (CrashSummary + j, countof(CrashSummary) - j,
" - tried to %s address %p",
CrashPointers.ExceptionRecord->ExceptionInformation[0] ? "write" : "read",
(void *)CrashPointers.ExceptionRecord->ExceptionInformation[1]);
}
}
CrashSummary[j++] = ')';
}
j += mysnprintf (CrashSummary + j, countof(CrashSummary) - j, "\r\nAddress: %p", CrashPointers.ExceptionRecord->ExceptionAddress);
Writef (file, "%s\r\nFlags: %08X\r\n\r\n", CrashSummary, CrashPointers.ExceptionRecord->ExceptionFlags);
Writef (file, "Windows %s %d.%d Build %d %s\r\n\r\n",
verinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ? "9x" : "NT",
verinfo.dwMajorVersion, verinfo.dwMinorVersion, verinfo.dwBuildNumber, verinfo.szCSDVersion);
CONTEXT *ctxt = CrashPointers.ContextRecord;
if (ctxt->ContextFlags & CONTEXT_SEGMENTS)
{
Writef (file, "GS=%04x FS=%04x ES=%04x DS=%04x\r\n",
ctxt->SegGs, ctxt->SegFs, ctxt->SegEs, ctxt->SegDs);
}
if (ctxt->ContextFlags & CONTEXT_INTEGER)
{
#ifndef _M_X64
Writef (file, "EAX=%08x EBX=%08x ECX=%08x EDX=%08x\r\nESI=%08x EDI=%08x\r\n",
ctxt->Eax, ctxt->Ebx, ctxt->Ecx, ctxt->Edx, ctxt->Esi, ctxt->Edi);
#else
Writef (file, "RAX=%016I64x RBX=%016I64x RCX=%016I64x\r\n"
"RDX=%016I64x RSI=%016I64x RDI=%016I64x\r\n"
"RBP=%016I64x R8=%016I64x R9=%016I64x\r\n"
"R10=%016I64x R11=%016I64x R12=%016I64x\r\n"
"R13=%016I64x R14=%016I64x R15=%016I64x\r\n",
ctxt->Rax, ctxt->Rbx, ctxt->Rcx, ctxt->Rdx, ctxt->Rsi, ctxt->Rdi, ctxt->Rbp,
ctxt->R8, ctxt->R9, ctxt->R10, ctxt->R11, ctxt->R12, ctxt->R13, ctxt->R14, ctxt->R15);
#endif
}
if (ctxt->ContextFlags & CONTEXT_CONTROL)
{
#ifndef _M_X64
Writef (file, "EBP=%08x EIP=%08x ESP=%08x CS=%04x SS=%04x\r\nEFlags=%08x\r\n",
ctxt->Ebp, ctxt->Eip, ctxt->Esp, ctxt->SegCs, ctxt->SegSs, ctxt->EFlags);
#else
Writef (file, "RIP=%016I64x RSP=%016I64x\r\nCS=%04x SS=%04x EFlags=%08x\r\n",
ctxt->Rip, ctxt->Rsp, ctxt->SegCs, ctxt->SegSs, ctxt->EFlags);
#endif
DWORD j;
for (i = 0, j = 1; (size_t)i < sizeof(eflagsBits)/sizeof(eflagsBits[0]); j <<= 1, ++i)
{
if (eflagsBits[i][0] != 'x')
{
Writef (file, " %c%c%c", eflagsBits[i][0], eflagsBits[i][1],
ctxt->EFlags & j ? '+' : '-');
}
}
Writef (file, "\r\n");
}
if (ctxt->ContextFlags & CONTEXT_FLOATING_POINT)
{
#ifndef _M_X64
Writef (file,
"\r\nFPU State:\r\n ControlWord=%04x StatusWord=%04x TagWord=%04x\r\n"
" ErrorOffset=%08x\r\n ErrorSelector=%08x\r\n DataOffset=%08x\r\n DataSelector=%08x\r\n"
// Cr0NpxState was renamed in recent Windows headers so better skip it here. Its meaning is unknown anyway.
//" Cr0NpxState=%08x\r\n"
"\r\n"
,
(WORD)ctxt->FloatSave.ControlWord, (WORD)ctxt->FloatSave.StatusWord, (WORD)ctxt->FloatSave.TagWord,
ctxt->FloatSave.ErrorOffset, ctxt->FloatSave.ErrorSelector, ctxt->FloatSave.DataOffset,
ctxt->FloatSave.DataSelector
//, ctxt->FloatSave.Cr0NpxState
);
for (i = 0; i < 8; ++i)
{
DWORD d0, d1;
memcpy(&d0, &ctxt->FloatSave.RegisterArea[20*i+4], sizeof(DWORD));
memcpy(&d1, &ctxt->FloatSave.RegisterArea[20*i], sizeof(DWORD));
Writef (file, "MM%d=%08x%08x\r\n", i, d0, d1);
}
#else
for (i = 0; i < 8; ++i)
{
Writef (file, "MM%d=%016I64x\r\n", i, ctxt->Legacy[i].Low);
}
for (i = 0; i < 16; ++i)
{
Writef (file, "XMM%d=%016I64x%016I64x\r\n", i, ctxt->FltSave.XmmRegisters[i].High, ctxt->FltSave.XmmRegisters[i].Low);
}
#endif
}
AddToolHelp (file);
#ifdef _M_IX86
Writef (file, "\r\nBytes near EIP:");
#else
Writef (file, "\r\nBytes near RIP:");
#endif
DumpBytes (file, (BYTE *)CrashPointers.ExceptionRecord->ExceptionAddress-16);
if (ctxt->ContextFlags & CONTEXT_CONTROL)
{
#ifndef _M_X64
AddStackInfo (file, (void *)(size_t)CrashPointers.ContextRecord->Esp,
CrashPointers.ExceptionRecord->ExceptionCode, ctxt);
#else
AddStackInfo (file, (void *)CrashPointers.ContextRecord->Rsp,
CrashPointers.ExceptionRecord->ExceptionCode, ctxt);
#endif
}
return file;
}
//==========================================================================
//
// AddToolHelp
//
// Adds the information supplied by the tool help functions to the text
// report. This includes the list of threads for this process and the
// loaded modules.
//
//==========================================================================
static void AddToolHelp (HANDLE file)
{
HMODULE kernel = GetModuleHandle ("kernel32.dll");
if (kernel == NULL)
return;
CREATESNAPSHOT pCreateToolhelp32Snapshot;
THREADWALK pThread32First;
THREADWALK pThread32Next;
MODULEWALK pModule32First;
MODULEWALK pModule32Next;
pCreateToolhelp32Snapshot = (CREATESNAPSHOT)GetProcAddress (kernel, "CreateToolhelp32Snapshot");
pThread32First = (THREADWALK)GetProcAddress (kernel, "Thread32First");
pThread32Next = (THREADWALK)GetProcAddress (kernel, "Thread32Next");
pModule32First = (MODULEWALK)GetProcAddress (kernel, "Module32First");
pModule32Next = (MODULEWALK)GetProcAddress (kernel, "Module32Next");
if (!(pCreateToolhelp32Snapshot && pThread32First && pThread32Next &&
pModule32First && pModule32Next))
{
Writef (file, "\r\nTool Help unavailable\r\n");
return;
}
HANDLE snapshot = pCreateToolhelp32Snapshot (TH32CS_SNAPMODULE|TH32CS_SNAPTHREAD, 0);
if (snapshot == INVALID_HANDLE_VALUE)
{
Writef (file, "\r\nTool Help snapshot unavailable\r\n");
return;
}
THREADENTRY32 thread = { sizeof(thread) };
Writef (file, "\r\nRunning threads:\r\n");
if (pThread32First (snapshot, &thread))
{
do
{
if (thread.th32OwnerProcessID == DbgProcessID)
{
Writef (file, "%08x", thread.th32ThreadID);
if (thread.th32ThreadID == DbgThreadID)
{
Writef (file, " at %p*", CrashAddress);
}
Writef (file, "\r\n");
}
} while (pThread32Next (snapshot, &thread));
}
MODULEENTRY32 module = { sizeof(module) };
Writef (file, "\r\nLoaded modules:\r\n");
if (pModule32First (snapshot, &module))
{
do
{
Writef (file, "%p - %p %c%s\r\n",
module.modBaseAddr, module.modBaseAddr + module.modBaseSize - 1,
module.modBaseAddr <= CrashPointers.ExceptionRecord->ExceptionAddress &&
module.modBaseAddr + module.modBaseSize > CrashPointers.ExceptionRecord->ExceptionAddress
? '*' : ' ',
module.szModule);
} while (pModule32Next (snapshot, &module));
}
CloseHandle (snapshot);
}
//==========================================================================
//
// AddStackInfo
//
// Writes a stack dump to the text report.
//
//==========================================================================
static void AddStackInfo (HANDLE file, void *dumpaddress, DWORD code, CONTEXT *ctxt)
{
DWORD *addr = (DWORD *)dumpaddress, *jump;
DWORD *topOfStack = GetTopOfStack (dumpaddress);
BYTE peekb;
#ifdef _M_IX86
DWORD peekd;
#else
QWORD peekq;
#endif
jump = topOfStack;
if (code == EXCEPTION_STACK_OVERFLOW)
{
// If the stack overflowed, only dump the first and last 16KB of it.
if (topOfStack - addr > 32768/4)
{
jump = addr + 16384/4;
}
}
StackWalk (file, dumpaddress, topOfStack, jump, ctxt);
Writef (file, "\r\nStack Contents:\r\n");
DWORD *scan;
for (scan = addr; scan < topOfStack; scan += 4)
{
int i;
ptrdiff_t max;
if (scan == jump)
{
scan = topOfStack - 16384/4;
Writef (file, "\r\n . . . Snip . . .\r\n\r\n");
}
Writef (file, "%p:", scan);
#ifdef _M_IX86
if (topOfStack - scan < 4)
{
max = topOfStack - scan;
}
else
{
max = 4;
}
for (i = 0; i < max; ++i)
{
if (!SafeReadMemory (&scan[i], &peekd, 4))
{
break;
}
Writef (file, " %08x", peekd);
}
for (; i < 4; ++i)