summaryrefslogtreecommitdiffstats
path: root/src/lib/kStuff/kDbg/kDbgModWinDbgHelp.cpp
blob: 3c3077385844734cd682d1e860d72c74e7212df3 (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
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
/* $Id: kDbgModWinDbgHelp.cpp 29 2009-07-01 20:30:29Z bird $ */
/** @file
 * kDbg - The Debug Info Reader, DbgHelp Based Reader.
 */

/*
 * Copyright (c) 2006-2007 Knut St. Osmundsen <bird-kStuff-spamix@anduin.net>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <Windows.h>
#define _IMAGEHLP64
#include <DbgHelp.h>

#include "kDbgInternal.h"
#include <k/kHlpAlloc.h>
#include <k/kHlpString.h>


/*******************************************************************************
*   Global Variables                                                           *
*******************************************************************************/
/** The dbghelp.dll module handle. */
static HMODULE g_hDbgHelp = NULL;
/** Pointer to the dbhelp.dll SymInitialize function. */
static BOOL (WINAPI *g_pfnSymInitialize)(IN HANDLE,IN LPSTR,IN BOOL);
/** Pointer to the dbhelp.dll SymCleanup function. */
static BOOL (WINAPI *g_pfnSymCleanup)(IN HANDLE);
/** Pointer to the dbhelp.dll SymSetOptions function. */
static DWORD (WINAPI *g_pfnSymSetOptions)(IN DWORD);
/** Pointer to the dbhelp.dll SymLoadModule64 function. */
static DWORD64 (WINAPI *g_pfnSymLoadModule64)(IN HANDLE, IN HANDLE, IN PCSTR, IN PCSTR ModuleName, IN DWORD64, IN DWORD);
/** Pointer to the dbhelp.dll SymFromAddr function. */
static DWORD (WINAPI *g_pfnSymFromAddr)(IN HANDLE, IN DWORD64, OUT PDWORD64, OUT PSYMBOL_INFO);
/** Pointer to the dbhelp.dll SymGetLineFromAddr64 function. */
static DWORD (WINAPI *g_pfnSymGetLineFromAddr64)(IN HANDLE, IN DWORD64, OUT PDWORD64, OUT PIMAGEHLP_LINE64);



/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/**
 * A dbghelp based PE debug reader.
 */
typedef struct KDBGMODDBGHELP
{
    /** The common module core. */
    KDBGMOD     Core;
    /** The image base. */
    DWORD64     ImageBase;
    /** The "process" handle we present dbghelp. */
    HANDLE      hSymInst;
    /** The image size. */
    KU32        cbImage;
    /** The number of sections. (We've added the implicit header section.) */
    KI32        cSections;
    /** The section headers (variable size). The first section is the
     * implicit header section.*/
    IMAGE_SECTION_HEADER    aSections[1];
} KDBGMODDBGHELP, *PKDBGMODDBGHELP;


/**
 * Convers a Windows error to kDbg error code.
 *
 * @returns kDbg status code.
 * @param   rc          The Windows error.
 */
static int kdbgModDHConvWinError(DWORD rc)
{
    switch (rc)
    {
        case 0:                     return 0;
        default:                    return KERR_GENERAL_FAILURE;
    }
}


/**
 * Calcs the RVA for a segment:offset address.
 *
 * @returns IPRT status code.
 *
 * @param   pModDH      The PE debug module instance.
 * @param   iSegment    The segment number. Special segments are dealt with as well.
 * @param   off         The segment offset.
 * @param   puRVA       Where to store the RVA on success.
 */
static int kdbgModDHSegOffToRVA(PKDBGMODDBGHELP pModDH, KI32 iSegment, KDBGADDR off, KU32 *puRVA)
{
    if (iSegment >= 0)
    {
        kDbgAssertMsgReturn(iSegment < pModDH->cSections, ("iSegment=%x cSections=%x\n", iSegment, pModDH->cSections),
                            KDBG_ERR_INVALID_ADDRESS);
        kDbgAssertMsgReturn(off < pModDH->aSections[iSegment].Misc.VirtualSize,
                            ("off=" PRI_KDBGADDR " VirtualSize=%x\n", off, pModDH->aSections[iSegment].Misc.VirtualSize),
                            KDBG_ERR_INVALID_ADDRESS);
        *puRVA = pModDH->aSections[iSegment].VirtualAddress + (KU32)off;
        return 0;
    }

    if (iSegment == KDBGSEG_RVA)
    {
        kDbgAssertMsgReturn(off < pModDH->cbImage, ("off=" PRI_KDBGADDR ", cbImage=%x\n", off, pModDH->cbImage),
                            KDBG_ERR_INVALID_ADDRESS);
        *puRVA = (KU32)off;
        return 0;
    }
    kDbgAssertMsgFailedReturn(("iSegment=%d\n", iSegment), KDBG_ERR_INVALID_ADDRESS);
}


/**
 * Calcs the segment:offset address for a RVA.
 *
 * @returns IPRT status code.
 *
 * @param   pModDH      The PE debug module instance.
 * @param   uRVA        The RVA.
 * @param   piSegment   Where to store the segment number.
 * @param   poff        Where to store the segment offset.
 */
static int kdbgModDHRVAToSegOff(PKDBGMODDBGHELP pModDH, KU32 uRVA, KI32 *piSegment, KDBGADDR *poff)
{
    kDbgAssertMsgReturn(uRVA < pModDH->cbImage, ("uRVA=%x, cbImage=%x\n", uRVA, pModDH->cbImage),
                        KDBG_ERR_INVALID_ADDRESS);
    for (KI32 iSegment = 0; iSegment < pModDH->cSections; iSegment++)
    {
        /** @todo should probably be less strict about address in the alignment gaps. */
        KU32 off = uRVA - pModDH->aSections[iSegment].VirtualAddress;
        if (off < pModDH->aSections[iSegment].Misc.VirtualSize)
        {
            *poff = off;
            *piSegment = iSegment;
            return 0;
        }
    }
    kDbgAssertMsgFailedReturn(("uRVA=%x\n", uRVA), KDBG_ERR_INVALID_ADDRESS);
}


/**
 * @copydoc KDBGMODOPS::pfnQueryLine
 */
static int kdbgModDHQueryLine(PKDBGMOD pMod, KI32 iSegment, KDBGADDR off, PKDBGLINE pLine)
{
    PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)pMod;

    /*
     * Translate the address to an RVA.
     */
    KU32 uRVA;
    int rc = kdbgModDHSegOffToRVA(pModDH, iSegment, off, &uRVA);
    if (!rc)
    {
        DWORD64 off;
        IMAGEHLP_LINE64 Line;
        Line.SizeOfStruct = sizeof(Line);
        if (g_pfnSymGetLineFromAddr64(pModDH->hSymInst, pModDH->ImageBase + uRVA, &off, &Line))
        {
            pLine->RVA = (KDBGADDR)(Line.Address - pModDH->ImageBase);
            rc = kdbgModDHRVAToSegOff(pModDH, (KU32)pLine->RVA, &pLine->iSegment, &pLine->offSegment);
            pLine->iLine = Line.LineNumber;
            KSIZE cchFile = kHlpStrLen(Line.FileName);
            pLine->cchFile = cchFile < sizeof(pLine->szFile)
                           ? (KU16)cchFile
                           : (KU16)sizeof(pLine->szFile) - 1;
            kHlpMemCopy(pLine->szFile, Line.FileName, pLine->cchFile);
            pLine->szFile[pLine->cchFile] = '\0';
        }
        else
        {
            DWORD Err = GetLastError();
            rc = kdbgModDHConvWinError(Err);
        }
    }
    return rc;
}


