forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathExcept.cpp
More file actions
1398 lines (1193 loc) · 55 KB
/
Copy pathExcept.cpp
File metadata and controls
1398 lines (1193 loc) · 55 KB
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
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/***********************************************************************************************
*** C O N F I D E N T I A L --- W E S T W O O D S T U D I O S ***
***********************************************************************************************
* *
* Project Name : Command & Conquer *
* *
* $Archive:: /Commando/Code/wwlib/Except.cpp $*
* *
* $Author:: Steve_t $*
* *
* $Modtime:: 2/07/02 12:28p $*
* *
* $Revision:: 14 $*
* *
*---------------------------------------------------------------------------------------------*
* *
* *
* *
* *
* *
* *
*---------------------------------------------------------------------------------------------*
* Functions: *
* *
* Exception_Proc -- Windows dialog callback for the exception dialog *
* Exception_Dialog -- Brings up the exception options dialog. *
* Add_Txt -- Add the given text to the machine state dump buffer. *
* Dump_Exception_Info -- Dump machine state information into a buffer *
* Exception_Handler -- Exception handler filter function *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
#if defined(_WIN32)
#include "always.h"
#include <windows.h>
#include "assert.h"
#include "cpudetect.h"
#include "Except.h"
//#include "debug.h"
#include "MPU.h"
//#include "commando\nat.h"
#include "thread.h"
#include "wwdebug.h"
#include "wwmemlog.h"
#include "mutex.h"
#include <conio.h>
#include <imagehlp.h>
#include <crtdbg.h>
#ifdef WWDEBUG
#define DebugString WWDebug_Printf
#else
void DebugString(char const *, ...){};
#endif //WWDEBUG
/*
** Enable this define to get the 'demo timed out' message on a crash or assert failure.
*/
//#define DEMO_TIME_OUT
/*
** Buffer to dump machine state information to. We don't want to allocate this at run-time
** in case the exception was caused by a malfunction in the memory system.
*/
static char ExceptionText [65536];
bool SymbolsAvailable = false;
HINSTANCE ImageHelp = (HINSTANCE) -1;
void (*AppCallback)() = nullptr;
char *(*AppVersionCallback)() = nullptr;
/*
** Flag to indicate we should exit when an exception occurs.
*/
bool ExitOnException = false;
bool TryingToExit = false;
/*
** Register dump variables. These are used to allow the game to restart from an arbitrary
** position after an exception occurs.
*/
unsigned long ExceptionReturnStack = 0;
unsigned long ExceptionReturnAddress = 0;
unsigned long ExceptionReturnFrame = 0;
/*
** Number of times the exception handler has recursed. Recursions are bad.
*/
int ExceptionRecursions = -1;
/*
** List of threads that the exception handler knows about.
*/
DynamicVectorClass<ThreadInfoType*> ThreadList;
/*
** Returns the CRITICAL_SECTION used to protect ThreadList.
**
** Allocated from the Windows process heap (not the CRT heap) and never freed.
** The CRT heap can be torn down during application shutdown before all threads
** have exited. If a thread calls Unregister_Thread_ID after the CRT heap is
** destroyed, any CRITICAL_SECTION allocated via _aligned_malloc (which uses
** the CRT heap) would already be invalid memory, causing an access violation
** when EnterCriticalSection dereferences it.
**
** The Windows process heap (GetProcessHeap) outlives the CRT heap and is only
** reclaimed when the process terminates, so this CRITICAL_SECTION remains valid
** for the entire process lifetime regardless of CRT shutdown order.
**
** Thread-safe one-time initialization is achieved via
** InterlockedCompareExchangePointer, which works on all supported Windows versions.
*/
static CRITICAL_SECTION* GetThreadListCS()
{
static CRITICAL_SECTION* volatile s_cs = nullptr;
if (s_cs == nullptr) {
CRITICAL_SECTION* cs = reinterpret_cast<CRITICAL_SECTION*>(
HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(CRITICAL_SECTION)));
if (cs != nullptr) {
InitializeCriticalSection(cs);
}
// Race-free handoff: only one thread's allocation wins; the loser is discarded.
if (InterlockedCompareExchangePointer(
reinterpret_cast<volatile PVOID*>(&s_cs), cs, nullptr) != nullptr) {
// Another thread initialized it first; discard our copy.
if (cs != nullptr) {
DeleteCriticalSection(cs);
HeapFree(GetProcessHeap(), 0, cs);
}
}
}
return s_cs;
}
/*
** RAII lock guard for the raw ThreadList CRITICAL_SECTION.
** Replaces CriticalSectionClass::LockClass for the thread-list lock so that
** the CriticalSectionClass wrapper (and its _aligned_malloc-based handle) is
** never used for this particular, shutdown-sensitive critical path.
*/
struct ScopedThreadListLock
{
explicit ScopedThreadListLock(CRITICAL_SECTION* cs) : cs_(cs)
{
if (cs_ != nullptr) {
EnterCriticalSection(cs_);
}
}
~ScopedThreadListLock()
{
if (cs_ != nullptr) {
LeaveCriticalSection(cs_);
}
}
private:
CRITICAL_SECTION* cs_;
ScopedThreadListLock(const ScopedThreadListLock&);
ScopedThreadListLock& operator=(const ScopedThreadListLock&);
};
/*
** Definitions to allow run-time linking to the Imagehlp.dll functions.
**
*/
typedef BOOL (WINAPI *SymCleanupType) (HANDLE hProcess);
typedef BOOL (WINAPI *SymGetSymFromAddrType) (HANDLE hProcess, DWORD Address, LPDWORD Displacement, PIMAGEHLP_SYMBOL Symbol);
typedef BOOL (WINAPI *SymInitializeType) (HANDLE hProcess, LPSTR UserSearchPath, BOOL fInvadeProcess);
typedef BOOL (WINAPI *SymLoadModuleType) (HANDLE hProcess, HANDLE hFile, LPSTR ImageName, LPSTR ModuleName, DWORD BaseOfDll, DWORD SizeOfDll);
typedef DWORD (WINAPI *SymSetOptionsType) (DWORD SymOptions);
typedef BOOL (WINAPI *SymUnloadModuleType) (HANDLE hProcess, DWORD BaseOfDll);
typedef BOOL (WINAPI *StackWalkType) (DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME StackFrame, LPVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE TranslateAddress);
typedef LPVOID (WINAPI *SymFunctionTableAccessType) (HANDLE hProcess, DWORD AddrBase);
typedef DWORD (WINAPI *SymGetModuleBaseType) (HANDLE hProcess, DWORD dwAddr);
static SymCleanupType _SymCleanup = nullptr;
static SymGetSymFromAddrType _SymGetSymFromAddr = nullptr;
static SymInitializeType _SymInitialize = nullptr;
static SymLoadModuleType _SymLoadModule = nullptr;
static SymSetOptionsType _SymSetOptions = nullptr;
static SymUnloadModuleType _SymUnloadModule = nullptr;
static StackWalkType _StackWalk = nullptr;
static SymFunctionTableAccessType _SymFunctionTableAccess = nullptr;
static SymGetModuleBaseType _SymGetModuleBase = nullptr;
static char const *const ImagehelpFunctionNames[] =
{
"SymCleanup",
"SymGetSymFromAddr",
"SymInitialize",
"SymLoadModule",
"SymSetOptions",
"SymUnloadModule",
"StackWalk",
"SymFunctionTableAccess",
"SymGetModuleBaseType",
nullptr
};
/***********************************************************************************************
* _purecall -- This function overrides the C library Pure Virtual Function Call error *
* *
* *
* *
* INPUT: Nothing *
* *
* OUTPUT: 0 = no error *
* *
* WARNINGS: None *
* *
* HISTORY: *
* 8/22/00 11:42AM ST : Created *
*=============================================================================================*/
int __cdecl _purecall()
{
int return_code = 0;
#ifdef WWDEBUG
/*
** Use int3 to cause an exception.
*/
WWDEBUG_SAY(("Pure Virtual Function call. Oh No!"));
WWDEBUG_BREAK
#endif //_DEBUG_ASSERT
return(return_code);
}
/***********************************************************************************************
* Last_Error_Text -- Get the system error text for GetLastError *
* *
* *
* *
* INPUT: Nothing *
* *
* OUTPUT: Ptr to error string *
* *
* WARNINGS: None *
* *
* HISTORY: *
* 8/14/98 11:11AM ST : Created *
*=============================================================================================*/
char const * Last_Error_Text()
{
static char message_buffer[256];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), &message_buffer[0], 256, nullptr);
return (message_buffer);
}
/***********************************************************************************************
* Add_Txt -- Add the given text to the machine state dump buffer. *
* *
* *
* *
* INPUT: Text *
* *
* OUTPUT: Nothing *
* *
* WARNINGS: None *
* *
* HISTORY: *
* 7/22/97 12:21PM ST : Created *
*=============================================================================================*/
static void Add_Txt (char const *txt)
{
if (strlen(ExceptionText) + strlen(txt) < ARRAY_SIZE(ExceptionText) - 1) {
strcat(ExceptionText, txt);
}
#if (0)
/*
** Log to debug output too.
*/
static char _debug_output_txt[512];
const char *in = txt;
char *out = _debug_output_txt;
bool done = false;
if (strlen(txt) < sizeof(_debug_output_txt)) {
for (int i=0 ; i<sizeof(_debug_output_txt) ; i++) {
switch (*in) {
case '\r':
in++;
continue;
case 0:
done = true;
// fall through
default:
*out++ = *in++;
break;
}
if (done) {
break;
}
}
DebugString(_debug_output_txt);
}
#endif //(0)
}
/***********************************************************************************************
* Dump_Exception_Info -- Dump machine state information into a buffer *
* *
* *
* *
* INPUT: ptr to exception information *
* *
* OUTPUT: Nothing *
* *
* WARNINGS: None *
* *
* HISTORY: *
* 7/22/97 12:21PM ST : Created *
*=============================================================================================*/
void Dump_Exception_Info(EXCEPTION_POINTERS *e_info)
{
/*
** List of possible exceptions
*/
static const unsigned int _codes[] = {
EXCEPTION_ACCESS_VIOLATION,
EXCEPTION_ARRAY_BOUNDS_EXCEEDED,
EXCEPTION_BREAKPOINT,
EXCEPTION_DATATYPE_MISALIGNMENT,
EXCEPTION_FLT_DENORMAL_OPERAND,
EXCEPTION_FLT_DIVIDE_BY_ZERO,
EXCEPTION_FLT_INEXACT_RESULT,
EXCEPTION_FLT_INVALID_OPERATION,
EXCEPTION_FLT_OVERFLOW,
EXCEPTION_FLT_STACK_CHECK,
EXCEPTION_FLT_UNDERFLOW,
EXCEPTION_ILLEGAL_INSTRUCTION,
EXCEPTION_IN_PAGE_ERROR,
EXCEPTION_INT_DIVIDE_BY_ZERO,
EXCEPTION_INT_OVERFLOW,
EXCEPTION_INVALID_DISPOSITION,
EXCEPTION_NONCONTINUABLE_EXCEPTION,
EXCEPTION_PRIV_INSTRUCTION,
EXCEPTION_SINGLE_STEP,
EXCEPTION_STACK_OVERFLOW,
0xffffffff
};
/*
** Information about each exception type.
*/
static char const * _code_txt[] = {
"Error code: EXCEPTION_ACCESS_VIOLATION\r\r\nDescription: The thread tried to read from or write to a virtual address for which it does not have the appropriate access.",
"Error code: EXCEPTION_ARRAY_BOUNDS_EXCEEDED\r\r\nDescription: The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking.",
"Error code: EXCEPTION_BREAKPOINT\r\r\nDescription: A breakpoint was encountered.",
"Error code: EXCEPTION_DATATYPE_MISALIGNMENT\r\r\nDescription: The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on.",
"Error code: EXCEPTION_FLT_DENORMAL_OPERAND\r\r\nDescription: One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value.",
"Error code: EXCEPTION_FLT_DIVIDE_BY_ZERO\r\r\nDescription: The thread tried to divide a floating-point value by a floating-point divisor of zero.",
"Error code: EXCEPTION_FLT_INEXACT_RESULT\r\r\nDescription: The result of a floating-point operation cannot be represented exactly as a decimal fraction.",
"Error code: EXCEPTION_FLT_INVALID_OPERATION\r\r\nDescription: Some strange unknown floating point operation was attempted.",
"Error code: EXCEPTION_FLT_OVERFLOW\r\r\nDescription: The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type.",
"Error code: EXCEPTION_FLT_STACK_CHECK\r\r\nDescription: The stack overflowed or underflowed as the result of a floating-point operation.",
"Error code: EXCEPTION_FLT_UNDERFLOW\r\r\nDescription: The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type.",
"Error code: EXCEPTION_ILLEGAL_INSTRUCTION\r\r\nDescription: The thread tried to execute an invalid instruction.",
"Error code: EXCEPTION_IN_PAGE_ERROR\r\r\nDescription: The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network.",
"Error code: EXCEPTION_INT_DIVIDE_BY_ZERO\r\r\nDescription: The thread tried to divide an integer value by an integer divisor of zero.",
"Error code: EXCEPTION_INT_OVERFLOW\r\r\nDescription: The result of an integer operation caused a carry out of the most significant bit of the result.",
"Error code: EXCEPTION_INVALID_DISPOSITION\r\r\nDescription: An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception.",
"Error code: EXCEPTION_NONCONTINUABLE_EXCEPTION\r\r\nDescription: The thread tried to continue execution after a noncontinuable exception occurred.",
"Error code: EXCEPTION_PRIV_INSTRUCTION\r\r\nDescription: The thread tried to execute an instruction whose operation is not allowed in the current machine mode.",
"Error code: EXCEPTION_SINGLE_STEP\r\r\nDescription: A trace trap or other single-instruction mechanism signaled that one instruction has been executed.",
"Error code: EXCEPTION_STACK_OVERFLOW\r\r\nDescription: The thread used up its stack.",
"Error code: ?????\r\r\nDescription: Unknown exception."
};
DebugString("Dump exception info\n");
/*
** Scrap buffer for constructing dump strings
*/
char scrap [256];
/*
** Clear out the dump buffer
*/
memset(ExceptionText, 0, sizeof (ExceptionText));
/*
** If this is the first time through then fix up the imagehelp function pointers since imagehlp.dll
** can't be statically linked.
*/
HINSTANCE imagehelp = LoadLibrary("IMAGEHLP.DLL");
if (imagehelp != nullptr) {
DebugString ("Exception Handler: Found IMAGEHLP.DLL - linking to required functions\n");
char const *function_name = nullptr;
unsigned long *fptr = (unsigned long*) &_SymCleanup;
int count = 0;
do {
function_name = ImagehelpFunctionNames[count];
if (function_name) {
*fptr = (unsigned long) GetProcAddress(imagehelp, function_name);
fptr++;
count++;
}
} while (function_name);
} else {
DebugString("Exception Handler: Unable to load IMAGEHLP.DLL\n");
}
/*
** Retrieve the programs symbols if they are available
*/
if (_SymSetOptions != nullptr) {
_SymSetOptions(SYMOPT_DEFERRED_LOADS);
}
int symload = 0;
int symbols_available = false;
if (_SymInitialize != nullptr && _SymInitialize (GetCurrentProcess(), nullptr, false)) {
DebugString("Exception Handler: Symbols are available\r\n\n");
symbols_available = true;
}
if (!symbols_available) {
DebugString ("Exception Handler: SymInitialize failed with code %d - %s\n", GetLastError(), Last_Error_Text());
} else {
if (_SymSetOptions != nullptr) {
_SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME);
}
char module_name[_MAX_PATH];
GetModuleFileName(nullptr, module_name, sizeof(module_name));
if (_SymLoadModule != nullptr) {
symload = _SymLoadModule(GetCurrentProcess(), nullptr, module_name, nullptr, 0, 0);
}
if (!symload) {
assert(_SymLoadModule != nullptr);
DebugString ("Exception Handler: SymLoad failed for module %s with code %d - %s\n", module_name, GetLastError(), Last_Error_Text());
}
}
unsigned char symbol [256];
unsigned long displacement;
IMAGEHLP_SYMBOL *symptr = (IMAGEHLP_SYMBOL*)&symbol;
/*
** Get the exception address and the machine context at the time of the exception
*/
CONTEXT *context = e_info->ContextRecord;
/*
** The following are set for access violation only
*/
int access_read_write=-1;
unsigned long access_address = 0;
if (e_info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
DebugString("Exception Handler: Exception is access violation\n");
access_read_write = e_info->ExceptionRecord->ExceptionInformation[0]; // 0=read, 1=write
access_address = e_info->ExceptionRecord->ExceptionInformation[1];
} else {
DebugString ("Exception Handler: Exception code is %d\n", e_info->ExceptionRecord->ExceptionCode);
}
/*
** Match the exception type with the error string and print it out
*/
int i=0;
for (; _codes[i] != 0xffffffff ; i++) {
if (_codes[i] == e_info->ExceptionRecord->ExceptionCode) {
DebugString("Exception Handler: Found exception description\n");
break;
}
}
Add_Txt(_code_txt[i]);
Add_Txt("\r\n");
/*
** For access violations, print out the violation address and if it was read or write.
*/
if (e_info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) {
sprintf(scrap, "Access address:%08X ", access_address);
Add_Txt(scrap);
if (access_read_write) {
Add_Txt("was written to.\r\n");
} else {
Add_Txt("was read from.\r\n");
}
}
/*
** If symbols are available, print out the exception eip address and the name of the
** function it represents.
*/
memset(symptr, 0, sizeof (IMAGEHLP_SYMBOL));
symptr->SizeOfStruct = sizeof (IMAGEHLP_SYMBOL);
symptr->MaxNameLength = 256-sizeof (IMAGEHLP_SYMBOL);
symptr->Size = 0;
symptr->Address = context->Eip;
if (!IsBadCodePtr((FARPROC)context->Eip)) {
if (_SymGetSymFromAddr != nullptr && _SymGetSymFromAddr (GetCurrentProcess(), context->Eip, &displacement, symptr)) {
snprintf(scrap, ARRAY_SIZE(scrap), "Exception occurred at %08X - %s + %08X\r\n",
context->Eip, symptr->Name, displacement);
} else {
DebugString ("Exception Handler: Failed to get symbol for EIP\r\n");
if (_SymGetSymFromAddr != nullptr) {
DebugString ("Exception Handler: SymGetSymFromAddr failed with code %d - %s\n", GetLastError(), Last_Error_Text());
}
sprintf (scrap, "Exception occurred at %08X\r\n", context->Eip);
}
} else {
DebugString ("Exception Handler: context->Eip is bad code pointer\n");
}
Add_Txt (scrap);
/*
** Try to walk the stack. It might work....
*/
DebugString("Stack walk...\n");
Add_Txt("\r\n Stack walk...\r\n");
unsigned long return_addresses[256];
int num_addresses = Stack_Walk(return_addresses, 256, context);
if (num_addresses) {
for (int s=0 ; s<num_addresses ; s++) {
unsigned long temp_addr = return_addresses[s];
displacement = 0;
for (int space = 0 ; space <= s ; space++) {
Add_Txt(" ");
}
if (symbols_available) {
symptr->SizeOfStruct = sizeof(symbol);
symptr->MaxNameLength = 128;
symptr->Size = 0;
symptr->Address = temp_addr;
if (_SymGetSymFromAddr != nullptr && _SymGetSymFromAddr (GetCurrentProcess(), temp_addr, &displacement, symptr)) {
char symbuf[256];
snprintf(symbuf, ARRAY_SIZE(symbuf), "%s + %08X\r\n", symptr->Name, displacement);
Add_Txt(symbuf);
}
} else {
char symbuf[256];
sprintf(symbuf, "%08x\r\n", temp_addr);
Add_Txt(symbuf);
}
}
Add_Txt("\r\n\r\n");
} else {
DebugString("Stack walk failed!\n");
Add_Txt("Stack walk failed!\r\n");
}
#if (0) //Don't have this info yet for Renegade.
/*
** Add in the version info.
*/
sprintf(scrap, "\r\nVersion %s\r\n", Version_Name());
Add_Txt(scrap);
sprintf(scrap, "Internal Version %s\r\n", VerNum.Version_Name());
Add_Txt(scrap);
char buildinfo[128];
buildinfo[0] = 0;
Build_Date_String(buildinfo, 128);
char build_number[128];
char build_name[128];
#endif //(0)
if (AppVersionCallback) {
snprintf(scrap, ARRAY_SIZE(scrap), "%s\r\n\r\n", AppVersionCallback());
Add_Txt(scrap);
}
/*
** Thread list.
*/
Add_Txt("Thread list\r\n");
/*
** Get the thread info from ThreadClass.
*/
for (int thread = 0 ; thread < ThreadList.Count() ; thread++) {
snprintf(scrap, ARRAY_SIZE(scrap), " ID: %08X - %s",
ThreadList[thread]->ThreadID, ThreadList[thread]->ThreadName);
Add_Txt(scrap);
if (GetCurrentThreadId() == ThreadList[thread]->ThreadID) {
Add_Txt(" ***CURRENT THREAD***");
}
Add_Txt("\r\n");
}
/*
** CPU type
*/
snprintf(scrap, ARRAY_SIZE(scrap), "\r\nCPU %s, %d Mhz, Vendor: %s\r\n",
(char*)CPUDetectClass::Get_Processor_String(), Get_RDTSC_CPU_Speed(),
(char*)CPUDetectClass::Get_Processor_Manufacturer_Name());
Add_Txt(scrap);
Add_Txt("\r\nDetails:\r\n");
DebugString("Register dump...\n");
/*
** Dump the registers.
*/
sprintf(scrap, "Eip:%08X\tEsp:%08X\tEbp:%08X\r\n", context->Eip, context->Esp, context->Ebp);
Add_Txt(scrap);
sprintf(scrap, "Eax:%08X\tEbx:%08X\tEcx:%08X\r\n", context->Eax, context->Ebx, context->Ecx);
Add_Txt(scrap);
sprintf(scrap, "Edx:%08X\tEsi:%08X\tEdi:%08X\r\n", context->Edx, context->Esi, context->Edi);
Add_Txt(scrap);
sprintf(scrap, "EFlags:%08X \r\n", context->EFlags);
Add_Txt(scrap);
sprintf(scrap, "CS:%04x SS:%04x DS:%04x ES:%04x FS:%04x GS:%04x\r\n", context->SegCs, context->SegSs, context->SegDs, context->SegEs, context->SegFs, context->SegGs);
Add_Txt(scrap);
/*
** Now the FP registers.
*/
Add_Txt("\r\nFloating point status\r\n");
sprintf(scrap, " Control word: %08x\r\n", context->FloatSave.ControlWord);
Add_Txt(scrap);
sprintf(scrap, " Status word: %08x\r\n", context->FloatSave.StatusWord);
Add_Txt(scrap);
sprintf(scrap, " Tag word: %08x\r\n", context->FloatSave.TagWord);
Add_Txt(scrap);
sprintf(scrap, " Error Offset: %08x\r\n", context->FloatSave.ErrorOffset);
Add_Txt(scrap);
sprintf(scrap, " Error Selector: %08x\r\n", context->FloatSave.ErrorSelector);
Add_Txt(scrap);
sprintf(scrap, " Data Offset: %08x\r\n", context->FloatSave.DataOffset);
Add_Txt(scrap);
sprintf(scrap, " Data Selector: %08x\r\n", context->FloatSave.DataSelector);
Add_Txt(scrap);
#if !defined(WOW64_SIZE_OF_80387_REGISTERS)
sprintf(scrap, " Cr0NpxState: %08x\r\n", context->FloatSave.Cr0NpxState);
Add_Txt(scrap);
#endif
for (int fp=0 ; fp<SIZE_OF_80387_REGISTERS / 10 ; fp++) {
sprintf(scrap, "ST%d : ", fp);
Add_Txt(scrap);
for (int b=0 ; b<10 ; b++) {
sprintf(scrap, "%02X", context->FloatSave.RegisterArea[(fp*10) + b]);
Add_Txt(scrap);
}
void *fp_data_ptr = (void*)(&context->FloatSave.RegisterArea[fp*10]);
// TheSuperHackers @refactor Replaced MSVC inline assembly with portable C++ cast for MinGW compatibility
/*
** Convert FP dump from temporary real value (10 bytes) to double (8 bytes).
** On x86, long double is the 10-byte x87 format, so we can just cast.
*/
double fp_value = (double)(*(long double*)fp_data_ptr);
sprintf(scrap, " %+#.17e\r\n", fp_value);
Add_Txt(scrap);
}
/*
** Dump the bytes at EIP. This will make it easier to match the crash address with later versions of the game.
*/
DebugString("EIP bytes dump...\n");
sprintf(scrap, "\r\nBytes at CS:EIP (%08X) : ", context->Eip);
unsigned char *eip_ptr = (unsigned char *) (context->Eip);
char bytestr[32];
for (int c = 0 ; c < 32 ; c++) {
if (IsBadReadPtr(eip_ptr, 1)) {
strlcat(scrap, "?? ", ARRAY_SIZE(scrap));
} else {
sprintf(bytestr, "%02X ", *eip_ptr);
strlcat(scrap, bytestr, ARRAY_SIZE(scrap));
}
eip_ptr++;
}
strlcat(scrap, "\r\n\r\n", ARRAY_SIZE(scrap));
Add_Txt(scrap);
/*
** Dump out the values on the stack.
*/
DebugString("Stack dump...\n");
Add_Txt("Stack dump (* indicates possible code address) :\r\n");
unsigned long *stackptr = (unsigned long*) context->Esp;
for (int j=0 ; j<2048 ; j++) {
if (IsBadReadPtr(stackptr, 4)) {
/*
** The stack contents cannot be read so just print up question marks.
*/
sprintf(scrap, "%p: ", static_cast<void*>(stackptr));
strlcat(scrap, "????????\r\n", ARRAY_SIZE(scrap));
} else {
/*
** If this stack address is in our memory space then try to match it with a code symbol.
*/
if (IsBadCodePtr((FARPROC)*stackptr)) {
sprintf(scrap, "%p: %08lX ", static_cast<void*>(stackptr), *stackptr);
strlcat(scrap, "DATA_PTR\r\n", ARRAY_SIZE(scrap));
} else {
sprintf(scrap, "%p: %08lX", static_cast<void*>(stackptr), *stackptr);
if (symbols_available) {
symptr->SizeOfStruct = sizeof(symbol);
symptr->MaxNameLength = 128;
symptr->Size = 0;
symptr->Address = *stackptr;
if (_SymGetSymFromAddr != nullptr && _SymGetSymFromAddr (GetCurrentProcess(), *stackptr, &displacement, symptr)) {
char symbuf[256];
snprintf(symbuf, ARRAY_SIZE(symbuf), " - %s + %08X", symptr->Name, displacement);
strlcat(scrap, symbuf, ARRAY_SIZE(scrap));
}
} else {
strlcat(scrap, " *", ARRAY_SIZE(scrap));
}
strlcat(scrap, "\r\n", ARRAY_SIZE(scrap));
}
}
Add_Txt(scrap);
stackptr++;
}
/*
** Unload the symbols.
*/
if (symbols_available) {
if (_SymCleanup != nullptr) {
_SymCleanup (GetCurrentProcess());
}
if (symload) {
if (_SymUnloadModule != nullptr) {
_SymUnloadModule(GetCurrentProcess(), 0);
}
}
}
if (imagehelp) {
FreeLibrary(imagehelp);
}
Add_Txt ("\r\n\r\n");
}
/***********************************************************************************************
* Exception_Handler -- Exception handler filter function *
* *
* *
* *
* INPUT: exception code *
* pointer to exception information pointers *
* *
* OUTPUT: EXCEPTION_EXECUTE_HANDLER -- Excecute the body of the __except construct *
* or EXCEPTION_CONTINUE_SEARCH -- Pass this exception down to the debugger *
* or EXCEPTION_CONTINUE_EXECUTION -- Continue to execute at the fault address *
* *
* WARNINGS: None *
* *
* HISTORY: *
* 7/22/97 12:29PM ST : Created *
*=============================================================================================*/
int Exception_Handler(int exception_code, EXCEPTION_POINTERS *e_info)
{
DebugString("Exception!\n");
#ifdef DEMO_TIME_OUT
if ( !WindowedMode ) {
Load_Title_Page("TITLE.PCX", true);
MouseCursor->Release_Mouse();
MessageBox(MainWindow, "This demo has timed out. Thank you for playing Red Alert 2.","Byeee!", MB_ICONEXCLAMATION|MB_OK);
return (EXCEPTION_EXECUTE_HANDLER);
}
#endif //DEMO_TIME_OUT
/*
** If we were trying to quit and we got another exception then just shut down the whole shooting match right here.
*/
if (TryingToExit) {
ExitProcess(0);
}
/*
** Track recursions because we need to know if something here is failing.
*/
ExceptionRecursions++;
if (ExceptionRecursions > 1) {
return (EXCEPTION_CONTINUE_SEARCH);
}
/*
** If there was a breakpoint then chances are it was set by a debugger. In RTS_DEBUG mode
** we probably should ignore breakpoints. Breakpoints become more significant in release
** mode since there probably isn't a debugger present.
*/
#ifdef RTS_DEBUG
if (exception_code == EXCEPTION_BREAKPOINT) {
return (EXCEPTION_CONTINUE_SEARCH);
}
#else
exception_code = exception_code;
#endif //RTS_DEBUG
#ifdef WWDEBUG
//CONTEXT *context;
#endif // WWDEBUG
if (ExceptionRecursions == 0) {
/*
** Create a dump of the exception info.
*/
Dump_Exception_Info(e_info);
/*
** Log the machine state to disk
*/
HANDLE debug_file;
DWORD actual;
debug_file = CreateFile("_except.txt", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if (debug_file != INVALID_HANDLE_VALUE){
WriteFile(debug_file, ExceptionText, strlen(ExceptionText), &actual, nullptr);
CloseHandle (debug_file);
#if (0)
#ifdef _DEBUG_PRINT
#ifndef RTS_DEBUG
/*
** Copy the exception debug file to the network. No point in doing this for the debug version
** since symbols are not normally available.
*/
DebugString ("About to copy debug file\n");
char filename[512];
if (Get_Global_Output_File_Name ("EXCEPT", filename, 512)) {
DebugString ("Copying DEBUG.TXT to %s\n", filename);
int result = CopyFile("debug.txt", filename, false);
if (result == 0) {
DebugString ("CopyFile failed with error code %d - %s\n", GetLastError(), Last_Error_Text());
}
}
DebugString ("Debug file copied\n");
#endif //RTS_DEBUG
#endif //_DEBUG_PRINT
#endif //(0)
}
}
/*
** Call the apps callback function.
*/
if (AppCallback) {
AppCallback();
}
/*
** If an exit is required then turn of memory leak reporting (there will be lots of them) and use
** EXCEPTION_EXECUTE_HANDLER to let us fall out of winmain.
*/
if (ExitOnException) {
#ifdef RTS_DEBUG
_CrtSetDbgFlag(0);
#endif //RTS_DEBUG
TryingToExit = true;
unsigned long id = Get_Main_Thread_ID();
if (id != GetCurrentThreadId()) {
DebugString("Exiting due to exception in sub thread\n");
ExitProcess(EXIT_SUCCESS);
}
return(EXCEPTION_EXECUTE_HANDLER);
}
return (EXCEPTION_CONTINUE_SEARCH);
}
/***********************************************************************************************
* Register_Thread_ID -- Let the exception handler know about a thread *
* *
* *
* *
* INPUT: Thread ID *
* Thread name *
* *
* OUTPUT: Nothing *
* *
* WARNINGS: None *
* *
* HISTORY: *
* 8/30/2001 3:04PM ST : Created *
*=============================================================================================*/
void Register_Thread_ID(unsigned long thread_id, char *thread_name, bool main_thread)
{
WWMEMLOG(MEM_GAMEDATA);
if (thread_name) {
ScopedThreadListLock lock(GetThreadListCS());
/*
** See if we already know about this thread. Maybe just the thread_id changed.
*/
for (int i=0 ; i<ThreadList.Count() ; i++) {
if (strcmp(thread_name, ThreadList[i]->ThreadName) == 0) {
ThreadList[i]->ThreadID = thread_id;
return;
}
}
ThreadInfoType *thread = new ThreadInfoType;
thread->ThreadID = thread_id;
strlcpy(thread->ThreadName, thread_name, ARRAY_SIZE(thread->ThreadName));
thread->Main = main_thread;
thread->ThreadHandle = INVALID_HANDLE_VALUE;
ThreadList.Add(thread);
}
}
#if (0)
/***********************************************************************************************
* Register_Thread_Handle -- Keep a copy of the thread handle that matches this thread ID *
* *
* *
* *
* INPUT: Thread ID *
* Thread handle *
* *
* OUTPUT: True if thread ID was matched *
* *
* WARNINGS: *
* *
* HISTORY: *
* 2/6/2002 9:40PM ST : Created *
*=============================================================================================*/
bool Register_Thread_Handle(unsigned long thread_id, HANDLE thread_handle)
{
for (int i=0 ; i<ThreadList.Count() ; i++) {