-
Notifications
You must be signed in to change notification settings - Fork 2
/
symbol_enum.cpp
479 lines (397 loc) · 15.7 KB
/
symbol_enum.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
#include "stdafx.h"
#include "symbol_enum.h"
namespace {
std::filesystem::path g_enginePath;
SymbolEnum::Callbacks* g_symbolServerCallbacks;
void VLogLine(PCWSTR format, va_list args) {
WCHAR buffer[1025];
int len = _vsnwprintf_s(buffer, _TRUNCATE, format, args);
if (len == -1) {
// Truncation occurred.
len = _countof(buffer) - 1;
}
while (--len >= 0 && buffer[len] == L'\n') {
// Skip all newlines at the end.
}
// Leave only a single trailing newline.
if (buffer[len + 1] == L'\n' && buffer[len + 2] == L'\n') {
buffer[len + 2] = L'\0';
}
OutputDebugString(buffer);
}
void LogLine(PCWSTR format, ...) {
va_list args;
va_start(args, format);
VLogLine(format, args);
va_end(args);
}
#define LOG(format, ...) \
LogLine(L"[!] SymbolEnum (%S): " format L"\n", __FUNCTION__, __VA_ARGS__)
#define VERBOSE(format, ...) \
LogLine(L"[+] SymbolEnum (%S): " format L"\n", __FUNCTION__, __VA_ARGS__)
std::wstring GetSymbolsSearchPath(PCWSTR symbolsPath, PCWSTR symbolServer) {
std::wstring symSearchPath = L"srv*";
symSearchPath += symbolsPath;
symSearchPath += L'*';
symSearchPath += symbolServer;
return symSearchPath;
}
void LogSymbolServerEvent(PCSTR msg) {
// Trim leading and trailing whitespace and control characters (mainly \b
// which is used for console output).
PCSTR p = msg;
while (*p != '\0' && (isspace(*p) || iscntrl(*p))) {
p++;
}
if (*p == '\0') {
return;
}
size_t len = strlen(p);
while (len > 0 && (isspace(p[len - 1]) || iscntrl(p[len - 1]))) {
len--;
}
VERBOSE(L"%.*S", static_cast<int>(len), p);
}
int PercentFromSymbolServerEvent(PCSTR msg) {
size_t msgLen = strlen(msg);
while (msgLen > 0 && isspace(msg[msgLen - 1])) {
msgLen--;
}
constexpr char suffix[] = " percent";
constexpr size_t suffixLen = ARRAYSIZE(suffix) - 1;
if (msgLen <= suffixLen ||
strncmp(suffix, msg + msgLen - suffixLen, suffixLen) != 0) {
return -1;
}
char percentStr[] = "000";
int digitsCount = 0;
for (size_t i = 1; i <= 3; i++) {
if (i > msgLen - suffixLen) {
break;
}
char p = msg[msgLen - suffixLen - i];
if (p < '0' || p > '9') {
break;
}
percentStr[3 - i] = p;
digitsCount++;
}
if (digitsCount == 0) {
return -1;
}
int percent = (percentStr[0] - '0') * 100 + (percentStr[1] - '0') * 10 +
(percentStr[2] - '0');
if (percent > 100) {
return -1;
}
return percent;
}
void** FindImportPtr(HMODULE hFindInModule,
PCSTR pModuleName,
PCSTR pImportName) {
IMAGE_DOS_HEADER* pDosHeader;
IMAGE_NT_HEADERS* pNtHeader;
ULONG_PTR ImageBase;
IMAGE_IMPORT_DESCRIPTOR* pImportDescriptor;
ULONG_PTR* pOriginalFirstThunk;
ULONG_PTR* pFirstThunk;
ULONG_PTR ImageImportByName;
// Init
pDosHeader = (IMAGE_DOS_HEADER*)hFindInModule;
pNtHeader = (IMAGE_NT_HEADERS*)((char*)pDosHeader + pDosHeader->e_lfanew);
if (!pNtHeader->OptionalHeader.DataDirectory[1].VirtualAddress)
return nullptr;
ImageBase = (ULONG_PTR)hFindInModule;
pImportDescriptor =
(IMAGE_IMPORT_DESCRIPTOR*)(ImageBase +
pNtHeader->OptionalHeader.DataDirectory[1]
.VirtualAddress);
// Search!
while (pImportDescriptor->OriginalFirstThunk) {
if (lstrcmpiA((char*)(ImageBase + pImportDescriptor->Name),
pModuleName) == 0) {
pOriginalFirstThunk =
(ULONG_PTR*)(ImageBase + pImportDescriptor->OriginalFirstThunk);
ImageImportByName = *pOriginalFirstThunk;
pFirstThunk =
(ULONG_PTR*)(ImageBase + pImportDescriptor->FirstThunk);
while (ImageImportByName) {
if (!(ImageImportByName & IMAGE_ORDINAL_FLAG)) {
if ((ULONG_PTR)pImportName & ~0xFFFF) {
ImageImportByName += sizeof(WORD);
if (lstrcmpA((char*)(ImageBase + ImageImportByName),
pImportName) == 0)
return (void**)pFirstThunk;
}
} else {
if (((ULONG_PTR)pImportName & ~0xFFFF) == 0)
if ((ImageImportByName & 0xFFFF) ==
(ULONG_PTR)pImportName)
return (void**)pFirstThunk;
}
pOriginalFirstThunk++;
ImageImportByName = *pOriginalFirstThunk;
pFirstThunk++;
}
}
pImportDescriptor++;
}
return nullptr;
}
BOOL CALLBACK SymbolServerCallback(UINT_PTR action,
ULONG64 data,
ULONG64 context) {
SymbolEnum::Callbacks* callbacks = g_symbolServerCallbacks;
if (!callbacks) {
return FALSE;
}
switch (action) {
case SSRVACTION_QUERYCANCEL: {
if (callbacks->queryCancel) {
ULONG64* doCancel = (ULONG64*)data;
*doCancel = callbacks->queryCancel();
return TRUE;
}
return FALSE;
}
case SSRVACTION_EVENT: {
IMAGEHLP_CBA_EVENT* evt = (IMAGEHLP_CBA_EVENT*)data;
LogSymbolServerEvent(evt->desc);
if (callbacks->notifyLog) {
callbacks->notifyLog(evt->desc);
}
int percent = PercentFromSymbolServerEvent(evt->desc);
if (percent >= 0 && callbacks->notifyProgress) {
callbacks->notifyProgress(percent);
}
return TRUE;
}
}
return FALSE;
}
struct DiaLoadCallback : public IDiaLoadCallback2 {
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,
void** ppvObject) override {
if (riid == __uuidof(IUnknown) || riid == __uuidof(IDiaLoadCallback)) {
*ppvObject = static_cast<IDiaLoadCallback*>(this);
return S_OK;
} else if (riid == __uuidof(IDiaLoadCallback2)) {
*ppvObject = static_cast<IDiaLoadCallback2*>(this);
return S_OK;
}
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE AddRef() override {
return 2; // On stack
}
ULONG STDMETHODCALLTYPE Release() override {
return 1; // On stack
}
HRESULT STDMETHODCALLTYPE NotifyDebugDir(BOOL fExecutable,
DWORD cbData,
BYTE* pbData) override {
// VERBOSE(L"Debug directory found in %s file",
// fExecutable ? L"exe" : L"dbg");
return S_OK;
}
HRESULT STDMETHODCALLTYPE NotifyOpenDBG(LPCOLESTR dbgPath,
HRESULT resultCode) override {
VERBOSE(L"Opened dbg file %s: %s (%08X)", dbgPath,
resultCode == S_OK ? L"success" : L"error", resultCode);
return S_OK;
}
HRESULT STDMETHODCALLTYPE NotifyOpenPDB(LPCOLESTR pdbPath,
HRESULT resultCode) override {
VERBOSE(L"Opened pdb file %s: %s (%08X)", pdbPath,
resultCode == S_OK ? L"success" : L"error", resultCode);
return S_OK;
}
// Only use explicitly specified search paths, restrict all but symbol
// server access:
HRESULT STDMETHODCALLTYPE RestrictRegistryAccess() override {
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE RestrictSymbolServerAccess() override {
return S_OK;
}
HRESULT STDMETHODCALLTYPE RestrictOriginalPathAccess() override {
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE RestrictReferencePathAccess() override {
return E_FAIL;
}
HRESULT STDMETHODCALLTYPE RestrictDBGAccess() override { return E_FAIL; }
HRESULT STDMETHODCALLTYPE RestrictSystemRootAccess() override {
return E_FAIL;
}
};
HMODULE WINAPI MsdiaLoadLibraryExWHook(LPCWSTR lpLibFileName,
HANDLE hFile,
DWORD dwFlags) {
if (wcscmp(lpLibFileName, L"SYMSRV.DLL") != 0) {
return LoadLibraryExW(lpLibFileName, hFile, dwFlags);
}
try {
DWORD dwNewFlags = dwFlags;
dwNewFlags |= LOAD_WITH_ALTERED_SEARCH_PATH;
// Strip flags incompatible with LOAD_WITH_ALTERED_SEARCH_PATH.
dwNewFlags &= ~LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
dwNewFlags &= ~LOAD_LIBRARY_SEARCH_APPLICATION_DIR;
dwNewFlags &= ~LOAD_LIBRARY_SEARCH_USER_DIRS;
dwNewFlags &= ~LOAD_LIBRARY_SEARCH_SYSTEM32;
dwNewFlags &= ~LOAD_LIBRARY_SEARCH_DEFAULT_DIRS;
auto symsrvPath = g_enginePath / L"symsrv_windhawk.dll";
HMODULE symsrvModule =
LoadLibraryExW(symsrvPath.c_str(), hFile, dwNewFlags);
if (!symsrvModule) {
DWORD error = GetLastError();
LOG(L"Couldn't load symsrv: %u", error);
SetLastError(error);
return symsrvModule;
}
PSYMBOLSERVERSETOPTIONSPROC pSymbolServerSetOptions =
reinterpret_cast<PSYMBOLSERVERSETOPTIONSPROC>(
GetProcAddress(symsrvModule, "SymbolServerSetOptions"));
if (pSymbolServerSetOptions) {
pSymbolServerSetOptions(SSRVOPT_UNATTENDED, TRUE);
pSymbolServerSetOptions(SSRVOPT_CALLBACK,
(ULONG_PTR)SymbolServerCallback);
pSymbolServerSetOptions(SSRVOPT_TRACE, TRUE);
} else {
LOG(L"Couldn't find SymbolServerSetOptions");
}
return symsrvModule;
} catch (const std::exception& e) {
LOG(L"Couldn't load symsrv: %S", e.what());
SetLastError(ERROR_MOD_NOT_FOUND);
return nullptr;
}
}
} // namespace
SymbolEnum::SymbolEnum(HMODULE moduleBase,
PCWSTR enginePath,
PCWSTR symbolsPath,
PCWSTR symbolServer,
UndecorateMode undecorateMode,
Callbacks callbacks) {
if (!moduleBase) {
moduleBase = GetModuleHandle(nullptr);
}
std::wstring modulePath = wil::GetModuleFileName<std::wstring>(moduleBase);
SymbolEnum(modulePath.c_str(), moduleBase, enginePath, symbolsPath,
symbolServer, undecorateMode, std::move(callbacks));
}
SymbolEnum::SymbolEnum(PCWSTR modulePath,
HMODULE moduleBase,
PCWSTR enginePath,
PCWSTR symbolsPath,
PCWSTR symbolServer,
UndecorateMode undecorateMode,
Callbacks callbacks)
: m_moduleBase(moduleBase), m_undecorateMode(undecorateMode) {
#ifdef _WIN64
g_enginePath = std::filesystem::path(enginePath) / L"64";
#else
g_enginePath = std::filesystem::path(enginePath) / L"32";
#endif
wil::com_ptr<IDiaDataSource> diaSource = LoadMsdia();
std::wstring symSearchPath =
GetSymbolsSearchPath(symbolsPath, symbolServer);
g_symbolServerCallbacks = &callbacks;
auto msdiaCallbacksCleanup =
wil::scope_exit([] { g_symbolServerCallbacks = nullptr; });
DiaLoadCallback diaLoadCallback;
THROW_IF_FAILED(diaSource->loadDataForExe(modulePath, symSearchPath.c_str(),
&diaLoadCallback));
wil::com_ptr<IDiaSession> diaSession;
THROW_IF_FAILED(diaSource->openSession(&diaSession));
THROW_IF_FAILED(diaSession->get_globalScope(&m_diaGlobal));
THROW_IF_FAILED(
m_diaGlobal->findChildren(kSymTags[0], nullptr, nsNone, &m_diaSymbols));
}
std::optional<SymbolEnum::Symbol> SymbolEnum::GetNextSymbol() {
while (true) {
wil::com_ptr<IDiaSymbol> diaSymbol;
ULONG count = 0;
HRESULT hr = m_diaSymbols->Next(1, &diaSymbol, &count);
THROW_IF_FAILED(hr);
if (hr == S_FALSE || count == 0) {
m_symTagIndex++;
if (m_symTagIndex < ARRAYSIZE(kSymTags)) {
THROW_IF_FAILED(m_diaGlobal->findChildren(
kSymTags[m_symTagIndex], nullptr, nsNone, &m_diaSymbols));
continue;
}
return std::nullopt;
}
DWORD currentSymbolRva;
hr = diaSymbol->get_relativeVirtualAddress(¤tSymbolRva);
THROW_IF_FAILED(hr);
if (hr == S_FALSE) {
continue; // no RVA
}
// Temporary compatibility code.
if (m_undecorateMode == UndecorateMode::OldVersionCompatible) {
// get_undecoratedName uses 0x20800 as flags:
// * UNDNAME_32_BIT_DECODE (0x800)
// * UNDNAME_NO_PTR64 (0x20000)
// For some reason, the old msdia version still included ptr64 in
// the output. For compatibility, use get_undecoratedNameEx and
// don't pass this flag.
constexpr DWORD kUndname32BitDecode = 0x800;
hr = diaSymbol->get_undecoratedNameEx(kUndname32BitDecode,
&m_currentSymbolName);
} else if (m_undecorateMode == UndecorateMode::Default) {
hr = diaSymbol->get_undecoratedName(&m_currentSymbolName);
} else {
m_currentSymbolName.reset();
hr = S_OK;
}
THROW_IF_FAILED(hr);
if (hr == S_FALSE) {
m_currentSymbolName.reset(); // no name
}
hr = diaSymbol->get_name(&m_currentDecoratedSymbolName);
THROW_IF_FAILED(hr);
if (hr == S_FALSE) {
m_currentDecoratedSymbolName.reset(); // no name
}
return SymbolEnum::Symbol{
reinterpret_cast<void*>(reinterpret_cast<BYTE*>(m_moduleBase) +
currentSymbolRva),
m_currentSymbolName.get(), m_currentDecoratedSymbolName.get()};
}
}
wil::com_ptr<IDiaDataSource> SymbolEnum::LoadMsdia() {
auto msdiaPath = g_enginePath / L"msdia140_windhawk.dll";
m_msdiaModule.reset(LoadLibraryEx(msdiaPath.c_str(), nullptr,
LOAD_WITH_ALTERED_SEARCH_PATH));
THROW_LAST_ERROR_IF_NULL(m_msdiaModule);
// msdia loads symsrv.dll by using the following call:
// LoadLibraryExW(L"SYMSRV.DLL");
// This is problematic for the following reasons:
// * If another file named symsrv.dll is already loaded,
// it will be used instead.
// * If not, the library loading search path doesn't include our folder
// by default.
// Especially due to the first point, we patch msdia in memory to use
// the full path to our copy of symsrv.dll.
// Also, to prevent from other msdia instances to load our version of
// symsrv, we name it differently.
void** msdiaLoadLibraryExWPtr =
FindImportPtr(m_msdiaModule.get(), "kernel32.dll", "LoadLibraryExW");
DWORD dwOldProtect;
THROW_IF_WIN32_BOOL_FALSE(
VirtualProtect(msdiaLoadLibraryExWPtr, sizeof(*msdiaLoadLibraryExWPtr),
PAGE_EXECUTE_READWRITE, &dwOldProtect));
*msdiaLoadLibraryExWPtr = MsdiaLoadLibraryExWHook;
THROW_IF_WIN32_BOOL_FALSE(VirtualProtect(msdiaLoadLibraryExWPtr,
sizeof(*msdiaLoadLibraryExWPtr),
dwOldProtect, &dwOldProtect));
wil::com_ptr<IDiaDataSource> diaSource;
THROW_IF_FAILED(NoRegCoCreate(msdiaPath.c_str(), CLSID_DiaSource,
IID_PPV_ARGS(&diaSource)));
// Decrements the reference count incremented by NoRegCoCreate.
FreeLibrary(m_msdiaModule.get());
return diaSource;
}