-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathstacktools.cpp
1707 lines (1369 loc) · 52.4 KB
/
stacktools.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
//===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $Workfile: $
// $NoKeywords: $
//===========================================================================//
#include "pch_tier0.h"
#include "tier0/stacktools.h"
#include "tier0/threadtools.h"
#include "tier0/icommandline.h"
#include "tier0/valve_off.h"
#if defined( PLATFORM_WINDOWS_PC )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <dbghelp.h>
#endif
#if defined( PLATFORM_X360 )
#include <xbdm.h>
#include "xbox/xbox_console.h"
#include "xbox/xbox_vxconsole.h"
#include <map>
#include <set>
#endif
#if defined( LINUX ) && defined( PLATFORM_GLIBC )
#include <execinfo.h>
#endif
#include "tier0/valve_on.h"
#include "tier0/memdbgon.h"
#if !defined( ENABLE_RUNTIME_STACK_TRANSLATION ) //disable the whole toolset
#if defined( LINUX ) && defined( PLATFORM_GLIBC )
int GetCallStack( void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
return backtrace( pReturnAddressesOut, iArrayCount );
}
int GetCallStack_Fast( void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
return backtrace( pReturnAddressesOut, iArrayCount );
}
#else
int GetCallStack( void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
return 0;
}
int GetCallStack_Fast( void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
return 0;
}
#endif
//where we'll find our PDB's for win32. Translation will not work until this has been called once (even if with NULL)
void SetStackTranslationSymbolSearchPath( const char *szSemicolonSeparatedList )
{
}
void StackToolsNotify_LoadedLibrary( const char *szLibName )
{
}
int TranslateStackInfo( const void * const *pCallStack, int iCallStackCount, tchar *szOutput, int iOutBufferSize, const tchar *szEntrySeparator, TranslateStackInfo_StyleFlags_t style )
{
if( iOutBufferSize > 0 )
*szOutput = '\0';
return 0;
}
void PreloadStackInformation( const void **pAddresses, int iAddressCount )
{
}
bool GetFileAndLineFromAddress( const void *pAddress, tchar *pFileNameOut, int iMaxFileNameLength, uint32 &iLineNumberOut, uint32 *pDisplacementOut )
{
if( iMaxFileNameLength > 0 )
*pFileNameOut = '\0';
return false;
}
bool GetSymbolNameFromAddress( const void *pAddress, tchar *pSymbolNameOut, int iMaxSymbolNameLength, uint64 *pDisplacementOut )
{
if( iMaxSymbolNameLength > 0 )
*pSymbolNameOut = '\0';
return false;
}
bool GetModuleNameFromAddress( const void *pAddress, tchar *pModuleNameOut, int iMaxModuleNameLength )
{
if( iMaxModuleNameLength > 0 )
*pModuleNameOut = '\0';
return false;
}
#else //#if !defined( ENABLE_RUNTIME_STACK_TRANSLATION )
//===============================================================================================================
// Shared Windows/X360 code
//===============================================================================================================
CTHREADLOCALPTR( CStackTop_Base ) g_StackTop;
class CStackTop_FriendFuncs : public CStackTop_Base
{
public:
friend int AppendParentStackTrace( void **pReturnAddressesOut, int iArrayCount, int iAlreadyFilled );
friend int GetCallStack_Fast( void **pReturnAddressesOut, int iArrayCount, int iSkipCount );
};
inline int AppendParentStackTrace( void **pReturnAddressesOut, int iArrayCount, int iAlreadyFilled )
{
CStackTop_FriendFuncs *pTop = (CStackTop_FriendFuncs *)(CStackTop_Base *)g_StackTop;
if( pTop != NULL )
{
if( pTop->m_pReplaceAddress != NULL )
{
for( int i = iAlreadyFilled; --i >= 0; )
{
if( pReturnAddressesOut[i] == pTop->m_pReplaceAddress )
{
iAlreadyFilled = i;
break;
}
}
}
if( pTop->m_iParentStackTraceLength != 0 )
{
int iCopy = MIN( iArrayCount - iAlreadyFilled, pTop->m_iParentStackTraceLength );
memcpy( pReturnAddressesOut + iAlreadyFilled, pTop->m_pParentStackTrace, iCopy * sizeof( void * ) );
iAlreadyFilled += iCopy;
}
}
return iAlreadyFilled;
}
inline bool ValidStackAddress( void *pAddress, const void *pNoLessThan, const void *pNoGreaterThan )
{
if( (uintp)pAddress & 3 )
return false;
if( pAddress < pNoLessThan ) //frame pointer traversal should always increase the pointer
return false;
if( pAddress > pNoGreaterThan ) //never traverse outside the stack (Oh 0xCCCCCCCC, how I hate you)
return false;
#if defined( WIN32 ) && !defined( _X360 ) && 1
if( IsBadReadPtr( pAddress, (sizeof( void * ) * 2) ) ) //safety net, but also throws an exception (handled internally) to stop bad access
return false;
#endif
return true;
}
#pragma auto_inline( off )
int GetCallStack_Fast( void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
//Only tested in windows. This function won't work with frame pointer omission enabled. "vpc /nofpo" all projects
#if (defined( TIER0_FPO_DISABLED ) || defined( _DEBUG )) &&\
(defined( WIN32 ) && !defined( _X360 ) && !defined(_M_X64))
void *pStackCrawlEBP;
__asm
{
mov [pStackCrawlEBP], ebp;
}
/*
With frame pointer omission disabled, this should be the pattern all the way up the stack
[ebp+00] Old ebp value
[ebp+04] Return address
*/
void *pNoLessThan = pStackCrawlEBP; //impossible for a valid stack to traverse before this address
int i;
CStackTop_FriendFuncs *pTop = (CStackTop_FriendFuncs *)(CStackTop_Base *)g_StackTop;
if( pTop != NULL ) //we can do fewer error checks if we have a valid reference point for the top of the stack
{
void *pNoGreaterThan = pTop->m_pStackBase;
//skips
for( i = 0; i != iSkipCount; ++i )
{
if( (pStackCrawlEBP < pNoLessThan) || (pStackCrawlEBP > pNoGreaterThan) )
return AppendParentStackTrace( pReturnAddressesOut, iArrayCount, 0 );
pNoLessThan = pStackCrawlEBP;
pStackCrawlEBP = *(void **)pStackCrawlEBP; //should be pointing at old ebp value
}
//store
for( i = 0; i != iArrayCount; ++i )
{
if( (pStackCrawlEBP < pNoLessThan) || (pStackCrawlEBP > pNoGreaterThan) )
break;
pReturnAddressesOut[i] = *((void **)pStackCrawlEBP + 1);
pNoLessThan = pStackCrawlEBP;
pStackCrawlEBP = *(void **)pStackCrawlEBP; //should be pointing at old ebp value
}
return AppendParentStackTrace( pReturnAddressesOut, iArrayCount, i );
}
else
{
void *pNoGreaterThan = ((unsigned char *)pNoLessThan) + (1024 * 1024); //standard stack is 1MB. TODO: Get actual stack end address if available since this check isn't foolproof
//skips
for( i = 0; i != iSkipCount; ++i )
{
if( !ValidStackAddress( pStackCrawlEBP, pNoLessThan, pNoGreaterThan ) )
return AppendParentStackTrace( pReturnAddressesOut, iArrayCount, 0 );
pNoLessThan = pStackCrawlEBP;
pStackCrawlEBP = *(void **)pStackCrawlEBP; //should be pointing at old ebp value
}
//store
for( i = 0; i != iArrayCount; ++i )
{
if( !ValidStackAddress( pStackCrawlEBP, pNoLessThan, pNoGreaterThan ) )
break;
pReturnAddressesOut[i] = *((void **)pStackCrawlEBP + 1);
pNoLessThan = pStackCrawlEBP;
pStackCrawlEBP = *(void **)pStackCrawlEBP; //should be pointing at old ebp value
}
return AppendParentStackTrace( pReturnAddressesOut, iArrayCount, i );
}
#endif
return 0;
}
#pragma auto_inline( on )
#if defined( WIN32 ) && !defined( _X360 )
//===============================================================================================================
// Windows version of the toolset
//===============================================================================================================
#if defined( TIER0_FPO_DISABLED )
//# define USE_CAPTURESTACKBACKTRACE //faster than StackWalk64, but only works on XP or newer and only with Frame Pointer Omission optimization disabled(/Oy-) for every function it traces through
#endif
#if defined(_M_IX86) || defined(_M_X64)
# define USE_STACKWALK64
# if defined(_M_IX86)
# define STACKWALK64_MACHINETYPE IMAGE_FILE_MACHINE_I386
# else
# define STACKWALK64_MACHINETYPE IMAGE_FILE_MACHINE_AMD64
# endif
#endif
typedef DWORD (WINAPI *PFN_SymGetOptions)( VOID );
typedef DWORD (WINAPI *PFN_SymSetOptions)( IN DWORD SymOptions );
typedef BOOL (WINAPI *PFN_SymSetSearchPath)( IN HANDLE hProcess, IN PSTR SearchPath );
typedef BOOL (WINAPI *PFN_SymInitialize)( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess );
typedef BOOL (WINAPI *PFN_SymCleanup)( IN HANDLE hProcess );
typedef BOOL (WINAPI *PFN_SymEnumerateModules64)( IN HANDLE hProcess, IN PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback, IN PVOID UserContext );
typedef BOOL (WINAPI *PFN_EnumerateLoadedModules64)( IN HANDLE hProcess, IN PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback, IN PVOID UserContext );
typedef DWORD64 (WINAPI *PFN_SymLoadModule64)( IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll );
typedef BOOL (WINAPI *PFN_SymUnloadModule64)( IN HANDLE hProcess, IN DWORD64 BaseOfDll );
typedef BOOL (WINAPI *PFN_SymFromAddr)( IN HANDLE hProcess, IN DWORD64 Address, OUT PDWORD64 Displacement, IN OUT PSYMBOL_INFO Symbol );
typedef BOOL (WINAPI *PFN_SymGetLineFromAddr64)( IN HANDLE hProcess, IN DWORD64 qwAddr, OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line64 );
typedef BOOL (WINAPI *PFN_SymGetModuleInfo64)( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PIMAGEHLP_MODULE64 ModuleInfo );
typedef BOOL (WINAPI *PFN_StackWalk64)( DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress );
typedef USHORT (WINAPI *PFN_CaptureStackBackTrace)( IN ULONG FramesToSkip, IN ULONG FramesToCapture, OUT PVOID *BackTrace, OUT OPTIONAL PULONG BackTraceHash );
DWORD WINAPI SymGetOptions_DummyFn( VOID )
{
return 0;
}
DWORD WINAPI SymSetOptions_DummyFn( IN DWORD SymOptions )
{
return 0;
}
BOOL WINAPI SymSetSearchPath_DummyFn( IN HANDLE hProcess, IN PSTR SearchPath )
{
return FALSE;
}
BOOL WINAPI SymInitialize_DummyFn( IN HANDLE hProcess, IN PSTR UserSearchPath, IN BOOL fInvadeProcess )
{
return FALSE;
}
BOOL WINAPI SymCleanup_DummyFn( IN HANDLE hProcess )
{
return TRUE;
}
BOOL WINAPI SymEnumerateModules64_DummyFn( IN HANDLE hProcess, IN PSYM_ENUMMODULES_CALLBACK64 EnumModulesCallback, IN PVOID UserContext )
{
return FALSE;
}
BOOL WINAPI EnumerateLoadedModules64_DummyFn( IN HANDLE hProcess, IN PENUMLOADED_MODULES_CALLBACK64 EnumLoadedModulesCallback, IN PVOID UserContext )
{
return FALSE;
}
DWORD64 WINAPI SymLoadModule64_DummyFn( IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll )
{
return 0;
}
BOOL WINAPI SymUnloadModule64_DummyFn( IN HANDLE hProcess, IN DWORD64 BaseOfDll )
{
return FALSE;
}
BOOL WINAPI SymFromAddr_DummyFn( IN HANDLE hProcess, IN DWORD64 Address, OUT PDWORD64 Displacement, IN OUT PSYMBOL_INFO Symbol )
{
return FALSE;
}
BOOL WINAPI SymGetLineFromAddr64_DummyFn( IN HANDLE hProcess, IN DWORD64 qwAddr, OUT PDWORD pdwDisplacement, OUT PIMAGEHLP_LINE64 Line64 )
{
return FALSE;
}
BOOL WINAPI SymGetModuleInfo64_DummyFn( IN HANDLE hProcess, IN DWORD64 dwAddr, OUT PIMAGEHLP_MODULE64 ModuleInfo )
{
return FALSE;
}
BOOL WINAPI StackWalk64_DummyFn( DWORD MachineType, HANDLE hProcess, HANDLE hThread, LPSTACKFRAME64 StackFrame, PVOID ContextRecord, PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress )
{
return FALSE;
}
USHORT WINAPI CaptureStackBackTrace_DummyFn( IN ULONG FramesToSkip, IN ULONG FramesToCapture, OUT PVOID *BackTrace, OUT OPTIONAL PULONG BackTraceHash )
{
return 0;
}
class CHelperFunctionsLoader
{
public:
CHelperFunctionsLoader( void )
{
m_bIsInitialized = false;
m_bShouldReloadSymbols = false;
m_hDbgHelpDll = NULL;
m_szPDBSearchPath = NULL;
m_pSymInitialize = SymInitialize_DummyFn;
m_pSymCleanup = SymCleanup_DummyFn;
m_pSymSetOptions = SymSetOptions_DummyFn;
m_pSymGetOptions = SymGetOptions_DummyFn;
m_pSymSetSearchPath = SymSetSearchPath_DummyFn;
m_pSymEnumerateModules64 = SymEnumerateModules64_DummyFn;
m_pEnumerateLoadedModules64 = EnumerateLoadedModules64_DummyFn;
m_pSymLoadModule64 = SymLoadModule64_DummyFn;
m_pSymUnloadModule64 = SymUnloadModule64_DummyFn;
m_pSymFromAddr = SymFromAddr_DummyFn;
m_pSymGetLineFromAddr64 = SymGetLineFromAddr64_DummyFn;
m_pSymGetModuleInfo64 = SymGetModuleInfo64_DummyFn;
#if defined( USE_STACKWALK64 )
m_pStackWalk64 = StackWalk64_DummyFn;
#endif
#if defined( USE_CAPTURESTACKBACKTRACE )
m_pCaptureStackBackTrace = CaptureStackBackTrace_DummyFn;
m_hNTDllDll = NULL;
#endif
}
~CHelperFunctionsLoader( void )
{
m_pSymCleanup( m_hProcess );
if( m_hDbgHelpDll != NULL )
::FreeLibrary( m_hDbgHelpDll );
#if defined( USE_CAPTURESTACKBACKTRACE )
if( m_hNTDllDll != NULL )
::FreeLibrary( m_hNTDllDll );
#endif
if( m_szPDBSearchPath != NULL )
delete []m_szPDBSearchPath;
}
static BOOL CALLBACK UnloadSymbolsCallback( PSTR ModuleName, DWORD64 BaseOfDll, PVOID UserContext )
{
const CHelperFunctionsLoader *pThis = ((CHelperFunctionsLoader *)UserContext);
pThis->m_pSymUnloadModule64( pThis->m_hProcess, BaseOfDll );
return TRUE;
}
#if _MSC_VER >= 1600
static BOOL CALLBACK LoadSymbolsCallback( PCSTR ModuleName, DWORD64 ModuleBase, ULONG ModuleSize, PVOID UserContext )
#else
static BOOL CALLBACK LoadSymbolsCallback( PSTR ModuleName, DWORD64 ModuleBase, ULONG ModuleSize, PVOID UserContext )
#endif
{
const CHelperFunctionsLoader *pThis = ((CHelperFunctionsLoader *)UserContext);
//SymLoadModule64( IN HANDLE hProcess, IN HANDLE hFile, IN PSTR ImageName, IN PSTR ModuleName, IN DWORD64 BaseOfDll, IN DWORD SizeOfDll );
pThis->m_pSymLoadModule64( pThis->m_hProcess, NULL, (PSTR)ModuleName, (PSTR)ModuleName, ModuleBase, ModuleSize );
return TRUE;
}
void TryLoadingNewSymbols( void )
{
AUTO_LOCK( m_Mutex );
if( m_bIsInitialized )
{
//m_pSymEnumerateModules64( m_hProcess, UnloadSymbolsCallback, this ); //unloaded modules we've already loaded
m_pEnumerateLoadedModules64( m_hProcess, LoadSymbolsCallback, this ); //load everything
m_bShouldReloadSymbols = false;
}
}
void SetStackTranslationSymbolSearchPath( const char *szSemicolonSeparatedList )
{
AUTO_LOCK( m_Mutex );
if( m_szPDBSearchPath != NULL )
delete []m_szPDBSearchPath;
if( szSemicolonSeparatedList == NULL )
{
m_szPDBSearchPath = NULL;
return;
}
int iLength = (int)strlen( szSemicolonSeparatedList ) + 1;
char *pNewPath = new char [iLength];
memcpy( pNewPath, szSemicolonSeparatedList, iLength );
m_szPDBSearchPath = pNewPath;
//re-init search paths. Or if we haven't yet loaded dbghelp.dll, this will go to the dummy function and do nothing
m_pSymSetSearchPath( m_hProcess, m_szPDBSearchPath );
//TryLoadingNewSymbols();
m_bShouldReloadSymbols = true;
}
bool GetSymbolNameFromAddress( const void *pAddress, tchar *pSymbolNameOut, int iMaxSymbolNameLength, uint64 *pDisplacementOut )
{
if( pAddress == NULL )
return false;
AUTO_LOCK( m_Mutex );
unsigned char genericbuffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME*sizeof(TCHAR)];
((PSYMBOL_INFO)genericbuffer)->SizeOfStruct = sizeof(SYMBOL_INFO);
((PSYMBOL_INFO)genericbuffer)->MaxNameLen = MAX_SYM_NAME;
DWORD64 dwDisplacement;
if( m_pSymFromAddr( m_hProcess, (DWORD64)pAddress, &dwDisplacement, (PSYMBOL_INFO)genericbuffer) )
{
strncpy( pSymbolNameOut, ((PSYMBOL_INFO)genericbuffer)->Name, iMaxSymbolNameLength );
if( pDisplacementOut != NULL )
*pDisplacementOut = dwDisplacement;
return true;
}
return false;
}
bool GetFileAndLineFromAddress( const void *pAddress, tchar *pFileNameOut, int iMaxFileNameLength, uint32 &iLineNumberOut, uint32 *pDisplacementOut )
{
if( pAddress == NULL )
return false;
AUTO_LOCK( m_Mutex );
tchar szBuffer[1024];
szBuffer[0] = _T('\0');
IMAGEHLP_LINE64 imageHelpLine64;
imageHelpLine64.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
imageHelpLine64.FileName = szBuffer;
DWORD dwDisplacement;
if( m_pSymGetLineFromAddr64( m_hProcess, (DWORD64)pAddress, &dwDisplacement, &imageHelpLine64 ) )
{
strncpy( pFileNameOut, imageHelpLine64.FileName, iMaxFileNameLength );
iLineNumberOut = imageHelpLine64.LineNumber;
if( pDisplacementOut != NULL )
*pDisplacementOut = dwDisplacement;
return true;
}
return false;
}
bool GetModuleNameFromAddress( const void *pAddress, tchar *pModuleNameOut, int iMaxModuleNameLength )
{
AUTO_LOCK( m_Mutex );
IMAGEHLP_MODULE64 moduleInfo;
moduleInfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE64);
if ( m_pSymGetModuleInfo64( m_hProcess, (DWORD64)pAddress, &moduleInfo ) )
{
strncpy( pModuleNameOut, moduleInfo.ModuleName, iMaxModuleNameLength );
return true;
}
return false;
}
//only returns false if we ran out of buffer space.
bool TranslatePointer( const void * const pAddress, tchar *pTranslationOut, int iTranslationBufferLength, TranslateStackInfo_StyleFlags_t style )
{
//AUTO_LOCK( m_Mutex );
if( pTranslationOut == NULL )
return false;
if( iTranslationBufferLength <= 0 )
return false;
//sample desired output
// valid translation - "tier0.dll!CHelperFunctionsLoader::TranslatePointer - u:\Dev\L4D\src\tier0\stacktools.cpp(162) + 4 bytes"
// fallback translation - "tier0.dll!0x01234567"
tchar *pWrite = pTranslationOut;
*pWrite = '\0';
int iLength;
if( style & TSISTYLEFLAG_MODULENAME )
{
if( !this->GetModuleNameFromAddress( pAddress, pWrite, iTranslationBufferLength ) )
strncpy( pWrite, "unknown_module", iTranslationBufferLength );
iLength = (int)strlen( pWrite );
pWrite += iLength;
iTranslationBufferLength -= iLength;
if( iTranslationBufferLength < 2 )
return false; //need more buffer
if( style & TSISTYLEFLAG_SYMBOLNAME )
{
*pWrite = '!';
++pWrite;
--iTranslationBufferLength;
*pWrite = '\0';
}
}
//use symbol name to test if the rest is going to work. So grab it whether they want it or not
if( !this->GetSymbolNameFromAddress( pAddress, pWrite, iTranslationBufferLength, NULL ) )
{
int nBytesWritten = _snprintf( pWrite, iTranslationBufferLength, "0x%p", pAddress );
if ( nBytesWritten < 0 )
{
*pWrite = '\0'; // if we can't write all of the line/lineandoffset, don't write any at all
return false;
}
return true;
}
else if( style & TSISTYLEFLAG_SYMBOLNAME )
{
iLength = (int)strlen( pWrite );
pWrite += iLength;
iTranslationBufferLength -= iLength;
}
else
{
*pWrite = '\0'; //symbol name lookup worked, but unwanted, discard
}
if( style & (TSISTYLEFLAG_FULLPATH | TSISTYLEFLAG_SHORTPATH | TSISTYLEFLAG_LINE | TSISTYLEFLAG_LINEANDOFFSET) )
{
if( pWrite != pTranslationOut ) //if we've written anything yet, separate the printed data from the file name and line
{
if( iTranslationBufferLength < 6 )
return false; //need more buffer
pWrite[0] = ' '; //append " - "
pWrite[1] = '-';
pWrite[2] = ' ';
pWrite[3] = '\0';
pWrite += 3;
iTranslationBufferLength -= 3;
}
uint32 iLine;
uint32 iDisplacement;
char szFileName[MAX_PATH];
if( this->GetFileAndLineFromAddress( pAddress, szFileName, MAX_PATH, iLine, &iDisplacement ) )
{
if( style & TSISTYLEFLAG_FULLPATH )
{
iLength = (int)strlen( szFileName );
if ( iTranslationBufferLength < iLength + 1 )
return false;
memcpy( pWrite, szFileName, iLength + 1 );
pWrite += iLength;
iTranslationBufferLength -= iLength;
}
else if( style & TSISTYLEFLAG_SHORTPATH )
{
//shorten the path and copy
iLength = (int)strlen( szFileName );
char *pShortened = szFileName + iLength;
int iSlashesAllowed = 3;
while( pShortened > szFileName )
{
if( (*pShortened == '\\') || (*pShortened == '/') )
{
--iSlashesAllowed;
if( iSlashesAllowed == 0 )
break;
}
--pShortened;
}
iLength = (int)strlen( pShortened );
if( iTranslationBufferLength < iLength + 1 )
{
//Remove the " - " that we can't append to
pWrite -= 3;
iTranslationBufferLength += 3;
*pWrite = '\0';
return false;
}
memcpy( pWrite, szFileName, iLength + 1 );
pWrite += iLength;
iTranslationBufferLength -= iLength;
}
if( style & (TSISTYLEFLAG_LINE | TSISTYLEFLAG_LINEANDOFFSET) )
{
int nBytesWritten = _snprintf( pWrite, iTranslationBufferLength, ((style & TSISTYLEFLAG_LINEANDOFFSET) && (iDisplacement != 0)) ? "(%d) + %d bytes" : "(%d)", iLine, iDisplacement );
if ( nBytesWritten < 0 )
{
*pWrite = '\0'; // if we can't write all of the line/lineandoffset, don't write any at all
return false;
}
pWrite += nBytesWritten;
iTranslationBufferLength -= nBytesWritten;
}
}
else
{
//Remove the " - " that we didn't append to
pWrite -= 3;
iTranslationBufferLength += 3;
*pWrite = '\0';
}
}
return true;
}
//about to actually use the functions, load if necessary
void EnsureReady( void )
{
if( m_bIsInitialized )
{
if( m_bShouldReloadSymbols )
TryLoadingNewSymbols();
return;
}
AUTO_LOCK( m_Mutex );
//Only enabled for P4 and Steam Beta builds
if( (CommandLine()->FindParm( "-steam" ) != 0) && //is steam
(CommandLine()->FindParm( "-internalbuild" ) == 0) ) //is not steam beta
{
//disable the toolset by falsifying initialized state
m_bIsInitialized = true;
return;
}
m_hProcess = GetCurrentProcess();
if( m_hProcess == NULL )
return;
m_bIsInitialized = true;
// get the function pointer directly so that we don't have to include the .lib, and that
// we can easily change it to using our own dll when this code is used on win98/ME/2K machines
m_hDbgHelpDll = ::LoadLibrary( "DbgHelp.dll" );
if ( !m_hDbgHelpDll )
{
//it's possible it's just way too early to initialize (as shown with attempts at using these tools in the memory allocator)
if( m_szPDBSearchPath == NULL ) //not a rock solid check, but pretty good compromise between endless failing initialization and general failure due to trying too early
m_bIsInitialized = false;
return;
}
m_pSymInitialize = (PFN_SymInitialize) ::GetProcAddress( m_hDbgHelpDll, "SymInitialize" );
if( m_pSymInitialize == NULL )
{
//very bad
::FreeLibrary( m_hDbgHelpDll );
m_hDbgHelpDll = NULL;
m_pSymInitialize = SymInitialize_DummyFn;
return;
}
m_pSymCleanup = (PFN_SymCleanup) ::GetProcAddress( m_hDbgHelpDll, "SymCleanup" );
if( m_pSymCleanup == NULL )
m_pSymCleanup = SymCleanup_DummyFn;
m_pSymGetOptions = (PFN_SymGetOptions) ::GetProcAddress( m_hDbgHelpDll, "SymGetOptions" );
if( m_pSymGetOptions == NULL )
m_pSymGetOptions = SymGetOptions_DummyFn;
m_pSymSetOptions = (PFN_SymSetOptions) ::GetProcAddress( m_hDbgHelpDll, "SymSetOptions" );
if( m_pSymSetOptions == NULL )
m_pSymSetOptions = SymSetOptions_DummyFn;
m_pSymSetSearchPath = (PFN_SymSetSearchPath) ::GetProcAddress( m_hDbgHelpDll, "SymSetSearchPath" );
if( m_pSymSetSearchPath == NULL )
m_pSymSetSearchPath = SymSetSearchPath_DummyFn;
m_pSymEnumerateModules64 = (PFN_SymEnumerateModules64) ::GetProcAddress( m_hDbgHelpDll, "SymEnumerateModules64" );
if( m_pSymEnumerateModules64 == NULL )
m_pSymEnumerateModules64 = SymEnumerateModules64_DummyFn;
m_pEnumerateLoadedModules64 = (PFN_EnumerateLoadedModules64) ::GetProcAddress( m_hDbgHelpDll, "EnumerateLoadedModules64" );
if( m_pEnumerateLoadedModules64 == NULL )
m_pEnumerateLoadedModules64 = EnumerateLoadedModules64_DummyFn;
m_pSymLoadModule64 = (PFN_SymLoadModule64) ::GetProcAddress( m_hDbgHelpDll, "SymLoadModule64" );
if( m_pSymLoadModule64 == NULL )
m_pSymLoadModule64 = SymLoadModule64_DummyFn;
m_pSymUnloadModule64 = (PFN_SymUnloadModule64) ::GetProcAddress( m_hDbgHelpDll, "SymUnloadModule64" );
if( m_pSymUnloadModule64 == NULL )
m_pSymUnloadModule64 = SymUnloadModule64_DummyFn;
m_pSymFromAddr = (PFN_SymFromAddr) ::GetProcAddress( m_hDbgHelpDll, "SymFromAddr" );
if( m_pSymFromAddr == NULL )
m_pSymFromAddr = SymFromAddr_DummyFn;
m_pSymGetLineFromAddr64 = (PFN_SymGetLineFromAddr64) ::GetProcAddress( m_hDbgHelpDll, "SymGetLineFromAddr64" );
if( m_pSymGetLineFromAddr64 == NULL )
m_pSymGetLineFromAddr64 = SymGetLineFromAddr64_DummyFn;
m_pSymGetModuleInfo64 = (PFN_SymGetModuleInfo64) ::GetProcAddress( m_hDbgHelpDll, "SymGetModuleInfo64" );
if( m_pSymGetModuleInfo64 == NULL )
m_pSymGetModuleInfo64 = SymGetModuleInfo64_DummyFn;
#if defined( USE_STACKWALK64 )
m_pStackWalk64 = (PFN_StackWalk64) ::GetProcAddress( m_hDbgHelpDll, "StackWalk64" );
if( m_pStackWalk64 == NULL )
m_pStackWalk64 = StackWalk64_DummyFn;
#endif
#if defined( USE_CAPTURESTACKBACKTRACE )
m_hNTDllDll = ::LoadLibrary( "ntdll.dll" );
m_pCaptureStackBackTrace = (PFN_CaptureStackBackTrace) ::GetProcAddress( m_hNTDllDll, "RtlCaptureStackBackTrace" );
if( m_pCaptureStackBackTrace == NULL )
m_pCaptureStackBackTrace = CaptureStackBackTrace_DummyFn;
#endif
m_pSymSetOptions( m_pSymGetOptions() |
SYMOPT_DEFERRED_LOADS | //load on demand
SYMOPT_EXACT_SYMBOLS | //don't load the wrong file
SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_NO_PROMPTS | //don't prompt ever
SYMOPT_LOAD_LINES ); //load line info
m_pSymInitialize( m_hProcess, m_szPDBSearchPath, FALSE );
TryLoadingNewSymbols();
}
bool m_bIsInitialized;
bool m_bShouldReloadSymbols;
HANDLE m_hProcess;
HMODULE m_hDbgHelpDll;
char *m_szPDBSearchPath;
CThreadFastMutex m_Mutex; //DbgHelp functions are all single threaded.
PFN_SymInitialize m_pSymInitialize;
PFN_SymCleanup m_pSymCleanup;
PFN_SymGetOptions m_pSymGetOptions;
PFN_SymSetOptions m_pSymSetOptions;
PFN_SymSetSearchPath m_pSymSetSearchPath;
PFN_SymEnumerateModules64 m_pSymEnumerateModules64;
PFN_EnumerateLoadedModules64 m_pEnumerateLoadedModules64;
PFN_SymLoadModule64 m_pSymLoadModule64;
PFN_SymUnloadModule64 m_pSymUnloadModule64;
PFN_SymFromAddr m_pSymFromAddr;
PFN_SymGetLineFromAddr64 m_pSymGetLineFromAddr64;
PFN_SymGetModuleInfo64 m_pSymGetModuleInfo64;
#if defined( USE_STACKWALK64 )
PFN_StackWalk64 m_pStackWalk64;
#endif
#if defined( USE_CAPTURESTACKBACKTRACE )
HMODULE m_hNTDllDll;
PFN_CaptureStackBackTrace m_pCaptureStackBackTrace;
#endif
};
static CHelperFunctionsLoader s_HelperFunctions;
#if defined( USE_STACKWALK64 ) //most reliable method thanks to boatloads of windows helper functions. Also the slowest.
int CrawlStack_StackWalk64( CONTEXT *pExceptionContext, void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
s_HelperFunctions.EnsureReady();
AUTO_LOCK( s_HelperFunctions.m_Mutex );
CONTEXT currentContext;
memcpy( ¤tContext, pExceptionContext, sizeof( CONTEXT ) );
STACKFRAME64 sfFrame = { 0 }; //memset(&sfFrame, 0x0, sizeof(sfFrame));
sfFrame.AddrPC.Mode = sfFrame.AddrFrame.Mode = AddrModeFlat;
#ifdef _M_X64
sfFrame.AddrPC.Offset = currentContext.Rip;
sfFrame.AddrFrame.Offset = currentContext.Rbp; // ????
#else
sfFrame.AddrPC.Offset = currentContext.Eip;
sfFrame.AddrFrame.Offset = currentContext.Ebp;
#endif
HANDLE hThread = GetCurrentThread();
int i;
for( i = 0; i != iSkipCount; ++i ) //skip entries that the requesting function thinks are uninformative
{
if(!s_HelperFunctions.m_pStackWalk64( STACKWALK64_MACHINETYPE, s_HelperFunctions.m_hProcess, hThread, &sfFrame, ¤tContext, NULL, NULL, NULL, NULL ) ||
(sfFrame.AddrFrame.Offset == 0) )
{
return 0;
}
}
for( i = 0; i != iArrayCount; ++i )
{
if(!s_HelperFunctions.m_pStackWalk64( STACKWALK64_MACHINETYPE, s_HelperFunctions.m_hProcess, hThread, &sfFrame, ¤tContext, NULL, NULL, NULL, NULL ) ||
(sfFrame.AddrFrame.Offset == 0) )
{
break;
}
pReturnAddressesOut[i] = (void *)sfFrame.AddrPC.Offset;
}
return i;
}
void GetCallStackReturnAddresses_Exception( void **CallStackReturnAddresses, int *pRetCount, int iSkipCount, _EXCEPTION_POINTERS * pExceptionInfo )
{
int iCount = CrawlStack_StackWalk64( pExceptionInfo->ContextRecord, CallStackReturnAddresses, *pRetCount, iSkipCount + 1 ); //skipping RaiseException()
*pRetCount = iCount;
}
#endif //#if defined( USE_STACKWALK64 )
int GetCallStack( void **pReturnAddressesOut, int iArrayCount, int iSkipCount )
{
s_HelperFunctions.EnsureReady();
++iSkipCount; //skip this function
#if defined( USE_CAPTURESTACKBACKTRACE )
if( s_HelperFunctions.m_pCaptureStackBackTrace != CaptureStackBackTrace_DummyFn )
{
//docs state a total limit of 63 back traces between skipped and stored
int iRetVal = s_HelperFunctions.m_pCaptureStackBackTrace( iSkipCount, MIN( iArrayCount, 63 - iSkipCount ), pReturnAddressesOut, NULL );
return AppendParentStackTrace( pReturnAddressesOut, iArrayCount, iRetVal );
}
#endif
#if defined( USE_STACKWALK64 )
if( s_HelperFunctions.m_pStackWalk64 != StackWalk64_DummyFn )
{
int iInOutArrayCount = iArrayCount; //array count becomes both input and output with exception handler version
__try
{
::RaiseException( 0, EXCEPTION_NONCONTINUABLE, 0, NULL );
}
__except ( GetCallStackReturnAddresses_Exception( pReturnAddressesOut, &iInOutArrayCount, iSkipCount, GetExceptionInformation() ), EXCEPTION_EXECUTE_HANDLER )
{
return AppendParentStackTrace( pReturnAddressesOut, iArrayCount, iInOutArrayCount );
}
}
#endif
return GetCallStack_Fast( pReturnAddressesOut, iArrayCount, iSkipCount );
}
void SetStackTranslationSymbolSearchPath( const char *szSemicolonSeparatedList )
{
s_HelperFunctions.SetStackTranslationSymbolSearchPath( szSemicolonSeparatedList );
}
void StackToolsNotify_LoadedLibrary( const char *szLibName )
{
s_HelperFunctions.m_bShouldReloadSymbols = true;
}
int TranslateStackInfo( const void * const *pCallStack, int iCallStackCount, tchar *szOutput, int iOutBufferSize, const tchar *szEntrySeparator, TranslateStackInfo_StyleFlags_t style )
{
s_HelperFunctions.EnsureReady();
tchar *szStartOutput = szOutput;
if( szEntrySeparator == NULL )
szEntrySeparator = _T("");
int iSeparatorSize = (int)strlen( szEntrySeparator );
for( int i = 0; i < iCallStackCount; ++i )
{
if( !s_HelperFunctions.TranslatePointer( pCallStack[i], szOutput, iOutBufferSize, style ) )
{
return i;
}
int iLength = (int)strlen( szOutput );
szOutput += iLength;
iOutBufferSize -= iLength;
if( iOutBufferSize > iSeparatorSize )
{
memcpy( szOutput, szEntrySeparator, iSeparatorSize * sizeof( tchar ) );
szOutput += iSeparatorSize;
iOutBufferSize -= iSeparatorSize;
}
*szOutput = '\0';
}
szOutput -= iSeparatorSize;
if( szOutput >= szStartOutput )
*szOutput = '\0';
return iCallStackCount;
}
void PreloadStackInformation( void * const *pAddresses, int iAddressCount )
{
//nop on anything but 360
}
bool GetFileAndLineFromAddress( const void *pAddress, tchar *pFileNameOut, int iMaxFileNameLength, uint32 &iLineNumberOut, uint32 *pDisplacementOut )
{
s_HelperFunctions.EnsureReady();
return s_HelperFunctions.GetFileAndLineFromAddress( pAddress, pFileNameOut, iMaxFileNameLength, iLineNumberOut, pDisplacementOut );
}
bool GetSymbolNameFromAddress( const void *pAddress, tchar *pSymbolNameOut, int iMaxSymbolNameLength, uint64 *pDisplacementOut )
{
s_HelperFunctions.EnsureReady();
return s_HelperFunctions.GetSymbolNameFromAddress( pAddress, pSymbolNameOut, iMaxSymbolNameLength, pDisplacementOut );
}
bool GetModuleNameFromAddress( const void *pAddress, tchar *pModuleNameOut, int iMaxModuleNameLength )
{
s_HelperFunctions.EnsureReady();
return s_HelperFunctions.GetModuleNameFromAddress( pAddress, pModuleNameOut, iMaxModuleNameLength );