aboutsummaryrefslogtreecommitdiffhomepage
path: root/samples/findfunc/symtest.cpp
blob: 74cd5397b0f8bd5c047fca0ea457ad409d8f4e64 (plain)
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
//////////////////////////////////////////////////////////////////////////////
//
//  Detour Test Program (symtest.cpp of symtest.exe)
//
//  Microsoft Research Detours Package
//
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//

#include <windows.h>
#include <stdio.h>
#pragma warning(push)
#if _MSC_VER > 1400
#pragma warning(disable:6102 6103) // /analyze warnings
#endif
#include <strsafe.h>
#pragma warning(pop)
#include <detours.h>
#include "target.h"

#if (_MSC_VER < 1299)
#include <imagehlp.h>
typedef IMAGEHLP_MODULE IMAGEHLP_MODULE64;
typedef PIMAGEHLP_MODULE PIMAGEHLP_MODULE64;
typedef IMAGEHLP_SYMBOL SYMBOL_INFO;
typedef PIMAGEHLP_SYMBOL PSYMBOL_INFO;
#else
#pragma warning(push)
#pragma warning(disable:4091) // empty typedef
#include <dbghelp.h>
#pragma warning(pop)
#endif

//////////////////////////////////////////////////////////////////////////////
//
typedef LPAPI_VERSION (NTAPI *PF_ImagehlpApiVersionEx)(LPAPI_VERSION AppVersion);

typedef BOOL (NTAPI *PF_SymInitialize)(IN HANDLE hProcess,
                                       IN LPCSTR UserSearchPath,
                                       IN BOOL fInvadeProcess);
typedef DWORD (NTAPI *PF_SymSetOptions)(IN DWORD SymOptions);
typedef DWORD (NTAPI *PF_SymGetOptions)(VOID);
typedef DWORD64 (NTAPI *PF_SymLoadModule64)(IN HANDLE hProcess,
                                            IN HANDLE hFile,
                                            IN PSTR ImageName,
                                            IN PSTR ModuleName,
                                            IN DWORD64 BaseOfDll,
                                            IN DWORD SizeOfDll);
typedef BOOL (NTAPI *PF_SymGetModuleInfo64)(IN HANDLE hProcess,
                                            IN DWORD64 qwAddr,
                                            OUT PIMAGEHLP_MODULE64 ModuleInfo);
typedef BOOL (NTAPI *PF_SymFromName)(IN HANDLE hProcess,
                                     IN LPSTR Name,
                                     OUT PSYMBOL_INFO Symbol);
#if (_MSC_VER < 1299)
typedef BOOL (NTAPI *PF_SymRegisterCallback64)();
typedef BOOL (NTAPI *PF_SymEnumerateModules64)();
typedef BOOL (NTAPI *PF_SymEnumSymbols)();
#else
typedef BOOL (NTAPI *PF_SymRegisterCallback64)(IN HANDLE hProcess,
                                               IN PSYMBOL_REGISTERED_CALLBACK64
                                               CallbackFunction,
                                               IN ULONG64 UserContext);
typedef BOOL (NTAPI *PF_SymEnumerateModules64)(IN HANDLE hProcess,
                                               IN PSYM_ENUMMODULES_CALLBACK64
                                               EnumModulesCallback,
                                               IN PVOID UserContext);
typedef BOOL (NTAPI *PF_SymEnumSymbols)(IN HANDLE hProcess,
                                        IN ULONG64 BaseOfDll,
                                        IN PCSTR Mask,
                                        IN PSYM_ENUMERATESYMBOLS_CALLBACK
                                        EnumSymbolsCallback,
                                        IN PVOID UserContext);
#endif

PF_ImagehlpApiVersionEx     pfImagehlpApiVersionEx = NULL;
PF_SymInitialize            pfSymInitialize = NULL;
PF_SymSetOptions            pfSymSetOptions = NULL;
PF_SymGetOptions            pfSymGetOptions = NULL;
PF_SymLoadModule64          pfSymLoadModule64 = NULL;
PF_SymGetModuleInfo64       pfSymGetModuleInfo64 = NULL;
PF_SymFromName              pfSymFromName = NULL;
PF_SymRegisterCallback64    pfSymRegisterCallback64 = NULL;
PF_SymEnumerateModules64    pfSymEnumerateModules64 = NULL;
PF_SymEnumSymbols           pfSymEnumSymbols = NULL;

