-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathmsdia.cpp
More file actions
1731 lines (1598 loc) · 51.5 KB
/
msdia.cpp
File metadata and controls
1731 lines (1598 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is included from 4 places:
// - efd/pdb.cpp efd: to dump pdb contents
// - base/pdb2til.cpp tilib: to convert pdb to til
// - plugins/pdb/pdb.cpp ida: read pdb info and populate idb
// - dbg/win32_server/tilfuncs.cpp win32_server: read pdb info and send it to ida
//
// The following symbols may be defined:
// PDB_PLUGIN pdb
// PDB_WIN32_SERVER win32_server
#include <diskio.hpp>
#include "msdia.hpp"
#include "../../ldr/pe/pe.h"
#include "pdblocal.cpp"
#include "dia2_internal.h"
#include "Program.h"
//因为从Visual Studio 2010开始DIA SDK的各个接口的虚表结构就改变了(虽然接口名字并没改变还是叫IDiaSession、IDiaSymbol等),
//因此一套源码不能编译为同时支持两种不同虚表结构的接口的组件
//使用低于Visual Studio 2010提供的DIA SDK的版本时需要注释掉下面这个__IS_MSDIA100_OR_GREATER__宏,不然会报错提示
#define __IS_MSDIA100_OR_GREATER__
#ifdef __IS_MSDIA100_OR_GREATER__
__if_not_exists(IDiaSession::findChildrenEx)
{
static int temp_result_for__IS_MSDIA100_OR_GREATER__ = _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%ls", L"PLEASE undefine __IS_MSDIA100_OR_GREATER__");
}
#endif
//lint -esym(843, g_diadlls, g_pdb_errors, PathIsUNC) could be declared as const
int pdb_session_t::session_count = 0;
bool pdb_session_t::co_initialized = false;
#ifndef _INC_SHLWAPI
typedef BOOL (__stdcall *PathIsUNC_t)(LPCTSTR pszPath);
static PathIsUNC_t PathIsUNC = nullptr;
#endif
static bool check_for_odd_paths(const char *fname);
//---------------------------------------------------------------------------
class msdia_reader_t
{
public:
virtual ~msdia_reader_t() {}
virtual bool read(uint64 offset, void *buf, uint32 count, uint32 *nread) = 0;
virtual bool setup(void) { return true; }
};
//---------------------------------------------------------------------------
class local_exe_msdia_reader_t : public msdia_reader_t
{
LPCWSTR FileName;
HANDLE hFile;
public:
local_exe_msdia_reader_t(LPCWSTR _FileName)
{
FileName = _FileName;
hFile = INVALID_HANDLE_VALUE;
}
~local_exe_msdia_reader_t(void)
{
if ( hFile != INVALID_HANDLE_VALUE )
CloseHandle(hFile);
}
virtual bool setup(void) override
{
hFile = CreateFileW(
FileName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr,
OPEN_EXISTING,
0,
nullptr);
return hFile != INVALID_HANDLE_VALUE;
}
virtual bool read(uint64 offset, void *buf, uint32 count, uint32 *nread) override
{
if ( hFile == INVALID_HANDLE_VALUE )
return false;
LARGE_INTEGER pos;
pos.QuadPart = (LONGLONG) offset;
if ( SetFilePointerEx(hFile, pos, nullptr, FILE_BEGIN) == 0 )
return false;
if ( ReadFile(hFile, buf, count, (DWORD *) nread, nullptr) == 0 )
return false;
return true;
}
};
#ifdef PDB_PLUGIN
//---------------------------------------------------------------------------
class local_mem_msdia_reader_t : public msdia_reader_t
{
public:
virtual bool read(uint64 offset, void *buf, uint32 count, uint32 *nread) override
{
if ( get_bytes(buf, count, offset) != count )
return false;
*nread = count;
return true;
}
};
#elif defined(PDB_WIN32_SERVER)
//---------------------------------------------------------------------------
class win32_msdia_reader_t : public msdia_reader_t
{
pdb_remote_session_t *pdb_rsess;
pdb_rr_kind_t kind;
public:
win32_msdia_reader_t(void *_pdb_rsess, pdb_rr_kind_t _kind)
{
pdb_rsess = (pdb_remote_session_t *) _pdb_rsess;
kind = _kind;
}
virtual bool read(uint64 offset, void *buf, uint32 count, uint32 *nread) override
{
return pdb_rsess->client_read_request.request_read(kind, offset, count, buf, nread);
}
};
#endif
//----------------------------------------------------------------------
// Common code for PDB handling
//----------------------------------------------------------------------
class CCallback : public IDiaLoadCallback2,
public IDiaReadExeAtRVACallback,
public IDiaReadExeAtOffsetCallback
{
unsigned int m_nRefCount;
ea_t m_load_address;
msdia_reader_t *msdia_reader;
pdb_session_t *pdb_session;
DWORDLONG last_cv_off;
ea_t last_cv_rva;
public:
CCallback(pdb_session_t *_pdb_session,
msdia_reader_t *_msdia_reader,
ea_t _load_address)
: msdia_reader(_msdia_reader),
m_load_address(_load_address),
// Note: we initialize the reference count to 1 since the only
// instance of this object is created in the stack, and
// the destructor will take care of the cleanup.
m_nRefCount(1),
pdb_session(_pdb_session),
last_cv_off(0),
last_cv_rva(BADADDR)
{
}
// IUnknown
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&m_nRefCount);
}
ULONG STDMETHODCALLTYPE Release()
{
// Note: we don't check the reference count and delete the object
// (see comment for the m_nRefCount field).
return InterlockedDecrement(&m_nRefCount);
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID rid, void **ppUnk)
{
if ( ppUnk == nullptr )
return E_INVALIDARG;
*ppUnk = nullptr;
if ( rid == __uuidof(IDiaLoadCallback2) || rid == __uuidof(IDiaLoadCallback) )
{
*ppUnk = (IDiaLoadCallback2 *)this;
}
else if ( rid == __uuidof(IDiaReadExeAtRVACallback) )
{
// we may use only one of IDiaReadExeAtRVACallback and IDiaReadExeAtOffsetCallback
// claiming that both are supported will lead to crashes in MSDIA
if ( m_load_address != BADADDR )
*ppUnk = (IDiaReadExeAtRVACallback *)this;
}
else if ( rid == __uuidof(IDiaReadExeAtOffsetCallback) )
{
// see the comment above about IDiaReadExeAtRVACallback
if ( m_load_address == BADADDR )
*ppUnk = (IDiaReadExeAtOffsetCallback *)this;
}
else if ( rid == __uuidof(IUnknown) )
{
*ppUnk = (IUnknown *)(IDiaLoadCallback *)this;
}
if ( *ppUnk == nullptr )
return E_NOINTERFACE;
AddRef();
return S_OK;
}
HRESULT STDMETHODCALLTYPE NotifyDebugDir(
BOOL fExecutable,
DWORD cbData,
BYTE data[])
{
// msdia90.dll can crash on bogus CV data
// so we remember the offset here and check it in ReadFileAt
if ( fExecutable && cbData >= sizeof(debug_entry_t) )
{
debug_entry_t &de = *(debug_entry_t *)data;
if ( de.type == DBG_CV )
{
last_cv_off = de.seek;
last_cv_rva = de.rva;
}
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE NotifyOpenDBG(
LPCOLESTR dbgPath,
HRESULT resultCode)
{
if ( resultCode == S_OK )
deb(IDA_DEBUG_DEBUGGER, "MSDIA: dbg file \"%S\" matched\n", dbgPath);
else
deb(IDA_DEBUG_DEBUGGER, "MSDIA: \"%S\": %s\n", dbgPath, pdberr(resultCode));
return S_OK;
}
HRESULT STDMETHODCALLTYPE NotifyOpenPDB(
LPCOLESTR pdbPath,
HRESULT resultCode)
{
if ( resultCode == S_OK )
deb(IDA_DEBUG_DEBUGGER, "MSDIA: pdb file \"%S\" matched\n", pdbPath);
else
deb(IDA_DEBUG_DEBUGGER, "MSDIA: \"%S\": %s\n", pdbPath, pdberr(resultCode));
#ifdef _DEBUG
qstring spath;
utf16_utf8(&spath, pdbPath);
pdb_session->_pdb_path = spath;
#endif
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictRegistryAccess()
{
// return hr != S_OK to prevent querying the registry for symbol search paths
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictSymbolServerAccess()
{
// return hr != S_OK to prevent accessing a symbol server
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictOriginalPathAccess()
{
// return hr != S_OK to prevent querying the registry for symbol search paths
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictReferencePathAccess()
{
// return hr != S_OK to prevent accessing a symbol server
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictDBGAccess()
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictSystemRootAccess()
{
return S_OK;
}
bool check_codeview_data(BYTE pbData[], DWORD cbData, qwstring& wspath)
{
bool ok = true;
if ( cbData > 4 )
{
// check that the data has a valid NB or RSDS signature and PDB path doesn't look suspicious
ok = false;
if ( pbData[0] == 'N' && pbData[1] == 'B' && cbData >= sizeof(cv_info_pdb20_t) )
{
char *pdbname = (char*)pbData + sizeof(cv_info_pdb20_t);
pbData[cbData-1] = '\0';
ok = check_for_odd_paths(pdbname);
}
else if ( memcmp(pbData, "RSDS", 4) == 0 && cbData >= sizeof(rsds_t) )
{
char *pdbname = (char*)pbData + sizeof(rsds_t);
pbData[cbData-1] = '\0';
ok = check_for_odd_paths(pdbname);
if (ok)
{
void try_download_pdb_from_sym_server_by_idm_when_not_exist(clsid_t & guid, uint32 age, const char* pdb_path, qstring & spath);
rsds_t* pdb_info = (rsds_t*)pbData;
qstring spath = utf16_utf8(wspath.c_str());
try_download_pdb_from_sym_server_by_idm_when_not_exist(pdb_info->guid, pdb_info->age, pdbname, spath);
}
}
}
return ok;
}
// IDiaReadExeAtRVACallback
HRESULT STDMETHODCALLTYPE ReadExecutableAtRVA(
DWORD relativeVirtualAddress,
DWORD cbData,
DWORD *pcbData,
BYTE data[])
{
ea_t ea = m_load_address + relativeVirtualAddress;
if ( !msdia_reader->read(ea, data, cbData, (uint32 *) pcbData) )
return E_FAIL;
// are we reading the CV debug directory entry?
if ( relativeVirtualAddress == last_cv_rva )
return check_codeview_data(data, cbData, pdb_session->wspath) ? S_OK : E_FAIL;
return S_OK;
}
// IDiaReadExeAtOffsetCallback
HRESULT STDMETHODCALLTYPE ReadExecutableAt(
DWORDLONG fileOffset,
DWORD cbData,
DWORD *pcbData,
BYTE data[])
{
if ( !msdia_reader->read(fileOffset, data, cbData, (uint32 *) pcbData) )
return E_FAIL;
// are we reading the CV debug directory entry?
if ( fileOffset != 0 && last_cv_off == fileOffset )
return check_codeview_data(data, cbData, pdb_session->wspath) ? S_OK : E_FAIL;
return S_OK;
}
};
//---------------------------------------------------------------------------
static const char *const g_pdb_errors[] =
{
"Operation successful (E_PDB_OK)",
"(E_PDB_USAGE)",
"Out of memory (E_PDB_OUT_OF_MEMORY)",
"(E_PDB_FILE_SYSTEM)",
"Failed to open the file, or the file has an invalid format (E_PDB_NOT_FOUND)",
"Signature does not match (E_PDB_INVALID_SIG)",
"Age does not match (E_PDB_INVALID_AGE)",
"(E_PDB_PRECOMP_REQUIRED)",
"(E_PDB_OUT_OF_TI)",
"(E_PDB_NOT_IMPLEMENTED)",
"(E_PDB_V1_PDB)",
"Attempted to access a file with an obsolete format (E_PDB_FORMAT)",
"(E_PDB_LIMIT)",
"(E_PDB_CORRUPT)",
"(E_PDB_TI16)",
"(E_PDB_ACCESS_DENIED)",
"(E_PDB_ILLEGAL_TYPE_EDIT)",
"(E_PDB_INVALID_EXECUTABLE)",
"(E_PDB_DBG_NOT_FOUND)",
"(E_PDB_NO_DEBUG_INFO)",
"(E_PDB_INVALID_EXE_TIMESTAMP)",
"(E_PDB_RESERVED)",
"(E_PDB_DEBUG_INFO_NOT_IN_PDB)",
"(E_PDB_SYMSRV_BAD_CACHE_PATH)",
"(E_PDB_SYMSRV_CACHE_FULL)",
};
//---------------------------------------------------------------------------
inline void pdberr_suggest_vs_runtime(HRESULT hr)
{
if ( hr == E_NOINTERFACE )
{
msg("<< It appears that MS DIA SDK is not installed.\n");
#ifndef __IS_MSDIA100_OR_GREATER__
#ifdef __X86__
msg("Please try installing \"Microsoft Visual C++ 2008 Redistributable Package / x86\" >>\n");
#else
msg("Please try installing \"Microsoft Visual C++ 2008 Redistributable Package / x64\" >>\n");
#endif
#endif
}
}
//---------------------------------------------------------------------------
const char *pdberr(int code)
{
switch ( code )
{ // tab in first pos is flag for replace warning to msg
case E_INVALIDARG: return "Invalid parameter.";
case E_UNEXPECTED: return "Data source has already been prepared.";
default:
if ( code >= E_PDB_OK && (code - E_PDB_OK) < qnumber(g_pdb_errors) )
return g_pdb_errors[code - E_PDB_OK];
}
return winerr(code);
}
//----------------------------------------------------------------------
#ifdef __IS_MSDIA100_OR_GREATER__
static const GUID* const g_msdiav[] = { &__uuidof(DiaSource) };
static const int g_diaver[] = { 1400 };
static const char* const g_diadlls[] = { "msdia140.dll" };
#else
class DECLSPEC_UUID("4c41678e-887b-4365-a09e-925d28db33c2") DiaSource90;
class DECLSPEC_UUID("1fbd5ec4-b8e4-4d94-9efe-7ccaf9132c98") DiaSource80;
class DECLSPEC_UUID("31495af6-0897-4f1e-8dac-1447f10174a1") DiaSource71;
static const GUID *const g_d90 = &__uuidof(DiaSource90); // msdia90.dll
static const GUID *const g_d80 = &__uuidof(DiaSource80); // msdia80.dll
static const GUID *const g_d71 = &__uuidof(DiaSource71); // msdia71.dll
static const GUID *const g_msdiav[] = { g_d90, g_d80, g_d71 };
static const int g_diaver[] = { 900, 800, 710 };
static const char *const g_diadlls[] = { "msdia90.dll", "msdia80.dll", "msdia71.dll" };
#endif
//----------------------------------------------------------------------
HRESULT __stdcall CoCreateInstanceNoReg(
LPCTSTR szDllName,
IN REFCLSID rclsid,
IUnknown *pUnkOuter,
IN REFIID riid,
OUT LPVOID FAR *ppv,
OUT HMODULE *phMod)
{
// http://lallousx86.wordpress.com/2007/01/29/emulating-cocreateinstance/
HRESULT hr = REGDB_E_CLASSNOTREG;
HMODULE hDll;
do
{
hDll = LoadLibrary(szDllName);
if ( hDll == nullptr )
break;
HRESULT (__stdcall *GetClassObject)(REFCLSID rclsid, REFIID riid, LPVOID FAR *ppv);
*(FARPROC*)&GetClassObject = GetProcAddress(hDll, "DllGetClassObject");
if ( GetClassObject == nullptr )
break;
IClassFactory *pIFactory;
hr = GetClassObject(rclsid, IID_IClassFactory, (LPVOID *)&pIFactory);
if ( FAILED(hr) )
break;
hr = pIFactory->CreateInstance(pUnkOuter, riid, ppv);
pIFactory->Release();
}
while ( false );
if ( FAILED(hr) && hDll != nullptr )
FreeLibrary(hDll);
else
*phMod = hDll;
return hr;
}
//----------------------------------------------------------------------------
// Note: This will return the machine type, as it is known
// by the IDB, which might not be what you think. For example,
// if you need to tell x86 and x64 apart, you're out of luck.
// You may want to consider looking at pdbaccess_t's
// get_machine_type().
static DWORD get_machine_type(DWORD dwMachType)
{
DWORD machine;
switch ( dwMachType )
{
default:
machine = CV_CFL_80386;
break;
case IMAGE_FILE_MACHINE_IA64:
machine = CV_CFL_IA64;
break;
case IMAGE_FILE_MACHINE_AMD64:
machine = CV_CFL_AMD64;
break;
case IMAGE_FILE_MACHINE_THUMB:
case IMAGE_FILE_MACHINE_ARM:
machine = CV_CFL_ARM6;
break;
case PECPU_ARMV7:
machine = CV_CFL_ARM7;
break;
case PECPU_ARM64:
machine = CV_CFL_ARM64;
break;
case PECPU_PPC:
machine = CV_CFL_PPC620;
break;
case PECPU_PPCFP:
machine = CV_CFL_PPCFP;
break;
case PECPU_PPCBE:
machine = CV_CFL_PPCBE;
break;
}
return machine;
}
//----------------------------------------------------------------------
pdb_session_t::~pdb_session_t()
{
if ( --session_count == 0 && co_initialized )
{
CoUninitialize();
co_initialized = false;
}
}
//----------------------------------------------------------------------
void pdb_session_t::close()
{
if ( pdb_access != nullptr )
{
delete pdb_access;
pdb_access = nullptr;
}
if ( dia_hmod != nullptr )
{
FreeLibrary(dia_hmod);
dia_hmod = nullptr;
}
#ifdef _DEBUG
if ( !_pdb_path.empty() && qfileexist(_pdb_path.begin() ) )
{
HANDLE hFile = CreateFileA(_pdb_path.begin(), GENERIC_READ, /*FILE_SHARE_READ*/ 0, 0, OPEN_EXISTING, 0, 0);
if ( hFile == INVALID_HANDLE_VALUE )
warning("Couldn't acquire probing lock to \"%s\"; file might be still locked by IDA", _pdb_path.begin());
else
CloseHandle(hFile);
}
#endif
}
//----------------------------------------------------------------------
#include "dbghelp.h"
// copied from dbghelp.h
#ifndef SSRVOPT_CALLBACK
#define SSRVOPT_CALLBACK 0x000001
#endif
#ifndef SSRVOPT_SETCONTEXT
#define SSRVOPT_SETCONTEXT 0x000800
#endif
#ifndef SSRVOPT_TRACE
#define SSRVOPT_TRACE 0x000400
#endif
#ifndef SSRVACTION_TRACE
#define SSRVACTION_TRACE 1
#define SSRVACTION_QUERYCANCEL 2
#define SSRVACTION_EVENT 3
#define SSRVACTION_EVENTW 4
#endif
#ifndef SSRVACTION_SIZE
#define SSRVACTION_SIZE 5
#endif
//----------------------------------------------------------------------
static void symsrv_dprint(const char *str)
{
qstring qbuf(str);
qbuf.replace("\b", ""); // remove backspaces
if ( qbuf.empty() )
return;
// strings usually already start with "SYMSRV: "
if ( strncmp(qbuf.c_str(), "SYMSRV: ", 9) != 0 )
qbuf.insert(0, "SYMSRV: ");
// strings usually already end with '\n'
if ( qbuf.last() != '\n' )
qbuf.append('\n');
deb(IDA_DEBUG_DEBUGGER, "%s", qbuf.c_str());
}
static int GetDownloadPercentFromSymbolServerMessage(CString& Src)
{
int result = 0;
if (Src.Find("copied") == -1)
{
if (Src.Find("percent") != -1)
{
Src.TrimLeft('\b');
char* EndPtr = nullptr;
result = strtol(Src, &EndPtr, 10);
}
}
else
{
result = 100;
}
return result;
}
//----------------------------------------------------------------------
static BOOL CALLBACK SymbolServerCallback(
UINT_PTR action,
ULONG64 data,
ULONG64 context)
{
bool *wait_box_shown = (bool *) context;
switch ( action )
{
case SSRVACTION_SIZE:
{
if ( !*wait_box_shown )
show_wait_box("Downloading pdb...");
*wait_box_shown = true;
}
break;
case SSRVACTION_QUERYCANCEL:
{
//https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nc-dbghelp-psymbolservercallbackproc
//文档说明是取消变量*data是ULONG64类型
ULONG64* do_cancel = (ULONG64*)data;
// apparently this can arrive before SSRVACTION_SIZE
// so check that we did show the waitbox
if ( *wait_box_shown && user_cancelled() )
*do_cancel = TRUE;
else
*do_cancel = FALSE;
}
break;
case SSRVACTION_TRACE:
symsrv_dprint((const char *)data);
ATLTRACE((const char*)data);
break;
case SSRVACTION_EVENT:
IMAGEHLP_CBA_EVENT *pev = (IMAGEHLP_CBA_EVENT*)data;
// Event information is usually all zero.
if ( pev->severity != 0 || pev->code != 0 || pev->object != nullptr )
deb(IDA_DEBUG_DEBUGGER, "SYMSRV: event severity: %d code: %d object: %p\n", pev->severity, pev->code, pev->object);
CString strText;
if (IS_INTRESOURCE(pev->desc))
{
strText.LoadString((UINT)pev->desc);
}
else
{
strText = pev->desc;
}
if (strText.Find('\b') == -1 && strText.Find("percent") == -1 && strText.Find("copied") == -1)
{
symsrv_dprint(strText);
ATLTRACE(strText);
}
else
{
int nPercent = GetDownloadPercentFromSymbolServerMessage(strText);
replace_wait_box("Downloading pdb (%d%%)", nPercent);
}
break;
}
return TRUE;
}
void try_download_pdb_from_sym_server_by_idm_when_not_exist(clsid_t& guid, uint32 age, const char* pdb_path, qstring& spath)
{
CRegKey key;
if (!key.Open(HKEY_CURRENT_USER, "Software\\DownloadManager", KEY_READ))
{
TCHAR szExePath[MAX_PATH];
ULONG nChars = _countof(szExePath);
if (!key.QueryStringValue("ExePath", szExePath, &nChars))
{
if (qfileexist(szExePath))
{
typedef BOOL(WINAPI* HTTPOPENFILEHANDLE)(LPCSTR, LPCSTR, DWORD, HANDLE*, HANDLE*);
typedef BOOL(WINAPI* HTTPQUERYDATAAVAILABLE)(HANDLE, LPDWORD, DWORD, DWORD_PTR);
typedef BOOL(WINAPI* HTTPREADFILE)(HANDLE, LPVOID, DWORD, LPDWORD);
typedef BOOL(WINAPI* HTTPCLOSEHANDLE)(HANDLE);
HMODULE symsrv_hmod = GetModuleHandle("symsrv.dll");
HTTPOPENFILEHANDLE httpOpenFileHandle = (HTTPOPENFILEHANDLE)GetProcAddress(symsrv_hmod, "httpOpenFileHandle");
HTTPQUERYDATAAVAILABLE httpQueryDataAvailable = (HTTPQUERYDATAAVAILABLE)GetProcAddress(symsrv_hmod, "httpQueryDataAvailable");
HTTPREADFILE httpReadFile = (HTTPREADFILE)GetProcAddress(symsrv_hmod, "httpReadFile");
HTTPCLOSEHANDLE httpCloseHandle = (HTTPCLOSEHANDLE)GetProcAddress(symsrv_hmod, "httpCloseHandle");
BOOL bHttpIsValid = httpOpenFileHandle && httpQueryDataAvailable && httpReadFile && httpCloseHandle;
ASSERT(bHttpIsValid);
if (bHttpIsValid)
{
PSYMBOLSERVERSETOPTIONSPROC set_options = (PSYMBOLSERVERSETOPTIONSPROC)(void*)GetProcAddress(symsrv_hmod, "SymbolServerSetOptions");
PSYMBOLSERVERGETINDEXSTRING get_index_string = (PSYMBOLSERVERGETINDEXSTRING)GetProcAddress(symsrv_hmod, "SymbolServerGetIndexString");
ASSERT(set_options && get_index_string);
if (set_options && get_index_string)
{
CHAR szIndexString[sizeof(GUID) * 2 + 1 + 1 + 1];
set_options(SSRVOPT_PARAMTYPE, SSRVOPT_GUIDPTR);
BOOL bResult = get_index_string(&guid, age, 0, szIndexString, _countof(szIndexString));
ASSERT(bResult);
if (bResult)
{
const char* pdb_name = qbasename(pdb_path);
qstring path;
path.sprnt("%s/%s/%s", pdb_name, szIndexString, pdb_name);
bool bFindCache = false;
qvector<qstring> cache_paths;
qvector<qstring> srvs;
LPSTR next_token = nullptr;
LPSTR token = qstrtok(spath.begin(), ";", &next_token);
while (token != nullptr)
{
qstring item(token);
LPSTR next_token_item = nullptr;
LPTSTR spath_prefix = qstrtok(item.begin(), "*", &next_token_item);
ASSERT(spath_prefix);
if (!strnicmp(spath_prefix, "srv", _countof("srv") - 1))
{
LPTSTR cache_path = qstrtok(nullptr, "*", &next_token_item);
ASSERT(cache_path);
if (cache_path)
{
qstring cache_file;
cache_file.sprnt("%s\\%s", cache_path, path.c_str());
if (qfileexist(cache_file.c_str()))
{
bFindCache = true;
break;
}
cache_paths.push_back(cache_path);
LPTSTR srv = qstrtok(nullptr, "*", &next_token_item);
if (srv)
{
srvs.push_back(srv);
}
}
}
// Get next token:
token = qstrtok(nullptr, ";", &next_token);
}
if (!bFindCache)
{
for (size_t i = 0; i < cache_paths.size(); i++)
{
qstring srv = srvs[i];
size_t pos = srv.find("//");
if (pos != qstring::npos)
{
pos = srv.find('/', pos + 2);
}
else
{
pos = srv.find('/');
}
qstring srv_path;
if (pos != qstring::npos)
{
srv_path = &srv[pos + 1];
if (srv_path.last() != '/')
{
srv_path.append('/');
}
srv.resize(pos);
}
HANDLE hsite, hfile;
BOOL bResult = httpOpenFileHandle(srv.c_str(), (srv_path + path).c_str(), 0, &hsite, &hfile);
if (!bResult)
{
//尝试查找压缩格式的PDB文件(Mozilla服务器只提供了压缩格式,目前版本的IDA的PDB插件并不支持)
qstring path_Compressed;//CompressedFileName
path_Compressed = path.substr(0, path.length() - 1);
path_Compressed.append('_');
BOOL bResult_Compressed = httpOpenFileHandle(srv.c_str(), (srv_path + path_Compressed).c_str(), 0, &hsite, &hfile);
if (bResult_Compressed)
{
//由于需要处理CAB,LZExpand,ZIP的解压,所以目前我们暂时不处理,UncompressFile
//此时回落到使用symsrv.dll进行下载
msg("PDB: The external downloader currently does not support downloading compressed PDB files.\n");
break;
}
}
BOOL bDownloadPdbCompleted = FALSE;
if (bResult)
{
DWORD dwNumberOfBytesAvailable;
if (httpQueryDataAvailable(hfile, &dwNumberOfBytesAvailable, 0, 0))
{
char szBuffer[64];
DWORD dwNumberOfBytesToRead = __min(_countof(szBuffer), dwNumberOfBytesAvailable);
DWORD dwNumberOfBytesRead;
if (httpReadFile(hfile, szBuffer, dwNumberOfBytesToRead, &dwNumberOfBytesRead))
{
if (dwNumberOfBytesRead == dwNumberOfBytesToRead)
{
//下载下来的不一定是一个PDB文件,老版本symsrv.dll甚至会把HTTP 404 Not Found的数据都读取出来
if (!strncmp(szBuffer, "Microsoft C/C++ ", _countof("Microsoft C/C++ ") - 1))
{
ATLTRACE("FIND PDB IN SERVER: %s\n", srv);
qstring url(srv);
if (url.last() != '/')
{
url.append('/');
}
url.append(srv_path + path);
char szRelPath[MAX_PATH];
szRelPath[0] = 0;
qdirname(szRelPath, _countof(szRelPath), path.c_str());
size_t nRelPathLen = qstrlen(szRelPath);
for (size_t j = 0; j < nRelPathLen; j++)
{
if (szRelPath[j] == '/')
{
szRelPath[j] = '\\';
}
}
qstring local_path(cache_paths[i]);
if (local_path[local_path.length() - 1] != '\\')
{
local_path.append('\\');
}
local_path.append(szRelPath);
qstring local_full_path(local_path);
local_full_path.append('\\');
local_full_path.append(pdb_name);
if (qfileexist(local_full_path.c_str()))
{
qunlink(local_full_path.c_str());
}
show_wait_box("Waiting for external download to complete...\n%s", url.c_str());
qstring strArgs;
strArgs.sprnt("/d \"%s\" /p \"%s\" /f \"%s\" /q /n", url.c_str(), local_path.c_str(), pdb_name);
launch_process_params_t lpp;
lpp.flags = 0;
lpp.path = szExePath;
lpp.args = strArgs.c_str();
qstring errbuf;
void* handle = launch_process(lpp, &errbuf);
if (handle)
{
while (!qfileexist(local_full_path.c_str()))
{
if (handle)
{
int exit_code = 0;
if (check_process_exit(handle, &exit_code, 50) == 0)
{
handle = nullptr;
}
}
else
{
Sleep(50);
}
if (user_cancelled())
{
break;
}
}
if (qfileexist(local_full_path.c_str()))
{
//等待第三方下载工具写入完成,也即我们能获取到独占写入权限的时候
do
{
FILE* file = qfopen(local_full_path.c_str(), "a+b");
if (file)
{
qfclose(file);
file = nullptr;
bDownloadPdbCompleted = TRUE;
break;
}
Sleep(50);
} while (TRUE);
}
}
hide_wait_box();
}
}
}
}
httpCloseHandle(hfile);
hfile = nullptr;
httpCloseHandle(hsite);
hsite = nullptr;
}
if (bDownloadPdbCompleted)
{
break;
}
}
}
}
}
}
}
}
}
}
//----------------------------------------------------------------------------
class symsrv_cb_t
{
HMODULE symsrv_hmod;
bool wait_box_shown;
PSYMBOLSERVERGETOPTIONDATAPROC get_option_data; // "DbgHelp.dll 10.0 or later"
PSYMBOLSERVERSETOPTIONSPROC set_options;
ULONG64 was_context;
ULONG64 was_callback;
public:
symsrv_cb_t(void)
{
symsrv_hmod = LoadLibrary("symsrv.dll");
if (!symsrv_hmod)
{
warning("The \"symsrv.dll\" file cannot be found, so it may not be possible to download symbols online!");
}
else
{
TCHAR szVersionFile[MAX_PATH];
GetModuleFileName(symsrv_hmod, szVersionFile, _countof(szVersionFile));
ASSERT(szVersionFile[0]);
//https://stackoverflow.com/questions/940707/how-do-i-programmatically-get-the-version-of-a-dll-or-exe-file
DWORD verHandle = 0;
UINT size = 0;
LPBYTE lpBuffer = nullptr;
DWORD verSize = GetFileVersionInfoSize(szVersionFile, &verHandle);
if (verSize != 0)
{
BYTE* verData = new BYTE[verSize];
if (GetFileVersionInfo(szVersionFile, verHandle, verSize, verData))
{
if (VerQueryValue(verData, _T("\\"), (LPVOID*)&lpBuffer, &size))
{
if (size)
{
VS_FIXEDFILEINFO* verInfo = (VS_FIXEDFILEINFO*)lpBuffer;
if (verInfo->dwSignature == 0xfeef04bd)
{
// Doesn't matter if you are on 32 bit or 64 bit,
// DWORD is always 32 bits, so first two revision numbers
// come from dwFileVersionMS, last two come from dwFileVersionLS
ULONGLONG ullCurVersion = make_uint64(verInfo->dwFileVersionLS, verInfo->dwFileVersionMS);
ULONGLONG ullMinVersion = make_uint64(MAKELONG(1001, 19596), MAKELONG(0, 10));
if (ullCurVersion < ullMinVersion)
{
warning("The version of the symsrv.dll file is lower than 10.0.19596.1001, so it cannot support immediate cancellation of the download operation!");
}
}
}
}
}
delete[] verData;
verData = nullptr;
}
}
wait_box_shown = false;
get_option_data = nullptr;
set_options = nullptr;
was_context = 0;
was_callback = 0;
}
void init(void)
{
if ( symsrv_hmod != nullptr )
{
get_option_data = (PSYMBOLSERVERGETOPTIONDATAPROC)(void *)GetProcAddress(symsrv_hmod, "SymbolServerGetOptionData");
if ( get_option_data != nullptr )
{
get_option_data(SSRVOPT_SETCONTEXT, &was_context);
get_option_data(SSRVOPT_CALLBACK, &was_callback);
}
set_options = (PSYMBOLSERVERSETOPTIONSPROC)(void *)GetProcAddress(symsrv_hmod, "SymbolServerSetOptions");
if ( set_options != nullptr )
{
set_options(SSRVOPT_SETCONTEXT, (ULONG64) (intptr_t) &wait_box_shown);
set_options(SSRVOPT_CALLBACK, (ULONG64) SymbolServerCallback);
if ( (debug & IDA_DEBUG_DEBUGGER) != 0 )
{
set_options(SSRVOPT_TRACE, (ULONG64) TRUE);
}
}
}
}
void term(void)