source: trunk/kLdr/kLdrModPE.c@ 23

Last change on this file since 23 was 2, checked in by bird, 18 years ago

Imported http://svn.netlabs.org/repos/libc/trunk/kStuff, revision 3612.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 68.6 KB
Line 
1/* $Id: kLdrModPE.c 2 2007-11-16 16:07:14Z bird $ */
2/** @file
3 * kLdr - The Module Interpreter for the Portable Executable (PE) Format.
4 */
5
6/*
7 * Copyright (c) 2006-2007 knut st. osmundsen <bird-kStuff-spam@anduin.net>
8 *
9 * This file is part of kStuff.
10 *
11 * kStuff is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
15 *
16 * In addition to the permissions in the GNU Lesser General Public
17 * License, you are granted unlimited permission to link the compiled
18 * version of this file into combinations with other programs, and to
19 * distribute those combinations without any restriction coming from
20 * the use of this file.
21 *
22 * kStuff is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 * Lesser General Public License for more details.
26 *
27 * You should have received a copy of the GNU Lesser General Public
28 * License along with kStuff; if not, write to the Free Software
29 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
30 * 02110-1301, USA
31 */
32
33/*******************************************************************************
34* Header Files *
35*******************************************************************************/
36#include <k/kLdr.h>
37#include "kLdrInternal.h"
38#include <k/kLdrFmts/pe.h>
39
40
41/*******************************************************************************
42* Defined Constants And Macros *
43*******************************************************************************/
44/** @def KLDRMODPE_STRICT
45 * Define KLDRMODPE_STRICT to enabled strict checks in KLDRMODPE. */
46#define KLDRMODPE_STRICT 1
47
48/** @def KLDRMODPE_ASSERT
49 * Assert that an expression is true when KLDR_STRICT is defined.
50 */
51#ifdef KLDRMODPE_STRICT
52# define KLDRMODPE_ASSERT(expr) kHlpAssert(expr)
53#else
54# define KLDRMODPE_ASSERT(expr) do {} while (0)
55#endif
56
57/** @def KLDRMODPE_RVA2TYPE
58 * Converts a RVA to a pointer of the specified type.
59 * @param pvBits The bits (image base).
60 * @param uRVA The image relative virtual address.
61 * @param type The type to cast to.
62 */
63#define KLDRMODPE_RVA2TYPE(pvBits, uRVA, type) \
64 ( (type) ((KUPTR)(pvBits) + (KUPTR)(uRVA)) )
65
66/** @def KLDRMODPE_VALID_RVA
67 * Checks that the specified RVA value is non-zero and within the bounds of the image.
68 * @returns true/false.
69 * @param pModPE The PE module interpreter instance.
70 * @param uRVA The RVA to validate.
71 */
72#define KLDRMODPE_VALID_RVA(pModPE, uRVA) \
73 ( (uRVA) && (uRVA) < (pModPE)->Hdrs.OptionalHeader.SizeOfImage )
74
75
76
77/*******************************************************************************
78* Structures and Typedefs *
79*******************************************************************************/
80/**
81 * Instance data for the PE module interpreter.
82 */
83typedef struct KLDRMODPE
84{
85 /** Pointer to the module. (Follows the section table.) */
86 PKLDRMOD pMod;
87 /** Pointer to the RDR mapping of the raw file bits. NULL if not mapped. */
88 const void *pvBits;
89 /** Pointer to the user mapping. */
90 const void *pvMapping;
91 /** Reserved flags. */
92 KU32 f32Reserved;
93 /** The number of imported modules.
94 * If ~(KU32)0 this hasn't been determined yet. */
95 KU32 cImportModules;
96 /** The offset of the NT headers. */
97 KLDRFOFF offHdrs;
98 /** Copy of the NT headers. */
99 IMAGE_NT_HEADERS64 Hdrs;
100 /** The section header table . */
101 IMAGE_SECTION_HEADER aShdrs[1];
102} KLDRMODPE, *PKLDRMODPE;
103
104
105/*******************************************************************************
106* Internal Functions *
107*******************************************************************************/
108static KI32 kldrModPENumberOfImports(PKLDRMOD pMod, const void *pvBits);
109static int kldrModPERelocateBits(PKLDRMOD pMod, void *pvBits, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress,
110 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
111
112static int kldrModPEDoCreate(PKRDR pRdr, KLDRFOFF offNewHdr, PKLDRMODPE *ppMod);
113/*static void kldrModPEDoLoadConfigConversion(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg); */
114static int kLdrModPEDoOptionalHeaderValidation(PKLDRMODPE pModPE);
115static int kLdrModPEDoSectionHeadersValidation(PKLDRMODPE pModPE);
116static void kldrModPEDoOptionalHeaderConversion(PIMAGE_OPTIONAL_HEADER64 pOptionalHeader);
117static int kldrModPEDoForwarderQuery(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
118 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser, PKLDRADDR puValue, KU32 *pfKind);
119static int kldrModPEDoFixups(PKLDRMODPE pModPE, void *pvMapping, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress);
120static int kldrModPEDoImports32Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
121 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
122static int kldrModPEDoImports64Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
123 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
124static int kldrModPEDoImports(PKLDRMODPE pModPE, void *pvMapping, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser);
125static int kldrModPEDoCallDLL(PKLDRMODPE pModPE, unsigned uOp, KUPTR uHandle);
126static int kldrModPEDoCallTLS(PKLDRMODPE pModPE, unsigned uOp, KUPTR uHandle);
127static KI32 kldrModPEDoCall(KUPTR uEntrypoint, KUPTR uHandle, KU32 uOp, void *pvReserved);
128
129
130/**
131 * Create a loader module instance interpreting the executable image found
132 * in the specified file provider instance.
133 *
134 * @returns 0 on success and *ppMod pointing to a module instance.
135 * On failure, a non-zero OS specific error code is returned.
136 * @param pOps Pointer to the registered method table.
137 * @param pRdr The file provider instance to use.
138 * @param offNewHdr The offset of the new header in MZ files. -1 if not found.
139 * @param ppMod Where to store the module instance pointer.
140 */
141static int kldrModPECreate(PCKLDRMODOPS pOps, PKRDR pRdr, KLDRFOFF offNewHdr, PPKLDRMOD ppMod)
142{
143 PKLDRMODPE pModPE;
144 int rc;
145
146 /*
147 * Create the instance data and do a minimal header validation.
148 */
149 rc = kldrModPEDoCreate(pRdr, offNewHdr, &pModPE);
150 if (!rc)
151 {
152 pModPE->pMod->pOps = pOps;
153 pModPE->pMod->u32Magic = KLDRMOD_MAGIC;
154 *ppMod = pModPE->pMod;
155 return 0;
156 }
157 kHlpFree(pModPE);
158 return rc;
159}
160
161
162/**
163 * Separate function for reading creating the PE module instance to
164 * simplify cleanup on failure.
165 */
166static int kldrModPEDoCreate(PKRDR pRdr, KLDRFOFF offNewHdr, PKLDRMODPE *ppModPE)
167{
168 struct
169 {
170 KU32 Signature;
171 IMAGE_FILE_HEADER FileHdr;
172 } s;
173 PKLDRMODPE pModPE;
174 PKLDRMOD pMod;
175 KSIZE cb;
176 KSIZE cchFilename;
177 KLDRFOFF off;
178 KU32 i;
179 int rc;
180 *ppModPE = NULL;
181
182 /*
183 * Read the signature and file header.
184 */
185 rc = kRdrRead(pRdr, &s, sizeof(s), offNewHdr > 0 ? offNewHdr : 0);
186 if (rc)
187 return rc;
188 if (s.Signature != IMAGE_NT_SIGNATURE)
189 return KLDR_ERR_UNKNOWN_FORMAT;
190
191 /* sanity checks. */
192 if ( s.FileHdr.NumberOfSections > 4096
193 || ( s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)
194 && s.FileHdr.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER64))
195 || !(s.FileHdr.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)
196 )
197 return KLDR_ERR_PE_BAD_FILE_HEADER;
198 if ( s.FileHdr.Machine != IMAGE_FILE_MACHINE_I386
199 && s.FileHdr.Machine != IMAGE_FILE_MACHINE_AMD64
200 )
201 return KLDR_ERR_PE_UNSUPPORTED_MACHINE;
202
203 /*
204 * Calc the instance size, allocate and initialize it.
205 */
206 cchFilename = kHlpStrLen(kRdrName(pRdr));
207 cb = K_ALIGN_Z(K_OFFSETOF(KLDRMODPE, aShdrs[s.FileHdr.NumberOfSections]), 16)
208 + K_OFFSETOF(KLDRMOD, aSegments[s.FileHdr.NumberOfSections + 1])
209 + cchFilename + 1;
210 pModPE = (PKLDRMODPE)kHlpAlloc(cb);
211 if (!pModPE)
212 return KERR_NO_MEMORY;
213 *ppModPE = pModPE;
214
215 /* KLDRMOD */
216 pMod = (PKLDRMOD)((KU8 *)pModPE + K_ALIGN_Z(K_OFFSETOF(KLDRMODPE, aShdrs[s.FileHdr.NumberOfSections]), 16));
217 pMod->pvData = pModPE;
218 pMod->pRdr = pRdr;
219 pMod->pOps = NULL; /* set upon success. */
220 pMod->cSegments = s.FileHdr.NumberOfSections + 1;
221 pMod->cchFilename = cchFilename;
222 pMod->pszFilename = (char *)&pMod->aSegments[pMod->cSegments];
223 kHlpMemCopy((char *)pMod->pszFilename, kRdrName(pRdr), cchFilename + 1);
224 pMod->pszName = kHlpGetFilename(pMod->pszFilename);
225 pMod->cchName = cchFilename - (pMod->pszName - pMod->pszFilename);
226 switch (s.FileHdr.Machine)
227 {
228 case IMAGE_FILE_MACHINE_I386:
229 pMod->enmCpu = KCPU_I386;
230 pMod->enmArch = KCPUARCH_X86_32;
231 pMod->enmEndian = KLDRENDIAN_LITTLE;
232 break;
233
234 case IMAGE_FILE_MACHINE_AMD64:
235 pMod->enmCpu = KCPU_K8;
236 pMod->enmArch = KCPUARCH_AMD64;
237 pMod->enmEndian = KLDRENDIAN_LITTLE;
238 break;
239 default:
240 kHlpAssert(0);
241 break;
242 }
243 pMod->enmFmt = KLDRFMT_PE;
244 if (s.FileHdr.Characteristics & IMAGE_FILE_DLL)
245 pMod->enmType = !(s.FileHdr.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
246 ? KLDRTYPE_SHARED_LIBRARY_RELOCATABLE
247 : KLDRTYPE_SHARED_LIBRARY_FIXED;
248 else
249 pMod->enmType = !(s.FileHdr.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
250 ? KLDRTYPE_EXECUTABLE_RELOCATABLE
251 : KLDRTYPE_EXECUTABLE_FIXED;
252 pMod->u32Magic = 0; /* set upon success. */
253
254 /* KLDRMODPE */
255 pModPE->pMod = pMod;
256 pModPE->pvBits = NULL;
257 pModPE->pvMapping = NULL;
258 pModPE->f32Reserved = 0;
259 pModPE->cImportModules = ~(KU32)0;
260 pModPE->offHdrs = offNewHdr >= 0 ? offNewHdr : 0;
261 pModPE->Hdrs.Signature = s.Signature;
262 pModPE->Hdrs.FileHeader = s.FileHdr;
263
264 /*
265 * Read the optional header and the section table.
266 */
267 off = pModPE->offHdrs + sizeof(pModPE->Hdrs.Signature) + sizeof(pModPE->Hdrs.FileHeader);
268 rc = kRdrRead(pRdr, &pModPE->Hdrs.OptionalHeader, pModPE->Hdrs.FileHeader.SizeOfOptionalHeader, off);
269 if (rc)
270 return rc;
271 if (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader != sizeof(pModPE->Hdrs.OptionalHeader))
272 kldrModPEDoOptionalHeaderConversion(&pModPE->Hdrs.OptionalHeader);
273 off += pModPE->Hdrs.FileHeader.SizeOfOptionalHeader;
274 rc = kRdrRead(pRdr, &pModPE->aShdrs[0], sizeof(IMAGE_SECTION_HEADER) * pModPE->Hdrs.FileHeader.NumberOfSections, off);
275 if (rc)
276 return rc;
277
278 /*
279 * Validate the two.
280 */
281 rc = kLdrModPEDoOptionalHeaderValidation(pModPE);
282 if (rc)
283 return rc;
284 for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
285 {
286 rc = kLdrModPEDoSectionHeadersValidation(pModPE);
287 if (rc)
288 return rc;
289 }
290
291 /*
292 * Setup the KLDRMOD segment array.
293 */
294 /* The implied headers section. */
295 pMod->aSegments[0].pvUser = NULL;
296 pMod->aSegments[0].pchName = "TheHeaders";
297 pMod->aSegments[0].cchName = sizeof("TheHeaders") - 1;
298 pMod->aSegments[0].enmProt = KPROT_READONLY;
299 pMod->aSegments[0].cb = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
300 pMod->aSegments[0].Alignment = pModPE->Hdrs.OptionalHeader.SectionAlignment;
301 pMod->aSegments[0].LinkAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
302 pMod->aSegments[0].offFile = 0;
303 pMod->aSegments[0].cbFile = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
304 pMod->aSegments[0].RVA = 0;
305 if (pMod->cSegments > 1)
306 pMod->aSegments[0].cbMapped = pModPE->aShdrs[0].VirtualAddress;
307 else
308 pMod->aSegments[0].cbMapped = pModPE->Hdrs.OptionalHeader.SizeOfHeaders;
309 pMod->aSegments[0].MapAddress = 0;
310
311 /* The section headers. */
312 for (i = 0; i < pModPE->Hdrs.FileHeader.NumberOfSections; i++)
313 {
314 const char *pch;
315
316 /* unused */
317 pMod->aSegments[i + 1].pvUser = NULL;
318 pMod->aSegments[i + 1].MapAddress = 0;
319 pMod->aSegments[i + 1].SelFlat = 0;
320 pMod->aSegments[i + 1].Sel16bit = 0;
321 pMod->aSegments[i + 1].fFlags = 0;
322
323 /* name */
324 pMod->aSegments[i + 1].pchName = pch = (const char *)&pModPE->aShdrs[i].Name[0];
325 cb = IMAGE_SIZEOF_SHORT_NAME;
326 while ( cb > 0
327 && (pch[cb - 1] == ' ' || pch[cb - 1] == '\0'))
328 cb--;
329 pMod->aSegments[i + 1].cchName = cb;
330
331 /* size and addresses */
332 if (!(pModPE->aShdrs[i].Characteristics & IMAGE_SCN_TYPE_NOLOAD))
333 {
334 pMod->aSegments[i + 1].cb = pModPE->aShdrs[i].Misc.VirtualSize;
335 pMod->aSegments[i + 1].LinkAddress = pModPE->aShdrs[i].VirtualAddress
336 + pModPE->Hdrs.OptionalHeader.ImageBase;
337 pMod->aSegments[i + 1].RVA = pModPE->aShdrs[i].VirtualAddress;
338 pMod->aSegments[i + 1].cbMapped = pModPE->aShdrs[i].Misc.VirtualSize;
339 if (i + 2 < pMod->cSegments)
340 pMod->aSegments[i + 1].cbMapped= pModPE->aShdrs[i + 1].VirtualAddress
341 - pModPE->aShdrs[i].VirtualAddress;
342 }
343 else
344 {
345 pMod->aSegments[i + 1].cb = 0;
346 pMod->aSegments[i + 1].cbMapped = 0;
347 pMod->aSegments[i + 1].LinkAddress = NIL_KLDRADDR;
348 pMod->aSegments[i + 1].RVA = 0;
349 }
350
351 /* file location */
352 pMod->aSegments[i + 1].offFile = pModPE->aShdrs[i].PointerToRawData;
353 pMod->aSegments[i + 1].cbFile = pModPE->aShdrs[i].SizeOfRawData;
354 if ( pMod->aSegments[i + 1].cbMapped > 0 /* if mapped */
355 && (KLDRSIZE)pMod->aSegments[i + 1].cbFile > pMod->aSegments[i + 1].cbMapped)
356 pMod->aSegments[i + 1].cbFile = pMod->aSegments[i + 1].cbMapped;
357
358 /* protection */
359 switch ( pModPE->aShdrs[i].Characteristics
360 & (IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE))
361 {
362 case 0:
363 case IMAGE_SCN_MEM_SHARED:
364 pMod->aSegments[i + 1].enmProt = KPROT_NOACCESS;
365 break;
366 case IMAGE_SCN_MEM_READ:
367 case IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
368 pMod->aSegments[i + 1].enmProt = KPROT_READONLY;
369 break;
370 case IMAGE_SCN_MEM_WRITE:
371 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
372 pMod->aSegments[i + 1].enmProt = KPROT_WRITECOPY;
373 break;
374 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
375 case IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
376 pMod->aSegments[i + 1].enmProt = KPROT_READWRITE;
377 break;
378 case IMAGE_SCN_MEM_EXECUTE:
379 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_SHARED:
380 pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE;
381 break;
382 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ:
383 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_SHARED:
384 pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE_READ;
385 break;
386 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE:
387 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ:
388 pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE_WRITECOPY;
389 break;
390 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED:
391 case IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_SHARED | IMAGE_SCN_MEM_READ:
392 pMod->aSegments[i + 1].enmProt = KPROT_EXECUTE_READWRITE;
393 break;
394 }
395
396 /* alignment. */
397 switch (pModPE->aShdrs[i].Characteristics & IMAGE_SCN_ALIGN_MASK)
398 {
399 case 0: /* hope this is right... */
400 pMod->aSegments[i + 1].Alignment = pModPE->Hdrs.OptionalHeader.SectionAlignment;
401 break;
402 case IMAGE_SCN_ALIGN_1BYTES: pMod->aSegments[i + 1].Alignment = 1; break;
403 case IMAGE_SCN_ALIGN_2BYTES: pMod->aSegments[i + 1].Alignment = 2; break;
404 case IMAGE_SCN_ALIGN_4BYTES: pMod->aSegments[i + 1].Alignment = 4; break;
405 case IMAGE_SCN_ALIGN_8BYTES: pMod->aSegments[i + 1].Alignment = 8; break;
406 case IMAGE_SCN_ALIGN_16BYTES: pMod->aSegments[i + 1].Alignment = 16; break;
407 case IMAGE_SCN_ALIGN_32BYTES: pMod->aSegments[i + 1].Alignment = 32; break;
408 case IMAGE_SCN_ALIGN_64BYTES: pMod->aSegments[i + 1].Alignment = 64; break;
409 case IMAGE_SCN_ALIGN_128BYTES: pMod->aSegments[i + 1].Alignment = 128; break;
410 case IMAGE_SCN_ALIGN_256BYTES: pMod->aSegments[i + 1].Alignment = 256; break;
411 case IMAGE_SCN_ALIGN_512BYTES: pMod->aSegments[i + 1].Alignment = 512; break;
412 case IMAGE_SCN_ALIGN_1024BYTES: pMod->aSegments[i + 1].Alignment = 1024; break;
413 case IMAGE_SCN_ALIGN_2048BYTES: pMod->aSegments[i + 1].Alignment = 2048; break;
414 case IMAGE_SCN_ALIGN_4096BYTES: pMod->aSegments[i + 1].Alignment = 4096; break;
415 case IMAGE_SCN_ALIGN_8192BYTES: pMod->aSegments[i + 1].Alignment = 8192; break;
416 default: kHlpAssert(0); pMod->aSegments[i + 1].Alignment = 0; break;
417 }
418 }
419
420 /*
421 * We're done.
422 */
423 *ppModPE = pModPE;
424 return 0;
425}
426
427
428/**
429 * Converts a 32-bit optional header to a 64-bit one
430 *
431 * @param pOptHdr The optional header to convert.
432 */
433static void kldrModPEDoOptionalHeaderConversion(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
434{
435 /* volatile everywhere! */
436 IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
437 IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
438 KU32 volatile *pu32Dst;
439 KU32 volatile *pu32Src;
440 KU32 volatile *pu32SrcLast;
441 KU32 u32;
442
443 /* From LoaderFlags and out the difference is 4 * 32-bits. */
444 pu32Dst = (KU32 *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
445 pu32Src = (KU32 *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
446 pu32SrcLast = (KU32 *)&pOptHdr32->LoaderFlags;
447 while (pu32Src >= pu32SrcLast)
448 *pu32Dst-- = *pu32Src--;
449
450 /* The previous 4 fields are 32/64 and needs special attention. */
451 pOptHdr64->SizeOfHeapCommit = pOptHdr32->SizeOfHeapCommit;
452 pOptHdr64->SizeOfHeapReserve = pOptHdr32->SizeOfHeapReserve;
453 pOptHdr64->SizeOfStackCommit = pOptHdr32->SizeOfStackCommit;
454 u32 = pOptHdr32->SizeOfStackReserve;
455 pOptHdr64->SizeOfStackReserve = u32;
456
457 /*
458 * The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version.
459 * Thus, ImageBase needs some special treatement. It will probably work fine assigning one to the
460 * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
461 */
462 u32 = pOptHdr32->ImageBase;
463 pOptHdr64->ImageBase = u32;
464}
465
466
467#if 0
468/**
469 * Converts a 32-bit load config directory to a 64 bit one.
470 *
471 * @param pOptHdr The load config to convert.
472 */
473static void kldrModPEDoLoadConfigConversion(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
474{
475 /* volatile everywhere! */
476 IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
477 IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
478 KU32 u32;
479
480 pLoadCfg64->SEHandlerCount = pLoadCfg32->SEHandlerCount;
481 pLoadCfg64->SEHandlerTable = pLoadCfg32->SEHandlerTable;
482 pLoadCfg64->SecurityCookie = pLoadCfg32->SecurityCookie;
483 pLoadCfg64->EditList = pLoadCfg32->EditList;
484 pLoadCfg64->Reserved1 = pLoadCfg32->Reserved1;
485 pLoadCfg64->CSDVersion = pLoadCfg32->CSDVersion;
486 /* (ProcessHeapFlags switched place with ProcessAffinityMask, but we're
487 * more than 16 byte off by now so it doesn't matter.) */
488 pLoadCfg64->ProcessHeapFlags = pLoadCfg32->ProcessHeapFlags;
489 pLoadCfg64->ProcessAffinityMask = pLoadCfg32->ProcessAffinityMask;
490 pLoadCfg64->VirtualMemoryThreshold = pLoadCfg32->VirtualMemoryThreshold;
491 pLoadCfg64->MaximumAllocationSize = pLoadCfg32->MaximumAllocationSize;
492 pLoadCfg64->LockPrefixTable = pLoadCfg32->LockPrefixTable;
493 pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
494 u32 = pLoadCfg32->DeCommitFreeBlockThreshold;
495 pLoadCfg64->DeCommitFreeBlockThreshold = u32;
496 /* the remainder matches. */
497}
498#endif
499
500
501/**
502 * Internal worker which validates the section headers.
503 */
504static int kLdrModPEDoOptionalHeaderValidation(PKLDRMODPE pModPE)
505{
506 const unsigned fIs32Bit = pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32);
507
508 /* the magic */
509 if ( pModPE->Hdrs.OptionalHeader.Magic
510 != (fIs32Bit ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC))
511 return KLDR_ERR_PE_BAD_OPTIONAL_HEADER;
512
513 /** @todo validate more */
514 return 0;
515}
516
517
518/**
519 * Internal worker which validates the section headers.
520 */
521static int kLdrModPEDoSectionHeadersValidation(PKLDRMODPE pModPE)
522{
523 /** @todo validate shdrs */
524 return 0;
525}
526
527
528/** @copydoc KLDRMODOPS::pfnDestroy */
529static int kldrModPEDestroy(PKLDRMOD pMod)
530{
531 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
532 int rc = 0;
533 KLDRMODPE_ASSERT(!pModPE->pvMapping);
534
535 if (pMod->pRdr)
536 {
537 rc = kRdrClose(pMod->pRdr);
538 pMod->pRdr = NULL;
539 }
540 pMod->u32Magic = 0;
541 pMod->pOps = NULL;
542 kHlpFree(pModPE);
543 return rc;
544}
545
546
547/**
548 * Performs the mapping of the image.
549 *
550 * This can be used to do the internal mapping as well as the
551 * user requested mapping. fForReal indicates which is desired.
552 *
553 * @returns 0 on success, non-zero OS or kLdr status code on failure.
554 * @param pModPE The interpreter module instance
555 * @param fForReal If set, do the user mapping. if clear, do the internal mapping.
556 */
557static int kldrModPEDoMap(PKLDRMODPE pModPE, unsigned fForReal)
558{
559 PKLDRMOD pMod = pModPE->pMod;
560 KBOOL fFixed;
561 void *pvBase;
562 int rc;
563 KU32 i;
564
565 /*
566 * Map it.
567 */
568 /* fixed image? */
569 fFixed = fForReal
570 && ( pMod->enmType == KLDRTYPE_EXECUTABLE_FIXED
571 || pMod->enmType == KLDRTYPE_SHARED_LIBRARY_FIXED);
572 if (!fFixed)
573 pvBase = NULL;
574 else
575 {
576 pvBase = (void *)(KUPTR)pMod->aSegments[0].LinkAddress;
577 if ((KUPTR)pvBase != pMod->aSegments[0].LinkAddress)
578 return KLDR_ERR_ADDRESS_OVERFLOW;
579 }
580
581 /* try do the prepare */
582 rc = kRdrMap(pMod->pRdr, &pvBase, pMod->cSegments, pMod->aSegments, fFixed);
583 if (rc)
584 return rc;
585
586 /*
587 * Update the segments with their map addresses.
588 */
589 if (fForReal)
590 {
591 for (i = 0; i < pMod->cSegments; i++)
592 {
593 if (pMod->aSegments[i].RVA != NIL_KLDRADDR)
594 pMod->aSegments[i].MapAddress = (KUPTR)pvBase + (KUPTR)pMod->aSegments[i].RVA;
595 }
596 pModPE->pvMapping = pvBase;
597 }
598 else
599 pModPE->pvBits = pvBase;
600 return 0;
601}
602
603
604/**
605 * Unmaps a image mapping.
606 *
607 * This can be used to do the internal mapping as well as the
608 * user requested mapping. fForReal indicates which is desired.
609 *
610 * @returns 0 on success, non-zero OS or kLdr status code on failure.
611 * @param pModPE The interpreter module instance
612 * @param pvMapping The mapping to unmap.
613 */
614static int kldrModPEDoUnmap(PKLDRMODPE pModPE, const void *pvMapping)
615{
616 PKLDRMOD pMod = pModPE->pMod;
617 int rc;
618 KU32 i;
619
620 /*
621 * Try unmap the image.
622 */
623 rc = kRdrUnmap(pMod->pRdr, (void *)pvMapping, pMod->cSegments, pMod->aSegments);
624 if (rc)
625 return rc;
626
627 /*
628 * Update the segments to reflect that they aren't mapped any longer.
629 */
630 if (pModPE->pvMapping == pvMapping)
631 {
632 pModPE->pvMapping = NULL;
633 for (i = 0; i < pMod->cSegments; i++)
634 pMod->aSegments[i].MapAddress = 0;
635 }
636 if (pModPE->pvBits == pvMapping)
637 pModPE->pvBits = NULL;
638
639 return 0;
640}
641
642
643/**
644 * Gets usable bits and the right base address.
645 *
646 * @returns 0 on success.
647 * @returns A non-zero status code if the BaseAddress isn't right or some problem is encountered
648 * featch in a temp mapping the bits.
649 * @param pModPE The interpreter module instance
650 * @param ppvBits The bits address, IN & OUT.
651 * @param pBaseAddress The base address, IN & OUT. Optional.
652 */
653static int kldrModPEBitsAndBaseAddress(PKLDRMODPE pModPE, const void **ppvBits, PKLDRADDR pBaseAddress)
654{
655 int rc = 0;
656
657 /*
658 * Correct the base address.
659 *
660 * We don't use the base address for interpreting the bits in this
661 * interpreter, which makes things relativly simple.
662 */
663 if (pBaseAddress)
664 {
665 if (*pBaseAddress == KLDRMOD_BASEADDRESS_MAP)
666 *pBaseAddress = pModPE->pMod->aSegments[0].MapAddress;
667 else if (*pBaseAddress == KLDRMOD_BASEADDRESS_LINK)
668 *pBaseAddress = pModPE->Hdrs.OptionalHeader.ImageBase;
669 }
670
671 /*
672 * Get bits.
673 */
674 if (ppvBits && !*ppvBits)
675 {
676 if (pModPE->pvMapping)
677 *ppvBits = pModPE->pvMapping;
678 else if (pModPE->pvBits)
679 *ppvBits = pModPE->pvBits;
680 else
681 {
682 /* create an internal mapping. */
683 rc = kldrModPEDoMap(pModPE, 0 /* not for real */);
684 if (rc)
685 return rc;
686 KLDRMODPE_ASSERT(pModPE->pvBits);
687 *ppvBits = pModPE->pvBits;
688 }
689 }
690
691 return 0;
692}
693
694
695/** @copydoc kLdrModQuerySymbol */
696static int kldrModPEQuerySymbol(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, KU32 iSymbol,
697 const char *pchSymbol, KSIZE cchSymbol, const char *pszVersion,
698 PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser, PKLDRADDR puValue, KU32 *pfKind)
699
700{
701 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
702 const KU32 *paExportRVAs;
703 const IMAGE_EXPORT_DIRECTORY *pExpDir;
704 KU32 iExpOrd;
705 KU32 uRVA;
706 int rc;
707
708 /*
709 * Make sure we've got mapped bits and resolve any base address aliases.
710 */
711 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
712 if (rc)
713 return rc;
714 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
715 < sizeof(IMAGE_EXPORT_DIRECTORY))
716 return KLDR_ERR_SYMBOL_NOT_FOUND;
717 if (pszVersion && *pszVersion)
718 return KLDR_ERR_SYMBOL_NOT_FOUND;
719
720 pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
721 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
722 PIMAGE_EXPORT_DIRECTORY);
723 if (!pchSymbol)
724 {
725 /*
726 * Simple, calculate the unbased ordinal and bounds check it.
727 */
728 iExpOrd = iSymbol - pExpDir->Base;
729 if (iExpOrd >= K_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions))
730 return KLDR_ERR_SYMBOL_NOT_FOUND;
731 }
732 else
733 {
734 /*
735 * Do a binary search for the name.
736 * (The name table is sorted in ascending ordered by the linker.)
737 */
738 const KU32 *paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const KU32 *);
739 const KU16 *paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const KU16 *);
740 KI32 iStart = 1; /* one based binary searching is simpler. */
741 KI32 iEnd = pExpDir->NumberOfNames;
742
743 for (;;)
744 {
745 KI32 i;
746 int diff;
747 const char *pszName;
748
749 /* done? */
750 if (iStart > iEnd)
751 {
752#ifdef KLDRMODPE_STRICT /* Make sure the linker and we both did our job right. */
753 for (i = 0; i < (KI32)pExpDir->NumberOfNames; i++)
754
755 {
756 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i], const char *);
757 KLDRMODPE_ASSERT(kHlpStrNComp(pszName, pchSymbol, cchSymbol) || pszName[cchSymbol]);
758 KLDRMODPE_ASSERT(i == 0 || kHlpStrComp(pszName, KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *)));
759 }
760#endif
761 return KLDR_ERR_SYMBOL_NOT_FOUND;
762 }
763
764 i = (iEnd - iStart) / 2 + iStart;
765 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *);
766 diff = kHlpStrNComp(pszName, pchSymbol, cchSymbol);
767 if (!diff)
768 diff = pszName[cchSymbol] - 0;
769 if (diff < 0)
770 iStart = i + 1; /* The symbol must be after the current name. */
771 else if (diff)
772 iEnd = i - 1; /* The symbol must be before the current name. */
773 else
774 {
775 iExpOrd = paOrdinals[i - 1]; /* match! */
776 break;
777 }
778 }
779 }
780
781 /*
782 * Lookup the address in the 'symbol' table.
783 */
784 paExportRVAs = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const KU32 *);
785 uRVA = paExportRVAs[iExpOrd];
786 if ( uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
787 < pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
788 return kldrModPEDoForwarderQuery(pModPE, pvBits, KLDRMODPE_RVA2TYPE(pvBits, uRVA, const char *),
789 pfnGetForwarder, pvUser, puValue, pfKind);
790
791 /*
792 * Set the return value.
793 */
794 if (puValue)
795 *puValue = BaseAddress + uRVA;
796 if (pfKind)
797 *pfKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
798 ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
799 | KLDRSYMKIND_NO_TYPE;
800 return 0;
801}
802
803
804/**
805 * Deal with a forwarder entry.
806 *
807 * We do this seprately from kldrModPEQuerySymbol because the code is clumsy (as is all PE code
808 * thanks to the descriptive field names), and because it uses quite a bit more stack and we're
809 * trying to avoid allocating stack unless we have to.
810 *
811 * @returns See kLdrModQuerySymbol.
812 * @param pModPE The PE module interpreter instance.
813 * @param pvBits Where to read the image from.
814 * @param pszForwarder The forwarder entry name.
815 * @param pfnGetForwarder The callback for resolving forwarder symbols. (optional)
816 * @param pvUser The user argument for the callback.
817 * @param puValue Where to put the value. (optional)
818 * @param pfKind Where to put the symbol kind. (optional)
819 */
820static int kldrModPEDoForwarderQuery(PKLDRMODPE pModPE, const void *pvBits, const char *pszForwarder,
821 PFNKLDRMODGETIMPORT pfnGetForwarder, void *pvUser, PKLDRADDR puValue, KU32 *pfKind)
822{
823 const IMAGE_IMPORT_DESCRIPTOR *paImpDir;
824 KU32 iImpModule;
825 KU32 cchImpModule;
826 const char *pszSymbol;
827 KU32 iSymbol;
828 int rc;
829
830 if (!pfnGetForwarder)
831 return KLDR_ERR_FORWARDER_SYMBOL;
832
833 /*
834 * Separate the name into a module name and a symbol name or ordinal.
835 *
836 * The module name ends at the first dot ('.').
837 * After the dot follows either a symbol name or a hash ('#') + ordinal.
838 */
839 pszSymbol = pszForwarder;
840 while (*pszSymbol != '.')
841 pszSymbol++;
842 if (!*pszSymbol)
843 return KLDR_ERR_PE_BAD_FORWARDER;
844 cchImpModule = pszSymbol - pszForwarder;
845
846 pszSymbol++; /* skip the dot */
847 if (!*pszSymbol)
848 return KLDR_ERR_PE_BAD_FORWARDER;
849 if (*pszSymbol == '#')
850 {
851 unsigned uBase;
852 pszSymbol++; /* skip the hash */
853
854 /* base detection */
855 uBase = 10;
856 if (pszSymbol[0] == '0' && (pszSymbol[1] == 'x' || pszSymbol[1] == 'X'))
857 {
858 uBase = 16;
859 pszSymbol += 2;
860 }
861
862 /* ascii to integer */
863 iSymbol = 0;
864 for (;;)
865 {
866 /* convert char to digit. */
867 unsigned uDigit = *pszSymbol++;
868 if (uDigit >= '0' && uDigit <= '9')
869 uDigit -= '0';
870 else if (uDigit >= 'a' && uDigit <= 'z')
871 uDigit -= 'a' + 10;
872 else if (uDigit >= 'A' && uDigit <= 'Z')
873 uDigit -= 'A' + 10;
874 else if (!uDigit)
875 break;
876 else
877 return KLDR_ERR_PE_BAD_FORWARDER;
878 if (uDigit >= uBase)
879 return KLDR_ERR_PE_BAD_FORWARDER;
880
881 /* insert the digit */
882 iSymbol *= uBase;
883 iSymbol += uDigit;
884 }
885
886 pszSymbol = NULL; /* no symbol name. */
887 }
888 else
889 iSymbol = NIL_KLDRMOD_SYM_ORDINAL; /* no ordinal number. */
890
891
892 /*
893 * Find the import module name.
894 *
895 * We ASSUME the linker will make sure there is an import
896 * entry for the module... not sure if this is right though.
897 */
898 if ( !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
899 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
900 return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
901 paImpDir = KLDRMODPE_RVA2TYPE(pvBits,
902 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
903 const IMAGE_IMPORT_DESCRIPTOR *);
904
905 kldrModPENumberOfImports(pModPE->pMod, pvBits);
906 for (iImpModule = 0; iImpModule < pModPE->cImportModules; iImpModule++)
907 {
908 const char *pszName = KLDRMODPE_RVA2TYPE(pvBits, paImpDir[iImpModule].Name, const char *);
909 KSIZE cchName = kHlpStrLen(pszName);
910 if ( ( cchName == cchImpModule
911 || ( cchName > cchImpModule
912 && pszName[cchImpModule] == '.'
913 && (pszName[cchImpModule + 1] == 'd' || pszName[cchImpModule + 1] == 'D')
914 && (pszName[cchImpModule + 2] == 'l' || pszName[cchImpModule + 2] == 'L')
915 && (pszName[cchImpModule + 3] == 'l' || pszName[cchImpModule + 3] == 'L'))
916 )
917 && kHlpMemICompAscii(pszName, pszForwarder, cchImpModule)
918 )
919 {
920 /*
921 * Now the rest is up to the callback (almost).
922 */
923 rc = pfnGetForwarder(pModPE->pMod, iImpModule, iSymbol, pszSymbol,
924 pszSymbol ? kHlpStrLen(pszSymbol) : 0, NULL, puValue, pfKind, pvUser);
925 if (!rc && pfKind)
926 *pfKind |= KLDRSYMKIND_FORWARDER;
927 return rc;
928 }
929 }
930 return KLDR_ERR_PE_FORWARDER_IMPORT_NOT_FOUND;
931}
932
933
934/** @copydoc kLdrModEnumSymbols */
935static int kldrModPEEnumSymbols(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress,
936 KU32 fFlags, PFNKLDRMODENUMSYMS pfnCallback, void *pvUser)
937{
938 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
939 const KU32 *paFunctions;
940 const IMAGE_EXPORT_DIRECTORY *pExpDir;
941 const KU32 *paRVANames;
942 const KU16 *paOrdinals;
943 KU32 iFunction;
944 KU32 cFunctions;
945 KU32 cNames;
946 int rc;
947
948 /*
949 * Make sure we've got mapped bits and resolve any base address aliases.
950 */
951 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, &BaseAddress);
952 if (rc)
953 return rc;
954
955 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size
956 < sizeof(IMAGE_EXPORT_DIRECTORY))
957 return 0; /* no exports to enumerate, return success. */
958
959 pExpDir = KLDRMODPE_RVA2TYPE(pvBits,
960 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress,
961 PIMAGE_EXPORT_DIRECTORY);
962
963 /*
964 * Enumerate the ordinal exports.
965 */
966 paRVANames = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, const KU32 *);
967 paOrdinals = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, const KU16 *);
968 paFunctions = KLDRMODPE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, const KU32 *);
969 cFunctions = pExpDir->NumberOfFunctions;
970 cNames = pExpDir->NumberOfNames;
971 for (iFunction = 0; iFunction < cFunctions; iFunction++)
972 {
973 unsigned fFoundName;
974 KU32 iName;
975 const KU32 uRVA = paFunctions[iFunction];
976 const KLDRADDR uValue = BaseAddress + uRVA;
977 KU32 fKind = (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
978 ? KLDRSYMKIND_32BIT : KLDRSYMKIND_64BIT)
979 | KLDRSYMKIND_NO_TYPE;
980 if ( uRVA - pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
981 < pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
982 fKind |= KLDRSYMKIND_FORWARDER;
983
984 /*
985 * Any symbol names?
986 */
987 fFoundName = 0;
988 for (iName = 0; iName < cNames; iName++)
989 {
990 const char *pszName;
991 if (paOrdinals[iName] != iFunction)
992 continue;
993 fFoundName = 1;
994 pszName = KLDRMODPE_RVA2TYPE(pvBits, paRVANames[iName], const char *);
995 rc = pfnCallback(pMod, iFunction + pExpDir->Base, pszName, kHlpStrLen(pszName), NULL,
996 uValue, fKind, pvUser);
997 if (rc)
998 return rc;
999 }
1000
1001 /*
1002 * If no names, call once with the ordinal only.
1003 */
1004 if (!fFoundName)
1005 {
1006 rc = pfnCallback(pMod, iFunction + pExpDir->Base, NULL, 0, NULL, uValue, fKind, pvUser);
1007 if (rc)
1008 return rc;
1009 }
1010 }
1011
1012 return 0;
1013}
1014
1015
1016/** @copydoc kLdrModGetImport */
1017static int kldrModPEGetImport(PKLDRMOD pMod, const void *pvBits, KU32 iImport, char *pszName, KSIZE cchName)
1018{
1019 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1020 const IMAGE_IMPORT_DESCRIPTOR *pImpDesc;
1021 const char *pszImportName;
1022 KSIZE cchImportName;
1023 int rc;
1024
1025 /*
1026 * Make sure we've got mapped bits and resolve any base address aliases.
1027 */
1028 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL);
1029 if (rc)
1030 return rc;
1031
1032 /*
1033 * Simple bounds check.
1034 */
1035 if (iImport >= (KU32)kldrModPENumberOfImports(pMod, pvBits))
1036 return KLDR_ERR_IMPORT_ORDINAL_OUT_OF_BOUNDS;
1037
1038 /*
1039 * Get the name.
1040 */
1041 pImpDesc = KLDRMODPE_RVA2TYPE(pvBits,
1042 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress
1043 + sizeof(IMAGE_IMPORT_DESCRIPTOR) * iImport,
1044 const IMAGE_IMPORT_DESCRIPTOR *);
1045 pszImportName = KLDRMODPE_RVA2TYPE(pvBits, pImpDesc->Name, const char *);
1046 cchImportName = kHlpStrLen(pszImportName);
1047 if (cchImportName < cchName)
1048 {
1049 kHlpMemCopy(pszName, pszImportName, cchImportName + 1);
1050 rc = 0;
1051 }
1052 else
1053 {
1054 kHlpMemCopy(pszName, pszImportName, cchName);
1055 if (cchName)
1056 pszName[cchName - 1] = '\0';
1057 rc = KERR_BUFFER_OVERFLOW;
1058 }
1059
1060 return rc;
1061}
1062
1063
1064/** @copydoc kLdrModNumberOfImports */
1065static KI32 kldrModPENumberOfImports(PKLDRMOD pMod, const void *pvBits)
1066{
1067 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1068 if (pModPE->cImportModules == ~(KU32)0)
1069 {
1070 /*
1071 * We'll have to walk the import descriptors to figure out their number.
1072 * First, make sure we've got mapped bits.
1073 */
1074 if (kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL))
1075 return -1;
1076 pModPE->cImportModules = 0;
1077 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size
1078 && pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1079 {
1080 const IMAGE_IMPORT_DESCRIPTOR *pImpDesc;
1081
1082 pImpDesc = KLDRMODPE_RVA2TYPE(pvBits,
1083 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
1084 const IMAGE_IMPORT_DESCRIPTOR *);
1085 while (pImpDesc->Name && pImpDesc->FirstThunk)
1086 {
1087 pModPE->cImportModules++;
1088 pImpDesc++;
1089 }
1090 }
1091 }
1092 return pModPE->cImportModules;
1093}
1094
1095
1096/** @copydoc kLdrModGetStackInfo */
1097static int kldrModPEGetStackInfo(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, PKLDRSTACKINFO pStackInfo)
1098{
1099 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1100
1101 pStackInfo->Address = NIL_KLDRADDR;
1102 pStackInfo->LinkAddress = NIL_KLDRADDR;
1103 pStackInfo->cbStack = pStackInfo->cbStackThread = pModPE->Hdrs.OptionalHeader.SizeOfStackReserve;
1104
1105 return 0;
1106}
1107
1108
1109/** @copydoc kLdrModQueryMainEntrypoint */
1110static int kldrModPEQueryMainEntrypoint(PKLDRMOD pMod, const void *pvBits, KLDRADDR BaseAddress, PKLDRADDR pMainEPAddress)
1111{
1112 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1113 int rc;
1114
1115 /*
1116 * Resolve base address alias if any.
1117 */
1118 rc = kldrModPEBitsAndBaseAddress(pModPE, NULL, &BaseAddress);
1119 if (rc)
1120 return rc;
1121
1122 /*
1123 * Convert the address from the header.
1124 */
1125 *pMainEPAddress = pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint
1126 ? BaseAddress + pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint
1127 : NIL_KLDRADDR;
1128 return 0;
1129}
1130
1131
1132/** @copydoc kLdrModEnumDbgInfo */
1133static int kldrModPEEnumDbgInfo(PKLDRMOD pMod, const void *pvBits, PFNKLDRENUMDBG pfnCallback, void *pvUser)
1134{
1135 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1136 const IMAGE_DEBUG_DIRECTORY *pDbgDir;
1137 KU32 iDbgInfo;
1138 KU32 cb;
1139 int rc;
1140
1141 /*
1142 * Check that there is a debug directory first.
1143 */
1144 cb = pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size;
1145 if ( cb < sizeof(IMAGE_DEBUG_DIRECTORY) /* screw borland linkers */
1146 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress)
1147 return 0;
1148
1149 /*
1150 * Make sure we've got mapped bits.
1151 */
1152 rc = kldrModPEBitsAndBaseAddress(pModPE, &pvBits, NULL);
1153 if (rc)
1154 return rc;
1155
1156 /*
1157 * Enumerate the debug directory.
1158 */
1159 pDbgDir = KLDRMODPE_RVA2TYPE(pvBits,
1160 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress,
1161 const IMAGE_DEBUG_DIRECTORY *);
1162 for (iDbgInfo = 0;; iDbgInfo++, pDbgDir++, cb -= sizeof(IMAGE_DEBUG_DIRECTORY))
1163 {
1164 KLDRDBGINFOTYPE enmDbgInfoType;
1165
1166 /* convert the type. */
1167 switch (pDbgDir->Type)
1168 {
1169 case IMAGE_DEBUG_TYPE_UNKNOWN:
1170 case IMAGE_DEBUG_TYPE_FPO:
1171 case IMAGE_DEBUG_TYPE_COFF: /*stabs dialect??*/
1172 case IMAGE_DEBUG_TYPE_MISC:
1173 case IMAGE_DEBUG_TYPE_EXCEPTION:
1174 case IMAGE_DEBUG_TYPE_FIXUP:
1175 case IMAGE_DEBUG_TYPE_BORLAND:
1176 default:
1177 enmDbgInfoType = KLDRDBGINFOTYPE_UNKNOWN;
1178 break;
1179 case IMAGE_DEBUG_TYPE_CODEVIEW:
1180 enmDbgInfoType = KLDRDBGINFOTYPE_CODEVIEW;
1181 break;
1182 }
1183
1184 rc = pfnCallback(pMod, iDbgInfo,
1185 enmDbgInfoType, pDbgDir->MajorVersion, pDbgDir->MinorVersion,
1186 pDbgDir->PointerToRawData ? pDbgDir->PointerToRawData : -1,
1187 pDbgDir->AddressOfRawData ? pDbgDir->AddressOfRawData : NIL_KLDRADDR,
1188 pDbgDir->SizeOfData,
1189 NULL,
1190 pvUser);
1191 if (rc)
1192 break;
1193
1194 /* next */
1195 if (cb <= sizeof(IMAGE_DEBUG_DIRECTORY))
1196 break;
1197 }
1198
1199 return rc;
1200}
1201
1202
1203/** @copydoc kLdrModHasDbgInfo */
1204static int kldrModPEHasDbgInfo(PKLDRMOD pMod, const void *pvBits)
1205{
1206 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1207
1208 /*
1209 * Base this entirely on the presence of a debug directory.
1210 */
1211 if ( pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].Size
1212 < sizeof(IMAGE_DEBUG_DIRECTORY) /* screw borland linkers */
1213 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG].VirtualAddress)
1214 return KLDR_ERR_NO_DEBUG_INFO;
1215 return 0;
1216}
1217
1218
1219/** @copydoc kLdrModMap */
1220static int kldrModPEMap(PKLDRMOD pMod)
1221{
1222 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1223 int rc;
1224
1225 /*
1226 * Already mapped?
1227 */
1228 if (pModPE->pvMapping)
1229 return KLDR_ERR_ALREADY_MAPPED;
1230
1231 /*
1232 * We've got a common worker which does this.
1233 */
1234 rc = kldrModPEDoMap(pModPE, 1 /* the real thing */);
1235 if (rc)
1236 return rc;
1237 KLDRMODPE_ASSERT(pModPE->pvMapping);
1238 return 0;
1239}
1240
1241
1242/** @copydoc kLdrModUnmap */
1243static int kldrModPEUnmap(PKLDRMOD pMod)
1244{
1245 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1246 int rc;
1247
1248 /*
1249 * Mapped?
1250 */
1251 if (!pModPE->pvMapping)
1252 return KLDR_ERR_NOT_MAPPED;
1253
1254 /*
1255 * We've got a common worker which does this.
1256 */
1257 rc = kldrModPEDoUnmap(pModPE, pModPE->pvMapping);
1258 if (rc)
1259 return rc;
1260 KLDRMODPE_ASSERT(!pModPE->pvMapping);
1261 return 0;
1262
1263}
1264
1265
1266/** @copydoc kLdrModAllocTLS */
1267static int kldrModPEAllocTLS(PKLDRMOD pMod)
1268{
1269 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1270
1271 /*
1272 * Mapped?
1273 */
1274 if (!pModPE->pvMapping)
1275 return KLDR_ERR_NOT_MAPPED;
1276
1277 /*
1278 * If no TLS directory then there is nothing to do.
1279 */
1280 if ( !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size
1281 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress)
1282 return 0;
1283 /** @todo implement TLS. */
1284 return -1;
1285}
1286
1287
1288/** @copydoc kLdrModFreeTLS */
1289static void kldrModPEFreeTLS(PKLDRMOD pMod)
1290{
1291 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1292
1293 /*
1294 * Mapped?
1295 */
1296 if (!pModPE->pvMapping)
1297 return;
1298
1299 /*
1300 * If no TLS directory then there is nothing to do.
1301 */
1302 if ( !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size
1303 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress)
1304 return;
1305 /** @todo implement TLS. */
1306 return;
1307}
1308
1309
1310/** @copydoc kLdrModReload */
1311static int kldrModPEReload(PKLDRMOD pMod)
1312{
1313 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1314
1315 /*
1316 * Mapped?
1317 */
1318 if (!pModPE->pvMapping)
1319 return KLDR_ERR_NOT_MAPPED;
1320
1321 /* the file provider does it all */
1322 return kRdrRefresh(pMod->pRdr, (void *)pModPE->pvMapping, pMod->cSegments, pMod->aSegments);
1323}
1324
1325
1326/** @copydoc kLdrModFixupMapping */
1327static int kldrModPEFixupMapping(PKLDRMOD pMod, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
1328{
1329 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1330 int rc, rc2;
1331
1332 /*
1333 * Mapped?
1334 */
1335 if (!pModPE->pvMapping)
1336 return KLDR_ERR_NOT_MAPPED;
1337
1338 /*
1339 * Before doing anything we'll have to make all pages writable.
1340 */
1341 rc = kRdrProtect(pMod->pRdr, (void *)pModPE->pvMapping, pMod->cSegments, pMod->aSegments, 1 /* unprotect */);
1342 if (rc)
1343 return rc;
1344
1345 /*
1346 * Apply base relocations.
1347 */
1348 rc = kldrModPEDoFixups(pModPE, (void *)pModPE->pvMapping, (KUPTR)pModPE->pvMapping,
1349 pModPE->Hdrs.OptionalHeader.ImageBase);
1350
1351 /*
1352 * Resolve imports.
1353 */
1354 if (!rc)
1355 rc = kldrModPEDoImports(pModPE, (void *)pModPE->pvMapping, pfnGetImport, pvUser);
1356
1357 /*
1358 * Restore protection.
1359 */
1360 rc2 = kRdrProtect(pMod->pRdr, (void *)pModPE->pvMapping, pMod->cSegments, pMod->aSegments, 0 /* protect */);
1361 if (!rc && rc2)
1362 rc = rc2;
1363 return rc;
1364}
1365
1366
1367/**
1368 * Applies base relocations to a (unprotected) image mapping.
1369 *
1370 * @returns 0 on success, non-zero kLdr status code on failure.
1371 * @param pModPE The PE module interpreter instance.
1372 * @param pvMapping The mapping to fixup.
1373 * @param NewBaseAddress The address to fixup the mapping to.
1374 * @param OldBaseAddress The address the mapping is currently fixed up to.
1375 */
1376static int kldrModPEDoFixups(PKLDRMODPE pModPE, void *pvMapping, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress)
1377{
1378 const KLDRADDR Delta = NewBaseAddress - OldBaseAddress;
1379 KU32 cbLeft = pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size;
1380 const IMAGE_BASE_RELOCATION *pBR, *pFirstBR;
1381
1382 /*
1383 * Don't don anything if the delta is 0 or there aren't any relocations.
1384 */
1385 if ( !Delta
1386 || !cbLeft
1387 || !pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress)
1388 return 0;
1389
1390 /*
1391 * Process the fixups block by block.
1392 * (These blocks appears to be 4KB on all archs despite the native page size.)
1393 */
1394 pBR = pFirstBR = KLDRMODPE_RVA2TYPE(pvMapping,
1395 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress,
1396 const IMAGE_BASE_RELOCATION *);
1397 while ( cbLeft > sizeof(IMAGE_BASE_RELOCATION)
1398 && pBR->SizeOfBlock >= sizeof(IMAGE_BASE_RELOCATION) /* paranoia */)
1399 {
1400 union
1401 {
1402 KU8 *pu8;
1403 KU16 *pu16;
1404 KU32 *pu32;
1405 KU64 *pu64;
1406 } uChunk,
1407 u;
1408 const KU16 *poffFixup = (const KU16 *)(pBR + 1);
1409 const KU32 cbBlock = K_MIN(cbLeft, pBR->SizeOfBlock) - sizeof(IMAGE_BASE_RELOCATION); /* more caution... */
1410 KU32 cFixups = cbBlock / sizeof(poffFixup[0]);
1411 uChunk.pu8 = KLDRMODPE_RVA2TYPE(pvMapping, pBR->VirtualAddress, KU8 *);
1412
1413 /*
1414 * Loop thru the fixups in this chunk.
1415 */
1416 while (cFixups > 0)
1417 {
1418 u.pu8 = uChunk.pu8 + (*poffFixup & 0xfff);
1419 switch (*poffFixup >> 12) /* ordered by value. */
1420 {
1421 /* 0 - Alignment placeholder. */
1422 case IMAGE_REL_BASED_ABSOLUTE:
1423 break;
1424
1425 /* 1 - 16-bit, add 2nd 16-bit part of the delta. (rare) */
1426 case IMAGE_REL_BASED_HIGH:
1427 *u.pu16 += (KU16)(Delta >> 16);
1428 break;
1429
1430 /* 2 - 16-bit, add 1st 16-bit part of the delta. (rare) */
1431 case IMAGE_REL_BASED_LOW:
1432 *u.pu16 += (KU16)Delta;
1433 break;
1434
1435 /* 3 - 32-bit, add delta. (frequent in 32-bit images) */
1436 case IMAGE_REL_BASED_HIGHLOW:
1437 *u.pu32 += (KU32)Delta;
1438 break;
1439
1440 /* 4 - 16-bit, add 2nd 16-bit of the delta, sign adjust for the lower 16-bit. one arg. (rare) */
1441 case IMAGE_REL_BASED_HIGHADJ:
1442 {
1443 KI32 i32;
1444 if (cFixups <= 1)
1445 return KLDR_ERR_PE_BAD_FIXUP;
1446
1447 i32 = (KU32)*u.pu16 << 16;
1448 i32 |= *++poffFixup; cFixups--; /* the addend argument */
1449 i32 += (KU32)Delta;
1450 i32 += 0x8000;
1451 *u.pu16 = (KU16)(i32 >> 16);
1452 break;
1453 }
1454
1455 /* 5 - 32-bit MIPS JMPADDR, no implemented. */
1456 case IMAGE_REL_BASED_MIPS_JMPADDR:
1457 *u.pu32 = (*u.pu32 & 0xc0000000)
1458 | ((KU32)((*u.pu32 << 2) + (KU32)Delta) >> 2);
1459 break;
1460
1461 /* 6 - Intra section? Reserved value in later specs. Not implemented. */
1462 case IMAGE_REL_BASED_SECTION:
1463 KLDRMODPE_ASSERT(!"SECTION");
1464 return KLDR_ERR_PE_BAD_FIXUP;
1465
1466 /* 7 - Relative intra section? Reserved value in later specs. Not implemented. */
1467 case IMAGE_REL_BASED_REL32:
1468 KLDRMODPE_ASSERT(!"SECTION");
1469 return KLDR_ERR_PE_BAD_FIXUP;
1470
1471 /* 8 - reserved according to binutils... */
1472 case 8:
1473 KLDRMODPE_ASSERT(!"RESERVERED8");
1474 return KLDR_ERR_PE_BAD_FIXUP;
1475
1476 /* 9 - IA64_IMM64 (/ MIPS_JMPADDR16), no specs nor need to support the platform yet.
1477 * Bet this requires more code than all the other fixups put together in good IA64 spirit :-) */
1478 case IMAGE_REL_BASED_IA64_IMM64:
1479 KLDRMODPE_ASSERT(!"IA64_IMM64 / MIPS_JMPADDR16");
1480 return KLDR_ERR_PE_BAD_FIXUP;
1481
1482 /* 10 - 64-bit, add delta. (frequently in 64-bit images) */
1483 case IMAGE_REL_BASED_DIR64:
1484 *u.pu64 += (KU64)Delta;
1485 break;
1486
1487 /* 11 - 16-bit, add 3rd 16-bit of the delta, sign adjust for the lower 32-bit. two args. (rare) */
1488 case IMAGE_REL_BASED_HIGH3ADJ:
1489 {
1490 KI64 i64;
1491 if (cFixups <= 2)
1492 return KLDR_ERR_PE_BAD_FIXUP;
1493
1494 i64 = (KU64)*u.pu16 << 32
1495 | ((KU32)poffFixup[2] << 16)
1496 | poffFixup[1];
1497 i64 += Delta;
1498 i64 += 0x80008000UL;
1499 *u.pu16 = (KU16)(i64 >> 32);
1500 /* skip the addends arguments */
1501 poffFixup += 2;
1502 cFixups -= 2;
1503 break;
1504 }
1505
1506 /* the rest are yet to be defined.*/
1507 default:
1508 return KLDR_ERR_PE_BAD_FIXUP;
1509 }
1510
1511 /*
1512 * Next relocation.
1513 */
1514 poffFixup++;
1515 cFixups--;
1516 }
1517
1518
1519 /*
1520 * Next block.
1521 */
1522 cbLeft -= pBR->SizeOfBlock;
1523 pBR = (PIMAGE_BASE_RELOCATION)((KUPTR)pBR + pBR->SizeOfBlock);
1524 }
1525
1526 return 0;
1527}
1528
1529
1530
1531/**
1532 * Resolves imports.
1533 *
1534 * @returns 0 on success, non-zero kLdr status code on failure.
1535 * @param pModPE The PE module interpreter instance.
1536 * @param pvMapping The mapping which imports should be resolved.
1537 * @param pfnGetImport The callback for resolving an imported symbol.
1538 * @param pvUser User argument to the callback.
1539 */
1540static int kldrModPEDoImports(PKLDRMODPE pModPE, void *pvMapping, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
1541{
1542 const IMAGE_IMPORT_DESCRIPTOR *pImpDesc;
1543
1544 /*
1545 * If no imports, there is nothing to do.
1546 */
1547 kldrModPENumberOfImports(pModPE->pMod, pvMapping);
1548 if (!pModPE->cImportModules)
1549 return 0;
1550
1551 pImpDesc = KLDRMODPE_RVA2TYPE(pvMapping,
1552 pModPE->Hdrs.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
1553 const IMAGE_IMPORT_DESCRIPTOR *);
1554 if (pModPE->Hdrs.FileHeader.SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32))
1555 return kldrModPEDoImports32Bit(pModPE, pvMapping, pImpDesc, pfnGetImport, pvUser);
1556 return kldrModPEDoImports64Bit(pModPE, pvMapping, pImpDesc, pfnGetImport, pvUser);
1557}
1558
1559
1560/**
1561 * Resolves imports, 32-bit image.
1562 *
1563 * @returns 0 on success, non-zero kLdr status code on failure.
1564 * @param pModPE The PE module interpreter instance.
1565 * @param pvMapping The mapping which imports should be resolved.
1566 * @param pImpDesc Pointer to the first import descriptor.
1567 * @param pfnGetImport The callback for resolving an imported symbol.
1568 * @param pvUser User argument to the callback.
1569 */
1570static int kldrModPEDoImports32Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
1571 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
1572{
1573 PKLDRMOD pMod = pModPE->pMod;
1574 KU32 iImp;
1575
1576 /*
1577 * Iterate the import descriptors.
1578 */
1579 for (iImp = 0; iImp < pModPE->cImportModules; iImp++, pImpDesc++)
1580 {
1581 PIMAGE_THUNK_DATA32 pFirstThunk = KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, PIMAGE_THUNK_DATA32);
1582 const IMAGE_THUNK_DATA32 *pThunk = pImpDesc->u.OriginalFirstThunk
1583 ? KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->u.OriginalFirstThunk, const IMAGE_THUNK_DATA32 *)
1584 : KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, const IMAGE_THUNK_DATA32 *);
1585
1586 /* Iterate the thunks. */
1587 while (pThunk->u1.Ordinal != 0)
1588 {
1589 KLDRADDR Value;
1590 KU32 fKind = KLDRSYMKIND_REQ_FLAT;
1591 int rc;
1592
1593 /* Ordinal or name import? */
1594 if (IMAGE_SNAP_BY_ORDINAL32(pThunk->u1.Ordinal))
1595 rc = pfnGetImport(pMod, iImp, IMAGE_ORDINAL32(pThunk->u1.Ordinal), NULL, 0, NULL, &Value, &fKind, pvUser);
1596 else if (KLDRMODPE_VALID_RVA(pModPE, pThunk->u1.Ordinal))
1597 {
1598 const IMAGE_IMPORT_BY_NAME *pName = KLDRMODPE_RVA2TYPE(pvMapping, pThunk->u1.Ordinal, const IMAGE_IMPORT_BY_NAME *);
1599 rc = pfnGetImport(pMod, iImp, NIL_KLDRMOD_SYM_ORDINAL, (const char *)pName->Name,
1600 kHlpStrLen((const char *)pName->Name), NULL, &Value, &fKind, pvUser);
1601 }
1602 else
1603 {
1604 KLDRMODPE_ASSERT(!"bad 32-bit import");
1605 return KLDR_ERR_PE_BAD_IMPORT;
1606 }
1607 if (rc)
1608 return rc;
1609
1610 /* Apply it. */
1611 pFirstThunk->u1.Function = (KU32)Value;
1612 if (pFirstThunk->u1.Function != Value)
1613 {
1614 KLDRMODPE_ASSERT(!"overflow");
1615 return KLDR_ERR_ADDRESS_OVERFLOW;
1616 }
1617
1618 /* next */
1619 pThunk++;
1620 pFirstThunk++;
1621 }
1622 }
1623
1624 return 0;
1625}
1626
1627
1628/**
1629 * Resolves imports, 64-bit image.
1630 *
1631 * @returns 0 on success, non-zero kLdr status code on failure.
1632 * @param pModPE The PE module interpreter instance.
1633 * @param pvMapping The mapping which imports should be resolved.
1634 * @param pImpDesc Pointer to the first import descriptor.
1635 * @param pfnGetImport The callback for resolving an imported symbol.
1636 * @param pvUser User argument to the callback.
1637 */
1638static int kldrModPEDoImports64Bit(PKLDRMODPE pModPE, void *pvMapping, const IMAGE_IMPORT_DESCRIPTOR *pImpDesc,
1639 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
1640{
1641 PKLDRMOD pMod = pModPE->pMod;
1642 KU32 iImp;
1643
1644 /*
1645 * Iterate the import descriptors.
1646 */
1647 for (iImp = 0; iImp < pModPE->cImportModules; iImp++, pImpDesc++)
1648 {
1649 PIMAGE_THUNK_DATA64 pFirstThunk = KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, PIMAGE_THUNK_DATA64);
1650 const IMAGE_THUNK_DATA64 *pThunk = pImpDesc->u.OriginalFirstThunk
1651 ? KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->u.OriginalFirstThunk, const IMAGE_THUNK_DATA64 *)
1652 : KLDRMODPE_RVA2TYPE(pvMapping, pImpDesc->FirstThunk, const IMAGE_THUNK_DATA64 *);
1653
1654 /* Iterate the thunks. */
1655 while (pThunk->u1.Ordinal != 0)
1656 {
1657 KLDRADDR Value;
1658 KU32 fKind = KLDRSYMKIND_REQ_FLAT;
1659 int rc;
1660
1661 /* Ordinal or name import? */
1662 if (IMAGE_SNAP_BY_ORDINAL64(pThunk->u1.Ordinal))
1663 rc = pfnGetImport(pMod, iImp, (KU32)IMAGE_ORDINAL64(pThunk->u1.Ordinal), NULL, 0, NULL, &Value, &fKind, pvUser);
1664 else if (KLDRMODPE_VALID_RVA(pModPE, pThunk->u1.Ordinal))
1665 {
1666 const IMAGE_IMPORT_BY_NAME *pName = KLDRMODPE_RVA2TYPE(pvMapping, pThunk->u1.Ordinal, const IMAGE_IMPORT_BY_NAME *);
1667 rc = pfnGetImport(pMod, iImp, NIL_KLDRMOD_SYM_ORDINAL, (const char *)pName->Name,
1668 kHlpStrLen((const char *)pName->Name), NULL, &Value, &fKind, pvUser);
1669 }
1670 else
1671 {
1672 KLDRMODPE_ASSERT(!"bad 64-bit import");
1673 return KLDR_ERR_PE_BAD_IMPORT;
1674 }
1675 if (rc)
1676 return rc;
1677
1678 /* Apply it. */
1679 pFirstThunk->u1.Function = Value;
1680
1681 /* next */
1682 pThunk++;
1683 pFirstThunk++;
1684 }
1685 }
1686
1687 return 0;
1688}
1689
1690
1691
1692/** @copydoc kLdrModCallInit */
1693static int kldrModPECallInit(PKLDRMOD pMod, KUPTR uHandle)
1694{
1695 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1696 int rc;
1697
1698 /*
1699 * Mapped?
1700 */
1701 if (!pModPE->pvMapping)
1702 return KLDR_ERR_NOT_MAPPED;
1703
1704 /*
1705 * Do TLS callbacks first and then call the init/term function if it's a DLL.
1706 */
1707 rc = kldrModPEDoCallTLS(pModPE, DLL_PROCESS_ATTACH, uHandle);
1708 if ( !rc
1709 && (pModPE->Hdrs.FileHeader.Characteristics & IMAGE_FILE_DLL))
1710 {
1711 rc = kldrModPEDoCallDLL(pModPE, DLL_PROCESS_ATTACH, uHandle);
1712 if (rc)
1713 kldrModPEDoCallTLS(pModPE, DLL_PROCESS_DETACH, uHandle);
1714 }
1715
1716 return rc;
1717}
1718
1719
1720/**
1721 * Call the DLL entrypoint.
1722 *
1723 * @returns 0 on success.
1724 * @returns KLDR_ERR_MODULE_INIT_FAILED or KLDR_ERR_THREAD_ATTACH_FAILED on failure.
1725 * @param pModPE The PE module interpreter instance.
1726 * @param uOp The operation (DLL_*).
1727 * @param uHandle The module handle to present.
1728 */
1729static int kldrModPEDoCallDLL(PKLDRMODPE pModPE, unsigned uOp, KUPTR uHandle)
1730{
1731 int rc;
1732
1733 /*
1734 * If no entrypoint there isn't anything to be done.
1735 */
1736 if (!pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint)
1737 return 0;
1738
1739 /*
1740 * Invoke the entrypoint and convert the boolean result to a kLdr status code.
1741 */
1742 rc = kldrModPEDoCall((KUPTR)pModPE->pvMapping + pModPE->Hdrs.OptionalHeader.AddressOfEntryPoint,
1743 uHandle, uOp, NULL);
1744 if (rc)
1745 rc = 0;
1746 else if (uOp == DLL_PROCESS_ATTACH)
1747 rc = KLDR_ERR_MODULE_INIT_FAILED;
1748 else if (uOp == DLL_THREAD_ATTACH)
1749 rc = KLDR_ERR_THREAD_ATTACH_FAILED;
1750 else /* detach: ignore failures */
1751 rc = 0;
1752 return rc;
1753}
1754
1755
1756/**
1757 * Call the TLS entrypoints.
1758 *
1759 * @returns 0 on success.
1760 * @returns KLDR_ERR_THREAD_ATTACH_FAILED on failure.
1761 * @param pModPE The PE module interpreter instance.
1762 * @param uOp The operation (DLL_*).
1763 * @param uHandle The module handle to present.
1764 */
1765static int kldrModPEDoCallTLS(PKLDRMODPE pModPE, unsigned uOp, KUPTR uHandle)
1766{
1767 /** @todo implement TLS support. */
1768 return 0;
1769}
1770
1771
1772/**
1773 * Do a 3 parameter callback.
1774 *
1775 * @returns 32-bit callback return.
1776 * @param uEntrypoint The address of the function to be called.
1777 * @param uHandle The first argument, the module handle.
1778 * @param uOp The second argumnet, the reason we're calling.
1779 * @param pvReserved The third argument, reserved argument. (figure this one out)
1780 */
1781static KI32 kldrModPEDoCall(KUPTR uEntrypoint, KUPTR uHandle, KU32 uOp, void *pvReserved)
1782{
1783 KI32 rc;
1784
1785/** @todo try/except */
1786#if defined(__X86__) || defined(__i386__) || defined(_M_IX86)
1787 /*
1788 * Be very careful.
1789 * Not everyone will have got the calling convention right.
1790 */
1791# ifdef __GNUC__
1792 __asm__ __volatile__(
1793 "pushl %2\n\t"
1794 "pushl %1\n\t"
1795 "pushl %0\n\t"
1796 "lea 12(%%esp), %2\n\t"
1797 "call *%3\n\t"
1798 "movl %2, %%esp\n\t"
1799 : "=a" (rc)
1800 : "d" (uOp),
1801 "S" (0),
1802 "c" (uEntrypoint),
1803 "0" (uHandle));
1804# elif defined(_MSC_VER)
1805 __asm {
1806 mov eax, [uHandle]
1807 mov edx, [uOp]
1808 mov ecx, 0
1809 mov ebx, [uEntrypoint]
1810 push edi
1811 mov edi, esp
1812 push ecx
1813 push edx
1814 push eax
1815 call ebx
1816 mov esp, edi
1817 pop edi
1818 mov [rc], eax
1819 }
1820# else
1821# error "port me!"
1822# endif
1823
1824#elif defined(__AMD64__) || defined(__x86_64__) || defined(_M_IX86)
1825 /*
1826 * For now, let's just get the work done...
1827 */
1828 /** @todo Deal with GCC / MSC differences in some sensible way. */
1829 int (*pfn)(KUPTR uHandle, KU32 uOp, void *pvReserved);
1830 pfn = (int (*)(KUPTR uHandle, KU32 uOp, void *pvReserved))uEntrypoint;
1831 rc = pfn(uHandle, uOp, NULL);
1832
1833#else
1834# error "port me"
1835#endif
1836
1837 return rc;
1838}
1839
1840
1841/** @copydoc kLdrModCallTerm */
1842static int kldrModPECallTerm(PKLDRMOD pMod, KUPTR uHandle)
1843{
1844 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1845
1846 /*
1847 * Mapped?
1848 */
1849 if (!pModPE->pvMapping)
1850 return KLDR_ERR_NOT_MAPPED;
1851
1852 /*
1853 * Do TLS callbacks first.
1854 */
1855 kldrModPEDoCallTLS(pModPE, DLL_PROCESS_DETACH, uHandle);
1856 if (pModPE->Hdrs.FileHeader.Characteristics & IMAGE_FILE_DLL)
1857 kldrModPEDoCallDLL(pModPE, DLL_PROCESS_DETACH, uHandle);
1858
1859 return 0;
1860}
1861
1862
1863/** @copydoc kLdrModCallThread */
1864static int kldrModPECallThread(PKLDRMOD pMod, KUPTR uHandle, unsigned fAttachingOrDetaching)
1865{
1866 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1867 unsigned uOp = fAttachingOrDetaching ? DLL_THREAD_ATTACH : DLL_THREAD_DETACH;
1868 int rc;
1869
1870 /*
1871 * Do TLS callbacks first and then call the init/term function if it's a DLL.
1872 */
1873 rc = kldrModPEDoCallTLS(pModPE, uOp, uHandle);
1874 if (!fAttachingOrDetaching)
1875 rc = 0;
1876 if ( !rc
1877 && (pModPE->Hdrs.FileHeader.Characteristics & IMAGE_FILE_DLL))
1878 {
1879 rc = kldrModPEDoCallDLL(pModPE, uOp, uHandle);
1880 if (!fAttachingOrDetaching)
1881 rc = 0;
1882 if (rc)
1883 kldrModPEDoCallTLS(pModPE, uOp, uHandle);
1884 }
1885
1886 return rc;
1887}
1888
1889
1890/** @copydoc kLdrModSize */
1891static KLDRADDR kldrModPESize(PKLDRMOD pMod)
1892{
1893 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1894 return pModPE->Hdrs.OptionalHeader.SizeOfImage;
1895}
1896
1897
1898/** @copydoc kLdrModGetBits */
1899static int kldrModPEGetBits(PKLDRMOD pMod, void *pvBits, KLDRADDR BaseAddress, PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
1900{
1901 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1902 KU32 i;
1903 int rc;
1904
1905 /*
1906 * Zero the entire buffer first to simplify things.
1907 */
1908 kHlpMemSet(pvBits, 0, pModPE->Hdrs.OptionalHeader.SizeOfImage);
1909
1910 /*
1911 * Iterate the segments and read the data within them.
1912 */
1913 for (i = 0; i < pMod->cSegments; i++)
1914 {
1915 /* skip it? */
1916 if ( pMod->aSegments[i].cbFile == -1
1917 || pMod->aSegments[i].offFile == -1
1918 || pMod->aSegments[i].LinkAddress == NIL_KLDRADDR
1919 || !pMod->aSegments[i].Alignment)
1920 continue;
1921 rc = kRdrRead(pMod->pRdr,
1922 (KU8 *)pvBits + (pMod->aSegments[i].LinkAddress - pModPE->Hdrs.OptionalHeader.ImageBase),
1923 pMod->aSegments[i].cbFile,
1924 pMod->aSegments[i].offFile);
1925 if (rc)
1926 return rc;
1927 }
1928
1929 /*
1930 * Perform relocations.
1931 */
1932 return kldrModPERelocateBits(pMod, pvBits, BaseAddress, pModPE->Hdrs.OptionalHeader.ImageBase, pfnGetImport, pvUser);
1933
1934}
1935
1936
1937/** @copydoc kLdrModRelocateBits */
1938static int kldrModPERelocateBits(PKLDRMOD pMod, void *pvBits, KLDRADDR NewBaseAddress, KLDRADDR OldBaseAddress,
1939 PFNKLDRMODGETIMPORT pfnGetImport, void *pvUser)
1940{
1941 PKLDRMODPE pModPE = (PKLDRMODPE)pMod->pvData;
1942 int rc;
1943
1944 /*
1945 * Call workers to do the jobs.
1946 */
1947 rc = kldrModPEDoFixups(pModPE, pvBits, NewBaseAddress, OldBaseAddress);
1948 if (!rc)
1949 rc = kldrModPEDoImports(pModPE, pvBits, pfnGetImport, pvUser);
1950
1951 return rc;
1952}
1953
1954
1955/**
1956 * The PE module interpreter method table.
1957 */
1958KLDRMODOPS g_kLdrModPEOps =
1959{
1960 "PE",
1961 NULL,
1962 kldrModPECreate,
1963 kldrModPEDestroy,
1964 kldrModPEQuerySymbol,
1965 kldrModPEEnumSymbols,
1966 kldrModPEGetImport,
1967 kldrModPENumberOfImports,
1968 NULL /* can execute one is optional */,
1969 kldrModPEGetStackInfo,
1970 kldrModPEQueryMainEntrypoint,
1971 NULL, /** @todo resources */
1972 NULL, /** @todo resources */
1973 kldrModPEEnumDbgInfo,
1974 kldrModPEHasDbgInfo,
1975 kldrModPEMap,
1976 kldrModPEUnmap,
1977 kldrModPEAllocTLS,
1978 kldrModPEFreeTLS,
1979 kldrModPEReload,
1980 kldrModPEFixupMapping,
1981 kldrModPECallInit,
1982 kldrModPECallTerm,
1983 kldrModPECallThread,
1984 kldrModPESize,
1985 kldrModPEGetBits,
1986 kldrModPERelocateBits,
1987 NULL, /** @todo mostly done */
1988 42 /* the end */
1989};
Note: See TracBrowser for help on using the repository browser.