/**
 * @copydoc KDBGMODOPS::pfnQuerySymbol
 */
static int kdbgModDHQuerySymbol(PKDBGMOD pMod, KI32 iSegment, KDBGADDR off, PKDBGSYMBOL pSym)
{
    PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)pMod;

    /*
     * Translate the address to an RVA.
     */
    KU32 uRVA;
    int rc = kdbgModDHSegOffToRVA(pModDH, iSegment, off, &uRVA);
    if (!rc)
    {
        DWORD64 off;
        union
        {
            SYMBOL_INFO Sym;
            char        achBuffer[sizeof(SYMBOL_INFO) + KDBG_SYMBOL_MAX];
        } Buf;
        Buf.Sym.SizeOfStruct = sizeof(SYMBOL_INFO);
        Buf.Sym.MaxNameLen = KDBG_SYMBOL_MAX;
        if (g_pfnSymFromAddr(pModDH->hSymInst, pModDH->ImageBase + uRVA, &off, &Buf.Sym))
        {
            pSym->cb      = Buf.Sym.Size;
            pSym->Address = NIL_KDBGADDR;
            pSym->fFlags  = 0;
            if (Buf.Sym.Flags & SYMFLAG_FUNCTION)
                pSym->fFlags |= KDBGSYM_FLAGS_CODE;
            else if (Buf.Sym.Flags & SYMFLAG_CONSTANT)
                pSym->fFlags |= KDBGSYM_FLAGS_ABS; /** @todo SYMFLAG_CONSTANT must be tested - documentation is too brief to say what is really meant here.*/
            else
                pSym->fFlags |= KDBGSYM_FLAGS_DATA;
            if (Buf.Sym.Flags & SYMFLAG_EXPORT)
                pSym->fFlags |= KDBGSYM_FLAGS_EXPORTED;
            if ((Buf.Sym.Flags & (SYMFLAG_VALUEPRESENT | SYMFLAG_CONSTANT)) == (SYMFLAG_VALUEPRESENT | SYMFLAG_CONSTANT))
            {
                pSym->iSegment   = KDBGSEG_ABS;
                pSym->offSegment = (KDBGADDR)Buf.Sym.Value;
                pSym->RVA        = (KDBGADDR)Buf.Sym.Value;
            }
            else
            {
                pSym->RVA        = (KDBGADDR)(Buf.Sym.Address - pModDH->ImageBase);
                rc = kdbgModDHRVAToSegOff(pModDH, (KU32)pSym->RVA, &pSym->iSegment, &pSym->offSegment);
            }
            pSym->cchName = (KU16)Buf.Sym.NameLen;
            if (pSym->cchName >= sizeof(pSym->szName))
                pSym->cchName = sizeof(pSym->szName) - 1;
            kHlpMemCopy(pSym->szName, Buf.Sym.Name, Buf.Sym.NameLen);
            pSym->szName[Buf.Sym.NameLen] = '\0';
        }
        else
        {
            DWORD Err = GetLastError();
            rc = kdbgModDHConvWinError(Err);
        }
    }
    return rc;
}