//////////////////////////////////////////////////////////////////////////////
//

#if (_MSC_VER > 1299)
static BOOL WINAPI SymEnumerateCallback(
                                        PCSTR pszModule,
                                        DWORD64 base,
                                        PVOID pvUserContext)
{
    (void)pvUserContext;
    printf("  %p: %s\n", (PVOID)base, pszModule);
    return TRUE;
}

static int nSymbolCount = 0;
static BOOL WINAPI SymEnumerateSymbols(PSYMBOL_INFO pSym,
                                       ULONG size,
                                       PVOID pvUserContext)
{
    (void)size;
    (void)pvUserContext;
    if (strstr(pSym->Name, "Target") != NULL ||
        strstr(pSym->Name, "Hidden") != NULL) {
        printf("  %p: %s\n", (PVOID)pSym->Address, pSym->Name);
        nSymbolCount++;
    }
    else if (nSymbolCount < 5) {
        printf("  %p: %s\n", (PVOID)pSym->Address, pSym->Name);
        nSymbolCount++;
    }
    return TRUE;
}

static void truncate(PCHAR data)
{
    size_t len = strlen(data);
    if (len > 0 && data[len-1] == '\r') {
        data[--len] = '\0';
    }
    if (len > 0 && data[len-1] == '\n') {
        data[--len] = '\0';
    }
}

BOOL WINAPI CallbackFunction(HANDLE hProcess, ULONG action, ULONG64 data, ULONG64 context)
{
    (void)context;

    switch (action) {
      case CBA_DEBUG_INFO:
        truncate((PCHAR)data);
        printf("::> %s\n", (PCHAR)data);
        return TRUE;

      case CBA_DEFERRED_SYMBOL_LOAD_CANCEL:
        printf("::> proc=%p action=%08lx data=%p\n",
                      (PVOID)hProcess,
                      action,
                      (PVOID)data);
        {
            PIMAGEHLP_DEFERRED_SYMBOL_LOAD64 pi = (PIMAGEHLP_DEFERRED_SYMBOL_LOAD64)data;
            printf("pi->SizeOfStruct = %ld\n", pi->SizeOfStruct);
            printf("pi->BaseOfImage  = %p\n", (PVOID)(size_t)pi->BaseOfImage);
            printf("pi->CheckSum     = %8lx\n", pi->CheckSum);
            printf("pi->FileName     = %p [%s]\n", pi->FileName, pi->FileName);
            printf("pi->Reparse      = %d\n", pi->Reparse);
        }
        return FALSE;
      default:
        printf("::> proc=%p action=%08lx data=%p\n",
                      (PVOID)hProcess,
                      action,
                      (PVOID)data);
        return FALSE;
    }
}
#endif

