forked from HeliumProject/Platform
/
ExceptionWin.cpp
995 lines (829 loc) · 25.6 KB
/
ExceptionWin.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
#include "PlatformPch.h"
#include "Exception.h"
#include "Platform/Types.h"
#include "Platform/Locks.h"
#include "Platform/Error.h"
#include "Platform/Assert.h"
#include "Platform/Encoding.h"
#include "Platform/Exception.h"
#include "Platform/Trace.h"
#include "Platform/Console.h"
#include "Platform/Process.h"
#include <map>
#include <time.h>
#include <shlobj.h>
#include <tlhelp32.h>
#define DBGHELP_TRANSLATE_TCHAR
#pragma warning( push )
#pragma warning( disable : 4091 )
#include <dbghelp.h>
#pragma warning( pop )
#pragma comment ( lib, "dbghelp.lib" )
using namespace Helium;
//#define DEBUG_SYMBOLS
// disable the optimizer if debugging in release
#if defined(DEBUG_SYMBOLS) && defined(NDEBUG)
#pragma optimize("", off)
#endif
// loaded flag
static bool g_Initialized = false;
// Utility to print to a string
static void PrintToString(std::string& str, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
size_t needed = StringPrintArgs(NULL, 0, fmt, args) + 1;
char* buf = (char*)alloca( sizeof(char) * needed );
StringPrintArgs(buf, sizeof(buf) * needed, fmt, args);
buf[ needed - 1] = 0;
va_end(args);
str += buf;
}
// Callback that loads symbol data from loaded dll into DbgHelp system, dumping error info
static BOOL CALLBACK EnumerateLoadedModulesProc(PCTSTR name, DWORD64 base, ULONG size, PVOID data)
{
if (SymLoadModuleEx(GetCurrentProcess(), 0, name, 0, base, size, NULL, 0))
{
HELIUM_CONVERT_TO_CHAR( name, convertedName );
IMAGEHLP_MODULE64 moduleInfo;
ZeroMemory(&moduleInfo, sizeof(IMAGEHLP_MODULE64));
moduleInfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if ( SymGetModuleInfo64( GetCurrentProcess(), base, &moduleInfo ) )
{
if ( moduleInfo.LoadedPdbName[0] != '\0' )
{
HELIUM_CONVERT_TO_CHAR( moduleInfo.LoadedPdbName, convertedPdbName );
Print( TXT("Success loading symbols for module: %s, base: 0x%" HELIUM_PRINT_POINTER ", size: %u: %s\n"), convertedName, base, size, convertedPdbName );
}
else
{
Print( TXT("Success loading symbols for module: %s, base: 0x%" HELIUM_PRINT_POINTER ", size: %u\n"), convertedName, base, size );
}
}
else
{
Print( TXT("Failure loading symbols for module: %s: %s\n"), convertedName, Helium::GetErrorString().c_str() );
}
}
return TRUE;
}
// Load debugging information for the currently loaded dlls, call this each time you need to use Sym*() API. Keep calling it
static void EnumerateLoadedModules()
{
// load debugging information
// this is probably slow, but SYMOPT_DEFERRED_LOADS doesn't always work with
// dynamically loaded dlls so we do this instead of SYMOPT_DEFERRED_LOADS and
// invading the process during SymInitialize
EnumerateLoadedModules64(GetCurrentProcess(), &EnumerateLoadedModulesProc, NULL);
}
bool Helium::IsDebuggerPresent()
{
return ::IsDebuggerPresent() != 0;
}
bool Helium::InitializeSymbols(const std::string& path)
{
if ( !g_Initialized )
{
std::wstring dir;
if ( path.empty() )
{
wchar_t module[MAX_PATH];
wchar_t drive[MAX_PATH];
wchar_t path[MAX_PATH];
wchar_t file[MAX_PATH];
wchar_t ext[MAX_PATH];
GetModuleFileName(0,module,MAX_PATH);
_tsplitpath(module,drive,path,file,ext);
dir = drive;
dir += path;
}
else
{
ConvertString(path, dir);
}
DWORD options = SYMOPT_FAIL_CRITICAL_ERRORS |
SYMOPT_LOAD_LINES |
SYMOPT_UNDNAME;
SymSetOptions(options);
// initialize symbols (dbghelp.dll)
if ( SymInitialize(GetCurrentProcess(), dir.c_str(), FALSE) == 0 )
{
Print( TXT("Failure initializing symbol API: %s\n"), Helium::GetErrorString().c_str() );
return false;
}
// success
g_Initialized = true;
}
return true;
}
bool Helium::GetSymbolsInitialized()
{
return g_Initialized;
}
std::string Helium::GetSymbolInfo(uintptr_t adr, bool enumLoadedModules)
{
HELIUM_ASSERT( g_Initialized );
if ( enumLoadedModules )
{
// load debugging information
EnumerateLoadedModules();
}
// module image name "reflect.dll"
wchar_t module[MAX_PATH];
ZeroMemory(&module, sizeof(module));
wchar_t extension[MAX_PATH];
ZeroMemory(&extension, sizeof(extension));
// symbol name "Reflect::Class::AddSerializer + 0x16d"
char symbol[MAX_SYM_NAME+16];
ZeroMemory(&symbol, sizeof(symbol));
// source file name "typeinfo.cpp"
wchar_t filename[MAX_PATH];
ZeroMemory(&filename, sizeof(filename));
// line number in source "246"
DWORD line = 0xFFFFFFFF;
// resulting line is worst case of all components
char result[sizeof(module) + sizeof(symbol) + sizeof(filename) + 64];
ZeroMemory(&result, sizeof(result));
//
// Start by finding the module the address is in
//
IMAGEHLP_MODULE64 moduleInfo;
ZeroMemory(&moduleInfo, sizeof(IMAGEHLP_MODULE64));
moduleInfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if (SymGetModuleInfo64(GetCurrentProcess(), adr, &moduleInfo))
{
// success, copy the module info
_tsplitpath(moduleInfo.ImageName, NULL, NULL, module, extension);
_tcscat(module, extension);
//
// Now find symbol information
//
// displacement of the symbol
DWORD64 disp;
// okay, the name runs off the end of the structure, so setup a buffer and cast it
ULONG64 buffer[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME*sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64)];
PSYMBOL_INFO symbolInfo = (PSYMBOL_INFO)buffer;
symbolInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
symbolInfo->MaxNameLen = MAX_SYM_NAME;
if ( SymFromAddr(GetCurrentProcess(), adr, &disp, symbolInfo) != 0 )
{
HELIUM_WIDE_TO_TCHAR(symbolInfo->Name, convertedSymbolName);
// success, copy the symbol info
StringPrint(symbol, TXT("%s + 0x%"HELIUM_PRINT_POINTER), convertedSymbolName, disp);
//
// Now find source line information
//
DWORD d;
IMAGEHLP_LINE64 l;
ZeroMemory(&l,sizeof(l));
l.SizeOfStruct = sizeof(l);
if ( SymGetLineFromAddr64(GetCurrentProcess(), adr, &d, &l) !=0 )
{
// success, copy the source file name
_tcscpy(filename, l.FileName);
wchar_t ext[MAX_PATH];
wchar_t file[MAX_PATH];
_tsplitpath(filename, NULL, NULL, file, ext);
HELIUM_WIDE_TO_TCHAR(module, convertedModule);
HELIUM_WIDE_TO_TCHAR(file, convertedFile);
HELIUM_WIDE_TO_TCHAR(ext, convertedExt);
StringPrint(result, TXT("%s, %s : %s%s(%d)"), convertedModule, symbol, convertedFile, convertedExt, l.LineNumber);
return result;
}
StringPrint(result, TXT("%s, %s"), module, symbol);
return result;
}
StringPrint(result, TXT("%s"), module);
return result;
}
else
{
DWORD err = GetLastError();
return TXT("Unknown");
}
}
Helium::Exception* Helium::GetHeliumException(uintptr_t addr)
{
Helium::Exception* cppException = (Helium::Exception*)addr;
__try
{
// if its non-null
if (cppException)
{
// this will explode if the address isn't really a c++ exception (std::exception)
cppException->What();
}
// i guess we lived!
return cppException;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// uh oh, somebody is throwing register types or another root struct or class
return NULL;
}
}
std::exception* Helium::GetStandardException(uintptr_t addr)
{
std::exception* cppException = (std::exception*)addr;
__try
{
// if its non-null
if (cppException)
{
// this will explode if the address isn't really a c++ exception (std::exception)
cppException->what();
}
// i guess we lived!
return cppException;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// uh oh, somebody is throwing register types or another root struct or class
return NULL;
}
}
bool Helium::GetStackTrace(std::vector<uintptr_t>& trace, unsigned omitFrames)
{
// Some techniques borrowed from Visual Leak Detector 1.9
// (http://www.codeproject.com/tools/visualleakdetector.asp)
CONTEXT context;
volatile char *p = 0;
__try
{
*p = 0;
}
__except(CopyMemory(&context, (GetExceptionInformation())->ContextRecord, sizeof(context)), EXCEPTION_EXECUTE_HANDLER)
{
}
return GetStackTrace(&context, trace, omitFrames+1);
}
bool Helium::GetStackTrace(LPCONTEXT context, std::vector<uintptr_t>& stack, unsigned omitFrames)
{
HELIUM_ASSERT( g_Initialized );
// load debugging information
EnumerateLoadedModules();
if (omitFrames == 0)
{
// our our current location as the top of the stack
stack.push_back( context->IPREG );
}
else
{
omitFrames--;
}
// this is for handling stack overflows
std::map<int64_t, uint32_t> visited;
// setup the stack frame to use for traversal
STACKFRAME64 frame;
memset(&frame,0,sizeof(frame));
frame.AddrPC.Offset = context->IPREG;
frame.AddrPC.Segment = 0;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Offset = context->SPREG;
frame.AddrStack.Segment = 0;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Offset = context->BPREG;
frame.AddrFrame.Segment = 0;
frame.AddrFrame.Mode = AddrModeFlat;
// make a copy here because StackWalk64 can modify the one you give it
CONTEXT context_copy;
memcpy(&context_copy, context, sizeof(context_copy));
while(1)
{
if (!StackWalk64(IMAGE_FILE_ARCH,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
&context_copy,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL))
{
break;
}
if (frame.AddrReturn.Offset == 0x0 || frame.AddrReturn.Offset == 0xffffffffcccccccc)
{
break;
}
if (visited[ frame.AddrReturn.Offset ]++ >= 8192)
{
break;
}
#ifdef DEBUG_SYMBOLS
Print( TXT( "0x%" HELIUM_PRINT_POINTER " - %s\n" ), frame.AddrReturn.Offset, GetSymbolInfo(frame.AddrReturn.Offset, false).c_str() );
#endif
if (omitFrames == 0)
{
stack.push_back( (uintptr_t)frame.AddrReturn.Offset );
}
else
{
omitFrames--;
}
}
return !stack.empty();
}
void Helium::TranslateStackTrace(const std::vector<uintptr_t>& trace, std::string& buffer)
{
std::vector<uintptr_t>::const_iterator itr = trace.begin();
std::vector<uintptr_t>::const_iterator end = trace.end();
for ( ; itr != end; ++itr )
{
PrintToString(buffer, TXT("0x%" HELIUM_PRINT_POINTER " - %s\n"), *itr, GetSymbolInfo(*itr, false).c_str() );
}
}
const char* Helium::GetExceptionClass(uint32_t exceptionCode)
{
const char* ex_name = NULL;
switch (exceptionCode)
{
case EXCEPTION_ACCESS_VIOLATION:
ex_name = TXT("EXCEPTION_ACCESS_VIOLATION");
break;
case EXCEPTION_BREAKPOINT:
ex_name = TXT("EXCEPTION_BREAKPOINT");
break;
case EXCEPTION_SINGLE_STEP:
ex_name = TXT("EXCEPTION_SINGLE_STEP");
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
ex_name = TXT("EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
ex_name = TXT("EXCEPTION_FLT_DENORMAL_OPERAND");
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
ex_name = TXT("EXCEPTION_FLT_DIVIDE_BY_ZERO");
break;
case EXCEPTION_FLT_INEXACT_RESULT:
ex_name = TXT("EXCEPTION_FLT_INEXACT_RESULT");
break;
case EXCEPTION_FLT_INVALID_OPERATION:
ex_name = TXT("EXCEPTION_FLT_INVALID_OPERATION");
break;
case EXCEPTION_FLT_OVERFLOW:
ex_name = TXT("EXCEPTION_FLT_OVERFLOW");
break;
case EXCEPTION_FLT_STACK_CHECK:
ex_name = TXT("EXCEPTION_FLT_STACK_CHECK");
break;
case EXCEPTION_FLT_UNDERFLOW:
ex_name = TXT("EXCEPTION_FLT_UNDERFLOW");
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
ex_name = TXT("EXCEPTION_INT_DIVIDE_BY_ZERO");
break;
case EXCEPTION_INT_OVERFLOW:
ex_name = TXT("EXCEPTION_INT_OVERFLOW");
break;
case EXCEPTION_PRIV_INSTRUCTION:
ex_name = TXT("EXCEPTION_PRIV_INSTRUCTION");
break;
case EXCEPTION_IN_PAGE_ERROR:
ex_name = TXT("EXCEPTION_IN_PAGE_ERROR");
break;
case EXCEPTION_ILLEGAL_INSTRUCTION:
ex_name = TXT("EXCEPTION_ILLEGAL_INSTRUCTION");
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
ex_name = TXT("EXCEPTION_NONCONTINUABLE_EXCEPTION");
break;
case EXCEPTION_STACK_OVERFLOW:
ex_name = TXT("EXCEPTION_STACK_OVERFLOW");
break;
case EXCEPTION_INVALID_DISPOSITION:
ex_name = TXT("EXCEPTION_INVALID_DISPOSITION");
break;
case EXCEPTION_GUARD_PAGE:
ex_name = TXT("EXCEPTION_GUARD_PAGE");
break;
case EXCEPTION_INVALID_HANDLE:
ex_name = TXT("EXCEPTION_INVALID_HANDLE");
break;
case 0xC00002B5:
ex_name = TXT("Multiple floating point traps");
break;
}
if (ex_name == NULL)
{
ex_name = TXT("Unknown Exception");
}
return ex_name;
}
void Helium::GetExceptionDetails( LPEXCEPTION_POINTERS info, ExceptionArgs& args )
{
static Helium::Mutex s_ExceptionMutex;
Helium::MutexScopeLock mutex ( s_ExceptionMutex );
typedef std::vector< std::pair<DWORD, HANDLE> > V_ThreadHandles;
V_ThreadHandles threads;
// the first thing we do is check out other threads, since they are still running!
HANDLE snapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if ( snapshot != INVALID_HANDLE_VALUE )
{
THREADENTRY32 thread;
memset(&thread, 0, sizeof( thread ));
thread.dwSize = sizeof( thread );
if ( Thread32First(snapshot, &thread) )
{
do
{
if ( thread.th32OwnerProcessID == GetCurrentProcessId() && thread.th32ThreadID != GetCurrentThreadId() )
{
HANDLE handle = ::OpenThread( THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, FALSE, thread.th32ThreadID );
if ( handle )
{
::SuspendThread( handle );
threads.push_back( std::make_pair( thread.th32ThreadID, handle ) );
}
}
}
while ( Thread32Next( snapshot, &thread ) );
}
::CloseHandle( snapshot );
}
V_ThreadHandles::const_iterator itr = threads.begin();
V_ThreadHandles::const_iterator end = threads.end();
for ( ; itr != end; ++itr )
{
DWORD id = itr->first;
HANDLE handle = itr->second;
args.m_Threads.push_back( TXT("") );
PrintToString( args.m_Threads.back(), TXT("Thread %d:\n"), id );
std::string::size_type size = args.m_Threads.back().size();
CONTEXT context;
memset(&context, 0, sizeof( context ));
context.ContextFlags = CONTEXT_FULL;
if ( ::GetThreadContext( handle, &context ) )
{
PrintToString( args.m_Threads.back(),
TXT("\nControl Registers:\n")
TXT("EIP = 0x%" HELIUM_PRINT_POINTER " ESP = 0x%" HELIUM_PRINT_POINTER "\n")
TXT("EBP = 0x%" HELIUM_PRINT_POINTER " EFL = 0x%" HELIUM_PRINT_POINTER "\n"),
info->ContextRecord->IPREG,
info->ContextRecord->SPREG,
info->ContextRecord->BPREG,
info->ContextRecord->EFlags );
PrintToString( args.m_Threads.back(),
TXT("\nInteger Registers:\n")
TXT("EAX = 0x%" HELIUM_PRINT_POINTER " EBX = 0x%" HELIUM_PRINT_POINTER "\n")
TXT("ECX = 0x%" HELIUM_PRINT_POINTER " EDX = 0x%" HELIUM_PRINT_POINTER "\n")
TXT("ESI = 0x%" HELIUM_PRINT_POINTER " EDI = 0x%" HELIUM_PRINT_POINTER "\n"),
info->ContextRecord->AXREG,
info->ContextRecord->BXREG,
info->ContextRecord->CXREG,
info->ContextRecord->DXREG,
info->ContextRecord->SIREG,
info->ContextRecord->DIREG );
PrintToString( args.m_Threads.back(), TXT("\nCallstack:\n") );
std::vector<uintptr_t> trace;
if ( GetStackTrace( &context, trace ) )
{
TranslateStackTrace( trace, args.m_Threads.back() );
}
}
if ( args.m_Threads.back().size() == size )
{
args.m_Threads.back() += TXT("No thread info\n");
}
::ResumeThread( handle );
::CloseHandle( handle );
}
threads.clear();
args.m_SEHCode = info->ExceptionRecord->ExceptionCode;
args.m_SEHClass = GetExceptionClass( info->ExceptionRecord->ExceptionCode );
if (info->ExceptionRecord->ExceptionCode == 0xE06D7363) // Microsoft C++ Exception code
{
args.m_Type = ExceptionTypes::CPP;
Helium::Exception* ex = GetHeliumException(info->ExceptionRecord->ExceptionInformation[1]);
if (ex)
{
const char* cppClass = "Unknown";
#ifdef _CPPRTTI
try
{
cppClass = typeid(*ex).name();
}
catch (...)
{
}
#else
cppClass = "Unknown, no RTTI";
#endif
Helium::ConvertString( cppClass, args.m_CPPClass );
Helium::ConvertString( ex->What(), args.m_Message );
}
else
{
std::exception* ex = GetStandardException(info->ExceptionRecord->ExceptionInformation[1]);
if ( ex )
{
const char* cppClass = "Unknown";
#ifdef _CPPRTTI
try
{
cppClass = typeid(*ex).name();
}
catch (...)
{
cppClass = "Unknown";
}
#else
cppClass = "Unknown, no RTTI";
#endif
Helium::ConvertString( cppClass, args.m_CPPClass );
Helium::ConvertString( ex->what(), args.m_Message );
}
}
if ( args.m_CPPClass.empty() && args.m_Message.empty() )
{
args.m_Message = TXT("Thrown object is not a known type of C++ exception");
}
info->ContextRecord->IPREG = (DWORD)info->ExceptionRecord->ExceptionInformation[2];
}
else
{
args.m_Type = ExceptionTypes::Structured;
if (args.m_SEHCode == EXCEPTION_ACCESS_VIOLATION)
{
PrintToString( args.m_Message, TXT("Attempt to %s address 0x%" HELIUM_PRINT_POINTER ""), (info->ExceptionRecord->ExceptionInformation[0]==1)?TXT("write to"):TXT("read from"), info->ExceptionRecord->ExceptionInformation[1]);
}
if (info->ContextRecord->ContextFlags & CONTEXT_CONTROL)
{
PrintToString( args.m_SEHControlRegisters,
TXT("Control Registers:\n")
TXT("EIP = 0x%" HELIUM_PRINT_POINTER " ESP = 0x%" HELIUM_PRINT_POINTER "\n")
TXT("EBP = 0x%" HELIUM_PRINT_POINTER " EFL = 0x%" HELIUM_PRINT_POINTER "\n"),
info->ContextRecord->IPREG,
info->ContextRecord->SPREG,
info->ContextRecord->BPREG,
info->ContextRecord->EFlags );
}
if ( info->ContextRecord->ContextFlags & CONTEXT_INTEGER )
{
PrintToString( args.m_SEHIntegerRegisters,
TXT("Integer Registers:\n")
TXT("EAX = 0x%" HELIUM_PRINT_POINTER " EBX = 0x%" HELIUM_PRINT_POINTER "\n")
TXT("ECX = 0x%" HELIUM_PRINT_POINTER " EDX = 0x%" HELIUM_PRINT_POINTER "\n")
TXT("ESI = 0x%" HELIUM_PRINT_POINTER " EDI = 0x%" HELIUM_PRINT_POINTER "\n"),
info->ContextRecord->AXREG,
info->ContextRecord->BXREG,
info->ContextRecord->CXREG,
info->ContextRecord->DXREG,
info->ContextRecord->SIREG,
info->ContextRecord->DIREG );
}
}
std::vector<uintptr_t> trace;
if ( GetStackTrace( info->ContextRecord, trace ) )
{
TranslateStackTrace( trace, args.m_Callstack );
}
}
std::string Helium::GetExceptionInfo(LPEXCEPTION_POINTERS info)
{
ExceptionArgs args ( ExceptionTypes::Structured, false );
GetExceptionDetails( info, args );
std::string buffer;
buffer += TXT("An exception has occurred\n");
switch ( args.m_Type )
{
case ExceptionTypes::CPP:
{
PrintToString( buffer, TXT("Type: C++ Exception\n") );
PrintToString( buffer, TXT("Class: %s\n"), args.m_CPPClass.c_str() );
if ( !args.m_Message.empty() )
{
PrintToString( buffer, TXT("Message:\n%s\n"), args.m_Message.c_str() );
}
break;
}
case ExceptionTypes::Structured:
{
PrintToString( buffer, TXT("Type: SEH Exception\n") );
PrintToString( buffer, TXT("Code: 0x%" HELIUM_PRINT_POINTER "\n"), args.m_SEHCode );
PrintToString( buffer, TXT("Class: %s\n"), args.m_SEHClass.c_str() );
if ( !args.m_Message.empty() )
{
PrintToString( buffer, TXT("Message:\n%s\n"), args.m_Message.c_str() );
}
if ( !args.m_SEHControlRegisters.empty() )
{
PrintToString( buffer, TXT("\n%s"), args.m_SEHControlRegisters.c_str() );
}
if ( !args.m_SEHIntegerRegisters.empty() )
{
PrintToString( buffer, TXT("\n%s"), args.m_SEHIntegerRegisters.c_str() );
}
break;
}
}
buffer += TXT("\nCallstack:\n");
if ( !args.m_Callstack.empty() )
{
PrintToString( buffer, TXT("%s"), args.m_Callstack.c_str() );
}
else
{
buffer += TXT("No call stack info\n");
}
std::vector< std::string >::const_iterator itr = args.m_Threads.begin();
std::vector< std::string >::const_iterator end = args.m_Threads.end();
for ( ; itr != end; ++itr )
{
PrintToString( buffer, TXT("\n%s"), itr->c_str() );
}
return buffer;
}
#if !HELIUM_RELEASE && !HELIUM_PROFILE
static Mutex& GetStackWalkMutex()
{
static Mutex stackWalkMutex;
return stackWalkMutex;
}
static void ConditionalSymInitialize()
{
static volatile bool bSymInitialized = false;
if( !bSymInitialized )
{
HELIUM_TRACE( TraceLevels::Info, TXT( "Initializing symbol handler for the current process...\n" ) );
HANDLE hProcess = GetCurrentProcess();
HELIUM_ASSERT( hProcess );
BOOL bInitialized = SymInitialize( hProcess, NULL, TRUE );
if( bInitialized )
{
HELIUM_TRACE( TraceLevels::Info, TXT( "Symbol handler initialization successful!\n" ) );
}
else
{
HELIUM_TRACE(
TraceLevels::Info,
TXT( "Symbol handler initialization failed (error code %u).\n" ),
::GetLastError() );
}
bSymInitialized = true;
}
}
/// Get the current stack trace.
///
/// @param[out] ppStackTraceArray Array in which to store the backtrace of program counter addresses.
/// @param[in] stackTraceArraySize Maximum number of addresses to fill in the output array.
/// @param[in] skipCount Number of stack levels to skip before filling the output array, counting the stack
/// level for this function call. By default, this is one, meaning that only the call
/// to this function is skipped.
///
/// @return Number of addresses stored in the output array.
size_t Helium::GetStackTrace( void** ppStackTraceArray, size_t stackTraceArraySize, size_t skipCount )
{
HELIUM_ASSERT( ppStackTraceArray || stackTraceArraySize == 0 );
MutexScopeLock scopeLock( GetStackWalkMutex() );
ConditionalSymInitialize();
// Get the current context.
CONTEXT context;
RtlCaptureContext( &context );
// Initialize the stack frame structure for the first call to StackWalk64().
STACKFRAME64 stackFrame;
MemoryZero( &stackFrame, sizeof( stackFrame ) );
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrFrame.Mode = AddrModeFlat;
stackFrame.AddrStack.Mode = AddrModeFlat;
#if HELIUM_OS_WIN32
const DWORD machineType = IMAGE_FILE_MACHINE_I386;
stackFrame.AddrPC.Offset = context.Eip;
stackFrame.AddrFrame.Offset = context.Ebp;
stackFrame.AddrStack.Offset = context.Esp;
#else
// Assuming x86-64 (likely not supporting Itanium).
const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
stackFrame.AddrPC.Offset = context.Rip;
stackFrame.AddrFrame.Offset = context.Rdi/*Rbp*/;
stackFrame.AddrStack.Offset = context.Rsp;
#endif
HANDLE hProcess = GetCurrentProcess();
HELIUM_ASSERT( hProcess );
HANDLE hThread = GetCurrentThread();
HELIUM_ASSERT( hThread );
// Skip addresses first.
for( size_t skipIndex = 0; skipIndex < skipCount; ++skipIndex )
{
BOOL bResult = StackWalk64(
machineType,
hProcess,
hThread,
&stackFrame,
&context,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL );
if( !bResult || stackFrame.AddrPC.Offset == 0 )
{
return 0;
}
}
// Fill out the remaining stack frame addresses up to the output array limit.
for( size_t traceIndex = 0; traceIndex < stackTraceArraySize; ++traceIndex )
{
BOOL bResult = StackWalk64(
machineType,
hProcess,
hThread,
&stackFrame,
&context,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL );
if( !bResult || stackFrame.AddrPC.Offset == 0 )
{
return traceIndex;
}
ppStackTraceArray[ traceIndex ] =
reinterpret_cast< void* >( static_cast< uintptr_t >( stackFrame.AddrPC.Offset ) );
}
return stackTraceArraySize;
}
/// Get the symbol for the specified address.
///
/// @param[out] rSymbol Address symbol.
/// @param[in] pAddress Address to translate.
///
/// @return True if the address was successfully resolved, false if not.
void Helium::GetAddressSymbol( std::string& rSymbol, void* pAddress )
{
HELIUM_ASSERT( pAddress );
MutexScopeLock scopeLock( GetStackWalkMutex() );
ConditionalSymInitialize();
// rSymbol.Remove( 0, rSymbol.GetSize() );
rSymbol.clear();
HANDLE hProcess = GetCurrentProcess();
HELIUM_ASSERT( hProcess );
bool bAddedModuleName = false;
DWORD64 moduleBase = SymGetModuleBase64( hProcess, reinterpret_cast< uintptr_t >( pAddress ) );
if( moduleBase )
{
IMAGEHLP_MODULE64 moduleInfo;
MemoryZero( &moduleInfo, sizeof( moduleInfo ) );
moduleInfo.SizeOfStruct = sizeof( moduleInfo );
if( SymGetModuleInfo64( hProcess, moduleBase, &moduleInfo ) )
{
rSymbol += TXT( "(" );
HELIUM_WIDE_TO_TCHAR( moduleInfo.ModuleName, convertedModuleName );
rSymbol += convertedModuleName;
rSymbol += TXT( ") " );
bAddedModuleName = true;
}
}
if( !bAddedModuleName )
{
rSymbol += TXT( "(???) " );
}
uint64_t symbolInfoBuffer[
( sizeof( SYMBOL_INFO ) + sizeof( char ) * ( MAX_SYM_NAME - 1 ) + sizeof( uint64_t ) - 1 ) /
sizeof( uint64_t ) ];
MemoryZero( symbolInfoBuffer, sizeof( symbolInfoBuffer ) );
SYMBOL_INFO& rSymbolInfo = *reinterpret_cast< SYMBOL_INFO* >( &symbolInfoBuffer[ 0 ] );
rSymbolInfo.SizeOfStruct = sizeof( SYMBOL_INFO );
rSymbolInfo.MaxNameLen = MAX_SYM_NAME;
if( SymFromAddr( hProcess, reinterpret_cast< uintptr_t >( pAddress ), NULL, &rSymbolInfo ) )
{
rSymbolInfo.Name[ MAX_SYM_NAME - 1 ] = TXT( '\0' );
HELIUM_WIDE_TO_TCHAR( rSymbolInfo.Name, convertedName );
rSymbol += convertedName;
rSymbol += TXT( " " );
}
else
{
rSymbol += TXT( "??? " );
}
DWORD displacement = 0;
IMAGEHLP_LINE64 lineInfo;
MemoryZero( &lineInfo, sizeof( lineInfo ) );
lineInfo.SizeOfStruct = sizeof( lineInfo );
if( SymGetLineFromAddr64( hProcess, reinterpret_cast< uintptr_t >( pAddress ), &displacement, &lineInfo ) )
{
char lineNumberBuffer[ 32 ];
StringPrint( lineNumberBuffer, HELIUM_ARRAY_COUNT( lineNumberBuffer ), TXT( "%u" ), lineInfo.LineNumber );
lineNumberBuffer[ HELIUM_ARRAY_COUNT( lineNumberBuffer ) - 1 ] = TXT( '\0' );
rSymbol += TXT( "(" );
HELIUM_WIDE_TO_TCHAR( lineInfo.FileName, convertedFileName );
rSymbol += convertedFileName;
rSymbol += TXT( ", line " );
rSymbol += lineNumberBuffer;
rSymbol += TXT( ")" );
}
else
{
rSymbol += TXT( "(???, line ?)" );
}
}
/// Write a string to any platform-specific debug log output.
///
/// @param[in] pMessage Message string to write to the debug log.
void Helium::DebugLog( const char* pMessage )
{
HELIUM_ASSERT( pMessage );
HELIUM_TCHAR_TO_WIDE( pMessage, convertedMessage );
OutputDebugStringW( convertedMessage );
}
#endif // !HELIUM_RELEASE && !HELIUM_PROFILE