source: trunk/kLdr/kLdrModPE.c@ 2854

Last change on this file since 2854 was 2854, checked in by bird, 19 years ago

Hacking away on the PE module interpreter.

File size: 34.1 KB
Line 
1/* $Id: kLdrMod.c 2851 2006-11-02 03:21:54Z bird $ */
2/** @file
3 *
4 * kLdr - The Module Interpreter for the Portable Executable (PE) Format.
5 *
6 * Copyright (c) 2006 knut st. osmundsen <bird-kbuild-src@anduin.net>
7 *
8 *
9 * This file is part of kLdr.
10 *
11 * kLdr is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * kLdr is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with kLdr; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 *
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include <kLdr.h>
32#include "kLdrHlp.h"
33#include "kLdrInternal.h"
34#include "kLdrModPE.h"
35
36/*******************************************************************************
37* Defined Constants And Macros *
38*******************************************************************************/
39/** @def KLDRMODPE_STRICT
40 * Define KLDRMODPE_STRICT to enabled strict checks in KLDRMODPE. */
41#define KLDRMOD_STRICT 1
42
43/** @def KLDRMODPE_ASSERT
44 * Assert that an expression is true when KLDR_STRICT is defined.
45 */
46#ifdef KLDRMODPE_STRICT
47# define KLDRMODPE_ASSERT(expr) kldrHlpAssert(expr)
48#else
49# define KLDRMODPE_ASSERT(expr) do {} while (0)
50#endif
51
52/** @def KLDRMODPE_RVA2TYPE
53 * Converts a RVA to a pointer of the specified type.
54 * @param pvBits The bits (image base).
55 * @param uRVA The image relative virtual address.
56 * @param type The type to cast to.
57 */
58#define KLDRMODPE_RVA2TYPE(pvBits, uRVA, type) \
59 ( (type) ((uintptr_t)(pvBits) + (uRVA)) )
60
61
62
63/*******************************************************************************
64* Structures and Typedefs *
65*******************************************************************************/
66/**
67 * Instance data for the PE module interpreter.
68 */
69typedef struct KLDRMODPE
70{
71 /** Pointer to the module. (Follows the section table.) */
72 PKLDRMOD pMod;
73 /** Pointer to the RDR mapping of the raw file bits. NULL if not mapped. */
74 const void *pvBits;
75 /** Whether we've mapped the image or not. */
76 uint32_t fMapped : 1;
77 /** Reserved flags. */
78 uint32_t f31Reserved;
79 /** The number of imported modules.
80 * If ~(uint32_t)0 this hasn't been determined yet. */
81 uint32_t cImportModules;
82 /** The offset of the NT headers. */
83 off_t offHdrs;
84 /** Copy of the NT headers. */
85 IMAGE_NT_HEADERS64 Hdrs;
86 /** The section header table . */
87 IMAGE_SECTION_HEADER aShdrs[1];
88} KLDRMODPE, *PKLDRMODPE;
89
90
91/*******************************************************************************
92* Internal Functions *
93*******************************************************************************/
94static int kldrModPECreateInstance(PKLDRRDR pRdr, off_t offNewHdr, PKLDRMODPE *ppMod);
95static void kldrModPEConvertLoadConfig(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg);
96static int kLdrModPEValidateOptionalHeader(PKLDRMODPE pModPE);
97static int kLdrModPEValidateSectionHeaders(PKLDRMODPE pModPE);
98static void kldrModPEConvertOptionalHeader(PIMAGE_OPTIONAL_HEADER64 pOptionalHeader);
99static int kldrModPEQueryForwarder(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
100 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser, PKLDRADDR puValue, uint32_t *pfKind);
101
102
103/**
104 * Create a loader module instance interpreting the executable image found
105 * in the specified file provider instance.
106 *
107 * @returns 0 on success and *ppMod pointing to a module instance.
108 * On failure, a non-zero OS specific error code is returned.
109 * @param pOps Pointer to the registered method table.
110 * @param pRdr The file provider instance to use.
111 * @param offNewHdr The offset of the new header in MZ files. -1 if not found.
112 * @param ppMod Where to store the module instance pointer.
113 */
114static int kldrModPECreate(PCKLDRMODOPS pOps, PKLDRRDR pRdr, off_t offNewHdr, PPKLDRMOD ppMod)
115{
116 PKLDRMODPE pModPE;
117 int rc;
118
119 /*
120 * Create the instance data and do a minimal header validation.
121 */
122 rc = kldrModPECreateInstance(pRdr, offNewHdr, &pModPE);
123 if (!rc)
124 {
125 pModPE->pMod->pOps = pOps;
126 pModPE->pMod->u32Magic = KLDRMOD_MAGIC;
127 *ppMod = pModPE->pMod;
128 return 0;
129 }
130 kldrHlpFree(pModPE);
131 return rc;
132}
133
134
135/**
136 * Separate function for reading creating the PE module instance to
137 * simplify cleanup on failure.
138 */
139static int kldrModPECreateInstance(PKLDRRDR pRdr, off_t offNewHdr, PKLDRMODPE *ppModPE)
140{
141 struct
142 {
143 uint32_t Signature;
144 IMAGE_FILE_HEADER FileHdr;
145 } s;
146 PKLDRMODPE pModPE;
147 PKLDRMOD pMod;
148 size_t cb;
149 size_t cchFilename;
150 off_t off;
151 uint32_t i;
152 int rc;
153 *ppModPE = NULL;
154
155 /*
156 * Read the signature and file header.
157 */
158 rc = kLdrRdrRead(pRdr, &s, sizeof(s), offNewHdr > 0 ? offNewHdr : 0);
159 if (rc)
160 return rc;
161 if (s.Signature != IMAGE_NT_SIGNATURE)
162 return KLDR_ERR_UNKNOWN_FORMAT;
163
164 /* sanity checks. */
165 if ( s.FileHdr.NumberOfSections > 1024*1024
166 || ( s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)
167 && s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER64))
168 )
169 return KLDR_ERR_PE_BAD_FILE_HEADER;
170 if ( s.FileHdr.Machine != IMAGE_FILE_MACHINE_I386
171 && s.FileHdr.Machine != IMAGE_FILE_MACHINE_AMD64
172 )
173 return KLDR_ERR_PE_UNSUPPORTED_MACHINE;
174
175 /*
176 * Calc the instance size, allocate and initialize it.
177 */
178 cchFilename = kLdrHlpStrLen(kLdrRdrName(pRdr));
179 cb = sizeof(KLDRMOD)
180 + s.FileHdr.NumberOfSections * sizeof(KLDRSEG)
181 + sizeof(KLDRMODPE) - sizeof(IMAGE_SECTION_HEADER)
182 + s.FileHdr.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)
183 + cchFilename + 1;
184 pModPE = (PKLDRMODPE)kldrHlpAlloc(cb);
185 if (!pModPE)
186 return KLDR_ERR_NO_MEMORY;
187
188 /* KLDRMOD */
189 pMod = (PKLDRMOD)((uint8_t *)pModPE + sizeof(KLDRMOD) + (s.FileHdr.NumberOfSections + 1) * sizeof(KLDRSEG));
190 pMod->pvData = pModPE;
191 pMod->pRdr = pRdr;
192 pMod->pOps = NULL; /* set upon success. */
193 pMod->cSegments = s.FileHdr.NumberOfSections + 1;
194 pMod->cchFilename = cchFilename;
195 pMod->pszFilename = (char *)&pMod->aSegments[pMod->cSegments];
196 kLdrHlpMemCopy((char *)pMod->pszFilename, kLdrRdrName(pRdr), cchFilename + 1);
197 pMod->pszName = kldrHlpGetFilename(pMod->pszFilename);
198 pMod->cchName = cchFilename - (pMod->pszName - pMod->pszFilename);
199 switch (s.FileHdr.Machine)
200 {
201 case IMAGE_FILE_MACHINE_I386:
202 pMod->enmCpu = KLDRCPU_I386;
203 pMod->enmArch = KLDRARCH_X86_32;
204 pMod->enmEndian = KLDRENDIAN_LITTLE;
205 break;
206
207 case IMAGE_FILE_MACHINE_AMD64:
208 pMod->enmCpu = KLDRCPU_K8;
209 pMod->enmArch = KLDRARCH_AMD64;
210 pMod->enmEndian = KLDRENDIAN_LITTLE;
211 break;
212 default:
213 kldrHlpAssert(0);
214 break;
215 }
216 pMod->enmFmt = KLDRFMT_PE;
217 pMod->u32Magic = 0; /* set upon success. */
218
219 /* KLDRMODPE */
220 pModPE->pMod = pMod;
221 pModPE->pvBits = NULL;
222 pModPE->fMapped = 0;
223 pModPE->f31Reserved = 0;
224 pModPE->cImportModules = ~(uint32_t)0;
225 pModPE->offHdrs = offNewHdr >= 0 ? offNewHdr : 0;
226 pModPE->Hdrs.Signature = s.Signature;
227 pModPE->Hdrs.FileHeader = s.FileHdr;
228 *ppModPE = pModPE;
229
230 /*
231 * Read the optional header and the section table.
232 */
233 off = pModPE->offHdrs + sizeof(pModPE->Hdrs.Signature) + sizeof(pModPE->Hdrs.FileHeader);
234 rc = kLdrRdrRead(pRdr, &pModPE->Hdrs.OptionalHeader, pModPE->Hdrs.FileHeader.SizeOfOptionalHeader, off);
235 if (rc)
236 return rc;
237 if (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader != sizeof(pModPE->Hdrs.OptionalHeader))
238 kldrModPEConvertOptionalHeader(&pModPE->Hdrs.OptionalHeader);
239 off += pModPE->Hdrs.FileHeader.SizeOfOptionalHeader;
240 rc = kLdrRdrRead(pRdr, &pModPE->aShdrs[0], sizeof(IMAGE_SECTION_HEADER) * pModPE->Hdrs.FileHeader.NumberOfSections, off);
241 if (rc)
242 return rc;
243
244 /*
245 * Validate the two.
246 */
247 rc = kLdrModPEValidateOptionalHeader(pModPE);
248 if (rc)
249 return rc;
250 for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
251 {
252 rc = kLdrModPEValidateSectionHeaders(pModPE);
253 if (rc)
254 return rc;
255 }
256
257 /*
258 * Setup the KLDRMOD segment array.
259 */
260 /* The implied headers section. */
261 pMod->aSegments[0].pvUser = NULL;
262 pMod->aSegments[0].pchName = "TheHeaders";
263 pMod->aSegments[0].cchName = sizeof("TheHeaders") - 1;
264 pMod->aSegments[0].cb = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
265 pMod->aSegments[0].LinkAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
266 pMod->aSegments[0].MapAddress = NIL_KLDRADDR;
267 pMod->aSegments[0].enmProt = KLDRPROT_READONLY;
268
269 /* The section headers. */
270 for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
271 {
272 char *pch;
273 pMod->aSegments[i + 1].pvUser = NULL;
274 pMod->aSegments[i + 1].pchName = pch = &pModPE->aShdrs[i].Name[0];
275 cb = IMAGE_SIZEOF_SHORT_NAME;
276 while ( cb > 0
277 && (pch[cb - 1] == ' ' || pch[cb - 1] == '\0'))
278 cb--;
279 pMod->aSegments[i + 1].cchName = cb;
280 if (!(pModPE->aShdrs[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
281 {
282 pMod->aSegments[i + 1].cb = pModPE->aShdrs[i].Misc.VirtualSize;
283 pMod->aSegments[i + 1].LinkAddress = pModPE->aShdrs[i].VirtualAddress;
284 }
285 else
286 {
287 pMod->aSegments[i + 1].cb = 0;
288 pMod->aSegments[i + 1].LinkAddress = NIL_KLDRADDR;
289 }
290 pMod->aSegments[i + 1].MapAddress = NIL_KLDRADDR;
291 switch ( pModPE->aShdrs[i].Characteristics
292 & (IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE))
293 {
294 case 0:
295 case IMAGE_SCN_MEM_SHARED:
296 pMod->aSegments[i + 1].enmProt = KLDRPROT_NOACCESS;
297 break;
298 case IMAGE_SCN_MEM_READ:
299 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
300 pMod->aSegments[i + 1].enmProt = KLDRPROT_READONLY;
301 break;
302 case IMAGE_SCN_MEM_WRITE:
303 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
304 pMod->aSegments[i + 1].enmProt = KLDRPROT_WRITECOPY;
305 break;
306 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
307 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
308 pMod->aSegments[i + 1].enmProt = KLDRPROT_READWRITE;
309 break;
310 case IMAGE_SCN_MEM_EXECUTE:
311 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_SHARED:
312 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE;
313 break;
314 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ:
315 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
316 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE_READ;
317 break;
318 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE:
319 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
320 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE_WRITECOPY;
321 break;
322 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
323 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
324 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE_READWRITE;
325 break;
326 }
327 switch (pModPE->aShdrs[i].Characteristics & IMAGE_SCN_ALIGN_MASK)
328 {
329 default: kldrHlpAssert(0);
330 case 0: pMod->aSegments[i + 1].Alignment = 0; break;
331 case IMAGE_SCN_ALIGN_1BYTES: pMod->aSegments[i + 1].Alignment = 1; break;
332 case IMAGE_SCN_ALIGN_2BYTES: pMod->aSegments[i + 1].Alignment = 2; break;
333 case IMAGE_SCN_ALIGN_4BYTES: pMod->aSegments[i + 1].Alignment = 4; break;
334 case IMAGE_SCN_ALIGN_8BYTES: pMod->aSegments[i + 1].Alignment = 8; break;
335 case IMAGE_SCN_ALIGN_16BYTES: pMod->aSegments[i + 1].Alignment = 16; break;
336 case IMAGE_SCN_ALIGN_32BYTES: pMod->aSegments[i + 1].Alignment = 32; break;
337 case IMAGE_SCN_ALIGN_64BYTES: pMod->aSegments[i + 1].Alignment = 64; break;
338 case IMAGE_SCN_ALIGN_128BYTES: pMod->aSegments[i + 1].Alignment = 128; break;
339 case IMAGE_SCN_ALIGN_256BYTES: pMod->aSegments[i + 1].Alignment = 256; break;
340 case IMAGE_SCN_ALIGN_512BYTES: pMod->aSegments[i + 1].Alignment = 512; break;
341 case IMAGE_SCN_ALIGN_1024BYTES: pMod->aSegments[i + 1].Alignment = 1024; break;
342 case IMAGE_SCN_ALIGN_2048BYTES: pMod->aSegments[i + 1].Alignment = 2048; break;
343 case IMAGE_SCN_ALIGN_4096BYTES: pMod->aSegments[i + 1].Alignment = 4096; break;
344 case IMAGE_SCN_ALIGN_8192BYTES: pMod->aSegments[i + 1].Alignment = 8192; break;
345 }
346 }
347
348 /*
349 * We're done.
350 */
351 *ppModPE = pModPE;
352 return 0;
353}
354
355
356/**
357 * Internal worker which validates the section headers.
358 */
359static int kLdrModPEValidateOptionalHeader(PKLDRMODPE pModPE)
360{
361 const unsigned fIs32Bit = pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32);
362
363 /* the magic */
364 if ( pModPE->Hdrs.OptionalHeader.Magic
365 != (fIs32Bit ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC))
366 return KLDR_ERR_PE_BAD_OPTIONAL_HEADER;
367
368 /** @todo validate more */
369 return 0;
370}
371
372
373/**
374 * Internal worker which validates the section headers.
375 */
376static int kLdrModPEValidateSectionHeaders(PKLDRMODPE pModPE)
377{
378 /** @todo validate shdrs */
379 return 0;
380}
381
382
383/**
384 * Converts a 32-bit optional header to a 64-bit one
385 *
386 * @param pOptHdr The optional header to convert.
387 */
388static void kldrModPEConvertOptionalHeader(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
389{
390 /* volatile everywhere! */
391 IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
392 IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
393 uint32_t volatile *pu32Dst;
394 uint32_t volatile *pu32Src;
395 uint32_t volatile *pu32SrcLast;
396 uint32_t u32;
397
398 /* From LoaderFlags and out the difference is 4 * 32-bits. */
399 pu32Dst = (uint32_t *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
400 pu32Src = (uint32_t *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
401 pu32SrcLast = (uint32_t *)&pOptHdr32->LoaderFlags;
402 while (pu32Src >= pu32SrcLast)
403 *pu32Dst-- = *pu32Src--;
404
405 /* The previous 4 fields are 32/64 and needs special attention. */
406 pOptHdr64->SizeOfHeapCommit = pOptHdr32->SizeOfHeapCommit;
407 pOptHdr64->SizeOfHeapReserve = pOptHdr32->SizeOfHeapReserve;
408 pOptHdr64->SizeOfStackCommit = pOptHdr32->SizeOfStackCommit;
409 u32 = pOptHdr32->SizeOfStackReserve;
410 pOptHdr64->SizeOfStackReserve = u32;
411
412 /*
413 * The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version.
414 * Thus, ImageBase needs some special treatement. It will probably work fine assigning one to the
415 * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
416 */
417 u32 = pOptHdr32->ImageBase;
418 pOptHdr64->ImageBase = u32;
419}
420
421
422/**
423 * Converts a 32-bit load config directory to a 64 bit one.
424 *
425 * @param pOptHdr The load config to convert.
426 */
427static void kldrModPEConvertLoadConfig(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
428{
429 /* volatile everywhere! */
430 IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
431 IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
432 uint32_t u32;
433
434 pLoadCfg64->SEHandlerCount = pLoadCfg32->SEHandlerCount;
435 pLoadCfg64->SEHandlerTable = pLoadCfg32->SEHandlerTable;
436 pLoadCfg64->SecurityCookie = pLoadCfg32->SecurityCookie;
437 pLoadCfg64->EditList = pLoadCfg32->EditList;
438 pLoadCfg64->Reserved1 = pLoadCfg32->Reserved1;
439 pLoadCfg64->CSDVersion = pLoadCfg32->CSDVersion;
440 /* (ProcessHeapFlags switched place with ProcessAffinityMask, but we're
441 * more than 16 byte off by now so it doesn't matter.) */
442 pLoadCfg64->ProcessHeapFlags = pLoadCfg32->ProcessHeapFlags;
443 pLoadCfg64->ProcessAffinityMask = pLoadCfg32->ProcessAffinityMask;
444 pLoadCfg64->VirtualMemoryThreshold = pLoadCfg32->VirtualMemoryThreshold;
445 pLoadCfg64->MaximumAllocationSize = pLoadCfg32->MaximumAllocationSize;
446 pLoadCfg64->LockPrefixTable = pLoadCfg32->LockPrefixTable;
447 pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
448 u32 = pLoadCfg32->DeCommitFreeBlockThreshold;
449 pLoadCfg64->DeCommitFreeBlockThreshold = u32;
450 /* the remainder matches. */
451}
452
453
454/** @copydoc KLDRMODOPS::pfnDestroy */
455static int kldrModPEDestroy(PKLDRMOD pMod)
456{
457 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
458 int rc = 0;
459 KLDRMODPE_ASSERT(pModPE->fMapped);
460
461 if (pMod->pRdr)
462 {
463 rc = kLdrRdrClose(pMod->pRdr);
464 pMod->pRdr = NULL;
465 }
466 pMod->u32Magic = 0;
467 pMod->pOps = NULL;
468 kldrHlpFree(pModPE);
469 return rc;
470}
471
472
473/**
474 * Gets usable bits and the right base address.
475 *
476 * @returns 0 on success.
477 * @returns A non-zero status code if the BaseAddress isn't right or some problem is encountered
478 * featch in a temp mapping the bits.
479 * @param pModPE The interpreter module instance
480 * @param ppvBits The bits address, IN & OUT.
481 * @param pBaseAddress The base address, IN & OUT. Optional.
482 */
483static int kldrModPEBitsAndBaseAddress(PKLDRMODPE pModPE, const void **ppvBits, PKLDRADDR pBaseAddress)
484{
485 int rc = 0;
486
487 /*
488 * Correct the base address.
489 *
490 * We don't use the base address for interpreting the bits in this
491 * interpreter, which makes things relativly simple.
492 */
493 if (pBaseAddress)
494 {
495 if (*pBaseAddress == KLDRMOD_BASEADDRESS_MAP)
496 *pBaseAddress = pModPE->pMod->aSegments[0].MapAddress;
497 else if (*pBaseAddress == KLDRMOD_BASEADDRESS_LINK)
498 *pBaseAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
499 }
500
501 /*
502 * Get bits.
503 */
504 if (!*ppvBits)
505 {
506 if (pModPE->fMapped)
507 *ppvBits = (void *)(uintptr_t)pModPE->pMod->aSegments[0].MapAddress;
508 else if (pModPE->pvBits)
509 *ppvBits = pModPE->pvBits;
510 else
511 {
512 /** @todo do an internal mapping. */
513 rc = -1;
514 }
515 }
516
517 return 0;
518}
519
520
521/** @copydoc kLdrModQuerySymbol */
522static int kldrModPEQuerySymbol(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, uint32_t uSymbol,
523 const char *pszSymbol, PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser,
524 PKLDRADDR puValue, uint32_t *pfKind)
525{
526 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
527 const uint32_t *paExportRVAs;
528 const IMAGE_EXPORT_DIRECTORY *pExpDir;
529 uint32_t iExpOrd;
530 uint32_t uRVA;
531 int rc;
532
533 /*
534 * Make sure we've got mapped bits and resolve any base address aliases.
535 */
536 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
537 if (rc)
538 return rc;
539 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
540 < sizeof(IMAGE_EXPORT_DIRECTORY))
541 return KLDR_ERR_SYMBOL_NOT_FOUND;
542
543 pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
544 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
545 PIMAGE_EXPORT_DIRECTORY);
546 if (!pszSymbol)
547 {
548 /*
549 * Simple, calculate the unbased ordinal and bounds check it.
550 */
551 iExpOrd = uSymbol - pExpDir->Base;
552 if (iExpOrd >= KLDR_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions))
553 return KLDR_ERR_SYMBOL_NOT_FOUND;
554 }
555 else
556 {
557 /*
558 * Do a binary search for the name.
559 * (The name table is sorted in ascending ordered by the linker.)
560 */
561 const uint32_t *paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const uint32_t *);
562 const uint16_t *paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const uint16_t *);
563 int32_t iStart = 1; /* one based binary searching is simpler. */
564 int32_t iEnd = pExpDir->NumberOfNames;
565
566 for (;;)
567 {
568 int32_t i;
569 int diff;
570 const char *pszName;
571
572 /* done? */
573 if (iStart > iEnd)
574 {
575#ifdef KLDRMODPE_STRICT /* Make sure the linker and we both did our job right. */
576 for (i = 0; i < pExpDir->NumberOfNames; i++)
577
578 {
579 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i], const char *);
580 KLDRMODPE_ASSERT(kLdrHlpStrComp(pszName, pszSymbol));
581 KLDRMODPE_ASSERT(i == 0 || kLdrHlpStrComp(pszName, KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *)));
582 }
583#endif
584 return KLDR_ERR_SYMBOL_NOT_FOUND;
585 }
586
587 i = (iEnd - iStart) / 2 + iStart;
588 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *);
589 diff = kLdrHlpStrComp(pszName, pszSymbol);
590 if (diff < 0)
591 iStart = i + 1; /* The symbol must be after the current name. */
592 else if (diff)
593 iEnd = i - 1; /* The symbol must be before the current name. */
594 else
595 {
596 iExpOrd = paOrdinals[i - 1]; /* match! */
597 break;
598 }
599 }
600 }
601
602 /*
603 * Lookup the address in the 'symbol' table.
604 */
605 paExportRVAs = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const uint32_t *);
606 uRVA = paExportRVAs[iExpOrd];
607 if ( uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
608 < pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
609 return kldrModPEQueryForwarder(pModPE, pvBits, KLDRMODPE_RVA2TYPE(pvBits, uRVA, const char *),
610 pfnGetForwarder, pvUser, puValue, pfKind);
611
612 /*
613 * Set the return value.
614 */
615 if (puValue)
616 *puValue = BaseAddress + uRVA;
617 if (pfKind)
618 *pfKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
619 ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
620 | KLDRSYMKIND_NO_TYPE;
621 return 0;
622}
623
624
625/**
626 * Deal with a forwarder entry.
627 *
628 * We do this seprately from kldrModPEQuerySymbol because the code is clumsy (as is all PE code
629 * thanks to the descriptive field names), and because it uses quite a bit more stack and we're
630 * trying to avoid allocating stack unless we have to.
631 *
632 * @returns See kLdrModQuerySymbol.
633 * @param pModPE The PE module interpreter instance.
634 * @param pvBits Where to read the image from.
635 * @param pszForwarder The forwarder entry name.
636 * @param pfnGetForwarder The callback for resolving forwarder symbols. (optional)
637 * @param pvUser The user argument for the callback.
638 * @param puValue Where to put the value. (optional)
639 * @param pfKind Where to put the symbol kind. (optional)
640 */
641static int kldrModPEQueryForwarder(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
642 PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser, PKLDRADDR puValue, uint32_t *pfKind)
643{
644 const IMAGE_IMPORT_DESCRIPTOR *paImpDir;
645 uint32_t cImpModules;
646 uint32_t iImpModule;
647 uint32_t cchImpModule;
648 const char *pszSymbol;
649 uint32_t uSymbol;
650 int rc;
651
652 if (!pfnGetForwarder)
653 return KLDR_ERR_FORWARDER_SYMBOL;
654
655 /*
656 * Separate the name into a module name and a symbol name or ordinal.
657 *
658 * The module name ends at the first dot ('.').
659 * After the dot follows either a symbol name or a hash ('#') + ordinal.
660 */
661 pszSymbol = pszForwarder;
662 while (*pszSymbol != '.')
663 pszSymbol++;
664 if (!*pszSymbol)
665 return KLDR_ERR_PE_BAD_FORWARDER;
666 cchImpModule = pszSymbol - pszForwarder;
667
668 pszSymbol++; /* skip the dot */
669 if (!*pszSymbol)
670 return KLDR_ERR_PE_BAD_FORWARDER;
671 if (*pszSymbol == '#')
672 {
673 unsigned uBase;
674 pszSymbol++; /* skip the hash */
675
676 /* base detection */
677 uBase = 10;
678 if (pszSymbol[0] == '0' && (pszSymbol[1] == 'x' || pszSymbol[1] == 'X'))
679 {
680 uBase = 16;
681 pszSymbol += 2;
682 }
683
684 /* ascii to integer */
685 uSymbol = 0;
686 for (;;)
687 {
688 /* convert char to digit. */
689 unsigned uDigit = *pszSymbol++;
690 if (uDigit >= '0' && uDigit <= '9')
691 uDigit -= '0';
692 else if (uDigit >= 'a' && uDigit <= 'z')
693 uDigit -= 'a' + 10;
694 else if (uDigit >= 'A' && uDigit <= 'Z')
695 uDigit -= 'A' + 10;
696 else if (!uDigit)
697 break;
698 else
699 return KLDR_ERR_PE_BAD_FORWARDER;
700 if (uDigit >= uBase)
701 return KLDR_ERR_PE_BAD_FORWARDER;
702
703 /* insert the digit */
704 uSymbol *= uBase;
705 uSymbol += uDigit;
706 }
707
708 pszSymbol = NULL; /* no symbol name. */
709 }
710 else
711 uSymbol = NIL_KLDRMOD_SYM_ORDINAL; /* no ordinal number. */
712
713
714 /*
715 * Find the import module name.
716 *
717 * We ASSUME the linker will make sure there is an import
718 * entry for the module... not sure if this is right though.
719 */
720 cImpModules = pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
721 / sizeof(IMAGE_IMPORT_DESCRIPTOR);
722 paImpDir = KLDRMODPE_RVA2TYPE(pvBits,
723 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
724 const IMAGE_IMPORT_DESCRIPTOR *);
725 for (iImpModule = 0; iImpModule < cImpModules; cImpModules++)
726 {
727 const char *pszName = KLDRMODPE_RVA2TYPE(pvBits, paImpDir[iImpModule].Name, const char *);
728 const size_t cchName = kLdrHlpStrLen(pszName);
729 if ( ( cchName == cchImpModule
730 || ( cchName > cchImpModule
731 && pszName[cchImpModule] == '.'
732 && (pszName[cchImpModule + 1] == 'd' || pszName[cchImpModule + 1] == 'D')
733 && (pszName[cchImpModule + 2] == 'l' || pszName[cchImpModule + 2] == 'L')
734 && (pszName[cchImpModule + 3] == 'l' || pszName[cchImpModule + 3] == 'L'))
735 )
736 && kLdrHlpMemIComp(pszName, pszForwarder, cchImpModule)
737 )
738 break;
739 }
740 if (iImpModule >= cImpModules)
741 return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
742
743 /*
744 * Now the rest is up to the callback (almost).
745 */
746 rc = pfnGetForwarder(pModPE->pMod, iImpModule, uSymbol, pszSymbol, puValue, pfKind, pvUser);
747 if (!rc && pfKind)
748 *pfKind |= KLDRSYMKIND_FORWARDER;
749 return rc;
750}
751
752
753/** @copydoc kLdrModEnumSymbols */
754static int kldrModPEEnumSymbols(PKLDRMOD pMod, uint32_t fFlags, const void *pvBits, KLDRADDR BaseAddress,
755 PFNKLDRMODENUMSYMS pfnCallback, void *pvUser)
756{
757 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
758 const uint32_t *paFunctions;
759 const IMAGE_EXPORT_DIRECTORY *pExpDir;
760 const uint32_t *paRVANames;
761 const uint16_t *paOrdinals;
762 uint32_t iFunction;
763 uint32_t cFunctions;
764 uint32_t cNames;
765 int rc;
766
767 /*
768 * Make sure we've got mapped bits and resolve any base address aliases.
769 */
770 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
771 if (rc)
772 return rc;
773
774 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
775 < sizeof(IMAGE_EXPORT_DIRECTORY))
776 return KLDR_ERR_SYMBOL_NOT_FOUND;
777 pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
778 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
779 PIMAGE_EXPORT_DIRECTORY);
780
781 /*
782 * Enumerate the ordinal exports.
783 */
784 paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const uint32_t *);
785 paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const uint16_t *);
786 paFunctions = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const uint32_t *);
787 cFunctions = pExpDir->NumberOfFunctions;
788 cNames = pExpDir->NumberOfNames;
789 for (iFunction = 0; iFunction < cFunctions; iFunction++)
790 {
791 unsigned fFoundName;
792 uint32_t iName;
793 const uint32_t uRVA = paFunctions[iFunction];
794 const KLDRADDR uValue = BaseAddress + uRVA;
795 uint32_t fKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
796 ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
797 | KLDRSYMKIND_NO_TYPE;
798 if ( uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
799 < pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
800 fKind |= KLDRSYMKIND_FORWARDER;
801
802 /*
803 * Any symbol names?
804 */
805 fFoundName = 0;
806 for (iName = 0; iName < cNames; iName++)
807 {
808 if (!paOrdinals[iName] != iFunction)
809 continue;
810 fFoundName = 1;
811 rc = pfnCallback(pMod, iName + pExpDir->Base, KLDRMODPE_RVA2TYPE(pvBits, paRVANames[iName], const char *),
812 uValue, fKind, pvUser);
813 if (rc)
814 return rc;
815 }
816
817 /*
818 * If no names, call once with the ordinal only.
819 */
820 if (!fFoundName)
821 {
822 rc = pfnCallback(pMod, iName + pExpDir->Base, NULL, uValue, fKind, pvUser);
823 if (rc)
824 return rc;
825 }
826 }
827
828 return 0;
829}
830
831
832/** @copydoc kLdrModGetImport */
833int (* pfnGetImport)(PKLDRMOD pMod, void *pvBits, uint32_t iImport, const char *pszName, size_t cchName);
834/** @copydoc kLdrModNumberOfImports */
835int32_t (* pfnNumberOfImports)(PKLDRMOD pMod, void *pvBits);
836/** @copydoc kLdrModCanExecuteOn */
837int (* pfnCanExecuteOn)(PKLDRMOD pMod, void *pvBits, KLDRARCH enmArch, KLDRCPU enmCpu);
838/** @copydoc kLdrModGetStackInfo */
839int (* pfnGetStackInfo)(PKLDRMOD pMod, void *pvBits, KLDRADDR BaseAddress, PKLDRSTACKINFO pStackInfo);
840/** @copydoc kLdrModQueryMainEntrypoint */
841int (* pfnQueryMainEntrypoint)(PKLDRMOD pMod, void *pvBits, KLDRADDR BaseAddress, PKLDRADDR pMainEPAddress);
842/** @copydoc kLdrModEnumDbgInfo */
843int (* pfnEnumDbgInfo)(PKLDRMOD pMod, void *pvBits, PFNKLDRENUMDBG pfnCallback, void *pvUser);
844/** @copydoc kLdrModHasDbgInfo */
845int (* pfnHasDbgInfo)(PKLDRMOD pMod, void *pvBits);
846/** @copydoc kLdrModMap */
847int (* pfnMap)(PKLDRMOD pMod);
848/** @copydoc kLdrModUnmap */
849int (* pfnUnmap)(PKLDRMOD pMod);
850/** @copydoc kLdrModAllocTLS */
851int (* pfnAllocTLS)(PKLDRMOD pMod);
852/** @copydoc kLdrModFreeTLS */
853void (* pfnFreeTLS)(PKLDRMOD pMod);
854/** @copydoc kLdrModReload */
855int (* pfnReload)(PKLDRMOD pMod);
856/** @copydoc kLdrModFixupMapping */
857int (* pfnFixupMapping)(PKLDRMOD pMod, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
858/** @copydoc kLdrModCallInit */
859int (* pfnCallInit)(PKLDRMOD pMod);
860/** @copydoc kLdrModCallTerm */
861int (* pfnCallTerm)(PKLDRMOD pMod);
862/** @copydoc kLdrModCallThread */
863int (* pfnCallThread)(PKLDRMOD pMod, unsigned fAttachingOrDetaching);
864/** @copydoc kLdrModSize */
865size_t (* pfnSize)(PKLDRMOD pMod);
866/** @copydoc kLdrModGetBits */
867int (* pfnGetBits)(PKLDRMOD pMod, void *pvBits, KLDRADDR BaseAddress, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
868/** @copydoc kLdrModRelocateBits */
869int (* pfnRelocateBits)(PKLDRMOD pMod, void *pvBits, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress,
870 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
871
Note: See TracBrowser for help on using the repository browser.