/**
 * @copydoc KDBGMODOPS::pfnClose
 */
static int kdbgModDHClose(PKDBGMOD pMod)
{
    PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)pMod;

    if (g_pfnSymCleanup(pModDH->hSymInst))
        return 0;

    DWORD Err = GetLastError();
    int rc = kdbgModDHConvWinError(Err);
    kDbgAssertMsgFailed(("SymInitialize failed: Err=%d rc=%d\n", Err, rc));
    return rc;
}


/**
 * Checks if the specified dbghelp.dll is usable.
 *
 * @returns IPRT status code.
 *
 * @param   pszPath     the path to the dbghelp.dll.
 */
static int kdbgModDHTryDbgHelp(const char *pszPath, KU32 *pu32FileVersionMS, KU32 *pu32FileVersionLS)
{
    int rc;
    DWORD dwHandle = 0;
    DWORD cb = GetFileVersionInfoSize(pszPath, &dwHandle);
    if (cb > 0)
    {
        void *pvBuf = alloca(cb);
        if (GetFileVersionInfo(pszPath, dwHandle, cb, pvBuf))
        {
            UINT cbValue = 0;
            VS_FIXEDFILEINFO *pFileInfo;
            if (VerQueryValue(pvBuf, "\\", (void **)&pFileInfo, &cbValue))
            {
                /** @todo somehow reject 64-bit .dlls when in 32-bit mode... dwFileOS is completely useless. */
                if (    *pu32FileVersionMS < pFileInfo->dwFileVersionMS
                    ||  (   *pu32FileVersionMS == pFileInfo->dwFileVersionMS
                         && *pu32FileVersionLS  > pFileInfo->dwFileVersionLS))
                {
                    *pu32FileVersionMS = pFileInfo->dwFileVersionMS;
                    *pu32FileVersionLS = pFileInfo->dwFileVersionLS;
                }
                if (pFileInfo->dwFileVersionMS >= 0x60004)
                    rc = 0;
                else
                    rc = KDBG_ERR_DBGHLP_VERSION_MISMATCH;
            }
            else
                rc = KERR_GENERAL_FAILURE;
        }
        else
            rc = kdbgModDHConvWinError(GetLastError());
    }
    else
        rc = kdbgModDHConvWinError(GetLastError());
    return rc;
}


