VirtualBox

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

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

IPRT: More debug info hacking.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 62.6 KB
Line 
1/* $Id: ldrPE.cpp 38547 2011-08-26 12:58:47Z 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::pfnEnumSegments. */
779static DECLCALLBACK(int) rtldrPE_EnumSegments(PRTLDRMODINTERNAL pMod, PFNRTLDRENUMSEGS pfnCallback, void *pvUser)
780{
781 return VINF_NOT_SUPPORTED;
782}
783
784
785/** @copydoc RTLDROPS::pfnDone */
786static DECLCALLBACK(int) rtldrPEDone(PRTLDRMODINTERNAL pMod)
787{
788 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
789 if (pModPe->pvBits)
790 {
791 RTMemFree(pModPe->pvBits);
792 pModPe->pvBits = NULL;
793 }
794 if (pModPe->pReader)
795 {
796 int rc = pModPe->pReader->pfnDestroy(pModPe->pReader);
797 AssertRC(rc);
798 pModPe->pReader = NULL;
799 }
800 return VINF_SUCCESS;
801}
802
803/** @copydoc RTLDROPS::pfnClose */
804static DECLCALLBACK(int) rtldrPEClose(PRTLDRMODINTERNAL pMod)
805{
806 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
807 if (pModPe->paSections)
808 {
809 RTMemFree(pModPe->paSections);
810 pModPe->paSections = NULL;
811 }
812 if (pModPe->pvBits)
813 {
814 RTMemFree(pModPe->pvBits);
815 pModPe->pvBits = NULL;
816 }
817 if (pModPe->pReader)
818 {
819 int rc = pModPe->pReader->pfnDestroy(pModPe->pReader);
820 AssertRC(rc);
821 pModPe->pReader = NULL;
822 }
823 return VINF_SUCCESS;
824}
825
826
827/**
828 * Operations for a 32-bit PE module.
829 */
830static const RTLDROPSPE s_rtldrPE32Ops =
831{
832 {
833 "pe32",
834 rtldrPEClose,
835 NULL,
836 rtldrPEDone,
837 rtldrPEEnumSymbols,
838 /* ext */
839 rtldrPEGetImageSize,
840 rtldrPEGetBits,
841 rtldrPERelocate,
842 rtldrPEGetSymbolEx,
843 rtldrPE_EnumDbgInfo,
844 rtldrPE_EnumSegments,
845 42
846 },
847 rtldrPEResolveImports32,
848 42
849};
850
851
852/**
853 * Operations for a 64-bit PE module.
854 */
855static const RTLDROPSPE s_rtldrPE64Ops =
856{
857 {
858 "pe64",
859 rtldrPEClose,
860 NULL,
861 rtldrPEDone,
862 rtldrPEEnumSymbols,
863 /* ext */
864 rtldrPEGetImageSize,
865 rtldrPEGetBits,
866 rtldrPERelocate,
867 rtldrPEGetSymbolEx,
868 rtldrPE_EnumDbgInfo,
869 rtldrPE_EnumSegments,
870 42
871 },
872 rtldrPEResolveImports64,
873 42
874};
875
876
877/**
878 * Converts the optional header from 32 bit to 64 bit.
879 * This is a rather simple task, if you start from the right end.
880 *
881 * @param pOptHdr On input this is a PIMAGE_OPTIONAL_HEADER32.
882 * On output this will be a PIMAGE_OPTIONAL_HEADER64.
883 */
884static void rtldrPEConvert32BitOptionalHeaderTo64Bit(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
885{
886 /*
887 * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
888 */
889 IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
890 IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
891
892 /* from LoaderFlags and out the difference is 4 * 32-bits. */
893 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, LoaderFlags) + 16 == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, LoaderFlags));
894 Assert( RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]) + 16
895 == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]));
896 uint32_t volatile *pu32Dst = (uint32_t *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
897 const uint32_t volatile *pu32Src = (uint32_t *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
898 const uint32_t volatile *pu32SrcLast = (uint32_t *)&pOptHdr32->LoaderFlags;
899 while (pu32Src >= pu32SrcLast)
900 *pu32Dst-- = *pu32Src--;
901
902 /* the previous 4 fields are 32/64 and needs special attention. */
903 pOptHdr64->SizeOfHeapCommit = pOptHdr32->SizeOfHeapCommit;
904 pOptHdr64->SizeOfHeapReserve = pOptHdr32->SizeOfHeapReserve;
905 pOptHdr64->SizeOfStackCommit = pOptHdr32->SizeOfStackCommit;
906 uint32_t u32SizeOfStackReserve = pOptHdr32->SizeOfStackReserve;
907 pOptHdr64->SizeOfStackReserve = u32SizeOfStackReserve;
908
909 /* The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version..
910 * Thus, ImageBase needs some special treatment. It will probably work fine assigning one to the
911 * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
912 */
913 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, SizeOfStackReserve) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve));
914 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, BaseOfData) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, ImageBase));
915 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, SectionAlignment) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, SectionAlignment));
916 uint32_t u32ImageBase = pOptHdr32->ImageBase;
917 pOptHdr64->ImageBase = u32ImageBase;
918}
919
920
921/**
922 * Converts the load config directory from 32 bit to 64 bit.
923 * This is a rather simple task, if you start from the right end.
924 *
925 * @param pLoadCfg On input this is a PIMAGE_LOAD_CONFIG_DIRECTORY32.
926 * On output this will be a PIMAGE_LOAD_CONFIG_DIRECTORY64.
927 */
928static void rtldrPEConvert32BitLoadConfigTo64Bit(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
929{
930 /*
931 * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
932 */
933 IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
934 IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
935
936 pLoadCfg64->SEHandlerCount = pLoadCfg32->SEHandlerCount;
937 pLoadCfg64->SEHandlerTable = pLoadCfg32->SEHandlerTable;
938 pLoadCfg64->SecurityCookie = pLoadCfg32->SecurityCookie;
939 pLoadCfg64->EditList = pLoadCfg32->EditList;
940 pLoadCfg64->Reserved1 = pLoadCfg32->Reserved1;
941 pLoadCfg64->CSDVersion = pLoadCfg32->CSDVersion;
942 pLoadCfg64->ProcessHeapFlags = pLoadCfg32->ProcessHeapFlags; /* switched place with ProcessAffinityMask, but we're more than 16 byte off by now so it doesn't matter. */
943 pLoadCfg64->ProcessAffinityMask = pLoadCfg32->ProcessAffinityMask;
944 pLoadCfg64->VirtualMemoryThreshold = pLoadCfg32->VirtualMemoryThreshold;
945 pLoadCfg64->MaximumAllocationSize = pLoadCfg32->MaximumAllocationSize;
946 pLoadCfg64->LockPrefixTable = pLoadCfg32->LockPrefixTable;
947 pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
948 uint32_t u32DeCommitFreeBlockThreshold = pLoadCfg32->DeCommitFreeBlockThreshold;
949 pLoadCfg64->DeCommitFreeBlockThreshold = u32DeCommitFreeBlockThreshold;
950 /* the rest is equal. */
951 Assert( RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, DeCommitFreeBlockThreshold)
952 == RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY64, DeCommitFreeBlockThreshold));
953}
954
955
956/**
957 * Validates the file header.
958 *
959 * @returns iprt status code.
960 * @param pFileHdr Pointer to the file header that needs validating.
961 * @param pszLogName The log name to prefix the errors with.
962 * @param penmArch Where to store the CPU architecture.
963 */
964int rtldrPEValidateFileHeader(PIMAGE_FILE_HEADER pFileHdr, const char *pszLogName, PRTLDRARCH penmArch)
965{
966 size_t cbOptionalHeader;
967 switch (pFileHdr->Machine)
968 {
969 case IMAGE_FILE_MACHINE_I386:
970 cbOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32);
971 *penmArch = RTLDRARCH_X86_32;
972 break;
973 case IMAGE_FILE_MACHINE_AMD64:
974 cbOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
975 *penmArch = RTLDRARCH_AMD64;
976 break;
977
978 default:
979 Log(("rtldrPEOpen: %s: Unsupported Machine=%#x\n",
980 pszLogName, pFileHdr->Machine));
981 *penmArch = RTLDRARCH_INVALID;
982 return VERR_BAD_EXE_FORMAT;
983 }
984 if (pFileHdr->SizeOfOptionalHeader != cbOptionalHeader)
985 {
986 Log(("rtldrPEOpen: %s: SizeOfOptionalHeader=%#x expected %#x\n",
987 pszLogName, pFileHdr->SizeOfOptionalHeader, cbOptionalHeader));
988 return VERR_BAD_EXE_FORMAT;
989 }
990 /* This restriction needs to be implemented elsewhere. */
991 if (pFileHdr->Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
992 {
993 Log(("rtldrPEOpen: %s: IMAGE_FILE_RELOCS_STRIPPED\n", pszLogName));
994 return VERR_BAD_EXE_FORMAT;
995 }
996 if (pFileHdr->NumberOfSections > 42)
997 {
998 Log(("rtldrPEOpen: %s: NumberOfSections=%d - our limit is 42, please raise it if the binary makes sense.(!!!)\n",
999 pszLogName, pFileHdr->NumberOfSections));
1000 return VERR_BAD_EXE_FORMAT;
1001 }
1002 if (pFileHdr->NumberOfSections < 1)
1003 {
1004 Log(("rtldrPEOpen: %s: NumberOfSections=%d - we can't have an image without sections (!!!)\n",
1005 pszLogName, pFileHdr->NumberOfSections));
1006 return VERR_BAD_EXE_FORMAT;
1007 }
1008 return VINF_SUCCESS;
1009}
1010
1011
1012/**
1013 * Validates the optional header (64/32-bit)
1014 *
1015 * @returns iprt status code.
1016 * @param pOptHdr Pointer to the optional header which needs validation.
1017 * @param pszLogName The log name to prefix the errors with.
1018 * @param offNtHdrs The offset of the NT headers from teh start of the file.
1019 * @param pFileHdr Pointer to the file header (valid).
1020 * @param cbRawImage The raw image size.
1021 */
1022static int rtldrPEValidateOptionalHeader(const IMAGE_OPTIONAL_HEADER64 *pOptHdr, const char *pszLogName, RTFOFF offNtHdrs,
1023 const IMAGE_FILE_HEADER *pFileHdr, RTFOFF cbRawImage)
1024{
1025 const uint16_t CorrectMagic = pFileHdr->SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
1026 ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1027 if (pOptHdr->Magic != CorrectMagic)
1028 {
1029 Log(("rtldrPEOpen: %s: Magic=%#x - expected %#x!!!\n", pszLogName, pOptHdr->Magic, CorrectMagic));
1030 return VERR_BAD_EXE_FORMAT;
1031 }
1032 const uint32_t cbImage = pOptHdr->SizeOfImage;
1033 if (cbImage > _1G)
1034 {
1035 Log(("rtldrPEOpen: %s: SizeOfImage=%#x - Our limit is 1GB (%#x)!!!\n", pszLogName, cbImage, _1G));
1036 return VERR_BAD_EXE_FORMAT;
1037 }
1038 const uint32_t cbMinImageSize = pFileHdr->SizeOfOptionalHeader + sizeof(*pFileHdr) + 4 + (uint32_t)offNtHdrs;
1039 if (cbImage < cbMinImageSize)
1040 {
1041 Log(("rtldrPEOpen: %s: SizeOfImage=%#x to small, minimum %#x!!!\n", pszLogName, cbImage, cbMinImageSize));
1042 return VERR_BAD_EXE_FORMAT;
1043 }
1044 if (pOptHdr->AddressOfEntryPoint >= cbImage)
1045 {
1046 Log(("rtldrPEOpen: %s: AddressOfEntryPoint=%#x - beyond image size (%#x)!!!\n",
1047 pszLogName, pOptHdr->AddressOfEntryPoint, cbImage));
1048 return VERR_BAD_EXE_FORMAT;
1049 }
1050 if (pOptHdr->BaseOfCode >= cbImage)
1051 {
1052 Log(("rtldrPEOpen: %s: BaseOfCode=%#x - beyond image size (%#x)!!!\n",
1053 pszLogName, pOptHdr->BaseOfCode, cbImage));
1054 return VERR_BAD_EXE_FORMAT;
1055 }
1056#if 0/* only in 32-bit header */
1057 if (pOptHdr->BaseOfData >= cbImage)
1058 {
1059 Log(("rtldrPEOpen: %s: BaseOfData=%#x - beyond image size (%#x)!!!\n",
1060 pszLogName, pOptHdr->BaseOfData, cbImage));
1061 return VERR_BAD_EXE_FORMAT;
1062 }
1063#endif
1064 if (pOptHdr->SizeOfHeaders >= cbImage)
1065 {
1066 Log(("rtldrPEOpen: %s: SizeOfHeaders=%#x - beyond image size (%#x)!!!\n",
1067 pszLogName, pOptHdr->SizeOfHeaders, cbImage));
1068 return VERR_BAD_EXE_FORMAT;
1069 }
1070 /* don't know how to do the checksum, so ignore it. */
1071 if (pOptHdr->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1072 {
1073 Log(("rtldrPEOpen: %s: Subsystem=%#x (unknown)!!!\n", pszLogName, pOptHdr->Subsystem));
1074 return VERR_BAD_EXE_FORMAT;
1075 }
1076 if (pOptHdr->SizeOfHeaders < cbMinImageSize + pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER))
1077 {
1078 Log(("rtldrPEOpen: %s: SizeOfHeaders=%#x - cbMinImageSize %#x + sections %#x = %#llx!!!\n",
1079 pszLogName, pOptHdr->SizeOfHeaders,
1080 cbImage, cbMinImageSize, pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER),
1081 cbMinImageSize + pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)));
1082 return VERR_BAD_EXE_FORMAT;
1083 }
1084 if (pOptHdr->SizeOfStackReserve < pOptHdr->SizeOfStackCommit)
1085 {
1086 Log(("rtldrPEOpen: %s: SizeOfStackReserve %#x < SizeOfStackCommit %#x!!!\n",
1087 pszLogName, pOptHdr->SizeOfStackReserve, pOptHdr->SizeOfStackCommit));
1088 return VERR_BAD_EXE_FORMAT;
1089 }
1090 if (pOptHdr->SizeOfHeapReserve < pOptHdr->SizeOfHeapCommit)
1091 {
1092 Log(("rtldrPEOpen: %s: SizeOfStackReserve %#x < SizeOfStackCommit %#x!!!\n",
1093 pszLogName, pOptHdr->SizeOfStackReserve, pOptHdr->SizeOfStackCommit));
1094 return VERR_BAD_EXE_FORMAT;
1095 }
1096
1097 /* DataDirectory */
1098 if (pOptHdr->NumberOfRvaAndSizes != RT_ELEMENTS(pOptHdr->DataDirectory))
1099 {
1100 Log(("rtldrPEOpen: %s: NumberOfRvaAndSizes=%d!!!\n", pszLogName, pOptHdr->NumberOfRvaAndSizes));
1101 return VERR_BAD_EXE_FORMAT;
1102 }
1103 for (unsigned i = 0; i < RT_ELEMENTS(pOptHdr->DataDirectory); i++)
1104 {
1105 IMAGE_DATA_DIRECTORY const *pDir = &pOptHdr->DataDirectory[i];
1106 if (!pDir->Size)
1107 continue;
1108 size_t cb = cbImage;
1109 switch (i)
1110 {
1111 case IMAGE_DIRECTORY_ENTRY_EXPORT: // 0
1112 case IMAGE_DIRECTORY_ENTRY_IMPORT: // 1
1113 case IMAGE_DIRECTORY_ENTRY_RESOURCE: // 2
1114 case IMAGE_DIRECTORY_ENTRY_EXCEPTION: // 3
1115 case IMAGE_DIRECTORY_ENTRY_BASERELOC: // 5
1116 case IMAGE_DIRECTORY_ENTRY_DEBUG: // 6
1117 case IMAGE_DIRECTORY_ENTRY_COPYRIGHT: // 7
1118 case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: // 11
1119 case IMAGE_DIRECTORY_ENTRY_IAT: // 12 /* Import Address Table */
1120 break;
1121 case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: // 10 - need to check for lock prefixes.
1122 /* Delay inspection after section table is validated. */
1123 break;
1124
1125 case IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT: // 13
1126 Log(("rtldrPEOpen: %s: dir no. %d (DELAY_IMPORT) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1127 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1128 return VERR_LDRPE_DELAY_IMPORT;
1129
1130 case IMAGE_DIRECTORY_ENTRY_SECURITY: // 4
1131 /* The VirtualAddress is a PointerToRawData. */
1132 cb = (size_t)cbRawImage; Assert((RTFOFF)cb == cbRawImage);
1133 Log(("rtldrPEOpen: %s: dir no. %d (SECURITY) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1134 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1135 if (pDir->Size < sizeof(WIN_CERTIFICATE))
1136 {
1137 Log(("rtldrPEOpen: %s: Security directory is too small: %#x bytes\n", pszLogName, i, pDir->Size));
1138 return VERR_LDRPE_CERT_MALFORMED;
1139 }
1140 if (pDir->Size >= _1M)
1141 {
1142 Log(("rtldrPEOpen: %s: Security directory is too large: %#x bytes\n", pszLogName, i, pDir->Size));
1143 return VERR_LDRPE_CERT_MALFORMED;
1144 }
1145 if (pDir->VirtualAddress & 7)
1146 {
1147 Log(("rtldrPEOpen: %s: Security directory is misaligned: %#x\n", pszLogName, i, pDir->VirtualAddress));
1148 return VERR_LDRPE_CERT_MALFORMED;
1149 }
1150 break;
1151
1152 case IMAGE_DIRECTORY_ENTRY_GLOBALPTR: // 8 /* (MIPS GP) */
1153 Log(("rtldrPEOpen: %s: dir no. %d (GLOBALPTR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1154 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1155 return VERR_LDRPE_GLOBALPTR;
1156
1157 case IMAGE_DIRECTORY_ENTRY_TLS: // 9
1158 Log(("rtldrPEOpen: %s: dir no. %d (TLS) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1159 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1160 return VERR_LDRPE_TLS;
1161
1162 case IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR:// 14
1163 Log(("rtldrPEOpen: %s: dir no. %d (COM_DESCRIPTOR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1164 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1165 return VERR_LDRPE_COM_DESCRIPTOR;
1166
1167 default:
1168 Log(("rtldrPEOpen: %s: dir no. %d VirtualAddress=%#x Size=%#x is not supported!!!\n",
1169 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1170 return VERR_BAD_EXE_FORMAT;
1171 }
1172 if (pDir->VirtualAddress >= cb)
1173 {
1174 Log(("rtldrPEOpen: %s: dir no. %d VirtualAddress=%#x is invalid (limit %#x)!!!\n",
1175 pszLogName, i, pDir->VirtualAddress, cb));
1176 return VERR_BAD_EXE_FORMAT;
1177 }
1178 if (pDir->Size > cb - pDir->VirtualAddress)
1179 {
1180 Log(("rtldrPEOpen: %s: dir no. %d Size=%#x is invalid (rva=%#x, limit=%#x)!!!\n",
1181 pszLogName, i, pDir->Size, pDir->VirtualAddress, cb));
1182 return VERR_BAD_EXE_FORMAT;
1183 }
1184 }
1185 return VINF_SUCCESS;
1186}
1187
1188
1189/**
1190 * Validates the section headers.
1191 *
1192 * @returns iprt status code.
1193 * @param paSections Pointer to the array of sections that is to be validated.
1194 * @param cSections Number of sections in that array.
1195 * @param pszLogName The log name to prefix the errors with.
1196 * @param pOptHdr Pointer to the optional header (valid).
1197 * @param cbRawImage The raw image size.
1198 */
1199int rtldrPEValidateSectionHeaders(const IMAGE_SECTION_HEADER *paSections, unsigned cSections, const char *pszLogName,
1200 const IMAGE_OPTIONAL_HEADER64 *pOptHdr, RTFOFF cbRawImage)
1201{
1202 const uint32_t cbImage = pOptHdr->SizeOfImage;
1203 const IMAGE_SECTION_HEADER *pSH = &paSections[0];
1204 uint32_t uRvaPrev = pOptHdr->SizeOfHeaders;
1205 Log3(("RTLdrPE: Section Headers:\n"));
1206 for (unsigned cSHdrsLeft = cSections; cSHdrsLeft > 0; cSHdrsLeft--, pSH++)
1207 {
1208 const unsigned iSH = pSH - &paSections[0]; NOREF(iSH);
1209 Log3(("RTLdrPE: #%d '%-8.8s' Characteristics: %08RX32\n"
1210 "RTLdrPE: VirtAddr: %08RX32 VirtSize: %08RX32\n"
1211 "RTLdrPE: FileOff: %08RX32 FileSize: %08RX32\n"
1212 "RTLdrPE: RelocOff: %08RX32 #Relocs: %08RX32\n"
1213 "RTLdrPE: LineOff: %08RX32 #Lines: %08RX32\n",
1214 iSH, pSH->Name, pSH->Characteristics,
1215 pSH->VirtualAddress, pSH->Misc.VirtualSize,
1216 pSH->PointerToRawData, pSH->SizeOfRawData,
1217 pSH->PointerToRelocations, pSH->NumberOfRelocations,
1218 pSH->PointerToLinenumbers, pSH->NumberOfLinenumbers));
1219 if (pSH->Characteristics & (IMAGE_SCN_MEM_16BIT | IMAGE_SCN_MEM_FARDATA | IMAGE_SCN_MEM_PURGEABLE | IMAGE_SCN_MEM_PRELOAD))
1220 {
1221 Log(("rtldrPEOpen: %s: Unsupported section flag(s) %#x section #%d '%.*s'!!!\n",
1222 pszLogName, pSH->Characteristics, iSH, sizeof(pSH->Name), pSH->Name));
1223 return VERR_BAD_EXE_FORMAT;
1224 }
1225
1226 if ( pSH->Misc.VirtualSize
1227 && !(pSH->Characteristics & IMAGE_SCN_TYPE_NOLOAD)) /* binutils uses this for '.stab' even if it's reserved/obsoleted by MS. */
1228 {
1229 if (pSH->VirtualAddress < uRvaPrev)
1230 {
1231 Log(("rtldrPEOpen: %s: Overlaps previous section or sections aren't in ascending order, VirtualAddress=%#x uRvaPrev=%#x - section #%d '%.*s'!!!\n",
1232 pszLogName, pSH->VirtualAddress, uRvaPrev, iSH, sizeof(pSH->Name), pSH->Name));
1233 return VERR_BAD_EXE_FORMAT;
1234 }
1235 if (pSH->VirtualAddress > cbImage)
1236 {
1237 Log(("rtldrPEOpen: %s: VirtualAddress=%#x - beyond image size (%#x) - section #%d '%.*s'!!!\n",
1238 pszLogName, pSH->VirtualAddress, cbImage, iSH, sizeof(pSH->Name), pSH->Name));
1239 return VERR_BAD_EXE_FORMAT;
1240 }
1241
1242 if (pSH->VirtualAddress & (pOptHdr->SectionAlignment - 1)) //ASSUMES power of 2 alignment.
1243 {
1244 Log(("rtldrPEOpen: %s: VirtualAddress=%#x misaligned (%#x) - section #%d '%.*s'!!!\n",
1245 pszLogName, pSH->VirtualAddress, pOptHdr->SectionAlignment, iSH, sizeof(pSH->Name), pSH->Name));
1246 return VERR_BAD_EXE_FORMAT;
1247 }
1248
1249#ifdef PE_FILE_OFFSET_EQUALS_RVA
1250 /* Our loader code assume rva matches the file offset. */
1251 if ( pSH->SizeOfRawData
1252 && pSH->PointerToRawData != pSH->VirtualAddress)
1253 {
1254 Log(("rtldrPEOpen: %s: ASSUMPTION FAILED: file offset %#x != RVA %#x - section #%d '%.*s'!!!\n",
1255 pszLogName, pSH->PointerToRawData, pSH->VirtualAddress, iSH, sizeof(pSH->Name), pSH->Name));
1256 return VERR_BAD_EXE_FORMAT;
1257 }
1258#endif
1259 }
1260
1261 ///@todo only if SizeOfRawData > 0 ?
1262 if ( pSH->PointerToRawData > cbRawImage /// @todo pSH->PointerToRawData >= cbRawImage ?
1263 || pSH->SizeOfRawData > cbRawImage
1264 || pSH->PointerToRawData + pSH->SizeOfRawData > cbRawImage)
1265 {
1266 Log(("rtldrPEOpen: %s: PointerToRawData=%#x SizeOfRawData=%#x - beyond end of file (%#x) - section #%d '%.*s'!!!\n",
1267 pszLogName, pSH->PointerToRawData, pSH->SizeOfRawData, cbRawImage,
1268 iSH, sizeof(pSH->Name), pSH->Name));
1269 return VERR_BAD_EXE_FORMAT;
1270 }
1271
1272 if (pSH->PointerToRawData & (pOptHdr->FileAlignment - 1)) //ASSUMES power of 2 alignment.
1273 {
1274 Log(("rtldrPEOpen: %s: PointerToRawData=%#x misaligned (%#x) - section #%d '%.*s'!!!\n",
1275 pszLogName, pSH->PointerToRawData, pOptHdr->FileAlignment, iSH, sizeof(pSH->Name), pSH->Name));
1276 return VERR_BAD_EXE_FORMAT;
1277 }
1278
1279 /* ignore the relocations and linenumbers. */
1280
1281 uRvaPrev = pSH->VirtualAddress + pSH->Misc.VirtualSize;
1282 }
1283
1284 /** @todo r=bird: more sanity checks! */
1285 return VINF_SUCCESS;
1286}
1287
1288
1289/**
1290 * Reads image data by RVA using the section headers.
1291 *
1292 * @returns iprt status code.
1293 * @param pModPe The PE module instance.
1294 * @param pvBuf Where to store the bits.
1295 * @param cb Number of bytes to tread.
1296 * @param RVA Where to read from.
1297 */
1298static int rtldrPEReadRVA(PRTLDRMODPE pModPe, void *pvBuf, uint32_t cb, uint32_t RVA)
1299{
1300 const IMAGE_SECTION_HEADER *pSH = pModPe->paSections;
1301 PRTLDRREADER pReader = pModPe->pReader;
1302 uint32_t cbRead;
1303 int rc;
1304
1305 /*
1306 * Is it the headers, i.e. prior to the first section.
1307 */
1308 if (RVA < pModPe->cbHeaders)
1309 {
1310 cbRead = RT_MIN(pModPe->cbHeaders - RVA, cb);
1311 rc = pReader->pfnRead(pReader, pvBuf, cbRead, RVA);
1312 if ( cbRead == cb
1313 || RT_FAILURE(rc))
1314 return rc;
1315 cb -= cbRead;
1316 RVA += cbRead;
1317 pvBuf = (uint8_t *)pvBuf + cbRead;
1318 }
1319
1320 /* In the zero space between headers and the first section? */
1321 if (RVA < pSH->VirtualAddress)
1322 {
1323 cbRead = RT_MIN(pSH->VirtualAddress - RVA, cb);
1324 memset(pvBuf, 0, cbRead);
1325 if (cbRead == cb)
1326 return VINF_SUCCESS;
1327 cb -= cbRead;
1328 RVA += cbRead;
1329 pvBuf = (uint8_t *)pvBuf + cbRead;
1330 }
1331
1332 /*
1333 * Iterate the sections.
1334 */
1335 for (unsigned cLeft = pModPe->cSections;
1336 cLeft > 0;
1337 cLeft--, pSH++)
1338 {
1339 uint32_t off = RVA - pSH->VirtualAddress;
1340 if (off < pSH->Misc.VirtualSize)
1341 {
1342 cbRead = RT_MIN(pSH->Misc.VirtualSize - off, cb);
1343 rc = pReader->pfnRead(pReader, pvBuf, cbRead, pSH->PointerToRawData + off);
1344 if ( cbRead == cb
1345 || RT_FAILURE(rc))
1346 return rc;
1347 cb -= cbRead;
1348 RVA += cbRead;
1349 pvBuf = (uint8_t *)pvBuf + cbRead;
1350 }
1351 uint32_t RVANext = cLeft ? pSH[1].VirtualAddress : pModPe->cbImage;
1352 if (RVA < RVANext)
1353 {
1354 cbRead = RT_MIN(RVANext - RVA, cb);
1355 memset(pvBuf, 0, cbRead);
1356 if (cbRead == cb)
1357 return VINF_SUCCESS;
1358 cb -= cbRead;
1359 RVA += cbRead;
1360 pvBuf = (uint8_t *)pvBuf + cbRead;
1361 }
1362 }
1363
1364 AssertFailed();
1365 return VERR_INTERNAL_ERROR;
1366}
1367
1368
1369/**
1370 * Validates the data of some selected data directories entries.
1371 *
1372 * This requires a valid section table and thus has to wait
1373 * till after we've read and validated it.
1374 *
1375 * @returns iprt status code.
1376 * @param pModPe The PE module instance.
1377 * @param pOptHdr Pointer to the optional header (valid).
1378 */
1379int rtldrPEValidateDirectories(PRTLDRMODPE pModPe, const IMAGE_OPTIONAL_HEADER64 *pOptHdr)
1380{
1381 const char *pszLogName = pModPe->pReader->pfnLogName(pModPe->pReader); NOREF(pszLogName);
1382 union /* combine stuff we're reading to help reduce stack usage. */
1383 {
1384 IMAGE_LOAD_CONFIG_DIRECTORY64 Cfg64;
1385 } u;
1386
1387 /*
1388 * The load config entry may include lock prefix tables and whatnot which we don't implement.
1389 * It does also include a lot of stuff which we can ignore, so we'll have to inspect the
1390 * actual data before we can make up our mind about it all.
1391 */
1392 IMAGE_DATA_DIRECTORY Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG];
1393 if (Dir.Size)
1394 {
1395 const size_t cbExpect = pOptHdr->Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC
1396 ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
1397 : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64);
1398 if ( Dir.Size != cbExpect
1399 && ( cbExpect == sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
1400 && Dir.Size != (uint32_t)RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, SEHandlerTable))
1401 )
1402 {
1403 Log(("rtldrPEOpen: %s: load cfg dir: unexpected dir size of %d bytes, expected %d.\n",
1404 pszLogName, Dir.Size, cbExpect));
1405 return VERR_LDRPE_LOAD_CONFIG_SIZE;
1406 }
1407
1408 /*
1409 * Read and convert to 64-bit.
1410 */
1411 memset(&u.Cfg64, 0, sizeof(u.Cfg64));
1412 int rc = rtldrPEReadRVA(pModPe, &u.Cfg64, Dir.Size, Dir.VirtualAddress);
1413 if (RT_FAILURE(rc))
1414 return rc;
1415 rtldrPEConvert32BitLoadConfigTo64Bit(&u.Cfg64);
1416
1417 if (u.Cfg64.Size != cbExpect)
1418 {
1419 Log(("rtldrPEOpen: %s: load cfg dir: unexpected header size of %d bytes, expected %d.\n",
1420 pszLogName, u.Cfg64.Size, cbExpect));
1421 return VERR_LDRPE_LOAD_CONFIG_SIZE;
1422 }
1423 if (u.Cfg64.LockPrefixTable)
1424 {
1425 Log(("rtldrPEOpen: %s: load cfg dir: lock prefix table at %RX64. We don't support lock prefix tables!\n",
1426 pszLogName, u.Cfg64.LockPrefixTable));
1427 return VERR_LDRPE_LOCK_PREFIX_TABLE;
1428 }
1429#if 0/* this seems to be safe to ignore. */
1430 if ( u.Cfg64.SEHandlerTable
1431 || u.Cfg64.SEHandlerCount)
1432 {
1433 Log(("rtldrPEOpen: %s: load cfg dir: SEHandlerTable=%RX64 and SEHandlerCount=%RX64 are unsupported!\n",
1434 pszLogName, u.Cfg64.SEHandlerTable, u.Cfg64.SEHandlerCount));
1435 return VERR_BAD_EXE_FORMAT;
1436 }
1437#endif
1438 if (u.Cfg64.EditList)
1439 {
1440 Log(("rtldrPEOpen: %s: load cfg dir: EditList=%RX64 is unsupported!\n",
1441 pszLogName, u.Cfg64.EditList));
1442 return VERR_BAD_EXE_FORMAT;
1443 }
1444 }
1445
1446 /*
1447 * If the image is signed, take a look at the signature.
1448 */
1449 Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
1450 if (Dir.Size)
1451 {
1452 PWIN_CERTIFICATE pFirst = (PWIN_CERTIFICATE)RTMemTmpAlloc(Dir.Size);
1453 if (!pFirst)
1454 return VERR_NO_TMP_MEMORY;
1455 int rc = pModPe->pReader->pfnRead(pModPe->pReader, pFirst, Dir.Size, Dir.VirtualAddress);
1456 if (RT_SUCCESS(rc))
1457 {
1458 uint32_t off = 0;
1459 PWIN_CERTIFICATE pCur = pFirst;
1460 do
1461 {
1462 /* validate the members. */
1463 uint32_t const cbCur = RT_ALIGN_32(pCur->dwLength, 8);
1464 if ( cbCur < sizeof(WIN_CERTIFICATE)
1465 || cbCur + off > RT_ALIGN_32(Dir.Size, 8))
1466 {
1467 Log(("rtldrPEOpen: %s: cert at %#x/%#x: dwLength=%#x\n", pszLogName, off, Dir.Size, pCur->dwLength));
1468 rc = VERR_LDRPE_CERT_MALFORMED;
1469 break;
1470 }
1471 if ( pCur->wRevision != WIN_CERT_REVISION_2_0
1472 && pCur->wRevision != WIN_CERT_REVISION_1_0)
1473 {
1474 Log(("rtldrPEOpen: %s: cert at %#x/%#x: wRevision=%#x\n", pszLogName, off, Dir.Size, pCur->wRevision));
1475 rc = pCur->wRevision >= WIN_CERT_REVISION_1_0 ? VERR_LDRPE_CERT_UNSUPPORTED : VERR_LDRPE_CERT_MALFORMED;
1476 break;
1477 }
1478 if ( pCur->wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA
1479 && pCur->wCertificateType != WIN_CERT_TYPE_X509
1480 /*&& pCur->wCertificateType != WIN_CERT_TYPE_RESERVED_1*/
1481 /*&& pCur->wCertificateType != WIN_CERT_TYPE_TS_STACK_SIGNED*/
1482 && pCur->wCertificateType != WIN_CERT_TYPE_EFI_PKCS115
1483 && pCur->wCertificateType != WIN_CERT_TYPE_EFI_GUID
1484 )
1485 {
1486 Log(("rtldrPEOpen: %s: cert at %#x/%#x: wRevision=%#x\n", pszLogName, off, Dir.Size, pCur->wRevision));
1487 rc = pCur->wCertificateType ? VERR_LDRPE_CERT_UNSUPPORTED : VERR_LDRPE_CERT_MALFORMED;
1488 break;
1489 }
1490
1491 /** @todo Rainy Day: Implement further verification using openssl. */
1492
1493 /* next */
1494 off += cbCur;
1495 pCur = (PWIN_CERTIFICATE)((uint8_t *)pCur + cbCur);
1496 } while (off < Dir.Size);
1497 }
1498 RTMemTmpFree(pFirst);
1499 if (RT_FAILURE(rc))
1500 return rc;
1501 }
1502
1503
1504 return VINF_SUCCESS;
1505}
1506
1507
1508/**
1509 * Open a PE image.
1510 *
1511 * @returns iprt status code.
1512 * @param pReader The loader reader instance which will provide the raw image bits.
1513 * @param fFlags Reserved, MBZ.
1514 * @param enmArch Architecture specifier.
1515 * @param offNtHdrs The offset of the NT headers (where you find "PE\0\0").
1516 * @param phLdrMod Where to store the handle.
1517 */
1518int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs, PRTLDRMOD phLdrMod)
1519{
1520 /*
1521 * Read and validate the file header.
1522 */
1523 IMAGE_FILE_HEADER FileHdr;
1524 int rc = pReader->pfnRead(pReader, &FileHdr, sizeof(FileHdr), offNtHdrs + 4);
1525 if (RT_FAILURE(rc))
1526 return rc;
1527 RTLDRARCH enmArchImage;
1528 const char *pszLogName = pReader->pfnLogName(pReader);
1529 rc = rtldrPEValidateFileHeader(&FileHdr, pszLogName, &enmArchImage);
1530 if (RT_FAILURE(rc))
1531 return rc;
1532
1533 /*
1534 * Match the CPU architecture.
1535 */
1536 if ( enmArch != RTLDRARCH_WHATEVER
1537 && enmArch != enmArchImage)
1538 return VERR_LDR_ARCH_MISMATCH;
1539
1540 /*
1541 * Read and validate the "optional" header. Convert 32->64 if necessary.
1542 */
1543 IMAGE_OPTIONAL_HEADER64 OptHdr;
1544 rc = pReader->pfnRead(pReader, &OptHdr, FileHdr.SizeOfOptionalHeader, offNtHdrs + 4 + sizeof(IMAGE_FILE_HEADER));
1545 if (RT_FAILURE(rc))
1546 return rc;
1547 if (FileHdr.SizeOfOptionalHeader != sizeof(OptHdr))
1548 rtldrPEConvert32BitOptionalHeaderTo64Bit(&OptHdr);
1549 rc = rtldrPEValidateOptionalHeader(&OptHdr, pszLogName, offNtHdrs, &FileHdr, pReader->pfnSize(pReader));
1550 if (RT_FAILURE(rc))
1551 return rc;
1552
1553 /*
1554 * Read and validate section headers.
1555 */
1556 const size_t cbSections = sizeof(IMAGE_SECTION_HEADER) * FileHdr.NumberOfSections;
1557 PIMAGE_SECTION_HEADER paSections = (PIMAGE_SECTION_HEADER)RTMemAlloc(cbSections);
1558 if (!paSections)
1559 return VERR_NO_MEMORY;
1560 rc = pReader->pfnRead(pReader, paSections, cbSections, offNtHdrs + 4 + sizeof(IMAGE_FILE_HEADER) + FileHdr.SizeOfOptionalHeader);
1561 if (RT_SUCCESS(rc))
1562 {
1563 rc = rtldrPEValidateSectionHeaders(paSections, FileHdr.NumberOfSections, pszLogName,
1564 &OptHdr, pReader->pfnSize(pReader));
1565 if (RT_SUCCESS(rc))
1566 {
1567 /*
1568 * Allocate and initialize the PE module structure.
1569 */
1570 PRTLDRMODPE pModPe = (PRTLDRMODPE)RTMemAllocZ(sizeof(*pModPe));
1571 if (pModPe)
1572 {
1573 pModPe->Core.u32Magic = RTLDRMOD_MAGIC;
1574 pModPe->Core.eState = LDR_STATE_OPENED;
1575 if (FileHdr.SizeOfOptionalHeader == sizeof(OptHdr))
1576 pModPe->Core.pOps = &s_rtldrPE64Ops.Core;
1577 else
1578 pModPe->Core.pOps = &s_rtldrPE32Ops.Core;
1579 pModPe->pReader = pReader;
1580 pModPe->pvBits = NULL;
1581 pModPe->offNtHdrs = offNtHdrs;
1582 pModPe->u16Machine = FileHdr.Machine;
1583 pModPe->fFile = FileHdr.Characteristics;
1584 pModPe->cSections = FileHdr.NumberOfSections;
1585 pModPe->paSections = paSections;
1586 pModPe->uEntryPointRVA= OptHdr.AddressOfEntryPoint;
1587 pModPe->uImageBase = (RTUINTPTR)OptHdr.ImageBase;
1588 pModPe->cbImage = OptHdr.SizeOfImage;
1589 pModPe->cbHeaders = OptHdr.SizeOfHeaders;
1590 pModPe->ImportDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
1591 pModPe->RelocDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1592 pModPe->ExportDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
1593
1594 /*
1595 * Perform validation of some selected data directories which requires
1596 * inspection of the actual data.
1597 */
1598 rc = rtldrPEValidateDirectories(pModPe, &OptHdr);
1599 if (RT_SUCCESS(rc))
1600 {
1601 *phLdrMod = &pModPe->Core;
1602 return VINF_SUCCESS;
1603 }
1604 RTMemFree(pModPe);
1605 }
1606 else
1607 rc = VERR_NO_MEMORY;
1608 }
1609 }
1610 RTMemFree(paSections);
1611 return rc;
1612}
1613
Note: See TracBrowser for help on using the repository browser.

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