int __cdecl main(void)
{
    printf("symtest.exe: Starting.\n");
    fflush(stdout);

    //////////////////////////////////////////////////////// Get the functions.
    //
    HMODULE hDbgHelp = LoadLibraryA("dbghelp.dll");
    if (hDbgHelp == NULL) {
        printf("Couldn't load dbghelp.dll");
        return 1;
    }

    pfImagehlpApiVersionEx
        = (PF_ImagehlpApiVersionEx)GetProcAddress(hDbgHelp,
                                                  "ImagehlpApiVersionEx");
    pfSymInitialize
        = (PF_SymInitialize)GetProcAddress(hDbgHelp, "SymInitialize");
    pfSymSetOptions
        = (PF_SymSetOptions)GetProcAddress(hDbgHelp, "SymSetOptions");
    pfSymGetOptions
        = (PF_SymGetOptions)GetProcAddress(hDbgHelp, "SymGetOptions");
    pfSymLoadModule64
        = (PF_SymLoadModule64)GetProcAddress(hDbgHelp, "SymLoadModule64");
    pfSymGetModuleInfo64
        = (PF_SymGetModuleInfo64)GetProcAddress(hDbgHelp, "SymGetModuleInfo64");
    pfSymFromName
        = (PF_SymFromName)GetProcAddress(hDbgHelp, "SymFromName");
    pfSymRegisterCallback64
        = (PF_SymRegisterCallback64)GetProcAddress(hDbgHelp, "SymRegisterCallback64");
    pfSymEnumerateModules64
        = (PF_SymEnumerateModules64)GetProcAddress(hDbgHelp, "SymEnumerateModules64");
    pfSymEnumSymbols
        = (PF_SymEnumSymbols)GetProcAddress(hDbgHelp, "SymEnumSymbols");

    //////////////////////////////////////////////////////////////////////////////
    //
    HANDLE hProcess = GetCurrentProcess();

    API_VERSION av;
    ZeroMemory(&av, sizeof(av));
    av.MajorVersion = API_VERSION_NUMBER;

    pfImagehlpApiVersionEx(&av);
    printf("  Version: %d.%d (%d)\n",
                  av.MajorVersion,
                  av.MinorVersion,
                  API_VERSION_NUMBER);

    if (!pfSymInitialize(hProcess, NULL, FALSE)) {
        printf("SymInitialize failed: %ld\n", GetLastError());
        return 1;
    }

#if (_MSC_VER > 1299)
    pfSymRegisterCallback64(hProcess, CallbackFunction, NULL);
#endif

    DWORD dw = pfSymGetOptions();
    printf("GetOptions = %08lx\n", dw);
    dw &= ~(SYMOPT_CASE_INSENSITIVE |
            SYMOPT_UNDNAME |
            SYMOPT_DEFERRED_LOADS |
            0);
    dw |= (
#if defined(SYMOPT_EXACT_SYMBOLS)
           SYMOPT_EXACT_SYMBOLS |
#endif
#if defined(SYMOPT_DEBUG)
           SYMOPT_DEBUG |
#endif
#if defined(SYMOPT_NO_UNQUALIFIED_LOADS)
           SYMOPT_NO_UNQUALIFIED_LOADS |
#endif
#if defined(SYMOPT_FAIL_CRITICAL_ERRORS)
           SYMOPT_FAIL_CRITICAL_ERRORS |
#endif
#if defined(SYMOPT_INCLUDE_32BIT_MODULES)
           SYMOPT_INCLUDE_32BIT_MODULES |
#endif
           0);
    printf("SetOptions = %08lx\n", dw);
    pfSymSetOptions(dw);

    /////////////////////////////////////////////// First, try GetProcAddress.
    //
    PCHAR pszFile = "target" DETOURS_STRINGIFY(DETOURS_BITS) ".dll";
    HMODULE hModule = LoadLibraryA(pszFile);
    if (hModule == NULL) {
        printf("LoadLibraryA(%s) failed: %ld\n", pszFile, GetLastError());
        return 2;
    }

    ////////////////////////////////////////////////////// Then try ImageHelp.
    //
#if (_MSC_VER > 1299)

    //CHAR szFull[MAX_PATH];
    //GetModuleFileNameA(hModule, szFull, sizeof(szFull));
    printf("SymLoadModule64(%s) will be called.\n", pszFile /*szFull*/);
    DWORD64 loaded = pfSymLoadModule64(hProcess, NULL,
                                       (PCHAR)pszFile/*szFull*/, NULL,
                                       (DWORD64)hModule, 0);
    if (loaded == 0) {
        printf("SymLoadModule64(%p) failed: %ld\n", hProcess, GetLastError());
        printf("\n");
    }
    else {
        printf("SymLoadModule64(%p) succeeded: 0x%p\n", hProcess, (PVOID)loaded);
    }

    CHAR szModName[512];

    printf("Modules:\n");
// The first parameter of PSYM_ENUMMODULES_CALLBACK64 changed from PSTR to PCSTR
// between Windows 2003 and Windows 7. Cast here to work with either.
    pfSymEnumerateModules64(hProcess, (PSYM_ENUMMODULES_CALLBACK64)SymEnumerateCallback, NULL);
    printf("\n");

    IMAGEHLP_MODULE64 modinfo;
    ZeroMemory(&modinfo, sizeof(modinfo));
    modinfo.SizeOfStruct = 512/*sizeof(modinfo)*/;
    if (!pfSymGetModuleInfo64(hProcess, (DWORD64)hModule, &modinfo)) {
        printf("SymGetModuleInfo64(%p, %p) [64] failed: %ld\n",
                      hProcess, hModule, GetLastError());
    }
    else {
        printf("SymGetModuleInfo64(%p, %p) [64] succeeded: %ld\n",
                      hProcess, hModule, GetLastError());
        StringCchCopyA(szModName, ARRAYSIZE(szModName), modinfo.ModuleName);
        StringCchCatA(szModName, ARRAYSIZE(szModName), "!");

        printf("NumSyms:         %ld\n", modinfo.NumSyms);
        printf("SymType:         %d\n", modinfo.SymType);
        printf("ModuleName:      %s\n", modinfo.ModuleName);
        printf("ImageName:       %s\n", modinfo.ImageName);
        printf("LoadedImageName: %s\n", modinfo.LoadedImageName);
    }

    printf("\n");
    fflush(stdout);

    printf("DLLs:\n");
    for (hModule = NULL; (hModule = DetourEnumerateModules(hModule)) != NULL;) {
        CHAR szName[MAX_PATH];
        GetModuleFileNameA(hModule, szName, sizeof(szName));
        printf("  %p: %s\n", hModule, szName);
    }

    if (pfSymEnumSymbols == NULL) {
        printf("Couldn't find SymEnumSymbols.\n");
    }
    else {
        printf("===Enum===\n");
        SetLastError(0);
        nSymbolCount = 0;
        if (!pfSymEnumSymbols(hProcess, (DWORD64)hModule, NULL, SymEnumerateSymbols, NULL)) {
            printf("SymEnumSymbols() failed: %ld\n",
                          GetLastError());
        }
    }

    // Look for specific symbols.
    struct CFullSymbol : SYMBOL_INFO {
        CHAR szRestOfName[MAX_SYM_NAME];
    } symbol;
    CHAR szFullName[512];

    // Look for Target
    StringCchCopyA(szFullName, ARRAYSIZE(szFullName), szModName);
    StringCchCatA(szFullName, ARRAYSIZE(szFullName), "Target");
    printf("Symbol: [%s]\n", szFullName);

    ZeroMemory(&symbol, sizeof(symbol));
    symbol.SizeOfStruct = sizeof(SYMBOL_INFO);
#ifdef DBHLPAPI
    symbol.MaxNameLen = MAX_SYM_NAME;
#else
    symbol.MaxNameLength = MAX_SYM_NAME;
#endif

    SetLastError(0);
    if (!pfSymFromName(hProcess, szFullName, &symbol)) {
        printf("--SymFromName(%s) failed: %ld\n", szFullName, GetLastError());
    }
    if (symbol.Address != 0) {
        printf("--SymFromName(%s) succeeded\n", szFullName);
    }

    printf("%s => %p\n\n", szFullName, (PBYTE)symbol.Address);

    // Look for Hidden
    StringCchCopyA(szFullName, ARRAYSIZE(szFullName), szModName);
    StringCchCatA(szFullName, ARRAYSIZE(szFullName), "Hidden");
    printf("Symbol: [%s]\n", szFullName);

    ZeroMemory(&symbol, sizeof(symbol));
    symbol.SizeOfStruct = sizeof(SYMBOL_INFO);
#ifdef DBHLPAPI
    symbol.MaxNameLen = MAX_SYM_NAME;
#else
    symbol.MaxNameLength = MAX_SYM_NAME;
#endif

    SetLastError(0);
    if (!pfSymFromName(hProcess, szFullName, &symbol)) {
        printf("--SymFromName(%s) failed: %ld\n", szFullName, GetLastError());
    }
    if (symbol.Address != 0) {
        printf("--SymFromName(%s) succeeded\n", szFullName);
    }

    printf("%s => %p\n\n", szFullName, (PBYTE)symbol.Address);
#endif

    // We call Target once to insure it is loaded.
    Target(0);
    return 0;
}
//
///////////////////////////////////////////////////////////////// End of File.