VirtualBox

source: kStuff/trunk/kDbg/kDbgModWinDbgHelp.cpp@ 29

Last change on this file since 29 was 29, checked in by bird, 15 years ago

Finally got around execute the switch to the MIT license.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 25.3 KB
Line 
1/* $Id: kDbgModWinDbgHelp.cpp 29 2009-07-01 20:30:29Z bird $ */
2/** @file
3 * kDbg - The Debug Info Reader, DbgHelp Based Reader.
4 */
5
6/*
7 * Copyright (c) 2006-2007 Knut St. Osmundsen <[email protected]>
8 *
9 * Permission is hereby granted, free of charge, to any person
10 * obtaining a copy of this software and associated documentation
11 * files (the "Software"), to deal in the Software without
12 * restriction, including without limitation the rights to use,
13 * copy, modify, merge, publish, distribute, sublicense, and/or sell
14 * copies of the Software, and to permit persons to whom the
15 * Software is furnished to do so, subject to the following
16 * conditions:
17 *
18 * The above copyright notice and this permission notice shall be
19 * included in all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
23 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
25 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
26 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
28 * OTHER DEALINGS IN THE SOFTWARE.
29 */
30
31/*******************************************************************************
32* Header Files *
33*******************************************************************************/
34#include <Windows.h>
35#define _IMAGEHLP64
36#include <DbgHelp.h>
37
38#include "kDbgInternal.h"
39#include <k/kHlpAlloc.h>
40#include <k/kHlpString.h>
41
42
43/*******************************************************************************
44* Global Variables *
45*******************************************************************************/
46/** The dbghelp.dll module handle. */
47static HMODULE g_hDbgHelp = NULL;
48/** Pointer to the dbhelp.dll SymInitialize function. */
49static BOOL (WINAPI *g_pfnSymInitialize)(IN HANDLE,IN LPSTR,IN BOOL);
50/** Pointer to the dbhelp.dll SymCleanup function. */
51static BOOL (WINAPI *g_pfnSymCleanup)(IN HANDLE);
52/** Pointer to the dbhelp.dll SymSetOptions function. */
53static DWORD (WINAPI *g_pfnSymSetOptions)(IN DWORD);
54/** Pointer to the dbhelp.dll SymLoadModule64 function. */
55static DWORD64 (WINAPI *g_pfnSymLoadModule64)(IN HANDLE, IN HANDLE, IN PCSTR, IN PCSTR ModuleName, IN DWORD64, IN DWORD);
56/** Pointer to the dbhelp.dll SymFromAddr function. */
57static DWORD (WINAPI *g_pfnSymFromAddr)(IN HANDLE, IN DWORD64, OUT PDWORD64, OUT PSYMBOL_INFO);
58/** Pointer to the dbhelp.dll SymGetLineFromAddr64 function. */
59static DWORD (WINAPI *g_pfnSymGetLineFromAddr64)(IN HANDLE, IN DWORD64, OUT PDWORD64, OUT PIMAGEHLP_LINE64);
60
61
62
63/*******************************************************************************
64* Structures and Typedefs *
65*******************************************************************************/
66/**
67 * A dbghelp based PE debug reader.
68 */
69typedef struct KDBGMODDBGHELP
70{
71 /** The common module core. */
72 KDBGMOD Core;
73 /** The image base. */
74 DWORD64 ImageBase;
75 /** The "process" handle we present dbghelp. */
76 HANDLE hSymInst;
77 /** The image size. */
78 KU32 cbImage;
79 /** The number of sections. (We've added the implicit header section.) */
80 KI32 cSections;
81 /** The section headers (variable size). The first section is the
82 * implicit header section.*/
83 IMAGE_SECTION_HEADER aSections[1];
84} KDBGMODDBGHELP, *PKDBGMODDBGHELP;
85
86
87/**
88 * Convers a Windows error to kDbg error code.
89 *
90 * @returns kDbg status code.
91 * @param rc The Windows error.
92 */
93static int kdbgModDHConvWinError(DWORD rc)
94{
95 switch (rc)
96 {
97 case 0: return 0;
98 default: return KERR_GENERAL_FAILURE;
99 }
100}
101
102
103/**
104 * Calcs the RVA for a segment:offset address.
105 *
106 * @returns IPRT status code.
107 *
108 * @param pModDH The PE debug module instance.
109 * @param iSegment The segment number. Special segments are dealt with as well.
110 * @param off The segment offset.
111 * @param puRVA Where to store the RVA on success.
112 */
113static int kdbgModDHSegOffToRVA(PKDBGMODDBGHELP pModDH, KI32 iSegment, KDBGADDR off, KU32 *puRVA)
114{
115 if (iSegment >= 0)
116 {
117 kDbgAssertMsgReturn(iSegment < pModDH->cSections, ("iSegment=%x cSections=%x\n", iSegment, pModDH->cSections),
118 KDBG_ERR_INVALID_ADDRESS);
119 kDbgAssertMsgReturn(off < pModDH->aSections[iSegment].Misc.VirtualSize,
120 ("off=" PRI_KDBGADDR " VirtualSize=%x\n", off, pModDH->aSections[iSegment].Misc.VirtualSize),
121 KDBG_ERR_INVALID_ADDRESS);
122 *puRVA = pModDH->aSections[iSegment].VirtualAddress + (KU32)off;
123 return 0;
124 }
125
126 if (iSegment == KDBGSEG_RVA)
127 {
128 kDbgAssertMsgReturn(off < pModDH->cbImage, ("off=" PRI_KDBGADDR ", cbImage=%x\n", off, pModDH->cbImage),
129 KDBG_ERR_INVALID_ADDRESS);
130 *puRVA = (KU32)off;
131 return 0;
132 }
133 kDbgAssertMsgFailedReturn(("iSegment=%d\n", iSegment), KDBG_ERR_INVALID_ADDRESS);
134}
135
136
137/**
138 * Calcs the segment:offset address for a RVA.
139 *
140 * @returns IPRT status code.
141 *
142 * @param pModDH The PE debug module instance.
143 * @param uRVA The RVA.
144 * @param piSegment Where to store the segment number.
145 * @param poff Where to store the segment offset.
146 */
147static int kdbgModDHRVAToSegOff(PKDBGMODDBGHELP pModDH, KU32 uRVA, KI32 *piSegment, KDBGADDR *poff)
148{
149 kDbgAssertMsgReturn(uRVA < pModDH->cbImage, ("uRVA=%x, cbImage=%x\n", uRVA, pModDH->cbImage),
150 KDBG_ERR_INVALID_ADDRESS);
151 for (KI32 iSegment = 0; iSegment < pModDH->cSections; iSegment++)
152 {
153 /** @todo should probably be less strict about address in the alignment gaps. */
154 KU32 off = uRVA - pModDH->aSections[iSegment].VirtualAddress;
155 if (off < pModDH->aSections[iSegment].Misc.VirtualSize)
156 {
157 *poff = off;
158 *piSegment = iSegment;
159 return 0;
160 }
161 }
162 kDbgAssertMsgFailedReturn(("uRVA=%x\n", uRVA), KDBG_ERR_INVALID_ADDRESS);
163}
164
165
166/**
167 * @copydoc KDBGMODOPS::pfnQueryLine
168 */
169static int kdbgModDHQueryLine(PKDBGMOD pMod, KI32 iSegment, KDBGADDR off, PKDBGLINE pLine)
170{
171 PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)pMod;
172
173 /*
174 * Translate the address to an RVA.
175 */
176 KU32 uRVA;
177 int rc = kdbgModDHSegOffToRVA(pModDH, iSegment, off, &uRVA);
178 if (!rc)
179 {
180 DWORD64 off;
181 IMAGEHLP_LINE64 Line;
182 Line.SizeOfStruct = sizeof(Line);
183 if (g_pfnSymGetLineFromAddr64(pModDH->hSymInst, pModDH->ImageBase + uRVA, &off, &Line))
184 {
185 pLine->RVA = (KDBGADDR)(Line.Address - pModDH->ImageBase);
186 rc = kdbgModDHRVAToSegOff(pModDH, (KU32)pLine->RVA, &pLine->iSegment, &pLine->offSegment);
187 pLine->iLine = Line.LineNumber;
188 KSIZE cchFile = kHlpStrLen(Line.FileName);
189 pLine->cchFile = cchFile < sizeof(pLine->szFile)
190 ? (KU16)cchFile
191 : (KU16)sizeof(pLine->szFile) - 1;
192 kHlpMemCopy(pLine->szFile, Line.FileName, pLine->cchFile);
193 pLine->szFile[pLine->cchFile] = '\0';
194 }
195 else
196 {
197 DWORD Err = GetLastError();
198 rc = kdbgModDHConvWinError(Err);
199 }
200 }
201 return rc;
202}
203
204
205/**
206 * @copydoc KDBGMODOPS::pfnQuerySymbol
207 */
208static int kdbgModDHQuerySymbol(PKDBGMOD pMod, KI32 iSegment, KDBGADDR off, PKDBGSYMBOL pSym)
209{
210 PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)pMod;
211
212 /*
213 * Translate the address to an RVA.
214 */
215 KU32 uRVA;
216 int rc = kdbgModDHSegOffToRVA(pModDH, iSegment, off, &uRVA);
217 if (!rc)
218 {
219 DWORD64 off;
220 union
221 {
222 SYMBOL_INFO Sym;
223 char achBuffer[sizeof(SYMBOL_INFO) + KDBG_SYMBOL_MAX];
224 } Buf;
225 Buf.Sym.SizeOfStruct = sizeof(SYMBOL_INFO);
226 Buf.Sym.MaxNameLen = KDBG_SYMBOL_MAX;
227 if (g_pfnSymFromAddr(pModDH->hSymInst, pModDH->ImageBase + uRVA, &off, &Buf.Sym))
228 {
229 pSym->cb = Buf.Sym.Size;
230 pSym->Address = NIL_KDBGADDR;
231 pSym->fFlags = 0;
232 if (Buf.Sym.Flags & SYMFLAG_FUNCTION)
233 pSym->fFlags |= KDBGSYM_FLAGS_CODE;
234 else if (Buf.Sym.Flags & SYMFLAG_CONSTANT)
235 pSym->fFlags |= KDBGSYM_FLAGS_ABS; /** @todo SYMFLAG_CONSTANT must be tested - documentation is too brief to say what is really meant here.*/
236 else
237 pSym->fFlags |= KDBGSYM_FLAGS_DATA;
238 if (Buf.Sym.Flags & SYMFLAG_EXPORT)
239 pSym->fFlags |= KDBGSYM_FLAGS_EXPORTED;
240 if ((Buf.Sym.Flags & (SYMFLAG_VALUEPRESENT | SYMFLAG_CONSTANT)) == (SYMFLAG_VALUEPRESENT | SYMFLAG_CONSTANT))
241 {
242 pSym->iSegment = KDBGSEG_ABS;
243 pSym->offSegment = (KDBGADDR)Buf.Sym.Value;
244 pSym->RVA = (KDBGADDR)Buf.Sym.Value;
245 }
246 else
247 {
248 pSym->RVA = (KDBGADDR)(Buf.Sym.Address - pModDH->ImageBase);
249 rc = kdbgModDHRVAToSegOff(pModDH, (KU32)pSym->RVA, &pSym->iSegment, &pSym->offSegment);
250 }
251 pSym->cchName = (KU16)Buf.Sym.NameLen;
252 if (pSym->cchName >= sizeof(pSym->szName))
253 pSym->cchName = sizeof(pSym->szName) - 1;
254 kHlpMemCopy(pSym->szName, Buf.Sym.Name, Buf.Sym.NameLen);
255 pSym->szName[Buf.Sym.NameLen] = '\0';
256 }
257 else
258 {
259 DWORD Err = GetLastError();
260 rc = kdbgModDHConvWinError(Err);
261 }
262 }
263 return rc;
264}
265
266
267/**
268 * @copydoc KDBGMODOPS::pfnClose
269 */
270static int kdbgModDHClose(PKDBGMOD pMod)
271{
272 PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)pMod;
273
274 if (g_pfnSymCleanup(pModDH->hSymInst))
275 return 0;
276
277 DWORD Err = GetLastError();
278 int rc = kdbgModDHConvWinError(Err);
279 kDbgAssertMsgFailed(("SymInitialize failed: Err=%d rc=%d\n", Err, rc));
280 return rc;
281}
282
283
284/**
285 * Checks if the specified dbghelp.dll is usable.
286 *
287 * @returns IPRT status code.
288 *
289 * @param pszPath the path to the dbghelp.dll.
290 */
291static int kdbgModDHTryDbgHelp(const char *pszPath, KU32 *pu32FileVersionMS, KU32 *pu32FileVersionLS)
292{
293 int rc;
294 DWORD dwHandle = 0;
295 DWORD cb = GetFileVersionInfoSize(pszPath, &dwHandle);
296 if (cb > 0)
297 {
298 void *pvBuf = alloca(cb);
299 if (GetFileVersionInfo(pszPath, dwHandle, cb, pvBuf))
300 {
301 UINT cbValue = 0;
302 VS_FIXEDFILEINFO *pFileInfo;
303 if (VerQueryValue(pvBuf, "\\", (void **)&pFileInfo, &cbValue))
304 {
305 /** @todo somehow reject 64-bit .dlls when in 32-bit mode... dwFileOS is completely useless. */
306 if ( *pu32FileVersionMS < pFileInfo->dwFileVersionMS
307 || ( *pu32FileVersionMS == pFileInfo->dwFileVersionMS
308 && *pu32FileVersionLS > pFileInfo->dwFileVersionLS))
309 {
310 *pu32FileVersionMS = pFileInfo->dwFileVersionMS;
311 *pu32FileVersionLS = pFileInfo->dwFileVersionLS;
312 }
313 if (pFileInfo->dwFileVersionMS >= 0x60004)
314 rc = 0;
315 else
316 rc = KDBG_ERR_DBGHLP_VERSION_MISMATCH;
317 }
318 else
319 rc = KERR_GENERAL_FAILURE;
320 }
321 else
322 rc = kdbgModDHConvWinError(GetLastError());
323 }
324 else
325 rc = kdbgModDHConvWinError(GetLastError());
326 return rc;
327}
328
329
330/**
331 * Find the dbghelp.dll
332 */
333static int kdbgModDHFindDbgHelp(char *pszPath, KSIZE cchPath)
334{
335 /*
336 * Try the current directory.
337 */
338 KU32 FileVersionMS = 0;
339 KU32 FileVersionLS = 0;
340 int rc = KERR_GENERAL_FAILURE;
341 static char s_szDbgHelp[] = "\\dbghelp.dll";
342 if (GetCurrentDirectory((DWORD)(cchPath - sizeof(s_szDbgHelp) + 1), pszPath))
343 {
344 strcat(pszPath, s_szDbgHelp);
345 int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
346 if (!rc2)
347 return rc2;
348 if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
349 rc = rc2;
350 }
351
352 /*
353 * Try the application directory.
354 */
355 if (GetModuleFileName(NULL, pszPath, (DWORD)(cchPath - sizeof(s_szDbgHelp) + 1)))
356 {
357 kHlpStrCat(kHlpStrRChr(pszPath, '\\'), s_szDbgHelp);
358 int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
359 if (!rc)
360 return rc2;
361 if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
362 rc = rc2;
363 }
364
365 /*
366 * Try the windows directory.
367 */
368 if (GetSystemDirectory(pszPath, (DWORD)(cchPath - sizeof(s_szDbgHelp) + 1)))
369 {
370 kHlpStrCat(pszPath, s_szDbgHelp);
371 int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
372 if (!rc2)
373 return rc2;
374 if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
375 rc = rc2;
376 }
377
378 /*
379 * Try the windows directory.
380 */
381 if (GetWindowsDirectory(pszPath, (DWORD)(cchPath - sizeof(s_szDbgHelp) + 1)))
382 {
383 kHlpStrCat(pszPath, s_szDbgHelp);
384 int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
385 if (!rc2)
386 return rc2;
387 if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
388 rc = rc2;
389 }
390
391 /*
392 * Try the path.
393 */
394 /** @todo find the actual path specs, I'm probably not doing this 100% correctly here. */
395 DWORD cb = GetEnvironmentVariable("PATH", NULL, 0) + 64;
396 char *pszSearchPath = (char *) alloca(cb);
397 if (GetEnvironmentVariable("PATH", pszSearchPath, cb) < cb)
398 {
399 char *psz = pszSearchPath;
400 while (*psz)
401 {
402 /* find the end of the path. */
403 char *pszEnd = kHlpStrChr(psz, ';');
404 if (!pszEnd)
405 pszEnd = kHlpStrChr(psz, '\0');
406 if (pszEnd != psz)
407 {
408 /* construct filename and try it out */
409 kHlpMemCopy(pszPath, psz, pszEnd - psz);
410 kHlpMemCopy(&pszPath[pszEnd - psz], s_szDbgHelp, sizeof(s_szDbgHelp));
411 int rc2 = kdbgModDHTryDbgHelp(pszPath, &FileVersionMS, &FileVersionLS);
412 if (!rc2)
413 return rc2;
414 if (rc != KDBG_ERR_DBGHLP_VERSION_MISMATCH)
415 rc = rc2;
416 }
417
418 /* next path */
419 if (!*pszEnd)
420 break;
421 psz = pszEnd + 1;
422 }
423 }
424
425 if (rc == KDBG_ERR_DBGHLP_VERSION_MISMATCH)
426 kDbgAssertMsgFailed(("dbghelp.dll found, but it was ancient! The highest file version found was 0x%08x'%08x.\n"
427 "This program require a file version of at least 0x00060004'00000000. Please download\n"
428 "the latest windbg and use the dbghelp.dll from that package. Just put it somewhere in\n"
429 "the PATH and we'll find it.\n", FileVersionMS, FileVersionLS));
430 else
431 kDbgAssertMsgFailed(("dbghelp.dll was not found! Download the latest windbg and use the dbghelp.dll\n"
432 "from that package - just put it somewhere in the PATH and we'll find it.\n"));
433 return rc;
434}
435
436
437/**
438 * Loads the dbghelp.dll, check that it's the right version, and
439 * resolves all the symbols we need.
440 *
441 * @returns IPRT status code.
442 */
443static int kdbgModDHLoadDbgHelp(void)
444{
445 if (g_hDbgHelp)
446 return 0;
447
448 /* primitive locking - make some useful API for this kind of spinning! */
449 static volatile long s_lLock = 0;
450 while (InterlockedCompareExchange(&s_lLock, 1, 0))
451 while (s_lLock)
452 Sleep(1);
453 if (g_hDbgHelp)
454 {
455 InterlockedExchange(&s_lLock, 0);
456 return 0;
457 }
458
459 /*
460 * Load it - try current dir first.
461 */
462 char szPath[260];
463 int rc = kdbgModDHFindDbgHelp(szPath, sizeof(szPath));
464 if (rc)
465 {
466 InterlockedExchange(&s_lLock, 0);
467 return rc;
468 }
469
470 HMODULE hmod = LoadLibraryEx(szPath, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
471 if (!hmod)
472 {
473 DWORD Err = GetLastError();
474 int rc = kdbgModDHConvWinError(Err);
475 InterlockedExchange(&s_lLock, 0);
476 kDbgAssertMsgFailedReturn(("Failed to load '%s', Err=%d rc=%d\n", szPath, Err, rc), rc);
477 }
478
479 /*
480 * Check the API version (too).
481 */
482 LPAPI_VERSION (WINAPI *pfnImagehlpApiVersion)(VOID);
483 FARPROC *ppfn = (FARPROC *)&pfnImagehlpApiVersion;
484 *ppfn = GetProcAddress(hmod, "ImagehlpApiVersion");
485 if (*ppfn)
486 {
487 LPAPI_VERSION pVersion = pfnImagehlpApiVersion();
488 if ( pVersion
489 && ( pVersion->MajorVersion > 4
490 || (pVersion->MajorVersion == 4 && pVersion->MinorVersion > 0)
491 || (pVersion->MajorVersion == 4 && pVersion->MinorVersion == 0 && pVersion->Revision >= 5)
492 )
493 )
494 {
495 /*
496 * Resolve the entrypoints we need.
497 */
498 static const struct
499 {
500 const char *pszName;
501 FARPROC *ppfn;
502 } s_aFunctions[] =
503 {
504 { "SymInitialize", (FARPROC *)&g_pfnSymInitialize },
505 { "SymCleanup", (FARPROC *)&g_pfnSymCleanup },
506 { "SymSetOptions", (FARPROC *)&g_pfnSymSetOptions },
507 { "SymLoadModule64", (FARPROC *)&g_pfnSymLoadModule64 },
508 { "SymFromAddr", (FARPROC *)&g_pfnSymFromAddr },
509 { "SymFromAddr", (FARPROC *)&g_pfnSymFromAddr },
510 { "SymGetLineFromAddr64", (FARPROC *)&g_pfnSymGetLineFromAddr64 },
511 };
512 for (unsigned i = 0; i < K_ELEMENTS(s_aFunctions); i++)
513 {
514 FARPROC pfn = GetProcAddress(hmod, s_aFunctions[i].pszName);
515 if (!pfn)
516 {
517 DWORD Err = GetLastError();
518 rc = kdbgModDHConvWinError(Err);
519 kDbgAssertMsgFailed(("Failed to resolve %s in dbghelp, Err=%d rc=%d\n",
520 s_aFunctions[i].pszName, Err, rc));
521 break;
522 }
523 *s_aFunctions[i].ppfn = pfn;
524 }
525 if (!rc)
526 {
527 g_hDbgHelp = hmod;
528 Sleep(1);
529 InterlockedExchange(&s_lLock, 0);
530 return 0;
531 }
532 }
533 else
534 {
535 rc = KDBG_ERR_DBGHLP_VERSION_MISMATCH;
536 kDbgAssertMsgFailed(("ImagehlpApiVersion -> %p and MajorVersion=%d.\n", pVersion, pVersion ? pVersion->MajorVersion : 0));
537 }
538 }
539 else
540 {
541 DWORD Err = GetLastError();
542 rc = kdbgModDHConvWinError(Err);
543 kDbgAssertMsgFailed(("Failed to resolve ImagehlpApiVersionEx in dbghelp, Err=%d rc=%d\n", Err, rc));
544 }
545 FreeLibrary(hmod);
546 InterlockedExchange(&s_lLock, 0);
547 return rc;
548}
549
550
551/**
552 * @copydoc KDBGMODOPS::pfnOpen
553 */
554static int kdbgModDHOpen(PKDBGMOD *ppMod, PKRDR pRdr, KBOOL fCloseRdr, KFOFF off, KFOFF cb, struct KLDRMOD *pLdrMod)
555{
556 /*
557 * This reader doesn't support partial files.
558 * Also weed out small files early on as they cannot be
559 * PE images and will only cause read errors
560 */
561 if ( off != 0
562 || cb != KFOFF_MAX)
563 return KDBG_ERR_UNKOWN_FORMAT;
564 if (kRdrSize(pRdr) < sizeof(IMAGE_NT_HEADERS32) + sizeof(IMAGE_SECTION_HEADER))
565 return KDBG_ERR_UNKOWN_FORMAT;
566
567 /*
568 * We need to read the section headers and get the image size.
569 */
570 /* Find the PE header magic. */
571 KU32 offHdr = 0;
572 KU32 u32Magic;
573 int rc = kRdrRead(pRdr, &u32Magic, sizeof(u32Magic), 0);
574 kDbgAssertRCReturn(rc, rc);
575 if ((KU16)u32Magic == IMAGE_DOS_SIGNATURE)
576 {
577 rc = kRdrRead(pRdr, &offHdr, sizeof(offHdr), K_OFFSETOF(IMAGE_DOS_HEADER, e_lfanew));
578 kDbgAssertRCReturn(rc, rc);
579 if (!offHdr)
580 return KDBG_ERR_FORMAT_NOT_SUPPORTED;
581 if ( offHdr < sizeof(IMAGE_DOS_SIGNATURE)
582 || offHdr >= kRdrSize(pRdr) - 4)
583 return KDBG_ERR_BAD_EXE_FORMAT;
584
585 rc = kRdrRead(pRdr, &u32Magic, sizeof(u32Magic), offHdr);
586 kDbgAssertRCReturn(rc, rc);
587 }
588 if (u32Magic != IMAGE_NT_SIGNATURE)
589 return KDBG_ERR_FORMAT_NOT_SUPPORTED;
590
591 /* read the file header and the image size in the optional header.. */
592 IMAGE_FILE_HEADER FHdr;
593 rc = kRdrRead(pRdr, &FHdr, sizeof(FHdr), offHdr + K_OFFSETOF(IMAGE_NT_HEADERS32, FileHeader));
594 kDbgAssertRCReturn(rc, rc);
595
596 KU32 cbImage;
597 if (FHdr.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32))
598 rc = kRdrRead(pRdr, &cbImage, sizeof(cbImage),
599 offHdr + K_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader.SizeOfImage));
600 else if (FHdr.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER64))
601 rc = kRdrRead(pRdr, &cbImage, sizeof(cbImage),
602 offHdr + K_OFFSETOF(IMAGE_NT_HEADERS64, OptionalHeader.SizeOfImage));
603 else
604 kDbgAssertFailedReturn(KDBG_ERR_BAD_EXE_FORMAT);
605 kDbgAssertRCReturn(rc, rc);
606
607 /*
608 * Load dbghelp.dll.
609 */
610 rc = kdbgModDHLoadDbgHelp();
611 if (rc)
612 return rc;
613
614 /*
615 * Allocate the module and read/construct the section headers.
616 */
617 PKDBGMODDBGHELP pModDH = (PKDBGMODDBGHELP)kHlpAlloc(K_OFFSETOF(KDBGMODDBGHELP, aSections[FHdr.NumberOfSections + 2]));
618 kDbgAssertReturn(pModDH, KERR_NO_MEMORY);
619 pModDH->Core.u32Magic = KDBGMOD_MAGIC;
620 pModDH->Core.pOps = &g_kDbgModWinDbgHelpOpen;
621 pModDH->Core.pRdr = pRdr;
622 pModDH->Core.fCloseRdr = fCloseRdr;
623 pModDH->Core.pLdrMod = pLdrMod;
624 pModDH->cbImage = cbImage;
625 pModDH->cSections = 1 + FHdr.NumberOfSections;
626
627 rc = kRdrRead(pRdr, &pModDH->aSections[1], sizeof(pModDH->aSections[0]) * FHdr.NumberOfSections,
628 offHdr + K_OFFSETOF(IMAGE_NT_HEADERS32, OptionalHeader) + FHdr.SizeOfOptionalHeader);
629 if (!rc)
630 {
631 PIMAGE_SECTION_HEADER pSH = &pModDH->aSections[0];
632 kHlpMemCopy(pSH->Name, "headers", sizeof(pSH->Name));
633 pSH->Misc.VirtualSize = pModDH->aSections[1].VirtualAddress;
634 pSH->VirtualAddress = 0;
635 pSH->SizeOfRawData = pSH->Misc.VirtualSize;
636 pSH->PointerToRawData = 0;
637 pSH->PointerToRelocations = 0;
638 pSH->PointerToLinenumbers = 0;
639 pSH->NumberOfRelocations = 0;
640 pSH->NumberOfLinenumbers = 0;
641 pSH->Characteristics = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_ALIGN_4BYTES | IMAGE_SCN_MEM_READ;
642
643 KU32 uTheEnd = pModDH->aSections[FHdr.NumberOfSections].VirtualAddress
644 + pModDH->aSections[FHdr.NumberOfSections].Misc.VirtualSize;
645 if (uTheEnd < cbImage)
646 {
647 pSH = &pModDH->aSections[pModDH->cSections++];
648 kHlpMemCopy(pSH->Name, "tail\0\0\0", sizeof(pSH->Name));
649 pSH->Misc.VirtualSize = cbImage - uTheEnd;
650 pSH->VirtualAddress = uTheEnd;
651 pSH->SizeOfRawData = pSH->Misc.VirtualSize;
652 pSH->PointerToRawData = 0;
653 pSH->PointerToRelocations = 0;
654 pSH->PointerToLinenumbers = 0;
655 pSH->NumberOfRelocations = 0;
656 pSH->NumberOfLinenumbers = 0;
657 pSH->Characteristics = IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_ALIGN_1BYTES | IMAGE_SCN_MEM_READ;
658 }
659
660 /*
661 * Find a new dbghelp handle.
662 *
663 * We assume 4GB of handles outlast most debugging sessions, or in anyways that
664 * when we start reusing handles they are no longer in use. :-)
665 */
666 static volatile long s_u32LastHandle = 1;
667 HANDLE hSymInst = (HANDLE)InterlockedIncrement(&s_u32LastHandle);
668 while ( hSymInst == INVALID_HANDLE_VALUE
669 || hSymInst == (HANDLE)0
670 || hSymInst == GetCurrentProcess())
671 hSymInst = (HANDLE)InterlockedIncrement(&s_u32LastHandle);
672
673 /*
674 * Initialize dbghelp and try open the specified module.
675 */
676 if (g_pfnSymInitialize(hSymInst, NULL, FALSE))
677 {
678 g_pfnSymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_AUTO_PUBLICS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS);
679
680 KIPTR NativeFH = kRdrNativeFH(pRdr);
681 DWORD64 ImageBase = g_pfnSymLoadModule64(hSymInst, NativeFH == -1 ? NULL : (HANDLE)NativeFH,
682 kRdrName(pRdr), NULL, 0x00400000, 0);
683 if (ImageBase)
684 {
685 pModDH->hSymInst = hSymInst;
686 pModDH->ImageBase = ImageBase;
687 *ppMod = &pModDH->Core;
688 return rc;
689 }
690
691 DWORD Err = GetLastError();
692 rc = kdbgModDHConvWinError(Err);
693 kDbgAssertMsgFailed(("SymLoadModule64 failed: Err=%d rc=%d\n", Err, rc));
694 g_pfnSymCleanup(hSymInst);
695 }
696 else
697 {
698 DWORD Err = GetLastError();
699 rc = kdbgModDHConvWinError(Err);
700 kDbgAssertMsgFailed(("SymInitialize failed: Err=%d rc=%d\n", Err, rc));
701 }
702 }
703 else
704 kDbgAssertRC(rc);
705
706 kHlpFree(pModDH);
707 return rc;
708}
709
710
711/**
712 * Methods for a PE module.
713 */
714KDBGMODOPS const g_kDbgModWinDbgHelpOpen =
715{
716 "Windows DbgHelp",
717 NULL,
718 kdbgModDHOpen,
719 kdbgModDHClose,
720 kdbgModDHQuerySymbol,
721 kdbgModDHQueryLine,
722 "Windows DbgHelp"
723};
724
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette