VirtualBox

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

Last change on this file since 31396 was 28800, checked in by vboxsync, 15 years ago

Automated rebranding to Oracle copyright/license strings via filemuncher

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 62.0 KB
Line 
1/* $Id: ldrPE.cpp 28800 2010-04-27 08:22:32Z vboxsync $ */
2/** @file
3 * IPRT - Binary Image Loader, Portable Executable (PE).
4 */
5
6/*
7 * Copyright (C) 2006-2007 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#define LOG_GROUP RTLOGGROUP_LDR
32#include <iprt/ldr.h>
33#include "internal/iprt.h"
34
35#include <iprt/alloc.h>
36#include <iprt/assert.h>
37#include <iprt/log.h>
38#include <iprt/string.h>
39#include <iprt/err.h>
40#include "internal/ldrPE.h"
41#include "internal/ldr.h"
42
43
44/*******************************************************************************
45* Defined Constants And Macros *
46*******************************************************************************/
47/** Converts rva to a type.
48 * @param pvBits Pointer to base of image bits.
49 * @param rva Relative virtual address.
50 * @param type Type.
51 */
52#define PE_RVA2TYPE(pvBits, rva, type) ((type) ((uintptr_t)pvBits + (uintptr_t)(rva)) )
53
54
55/*******************************************************************************
56* Structures and Typedefs *
57*******************************************************************************/
58/**
59 * The PE loader structure.
60 */
61typedef struct RTLDRMODPE
62{
63 /** Core module structure. */
64 RTLDRMODINTERNAL Core;
65 /** Pointer to the reader instance. */
66 PRTLDRREADER pReader;
67 /** Pointer to internal copy of image bits.
68 * @todo the reader should take care of this. */
69 void *pvBits;
70 /** The offset of the NT headers. */
71 RTFOFF offNtHdrs;
72
73 /** The machine type (IMAGE_FILE_HEADER::Machine). */
74 uint16_t u16Machine;
75 /** The file flags (IMAGE_FILE_HEADER::Characteristics). */
76 uint16_t fFile;
77 /** Number of sections (IMAGE_FILE_HEADER::NumberOfSections). */
78 unsigned cSections;
79 /** Pointer to an array of the section headers related to the file. */
80 PIMAGE_SECTION_HEADER paSections;
81
82 /** The RVA of the entry point (IMAGE_OPTIONAL_HEADER32::AddressOfEntryPoint). */
83 RTUINTPTR uEntryPointRVA;
84 /** The base address of the image at link time (IMAGE_OPTIONAL_HEADER32::ImageBase). */
85 RTUINTPTR uImageBase;
86 /** The size of the loaded image (IMAGE_OPTIONAL_HEADER32::SizeOfImage). */
87 uint32_t cbImage;
88 /** Size of the header (IMAGE_OPTIONAL_HEADER32::SizeOfHeaders). */
89 uint32_t cbHeaders;
90 /** The import data directory entry. */
91 IMAGE_DATA_DIRECTORY ImportDir;
92 /** The base relocation data directory entry. */
93 IMAGE_DATA_DIRECTORY RelocDir;
94 /** The export data directory entry. */
95 IMAGE_DATA_DIRECTORY ExportDir;
96} RTLDRMODPE, *PRTLDRMODPE;
97
98/**
99 * PE Loader module operations.
100 *
101 * The PE loader has one operation which is a bit different between 32-bit and 64-bit PE images,
102 * and for historical and performance reasons have been split into separate functions. Thus the
103 * PE loader extends the RTLDROPS structure with this one entry.
104 */
105typedef struct RTLDROPSPE
106{
107 /** The usual ops. */
108 RTLDROPS Core;
109
110 /**
111 * Resolves all imports.
112 *
113 * @returns iprt status code.
114 * @param pModPe Pointer to the PE loader module structure.
115 * @param pvBitsR Where to read raw image bits. (optional)
116 * @param pvBitsW Where to store the imports. The size of this buffer is equal or
117 * larger to the value returned by pfnGetImageSize().
118 * @param pfnGetImport The callback function to use to resolve imports (aka unresolved externals).
119 * @param pvUser User argument to pass to the callback.
120 */
121 DECLCALLBACKMEMBER(int, pfnResolveImports)(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, PFNRTLDRIMPORT pfnGetImport, void *pvUser);
122
123 /** Dummy entry to make sure we've initialized it all. */
124 RTUINT uDummy;
125} RTLDROPSPE, *PRTLDROPSPE;
126
127
128/*******************************************************************************
129* Internal Functions *
130*******************************************************************************/
131static void rtldrPEConvert32BitOptionalHeaderTo64Bit(PIMAGE_OPTIONAL_HEADER64 pOptHdr);
132static void rtldrPEConvert32BitLoadConfigTo64Bit(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg);
133static int rtldrPEApplyFixups(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, RTUINTPTR BaseAddress, RTUINTPTR OldBaseAddress);
134
135
136/** @copydoc RTLDROPS::pfnGetImageSize */
137static DECLCALLBACK(size_t) rtldrPEGetImageSize(PRTLDRMODINTERNAL pMod)
138{
139 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
140 return pModPe->cbImage;
141}
142
143
144/**
145 * Reads the image into memory.
146 *
147 * @returns iprt status code.
148 * @param pModPe The PE module.
149 * @param pvBits Where to store the bits, this buffer is at least pItem->Core.cbImage in size.
150 */
151static int rtldrPEGetBitsNoImportsNorFixups(PRTLDRMODPE pModPe, void *pvBits)
152{
153 /*
154 * Both these checks are related to pfnDone().
155 */
156 PRTLDRREADER pReader = pModPe->pReader;
157 if (!pReader)
158 {
159 AssertMsgFailed(("You've called done!\n"));
160 return VERR_WRONG_ORDER;
161 }
162 if (!pvBits)
163 return VERR_NO_MEMORY;
164
165 /*
166 * Zero everything (could be done per section).
167 */
168 memset(pvBits, 0, pModPe->cbImage);
169
170#ifdef PE_FILE_OFFSET_EQUALS_RVA
171 /*
172 * Read the entire image / file.
173 */
174 const RTFOFF cbRawImage = pReader->pfnSize(pReader)
175 rc = pReader->pfnRead(pReader, pvBits, RT_MIN(pModPe->cbImage, cbRawImage), 0);
176 if (RT_FAILURE(rc))
177 Log(("rtldrPE: %s: Reading %#x bytes at offset %#x failed, %Rrc!!! (the entire image)\n",
178 pReader->pfnLogName(pReader), RT_MIN(pModPe->cbImage, cbRawImage), 0, rc));
179#else
180
181 /*
182 * Read the headers.
183 */
184 int rc = pReader->pfnRead(pReader, pvBits, pModPe->cbHeaders, 0);
185 if (RT_SUCCESS(rc))
186 {
187 /*
188 * Read the sections.
189 */
190 PIMAGE_SECTION_HEADER pSH = pModPe->paSections;
191 for (unsigned cLeft = pModPe->cSections; cLeft > 0; cLeft--, pSH++)
192 if (pSH->SizeOfRawData && pSH->Misc.VirtualSize)
193 {
194 rc = pReader->pfnRead(pReader, (uint8_t *)pvBits + pSH->VirtualAddress, pSH->SizeOfRawData, pSH->PointerToRawData);
195 if (RT_FAILURE(rc))
196 {
197 Log(("rtldrPE: %s: Reading %#x bytes at offset %#x failed, %Rrc - section #%d '%.*s'!!!\n",
198 pReader->pfnLogName(pReader), pSH->SizeOfRawData, pSH->PointerToRawData, rc,
199 pSH - pModPe->paSections, sizeof(pSH->Name), pSH->Name));
200 break;
201 }
202 }
203 }
204 else
205 Log(("rtldrPE: %s: Reading %#x bytes at offset %#x failed, %Rrc!!!\n",
206 pReader->pfnLogName(pReader), pModPe->cbHeaders, 0, rc));
207#endif
208 return rc;
209}
210
211
212/**
213 * Reads the bits into the internal buffer pointed to by PRTLDRMODPE::pvBits.
214 *
215 * @returns iprt status code.
216 * @param pModPe The PE module.
217 */
218static int rtldrPEReadBits(PRTLDRMODPE pModPe)
219{
220 Assert(!pModPe->pvBits);
221 void *pvBitsW = RTMemAllocZ(pModPe->cbImage);
222 if (!pvBitsW)
223 return VERR_NO_MEMORY;
224 int rc = rtldrPEGetBitsNoImportsNorFixups(pModPe, pvBitsW);
225 if (RT_SUCCESS(rc))
226 pModPe->pvBits = pvBitsW;
227 else
228 RTMemFree(pvBitsW);
229 return rc;
230}
231
232
233/** @copydoc RTLDROPS::pfnGetBits */
234static DECLCALLBACK(int) rtldrPEGetBits(PRTLDRMODINTERNAL pMod, void *pvBits, RTUINTPTR BaseAddress, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
235{
236 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
237
238 /*
239 * Read the image.
240 */
241 int rc = rtldrPEGetBitsNoImportsNorFixups(pModPe, pvBits);
242 if (RT_SUCCESS(rc))
243 {
244 /*
245 * Resolve imports.
246 */
247 rc = ((PRTLDROPSPE)pMod->pOps)->pfnResolveImports(pModPe, pvBits, pvBits, pfnGetImport, pvUser);
248 if (RT_SUCCESS(rc))
249 {
250 /*
251 * Apply relocations.
252 */
253 rc = rtldrPEApplyFixups(pModPe, pvBits, pvBits, BaseAddress, pModPe->uImageBase);
254 if (RT_SUCCESS(rc))
255 return rc;
256 AssertMsgFailed(("Failed to apply fixups. rc=%Rrc\n", rc));
257 }
258 else
259 AssertMsgFailed(("Failed to resolve imports. rc=%Rrc\n", rc));
260 }
261 return rc;
262}
263
264
265/** @copydoc RTLDROPSPE::pfnResolveImports */
266static DECLCALLBACK(int) rtldrPEResolveImports32(PRTLDRMODPE pModPe, const void *pvBitsR, void *pvBitsW, PFNRTLDRIMPORT pfnGetImport, void *pvUser)
267{
268 /*
269 * Check if there is actually anything to work on.
270 */
271 if ( !pModPe->ImportDir.VirtualAddress
272 || !pModPe->ImportDir.Size)
273 return 0;
274
275 /*
276 * Walk the IMAGE_IMPORT_DESCRIPTOR table.
277 */
278 int rc = VINF_SUCCESS;
279 PIMAGE_IMPORT_DESCRIPTOR pImps;
280 for (pImps = PE_RVA2TYPE(pvBitsR, pModPe->ImportDir.VirtualAddress, PIMAGE_IMPORT_DESCRIPTOR);
281 !rc && pImps->Name != 0 && pImps->FirstThunk != 0;
282 pImps++)
283 {
284 const char *pszModName = PE_RVA2TYPE(pvBitsR, pImps->Name, const char *);
285 PIMAGE_THUNK_DATA32 pFirstThunk; /* update this. */
286 PIMAGE_THUNK_DATA32 pThunk; /* read from this. */
287 Log3(("RTLdrPE: Import descriptor: %s\n", pszModName));
288 Log4(("RTLdrPE: OriginalFirstThunk = %#RX32\n"
289 "RTLdrPE: TimeDateStamp = %#RX32\n"
290 "RTLdrPE: ForwarderChain = %#RX32\n"
291 "RTLdrPE: Name = %#RX32\n"
292 "RTLdrPE: FirstThunk = %#RX32\n",
293 pImps->u.OriginalFirstThunk, pImps->TimeDateStamp,
294 pImps->ForwarderChain, pImps->Name, pImps->FirstThunk));
295
296 /*
297 * Walk the thunks table(s).
298 */
299 pFirstThunk = PE_RVA2TYPE(pvBitsW, pImps->FirstThunk, PIMAGE_THUNK_DATA32);
300 pThunk = pImps->u.OriginalFirstThunk == 0
301 ? PE_RVA2TYPE(pvBitsR, pImps->FirstThunk, PIMAGE_THUNK_DATA32)
302 : PE_RVA2TYPE(pvBitsR, pImps->u.OriginalFirstThunk, PIMAGE_THUNK_DATA32);
303 while (!rc && pThunk->u1.Ordinal != 0)
304 {
305 RTUINTPTR Value = 0;
306 if (pThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG32)
307 {
308 rc = pfnGetImport(&pModPe->Core, pszModName, NULL, IMAGE_ORDINAL32(pThunk->u1.Ordinal), &Value, pvUser);
309 Log4((RT_SUCCESS(rc) ? "RTLdrPE: %RTptr #%u\n" : "RTLdrPE: %08RX32 #%u rc=%Rrc\n",
310 (uint32_t)Value, IMAGE_ORDINAL32(pThunk->u1.Ordinal), rc));
311 }
312 else if ( pThunk->u1.Ordinal > 0
313 && pThunk->u1.Ordinal < pModPe->cbImage)
314 {
315 rc = pfnGetImport(&pModPe->Core, pszModName, PE_RVA2TYPE(pvBitsR, (char*)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*)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::pfnDone */
771static DECLCALLBACK(int) rtldrPEDone(PRTLDRMODINTERNAL pMod)
772{
773 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
774 if (pModPe->pvBits)
775 {
776 RTMemFree(pModPe->pvBits);
777 pModPe->pvBits = NULL;
778 }
779 if (pModPe->pReader)
780 {
781 int rc = pModPe->pReader->pfnDestroy(pModPe->pReader);
782 AssertRC(rc);
783 pModPe->pReader = NULL;
784 }
785 return VINF_SUCCESS;
786}
787
788/** @copydoc RTLDROPS::pfnClose */
789static DECLCALLBACK(int) rtldrPEClose(PRTLDRMODINTERNAL pMod)
790{
791 PRTLDRMODPE pModPe = (PRTLDRMODPE)pMod;
792 if (pModPe->paSections)
793 {
794 RTMemFree(pModPe->paSections);
795 pModPe->paSections = NULL;
796 }
797 if (pModPe->pvBits)
798 {
799 RTMemFree(pModPe->pvBits);
800 pModPe->pvBits = NULL;
801 }
802 if (pModPe->pReader)
803 {
804 int rc = pModPe->pReader->pfnDestroy(pModPe->pReader);
805 AssertRC(rc);
806 pModPe->pReader = NULL;
807 }
808 return VINF_SUCCESS;
809}
810
811
812/**
813 * Operations for a 32-bit PE module.
814 */
815static const RTLDROPSPE s_rtldrPE32Ops =
816{
817 {
818 "pe32",
819 rtldrPEClose,
820 NULL,
821 rtldrPEDone,
822 rtldrPEEnumSymbols,
823 /* ext */
824 rtldrPEGetImageSize,
825 rtldrPEGetBits,
826 rtldrPERelocate,
827 rtldrPEGetSymbolEx,
828 42
829 },
830 rtldrPEResolveImports32,
831 42
832};
833
834
835/**
836 * Operations for a 64-bit PE module.
837 */
838static const RTLDROPSPE s_rtldrPE64Ops =
839{
840 {
841 "pe64",
842 rtldrPEClose,
843 NULL,
844 rtldrPEDone,
845 rtldrPEEnumSymbols,
846 /* ext */
847 rtldrPEGetImageSize,
848 rtldrPEGetBits,
849 rtldrPERelocate,
850 rtldrPEGetSymbolEx,
851 42
852 },
853 rtldrPEResolveImports64,
854 42
855};
856
857
858/**
859 * Converts the optional header from 32 bit to 64 bit.
860 * This is a rather simple task, if you start from the right end.
861 *
862 * @param pOptHdr On input this is a PIMAGE_OPTIONAL_HEADER32.
863 * On output this will be a PIMAGE_OPTIONAL_HEADER64.
864 */
865static void rtldrPEConvert32BitOptionalHeaderTo64Bit(PIMAGE_OPTIONAL_HEADER64 pOptHdr)
866{
867 /*
868 * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
869 */
870 IMAGE_OPTIONAL_HEADER32 volatile *pOptHdr32 = (IMAGE_OPTIONAL_HEADER32 volatile *)pOptHdr;
871 IMAGE_OPTIONAL_HEADER64 volatile *pOptHdr64 = pOptHdr;
872
873 /* from LoaderFlags and out the difference is 4 * 32-bits. */
874 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, LoaderFlags) + 16 == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, LoaderFlags));
875 Assert( RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]) + 16
876 == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]));
877 uint32_t volatile *pu32Dst = (uint32_t *)&pOptHdr64->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
878 const uint32_t volatile *pu32Src = (uint32_t *)&pOptHdr32->DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES] - 1;
879 const uint32_t volatile *pu32SrcLast = (uint32_t *)&pOptHdr32->LoaderFlags;
880 while (pu32Src >= pu32SrcLast)
881 *pu32Dst-- = *pu32Src--;
882
883 /* the previous 4 fields are 32/64 and needs special attention. */
884 pOptHdr64->SizeOfHeapCommit = pOptHdr32->SizeOfHeapCommit;
885 pOptHdr64->SizeOfHeapReserve = pOptHdr32->SizeOfHeapReserve;
886 pOptHdr64->SizeOfStackCommit = pOptHdr32->SizeOfStackCommit;
887 uint32_t u32SizeOfStackReserve = pOptHdr32->SizeOfStackReserve;
888 pOptHdr64->SizeOfStackReserve = u32SizeOfStackReserve;
889
890 /* The rest matches except for BaseOfData which has been merged into ImageBase in the 64-bit version..
891 * Thus, ImageBase needs some special treatement. It will probably work fine assigning one to the
892 * other since this is all declared volatile, but taking now chances, we'll use a temp variable.
893 */
894 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, SizeOfStackReserve) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve));
895 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, BaseOfData) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, ImageBase));
896 Assert(RT_OFFSETOF(IMAGE_OPTIONAL_HEADER32, SectionAlignment) == RT_OFFSETOF(IMAGE_OPTIONAL_HEADER64, SectionAlignment));
897 uint32_t u32ImageBase = pOptHdr32->ImageBase;
898 pOptHdr64->ImageBase = u32ImageBase;
899}
900
901
902/**
903 * Converts the load config directory from 32 bit to 64 bit.
904 * This is a rather simple task, if you start from the right end.
905 *
906 * @param pLoadCfg On input this is a PIMAGE_LOAD_CONFIG_DIRECTORY32.
907 * On output this will be a PIMAGE_LOAD_CONFIG_DIRECTORY64.
908 */
909static void rtldrPEConvert32BitLoadConfigTo64Bit(PIMAGE_LOAD_CONFIG_DIRECTORY64 pLoadCfg)
910{
911 /*
912 * volatile everywhere! Trying to prevent the compiler being a smarta$$ and reorder stuff.
913 */
914 IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *pLoadCfg32 = (IMAGE_LOAD_CONFIG_DIRECTORY32 volatile *)pLoadCfg;
915 IMAGE_LOAD_CONFIG_DIRECTORY64 volatile *pLoadCfg64 = pLoadCfg;
916
917 pLoadCfg64->SEHandlerCount = pLoadCfg32->SEHandlerCount;
918 pLoadCfg64->SEHandlerTable = pLoadCfg32->SEHandlerTable;
919 pLoadCfg64->SecurityCookie = pLoadCfg32->SecurityCookie;
920 pLoadCfg64->EditList = pLoadCfg32->EditList;
921 pLoadCfg64->Reserved1 = pLoadCfg32->Reserved1;
922 pLoadCfg64->CSDVersion = pLoadCfg32->CSDVersion;
923 pLoadCfg64->ProcessHeapFlags = pLoadCfg32->ProcessHeapFlags; /* switched place with ProcessAffinityMask, but we're more than 16 byte off by now so it doesn't matter. */
924 pLoadCfg64->ProcessAffinityMask = pLoadCfg32->ProcessAffinityMask;
925 pLoadCfg64->VirtualMemoryThreshold = pLoadCfg32->VirtualMemoryThreshold;
926 pLoadCfg64->MaximumAllocationSize = pLoadCfg32->MaximumAllocationSize;
927 pLoadCfg64->LockPrefixTable = pLoadCfg32->LockPrefixTable;
928 pLoadCfg64->DeCommitTotalFreeThreshold = pLoadCfg32->DeCommitTotalFreeThreshold;
929 uint32_t u32DeCommitFreeBlockThreshold = pLoadCfg32->DeCommitFreeBlockThreshold;
930 pLoadCfg64->DeCommitFreeBlockThreshold = u32DeCommitFreeBlockThreshold;
931 /* the rest is equal. */
932 Assert( RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, DeCommitFreeBlockThreshold)
933 == RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY64, DeCommitFreeBlockThreshold));
934}
935
936
937/**
938 * Validates the file header.
939 *
940 * @returns iprt status code.
941 * @param pFileHdr Pointer to the file header that needs validating.
942 * @param pszLogName The log name to prefix the errors with.
943 * @param penmArch Where to store the CPU architecture.
944 */
945int rtldrPEValidateFileHeader(PIMAGE_FILE_HEADER pFileHdr, const char *pszLogName, PRTLDRARCH penmArch)
946{
947 size_t cbOptionalHeader;
948 switch (pFileHdr->Machine)
949 {
950 case IMAGE_FILE_MACHINE_I386:
951 cbOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER32);
952 *penmArch = RTLDRARCH_X86_32;
953 break;
954 case IMAGE_FILE_MACHINE_AMD64:
955 cbOptionalHeader = sizeof(IMAGE_OPTIONAL_HEADER64);
956 *penmArch = RTLDRARCH_AMD64;
957 break;
958
959 default:
960 Log(("rtldrPEOpen: %s: Unsupported Machine=%#x\n",
961 pszLogName, pFileHdr->Machine));
962 *penmArch = RTLDRARCH_INVALID;
963 return VERR_BAD_EXE_FORMAT;
964 }
965 if (pFileHdr->SizeOfOptionalHeader != cbOptionalHeader)
966 {
967 Log(("rtldrPEOpen: %s: SizeOfOptionalHeader=%#x expected %#x\n",
968 pszLogName, pFileHdr->SizeOfOptionalHeader, cbOptionalHeader));
969 return VERR_BAD_EXE_FORMAT;
970 }
971 /* This restriction needs to be implemented elsewhere. */
972 if (pFileHdr->Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
973 {
974 Log(("rtldrPEOpen: %s: IMAGE_FILE_RELOCS_STRIPPED\n", pszLogName));
975 return VERR_BAD_EXE_FORMAT;
976 }
977 if (pFileHdr->NumberOfSections > 42)
978 {
979 Log(("rtldrPEOpen: %s: NumberOfSections=%d - our limit is 42, please raise it if the binary makes sense.(!!!)\n",
980 pszLogName, pFileHdr->NumberOfSections));
981 return VERR_BAD_EXE_FORMAT;
982 }
983 if (pFileHdr->NumberOfSections < 1)
984 {
985 Log(("rtldrPEOpen: %s: NumberOfSections=%d - we can't have an image without sections (!!!)\n",
986 pszLogName, pFileHdr->NumberOfSections));
987 return VERR_BAD_EXE_FORMAT;
988 }
989 return VINF_SUCCESS;
990}
991
992
993/**
994 * Validates the optional header (64/32-bit)
995 *
996 * @returns iprt status code.
997 * @param pOptHdr Pointer to the optional header which needs validation.
998 * @param pszLogName The log name to prefix the errors with.
999 * @param offNtHdrs The offset of the NT headers from teh start of the file.
1000 * @param pFileHdr Pointer to the file header (valid).
1001 * @param cbRawImage The raw image size.
1002 */
1003static int rtldrPEValidateOptionalHeader(const IMAGE_OPTIONAL_HEADER64 *pOptHdr, const char *pszLogName, RTFOFF offNtHdrs,
1004 const IMAGE_FILE_HEADER *pFileHdr, RTFOFF cbRawImage)
1005{
1006 const uint16_t CorrectMagic = pFileHdr->SizeOfOptionalHeader == sizeof(IMAGE_OPTIONAL_HEADER32)
1007 ? IMAGE_NT_OPTIONAL_HDR32_MAGIC : IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1008 if (pOptHdr->Magic != CorrectMagic)
1009 {
1010 Log(("rtldrPEOpen: %s: Magic=%#x - expected %#x!!!\n", pszLogName, pOptHdr->Magic, CorrectMagic));
1011 return VERR_BAD_EXE_FORMAT;
1012 }
1013 const uint32_t cbImage = pOptHdr->SizeOfImage;
1014 if (cbImage > _1G)
1015 {
1016 Log(("rtldrPEOpen: %s: SizeOfImage=%#x - Our limit is 1GB (%#x)!!!\n", pszLogName, cbImage, _1G));
1017 return VERR_BAD_EXE_FORMAT;
1018 }
1019 const uint32_t cbMinImageSize = pFileHdr->SizeOfOptionalHeader + sizeof(*pFileHdr) + 4 + (uint32_t)offNtHdrs;
1020 if (cbImage < cbMinImageSize)
1021 {
1022 Log(("rtldrPEOpen: %s: SizeOfImage=%#x to small, minimum %#x!!!\n", pszLogName, cbImage, cbMinImageSize));
1023 return VERR_BAD_EXE_FORMAT;
1024 }
1025 if (pOptHdr->AddressOfEntryPoint >= cbImage)
1026 {
1027 Log(("rtldrPEOpen: %s: AddressOfEntryPoint=%#x - beyond image size (%#x)!!!\n",
1028 pszLogName, pOptHdr->AddressOfEntryPoint, cbImage));
1029 return VERR_BAD_EXE_FORMAT;
1030 }
1031 if (pOptHdr->BaseOfCode >= cbImage)
1032 {
1033 Log(("rtldrPEOpen: %s: BaseOfCode=%#x - beyond image size (%#x)!!!\n",
1034 pszLogName, pOptHdr->BaseOfCode, cbImage));
1035 return VERR_BAD_EXE_FORMAT;
1036 }
1037#if 0/* only in 32-bit header */
1038 if (pOptHdr->BaseOfData >= cbImage)
1039 {
1040 Log(("rtldrPEOpen: %s: BaseOfData=%#x - beyond image size (%#x)!!!\n",
1041 pszLogName, pOptHdr->BaseOfData, cbImage));
1042 return VERR_BAD_EXE_FORMAT;
1043 }
1044#endif
1045 if (pOptHdr->SizeOfHeaders >= cbImage)
1046 {
1047 Log(("rtldrPEOpen: %s: SizeOfHeaders=%#x - beyond image size (%#x)!!!\n",
1048 pszLogName, pOptHdr->SizeOfHeaders, cbImage));
1049 return VERR_BAD_EXE_FORMAT;
1050 }
1051 /* don't know how to do the checksum, so ignore it. */
1052 if (pOptHdr->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1053 {
1054 Log(("rtldrPEOpen: %s: Subsystem=%#x (unknown)!!!\n", pszLogName, pOptHdr->Subsystem));
1055 return VERR_BAD_EXE_FORMAT;
1056 }
1057 if (pOptHdr->SizeOfHeaders < cbMinImageSize + pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER))
1058 {
1059 Log(("rtldrPEOpen: %s: SizeOfHeaders=%#x - cbMinImageSize %#x + sections %#x = %#llx!!!\n",
1060 pszLogName, pOptHdr->SizeOfHeaders,
1061 cbImage, cbMinImageSize, pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER),
1062 cbMinImageSize + pFileHdr->NumberOfSections * sizeof(IMAGE_SECTION_HEADER)));
1063 return VERR_BAD_EXE_FORMAT;
1064 }
1065 if (pOptHdr->SizeOfStackReserve < pOptHdr->SizeOfStackCommit)
1066 {
1067 Log(("rtldrPEOpen: %s: SizeOfStackReserve %#x < SizeOfStackCommit %#x!!!\n",
1068 pszLogName, pOptHdr->SizeOfStackReserve, pOptHdr->SizeOfStackCommit));
1069 return VERR_BAD_EXE_FORMAT;
1070 }
1071 if (pOptHdr->SizeOfHeapReserve < pOptHdr->SizeOfHeapCommit)
1072 {
1073 Log(("rtldrPEOpen: %s: SizeOfStackReserve %#x < SizeOfStackCommit %#x!!!\n",
1074 pszLogName, pOptHdr->SizeOfStackReserve, pOptHdr->SizeOfStackCommit));
1075 return VERR_BAD_EXE_FORMAT;
1076 }
1077
1078 /* DataDirectory */
1079 if (pOptHdr->NumberOfRvaAndSizes != RT_ELEMENTS(pOptHdr->DataDirectory))
1080 {
1081 Log(("rtldrPEOpen: %s: NumberOfRvaAndSizes=%d!!!\n", pszLogName, pOptHdr->NumberOfRvaAndSizes));
1082 return VERR_BAD_EXE_FORMAT;
1083 }
1084 for (unsigned i = 0; i < RT_ELEMENTS(pOptHdr->DataDirectory); i++)
1085 {
1086 IMAGE_DATA_DIRECTORY const *pDir = &pOptHdr->DataDirectory[i];
1087 if (!pDir->Size)
1088 continue;
1089 size_t cb = cbImage;
1090 switch (i)
1091 {
1092 case IMAGE_DIRECTORY_ENTRY_EXPORT: // 0
1093 case IMAGE_DIRECTORY_ENTRY_IMPORT: // 1
1094 case IMAGE_DIRECTORY_ENTRY_RESOURCE: // 2
1095 case IMAGE_DIRECTORY_ENTRY_EXCEPTION: // 3
1096 case IMAGE_DIRECTORY_ENTRY_BASERELOC: // 5
1097 case IMAGE_DIRECTORY_ENTRY_DEBUG: // 6
1098 case IMAGE_DIRECTORY_ENTRY_COPYRIGHT: // 7
1099 case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT: // 11
1100 case IMAGE_DIRECTORY_ENTRY_IAT: // 12 /* Import Address Table */
1101 break;
1102 case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: // 10 - need to check for lock prefixes.
1103 /* Delay inspection after section table is validated. */
1104 break;
1105
1106 case IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT: // 13
1107 Log(("rtldrPEOpen: %s: dir no. %d (DELAY_IMPORT) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1108 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1109 return VERR_LDRPE_DELAY_IMPORT;
1110
1111 case IMAGE_DIRECTORY_ENTRY_SECURITY: // 4
1112 /* The VirtualAddress is a PointerToRawData. */
1113 cb = (size_t)cbRawImage; Assert((RTFOFF)cb == cbRawImage);
1114 Log(("rtldrPEOpen: %s: dir no. %d (SECURITY) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1115 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1116 if (pDir->Size < sizeof(WIN_CERTIFICATE))
1117 {
1118 Log(("rtldrPEOpen: %s: Security directory is too small: %#x bytes\n", pszLogName, i, pDir->Size));
1119 return VERR_LDRPE_CERT_MALFORMED;
1120 }
1121 if (pDir->Size >= _1M)
1122 {
1123 Log(("rtldrPEOpen: %s: Security directory is too large: %#x bytes\n", pszLogName, i, pDir->Size));
1124 return VERR_LDRPE_CERT_MALFORMED;
1125 }
1126 if (pDir->VirtualAddress & 7)
1127 {
1128 Log(("rtldrPEOpen: %s: Security directory is misaligned: %#x\n", pszLogName, i, pDir->VirtualAddress));
1129 return VERR_LDRPE_CERT_MALFORMED;
1130 }
1131 break;
1132
1133 case IMAGE_DIRECTORY_ENTRY_GLOBALPTR: // 8 /* (MIPS GP) */
1134 Log(("rtldrPEOpen: %s: dir no. %d (GLOBALPTR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1135 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1136 return VERR_LDRPE_GLOBALPTR;
1137
1138 case IMAGE_DIRECTORY_ENTRY_TLS: // 9
1139 Log(("rtldrPEOpen: %s: dir no. %d (TLS) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1140 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1141 return VERR_LDRPE_TLS;
1142
1143 case IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR:// 14
1144 Log(("rtldrPEOpen: %s: dir no. %d (COM_DESCRIPTOR) VirtualAddress=%#x Size=%#x is not supported!!!\n",
1145 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1146 return VERR_LDRPE_COM_DESCRIPTOR;
1147
1148 default:
1149 Log(("rtldrPEOpen: %s: dir no. %d VirtualAddress=%#x Size=%#x is not supported!!!\n",
1150 pszLogName, i, pDir->VirtualAddress, pDir->Size));
1151 return VERR_BAD_EXE_FORMAT;
1152 }
1153 if (pDir->VirtualAddress >= cb)
1154 {
1155 Log(("rtldrPEOpen: %s: dir no. %d VirtualAddress=%#x is invalid (limit %#x)!!!\n",
1156 pszLogName, i, pDir->VirtualAddress, cb));
1157 return VERR_BAD_EXE_FORMAT;
1158 }
1159 if (pDir->Size > cb - pDir->VirtualAddress)
1160 {
1161 Log(("rtldrPEOpen: %s: dir no. %d Size=%#x is invalid (rva=%#x, limit=%#x)!!!\n",
1162 pszLogName, i, pDir->Size, pDir->VirtualAddress, cb));
1163 return VERR_BAD_EXE_FORMAT;
1164 }
1165 }
1166 return VINF_SUCCESS;
1167}
1168
1169
1170/**
1171 * Validates the section headers.
1172 *
1173 * @returns iprt status code.
1174 * @param paSections Pointer to the array of sections that is to be validated.
1175 * @param cSections Number of sections in that array.
1176 * @param pszLogName The log name to prefix the errors with.
1177 * @param pOptHdr Pointer to the optional header (valid).
1178 * @param cbRawImage The raw image size.
1179 */
1180int rtldrPEValidateSectionHeaders(const IMAGE_SECTION_HEADER *paSections, unsigned cSections, const char *pszLogName,
1181 const IMAGE_OPTIONAL_HEADER64 *pOptHdr, RTFOFF cbRawImage)
1182{
1183 const uint32_t cbImage = pOptHdr->SizeOfImage;
1184 const IMAGE_SECTION_HEADER *pSH = &paSections[0];
1185 uint32_t uRvaPrev = pOptHdr->SizeOfHeaders;
1186 Log3(("RTLdrPE: Section Headers:\n"));
1187 for (unsigned cSHdrsLeft = cSections; cSHdrsLeft > 0; cSHdrsLeft--, pSH++)
1188 {
1189 const unsigned iSH = pSH - &paSections[0]; NOREF(iSH);
1190 Log3(("RTLdrPE: #%d '%-8.8s' Characteristics: %08RX32\n"
1191 "RTLdrPE: VirtAddr: %08RX32 VirtSize: %08RX32\n"
1192 "RTLdrPE: FileOff: %08RX32 FileSize: %08RX32\n"
1193 "RTLdrPE: RelocOff: %08RX32 #Relocs: %08RX32\n"
1194 "RTLdrPE: LineOff: %08RX32 #Lines: %08RX32\n",
1195 iSH, pSH->Name, pSH->Characteristics,
1196 pSH->VirtualAddress, pSH->Misc.VirtualSize,
1197 pSH->PointerToRawData, pSH->SizeOfRawData,
1198 pSH->PointerToRelocations, pSH->NumberOfRelocations,
1199 pSH->PointerToLinenumbers, pSH->NumberOfLinenumbers));
1200 if (pSH->Characteristics & (IMAGE_SCN_MEM_16BIT | IMAGE_SCN_MEM_FARDATA | IMAGE_SCN_MEM_PURGEABLE | IMAGE_SCN_MEM_PRELOAD))
1201 {
1202 Log(("rtldrPEOpen: %s: Unsupported section flag(s) %#x section #%d '%.*s'!!!\n",
1203 pszLogName, pSH->Characteristics, iSH, sizeof(pSH->Name), pSH->Name));
1204 return VERR_BAD_EXE_FORMAT;
1205 }
1206
1207 if ( pSH->Misc.VirtualSize
1208 && !(pSH->Characteristics & IMAGE_SCN_TYPE_NOLOAD)) /* binutils uses this for '.stab' even if it's reserved/obsoleted by MS. */
1209 {
1210 if (pSH->VirtualAddress < uRvaPrev)
1211 {
1212 Log(("rtldrPEOpen: %s: Overlaps previous section or sections aren't in ascending order, VirtualAddress=%#x uRvaPrev=%#x - section #%d '%.*s'!!!\n",
1213 pszLogName, pSH->VirtualAddress, uRvaPrev, iSH, sizeof(pSH->Name), pSH->Name));
1214 return VERR_BAD_EXE_FORMAT;
1215 }
1216 if (pSH->VirtualAddress > cbImage)
1217 {
1218 Log(("rtldrPEOpen: %s: VirtualAddress=%#x - beyond image size (%#x) - section #%d '%.*s'!!!\n",
1219 pszLogName, pSH->VirtualAddress, cbImage, iSH, sizeof(pSH->Name), pSH->Name));
1220 return VERR_BAD_EXE_FORMAT;
1221 }
1222
1223 if (pSH->VirtualAddress & (pOptHdr->SectionAlignment - 1)) //ASSUMES power of 2 alignment.
1224 {
1225 Log(("rtldrPEOpen: %s: VirtualAddress=%#x missaligned (%#x) - section #%d '%.*s'!!!\n",
1226 pszLogName, pSH->VirtualAddress, pOptHdr->SectionAlignment, iSH, sizeof(pSH->Name), pSH->Name));
1227 return VERR_BAD_EXE_FORMAT;
1228 }
1229
1230#ifdef PE_FILE_OFFSET_EQUALS_RVA
1231 /* Our loader code assume rva matches the file offset. */
1232 if ( pSH->SizeOfRawData
1233 && pSH->PointerToRawData != pSH->VirtualAddress)
1234 {
1235 Log(("rtldrPEOpen: %s: ASSUMPTION FAILED: file offset %#x != RVA %#x - section #%d '%.*s'!!!\n",
1236 pszLogName, pSH->PointerToRawData, pSH->VirtualAddress, iSH, sizeof(pSH->Name), pSH->Name));
1237 return VERR_BAD_EXE_FORMAT;
1238 }
1239#endif
1240 }
1241
1242 ///@todo only if SizeOfRawData > 0 ?
1243 if ( pSH->PointerToRawData > cbRawImage /// @todo pSH->PointerToRawData >= cbRawImage ?
1244 || pSH->SizeOfRawData > cbRawImage
1245 || pSH->PointerToRawData + pSH->SizeOfRawData > cbRawImage)
1246 {
1247 Log(("rtldrPEOpen: %s: PointerToRawData=%#x SizeOfRawData=%#x - beyond end of file (%#x) - section #%d '%.*s'!!!\n",
1248 pszLogName, pSH->PointerToRawData, pSH->SizeOfRawData, cbRawImage,
1249 iSH, sizeof(pSH->Name), pSH->Name));
1250 return VERR_BAD_EXE_FORMAT;
1251 }
1252
1253 if (pSH->PointerToRawData & (pOptHdr->FileAlignment - 1)) //ASSUMES power of 2 alignment.
1254 {
1255 Log(("rtldrPEOpen: %s: PointerToRawData=%#x missaligned (%#x) - section #%d '%.*s'!!!\n",
1256 pszLogName, pSH->PointerToRawData, pOptHdr->FileAlignment, iSH, sizeof(pSH->Name), pSH->Name));
1257 return VERR_BAD_EXE_FORMAT;
1258 }
1259
1260 /* ignore the relocations and linenumbers. */
1261
1262 uRvaPrev = pSH->VirtualAddress + pSH->Misc.VirtualSize;
1263 }
1264
1265 /** @todo r=bird: more sanity checks! */
1266 return VINF_SUCCESS;
1267}
1268
1269
1270/**
1271 * Reads image data by RVA using the section headers.
1272 *
1273 * @returns iprt status code.
1274 * @param pModPe The PE module instance.
1275 * @param pvBuf Where to store the bits.
1276 * @param cb Number of bytes to tread.
1277 * @param RVA Where to read from.
1278 */
1279static int rtldrPEReadRVA(PRTLDRMODPE pModPe, void *pvBuf, uint32_t cb, uint32_t RVA)
1280{
1281 const IMAGE_SECTION_HEADER *pSH = pModPe->paSections;
1282 PRTLDRREADER pReader = pModPe->pReader;
1283 uint32_t cbRead;
1284 int rc;
1285
1286 /*
1287 * Is it the headers, i.e. prior to the first section.
1288 */
1289 if (RVA < pModPe->cbHeaders)
1290 {
1291 cbRead = RT_MIN(pModPe->cbHeaders - RVA, cb);
1292 rc = pReader->pfnRead(pReader, pvBuf, cbRead, RVA);
1293 if ( cbRead == cb
1294 || RT_FAILURE(rc))
1295 return rc;
1296 cb -= cbRead;
1297 RVA += cbRead;
1298 pvBuf = (uint8_t *)pvBuf + cbRead;
1299 }
1300
1301 /* In the zero space between headers and the first section? */
1302 if (RVA < pSH->VirtualAddress)
1303 {
1304 cbRead = RT_MIN(pSH->VirtualAddress - RVA, cb);
1305 memset(pvBuf, 0, cbRead);
1306 if (cbRead == cb)
1307 return VINF_SUCCESS;
1308 cb -= cbRead;
1309 RVA += cbRead;
1310 pvBuf = (uint8_t *)pvBuf + cbRead;
1311 }
1312
1313 /*
1314 * Iterate the sections.
1315 */
1316 for (unsigned cLeft = pModPe->cSections;
1317 cLeft > 0;
1318 cLeft--, pSH++)
1319 {
1320 uint32_t off = RVA - pSH->VirtualAddress;
1321 if (off < pSH->Misc.VirtualSize)
1322 {
1323 cbRead = RT_MIN(pSH->Misc.VirtualSize - off, cb);
1324 rc = pReader->pfnRead(pReader, pvBuf, cbRead, pSH->PointerToRawData + off);
1325 if ( cbRead == cb
1326 || RT_FAILURE(rc))
1327 return rc;
1328 cb -= cbRead;
1329 RVA += cbRead;
1330 pvBuf = (uint8_t *)pvBuf + cbRead;
1331 }
1332 uint32_t RVANext = cLeft ? pSH[1].VirtualAddress : pModPe->cbImage;
1333 if (RVA < RVANext)
1334 {
1335 cbRead = RT_MIN(RVANext - RVA, cb);
1336 memset(pvBuf, 0, cbRead);
1337 if (cbRead == cb)
1338 return VINF_SUCCESS;
1339 cb -= cbRead;
1340 RVA += cbRead;
1341 pvBuf = (uint8_t *)pvBuf + cbRead;
1342 }
1343 }
1344
1345 AssertFailed();
1346 return VERR_INTERNAL_ERROR;
1347}
1348
1349
1350/**
1351 * Validates the data of some selected data directories entries.
1352 *
1353 * This requires a valid section table and thus has to wait
1354 * till after we've read and validated it.
1355 *
1356 * @returns iprt status code.
1357 * @param pModPe The PE module instance.
1358 * @param pOptHdr Pointer to the optional header (valid).
1359 */
1360int rtldrPEValidateDirectories(PRTLDRMODPE pModPe, const IMAGE_OPTIONAL_HEADER64 *pOptHdr)
1361{
1362 const char *pszLogName = pModPe->pReader->pfnLogName(pModPe->pReader); NOREF(pszLogName);
1363 union /* combine stuff we're reading to help reduce stack usage. */
1364 {
1365 IMAGE_LOAD_CONFIG_DIRECTORY64 Cfg64;
1366 } u;
1367
1368 /*
1369 * The load config entry may include lock prefix tables and whatnot which we don't implement.
1370 * It does also include a lot of stuff which we can ignore, so we'll have to inspect the
1371 * actual data before we can make up our mind about it all.
1372 */
1373 IMAGE_DATA_DIRECTORY Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG];
1374 if (Dir.Size)
1375 {
1376 const size_t cbExpect = pOptHdr->Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC
1377 ? sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
1378 : sizeof(IMAGE_LOAD_CONFIG_DIRECTORY64);
1379 if ( Dir.Size != cbExpect
1380 && ( cbExpect == sizeof(IMAGE_LOAD_CONFIG_DIRECTORY32)
1381 && Dir.Size != (uint32_t)RT_OFFSETOF(IMAGE_LOAD_CONFIG_DIRECTORY32, SEHandlerTable))
1382 )
1383 {
1384 Log(("rtldrPEOpen: %s: load cfg dir: unexpected dir size of %d bytes, expected %d.\n",
1385 pszLogName, Dir.Size, cbExpect));
1386 return VERR_LDRPE_LOAD_CONFIG_SIZE;
1387 }
1388
1389 /*
1390 * Read and convert to 64-bit.
1391 */
1392 memset(&u.Cfg64, 0, sizeof(u.Cfg64));
1393 int rc = rtldrPEReadRVA(pModPe, &u.Cfg64, Dir.Size, Dir.VirtualAddress);
1394 if (RT_FAILURE(rc))
1395 return rc;
1396 rtldrPEConvert32BitLoadConfigTo64Bit(&u.Cfg64);
1397
1398 if (u.Cfg64.Size != cbExpect)
1399 {
1400 Log(("rtldrPEOpen: %s: load cfg dir: unexpected header size of %d bytes, expected %d.\n",
1401 pszLogName, u.Cfg64.Size, cbExpect));
1402 return VERR_LDRPE_LOAD_CONFIG_SIZE;
1403 }
1404 if (u.Cfg64.LockPrefixTable)
1405 {
1406 Log(("rtldrPEOpen: %s: load cfg dir: lock prefix table at %RX64. We don't support lock prefix tables!\n",
1407 pszLogName, u.Cfg64.LockPrefixTable));
1408 return VERR_LDRPE_LOCK_PREFIX_TABLE;
1409 }
1410#if 0/* this seems to be safe to ignore. */
1411 if ( u.Cfg64.SEHandlerTable
1412 || u.Cfg64.SEHandlerCount)
1413 {
1414 Log(("rtldrPEOpen: %s: load cfg dir: SEHandlerTable=%RX64 and SEHandlerCount=%RX64 are unsupported!\n",
1415 pszLogName, u.Cfg64.SEHandlerTable, u.Cfg64.SEHandlerCount));
1416 return VERR_BAD_EXE_FORMAT;
1417 }
1418#endif
1419 if (u.Cfg64.EditList)
1420 {
1421 Log(("rtldrPEOpen: %s: load cfg dir: EditList=%RX64 is unsupported!\n",
1422 pszLogName, u.Cfg64.EditList));
1423 return VERR_BAD_EXE_FORMAT;
1424 }
1425 }
1426
1427 /*
1428 * If the image is signed, take a look at the signature.
1429 */
1430 Dir = pOptHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY];
1431 if (Dir.Size)
1432 {
1433 PWIN_CERTIFICATE pFirst = (PWIN_CERTIFICATE)RTMemTmpAlloc(Dir.Size);
1434 if (!pFirst)
1435 return VERR_NO_TMP_MEMORY;
1436 int rc = pModPe->pReader->pfnRead(pModPe->pReader, pFirst, Dir.Size, Dir.VirtualAddress);
1437 if (RT_SUCCESS(rc))
1438 {
1439 uint32_t off = 0;
1440 PWIN_CERTIFICATE pCur = pFirst;
1441 do
1442 {
1443 /* validate the members. */
1444 uint32_t const cbCur = RT_ALIGN_32(pCur->dwLength, 8);
1445 if ( cbCur < sizeof(WIN_CERTIFICATE)
1446 || cbCur + off > RT_ALIGN_32(Dir.Size, 8))
1447 {
1448 Log(("rtldrPEOpen: %s: cert at %#x/%#x: dwLength=%#x\n", pszLogName, off, Dir.Size, pCur->dwLength));
1449 rc = VERR_LDRPE_CERT_MALFORMED;
1450 break;
1451 }
1452 if ( pCur->wRevision != WIN_CERT_REVISION_2_0
1453 && pCur->wRevision != WIN_CERT_REVISION_1_0)
1454 {
1455 Log(("rtldrPEOpen: %s: cert at %#x/%#x: wRevision=%#x\n", pszLogName, off, Dir.Size, pCur->wRevision));
1456 rc = pCur->wRevision >= WIN_CERT_REVISION_1_0 ? VERR_LDRPE_CERT_UNSUPPORTED : VERR_LDRPE_CERT_MALFORMED;
1457 break;
1458 }
1459 if ( pCur->wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA
1460 && pCur->wCertificateType != WIN_CERT_TYPE_X509
1461 /*&& pCur->wCertificateType != WIN_CERT_TYPE_RESERVED_1*/
1462 /*&& pCur->wCertificateType != WIN_CERT_TYPE_TS_STACK_SIGNED*/
1463 && pCur->wCertificateType != WIN_CERT_TYPE_EFI_PKCS115
1464 && pCur->wCertificateType != WIN_CERT_TYPE_EFI_GUID
1465 )
1466 {
1467 Log(("rtldrPEOpen: %s: cert at %#x/%#x: wRevision=%#x\n", pszLogName, off, Dir.Size, pCur->wRevision));
1468 rc = pCur->wCertificateType ? VERR_LDRPE_CERT_UNSUPPORTED : VERR_LDRPE_CERT_MALFORMED;
1469 break;
1470 }
1471
1472 /** @todo Rainy Day: Implement further verfication using openssl. */
1473
1474 /* next */
1475 off += cbCur;
1476 pCur = (PWIN_CERTIFICATE)((uint8_t *)pCur + cbCur);
1477 } while (off < Dir.Size);
1478 }
1479 RTMemTmpFree(pFirst);
1480 if (RT_FAILURE(rc))
1481 return rc;
1482 }
1483
1484
1485 return VINF_SUCCESS;
1486}
1487
1488
1489/**
1490 * Open a PE image.
1491 *
1492 * @returns iprt status code.
1493 * @param pReader The loader reader instance which will provide the raw image bits.
1494 * @param fFlags Reserved, MBZ.
1495 * @param enmArch Architecture specifier.
1496 * @param offNtHdrs The offset of the NT headers (where you find "PE\0\0").
1497 * @param phLdrMod Where to store the handle.
1498 */
1499int rtldrPEOpen(PRTLDRREADER pReader, uint32_t fFlags, RTLDRARCH enmArch, RTFOFF offNtHdrs, PRTLDRMOD phLdrMod)
1500{
1501 /*
1502 * Read and validate the file header.
1503 */
1504 IMAGE_FILE_HEADER FileHdr;
1505 int rc = pReader->pfnRead(pReader, &FileHdr, sizeof(FileHdr), offNtHdrs + 4);
1506 if (RT_FAILURE(rc))
1507 return rc;
1508 RTLDRARCH enmArchImage;
1509 const char *pszLogName = pReader->pfnLogName(pReader);
1510 rc = rtldrPEValidateFileHeader(&FileHdr, pszLogName, &enmArchImage);
1511 if (RT_FAILURE(rc))
1512 return rc;
1513
1514 /*
1515 * Match the CPU architecture.
1516 */
1517 if ( enmArch != RTLDRARCH_WHATEVER
1518 && enmArch != enmArchImage)
1519 return VERR_LDR_ARCH_MISMATCH;
1520
1521 /*
1522 * Read and validate the "optional" header. Convert 32->64 if necessary.
1523 */
1524 IMAGE_OPTIONAL_HEADER64 OptHdr;
1525 rc = pReader->pfnRead(pReader, &OptHdr, FileHdr.SizeOfOptionalHeader, offNtHdrs + 4 + sizeof(IMAGE_FILE_HEADER));
1526 if (RT_FAILURE(rc))
1527 return rc;
1528 if (FileHdr.SizeOfOptionalHeader != sizeof(OptHdr))
1529 rtldrPEConvert32BitOptionalHeaderTo64Bit(&OptHdr);
1530 rc = rtldrPEValidateOptionalHeader(&OptHdr, pszLogName, offNtHdrs, &FileHdr, pReader->pfnSize(pReader));
1531 if (RT_FAILURE(rc))
1532 return rc;
1533
1534 /*
1535 * Read and validate section headers.
1536 */
1537 const size_t cbSections = sizeof(IMAGE_SECTION_HEADER) * FileHdr.NumberOfSections;
1538 PIMAGE_SECTION_HEADER paSections = (PIMAGE_SECTION_HEADER)RTMemAlloc(cbSections);
1539 if (!paSections)
1540 return VERR_NO_MEMORY;
1541 rc = pReader->pfnRead(pReader, paSections, cbSections, offNtHdrs + 4 + sizeof(IMAGE_FILE_HEADER) + FileHdr.SizeOfOptionalHeader);
1542 if (RT_SUCCESS(rc))
1543 {
1544 rc = rtldrPEValidateSectionHeaders(paSections, FileHdr.NumberOfSections, pszLogName,
1545 &OptHdr, pReader->pfnSize(pReader));
1546 if (RT_SUCCESS(rc))
1547 {
1548 /*
1549 * Allocate and initialize the PE module structure.
1550 */
1551 PRTLDRMODPE pModPe = (PRTLDRMODPE)RTMemAllocZ(sizeof(*pModPe));
1552 if (pModPe)
1553 {
1554 pModPe->Core.u32Magic = RTLDRMOD_MAGIC;
1555 pModPe->Core.eState = LDR_STATE_OPENED;
1556 if (FileHdr.SizeOfOptionalHeader == sizeof(OptHdr))
1557 pModPe->Core.pOps = &s_rtldrPE64Ops.Core;
1558 else
1559 pModPe->Core.pOps = &s_rtldrPE32Ops.Core;
1560 pModPe->pReader = pReader;
1561 pModPe->pvBits = NULL;
1562 pModPe->offNtHdrs = offNtHdrs;
1563 pModPe->u16Machine = FileHdr.Machine;
1564 pModPe->fFile = FileHdr.Characteristics;
1565 pModPe->cSections = FileHdr.NumberOfSections;
1566 pModPe->paSections = paSections;
1567 pModPe->uEntryPointRVA= OptHdr.AddressOfEntryPoint;
1568 pModPe->uImageBase = (RTUINTPTR)OptHdr.ImageBase;
1569 pModPe->cbImage = OptHdr.SizeOfImage;
1570 pModPe->cbHeaders = OptHdr.SizeOfHeaders;
1571 pModPe->ImportDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
1572 pModPe->RelocDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1573 pModPe->ExportDir = OptHdr.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
1574
1575 /*
1576 * Perform validation of some selected data directories which requires
1577 * inspection of the actual data.
1578 */
1579 rc = rtldrPEValidateDirectories(pModPe, &OptHdr);
1580 if (RT_SUCCESS(rc))
1581 {
1582 *phLdrMod = &pModPe->Core;
1583 return VINF_SUCCESS;
1584 }
1585 RTMemFree(pModPe);
1586 }
1587 else
1588 rc = VERR_NO_MEMORY;
1589 }
1590 }
1591 RTMemFree(paSections);
1592 return rc;
1593}
1594
Note: See TracBrowser for help on using the repository browser.

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