VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/ldr/ldrPE.cpp@ 38515

Last change on this file since 38515 was 38515, checked in by vboxsync, 14 years ago

IPRT: Working on debug info again.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 62.3 KB
Line 
1/* $Id: ldrPE.cpp 38515 2011-08-24 14:33:32Z vboxsync $ */
2/** @file
3 * IPRT - Binary Image Loader, Portable Executable (PE).
4 */
5
6/*
7 * Copyright (C) 2006-2007 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#define LOG_GROUP RTLOGGROUP_LDR
32#include <iprt/ldr.h>
33#include "internal/iprt.h"
34
35#include <iprt/alloc.h>
36#include <iprt/assert.h>
37#include <iprt/log.h>
38#include <iprt/string.h>
39#include <iprt/err.h>
40#include "internal/ldrPE.h"
41#include "internal/ldr.h"
42
43
44/*******************************************************************************
45* Defined Constants And Macros *
46*******************************************************************************/
47/** Converts rva to a type.
48 * @param pvBits Pointer to base of image bits.
49 * @param rva Relative virtual address.
50 * @param type Type.
51 */
52#define PE_RVA2TYPE(pvBits, rva, type) ((type) ((uintptr_t)pvBits + (uintptr_t)(rva)) )
53
54
55/*******************************************************************************
56* Structures and Typedefs *
57*******************************************************************************/
58/**
59 * The PE loader structure.
60 */
61typedef struct RTLDRMODPE
62{
63 /** Core module structure. */
64 RTLDRMODINTERNAL Core;
65 /** Pointer to the reader instance. */
66 PRTLDRREADER pReader;
67 /** Pointer to internal copy of image bits.
68 * @todo the reader should take care of this. */
69 void *pvBits;
70 /** The offset of the NT headers. */
71 RTFOFF offNtHdrs;
72
73 /** The machine type (IMAGE_FILE_HEADER::Machine). */
74 uint16_t u16Machine;
75 /** The file flags (IMAGE_FILE_HEADER::Characteristics). */
76 uint16_t fFile;
77 /** Number of sections (IMAGE_FILE_HEADER::NumberOfSections). */
78 unsigned cSections;
79 /** Pointer to an array of the section headers related to the file. */
80 PIMAGE_SECTION_HEADER paSections;
81
82 /** The RVA of the entry point (IMAGE_OPTIONAL_HEADER32::AddressOfEntryPoint). */
83 RTUINTPTR uEntryPointRVA;
84 /** The base address of the image at link time (IMAGE_OPTIONAL_HEADER32::ImageBase). */
85 RTUINTPTR uImageBase;
86 /** The size of the loaded image (IMAGE_OPTIONAL_HEADER32::SizeOfImage). */
87 uint32_t cbImage;
88 /** Size of the header (IMAGE_OPTIONAL_HEADER32::SizeOfHeaders). */
89 uint32_t cbHeaders;
90 /** The import data directory entry. */
91 IMAGE_DATA_DIRECTORY ImportDir;
92 /** The base relocation data directory entry. */
93 IMAGE_DATA_DIRECTORY RelocDir;
94 /** The export data directory entry. */
95 IMAGE_DATA_DIRECTORY ExportDir;
96} RTLDRMODPE, *PRTLDRMODPE;
97
98/**
99 * PE Loader module operations.
100 *
101 * The PE loader has one operation which is a bit different between 32-bit and 64-bit PE images,
102 * and for historical and performance reasons have been split into separate functions. Thus the
103 * PE loader extends the RTLDROPS structure with this one entry.
104 */
105typedef struct RTLDROPSPE
106{
107 /** The usual ops. */
108 RTLDROPS Core;
109
110 /**
111 * Resolves all imports.
112 *
113 * @returns iprt status code.
114 * @param pModPe Pointer to the PE loader module structure.
115 * @param pvBitsR Where to read raw image bits. (optional)
116 * @param pvBitsW Where to store the imports. The size of this buffer is equal or
117 * larger to the value returned by pfnGetImageSize().
118 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
119 * @param pvUser User argument to pass to the callback.
120 */
121 DECLCALLBACKMEMBER(int, pfnResolveImports)(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, PFNRTLDRIMPORT pfnGetImport, void *pvUser);
122
123 /** Dummy entry to make sure we've initialized it all. */
124 RTUINT uDummy;
125} RTLDROPSPE, *PRTLDROPSPE;
126
127
128/*******************************************************************************
129* Internal Functions *
130*******************************************************************************/
131static void rtldrPEConvert32BitOptionalHeaderTo64Bit(PIMAGE_OPTIONAL_HEADER64 pOptHdr);
132static void rtldrPEConvert32BitLoadConfigTo64Bit(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg);
133static int rtldrPEApplyFixups(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, RTUINTPTR BaseAddress, RTUINTPTR OldBaseAddress);
134
135
136/** @copydoc RTLDROPS::pfnGetImageSize */
137static DECLCALLBACK(size_t) rtldrPEGetImageSize(PRTLDRMODINTERNAL pMod)
138{
139 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
140 return pModPe->cbImage;
141}
142
143
144/**
145 * Reads the image into memory.
146 *
147 * @returns iprt status code.
148 * @param pModPe The PE module.
149 * @param pvBits Where to store the bits, this buffer is at least pItem->Core.cbImage in size.
150 */
151static int rtldrPEGetBitsNoImportsNorFixups(PRTLDRMODPE pModPe, void *pvBits)
152{
153 /*
154 * Both these checks are related to pfnDone().
155 */
156 PRTLDRREADER pReader = pModPe->pReader;
157 if (!pReader)
158 {
159 AssertMsgFailed(("You've called done!\n"));
160 return VERR_WRONG_ORDER;
161 }
162 if (!pvBits)
163 return VERR_NO_MEMORY;
164
165 /*
166 * Zero everything (could be done per section).
167 */
168 memset(pvBits, 0, pModPe->cbImage);
169
170#ifdef PE_FILE_OFFSET_EQUALS_RVA
171 /*
172 * Read the entire image / file.
173 */
174 const RTFOFF cbRawImage = pReader->pfnSize(pReader)
175 rc = pReader->pfnRead(pReader, pvBits, RT_MIN(pModPe->cbImage, cbRawImage), 0);
176 if (RT_FAILURE(rc))
177 Log(("rtldrPE: %s: Reading %#x bytes at offset %#x failed, %Rrc!!! (the entire image)\n",
178 pReader->pfnLogName(pReader), RT_MIN(pModPe->cbImage, cbRawImage), 0, rc));
179#else
180
181 /*
182 * Read the headers.
183 */
184 int rc = pReader->pfnRead(pReader, pvBits, pModPe->cbHeaders, 0);
185 if (RT_SUCCESS(rc))
186 {
187 /*
188 * Read the sections.
189 */
190 PIMAGE_SECTION_HEADER pSH = pModPe->paSections;
191 for (unsigned cLeft = pModPe->cSections; cLeft > 0; cLeft--, pSH++)
192 if (pSH->SizeOfRawData && pSH->Misc.VirtualSize)
193 {
194 rc = pReader->pfnRead(pReader, (uint8_t *)pvBits + pSH->VirtualAddress, pSH->SizeOfRawData, pSH->PointerToRawData);
195 if (RT_FAILURE(rc))
196 {
197 Log(("rtldrPE: %s: Reading %#x bytes at offset %#x failed, %Rrc - section #%d '%.*s'!!!\n",
198 pReader->pfnLogName(pReader), pSH->SizeOfRawData, pSH->PointerToRawData, rc,
199 pSH - pModPe->paSections, sizeof(pSH->Name), pSH->Name));
200 break;
201 }
202 }
203 }
204 else
205 Log(("rtldrPE: %s: Reading %#x bytes at offset %#x failed, %Rrc!!!\n",
206 pReader->pfnLogName(pReader), pModPe->cbHeaders, 0, rc));
207#endif
208 return rc;
209}
210
211
212/**
213 * Reads the bits into the internal buffer pointed to by PRTLDRMODPE::pvBits.
214 *
215 * @returns iprt status code.
216 * @param pModPe The PE module.
217 */
218static int rtldrPEReadBits(PRTLDRMODPE pModPe)
219{
220 Assert(!pModPe->pvBits);
221 void *pvBitsW = RTMemAllocZ(pModPe->cbImage);
222 if (!pvBitsW)
223 return VERR_NO_MEMORY;
224 int rc = rtldrPEGetBitsNoImportsNorFixups(pModPe, pvBitsW);
225 if (RT_SUCCESS(rc))
226 pModPe->pvBits = pvBitsW;
227 else
228 RTMemFree(pvBitsW);
229 return rc;
230}
231
232
233/** @copydoc RTLDROPS::pfnGetBits */
234static DECLCALLBACK(int) rtldrPEGetBits(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
235{
236 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
237
238 /*
239 * Read the image.
240 */
241 int rc = rtldrPEGetBitsNoImportsNorFixups(pModPe, pvBits);
242 if (RT_SUCCESS(rc))
243 {
244 /*
245 * Resolve imports.
246 */
247 rc = ((PRTLDROPSPE)pMod->pOps)->pfnResolveImports(pModPe, pvBits, pvBits, pfnGetImport, pvUser);
248 if (RT_SUCCESS(rc))
249 {
250 /*
251 * Apply relocations.
252 */
253 rc = rtldrPEApplyFixups(pModPe, pvBits, pvBits, BaseAddress, pModPe->uImageBase);
254 if (RT_SUCCESS(rc))
255 return rc;
256 AssertMsgFailed(("Failed to apply fixups. rc=%Rrc\n", rc));
257 }
258 else
259 AssertMsgFailed(("Failed to resolve imports. rc=%Rrc\n", rc));
260 }
261 return rc;
262}
263
264
265/** @copydoc RTLDROPSPE::pfnResolveImports */
266static DECLCALLBACK(int) rtldrPEResolveImports32(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
267{
268 /*
269 * Check if there is actually anything to work on.
270 */
271 if ( !pModPe->ImportDir.VirtualAddress
272 || !pModPe->ImportDir.Size)
273 return 0;
274
275 /*
276 * Walk the IMAGE_IMPORT_DESCRIPTOR table.
277 */
278 int rc = VINF_SUCCESS;
279 PIMAGE_IMPORT_DESCRIPTOR pImps;
280 for (pImps = PE_RVA2TYPE(pvBitsR, pModPe->ImportDir.VirtualAddress, PIMAGE_IMPORT_DESCRIPTOR);
281 !rc && pImps->Name != 0 && pImps->FirstThunk != 0;
282 pImps++)
283 {
284 const char *pszModName = PE_RVA2TYPE(pvBitsR, pImps->Name, const char *);
285 PIMAGE_THUNK_DATA32 pFirstThunk; /* update this. */
286 PIMAGE_THUNK_DATA32 pThunk; /* read from this. */
287 Log3(("RTLdrPE: Import descriptor: %s\n", pszModName));
288 Log4(("RTLdrPE: OriginalFirstThunk = %#RX32\n"
289 "RTLdrPE: TimeDateStamp = %#RX32\n"
290 "RTLdrPE: ForwarderChain = %#RX32\n"
291 "RTLdrPE: Name = %#RX32\n"
292 "RTLdrPE: FirstThunk = %#RX32\n",
293 pImps->u.OriginalFirstThunk, pImps->TimeDateStamp,
294 pImps->ForwarderChain, pImps->Name, pImps->FirstThunk));
295
296 /*
297 * Walk the thunks table(s).
298 */
299 pFirstThunk = PE_RVA2TYPE(pvBitsW, pImps->FirstThunk, PIMAGE_THUNK_DATA32);
300 pThunk = pImps->u.OriginalFirstThunk == 0
301 ? PE_RVA2TYPE(pvBitsR, pImps->FirstThunk, PIMAGE_THUNK_DATA32)
302 : PE_RVA2TYPE(pvBitsR, pImps->u.OriginalFirstThunk, PIMAGE_THUNK_DATA32);
303 while (!rc && pThunk->u1.Ordinal != 0)
304 {
305 RTUINTPTR Value = 0;
306 if (pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)
307 {
308 rc = pfnGetImport(&pModPe->Core, pszModName, NULL, IMAGE_ORDINAL32(pThunk->u1.Ordinal), &Value, pvUser);
309 Log4((RT_SUCCESS(rc) ? "RTLdrPE: %RTptr #%u\n" : "RTLdrPE: %08RX32 #%u rc=%Rrc\n",
310 (uint32_t)Value, IMAGE_ORDINAL32(pThunk->u1.Ordinal), rc));
311 }
312 else if ( pThunk->u1.Ordinal > 0
313 && pThunk->u1.Ordinal < pModPe->cbImage)
314 {
315 rc = pfnGetImport(&pModPe->Core, pszModName, PE_RVA2TYPE(pvBitsR, (char*)(uintptr_t)pThunk->u1.AddressOfData + 2, const char *),
316 ~0, &Value, pvUser);
317 Log4((RT_SUCCESS(rc) ? "RTLdrPE: %RTptr %s\n" : "RTLdrPE: %08RX32 %s rc=%Rrc\n",
318 (uint32_t)Value, PE_RVA2TYPE(pvBitsR, (char*)(uintptr_t)pThunk->u1.AddressOfData + 2, const char *), rc));
319 }
320 else
321 {
322 AssertMsgFailed(("bad import data thunk!\n"));
323 rc = VERR_BAD_EXE_FORMAT;
324 }
325 pFirstThunk->u1.Function = Value;
326 if (pFirstThunk->u1.Function != Value)
327 {
328 AssertMsgFailed(("external symbol address to big!\n"));
329 rc = VERR_ADDRESS_CONFLICT; /** @todo get me a better error status code. */
330 }
331 pThunk++;
332 pFirstThunk++;
333 }
334 }
335
336 return rc;
337}
338
339
340/** @copydoc RTLDROPSPE::pfnResolveImports */
341static DECLCALLBACK(int) rtldrPEResolveImports64(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
342{
343 /*
344 * Check if there is actually anything to work on.
345 */
346 if ( !pModPe->ImportDir.VirtualAddress
347 || !pModPe->ImportDir.Size)
348 return 0;
349
350 /*
351 * Walk the IMAGE_IMPORT_DESCRIPTOR table.
352 */
353 int rc = VINF_SUCCESS;
354 PIMAGE_IMPORT_DESCRIPTOR pImps;
355 for (pImps = PE_RVA2TYPE(pvBitsR, pModPe->ImportDir.VirtualAddress, PIMAGE_IMPORT_DESCRIPTOR);
356 !rc && pImps->Name != 0 && pImps->FirstThunk != 0;
357 pImps++)
358 {
359 const char * pszModName = PE_RVA2TYPE(pvBitsR, pImps->Name, const char *);
360 PIMAGE_THUNK_DATA64 pFirstThunk; /* update this. */
361 PIMAGE_THUNK_DATA64 pThunk; /* read from this. */
362 Log3(("RTLdrPE: Import descriptor: %s\n", pszModName));
363 Log4(("RTLdrPE: OriginalFirstThunk = %#RX32\n"
364 "RTLdrPE: TimeDateStamp = %#RX32\n"
365 "RTLdrPE: ForwarderChain = %#RX32\n"
366 "RTLdrPE: Name = %#RX32\n"
367 "RTLdrPE: FirstThunk = %#RX32\n",
368 pImps->u.OriginalFirstThunk, pImps->TimeDateStamp,
369 pImps->ForwarderChain, pImps->Name, pImps->FirstThunk));
370
371 /*
372 * Walk the thunks table(s).
373 */
374 pFirstThunk = PE_RVA2TYPE(pvBitsW, pImps->FirstThunk, PIMAGE_THUNK_DATA64);
375 pThunk = pImps->u.OriginalFirstThunk == 0
376 ? PE_RVA2TYPE(pvBitsR, pImps->FirstThunk, PIMAGE_THUNK_DATA64)
377 : PE_RVA2TYPE(pvBitsR, pImps->u.OriginalFirstThunk, PIMAGE_THUNK_DATA64);
378 while (!rc && pThunk->u1.Ordinal != 0)
379 {
380 RTUINTPTR Value = 0;
381 if (pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG64)
382 {
383 rc = pfnGetImport(&pModPe->Core, pszModName, NULL, (unsigned)IMAGE_ORDINAL64(pThunk->u1.Ordinal), &Value, pvUser);
384 Log4((RT_SUCCESS(rc) ? "RTLdrPE: %016RX64 #%u\n" : "RTLdrPE: %016RX64 #%u rc=%Rrc\n",
385 (uint64_t)Value, (unsigned)IMAGE_ORDINAL64(pThunk->u1.Ordinal), rc));
386 }
387 else if ( pThunk->u1.Ordinal > 0
388 && pThunk->u1.Ordinal < pModPe->cbImage)
389 {
390 /** @todo add validation of the string pointer! */
391 rc = pfnGetImport(&pModPe->Core, pszModName, PE_RVA2TYPE(pvBitsR, (uintptr_t)pThunk->u1.AddressOfData + 2, const char *),
392 ~0, &Value, pvUser);
393 Log4((RT_SUCCESS(rc) ? "RTLdrPE: %016RX64 %s\n" : "RTLdrPE: %016RX64 %s rc=%Rrc\n",
394 (uint64_t)Value, PE_RVA2TYPE(pvBitsR, (uintptr_t)pThunk->u1.AddressOfData + 2, const char *), rc));
395 }
396 else
397 {
398 AssertMsgFailed(("bad import data thunk!\n"));
399 rc = VERR_BAD_EXE_FORMAT;
400 }
401 pFirstThunk->u1.Function = Value;
402 pThunk++;
403 pFirstThunk++;
404 }
405 }
406
407 return rc;
408}
409
410
411/**
412 * Applies fixups.
413 */
414static int rtldrPEApplyFixups(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, RTUINTPTR BaseAddress, RTUINTPTR OldBaseAddress)
415{
416 if ( !pModPe->RelocDir.VirtualAddress
417 || !pModPe->RelocDir.Size)
418 return 0;
419
420 /*
421 * Apply delta fixups iterating fixup chunks.
422 */
423 PIMAGE_BASE_RELOCATION pbr = PE_RVA2TYPE(pvBitsR, pModPe->RelocDir.VirtualAddress, PIMAGE_BASE_RELOCATION);
424 PIMAGE_BASE_RELOCATION pBaseRelocs = pbr;
425 unsigned cbBaseRelocs = pModPe->RelocDir.Size;
426 RTUINTPTR uDelta = BaseAddress - OldBaseAddress;
427 Log2(("RTLdrPE: Fixups: uDelta=%#RTptr BaseAddress=%#RTptr OldBaseAddress=%#RTptr\n", uDelta, BaseAddress, OldBaseAddress));
428 Log4(("RTLdrPE: BASERELOC: VirtualAddres=%RX32 Size=%RX32\n", pModPe->RelocDir.VirtualAddress, pModPe->RelocDir.Size));
429 Assert(sizeof(*pbr) == sizeof(uint32_t) * 2);
430
431 while ( (uintptr_t)pbr - (uintptr_t)pBaseRelocs + 8 < cbBaseRelocs /* 8= VirtualAddress and SizeOfBlock members */
432 && pbr->SizeOfBlock >= 8)
433 {
434 uint16_t *pwoffFixup = (uint16_t *)(pbr + 1);
435 uint32_t cRelocations = (pbr->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(uint16_t);
436 Log3(("RTLdrPE: base relocs for %#010x, size %#06x (%d relocs)\n", pbr->VirtualAddress, pbr->SizeOfBlock, cRelocations));
437
438 /* Some bound checking just to be sure it works... */
439 if ((uintptr_t)pbr - (uintptr_t)pBaseRelocs + pbr->SizeOfBlock > cbBaseRelocs)
440 cRelocations = (((uintptr_t)pBaseRelocs + cbBaseRelocs) - (uintptr_t)pbr - sizeof(IMAGE_BASE_RELOCATION)) / sizeof(uint16_t);
441
442 /*
443 * Loop thru the fixups in this chunk.
444 */
445 while (cRelocations != 0)
446 {
447 /*
448 * Common fixup
449 */
450 static const char * const s_apszReloc[16] =
451 {
452 "ABS", "HIGH", "LOW", "HIGHLOW", "HIGHADJ", "MIPS_JMPADDR", "RES6", "RES7",
453 "RES8", "IA64_IMM64", "DIR64", "HIGH3ADJ", "RES12", "RES13", "RES14", "RES15"
454 }; NOREF(s_apszReloc);
455 union
456 {
457 uint16_t *pu16;
458 uint32_t *pu32;
459 uint64_t *pu64;
460 } u;
461 const int offFixup = *pwoffFixup & 0xfff;
462 u.pu32 = PE_RVA2TYPE(pvBitsW, offFixup + pbr->VirtualAddress, uint32_t *);
463 const int fType = *pwoffFixup >> 12;
464 Log4(("RTLdrPE: %08x %s\n", offFixup + pbr->VirtualAddress, s_apszReloc[fType]));
465 switch (fType)
466 {
467 case IMAGE_REL_BASED_HIGHLOW: /* 32-bit, add delta. */
468 *u.pu32 += uDelta;
469 break;
470 case IMAGE_REL_BASED_DIR64: /* 64-bit, add delta. */
471 *u.pu64 += (RTINTPTR)uDelta;
472 break;
473 case IMAGE_REL_BASED_ABSOLUTE: /* Alignment placeholder. */
474 break;
475 /* odd ones */
476 case IMAGE_REL_BASED_LOW: /* 16-bit, add 1st 16-bit part of the delta. */
477 *u.pu16 += (uint16_t)uDelta;
478 break;
479 case IMAGE_REL_BASED_HIGH: /* 16-bit, add 2nd 16-bit part of the delta. */
480 *u.pu16 += (uint16_t)(uDelta >> 16);
481 break;
482 /* never ever seen these next two, and I'm not 100% sure they are correctly implemented here. */
483 case IMAGE_REL_BASED_HIGHADJ:
484 {
485 if (cRelocations <= 1)
486 {
487 AssertMsgFailed(("HIGHADJ missing 2nd record!\n"));
488 return VERR_BAD_EXE_FORMAT;
489 }
490 cRelocations--;
491 pwoffFixup++;
492 int32_t i32 = (uint32_t)(*u.pu16 << 16) | *pwoffFixup;
493 i32 += uDelta;
494 i32 += 0x8000; //??
495 *u.pu16 = (uint16_t)(i32 >> 16);
496 break;
497 }
498 case IMAGE_REL_BASED_HIGH3ADJ:
499 {
500 if (cRelocations <= 2)
501 {
502 AssertMsgFailed(("HIGHADJ3 missing 2nd record!\n"));
503 return VERR_BAD_EXE_FORMAT;
504 }
505 cRelocations -= 2;
506 pwoffFixup++;
507 int64_t i64 = ((uint64_t)*u.pu16 << 32) | *(uint32_t *)pwoffFixup++;
508 i64 += (int64_t)uDelta << 16; //??
509 i64 += 0x80000000;//??
510 *u.pu16 = (uint16_t)(i64 >> 32);
511 break;
512 }
513 default:
514 AssertMsgFailed(("Unknown fixup type %d offset=%#x\n", fType, offFixup));
515 break;
516 }
517
518 /*
519 * Next offset/type
520 */
521 pwoffFixup++;
522 cRelocations--;
523 } /* while loop */
524
525 /*
526 * Next Fixup chunk. (i.e. next page)
527 */
528 pbr = (PIMAGE_BASE_RELOCATION)((uintptr_t)pbr + pbr->SizeOfBlock);
529 } /* while loop */
530
531 return 0;
532}
533
534
535/** @copydoc RTLDROPS::pfnRelocate. */
536static int rtldrPERelocate(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR NewBaseAddress, RTUINTPTR OldBaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
537{
538 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
539
540 /*
541 * Do we have to read the image bits?
542 */
543 if (!pModPe->pvBits)
544 {
545 int rc = rtldrPEReadBits(pModPe);
546 if (RT_FAILURE(rc))
547 return rc;
548 }
549
550 /*
551 * Process imports.
552 */
553 int rc = ((PRTLDROPSPE)pMod->pOps)->pfnResolveImports(pModPe, pModPe->pvBits, pvBits, pfnGetImport, pvUser);
554 if (RT_SUCCESS(rc))
555 {
556 /*
557 * Apply relocations.
558 */
559 rc = rtldrPEApplyFixups(pModPe, pModPe->pvBits, pvBits, NewBaseAddress, OldBaseAddress);
560 AssertRC(rc);
561 }
562 return rc;
563}
564
565
566/** @copydoc RTLDROPS::pfnGetSymbolEx. */
567static DECLCALLBACK(int) rtldrPEGetSymbolEx(PRTLDRMODINTERNAL pMod, const void *pvBits, RTUINTPTR BaseAddress, const char *pszSymbol, RTUINTPTR *pValue)
568{
569 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
570
571 /*
572 * Check if there is actually anything to work on.
573 */
574 if ( !pModPe->ExportDir.VirtualAddress
575 || !pModPe->ExportDir.Size)
576 return VERR_SYMBOL_NOT_FOUND;
577
578 /*
579 * No bits supplied? Do we need to read the bits?
580 */
581 if (!pvBits)
582 {
583 if (!pModPe->pvBits)
584 {
585 int rc = rtldrPEReadBits(pModPe);
586 if (RT_FAILURE(rc))
587 return rc;
588 }
589 pvBits = pModPe->pvBits;
590 }
591
592 PIMAGE_EXPORT_DIRECTORY pExpDir = PE_RVA2TYPE(pvBits, pModPe->ExportDir.VirtualAddress, PIMAGE_EXPORT_DIRECTORY);
593 int iExpOrdinal = 0; /* index into address table. */
594 if ((uintptr_t)pszSymbol <= 0xffff)
595 {
596 /*
597 * Find ordinal export: Simple table lookup.
598 */
599 unsigned uOrdinal = (uintptr_t)pszSymbol & 0xffff;
600 if ( uOrdinal >= pExpDir->Base + RT_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions)
601 || uOrdinal < pExpDir->Base)
602 return VERR_SYMBOL_NOT_FOUND;
603 iExpOrdinal = uOrdinal - pExpDir->Base;
604 }
605 else
606 {
607 /*
608 * Find Named Export: Do binary search on the name table.
609 */
610 uint32_t *paRVANames = PE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, uint32_t *);
611 uint16_t *paOrdinals = PE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, uint16_t *);
612 int iStart = 1;
613 int iEnd = pExpDir->NumberOfNames;
614
615 for (;;)
616 {
617 /* end of search? */
618 if (iStart > iEnd)
619 {
620 #ifdef RT_STRICT
621 /* do a linear search just to verify the correctness of the above algorithm */
622 for (unsigned i = 0; i < pExpDir->NumberOfNames; i++)
623 {
624 AssertMsg(i == 0 || strcmp(PE_RVA2TYPE(pvBits, paRVANames[i], const char *), PE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *)) > 0,
625 ("bug in binary export search!!!\n"));
626 AssertMsg(strcmp(PE_RVA2TYPE(pvBits, paRVANames[i], const char *), pszSymbol) != 0,
627 ("bug in binary export search!!!\n"));
628 }
629 #endif
630 return VERR_SYMBOL_NOT_FOUND;
631 }
632
633 int i = (iEnd - iStart) / 2 + iStart;
634 const char *pszExpName = PE_RVA2TYPE(pvBits, paRVANames[i - 1], const char *);
635 int diff = strcmp(pszExpName, pszSymbol);
636 if (diff > 0) /* pszExpName > pszSymbol: search chunck before i */
637 iEnd = i - 1;
638 else if (diff) /* pszExpName < pszSymbol: search chunk after i */
639 iStart = i + 1;
640 else /* pszExpName == pszSymbol */
641 {
642 iExpOrdinal = paOrdinals[i - 1];
643 break;
644 }
645 } /* binary search thru name table */
646 }
647
648 /*
649 * Found export (iExpOrdinal).
650 */
651 uint32_t * paAddress = PE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, uint32_t *);
652 unsigned uRVAExport = paAddress[iExpOrdinal];
653
654 if ( uRVAExport > pModPe->ExportDir.VirtualAddress
655 && uRVAExport < pModPe->ExportDir.VirtualAddress + pModPe->ExportDir.Size)
656 {
657 /* Resolve forwarder. */
658 AssertMsgFailed(("Forwarders are not supported!\n"));
659 return VERR_SYMBOL_NOT_FOUND;
660 }
661
662 /* Get plain export address */
663 *pValue = PE_RVA2TYPE(BaseAddress, uRVAExport, RTUINTPTR);
664
665 return VINF_SUCCESS;
666}
667
668
669/** @copydoc RTLDROPS::pfnEnumSymbols */
670static DECLCALLBACK(int) rtldrPEEnumSymbols(PRTLDRMODINTERNAL pMod, unsigned fFlags, const void *pvBits, RTUINTPTR BaseAddress,
671 PFNRTLDRENUMSYMS pfnCallback, void *pvUser)
672{
673 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
674
675 /*
676 * Check if there is actually anything to work on.
677 */
678 if ( !pModPe->ExportDir.VirtualAddress
679 || !pModPe->ExportDir.Size)
680 return VERR_SYMBOL_NOT_FOUND;
681
682 /*
683 * No bits supplied? Do we need to read the bits?
684 */
685 if (!pvBits)
686 {
687 if (!pModPe->pvBits)
688 {
689 int rc = rtldrPEReadBits(pModPe);
690 if (RT_FAILURE(rc))
691 return rc;
692 }
693 pvBits = pModPe->pvBits;
694 }
695
696 /*
697 * We enumerates by ordinal, which means using a slow linear search for
698 * getting any name
699 */
700 PIMAGE_EXPORT_DIRECTORY pExpDir = PE_RVA2TYPE(pvBits, pModPe->ExportDir.VirtualAddress, PIMAGE_EXPORT_DIRECTORY);
701 uint32_t *paAddress = PE_RVA2TYPE(pvBits, pExpDir->AddressOfFunctions, uint32_t *);
702 uint32_t *paRVANames = PE_RVA2TYPE(pvBits, pExpDir->AddressOfNames, uint32_t *);
703 uint16_t *paOrdinals = PE_RVA2TYPE(pvBits, pExpDir->AddressOfNameOrdinals, uint16_t *);
704 uintptr_t uNamePrev = 0;
705 unsigned cOrdinals = RT_MAX(pExpDir->NumberOfNames, pExpDir->NumberOfFunctions);
706 for (unsigned uOrdinal = 0; uOrdinal < cOrdinals; uOrdinal++)
707 {
708 if (paAddress[uOrdinal] /* needed? */)
709 {
710 /*
711 * Look for name.
712 */
713 const char *pszName = NULL;
714 /* Search from previous + 1 to the end. */
715 unsigned uName = uNamePrev + 1;
716 while (uName < pExpDir->NumberOfNames)
717 {
718 if (paOrdinals[uName] == uOrdinal)
719 {
720 pszName = PE_RVA2TYPE(pvBits, paRVANames[uName], const char *);
721 uNamePrev = uName;
722 break;
723 }
724 uName++;
725 }
726 if (!pszName)
727 {
728 /* Search from start to the previous. */
729 uName = 0;
730 for (uName = 0 ; uName <= uNamePrev; uName++)
731 {
732 if (paOrdinals[uName] == uOrdinal)
733 {
734 pszName = PE_RVA2TYPE(pvBits, paRVANames[uName], const char *);
735 uNamePrev = uName;
736 break;
737 }
738 }
739 }
740
741 /*
742 * Get address.
743 */
744 uintptr_t uRVAExport = paAddress[uOrdinal];
745 RTUINTPTR Value;
746 if ( uRVAExport - (uintptr_t)pModPe->ExportDir.VirtualAddress
747 < pModPe->ExportDir.Size)
748 {
749 /* Resolve forwarder. */
750 AssertMsgFailed(("Forwarders are not supported!\n"));
751 continue;
752 }
753 else
754 /* Get plain export address */
755 Value = PE_RVA2TYPE(BaseAddress, uRVAExport, RTUINTPTR);
756
757 /*
758 * Call back.
759 */
760 int rc = pfnCallback(pMod, pszName, uOrdinal + pExpDir->Base, Value, pvUser);
761 if (rc)
762 return rc;
763 }
764 }
765
766 return VINF_SUCCESS;
767}
768
769
770/** @copydoc RTLDROPS::pfnEnumDbgInfo. */
771static DECLCALLBACK(int) rtldrPE_EnumDbgInfo(PRTLDRMODINTERNAL pMod, const void *pvBits,
772 PFNRTLDRENUMDBG pfnCallback, void *pvUser)
773{
774 return VINF_NOT_SUPPORTED;
775}
776
777
778/** @copydoc RTLDROPS::pfnDone */
779static DECLCALLBACK(int) rtldrPEDone(PRTLDRMODINTERNAL pMod)
780{
781 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
782 if (pModPe->pvBits)
783 {
784 RTMemFree(pModPe->pvBits);
785 pModPe->pvBits = NULL;
786 }
787 if (pModPe->pReader)
788 {
789 int rc = pModPe->pReader->pfnDestroy(pModPe->pReader);
790 AssertRC(rc);
791 pModPe->pReader = NULL;
792 }
793 return VINF_SUCCESS;
794}
795
796/** @copydoc RTLDROPS::pfnClose */
797static DECLCALLBACK(int) rtldrPEClose(PRTLDRMODINTERNAL pMod)
798{
799 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
800 if (pModPe->paSections)
801 {
802 RTMemFree(pModPe->paSections);
803 pModPe->paSections = NULL;
804 }
805 if (pModPe->pvBits)
806 {
807 RTMemFree(pModPe->pvBits);
808 pModPe->pvBits = NULL;
809 }
810 if (pModPe->pReader)
811 {
812 int rc = pModPe->pReader->pfnDestroy(pModPe->pReader);
813 AssertRC(rc);
814 pModPe->pReader = NULL;
815 }
816 return VINF_SUCCESS;
817}
818
819
820/**
821 * Operations for a 32-bit PE module.
822 */
823static const RTLDROPSPE s_rtldrPE32Ops =
824{
825 {
826 "pe32",
827 rtldrPEClose,
828 NULL,
829 rtldrPEDone,
830 rtldrPEEnumSymbols,
831 /* ext */
832 rtldrPEGetImageSize,
833 rtldrPEGetBits,
834 rtldrPERelocate,
835 rtldrPEGetSymbolEx,
836 rtldrPE_EnumDbgInfo,
837 42
838 },
839 rtldrPEResolveImports32,
840 42
841};
842
843
844/**
845 * Operations for a 64-bit PE module.
846 */
847static const RTLDROPSPE s_rtldrPE64Ops =
848{
849 {
850 "pe64",
851 rtldrPEClose,
852 NULL,
853 rtldrPEDone,
854 rtldrPEEnumSymbols,
855 /* ext */
856 rtldrPEGetImageSize,
857 rtldrPEGetBits,
858 rtldrPERelocate,
859 rtldrPEGetSymbolEx,
860 rtldrPE_EnumDbgInfo,
861 42
862 },
863 rtldrPEResolveImports64,
864 42
865};
866
867
868/**
869 * Converts the optional header from 32 bit to 64 bit.
870 * This is a rather simple task, if you start from the right end.
871 *
872 * @param pOptHdr On input this is a PIMAGE_OPTIONAL_HEADER32.
873 * On output this will be a PIMAGE_OPTIONAL_HEADER64.
874 */
875static void rtldrPEConvert32BitOptionalHeaderTo64Bit(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
876{
877 /*
878 * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
879 */
880 IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
881 IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
882
883 /* from LoaderFlags and out the difference is 4 * 32-bits. */
884 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, LoaderFlags) + 16 == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, LoaderFlags));
885 Assert( RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]) + 16
886 == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]));
887 uint32_t volatile *pu32Dst = (uint32_t *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
888 const uint32_t volatile *pu32Src = (uint32_t *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
889 const uint32_t volatile *pu32SrcLast = (uint32_t *)&pOptHdr32->LoaderFlags;
890 while (pu32Src >= pu32SrcLast)
891 *pu32Dst-- = *pu32Src--;
892
893 /* the previous 4 fields are 32/64 and needs special attention. */
894 pOptHdr64->SizeOfHeapCommit = pOptHdr32->SizeOfHeapCommit;
895 pOptHdr64->SizeOfHeapReserve = pOptHdr32->SizeOfHeapReserve;
896 pOptHdr64->SizeOfStackCommit = pOptHdr32->SizeOfStackCommit;
897 uint32_t u32SizeOfStackReserve = pOptHdr32->SizeOfStackReserve;
898 pOptHdr64->SizeOfStackReserve = u32SizeOfStackReserve;
899
900 /* The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version..
901 * Thus, ImageBase needs some special treatment. It will probably work fine assigning one to the
902 * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
903 */
904 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, SizeOfStackReserve) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve));
905 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, BaseOfData) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, ImageBase));
906 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, SectionAlignment) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, SectionAlignment));
907 uint32_t u32ImageBase = pOptHdr32->ImageBase;
908 pOptHdr64->ImageBase = u32ImageBase;
909}
910
911
912/**
913 * Converts the load config directory from 32 bit to 64 bit.
914 * This is a rather simple task, if you start from the right end.
915 *
916 * @param pLoadCfg On input this is a PIMAGE_LOAD_CONFIG_DIRECTORY32.
917 * On output this will be a PIMAGE_LOAD_CONFIG_DIRECTORY64.
918 */
919static void rtldrPEConvert32BitLoadConfigTo64Bit(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
920{
921 /*
922 * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
923 */
924 IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
925 IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
926
927 pLoadCfg64->SEHandlerCount = pLoadCfg32->SEHandlerCount;
928 pLoadCfg64->SEHandlerTable = pLoadCfg32->SEHandlerTable;
929 pLoadCfg64->SecurityCookie = pLoadCfg32->SecurityCookie;
930 pLoadCfg64->EditList = pLoadCfg32->EditList;
931 pLoadCfg64->Reserved1 = pLoadCfg32->Reserved1;
932 pLoadCfg64->CSDVersion = pLoadCfg32->CSDVersion;
933 pLoadCfg64->ProcessHeapFlags = pLoadCfg32->ProcessHeapFlags; /* switched place with ProcessAffinityMask, but we're more than 16 byte off by now so it doesn't matter. */
934 pLoadCfg64->ProcessAffinityMask = pLoadCfg32->ProcessAffinityMask;
935 pLoadCfg64->VirtualMemoryThreshold = pLoadCfg32->VirtualMemoryThreshold;
936 pLoadCfg64->MaximumAllocationSize = pLoadCfg32->MaximumAllocationSize;
937 pLoadCfg64->LockPrefixTable = pLoadCfg32->LockPrefixTable;
938 pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
939 uint32_t u32DeCommitFreeBlockThreshold = pLoadCfg32->DeCommitFreeBlockThreshold;
940 pLoadCfg64->DeCommitFreeBlockThreshold = u32DeCommitFreeBlockThreshold;
941 /* the rest is equal. */
942 Assert( RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, DeCommitFreeBlockThreshold)
943 == RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY64, DeCommitFreeBlockThreshold));
944}
945
946
947/**
948 * Validates the file header.
949 *
950 * @returns iprt status code.
951 * @param pFileHdr Pointer to the file header that needs validating.
952 * @param pszLogName The log name to prefix the errors with.
953 * @param penmArch Where to store the CPU architecture.
954 */
955int rtldrPEValidateFileHeader(PIMAGE_FILE_HEADER pFileHdr, const char *pszLogName, PRTLDRARCH penmArch)
956{
957 size_t cbOptionalHeader;
958 switch (pFileHdr->Machine)
959 {
960 case IMAGE_FILE_MACHINE_I386:
961 cbOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32);
962 *penmArch = RTLDRARCH_X86_32;
963 break;
964 case IMAGE_FILE_MACHINE_AMD64:
965 cbOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
966 *penmArch = RTLDRARCH_AMD64;
967 break;
968
969 default:
970 Log(("rtldrPEOpen: %s: Unsupported Machine=%#x\n",
971 pszLogName, pFileHdr->Machine));
972 *penmArch = RTLDRARCH_INVALID;
973 return VERR_BAD_EXE_FORMAT;
974 }
975 if (pFileHdr->SizeOfOptionalHeader != cbOptionalHeader)
976 {
977 Log(("rtldrPEOpen: %s: SizeOfOptionalHeader=%#x expected %#x\n",
978 pszLogName, pFileHdr->SizeOfOptionalHeader, cbOptionalHeader));
979 return VERR_BAD_EXE_FORMAT;
980 }
981 /* This restriction needs to be implemented elsewhere. */
982 if (pFileHdr->Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
983 {
984 Log(("rtldrPEOpen: %s: IMAGE_FILE_RELOCS_STRIPPED\n", pszLogName));
985 return VERR_BAD_EXE_FORMAT;
986 }
987 if (pFileHdr->NumberOfSections > 42)
988 {
989 Log(("rtldrPEOpen: %s: NumberOfSections=%d - our limit is 42, please raise it if the binary makes sense.(!!!)\n",
990 pszLogName, pFileHdr->NumberOfSections));
991 return VERR_BAD_EXE_FORMAT;
992 }
993 if (pFileHdr->NumberOfSections < 1)
994 {
995 Log(("rtldrPEOpen: %s: NumberOfSections=%d - we can't have an image without sections (!!!)\n",
996 pszLogName, pFileHdr->NumberOfSections));
997 return VERR_BAD_EXE_FORMAT;
998 }
999 return VINF_SUCCESS;
1000}
1001
1002
1003/**
1004 * Validates the optional header (64/32-bit)
1005 *
1006 * @returns iprt status code.
1007 * @param pOptHdr Pointer to the optional header which needs validation.
1008 * @param pszLogName The log name to prefix the errors with.
1009 * @param offNtHdrs The offset of the NT headers from teh start of the file.
1010 * @param pFileHdr Pointer to the file header (valid).
1011 * @param cbRawImage The raw image size.
1012 */
1013static int rtldrPEValidateOptionalHeader(const IMAGE_OPTIONAL_HEADER64 *pOptHdr, const char *pszLogName, RTFOFF offNtHdrs,
1014 const IMAGE_FILE_HEADER *pFileHdr, RTFOFF cbRawImage)
1015{
1016 const uint16_t CorrectMagic = pFileHdr->SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
1017 ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1018 if (pOptHdr->Magic != CorrectMagic)
1019 {
1020 Log(("rtldrPEOpen: %s: Magic=%#x - expected %#x!!!\n", pszLogName, pOptHdr->Magic, CorrectMagic));
1021 return VERR_BAD_EXE_FORMAT;
1022 }
1023 const uint32_t cbImage = pOptHdr->SizeOfImage;
1024 if (cbImage > _1G)
1025 {
1026 Log(("rtldrPEOpen: %s: SizeOfImage=%#x - Our limit is 1GB (%#x)!!!\n", pszLogName, cbImage, _1G));
1027 return VERR_BAD_EXE_FORMAT;
1028 }
1029 const uint32_t cbMinImageSize = pFileHdr->SizeOfOptionalHeader + sizeof(*pFileHdr) + 4 + (uint32_t)offNtHdrs;
1030 if (cbImage < cbMinImageSize)
1031 {
1032 Log(("rtldrPEOpen: %s: SizeOfImage=%#x to small, minimum %#x!!!\n", pszLogName, cbImage, cbMinImageSize));
1033 return VERR_BAD_EXE_FORMAT;
1034 }
1035 if (pOptHdr->AddressOfEntryPoint >= cbImage)
1036 {
1037 Log(("rtldrPEOpen: %s: AddressOfEntryPoint=%#x - beyond image size (%#x)!!!\n",
1038 pszLogName, pOptHdr->AddressOfEntryPoint, cbImage));
1039 return VERR_BAD_EXE_FORMAT;
1040 }
1041 if (pOptHdr->BaseOfCode >= cbImage)
1042 {
1043 Log(("rtldrPEOpen: %s: BaseOfCode=%#x - beyond image size (%#x)!!!\n",
1044 pszLogName, pOptHdr->BaseOfCode, cbImage));
1045 return VERR_BAD_EXE_FORMAT;
1046 }
1047#if 0/* only in 32-bit header */
1048 if (pOptHdr->BaseOfData >= cbImage)
1049 {
1050 Log(("rtldrPEOpen: %s: BaseOfData=%#x - beyond image size (%#x)!!!\n",
1051 pszLogName, pOptHdr->BaseOfData, cbImage));
1052 return VERR_BAD_EXE_FORMAT;
1053 }
1054#endif
1055 if (pOptHdr->SizeOfHeaders >= cbImage)
1056 {
1057 Log(("rtldrPEOpen: %s: SizeOfHeaders=%#x - beyond image size (%#x)!!!\n",
1058 pszLogName, pOptHdr->SizeOfHeaders, cbImage));
1059 return VERR_BAD_EXE_FORMAT;
1060 }
1061 /* don't know how to do the checksum, so ignore it. */
1062 if (pOptHdr->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1063 {
1064 Log(("rtldrPEOpen: %s: Subsystem=%#x (unknown)!!!\n", pszLogName, pOptHdr->Subsystem));
1065 return VERR_BAD_EXE_FORMAT;
1066 }
1067 if (pOptHdr->SizeOfHeaders < cbMinImageSize + pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER))
1068 {
1069 Log(("rtldrPEOpen: %s: SizeOfHeaders=%#x - cbMinImageSize %#x + sections %#x = %#llx!!!\n",
1070 pszLogName, pOptHdr->SizeOfHeaders,
1071 cbImage, cbMinImageSize, pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER),
1072 cbMinImageSize + pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)));
1073 return VERR_BAD_EXE_FORMAT;
1074 }
1075 if (pOptHdr->SizeOfStackReserve < pOptHdr->SizeOfStackCommit)
1076 {
1077 Log(("rtldrPEOpen: %s: SizeOfStackReserve %#x < SizeOfStackCommit %#x!!!\n",
1078 pszLogName, pOptHdr->SizeOfStackReserve, pOptHdr->SizeOfStackCommit));
1079 return VERR_BAD_EXE_FORMAT;
1080 }
1081 if (pOptHdr->SizeOfHeapReserve < pOptHdr->SizeOfHeapCommit)
1082 {
1083 Log(("rtldrPEOpen: %s: SizeOfStackReserve %#x < SizeOfStackCommit %#x!!!\n",
1084 pszLogName, pOptHdr->SizeOfStackReserve, pOptHdr->SizeOfStackCommit));
1085 return VERR_BAD_EXE_FORMAT;
1086 }
1087
1088 /* DataDirectory */
1089 if (pOptHdr->NumberOfRvaAndSizes != RT_ELEMENTS(pOptHdr->DataDirectory))
1090 {
1091 Log(("rtldrPEOpen: %s: NumberOfRvaAndSizes=%d!!!\n", pszLogName, pOptHdr->NumberOfRvaAndSizes));
1092 return VERR_BAD_EXE_FORMAT;
1093 }
1094 for (unsigned i = 0; i < RT_ELEMENTS(pOptHdr->DataDirectory); i++)
1095 {
1096 IMAGE_DATA_DIRECTORY const *pDir = &pOptHdr->DataDirectory[i];
1097 if (!pDir->Size)
1098 continue;
1099 size_t cb = cbImage;
1100 switch (i)
1101 {
1102 case IMAGE_DIRECTORY_ENTRY_EXPORT: // 0
1103 case IMAGE_DIRECTORY_ENTRY_IMPORT: // 1
1104 case IMAGE_DIRECTORY_ENTRY_RESOURCE: // 2
1105 case IMAGE_DIRECTORY_ENTRY_EXCEPTION: // 3
1106 case IMAGE_DIRECTORY_ENTRY_BASERELOC: // 5
1107 case IMAGE_DIRECTORY_ENTRY_DEBUG: // 6
1108 case IMAGE_DIRECTORY_ENTRY_COPYRIGHT: // 7
1109 case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: // 11
1110 case IMAGE_DIRECTORY_ENTRY_IAT: // 12 /* Import Address Table */
1111 break;
1112 case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: // 10 - need to check for lock prefixes.
1113 /* Delay inspection after section table is validated. */
1114 break;
1115
1116 case IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT: // 13
1117 Log(("rtldrPEOpen: %s: dir no. %d (DELAY_IMPORT) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1118 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1119 return VERR_LDRPE_DELAY_IMPORT;
1120
1121 case IMAGE_DIRECTORY_ENTRY_SECURITY: // 4
1122 /* The VirtualAddress is a PointerToRawData. */
1123 cb = (size_t)cbRawImage; Assert((RTFOFF)cb == cbRawImage);
1124 Log(("rtldrPEOpen: %s: dir no. %d (SECURITY) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1125 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1126 if (pDir->Size < sizeof(WIN_CERTIFICATE))
1127 {
1128 Log(("rtldrPEOpen: %s: Security directory is too small: %#x bytes\n", pszLogName, i, pDir->Size));
1129 return VERR_LDRPE_CERT_MALFORMED;
1130 }
1131 if (pDir->Size >= _1M)
1132 {
1133 Log(("rtldrPEOpen: %s: Security directory is too large: %#x bytes\n", pszLogName, i, pDir->Size));
1134 return VERR_LDRPE_CERT_MALFORMED;
1135 }
1136 if (pDir->VirtualAddress & 7)
1137 {
1138 Log(("rtldrPEOpen: %s: Security directory is misaligned: %#x\n", pszLogName, i, pDir->VirtualAddress));
1139 return VERR_LDRPE_CERT_MALFORMED;
1140 }
1141 break;
1142
1143 case IMAGE_DIRECTORY_ENTRY_GLOBALPTR: // 8 /* (MIPS GP) */
1144 Log(("rtldrPEOpen: %s: dir no. %d (GLOBALPTR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1145 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1146 return VERR_LDRPE_GLOBALPTR;
1147
1148 case IMAGE_DIRECTORY_ENTRY_TLS: // 9
1149 Log(("rtldrPEOpen: %s: dir no. %d (TLS) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1150 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1151 return VERR_LDRPE_TLS;
1152
1153 case IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR:// 14
1154 Log(("rtldrPEOpen: %s: dir no. %d (COM_DESCRIPTOR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1155 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1156 return VERR_LDRPE_COM_DESCRIPTOR;
1157
1158 default:
1159 Log(("rtldrPEOpen: %s: dir no. %d VirtualAddress=%#x Size=%#x is not supported!!!\n",
1160 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1161 return VERR_BAD_EXE_FORMAT;
1162 }
1163 if (pDir->VirtualAddress >= cb)
1164 {
1165 Log(("rtldrPEOpen: %s: dir no. %d VirtualAddress=%#x is invalid (limit %#x)!!!\n",
1166 pszLogName, i, pDir->VirtualAddress, cb));
1167 return VERR_BAD_EXE_FORMAT;
1168 }
1169 if (pDir->Size > cb - pDir->VirtualAddress)
1170 {
1171 Log(("rtldrPEOpen: %s: dir no. %d Size=%#x is invalid (rva=%#x, limit=%#x)!!!\n",
1172 pszLogName, i, pDir->Size, pDir->VirtualAddress, cb));
1173 return VERR_BAD_EXE_FORMAT;
1174 }
1175 }
1176 return VINF_SUCCESS;
1177}
1178
1179
1180/**
1181 * Validates the section headers.
1182 *
1183 * @returns iprt status code.
1184 * @param paSections Pointer to the array of sections that is to be validated.
1185 * @param cSections Number of sections in that array.
1186 * @param pszLogName The log name to prefix the errors with.
1187 * @param pOptHdr Pointer to the optional header (valid).
1188 * @param cbRawImage The raw image size.
1189 */
1190int rtldrPEValidateSectionHeaders(const IMAGE_SECTION_HEADER *paSections, unsigned cSections, const char *pszLogName,
1191 const IMAGE_OPTIONAL_HEADER64 *pOptHdr, RTFOFF cbRawImage)
1192{
1193 const uint32_t cbImage = pOptHdr->SizeOfImage;
1194 const IMAGE_SECTION_HEADER *pSH = &paSections[0];
1195 uint32_t uRvaPrev = pOptHdr->SizeOfHeaders;
1196 Log3(("RTLdrPE: Section Headers:\n"));
1197 for (unsigned cSHdrsLeft = cSections; cSHdrsLeft > 0; cSHdrsLeft--, pSH++)
1198 {
1199 const unsigned iSH = pSH - &paSections[0]; NOREF(iSH);
1200 Log3(("RTLdrPE: #%d '%-8.8s' Characteristics: %08RX32\n"
1201 "RTLdrPE: VirtAddr: %08RX32 VirtSize: %08RX32\n"
1202 "RTLdrPE: FileOff: %08RX32 FileSize: %08RX32\n"
1203 "RTLdrPE: RelocOff: %08RX32 #Relocs: %08RX32\n"
1204 "RTLdrPE: LineOff: %08RX32 #Lines: %08RX32\n",
1205 iSH, pSH->Name, pSH->Characteristics,
1206 pSH->VirtualAddress, pSH->Misc.VirtualSize,
1207 pSH->PointerToRawData, pSH->SizeOfRawData,
1208 pSH->PointerToRelocations, pSH->NumberOfRelocations,
1209 pSH->PointerToLinenumbers, pSH->NumberOfLinenumbers));
1210 if (pSH->Characteristics & (IMAGE_SCN_MEM_16BIT | IMAGE_SCN_MEM_FARDATA | IMAGE_SCN_MEM_PURGEABLE | IMAGE_SCN_MEM_PRELOAD))
1211 {
1212 Log(("rtldrPEOpen: %s: Unsupported section flag(s) %#x section #%d '%.*s'!!!\n",
1213 pszLogName, pSH->Characteristics, iSH, sizeof(pSH->Name), pSH->Name));
1214 return VERR_BAD_EXE_FORMAT;
1215 }
1216
1217 if ( pSH->Misc.VirtualSize
1218 && !(pSH->Characteristics & IMAGE_SCN_TYPE_NOLOAD)) /* binutils uses this for '.stab' even if it's reserved/obsoleted by MS. */
1219 {
1220 if (pSH->VirtualAddress < uRvaPrev)
1221 {
1222 Log(("rtldrPEOpen: %s: Overlaps previous section or sections aren't in ascending order, VirtualAddress=%#x uRvaPrev=%#x - section #%d '%.*s'!!!\n",
1223 pszLogName, pSH->VirtualAddress, uRvaPrev, iSH, sizeof(pSH->Name), pSH->Name));
1224 return VERR_BAD_EXE_FORMAT;
1225 }
1226 if (pSH->VirtualAddress > cbImage)
1227 {
1228 Log(("rtldrPEOpen: %s: VirtualAddress=%#x - beyond image size (%#x) - section #%d '%.*s'!!!\n",
1229 pszLogName, pSH->VirtualAddress, cbImage, iSH, sizeof(pSH->Name), pSH->Name));
1230 return VERR_BAD_EXE_FORMAT;
1231 }
1232
1233 if (pSH->VirtualAddress & (pOptHdr->SectionAlignment - 1)) //ASSUMES power of 2 alignment.
1234 {
1235 Log(("rtldrPEOpen: %s: VirtualAddress=%#x misaligned (%#x) - section #%d '%.*s'!!!\n",
1236 pszLogName, pSH->VirtualAddress, pOptHdr->SectionAlignment, iSH, sizeof(pSH->Name), pSH->Name));
1237 return VERR_BAD_EXE_FORMAT;
1238 }
1239
1240#ifdef PE_FILE_OFFSET_EQUALS_RVA
1241 /* Our loader code assume rva matches the file offset. */
1242 if ( pSH->SizeOfRawData
1243 && pSH->PointerToRawData != pSH->VirtualAddress)
1244 {
1245 Log(("rtldrPEOpen: %s: ASSUMPTION FAILED: file offset %#x != RVA %#x - section #%d '%.*s'!!!\n",
1246 pszLogName, pSH->PointerToRawData, pSH->VirtualAddress, iSH, sizeof(pSH->Name), pSH->Name));
1247 return VERR_BAD_EXE_FORMAT;
1248 }
1249#endif
1250 }
1251
1252 ///@todo only if SizeOfRawData > 0 ?
1253 if ( pSH->PointerToRawData > cbRawImage /// @todo pSH->PointerToRawData >= cbRawImage ?
1254 || pSH->SizeOfRawData > cbRawImage
1255 || pSH->PointerToRawData + pSH->SizeOfRawData > cbRawImage)
1256 {
1257 Log(("rtldrPEOpen: %s: PointerToRawData=%#x SizeOfRawData=%#x - beyond end of file (%#x) - section #%d '%.*s'!!!\n",
1258 pszLogName, pSH->PointerToRawData, pSH->SizeOfRawData, cbRawImage,
1259 iSH, sizeof(pSH->Name), pSH->Name));
1260 return VERR_BAD_EXE_FORMAT;
1261 }
1262
1263 if (pSH->PointerToRawData & (pOptHdr->FileAlignment - 1)) //ASSUMES power of 2 alignment.
1264 {
1265 Log(("rtldrPEOpen: %s: PointerToRawData=%#x misaligned (%#x) - section #%d '%.*s'!!!\n",
1266 pszLogName, pSH->PointerToRawData, pOptHdr->FileAlignment, iSH, sizeof(pSH->Name), pSH->Name));
1267 return VERR_BAD_EXE_FORMAT;
1268 }
1269
1270 /* ignore the relocations and linenumbers. */
1271
1272 uRvaPrev = pSH->VirtualAddress + pSH->Misc.VirtualSize;
1273 }
1274
1275 /** @todo r=bird: more sanity checks! */
1276 return VINF_SUCCESS;
1277}
1278
1279
1280/**
1281 * Reads image data by RVA using the section headers.
1282 *
1283 * @returns iprt status code.
1284 * @param pModPe The PE module instance.
1285 * @param pvBuf Where to store the bits.
1286 * @param cb Number of bytes to tread.
1287 * @param RVA Where to read from.
1288 */
1289static int rtldrPEReadRVA(PRTLDRMODPE pModPe, void *pvBuf, uint32_t cb, uint32_t RVA)
1290{
1291 const IMAGE_SECTION_HEADER *pSH = pModPe->paSections;
1292 PRTLDRREADER pReader = pModPe->pReader;
1293 uint32_t cbRead;
1294 int rc;
1295
1296 /*
1297 * Is it the headers, i.e. prior to the first section.
1298 */
1299 if (RVA < pModPe->cbHeaders)
1300 {
1301 cbRead = RT_MIN(pModPe->cbHeaders - RVA, cb);
1302 rc = pReader->pfnRead(pReader, pvBuf, cbRead, RVA);
1303 if ( cbRead == cb
1304 || RT_FAILURE(rc))
1305 return rc;
1306 cb -= cbRead;
1307 RVA += cbRead;
1308 pvBuf = (uint8_t *)pvBuf + cbRead;
1309 }
1310
1311 /* In the zero space between headers and the first section? */
1312 if (RVA < pSH->VirtualAddress)
1313 {
1314 cbRead = RT_MIN(pSH->VirtualAddress - RVA, cb);
1315 memset(pvBuf, 0, cbRead);
1316 if (cbRead == cb)
1317 return VINF_SUCCESS;
1318 cb -= cbRead;
1319 RVA += cbRead;
1320 pvBuf = (uint8_t *)pvBuf + cbRead;
1321 }
1322
1323 /*
1324 * Iterate the sections.
1325 */
1326 for (unsigned cLeft = pModPe->cSections;
1327 cLeft > 0;
1328 cLeft--, pSH++)
1329 {
1330 uint32_t off = RVA - pSH->VirtualAddress;
1331 if (off < pSH->Misc.VirtualSize)
1332 {
1333 cbRead = RT_MIN(pSH->Misc.VirtualSize - off, cb);
1334 rc = pReader->pfnRead(pReader, pvBuf, cbRead, pSH->PointerToRawData + off);
1335 if ( cbRead == cb
1336 || RT_FAILURE(rc))
1337 return rc;
1338 cb -= cbRead;
1339 RVA += cbRead;
1340 pvBuf = (uint8_t *)pvBuf + cbRead;
1341 }
1342 uint32_t RVANext = cLeft ? pSH[1].VirtualAddress : pModPe->cbImage;
1343 if (RVA < RVANext)
1344 {
1345 cbRead = RT_MIN(RVANext - RVA, cb);
1346 memset(pvBuf, 0, cbRead);
1347 if (cbRead == cb)
1348 return VINF_SUCCESS;
1349 cb -= cbRead;
1350 RVA += cbRead;
1351 pvBuf = (uint8_t *)pvBuf + cbRead;
1352 }
1353 }
1354
1355 AssertFailed();
1356 return VERR_INTERNAL_ERROR;
1357}
1358
1359
1360/**
1361 * Validates the data of some selected data directories entries.
1362 *
1363 * This requires a valid section table and thus has to wait
1364 * till after we've read and validated it.
1365 *
1366 * @returns iprt status code.
1367 * @param pModPe The PE module instance.
1368 * @param pOptHdr Pointer to the optional header (valid).
1369 */
1370int rtldrPEValidateDirectories(PRTLDRMODPE pModPe, const IMAGE_OPTIONAL_HEADER64 *pOptHdr)
1371{
1372 const char *pszLogName = pModPe->pReader->pfnLogName(pModPe->pReader); NOREF(pszLogName);
1373 union /* combine stuff we're reading to help reduce stack usage. */
1374 {
1375 IMAGE_LOAD_CONFIG_DIRECTORY64 Cfg64;
1376 } u;
1377
1378 /*
1379 * The load config entry may include lock prefix tables and whatnot which we don't implement.
1380 * It does also include a lot of stuff which we can ignore, so we'll have to inspect the
1381 * actual data before we can make up our mind about it all.
1382 */
1383 IMAGE_DATA_DIRECTORY Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG];
1384 if (Dir.Size)
1385 {
1386 const size_t cbExpect = pOptHdr->Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC
1387 ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
1388 : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64);
1389 if ( Dir.Size != cbExpect
1390 && ( cbExpect == sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
1391 && Dir.Size != (uint32_t)RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, SEHandlerTable))
1392 )
1393 {
1394 Log(("rtldrPEOpen: %s: load cfg dir: unexpected dir size of %d bytes, expected %d.\n",
1395 pszLogName, Dir.Size, cbExpect));
1396 return VERR_LDRPE_LOAD_CONFIG_SIZE;
1397 }
1398
1399 /*
1400 * Read and convert to 64-bit.
1401 */
1402 memset(&u.Cfg64, 0, sizeof(u.Cfg64));
1403 int rc = rtldrPEReadRVA(pModPe, &u.Cfg64, Dir.Size, Dir.VirtualAddress);
1404 if (RT_FAILURE(rc))
1405 return rc;
1406 rtldrPEConvert32BitLoadConfigTo64Bit(&u.Cfg64);
1407
1408 if (u.Cfg64.Size != cbExpect)
1409 {
1410 Log(("rtldrPEOpen: %s: load cfg dir: unexpected header size of %d bytes, expected %d.\n",
1411 pszLogName, u.Cfg64.Size, cbExpect));
1412 return VERR_LDRPE_LOAD_CONFIG_SIZE;
1413 }
1414 if (u.Cfg64.LockPrefixTable)
1415 {
1416 Log(("rtldrPEOpen: %s: load cfg dir: lock prefix table at %RX64. We don't support lock prefix tables!\n",
1417 pszLogName, u.Cfg64.LockPrefixTable));
1418 return VERR_LDRPE_LOCK_PREFIX_TABLE;
1419 }
1420#if 0/* this seems to be safe to ignore. */
1421 if ( u.Cfg64.SEHandlerTable
1422 || u.Cfg64.SEHandlerCount)
1423 {
1424 Log(("rtldrPEOpen: %s: load cfg dir: SEHandlerTable=%RX64 and SEHandlerCount=%RX64 are unsupported!\n",
1425 pszLogName, u.Cfg64.SEHandlerTable, u.Cfg64.SEHandlerCount));
1426 return VERR_BAD_EXE_FORMAT;
1427 }
1428#endif
1429 if (u.Cfg64.EditList)
1430 {
1431 Log(("rtldrPEOpen: %s: load cfg dir: EditList=%RX64 is unsupported!\n",
1432 pszLogName, u.Cfg64.EditList));
1433 return VERR_BAD_EXE_FORMAT;
1434 }
1435 }
1436
1437 /*
1438 * If the image is signed, take a look at the signature.
1439 */
1440 Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
1441 if (Dir.Size)
1442 {
1443 PWIN_CERTIFICATE pFirst = (PWIN_CERTIFICATE)RTMemTmpAlloc(Dir.Size);
1444 if (!pFirst)
1445 return VERR_NO_TMP_MEMORY;
1446 int rc = pModPe->pReader->pfnRead(pModPe->pReader, pFirst, Dir.Size, Dir.VirtualAddress);
1447 if (RT_SUCCESS(rc))
1448 {
1449 uint32_t off = 0;
1450 PWIN_CERTIFICATE pCur = pFirst;
1451 do
1452 {
1453 /* validate the members. */
1454 uint32_t const cbCur = RT_ALIGN_32(pCur->dwLength, 8);
1455 if ( cbCur < sizeof(WIN_CERTIFICATE)
1456 || cbCur + off > RT_ALIGN_32(Dir.Size, 8))
1457 {
1458 Log(("rtldrPEOpen: %s: cert at %#x/%#x: dwLength=%#x\n", pszLogName, off, Dir.Size, pCur->dwLength));
1459 rc = VERR_LDRPE_CERT_MALFORMED;
1460 break;
1461 }
1462 if ( pCur->wRevision != WIN_CERT_REVISION_2_0
1463 && pCur->wRevision != WIN_CERT_REVISION_1_0)
1464 {
1465 Log(("rtldrPEOpen: %s: cert at %#x/%#x: wRevision=%#x\n", pszLogName, off, Dir.Size, pCur->wRevision));
1466 rc = pCur->wRevision >= WIN_CERT_REVISION_1_0 ? VERR_LDRPE_CERT_UNSUPPORTED : VERR_LDRPE_CERT_MALFORMED;
1467 break;
1468 }
1469 if ( pCur->wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA
1470 && pCur->wCertificateType != WIN_CERT_TYPE_X509
1471 /*&& pCur->wCertificateType != WIN_CERT_TYPE_RESERVED_1*/
1472 /*&& pCur->wCertificateType != WIN_CERT_TYPE_TS_STACK_SIGNED*/
1473 && pCur->wCertificateType != WIN_CERT_TYPE_EFI_PKCS115
1474 && pCur->wCertificateType != WIN_CERT_TYPE_EFI_GUID
1475 )
1476 {
1477 Log(("rtldrPEOpen: %s: cert at %#x/%#x: wRevision=%#x\n", pszLogName, off, Dir.Size, pCur->wRevision));
1478 rc = pCur->wCertificateType ? VERR_LDRPE_CERT_UNSUPPORTED : VERR_LDRPE_CERT_MALFORMED;
1479 break;
1480 }
1481
1482 /** @todo Rainy Day: Implement further verification using openssl. */
1483
1484 /* next */
1485 off += cbCur;
1486 pCur = (PWIN_CERTIFICATE)((uint8_t *)pCur + cbCur);
1487 } while (off < Dir.Size);
1488 }
1489 RTMemTmpFree(pFirst);
1490 if (RT_FAILURE(rc))
1491 return rc;
1492 }
1493
1494
1495 return VINF_SUCCESS;
1496}
1497
1498
1499/**
1500 * Open a PE image.
1501 *
1502 * @returns iprt status code.
1503 * @param pReader The loader reader instance which will provide the raw image bits.
1504 * @param fFlags Reserved, MBZ.
1505 * @param enmArch Architecture specifier.
1506 * @param offNtHdrs The offset of the NT headers (where you find "PE\0\0").
1507 * @param phLdrMod Where to store the handle.
1508 */
1509int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs, PRTLDRMOD phLdrMod)
1510{
1511 /*
1512 * Read and validate the file header.
1513 */
1514 IMAGE_FILE_HEADER FileHdr;
1515 int rc = pReader->pfnRead(pReader, &FileHdr, sizeof(FileHdr), offNtHdrs + 4);
1516 if (RT_FAILURE(rc))
1517 return rc;
1518 RTLDRARCH enmArchImage;
1519 const char *pszLogName = pReader->pfnLogName(pReader);
1520 rc = rtldrPEValidateFileHeader(&FileHdr, pszLogName, &enmArchImage);
1521 if (RT_FAILURE(rc))
1522 return rc;
1523
1524 /*
1525 * Match the CPU architecture.
1526 */
1527 if ( enmArch != RTLDRARCH_WHATEVER
1528 && enmArch != enmArchImage)
1529 return VERR_LDR_ARCH_MISMATCH;
1530
1531 /*
1532 * Read and validate the "optional" header. Convert 32->64 if necessary.
1533 */
1534 IMAGE_OPTIONAL_HEADER64 OptHdr;
1535 rc = pReader->pfnRead(pReader, &OptHdr, FileHdr.SizeOfOptionalHeader, offNtHdrs + 4 + sizeof(IMAGE_FILE_HEADER));
1536 if (RT_FAILURE(rc))
1537 return rc;
1538 if (FileHdr.SizeOfOptionalHeader != sizeof(OptHdr))
1539 rtldrPEConvert32BitOptionalHeaderTo64Bit(&OptHdr);
1540 rc = rtldrPEValidateOptionalHeader(&OptHdr, pszLogName, offNtHdrs, &FileHdr, pReader->pfnSize(pReader));
1541 if (RT_FAILURE(rc))
1542 return rc;
1543
1544 /*
1545 * Read and validate section headers.
1546 */
1547 const size_t cbSections = sizeof(IMAGE_SECTION_HEADER) * FileHdr.NumberOfSections;
1548 PIMAGE_SECTION_HEADER paSections = (PIMAGE_SECTION_HEADER)RTMemAlloc(cbSections);
1549 if (!paSections)
1550 return VERR_NO_MEMORY;
1551 rc = pReader->pfnRead(pReader, paSections, cbSections, offNtHdrs + 4 + sizeof(IMAGE_FILE_HEADER) + FileHdr.SizeOfOptionalHeader);
1552 if (RT_SUCCESS(rc))
1553 {
1554 rc = rtldrPEValidateSectionHeaders(paSections, FileHdr.NumberOfSections, pszLogName,
1555 &OptHdr, pReader->pfnSize(pReader));
1556 if (RT_SUCCESS(rc))
1557 {
1558 /*
1559 * Allocate and initialize the PE module structure.
1560 */
1561 PRTLDRMODPE pModPe = (PRTLDRMODPE)RTMemAllocZ(sizeof(*pModPe));
1562 if (pModPe)
1563 {
1564 pModPe->Core.u32Magic = RTLDRMOD_MAGIC;
1565 pModPe->Core.eState = LDR_STATE_OPENED;
1566 if (FileHdr.SizeOfOptionalHeader == sizeof(OptHdr))
1567 pModPe->Core.pOps = &s_rtldrPE64Ops.Core;
1568 else
1569 pModPe->Core.pOps = &s_rtldrPE32Ops.Core;
1570 pModPe->pReader = pReader;
1571 pModPe->pvBits = NULL;
1572 pModPe->offNtHdrs = offNtHdrs;
1573 pModPe->u16Machine = FileHdr.Machine;
1574 pModPe->fFile = FileHdr.Characteristics;
1575 pModPe->cSections = FileHdr.NumberOfSections;
1576 pModPe->paSections = paSections;
1577 pModPe->uEntryPointRVA= OptHdr.AddressOfEntryPoint;
1578 pModPe->uImageBase = (RTUINTPTR)OptHdr.ImageBase;
1579 pModPe->cbImage = OptHdr.SizeOfImage;
1580 pModPe->cbHeaders = OptHdr.SizeOfHeaders;
1581 pModPe->ImportDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
1582 pModPe->RelocDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1583 pModPe->ExportDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
1584
1585 /*
1586 * Perform validation of some selected data directories which requires
1587 * inspection of the actual data.
1588 */
1589 rc = rtldrPEValidateDirectories(pModPe, &OptHdr);
1590 if (RT_SUCCESS(rc))
1591 {
1592 *phLdrMod = &pModPe->Core;
1593 return VINF_SUCCESS;
1594 }
1595 RTMemFree(pModPe);
1596 }
1597 else
1598 rc = VERR_NO_MEMORY;
1599 }
1600 }
1601 RTMemFree(paSections);
1602 return rc;
1603}
1604
Note: See TracBrowser for help on using the repository browser.

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