source: trunk/kLdr/kLdrModPE.c@ 2855

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

More code.

File size: 37.4 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);
101static int32_t kldrModPENumberOfImports(PKLDRMOD pMod, const void *pvBits);
102
103
104/**
105 * Create a loader module instance interpreting the executable image found
106 * in the specified file provider instance.
107 *
108 * @returns 0 on success and *ppMod pointing to a module instance.
109 * On failure, a non-zero OS specific error code is returned.
110 * @param pOps Pointer to the registered method table.
111 * @param pRdr The file provider instance to use.
112 * @param offNewHdr The offset of the new header in MZ files. -1 if not found.
113 * @param ppMod Where to store the module instance pointer.
114 */
115static int kldrModPECreate(PCKLDRMODOPS pOps, PKLDRRDR pRdr, off_t offNewHdr, PPKLDRMOD ppMod)
116{
117 PKLDRMODPE pModPE;
118 int rc;
119
120 /*
121 * Create the instance data and do a minimal header validation.
122 */
123 rc = kldrModPECreateInstance(pRdr, offNewHdr, &pModPE);
124 if (!rc)
125 {
126 pModPE->pMod->pOps = pOps;
127 pModPE->pMod->u32Magic = KLDRMOD_MAGIC;
128 *ppMod = pModPE->pMod;
129 return 0;
130 }
131 kldrHlpFree(pModPE);
132 return rc;
133}
134
135
136/**
137 * Separate function for reading creating the PE module instance to
138 * simplify cleanup on failure.
139 */
140static int kldrModPECreateInstance(PKLDRRDR pRdr, off_t offNewHdr, PKLDRMODPE *ppModPE)
141{
142 struct
143 {
144 uint32_t Signature;
145 IMAGE_FILE_HEADER FileHdr;
146 } s;
147 PKLDRMODPE pModPE;
148 PKLDRMOD pMod;
149 size_t cb;
150 size_t cchFilename;
151 off_t off;
152 uint32_t i;
153 int rc;
154 *ppModPE = NULL;
155
156 /*
157 * Read the signature and file header.
158 */
159 rc = kLdrRdrRead(pRdr, &s, sizeof(s), offNewHdr > 0 ? offNewHdr : 0);
160 if (rc)
161 return rc;
162 if (s.Signature != IMAGE_NT_SIGNATURE)
163 return KLDR_ERR_UNKNOWN_FORMAT;
164
165 /* sanity checks. */
166 if ( s.FileHdr.NumberOfSections > 1024*1024
167 || ( s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)
168 && s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER64))
169 )
170 return KLDR_ERR_PE_BAD_FILE_HEADER;
171 if ( s.FileHdr.Machine != IMAGE_FILE_MACHINE_I386
172 && s.FileHdr.Machine != IMAGE_FILE_MACHINE_AMD64
173 )
174 return KLDR_ERR_PE_UNSUPPORTED_MACHINE;
175
176 /*
177 * Calc the instance size, allocate and initialize it.
178 */
179 cchFilename = kLdrHlpStrLen(kLdrRdrName(pRdr));
180 cb = sizeof(KLDRMOD)
181 + s.FileHdr.NumberOfSections * sizeof(KLDRSEG)
182 + sizeof(KLDRMODPE) - sizeof(IMAGE_SECTION_HEADER)
183 + s.FileHdr.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)
184 + cchFilename + 1;
185 pModPE = (PKLDRMODPE)kldrHlpAlloc(cb);
186 if (!pModPE)
187 return KLDR_ERR_NO_MEMORY;
188
189 /* KLDRMOD */
190 pMod = (PKLDRMOD)((uint8_t *)pModPE + sizeof(KLDRMOD) + (s.FileHdr.NumberOfSections + 1) * sizeof(KLDRSEG));
191 pMod->pvData = pModPE;
192 pMod->pRdr = pRdr;
193 pMod->pOps = NULL; /* set upon success. */
194 pMod->cSegments = s.FileHdr.NumberOfSections + 1;
195 pMod->cchFilename = cchFilename;
196 pMod->pszFilename = (char *)&pMod->aSegments[pMod->cSegments];
197 kLdrHlpMemCopy((char *)pMod->pszFilename, kLdrRdrName(pRdr), cchFilename + 1);
198 pMod->pszName = kldrHlpGetFilename(pMod->pszFilename);
199 pMod->cchName = cchFilename - (pMod->pszName - pMod->pszFilename);
200 switch (s.FileHdr.Machine)
201 {
202 case IMAGE_FILE_MACHINE_I386:
203 pMod->enmCpu = KLDRCPU_I386;
204 pMod->enmArch = KLDRARCH_X86_32;
205 pMod->enmEndian = KLDRENDIAN_LITTLE;
206 break;
207
208 case IMAGE_FILE_MACHINE_AMD64:
209 pMod->enmCpu = KLDRCPU_K8;
210 pMod->enmArch = KLDRARCH_AMD64;
211 pMod->enmEndian = KLDRENDIAN_LITTLE;
212 break;
213 default:
214 kldrHlpAssert(0);
215 break;
216 }
217 pMod->enmFmt = KLDRFMT_PE;
218 pMod->u32Magic = 0; /* set upon success. */
219
220 /* KLDRMODPE */
221 pModPE->pMod = pMod;
222 pModPE->pvBits = NULL;
223 pModPE->fMapped = 0;
224 pModPE->f31Reserved = 0;
225 pModPE->cImportModules = ~(uint32_t)0;
226 pModPE->offHdrs = offNewHdr >= 0 ? offNewHdr : 0;
227 pModPE->Hdrs.Signature = s.Signature;
228 pModPE->Hdrs.FileHeader = s.FileHdr;
229 *ppModPE = pModPE;
230
231 /*
232 * Read the optional header and the section table.
233 */
234 off = pModPE->offHdrs + sizeof(pModPE->Hdrs.Signature) + sizeof(pModPE->Hdrs.FileHeader);
235 rc = kLdrRdrRead(pRdr, &pModPE->Hdrs.OptionalHeader, pModPE->Hdrs.FileHeader.SizeOfOptionalHeader, off);
236 if (rc)
237 return rc;
238 if (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader != sizeof(pModPE->Hdrs.OptionalHeader))
239 kldrModPEConvertOptionalHeader(&pModPE->Hdrs.OptionalHeader);
240 off += pModPE->Hdrs.FileHeader.SizeOfOptionalHeader;
241 rc = kLdrRdrRead(pRdr, &pModPE->aShdrs[0], sizeof(IMAGE_SECTION_HEADER) * pModPE->Hdrs.FileHeader.NumberOfSections, off);
242 if (rc)
243 return rc;
244
245 /*
246 * Validate the two.
247 */
248 rc = kLdrModPEValidateOptionalHeader(pModPE);
249 if (rc)
250 return rc;
251 for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
252 {
253 rc = kLdrModPEValidateSectionHeaders(pModPE);
254 if (rc)
255 return rc;
256 }
257
258 /*
259 * Setup the KLDRMOD segment array.
260 */
261 /* The implied headers section. */
262 pMod->aSegments[0].pvUser = NULL;
263 pMod->aSegments[0].pchName = "TheHeaders";
264 pMod->aSegments[0].cchName = sizeof("TheHeaders") - 1;
265 pMod->aSegments[0].cb = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
266 pMod->aSegments[0].LinkAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
267 pMod->aSegments[0].MapAddress = NIL_KLDRADDR;
268 pMod->aSegments[0].enmProt = KLDRPROT_READONLY;
269
270 /* The section headers. */
271 for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
272 {
273 char *pch;
274 pMod->aSegments[i + 1].pvUser = NULL;
275 pMod->aSegments[i + 1].pchName = pch = &pModPE->aShdrs[i].Name[0];
276 cb = IMAGE_SIZEOF_SHORT_NAME;
277 while ( cb > 0
278 && (pch[cb - 1] == ' ' || pch[cb - 1] == '\0'))
279 cb--;
280 pMod->aSegments[i + 1].cchName = cb;
281 if (!(pModPE->aShdrs[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
282 {
283 pMod->aSegments[i + 1].cb = pModPE->aShdrs[i].Misc.VirtualSize;
284 pMod->aSegments[i + 1].LinkAddress = pModPE->aShdrs[i].VirtualAddress;
285 }
286 else
287 {
288 pMod->aSegments[i + 1].cb = 0;
289 pMod->aSegments[i + 1].LinkAddress = NIL_KLDRADDR;
290 }
291 pMod->aSegments[i + 1].MapAddress = NIL_KLDRADDR;
292 switch ( pModPE->aShdrs[i].Characteristics
293 & (IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE))
294 {
295 case 0:
296 case IMAGE_SCN_MEM_SHARED:
297 pMod->aSegments[i + 1].enmProt = KLDRPROT_NOACCESS;
298 break;
299 case IMAGE_SCN_MEM_READ:
300 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
301 pMod->aSegments[i + 1].enmProt = KLDRPROT_READONLY;
302 break;
303 case IMAGE_SCN_MEM_WRITE:
304 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
305 pMod->aSegments[i + 1].enmProt = KLDRPROT_WRITECOPY;
306 break;
307 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
308 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
309 pMod->aSegments[i + 1].enmProt = KLDRPROT_READWRITE;
310 break;
311 case IMAGE_SCN_MEM_EXECUTE:
312 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_SHARED:
313 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE;
314 break;
315 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ:
316 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
317 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE_READ;
318 break;
319 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE:
320 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
321 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE_WRITECOPY;
322 break;
323 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
324 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
325 pMod->aSegments[i + 1].enmProt = KLDRPROT_EXECUTE_READWRITE;
326 break;
327 }
328 switch (pModPE->aShdrs[i].Characteristics & IMAGE_SCN_ALIGN_MASK)
329 {
330 default: kldrHlpAssert(0);
331 case 0: pMod->aSegments[i + 1].Alignment = 0; break;
332 case IMAGE_SCN_ALIGN_1BYTES: pMod->aSegments[i + 1].Alignment = 1; break;
333 case IMAGE_SCN_ALIGN_2BYTES: pMod->aSegments[i + 1].Alignment = 2; break;
334 case IMAGE_SCN_ALIGN_4BYTES: pMod->aSegments[i + 1].Alignment = 4; break;
335 case IMAGE_SCN_ALIGN_8BYTES: pMod->aSegments[i + 1].Alignment = 8; break;
336 case IMAGE_SCN_ALIGN_16BYTES: pMod->aSegments[i + 1].Alignment = 16; break;
337 case IMAGE_SCN_ALIGN_32BYTES: pMod->aSegments[i + 1].Alignment = 32; break;
338 case IMAGE_SCN_ALIGN_64BYTES: pMod->aSegments[i + 1].Alignment = 64; break;
339 case IMAGE_SCN_ALIGN_128BYTES: pMod->aSegments[i + 1].Alignment = 128; break;
340 case IMAGE_SCN_ALIGN_256BYTES: pMod->aSegments[i + 1].Alignment = 256; break;
341 case IMAGE_SCN_ALIGN_512BYTES: pMod->aSegments[i + 1].Alignment = 512; break;
342 case IMAGE_SCN_ALIGN_1024BYTES: pMod->aSegments[i + 1].Alignment = 1024; break;
343 case IMAGE_SCN_ALIGN_2048BYTES: pMod->aSegments[i + 1].Alignment = 2048; break;
344 case IMAGE_SCN_ALIGN_4096BYTES: pMod->aSegments[i + 1].Alignment = 4096; break;
345 case IMAGE_SCN_ALIGN_8192BYTES: pMod->aSegments[i + 1].Alignment = 8192; break;
346 }
347 }
348
349 /*
350 * We're done.
351 */
352 *ppModPE = pModPE;
353 return 0;
354}
355
356
357/**
358 * Internal worker which validates the section headers.
359 */
360static int kLdrModPEValidateOptionalHeader(PKLDRMODPE pModPE)
361{
362 const unsigned fIs32Bit = pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32);
363
364 /* the magic */
365 if ( pModPE->Hdrs.OptionalHeader.Magic
366 != (fIs32Bit ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC))
367 return KLDR_ERR_PE_BAD_OPTIONAL_HEADER;
368
369 /** @todo validate more */
370 return 0;
371}
372
373
374/**
375 * Internal worker which validates the section headers.
376 */
377static int kLdrModPEValidateSectionHeaders(PKLDRMODPE pModPE)
378{
379 /** @todo validate shdrs */
380 return 0;
381}
382
383
384/**
385 * Converts a 32-bit optional header to a 64-bit one
386 *
387 * @param pOptHdr The optional header to convert.
388 */
389static void kldrModPEConvertOptionalHeader(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
390{
391 /* volatile everywhere! */
392 IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
393 IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
394 uint32_t volatile *pu32Dst;
395 uint32_t volatile *pu32Src;
396 uint32_t volatile *pu32SrcLast;
397 uint32_t u32;
398
399 /* From LoaderFlags and out the difference is 4 * 32-bits. */
400 pu32Dst = (uint32_t *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
401 pu32Src = (uint32_t *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
402 pu32SrcLast = (uint32_t *)&pOptHdr32->LoaderFlags;
403 while (pu32Src >= pu32SrcLast)
404 *pu32Dst-- = *pu32Src--;
405
406 /* The previous 4 fields are 32/64 and needs special attention. */
407 pOptHdr64->SizeOfHeapCommit = pOptHdr32->SizeOfHeapCommit;
408 pOptHdr64->SizeOfHeapReserve = pOptHdr32->SizeOfHeapReserve;
409 pOptHdr64->SizeOfStackCommit = pOptHdr32->SizeOfStackCommit;
410 u32 = pOptHdr32->SizeOfStackReserve;
411 pOptHdr64->SizeOfStackReserve = u32;
412
413 /*
414 * The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version.
415 * Thus, ImageBase needs some special treatement. It will probably work fine assigning one to the
416 * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
417 */
418 u32 = pOptHdr32->ImageBase;
419 pOptHdr64->ImageBase = u32;
420}
421
422
423/**
424 * Converts a 32-bit load config directory to a 64 bit one.
425 *
426 * @param pOptHdr The load config to convert.
427 */
428static void kldrModPEConvertLoadConfig(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
429{
430 /* volatile everywhere! */
431 IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
432 IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
433 uint32_t u32;
434
435 pLoadCfg64->SEHandlerCount = pLoadCfg32->SEHandlerCount;
436 pLoadCfg64->SEHandlerTable = pLoadCfg32->SEHandlerTable;
437 pLoadCfg64->SecurityCookie = pLoadCfg32->SecurityCookie;
438 pLoadCfg64->EditList = pLoadCfg32->EditList;
439 pLoadCfg64->Reserved1 = pLoadCfg32->Reserved1;
440 pLoadCfg64->CSDVersion = pLoadCfg32->CSDVersion;
441 /* (ProcessHeapFlags switched place with ProcessAffinityMask, but we're
442 * more than 16 byte off by now so it doesn't matter.) */
443 pLoadCfg64->ProcessHeapFlags = pLoadCfg32->ProcessHeapFlags;
444 pLoadCfg64->ProcessAffinityMask = pLoadCfg32->ProcessAffinityMask;
445 pLoadCfg64->VirtualMemoryThreshold = pLoadCfg32->VirtualMemoryThreshold;
446 pLoadCfg64->MaximumAllocationSize = pLoadCfg32->MaximumAllocationSize;
447 pLoadCfg64->LockPrefixTable = pLoadCfg32->LockPrefixTable;
448 pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
449 u32 = pLoadCfg32->DeCommitFreeBlockThreshold;
450 pLoadCfg64->DeCommitFreeBlockThreshold = u32;
451 /* the remainder matches. */
452}
453
454
455/** @copydoc KLDRMODOPS::pfnDestroy */
456static int kldrModPEDestroy(PKLDRMOD pMod)
457{
458 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
459 int rc = 0;
460 KLDRMODPE_ASSERT(pModPE->fMapped);
461
462 if (pMod->pRdr)
463 {
464 rc = kLdrRdrClose(pMod->pRdr);
465 pMod->pRdr = NULL;
466 }
467 pMod->u32Magic = 0;
468 pMod->pOps = NULL;
469 kldrHlpFree(pModPE);
470 return rc;
471}
472
473
474/**
475 * Gets usable bits and the right base address.
476 *
477 * @returns 0 on success.
478 * @returns A non-zero status code if the BaseAddress isn't right or some problem is encountered
479 * featch in a temp mapping the bits.
480 * @param pModPE The interpreter module instance
481 * @param ppvBits The bits address, IN & OUT.
482 * @param pBaseAddress The base address, IN & OUT. Optional.
483 */
484static int kldrModPEBitsAndBaseAddress(PKLDRMODPE pModPE, const void **ppvBits, PKLDRADDR pBaseAddress)
485{
486 int rc = 0;
487
488 /*
489 * Correct the base address.
490 *
491 * We don't use the base address for interpreting the bits in this
492 * interpreter, which makes things relativly simple.
493 */
494 if (pBaseAddress)
495 {
496 if (*pBaseAddress == KLDRMOD_BASEADDRESS_MAP)
497 *pBaseAddress = pModPE->pMod->aSegments[0].MapAddress;
498 else if (*pBaseAddress == KLDRMOD_BASEADDRESS_LINK)
499 *pBaseAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
500 }
501
502 /*
503 * Get bits.
504 */
505 if (!*ppvBits)
506 {
507 if (pModPE->fMapped)
508 *ppvBits = (void *)(uintptr_t)pModPE->pMod->aSegments[0].MapAddress;
509 else if (pModPE->pvBits)
510 *ppvBits = pModPE->pvBits;
511 else
512 {
513 /** @todo do an internal mapping. */
514 rc = -1;
515 }
516 }
517
518 return 0;
519}
520
521
522/** @copydoc kLdrModQuerySymbol */
523static int kldrModPEQuerySymbol(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, uint32_t uSymbol,
524 const char *pszSymbol, PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser,
525 PKLDRADDR puValue, uint32_t *pfKind)
526{
527 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
528 const uint32_t *paExportRVAs;
529 const IMAGE_EXPORT_DIRECTORY *pExpDir;
530 uint32_t iExpOrd;
531 uint32_t uRVA;
532 int rc;
533
534 /*
535 * Make sure we've got mapped bits and resolve any base address aliases.
536 */
537 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
538 if (rc)
539 return rc;
540 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
541 < sizeof(IMAGE_EXPORT_DIRECTORY))
542 return KLDR_ERR_SYMBOL_NOT_FOUND;
543
544 pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
545 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
546 PIMAGE_EXPORT_DIRECTORY);
547 if (!pszSymbol)
548 {
549 /*
550 * Simple, calculate the unbased ordinal and bounds check it.
551 */
552 iExpOrd = uSymbol - pExpDir->Base;
553 if (iExpOrd >= KLDR_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions))
554 return KLDR_ERR_SYMBOL_NOT_FOUND;
555 }
556 else
557 {
558 /*
559 * Do a binary search for the name.
560 * (The name table is sorted in ascending ordered by the linker.)
561 */
562 const uint32_t *paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const uint32_t *);
563 const uint16_t *paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const uint16_t *);
564 int32_t iStart = 1; /* one based binary searching is simpler. */
565 int32_t iEnd = pExpDir->NumberOfNames;
566
567 for (;;)
568 {
569 int32_t i;
570 int diff;
571 const char *pszName;
572
573 /* done? */
574 if (iStart > iEnd)
575 {
576#ifdef KLDRMODPE_STRICT /* Make sure the linker and we both did our job right. */
577 for (i = 0; i < pExpDir->NumberOfNames; i++)
578
579 {
580 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i], const char *);
581 KLDRMODPE_ASSERT(kLdrHlpStrComp(pszName, pszSymbol));
582 KLDRMODPE_ASSERT(i == 0 || kLdrHlpStrComp(pszName, KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *)));
583 }
584#endif
585 return KLDR_ERR_SYMBOL_NOT_FOUND;
586 }
587
588 i = (iEnd - iStart) / 2 + iStart;
589 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *);
590 diff = kLdrHlpStrComp(pszName, pszSymbol);
591 if (diff < 0)
592 iStart = i + 1; /* The symbol must be after the current name. */
593 else if (diff)
594 iEnd = i - 1; /* The symbol must be before the current name. */
595 else
596 {
597 iExpOrd = paOrdinals[i - 1]; /* match! */
598 break;
599 }
600 }
601 }
602
603 /*
604 * Lookup the address in the 'symbol' table.
605 */
606 paExportRVAs = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const uint32_t *);
607 uRVA = paExportRVAs[iExpOrd];
608 if ( uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
609 < pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
610 return kldrModPEQueryForwarder(pModPE, pvBits, KLDRMODPE_RVA2TYPE(pvBits, uRVA, const char *),
611 pfnGetForwarder, pvUser, puValue, pfKind);
612
613 /*
614 * Set the return value.
615 */
616 if (puValue)
617 *puValue = BaseAddress + uRVA;
618 if (pfKind)
619 *pfKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
620 ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
621 | KLDRSYMKIND_NO_TYPE;
622 return 0;
623}
624
625
626/**
627 * Deal with a forwarder entry.
628 *
629 * We do this seprately from kldrModPEQuerySymbol because the code is clumsy (as is all PE code
630 * thanks to the descriptive field names), and because it uses quite a bit more stack and we're
631 * trying to avoid allocating stack unless we have to.
632 *
633 * @returns See kLdrModQuerySymbol.
634 * @param pModPE The PE module interpreter instance.
635 * @param pvBits Where to read the image from.
636 * @param pszForwarder The forwarder entry name.
637 * @param pfnGetForwarder The callback for resolving forwarder symbols. (optional)
638 * @param pvUser The user argument for the callback.
639 * @param puValue Where to put the value. (optional)
640 * @param pfKind Where to put the symbol kind. (optional)
641 */
642static int kldrModPEQueryForwarder(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
643 PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser, PKLDRADDR puValue, uint32_t *pfKind)
644{
645 const IMAGE_IMPORT_DESCRIPTOR *paImpDir;
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 if ( !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
721 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
722 return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
723 paImpDir = KLDRMODPE_RVA2TYPE(pvBits,
724 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
725 const IMAGE_IMPORT_DESCRIPTOR *);
726
727 kldrModPENumberOfImports(pModPE->pMod, pvBits);
728 for (iImpModule = 0; iImpModule < pModPE->cImportModules; iImpModule++)
729 {
730 const char *pszName = KLDRMODPE_RVA2TYPE(pvBits, paImpDir[iImpModule].Name, const char *);
731 size_t cchName = kLdrHlpStrLen(pszName);
732 if ( ( cchName == cchImpModule
733 || ( cchName > cchImpModule
734 && pszName[cchImpModule] == '.'
735 && (pszName[cchImpModule + 1] == 'd' || pszName[cchImpModule + 1] == 'D')
736 && (pszName[cchImpModule + 2] == 'l' || pszName[cchImpModule + 2] == 'L')
737 && (pszName[cchImpModule + 3] == 'l' || pszName[cchImpModule + 3] == 'L'))
738 )
739 && kLdrHlpMemIComp(pszName, pszForwarder, cchImpModule)
740 )
741 {
742 /*
743 * Now the rest is up to the callback (almost).
744 */
745 rc = pfnGetForwarder(pModPE->pMod, iImpModule, uSymbol, pszSymbol, puValue, pfKind, pvUser);
746 if (!rc && pfKind)
747 *pfKind |= KLDRSYMKIND_FORWARDER;
748 return rc;
749 }
750 }
751 return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
752}
753
754
755/** @copydoc kLdrModEnumSymbols */
756static int kldrModPEEnumSymbols(PKLDRMOD pMod, uint32_t fFlags, const void *pvBits, KLDRADDR BaseAddress,
757 PFNKLDRMODENUMSYMS pfnCallback, void *pvUser)
758{
759 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
760 const uint32_t *paFunctions;
761 const IMAGE_EXPORT_DIRECTORY *pExpDir;
762 const uint32_t *paRVANames;
763 const uint16_t *paOrdinals;
764 uint32_t iFunction;
765 uint32_t cFunctions;
766 uint32_t cNames;
767 int rc;
768
769 /*
770 * Make sure we've got mapped bits and resolve any base address aliases.
771 */
772 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
773 if (rc)
774 return rc;
775
776 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
777 < sizeof(IMAGE_EXPORT_DIRECTORY))
778 return KLDR_ERR_SYMBOL_NOT_FOUND;
779 pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
780 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
781 PIMAGE_EXPORT_DIRECTORY);
782
783 /*
784 * Enumerate the ordinal exports.
785 */
786 paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const uint32_t *);
787 paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const uint16_t *);
788 paFunctions = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const uint32_t *);
789 cFunctions = pExpDir->NumberOfFunctions;
790 cNames = pExpDir->NumberOfNames;
791 for (iFunction = 0; iFunction < cFunctions; iFunction++)
792 {
793 unsigned fFoundName;
794 uint32_t iName;
795 const uint32_t uRVA = paFunctions[iFunction];
796 const KLDRADDR uValue = BaseAddress + uRVA;
797 uint32_t fKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
798 ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
799 | KLDRSYMKIND_NO_TYPE;
800 if ( uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
801 < pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
802 fKind |= KLDRSYMKIND_FORWARDER;
803
804 /*
805 * Any symbol names?
806 */
807 fFoundName = 0;
808 for (iName = 0; iName < cNames; iName++)
809 {
810 if (!paOrdinals[iName] != iFunction)
811 continue;
812 fFoundName = 1;
813 rc = pfnCallback(pMod, iName + pExpDir->Base, KLDRMODPE_RVA2TYPE(pvBits, paRVANames[iName], const char *),
814 uValue, fKind, pvUser);
815 if (rc)
816 return rc;
817 }
818
819 /*
820 * If no names, call once with the ordinal only.
821 */
822 if (!fFoundName)
823 {
824 rc = pfnCallback(pMod, iName + pExpDir->Base, NULL, uValue, fKind, pvUser);
825 if (rc)
826 return rc;
827 }
828 }
829
830 return 0;
831}
832
833
834/** @copydoc kLdrModGetImport */
835static int kldrModPEGetImport(PKLDRMOD pMod, void *pvBits, uint32_t iImport, char *pszName, size_t cchName)
836{
837 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
838 const IMAGE_IMPORT_DESCRIPTOR *pImpDesc;
839 const char *pszImportName;
840 size_t cchImportName;
841 int rc;
842
843 /*
844 * Make sure we've got mapped bits and resolve any base address aliases.
845 */
846 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL);
847 if (rc)
848 return rc;
849
850 /*
851 * Simple bounds check.
852 */
853 if (iImport >= (uint32_t)kldrModPENumberOfImports(pMod, pvBits))
854 return KLDR_ERR_IMPORT_ORDINAL_OUT_OF_BOUNDS;
855
856 /*
857 * Get the name.
858 */
859 pImpDesc = KLDRMODPE_RVA2TYPE(pvBits,
860 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress
861 + sizeof(IMAGE_IMPORT_DESCRIPTOR) * iImport,
862 const IMAGE_IMPORT_DESCRIPTOR *);
863 pszImportName = KLDRMODPE_RVA2TYPE(pvBits, pImpDesc->Name, const char *);
864 cchImportName = strlen(pszImportName);
865 if (cchImportName < cchName)
866 {
867 kLdrHlpMemCopy(pszName, pszImportName, cchImportName + 1);
868 rc = 0;
869 }
870 else
871 {
872 kLdrHlpMemCopy(pszName, pszImportName, cchName);
873 if (cchName)
874 pszName[cchName - 1] = '\0';
875 rc = KLDR_ERR_BUFFER_OVERFLOW;
876 }
877
878 return rc;
879}
880
881
882/** @copydoc kLdrModNumberOfImports */
883static int32_t kldrModPENumberOfImports(PKLDRMOD pMod, const void *pvBits)
884{
885 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
886 if (pModPE->cImportModules == ~(uint32_t)0)
887 {
888 /*
889 * We'll have to walk the import descriptors to figure out their number.
890 * First, make sure we've got mapped bits and resolve any base address aliases.
891 */
892 if (kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL))
893 return -1;
894 pModPE->cImportModules = 0;
895 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
896 && pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
897 {
898 const IMAGE_IMPORT_DESCRIPTOR *pImpDesc;
899
900 pImpDesc = KLDRMODPE_RVA2TYPE(pvBits,
901 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
902 const IMAGE_IMPORT_DESCRIPTOR *);
903 while (pImpDesc->Name && pImpDesc->FirstThunk)
904 {
905 pModPE->cImportModules = 0;
906 pImpDesc++;
907 }
908 }
909 }
910 return pModPE->cImportModules;
911}
912
913
914/** @copydoc kLdrModGetStackInfo */
915static int kldrModPEGetStackInfo(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, PKLDRSTACKINFO pStackInfo)
916{
917 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
918
919 pStackInfo->Address = NIL_KLDRADDR;
920 pStackInfo->LinkAddress = NIL_KLDRADDR;
921 pStackInfo->cbStack = pStackInfo->cbStackThread = pModPE->Hdrs.OptionalHeader.SizeOfStackReserve;
922
923 return 0;
924}
925
926
927/** @copydoc kLdrModQueryMainEntrypoint */
928static int kldrModPEQueryMainEntrypoint(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, PKLDRADDR pMainEPAddress)
929{
930 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
931 int rc;
932
933 rc = kldrModPEBitsAndBaseAddress(pModPE, NULL, &BaseAddress);
934 if (rc)
935 return rc;
936
937 *pMainEPAddress = pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint
938 ? BaseAddress + pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint
939 : NIL_KLDRADDR;
940 return 0;
941}
942
943
944/** @copydoc kLdrModEnumDbgInfo */
945int (* pfnEnumDbgInfo)(PKLDRMOD pMod, const void *pvBits, PFNKLDRENUMDBG pfnCallback, void *pvUser);
946
947/** @copydoc kLdrModHasDbgInfo */
948int (* pfnHasDbgInfo)(PKLDRMOD pMod, const void *pvBits);
949/** @copydoc kLdrModMap */
950int (* pfnMap)(PKLDRMOD pMod);
951/** @copydoc kLdrModUnmap */
952int (* pfnUnmap)(PKLDRMOD pMod);
953/** @copydoc kLdrModAllocTLS */
954int (* pfnAllocTLS)(PKLDRMOD pMod);
955/** @copydoc kLdrModFreeTLS */
956void (* pfnFreeTLS)(PKLDRMOD pMod);
957/** @copydoc kLdrModReload */
958int (* pfnReload)(PKLDRMOD pMod);
959/** @copydoc kLdrModFixupMapping */
960int (* pfnFixupMapping)(PKLDRMOD pMod, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
961/** @copydoc kLdrModCallInit */
962int (* pfnCallInit)(PKLDRMOD pMod);
963/** @copydoc kLdrModCallTerm */
964int (* pfnCallTerm)(PKLDRMOD pMod);
965/** @copydoc kLdrModCallThread */
966int (* pfnCallThread)(PKLDRMOD pMod, unsigned fAttachingOrDetaching);
967/** @copydoc kLdrModSize */
968size_t (* pfnSize)(PKLDRMOD pMod);
969/** @copydoc kLdrModGetBits */
970int (* pfnGetBits)(PKLDRMOD pMod, void *pvBits, KLDRADDR BaseAddress, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
971/** @copydoc kLdrModRelocateBits */
972int (* pfnRelocateBits)(PKLDRMOD pMod, void *pvBits, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress,
973 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
974
Note: See TracBrowser for help on using the repository browser.