/**
 * Find the dbghelp.dll
 */
static int kdbgModDHFindDbgHelp(char *pszPath, KSIZE cchPath)
{
    /*
     * Try the current directory.
     */
    KU32 FileVersionMS = 0;
    KU32 FileVersionLS = 0;
    int rc = KERR_GENERAL_FAILURE;
    static char s_szDbgHelp[] = "\\dbghelp.dll";
    if (GetCurrentDirectory((DWORD)(cchPath - sizeof(s_szDbgHelp) + 1), pszPath))
    {
        strcat(pszPath, s_szDbgHelp);
        int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
        if (!rc2)
            return rc2;
        if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
            rc = rc2;
    }

    /*
     * Try the application directory.
     */
    if (GetModuleFileName(NULL, pszPath, (DWORD)(cchPath - sizeof(s_szDbgHelp) + 1)))
    {
        kHlpStrCat(kHlpStrRChr(pszPath, '\\'), s_szDbgHelp);
        int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
        if (!rc)
            return rc2;
        if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
            rc = rc2;
    }

    /*
     * Try the windows directory.
     */
    if (GetSystemDirectory(pszPath, (DWORD)(cchPath - sizeof(s_szDbgHelp) + 1)))
    {
        kHlpStrCat(pszPath, s_szDbgHelp);
        int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
        if (!rc2)
            return rc2;
        if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
            rc = rc2;
    }

    /*
     * Try the windows directory.
     */
    if (GetWindowsDirectory(pszPath, (DWORD)(cchPath - sizeof(s_szDbgHelp) + 1)))
    {
        kHlpStrCat(pszPath, s_szDbgHelp);
        int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
        if (!rc2)
            return rc2;
        if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
            rc = rc2;
    }

    /*
     * Try the path.
     */
    /** @todo find the actual path specs, I'm probably not doing this 100% correctly here. */
    DWORD cb = GetEnvironmentVariable("PATH", NULL, 0) + 64;
    char *pszSearchPath = (char *) alloca(cb);
    if (GetEnvironmentVariable("PATH", pszSearchPath, cb) < cb)
    {
        char *psz = pszSearchPath;
        while (*psz)
        {
            /* find the end of the path. */
            char *pszEnd = kHlpStrChr(psz, ';');
            if (!pszEnd)
                pszEnd = kHlpStrChr(psz, '\0');
            if (pszEnd != psz)
            {
                /* construct filename and try it out */
                kHlpMemCopy(pszPath, psz, pszEnd - psz);
                kHlpMemCopy(&pszPath[pszEnd - psz], s_szDbgHelp, sizeof(s_szDbgHelp));
                int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
                if (!rc2)
                    return rc2;
                if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
                    rc = rc2;
            }

            /* next path */
            if (!*pszEnd)
                break;
            psz = pszEnd + 1;
        }
    }

    if (rc == KDBG_ERR_DBGHLP_VERSION_MISMATCH)
        kDbgAssertMsgFailed(("dbghelp.dll found, but it was ancient! The highest file version found was 0x%08x'%08x.\n"
                             "This program require a file version of at least 0x00060004'00000000. Please download\n"
                             "the latest windbg and use the dbghelp.dll from that package. Just put it somewhere in\n"
                             "the PATH and we'll find it.\n", FileVersionMS, FileVersionLS));
    else
        kDbgAssertMsgFailed(("dbghelp.dll was not found! Download the latest windbg and use the dbghelp.dll\n"
                             "from that package - just put it somewhere in the PATH and we'll find it.\n"));
    return rc;
}


