forked from alandtse/CrashLoggerSSE
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPdbHandler.cpp
More file actions
967 lines (872 loc) · 29.3 KB
/
Copy pathPdbHandler.cpp
File metadata and controls
967 lines (872 loc) · 29.3 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
// SPDX-License-Identifier: CC-BY-SA-4.0
// Code from StackOverflow
#pragma once
#include "PdbHandler.h"
#include "Settings.h"
#include <DbgHelp.h>
#include <atlcomcli.h>
#include <codecvt> // For string conversions
#include <comdef.h>
#include <regex>
#include <unordered_set>
// PDB error constants - these should be defined in cvconst.h but may not be available
// If available through DIA SDK, we can use them directly
#ifndef E_PDB_USAGE
# define E_PDB_USAGE HRESULT(0x806D0001L)
# define E_PDB_OUT_OF_MEMORY HRESULT(0x806D0002L)
# define E_PDB_FILE_SYSTEM HRESULT(0x806D0003L)
# define E_PDB_NOT_FOUND HRESULT(0x806D0004L)
# define E_PDB_INVALID_SIG HRESULT(0x806D0005L)
# define E_PDB_INVALID_AGE HRESULT(0x806D0006L)
# define E_PDB_PRECOMP_REQUIRED HRESULT(0x806D0007L)
# define E_PDB_OUT_OF_TI HRESULT(0x806D0008L)
# define E_PDB_NOT_IMPLEMENTED HRESULT(0x806D0009L)
# define E_PDB_V1_PDB HRESULT(0x806D000AL)
# define E_PDB_FORMAT HRESULT(0x806D000CL)
# define E_PDB_LIMIT HRESULT(0x806D000DL)
# define E_PDB_CORRUPT HRESULT(0x806D000EL)
# define E_PDB_TI16 HRESULT(0x806D000FL)
# define E_PDB_ACCESS_DENIED HRESULT(0x806D0010L)
# define E_PDB_ILLEGAL_TYPE_EDIT HRESULT(0x806D0011L)
# define E_PDB_INVALID_EXECUTABLE HRESULT(0x806D0012L)
# define E_PDB_DBG_NOT_FOUND HRESULT(0x806D0013L)
# define E_PDB_NO_DEBUG_INFO HRESULT(0x806D0014L)
# define E_PDB_INVALID_EXE_TIMESTAMP HRESULT(0x806D0015L)
# define E_PDB_RESERVED HRESULT(0x806D0016L)
# define E_PDB_DEBUG_INFO_NOT_IN_PDB HRESULT(0x806D0017L)
# define E_PDB_SYMSRV_BAD_CACHE_PATH HRESULT(0x806D0018L)
# define E_PDB_SYMSRV_CACHE_FULL HRESULT(0x806D0019L)
# define E_PDB_MAX HRESULT(0x806D001AL)
#endif
namespace Crash
{
namespace PDB
{
std::atomic<bool> symcacheChecked = false;
std::atomic<bool> symcacheValid = false;
//https://stackoverflow.com/questions/6284524/bstr-to-stdstring-stdwstring-and-vice-versa
std::string ConvertWCSToMBS(const wchar_t* pstr, long wslen)
{
int len = ::WideCharToMultiByte(CP_ACP, 0, pstr, wslen, NULL, 0, NULL, NULL);
std::string dblstr(len, '\0');
len = ::WideCharToMultiByte(CP_ACP, 0 /* no flags */,
pstr, wslen /* not necessary NULL-terminated */,
&dblstr[0], len,
NULL, NULL /* no default char */);
return dblstr;
}
std::string ConvertBSTRToMBS(BSTR bstr)
{
int wslen = ::SysStringLen(bstr);
return ConvertWCSToMBS((wchar_t*)bstr, wslen);
}
BSTR ConvertMBSToBSTR(const std::string& str)
{
int wslen = ::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
str.data(), str.length(),
NULL, 0);
BSTR wsdata = ::SysAllocStringLen(NULL, wslen);
::MultiByteToWideChar(CP_ACP, 0 /* no flags */,
str.data(), str.length(),
wsdata, wslen);
return wsdata;
}
std::wstring utf8_to_utf16(const std::string& utf8)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(utf8);
}
std::string utf16_to_utf8(const std::wstring& utf16)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.to_bytes(utf16);
}
[[nodiscard]] static std::string trim(const std::string& str)
{
const auto start = str.find_first_not_of(" \t\n\r");
const auto end = str.find_last_not_of(" \t\n\r");
return (start == std::string::npos) ? "" : str.substr(start, end - start + 1);
}
std::wstring trim(const std::wstring& wstr)
{
auto start = wstr.begin();
while (start != wstr.end() && std::iswspace(*start)) {
++start;
}
auto end = wstr.end();
do {
--end;
} while (end != start && std::iswspace(*end));
return std::wstring(start, end + 1);
}
[[nodiscard]] std::string demangle(const std::wstring& mangled)
{
// Early return for non-mangled names (Microsoft mangled names start with '?')
if (mangled.empty() || mangled[0] != L'?') {
return utf16_to_utf8(mangled);
}
static std::mutex demangle_mutex;
std::lock_guard lock{ demangle_mutex };
// Use a larger buffer for complex names
std::array<wchar_t, 0x2000> buffer{ L'\0' };
const auto length = UnDecorateSymbolNameW(
mangled.c_str(),
buffer.data(),
static_cast<DWORD>(buffer.size()),
UNDNAME_COMPLETE | // Full demangling
UNDNAME_NO_LEADING_UNDERSCORES | // Remove leading underscores
UNDNAME_NO_MS_KEYWORDS | // Remove MS-specific keywords
//UNDNAME_NO_FUNCTION_RETURNS | // Don't show function return types
UNDNAME_NO_ALLOCATION_MODEL | // Remove allocation model
UNDNAME_NO_ALLOCATION_LANGUAGE | // Remove allocation language
UNDNAME_NO_THISTYPE | // Don't show 'this' type
UNDNAME_NO_ACCESS_SPECIFIERS | // Remove public/private/protected
UNDNAME_NO_THROW_SIGNATURES | // Remove throw specifications
UNDNAME_NO_RETURN_UDT_MODEL | // Remove return UDT model
static_cast<DWORD>(0x8000)); // Disable enum/class/struct/union prefix
// Check if demangling succeeded
if (length == 0 || buffer[0] == L'\0') {
return utf16_to_utf8(mangled); // Failed, return original
}
// Ensure proper null termination
if (length < buffer.size()) {
buffer[length] = L'\0';
}
std::wstring demangled{ buffer.data() };
// Trim whitespace
demangled.erase(0, demangled.find_first_not_of(L" \t\r\n"));
demangled.erase(demangled.find_last_not_of(L" \t\r\n") + 1);
// Check for failed demangling indicators
if (demangled.empty() ||
demangled == L"<unknown>" ||
demangled == L"UNKNOWN" ||
demangled.starts_with(L"??")) {
return utf16_to_utf8(mangled);
}
// For crash analysis, show both demangled and original
return utf16_to_utf8(demangled) + " [" + utf16_to_utf8(mangled) + "]";
}
// Overload for std::string (narrow string) - now handles RTTI and MSVC symbols
[[nodiscard]] std::string demangle(const std::string& mangled)
{
if (mangled.empty())
return mangled;
if (mangled[0] == '.') {
// RTTI type descriptor: skip the leading dot
static std::mutex m;
std::lock_guard lock{ m };
std::array<char, 0x1000> buf{ '\0' };
// Use UNDNAME_NAME_ONLY to get just the type name
const auto len = UnDecorateSymbolName(
mangled.data() + 1, // skip leading '.'
buf.data(),
static_cast<std::uint32_t>(buf.size()),
UNDNAME_NAME_ONLY | UNDNAME_NO_ARGUMENTS | static_cast<std::uint32_t>(0x8000));
if (len != 0) {
std::string name{ buf.data(), len };
// Clean up whitespace
name.erase(0, name.find_first_not_of(" \t\r\n"));
name.erase(name.find_last_not_of(" \t\r\n") + 1);
return name;
} else {
// Fallback: strip .?AV...@@ to class name
auto start = mangled.find('A');
auto end = mangled.rfind("@@");
if (start != std::string::npos && end != std::string::npos && end > start + 1) {
return mangled.substr(start + 1, end - start - 1);
}
return mangled;
}
} else if (mangled[0] == '?') {
// MSVC symbol name
static std::mutex demangle_mutex;
std::lock_guard lock{ demangle_mutex };
std::array<char, 0x2000> buffer{ '\0' };
const auto length = UnDecorateSymbolName(
mangled.c_str(),
buffer.data(),
static_cast<DWORD>(buffer.size()),
UNDNAME_COMPLETE |
UNDNAME_NO_LEADING_UNDERSCORES |
UNDNAME_NO_MS_KEYWORDS |
UNDNAME_NO_ALLOCATION_MODEL |
UNDNAME_NO_ALLOCATION_LANGUAGE |
UNDNAME_NO_THISTYPE |
UNDNAME_NO_ACCESS_SPECIFIERS |
UNDNAME_NO_THROW_SIGNATURES |
UNDNAME_NO_RETURN_UDT_MODEL |
static_cast<DWORD>(0x8000));
if (length == 0 || buffer[0] == '\0') {
return mangled; // Failed, return original
}
if (length < buffer.size()) {
buffer[length] = '\0';
}
std::string demangled{ buffer.data() };
demangled.erase(0, demangled.find_first_not_of(" \t\r\n"));
demangled.erase(demangled.find_last_not_of(" \t\r\n") + 1);
if (demangled.empty() ||
demangled == "<unknown>" ||
demangled == "UNKNOWN" ||
demangled.starts_with("??")) {
return mangled;
}
return demangled + " [" + mangled + "]";
} else {
return mangled;
}
}
// Helper for BSTR to std::wstring
[[nodiscard]] std::wstring bstr_to_wstring(BSTR bstr)
{
if (!bstr)
return std::wstring();
return std::wstring(bstr, SysStringLen(bstr));
}
std::string processSymbol(IDiaSymbol* a_symbol, IDiaSession* a_session, const DWORD& a_rva, std::string_view& a_name, uintptr_t& a_offset, std::string& a_result)
{
BSTR name;
a_symbol->get_name(&name);
// Demangle the symbol name
std::string demangledName = demangle(bstr_to_wstring(name));
DWORD rva;
if (a_rva == 0)
a_symbol->get_relativeVirtualAddress(&rva); // find rva if not provided
else
rva = a_rva;
ULONGLONG length = 0;
if (a_symbol->get_length(&length) == S_OK) {
IDiaEnumLineNumbers* lineNums[100];
if (a_session->findLinesByRVA(rva, length, lineNums) == S_OK) {
auto& lineNumsPtr = lineNums[0];
CComPtr<IDiaLineNumber> line;
IDiaLineNumber* lineNum;
ULONG fetched = 0;
bool found_source = false;
bool found_line = false;
for (uint8_t i = 0; i < 5; ++i) {
if (lineNumsPtr->Next(i, &lineNum, &fetched) == S_OK && fetched == 1) {
found_source = false;
found_line = false;
DWORD sline;
IDiaSourceFile* srcFile;
BSTR fileName = nullptr;
std::string convertedFileName;
if (lineNum->get_sourceFile(&srcFile) == S_OK) {
BSTR fileName;
srcFile->get_fileName(&fileName);
convertedFileName = ConvertBSTRToMBS(fileName);
found_source = true;
}
if (lineNum->get_lineNumber(&sline) == S_OK)
found_line = true;
if (found_source && found_line)
a_result += fmt::format(" {}:{} {}", convertedFileName, +sline ? (uint64_t)sline : 0, demangledName);
else if (found_source)
a_result += fmt::format(" {} {}", convertedFileName, demangledName);
else if (found_line)
a_result += fmt::format(" unk_:{} {}", +sline ? (uint64_t)sline : 0, demangledName);
}
}
if (!found_source && !found_line) {
auto sRva = fmt::format("{:X}", rva);
bool is_annotated = demangledName.find('[') != std::string::npos;
if (!is_annotated) {
if (demangledName.ends_with(sRva))
sRva = "";
else
sRva = "_" + sRva;
} else {
sRva.clear();
}
a_result += fmt::format(" {}{}", demangledName, sRva);
}
}
}
if (a_result.empty())
logger::info("No symbol found for {}+{:07X}"sv, a_name, a_offset);
else
logger::info("Symbol returning: {}", a_result);
return a_result;
}
std::string print_hr_failure(HRESULT hr)
{
auto errMsg = "";
switch (hr) {
// PDB-specific error codes
case E_PDB_USAGE:
errMsg = "Invalid PDB usage";
break;
case E_PDB_OUT_OF_MEMORY:
errMsg = "Out of memory during PDB operation";
break;
case E_PDB_FILE_SYSTEM:
errMsg = "File system error accessing PDB";
break;
case E_PDB_NOT_FOUND:
errMsg = "PDB file not found";
break;
case E_PDB_INVALID_SIG:
errMsg = "PDB signature mismatch";
break;
case E_PDB_INVALID_AGE:
errMsg = "PDB age mismatch";
break;
case E_PDB_PRECOMP_REQUIRED:
errMsg = "Precompiled header required";
break;
case E_PDB_OUT_OF_TI:
errMsg = "Out of type indices";
break;
case E_PDB_NOT_IMPLEMENTED:
errMsg = "PDB feature not implemented";
break;
case E_PDB_V1_PDB:
errMsg = "Unsupported PDB v1.0 format";
break;
case E_PDB_FORMAT:
errMsg = "Invalid PDB format";
break;
case E_PDB_LIMIT:
errMsg = "PDB internal limit exceeded";
break;
case E_PDB_CORRUPT:
errMsg = "PDB file is corrupted";
break;
case E_PDB_TI16:
errMsg = "PDB 16-bit type index not supported";
break;
case E_PDB_ACCESS_DENIED:
errMsg = "Access denied to PDB file";
break;
case E_PDB_ILLEGAL_TYPE_EDIT:
errMsg = "Illegal type edit in PDB";
break;
case E_PDB_INVALID_EXECUTABLE:
errMsg = "Invalid executable format for PDB";
break;
case E_PDB_DBG_NOT_FOUND:
errMsg = "DBG file not found";
break;
case E_PDB_NO_DEBUG_INFO:
errMsg = "No debug information available";
break;
case E_PDB_INVALID_EXE_TIMESTAMP:
errMsg = "Executable timestamp mismatch";
break;
case E_PDB_RESERVED:
errMsg = "Reserved PDB error";
break;
case E_PDB_DEBUG_INFO_NOT_IN_PDB:
errMsg = "Debug info not in PDB format";
break;
case E_PDB_SYMSRV_BAD_CACHE_PATH:
errMsg = "Bad symbol server cache path";
break;
case E_PDB_SYMSRV_CACHE_FULL:
errMsg = "Symbol server cache full";
break;
case E_PDB_MAX:
errMsg = "Maximum PDB error reached";
break;
// Common HRESULT codes
case E_INVALIDARG:
errMsg = "Invalid argument passed to PDB function";
break;
case E_OUTOFMEMORY:
errMsg = "Out of memory";
break;
case E_FAIL:
errMsg = "Unspecified PDB failure";
break;
case E_NOTIMPL:
errMsg = "PDB function not implemented";
break;
case E_NOINTERFACE:
errMsg = "PDB interface not supported";
break;
case E_ACCESSDENIED:
errMsg = "Access denied to PDB resources";
break;
default:
_com_error err(hr);
errMsg = CT2A(err.ErrorMessage());
break;
}
return errMsg;
}
namespace
{
[[nodiscard]] std::string base_type_to_string(DWORD baseType, ULONGLONG length)
{
switch (baseType) {
case btVoid:
return "void";
case btBool:
return "bool";
case btChar:
return "char";
case btWChar:
return "wchar_t";
case btInt:
switch (length) {
case 1:
return "int8_t";
case 2:
return "int16_t";
case 4:
return "int32_t";
case 8:
return "int64_t";
default:
return "int";
}
case btUInt:
switch (length) {
case 1:
return "uint8_t";
case 2:
return "uint16_t";
case 4:
return "uint32_t";
case 8:
return "uint64_t";
default:
return "unsigned int";
}
case btFloat:
return length == 8 ? "double" : "float";
case btLong:
return "long";
case btULong:
return "unsigned long";
default:
return "<unknown>";
}
}
[[nodiscard]] std::string get_symbol_name(IDiaSymbol* symbol)
{
BSTR name{};
if (symbol->get_name(&name) == S_OK && name) {
const auto converted = ConvertBSTRToMBS(name);
::SysFreeString(name); // Free BSTR to prevent memory leak
return demangle(converted);
}
return "";
}
[[nodiscard]] std::string get_type_name(IDiaSymbol* type)
{
if (!type) {
return "<unknown>";
}
DWORD symTag = 0;
if (FAILED(type->get_symTag(&symTag))) {
return "<unknown>";
}
switch (symTag) {
case SymTagPointerType:
{
CComPtr<IDiaSymbol> pointee;
type->get_type(&pointee);
auto name = get_type_name(pointee);
BOOL isConst = FALSE;
type->get_constType(&isConst);
if (isConst && !name.starts_with("const ")) {
name = "const " + name;
}
return name + "*";
}
case SymTagBaseType:
{
DWORD baseType = 0;
ULONGLONG length = 0;
type->get_baseType(&baseType);
type->get_length(&length);
return base_type_to_string(baseType, length);
}
case SymTagEnum:
case SymTagUDT:
return get_symbol_name(type);
case SymTagArrayType:
{
CComPtr<IDiaSymbol> element;
type->get_type(&element);
DWORD count = 0;
type->get_count(&count);
return fmt::format("{}[{}]", get_type_name(element), count);
}
case SymTagFunctionType:
return "function";
default:
return get_symbol_name(type);
}
}
}
// Captures the actual PDB path DIA opens. loadDataForExe also searches the exe's own
// directory and symbol paths in addition to the searchPath we pass, so the file it loads
// is frequently NOT the one in that searchPath (e.g. it prefers a SkyrimVR.pdb sitting next
// to the exe over the Data/SKSE/Plugins copy). Logging only the searchPath is misleading;
// NotifyOpenPDB reports the real file. Restrict* methods return S_OK to keep the default
// (NULL-callback) access behavior. Stack-allocated for a synchronous loadDataForExe call,
// so AddRef/Release are no-ops.
class DiaLoadLogger : public IDiaLoadCallback2
{
public:
std::wstring openedPdb;
ULONG STDMETHODCALLTYPE AddRef() override { return 2; }
ULONG STDMETHODCALLTYPE Release() override { return 1; }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override
{
if (!ppv) {
return E_INVALIDARG;
}
if (riid == __uuidof(IUnknown) || riid == __uuidof(IDiaLoadCallback) || riid == __uuidof(IDiaLoadCallback2)) {
*ppv = static_cast<IDiaLoadCallback2*>(this);
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
HRESULT STDMETHODCALLTYPE NotifyDebugDir(BOOL, DWORD, BYTE*) override { return S_OK; }
HRESULT STDMETHODCALLTYPE NotifyOpenDBG(LPCOLESTR, HRESULT) override { return S_OK; }
HRESULT STDMETHODCALLTYPE NotifyOpenPDB(LPCOLESTR a_pdbPath, HRESULT a_resultCode) override
{
if (SUCCEEDED(a_resultCode) && a_pdbPath) {
openedPdb = a_pdbPath;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictRegistryAccess() override { return S_OK; }
HRESULT STDMETHODCALLTYPE RestrictSymbolServerAccess() override { return S_OK; }
HRESULT STDMETHODCALLTYPE RestrictOriginalPathAccess() override { return S_OK; }
HRESULT STDMETHODCALLTYPE RestrictReferencePathAccess() override { return S_OK; }
HRESULT STDMETHODCALLTYPE RestrictDBGAccess() override { return S_OK; }
HRESULT STDMETHODCALLTYPE RestrictSystemRootAccess() override { return S_OK; }
};
// Helper struct to encapsulate PDB session setup
struct PdbSession
{
CComPtr<IDiaDataSource> pSource;
CComPtr<IDiaSession> pSession;
CComPtr<IDiaSymbol> globalSymbol;
bool com_initialized_here = false;
~PdbSession()
{
if (com_initialized_here) {
CoUninitialize();
}
}
// Open a PDB session for the given module
bool open(std::string_view a_name, uintptr_t a_offset)
{
std::filesystem::path dllPath{ a_name };
std::string dll_path{ a_name };
if (!dllPath.has_parent_path()) {
dll_path = Crash::PDB::sPluginPath.data() + dllPath.filename().string();
}
HRESULT hr = S_OK;
// Initialize COM
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (FAILED(hr) && hr != RPC_E_CHANGED_MODE) {
auto error = print_hr_failure(hr);
logger::info("Failed to initialize COM library for dll {}+{:07X}\t{}", a_name, a_offset, error);
return false;
}
com_initialized_here = SUCCEEDED(hr);
// Load DIA data source
auto* msdia_dll = L"Data/SKSE/Plugins/msdia140.dll";
hr = NoRegCoCreate(msdia_dll, CLSID_DiaSource, __uuidof(IDiaDataSource), (void**)&pSource);
if (FAILED(hr)) {
auto error = print_hr_failure(hr);
logger::info("Failed to manually load msdia140.dll for dll {}+{:07X}\t{}", a_name, a_offset, error);
// Try registered copy
if (FAILED(hr = CoCreateInstance(CLSID_DiaSource, NULL, CLSCTX_INPROC_SERVER, __uuidof(IDiaDataSource), (void**)&pSource))) {
auto error = print_hr_failure(hr);
logger::info("Failed to load registered msdia140.dll for dll {}+{:07X}\t{}", a_name, a_offset, error);
return false;
}
}
// Prepare file paths
wchar_t wszFilename[_MAX_PATH];
wchar_t wszPath[_MAX_PATH];
std::wstring dll_path_w = utf8_to_utf16(dll_path);
wcsncpy(wszFilename, dll_path_w.c_str(), sizeof(wszFilename) / sizeof(wchar_t));
wszFilename[_MAX_PATH - 1] = L'\0';
// Get symcache config
const auto& debugConfig = Settings::GetSingleton()->GetDebug();
std::string symcache = debugConfig.symcache;
// Use namespace-level atomics for shared symcache validation state
if (!symcacheChecked.load(std::memory_order_acquire)) {
if (!symcache.empty() && std::filesystem::exists(symcache) && std::filesystem::is_directory(symcache)) {
logger::info("Symcache found at {}", symcache);
symcacheValid.store(true, std::memory_order_release);
} else {
logger::info("Symcache not found at {}", symcache.empty() ? "not defined" : symcache);
}
symcacheChecked.store(true, std::memory_order_release);
}
// Build search paths
std::vector<std::string> searchPaths = { Crash::PDB::sPluginPath.data() };
if (symcacheValid.load(std::memory_order_acquire)) {
searchPaths.push_back(fmt::format(fmt::runtime("cache*{}"s), symcache.c_str()));
}
// Try to load PDB
DiaLoadLogger loadLogger;
bool foundPDB = false;
for (const auto& path : searchPaths) {
std::wstring path_w = utf8_to_utf16(path);
wcsncpy(wszPath, path_w.c_str(), sizeof(wszPath) / sizeof(wchar_t));
wszPath[_MAX_PATH - 1] = L'\0';
// `path` is only a searchPath hint; DIA also searches the exe's directory and
// symbol paths, so the file it actually opens is reported via loadLogger below.
logger::info("Attempting to load pdb for {}+{:07X} (searchPath {})", a_name, a_offset, path);
hr = pSource->loadDataForExe(wszFilename, wszPath, &loadLogger);
if (FAILED(hr)) {
auto error = print_hr_failure(hr);
logger::info("Failed to open pdb for dll {}+{:07X}\t{}", a_name, a_offset, error);
continue;
}
foundPDB = true;
break;
}
if (!foundPDB) {
return false;
}
if (!loadLogger.openedPdb.empty()) {
logger::info("Successfully opened pdb for dll {}+{:07X} from {}", a_name, a_offset,
std::filesystem::path(loadLogger.openedPdb).string());
} else {
logger::info("Successfully opened pdb for dll {}+{:07X}", a_name, a_offset);
}
// Open session
if (FAILED(hr = pSource->openSession(&pSession))) {
auto error = print_hr_failure(hr);
logger::info("Failed to openSession for pdb for dll {}+{:07X}\t{}", a_name, a_offset, error);
return false;
}
// Get global scope
if (FAILED(hr = pSession->get_globalScope(&globalSymbol))) {
auto error = print_hr_failure(hr);
logger::info("Failed to get_globalScope for pdb for dll {}+{:07X}\t{}", a_name, a_offset, error);
return false;
}
return true;
}
};
//https://stackoverflow.com/questions/68412597/determining-source-code-filename-and-line-for-function-using-visual-studio-pdb
std::string pdb_details(std::string_view a_name, uintptr_t a_offset)
{
static std::mutex sync;
std::lock_guard l{ sync };
std::string result;
// Use shared PDB session helper
PdbSession session;
if (!session.open(a_name, a_offset)) {
return result;
}
const auto rva = static_cast<DWORD>(a_offset);
HRESULT hr = S_OK;
CComPtr<IDiaEnumTables> enumTables;
CComPtr<IDiaEnumSymbolsByAddr> enumSymbolsByAddr;
if (FAILED(hr = session.pSession->getEnumTables(&enumTables))) {
auto error = print_hr_failure(hr);
logger::info("Failed to getEnumTables for pdb for dll {}+{:07X}\t{}", a_name, a_offset, error);
return result;
}
if (FAILED(hr = session.pSession->getSymbolsByAddr(&enumSymbolsByAddr))) {
auto error = print_hr_failure(hr);
logger::info("Failed to getSymbolsByAddr for pdb for dll {}+{:07X}\t{}", a_name, a_offset, error);
return result;
}
CComPtr<IDiaSymbol> publicSymbol;
if (session.pSession->findSymbolByRVA(rva, SymTagEnum::SymTagPublicSymbol, &publicSymbol) == S_OK) {
auto publicResult = processSymbol(publicSymbol, session.pSession, rva, a_name, a_offset, result);
// Log the public result (already demangled in processSymbol)
logger::info("Public symbol found for {}+{:07X}: {}", a_name, a_offset, publicResult);
DWORD privateRva;
CComPtr<IDiaSymbol> privateSymbol;
if (publicSymbol->get_targetRelativeVirtualAddress(&privateRva) == S_OK &&
session.pSession->findSymbolByRVA(privateRva, SymTagEnum::SymTagFunction, &privateSymbol) == S_OK) {
auto privateResult = processSymbol(privateSymbol, session.pSession, privateRva, a_name, a_offset, result);
// Log the private result (already demangled in processSymbol)
logger::info("Private symbol found for {}+{:07X}: {}", a_name, a_offset, privateResult);
// Combine results
if (!privateResult.empty() && !publicResult.empty()) {
result = fmt::format("{}\t{}", privateResult, publicResult);
} else if (!privateResult.empty()) {
result = privateResult;
} else {
result = publicResult;
}
} else {
result = publicResult;
}
} else {
logger::info("No public symbol found for {}+{:07X}", a_name, a_offset);
}
return result;
}
std::string pdb_function_parameters(std::string_view a_name, uintptr_t a_offset)
{
static std::mutex sync;
std::lock_guard l{ sync };
std::string result;
// Use shared PDB session helper
PdbSession session;
if (!session.open(a_name, a_offset)) {
return result;
}
const auto rva = static_cast<DWORD>(a_offset);
HRESULT hr = S_OK;
CComPtr<IDiaSymbol> funcSymbol;
if (FAILED(hr = session.pSession->findSymbolByRVA(rva, SymTagFunction, &funcSymbol)) || !funcSymbol) {
return result;
}
CComPtr<IDiaEnumSymbols> enumSymbols;
if (FAILED(hr = funcSymbol->findChildren(SymTagData, NULL, nsNone, &enumSymbols)) || !enumSymbols) {
return result;
}
std::vector<std::string> params;
params.reserve(8);
ULONG fetched = 0;
CComPtr<IDiaSymbol> child;
while (SUCCEEDED(enumSymbols->Next(1, &child, &fetched)) && fetched == 1) {
DWORD dataKind = 0;
if (FAILED(child->get_dataKind(&dataKind))) {
child.Release();
continue;
}
if (dataKind != DataIsParam) {
child.Release();
continue;
}
BSTR name{};
std::string paramName;
if (child->get_name(&name) == S_OK && name) {
paramName = ConvertBSTRToMBS(name);
::SysFreeString(name); // Free BSTR to prevent memory leak
}
CComPtr<IDiaSymbol> type;
child->get_type(&type);
const auto typeName = get_type_name(type);
if (!paramName.empty()) {
params.push_back(fmt::format("{}: {}", paramName, typeName));
} else {
params.push_back(typeName);
}
if (params.size() >= 8) {
params.push_back("...");
break;
}
child.Release();
}
if (!params.empty()) {
std::string joined;
for (std::size_t i = 0; i < params.size(); ++i) {
if (i > 0) {
joined += ", ";
}
joined += params[i];
}
result = joined;
}
return result;
}
// dump all symbols in Plugin directory or fakepdb for exe
// this was the early POC test and written first in this module
void dump_symbols(bool exe)
{
// Initialize COM - handle the case where it's already initialized
HRESULT com_hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
bool com_initialized_here = SUCCEEDED(com_hr);
// RPC_E_CHANGED_MODE means COM is already initialized with different threading mode
if (FAILED(com_hr) && com_hr != RPC_E_CHANGED_MODE) {
logger::error("Failed to initialize COM for symbol dumping: {}", print_hr_failure(com_hr));
return;
}
int retflag;
if (exe) {
const auto string_path = "./SkyrimVR.exe";
std::filesystem::path file_path{ string_path };
dumpFileSymbols(file_path, retflag);
} else {
for (const auto& elem : std::filesystem::directory_iterator(Crash::PDB::sPluginPath)) {
if (const auto filename =
elem.path().has_filename() ?
std::make_optional(elem.path().filename().string()) :
std::nullopt;
filename.value().ends_with("dll")) {
dumpFileSymbols(elem.path(), retflag);
if (retflag == 3)
continue;
}
}
}
}
void dumpFileSymbols(const std::filesystem::path& path, int& retflag)
{
retflag = 1;
const auto filename = std::make_optional(path.filename().string());
logger::info("Found dll {}", *filename);
auto dll_path = path.string();
auto search_path = Crash::PDB::sPluginPath.data();
CComPtr<IDiaDataSource> source;
auto hr = CoCreateInstance(CLSID_DiaSource,
NULL,
CLSCTX_INPROC_SERVER,
__uuidof(IDiaDataSource),
(void**)&source);
if (FAILED(hr)) {
retflag = 3;
return;
};
{
wchar_t wszFilename[_MAX_PATH];
wchar_t wszPath[_MAX_PATH];
mbstowcs(wszFilename, dll_path.c_str(), sizeof(wszFilename) / sizeof(wszFilename[0]));
mbstowcs(wszPath, sPluginPath.data(), sizeof(wszPath) / sizeof(wszPath[0]));
hr = source->loadDataForExe(wszFilename, wszPath, NULL);
if (FAILED(hr)) {
retflag = 3;
return;
};
logger::info("Found pdb for dll {}", *filename);
}
CComPtr<IDiaSession> pSession;
if (FAILED(source->openSession(&pSession))) {
retflag = 3;
return;
};
IDiaEnumSymbolsByAddr* pEnumSymbolsByAddr;
IDiaSymbol* pSymbol;
ULONG celt = 0;
if (FAILED(pSession->getSymbolsByAddr(&pEnumSymbolsByAddr))) {
{
retflag = 3;
return;
};
}
if (FAILED(pEnumSymbolsByAddr->symbolByAddr(1, 0, &pSymbol))) {
pEnumSymbolsByAddr->Release();
{
retflag = 3;
return;
};
}
do {
const auto rva = 0;
std::string_view a_name = *filename;
uintptr_t a_offset = 0;
std::string result = "";
result = processSymbol(pSymbol, pSession, rva, a_name, a_offset, result);
logger::info("{}", result);
pSymbol->Release();
if (FAILED(pEnumSymbolsByAddr->Next(1, &pSymbol, &celt))) {
pEnumSymbolsByAddr->Release();
break;
}
} while (celt == 1);
pEnumSymbolsByAddr->Release();
}
}
}