VirtualBox

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

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

IPRT: More debug info & ldr stuff.

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