/**
 * Loads the dbghelp.dll, check that it's the right version, and
 * resolves all the symbols we need.
 *
 * @returns IPRT status code.
 */
static int kdbgModDHLoadDbgHelp(void)
{
    if (g_hDbgHelp)
        return 0;

    /* primitive locking - make some useful API for this kind of spinning! */
    static volatile long s_lLock = 0;
    while (InterlockedCompareExchange(&s_lLock, 1, 0))
        while (s_lLock)
            Sleep(1);
    if (g_hDbgHelp)
    {
        InterlockedExchange(&s_lLock, 0);
        return 0;
    }

    /*
     * Load it - try current dir first.
     */
    char szPath[260];
    int rc = kdbgModDHFindDbgHelp(szPath, sizeof(szPath));
    if (rc)
    {
        InterlockedExchange(&s_lLock, 0);
        return rc;
    }

    HMODULE hmod = LoadLibraryEx(szPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
    if (!hmod)
    {
        DWORD Err = GetLastError();
        int rc = kdbgModDHConvWinError(Err);
        InterlockedExchange(&s_lLock, 0);
        kDbgAssertMsgFailedReturn(("Failed to load '%s', Err=%d rc=%d\n", szPath, Err, rc), rc);
    }

    /*
     * Check the API version (too).
     */
    LPAPI_VERSION (WINAPI *pfnImagehlpApiVersion)(VOID);
    FARPROC *ppfn = (FARPROC *)&pfnImagehlpApiVersion;
    *ppfn = GetProcAddress(hmod, "ImagehlpApiVersion");
    if (*ppfn)
    {
        LPAPI_VERSION pVersion = pfnImagehlpApiVersion();
        if (    pVersion
            &&  (   pVersion->MajorVersion > 4
                 || (pVersion->MajorVersion == 4 && pVersion->MinorVersion > 0)
                 || (pVersion->MajorVersion == 4 && pVersion->MinorVersion == 0 && pVersion->Revision >= 5)
                )
           )
        {
            /*
             * Resolve the entrypoints we need.
             */
            static const struct
            {
                const char *pszName;
                FARPROC *ppfn;
            }   s_aFunctions[] =
            {
                { "SymInitialize",      (FARPROC *)&g_pfnSymInitialize },
                { "SymCleanup",         (FARPROC *)&g_pfnSymCleanup },
                { "SymSetOptions",      (FARPROC *)&g_pfnSymSetOptions },
                { "SymLoadModule64",    (FARPROC *)&g_pfnSymLoadModule64 },
                { "SymFromAddr",        (FARPROC *)&g_pfnSymFromAddr },
                { "SymFromAddr",        (FARPROC *)&g_pfnSymFromAddr },
                { "SymGetLineFromAddr64", (FARPROC *)&g_pfnSymGetLineFromAddr64 },
            };
            for (unsigned i = 0; i < K_ELEMENTS(s_aFunctions); i++)
            {
                FARPROC pfn = GetProcAddress(hmod, s_aFunctions[i].pszName);
                if (!pfn)
                {
                    DWORD Err = GetLastError();
                    rc = kdbgModDHConvWinError(Err);
                    kDbgAssertMsgFailed(("Failed to resolve %s in dbghelp, Err=%d rc=%d\n",
                                         s_aFunctions[i].pszName, Err, rc));
                    break;
                }
                *s_aFunctions[i].ppfn = pfn;
            }
            if (!rc)
            {
                g_hDbgHelp = hmod;
                Sleep(1);
                InterlockedExchange(&s_lLock, 0);
                return 0;
            }
        }
        else
        {
            rc = KDBG_ERR_DBGHLP_VERSION_MISMATCH;
            kDbgAssertMsgFailed(("ImagehlpApiVersion -> %p and MajorVersion=%d.\n", pVersion, pVersion ? pVersion->MajorVersion : 0));
        }
    }
    else
    {
        DWORD Err = GetLastError();
        rc = kdbgModDHConvWinError(Err);
        kDbgAssertMsgFailed(("Failed to resolve ImagehlpApiVersionEx in dbghelp, Err=%d rc=%d\n", Err, rc));
    }
    FreeLibrary(hmod);
    InterlockedExchange(&s_lLock, 0);
    return rc;
}


/**
 * @copydoc KDBGMODOPS::pfnOpen
 */
static int kdbgModDHOpen(PKDBGMOD *ppMod, PKRDR pRdr, KBOOL fCloseRdr, KFOFF off, KFOFF cb, struct KLDRMOD *pLdrMod)
{
    /*
     * This reader doesn't support partial files.
     * Also weed out small files early on as they cannot be
     * PE images and will only cause read errors
     */
    if (    off != 0
        ||  cb != KFOFF_MAX)
        return KDBG_ERR_UNKOWN_FORMAT;
    if (kRdrSize(pRdr) < sizeof(IMAGE_NT_HEADERS32) + sizeof(IMAGE_SECTION_HEADER))
        return KDBG_ERR_UNKOWN_FORMAT;

    /*
     * We need to read the section headers and get the image size.
     */
    /* Find the PE header magic. */
    KU32 offHdr = 0;
    KU32 u32Magic;
    int rc = kRdrRead(pRdr, &u32Magic, sizeof(u32Magic), 0);
    kDbgAssertRCReturn(rc, rc);
    if ((KU16)u32Magic == IMAGE_DOS_SIGNATURE)
    {
        rc = kRdrRead(pRdr, &offHdr, sizeof(offHdr), K_OFFSETOF(IMAGE_DOS_HEADER, e_lfanew));
        kDbgAssertRCReturn(rc, rc);
        if (!offHdr)
            return KDBG_ERR_FORMAT_NOT_SUPPORTED;
        if (    offHdr < sizeof(IMAGE_DOS_SIGNATURE)
            ||  offHdr >= kRdrSize(pRdr) - 4)
            return KDBG_ERR_BAD_EXE_FORMAT;

        rc = kRdrRead(pRdr, &u32Magic, sizeof(u32Magic), offHdr);
        kDbgAssertRCReturn(rc, rc);
    }
    if (u32Magic != IMAGE_NT_SIGNATURE)
        return KDBG_ERR_FORMAT_NOT_SUPPORTED;

    /* read the file header and the image size in the optional header.. */
    IMAGE_FILE_HEADER FHdr;
    rc = kRdrRead(pRdr, &FHdr, sizeof(FHdr), offHdr + K_OFFSETOF(IMAGE_NT_HEADERS32, FileHeader));
    kDbgAssertRCReturn(rc, rc);

    KU32 cbImage;
    if (FHdr.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32))
        rc = kRdrRead(pRdr, &cbImage, sizeof(cbImage),
                      offHdr + K_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader.SizeOfImage));
    else if (FHdr.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER64))
        rc = kRdrRead(pRdr, &cbImage, sizeof(cbImage),
                      offHdr + K_OFFSETOF(IMAGE_NT_HEADERS64, OptionalHeader.SizeOfImage));
    else
        kDbgAssertFailedReturn(KDBG_ERR_BAD_EXE_FORMAT);
    kDbgAssertRCReturn(rc, rc);

    /*
     * Load dbghelp.dll.
     */
    rc = kdbgModDHLoadDbgHelp();
    if (rc)
        return rc;

    /*
     * Allocate the module and read/construct the section headers.
     */
    PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)kHlpAlloc(K_OFFSETOF(KDBGMODDBGHELP, aSections[FHdr.NumberOfSections + 2]));
    kDbgAssertReturn(pModDH, KERR_NO_MEMORY);
    pModDH->Core.u32Magic   = KDBGMOD_MAGIC;
    pModDH->Core.pOps       = &g_kDbgModWinDbgHelpOpen;
    pModDH->Core.pRdr       = pRdr;
    pModDH->Core.fCloseRdr  = fCloseRdr;
    pModDH->Core.pLdrMod    = pLdrMod;
    pModDH->cbImage         = cbImage;
    pModDH->cSections       = 1 + FHdr.NumberOfSections;

    rc = kRdrRead(pRdr, &pModDH->aSections[1], sizeof(pModDH->aSections[0]) * FHdr.NumberOfSections,
                  offHdr + K_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader) + FHdr.SizeOfOptionalHeader);
    if (!rc)
    {
        PIMAGE_SECTION_HEADER pSH = &pModDH->aSections[0];
        kHlpMemCopy(pSH->Name, "headers", sizeof(pSH->Name));
        pSH->Misc.VirtualSize       = pModDH->aSections[1].VirtualAddress;
        pSH->VirtualAddress         = 0;
        pSH->SizeOfRawData          = pSH->Misc.VirtualSize;
        pSH->PointerToRawData       = 0;
        pSH->PointerToRelocations   = 0;
        pSH->PointerToLinenumbers   = 0;
        pSH->NumberOfRelocations    = 0;
        pSH->NumberOfLinenumbers    = 0;
        pSH->Characteristics        = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_MEM_READ;

        KU32 uTheEnd = pModDH->aSections[FHdr.NumberOfSections].VirtualAddress
                     + pModDH->aSections[FHdr.NumberOfSections].Misc.VirtualSize;
        if (uTheEnd < cbImage)
        {
            pSH = &pModDH->aSections[pModDH->cSections++];
            kHlpMemCopy(pSH->Name, "tail\0\0\0", sizeof(pSH->Name));
            pSH->Misc.VirtualSize       = cbImage - uTheEnd;
            pSH->VirtualAddress         = uTheEnd;
            pSH->SizeOfRawData          = pSH->Misc.VirtualSize;
            pSH->PointerToRawData       = 0;
            pSH->PointerToRelocations   = 0;
            pSH->PointerToLinenumbers   = 0;
            pSH->NumberOfRelocations    = 0;
            pSH->NumberOfLinenumbers    = 0;
            pSH->Characteristics        = IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES | IMAGE_SCN_MEM_READ;
        }

        /*
         * Find a new dbghelp handle.
         *
         * We assume 4GB of handles outlast most debugging sessions, or in anyways that
         * when we start reusing handles they are no longer in use. :-)
         */
        static volatile long s_u32LastHandle = 1;
        HANDLE hSymInst = (HANDLE)InterlockedIncrement(&s_u32LastHandle);
        while (     hSymInst == INVALID_HANDLE_VALUE
               ||   hSymInst == (HANDLE)0
               ||   hSymInst == GetCurrentProcess())
            hSymInst = (HANDLE)InterlockedIncrement(&s_u32LastHandle);

        /*
         * Initialize dbghelp and try open the specified module.
         */
        if (g_pfnSymInitialize(hSymInst, NULL, FALSE))
        {
            g_pfnSymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_AUTO_PUBLICS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS);

            KIPTR NativeFH = kRdrNativeFH(pRdr);
            DWORD64 ImageBase = g_pfnSymLoadModule64(hSymInst, NativeFH == -1 ? NULL : (HANDLE)NativeFH,
                                                     kRdrName(pRdr), NULL, 0x00400000, 0);
            if (ImageBase)
            {
                pModDH->hSymInst        = hSymInst;
                pModDH->ImageBase       = ImageBase;
                *ppMod = &pModDH->Core;
                return rc;
            }

            DWORD Err = GetLastError();
            rc = kdbgModDHConvWinError(Err);
            kDbgAssertMsgFailed(("SymLoadModule64 failed: Err=%d rc=%d\n", Err, rc));
            g_pfnSymCleanup(hSymInst);
        }
        else
        {
            DWORD Err = GetLastError();
            rc = kdbgModDHConvWinError(Err);
            kDbgAssertMsgFailed(("SymInitialize failed: Err=%d rc=%d\n", Err, rc));
        }
    }
    else
        kDbgAssertRC(rc);

    kHlpFree(pModDH);
    return rc;
}


/**
 * Methods for a PE module.
 */
KDBGMODOPS const g_kDbgModWinDbgHelpOpen =
{
    "Windows DbgHelp",
    NULL,
    kdbgModDHOpen,
    kdbgModDHClose,
    kdbgModDHQuerySymbol,
    kdbgModDHQueryLine,
    "Windows DbgHelp"
};