source: trunk/src/kernel32/winimagepeldr.cpp@ 10397

Last change on this file since 10397 was 10397, checked in by sandervl, 22 years ago

Loader updates

File size: 75.0 KB
Line 
1/* $Id: winimagepeldr.cpp,v 1.109 2004-01-15 10:39:13 sandervl Exp $ */
2
3/*
4 * Win32 PE loader Image base class
5 *
6 * Copyright 1998-2000 Sander van Leeuwen (sandervl@xs4all.nl)
7 * Copyright 1998 Knut St. Osmundsen
8 * Copyright 2003 Innotek Systemberatung GmbH (sandervl@innotek.de)
9 *
10 *
11 * Project Odin Software License can be found in LICENSE.TXT
12 *
13 * TODO: Check psh[i].Characteristics for more than only the code section
14 * TODO: Make resource section readonly when GDI32 is fixed
15 * TODO: Loading of forwarder dlls before handling imports might not be correct
16 * (circular dependencies; have to check what NT does)
17 * TODO: Two LoadLibrary calls in two threads at the same time won't be handled properly (rare but possible)
18 *
19 * NOTE: FLAG_PELDR_LOADASDATAFILE is a special flag to only load the resource directory
20 * of a PE image. Processing imports, sections etc is not done.
21 * This is useful for GetVersionSize/Resource in case it wants to
22 * get version info of an image that is not loaded.
23 * So an instance of this type can't be used for anything but resource lookup!
24 *
25 * NOTE: File pointer operations relative to the start of the file must add
26 * ulPEOffset (in case PE image start != file start)
27 *
28 */
29#define INCL_DOSFILEMGR /* File Manager values */
30#define INCL_DOSMODULEMGR
31#define INCL_DOSERRORS /* DOS Error values */
32#define INCL_DOSPROCESS /* DOS Process values */
33#define INCL_DOSMISC /* DOS Miscellanous values */
34#define INCL_WIN
35#define INCL_BASE
36#include <os2wrap.h> //Odin32 OS/2 api wrappers
37
38#include <stdio.h>
39#include <string.h>
40#include <stdlib.h>
41
42#include <assert.h>
43//use a different logfile
44#define PRIVATE_LOGGING
45#include <misc.h>
46#include <win32api.h>
47#include <heapcode.h>
48#include <custombuild.h>
49#include "winimagebase.h"
50#include "winimagepeldr.h"
51#include "windllpeldr.h"
52#include "windlllx.h"
53#include "winexebase.h"
54#include <pefile.h>
55#include <unicode.h>
56#include "oslibmisc.h"
57#include "initterm.h"
58#include <win\virtual.h>
59#include "oslibdos.h"
60#include "oslibmem.h"
61#include "mmap.h"
62#include <wprocess.h>
63
64//Define COMMIT_ALL to let the pe loader commit all sections of the image
65//This is very useful during debugging as you'll get lots of exceptions
66//otherwise.
67//#ifdef DEBUG
68#define COMMIT_ALL
69//#endif
70
71char szErrorModule[260] = "";
72
73#ifdef DEBUG
74static FILE *_privateLogFile = NULL;
75#endif
76
77ULONG WIN32API MissingApiOrd(char *parentimage, char *dllname, int ordinal);
78ULONG WIN32API MissingApiName(char *parentimage, char *dllname, char *functionname);
79ULONG WIN32API MissingApi(char *message);
80
81//******************************************************************************
82//******************************************************************************
83void OpenPrivateLogFilePE()
84{
85#ifdef DEBUG
86 char logname[CCHMAXPATH];
87
88 sprintf(logname, "pe_%d.log", loadNr);
89 _privateLogFile = fopen(logname, "w");
90 if(_privateLogFile == NULL) {
91 sprintf(logname, "%spe_%d.log", kernel32Path, loadNr);
92 _privateLogFile = fopen(logname, "w");
93 }
94 dprintfGlobal(("PE LOGFILE : %s", logname));
95#endif
96}
97//******************************************************************************
98//******************************************************************************
99void ClosePrivateLogFilePE()
100{
101#ifdef DEBUG
102 if(_privateLogFile) {
103 fclose(_privateLogFile);
104 _privateLogFile = NULL;
105 }
106#endif
107}
108//******************************************************************************
109//******************************************************************************
110Win32PeLdrImage::Win32PeLdrImage(char *pszFileName, BOOL isExe) :
111 Win32ImageBase(-1),
112 nrsections(0), imageSize(0), dwFlags(0), section(NULL),
113 imageVirtBase(-1), realBaseAddress(0), imageVirtEnd(0),
114 memmap(NULL), pFixups(NULL), dwFixupSize(0), peview(NULL),
115 originalBaseAddress(0)
116{
117 HFILE dllfile;
118
119 fIsPEImage = TRUE;
120
121 strcpy(szFileName, pszFileName);
122 strupr(szFileName);
123 if(isExe) {
124 if(!strchr(szFileName, '.')) {
125 strcat(szFileName,".EXE");
126 }
127 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
128 if(dllfile == NULL) {
129 if(!strstr(szFileName, ".EXE")) {
130 strcat(szFileName,".EXE");
131 }
132 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
133 if(dllfile == NULL) {
134 OSLibDosSearchPath(OSLIB_SEARCHENV, "PATH", szFileName, szFileName, sizeof(szFileName));
135 }
136 }
137 else OSLibDosClose(dllfile);
138 }
139 else {
140 findDll(szFileName, szModule, sizeof(szModule));
141 strcpy(szFileName, szModule);
142 }
143 strcpy(szModule, OSLibStripPath(szFileName));
144 strupr(szModule);
145}
146//******************************************************************************
147//******************************************************************************
148Win32PeLdrImage::~Win32PeLdrImage()
149{
150 if(memmap)
151 {
152 if(peview) {
153 memmap->unmapViewOfFile(peview);
154 peview = NULL;
155 }
156 memmap->Release();
157 memmap = NULL;
158 realBaseAddress = NULL;
159 }
160 else
161 if(realBaseAddress)
162 OSLibDosFreeMem((PVOID)realBaseAddress);
163
164 if(hFile) {
165 OSLibDosClose(hFile);
166 hFile = 0;
167 }
168
169 if(section)
170 free(section);
171}
172//******************************************************************************
173//******************************************************************************
174DWORD Win32PeLdrImage::init(ULONG reservedMem, ULONG ulPEOffset)
175{
176 ULONG filesize, ulRead, ulNewPos;
177 PIMAGE_SECTION_HEADER psh;
178 IMAGE_SECTION_HEADER sh;
179 IMAGE_OPTIONAL_HEADER oh;
180 IMAGE_FILE_HEADER fh;
181 IMAGE_TLS_DIRECTORY *tlsDir = NULL;
182 int nSections, i;
183 char szFullPath[CCHMAXPATH] = "";
184 IMAGE_DOS_HEADER doshdr;
185 ULONG signature;
186 DWORD lasterror = LDRERROR_INTERNAL;
187
188 //offset in executable image where real PE file starts (default 0)
189 this->ulPEOffset = ulPEOffset;
190
191 hFile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
192
193 dprintf((LOG, "KERNEL32-PELDR: Opening PE-image (%s) returned handle %08xh.\n",
194 szFileName,
195 hFile));
196
197 //change to PE image start if necessary
198 if(ulPEOffset) {
199 if(OSLibDosSetFilePtr(hFile, ulPEOffset, OSLIB_SETPTR_FILE_BEGIN) == -1) {
200 lasterror = LDRERROR_INVALID_MODULE;
201 goto failure;
202 }
203 }
204
205 //default error:
206 strcpy(szErrorModule, OSLibStripPath(szFileName));
207 if(hFile == NULL) {
208 lasterror = LDRERROR_INTERNAL;
209 goto failure;
210 }
211 //read dos header
212 if(DosRead(hFile, (LPVOID)&doshdr, sizeof(doshdr), &ulRead)) {
213 lasterror = LDRERROR_INVALID_MODULE;
214 goto failure;
215 }
216 if(OSLibDosSetFilePtr(hFile, ulPEOffset+doshdr.e_lfanew, OSLIB_SETPTR_FILE_BEGIN) == -1) {
217 lasterror = LDRERROR_INVALID_MODULE;
218 goto failure;
219 }
220 //read signature dword
221 if(DosRead(hFile, (LPVOID)&signature, sizeof(signature), &ulRead)) {
222 lasterror = LDRERROR_INVALID_MODULE;
223 goto failure;
224 }
225 //read pe header
226 if(DosRead(hFile, (LPVOID)&fh, sizeof(fh), &ulRead)) {
227 lasterror = LDRERROR_INVALID_MODULE;
228 goto failure;
229 }
230 //read optional header
231 if(DosRead(hFile, (LPVOID)&oh, sizeof(oh), &ulRead)) {
232 lasterror = LDRERROR_INVALID_MODULE;
233 goto failure;
234 }
235 if(doshdr.e_magic != IMAGE_DOS_SIGNATURE || signature != IMAGE_NT_SIGNATURE) {
236 dprintf((LOG, "Not a valid PE file (probably a 16 bits windows exe/dll)!"));
237 lasterror = LDRERROR_INVALID_MODULE;
238 goto failure;
239 }
240
241 if(oh.SizeOfImage == 0) {//just in case
242 oh.SizeOfImage = OSLibDosGetFileSize(hFile, NULL);
243 }
244 Characteristics = fh.Characteristics;
245
246 //save original base address of image
247 originalBaseAddress = oh.ImageBase;
248
249 imageSize = oh.SizeOfImage;
250 //Allocate memory to hold the entire image
251 if(allocSections(reservedMem) == FALSE) {
252 dprintf((LOG, "Failed to allocate image memory for %s at %x, rc %d", szFileName, oh.ImageBase, errorState));;
253 lasterror = LDRERROR_MEMORY;
254 goto failure;
255 }
256
257 memmap = new Win32MemMap(this, realBaseAddress, imageSize);
258 if(memmap == NULL || !memmap->Init()) {
259 lasterror = LDRERROR_MEMORY;
260 goto failure;
261 }
262 peview = memmap->mapViewOfFile(0, 0, 2);
263
264 if(DosQueryPathInfo(szFileName, FIL_QUERYFULLNAME, szFullPath, sizeof(szFullPath)) == 0) {
265 setFullPath(szFullPath);
266 }
267
268 //Use pointer to image header as module handle now. Some apps needs this
269#ifdef COMMIT_ALL
270 commitPage(realBaseAddress, FALSE, SINGLE_PAGE);
271#endif
272 hinstance = (HINSTANCE)realBaseAddress;
273
274 //Calculate address of optional header
275 poh = (PIMAGE_OPTIONAL_HEADER)OPTHEADEROFF(hinstance);
276
277 if(!(fh.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) {//not valid
278 dprintf((LOG, "Not a valid PE file!"));
279 lasterror = LDRERROR_INVALID_MODULE;
280 goto failure;
281 }
282 if(fh.Machine != IMAGE_FILE_MACHINE_I386) {
283 dprintf((LOG, "Doesn't run on x86 processors!"));
284 lasterror = LDRERROR_INVALID_CPU;
285 goto failure;
286 }
287 //IMAGE_FILE_SYSTEM == only drivers (device/file system/video etc)?
288 if(fh.Characteristics & IMAGE_FILE_SYSTEM) {
289 dprintf((LOG, "Can't convert system files"));
290 lasterror = LDRERROR_FILE_SYSTEM;
291 goto failure;
292 }
293
294 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
295 dprintf((LOG, "No fixups, might not run!"));
296 }
297
298 dprintf((LOG, "PE file : %s", szFileName));
299 dprintf((LOG, "PE Optional header: "));
300 dprintf((LOG, "Preferred address : %d", oh.ImageBase ));
301 dprintf((LOG, "Base Of Code : %d", oh.BaseOfCode ));
302 dprintf((LOG, "CodeSize : %d", oh.SizeOfCode ));
303 dprintf((LOG, "Base Of Data : %d", oh.BaseOfData ));
304 dprintf((LOG, "Data Size (uninit): %d", oh.SizeOfUninitializedData ));
305 dprintf((LOG, "Data Size (init) : %d", oh.SizeOfInitializedData ));
306 dprintf((LOG, "Entry Point : %d", oh.AddressOfEntryPoint ));
307 dprintf((LOG, "Section Alignment : %d", oh.SectionAlignment ));
308 dprintf((LOG, "Stack Reserve size: %d", oh.SizeOfStackReserve ));
309 dprintf((LOG, "Stack Commit size : %d", oh.SizeOfStackCommit ));
310 dprintf((LOG, "SizeOfHeapReserve : %d", oh.SizeOfHeapReserve ));
311 dprintf((LOG, "SizeOfHeapCommit : %d", oh.SizeOfHeapCommit ));
312 dprintf((LOG, "FileAlignment : %d", oh.FileAlignment ));
313 dprintf((LOG, "Subsystem : %d", oh.Subsystem ));
314 dprintf((LOG, "Image Size : %d", oh.SizeOfImage ));
315 dprintf((LOG, "Header Size : %d", oh.SizeOfHeaders ));
316 dprintf((LOG, "MajorImageVersion : %d", oh.MajorImageVersion ));
317 dprintf((LOG, "MinorImageVersion : %d", oh.MinorImageVersion ));
318
319 //get header page
320 commitPage(realBaseAddress, FALSE);
321
322 nSections = NR_SECTIONS(peview);
323 section = (Section *)malloc(nSections*sizeof(Section));
324 if(section == NULL) {
325 DebugInt3();
326 lasterror = LDRERROR_MEMORY;
327 goto failure;
328 }
329 memset(section, 0, nSections*sizeof(Section));
330
331 imageSize = 0;
332 if ((psh = (PIMAGE_SECTION_HEADER)SECTIONHDROFF (peview)) != NULL)
333 {
334 dprintf((LOG, "*************************PE SECTIONS START**************************" ));
335 for (i=0; i<nSections; i++)
336 {
337 dprintf((LOG, "Section: %-8s", psh[i].Name ));
338 dprintf((LOG, "Raw data size: %x", psh[i].SizeOfRawData ));
339 dprintf((LOG, "Virtual Address: %x", psh[i].VirtualAddress ));
340 dprintf((LOG, "Virtual Address Start:%x", psh[i].VirtualAddress+oh.ImageBase ));
341 dprintf((LOG, "Virtual Address End: %x", psh[i].VirtualAddress+oh.ImageBase+psh[i].Misc.VirtualSize ));
342 dprintf((LOG, "Virtual Size: %x", psh[i].Misc.VirtualSize ));
343 dprintf((LOG, "Pointer to raw data: %x", psh[i].PointerToRawData ));
344 dprintf((LOG, "Section flags: %x\n\n", psh[i].Characteristics ));
345
346 if(IsSectionType(peview, &psh[i], IMAGE_DIRECTORY_ENTRY_BASERELOC))
347 {
348 dprintf((LOG, ".reloc" ));
349 addSection(SECTION_RELOC, psh[i].PointerToRawData,
350 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
351 psh[i].Misc.VirtualSize, psh[i].Characteristics);
352 continue;
353 }
354 if(IsSectionType(peview, &psh[i], IMAGE_DIRECTORY_ENTRY_EXPORT))
355 {
356 //SvL: Angus.exe has empty export section that's really an
357 // uninitialized data section
358 if(psh[i].SizeOfRawData) {
359 dprintf((LOG, ".edata" ));
360 addSection(SECTION_EXPORT, psh[i].PointerToRawData,
361 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
362 psh[i].Misc.VirtualSize, psh[i].Characteristics);
363 continue;
364 }
365 }
366 if(IsSectionType(peview, &psh[i], IMAGE_DIRECTORY_ENTRY_RESOURCE))
367 {
368 dprintf((LOG, ".rsrc" ));
369 addSection(SECTION_RESOURCE, psh[i].PointerToRawData,
370 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
371 psh[i].Misc.VirtualSize, psh[i].Characteristics);
372 continue;
373 }
374 if(IsSectionType(peview, &psh[i], IMAGE_DIRECTORY_ENTRY_TLS))
375 {
376 dprintf((LOG, "TLS section"));
377 tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(peview, IMAGE_DIRECTORY_ENTRY_TLS);
378 if(tlsDir) {
379 addSection(SECTION_TLS, psh[i].PointerToRawData,
380 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
381 psh[i].Misc.VirtualSize, psh[i].Characteristics);
382 }
383 continue;
384 }
385 if(IsSectionType(peview, &psh[i], IMAGE_DIRECTORY_ENTRY_IMPORT))
386 {
387 int type = SECTION_IMPORT;
388 dprintf((LOG, "Import Data Section" ));
389 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE) {
390 dprintf((LOG, "Also Code Section"));
391 type |= SECTION_CODE;
392 }
393 addSection(type, psh[i].PointerToRawData,
394 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
395 psh[i].Misc.VirtualSize, psh[i].Characteristics);
396 continue;
397 }
398 //KSO Sun 1998-08-09: Borland does not alway set the CODE flag for its "CODE" section
399 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE ||
400 (psh[i].Characteristics & IMAGE_SCN_MEM_EXECUTE &&
401 !(psh[i].Characteristics & (IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_CNT_INITIALIZED_DATA))) //KSO: make sure its not marked as a datasection
402 )
403 {
404 dprintf((LOG, "Code Section"));
405 addSection(SECTION_CODE, psh[i].PointerToRawData,
406 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
407 psh[i].Misc.VirtualSize, psh[i].Characteristics);
408 continue;
409 }
410 /* bird: Do this test as late as possible since marking a section as debug
411 * because it the section will not be preloaded if marked SECTION_DEBUG
412 * causeing a lot of annoying page faults when all should be preloaded.
413 * A debug section may contain more than just the debug directory.
414 *
415 * IIRC the debug directory doesn't contain the debug info, it's a table telling
416 * raw file offsets of the different debug types. It's never been any custom of
417 * linkers to put debug info into loadable segments/sections/objects, so I've some
418 * difficulty seeing why we're doing this in the first place.
419 *
420 * Why aren't we just using a general approach, which trust the section flags and
421 * only precommits the tree directories we use (fixups/imports/exports)?
422 */
423 if(IsSectionType(peview, &psh[i], IMAGE_DIRECTORY_ENTRY_DEBUG))
424 {
425 dprintf((LOG, ".rdebug" ));
426 addSection(SECTION_DEBUG, psh[i].PointerToRawData,
427 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
428 psh[i].Misc.VirtualSize, psh[i].Characteristics);
429 continue;
430 }
431 if(!(psh[i].Characteristics & IMAGE_SCN_MEM_WRITE)) { //read only data section
432 dprintf((LOG, "Read Only Data Section" ));
433 addSection(SECTION_READONLYDATA, psh[i].PointerToRawData,
434 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
435 psh[i].Misc.VirtualSize, psh[i].Characteristics);
436 continue;
437 }
438 if(psh[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
439 dprintf((LOG, "Uninitialized Data Section" ));
440 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
441 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
442 psh[i].Misc.VirtualSize, psh[i].Characteristics);
443 continue;
444 }
445 if(psh[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) {
446 dprintf((LOG, "Initialized Data Section" ));
447 addSection(SECTION_INITDATA, psh[i].PointerToRawData,
448 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
449 psh[i].Misc.VirtualSize, psh[i].Characteristics);
450 continue;
451 }
452 if(psh[i].Characteristics & (IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ)) {
453 dprintf((LOG, "Other Section, stored as read/write uninit data" ));
454 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
455 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
456 psh[i].Misc.VirtualSize, psh[i].Characteristics);
457 continue;
458 }
459 dprintf((LOG, "Unknown section" ));
460 lasterror = LDRERROR_INVALID_SECTION;
461 goto failure;
462 }
463 }
464 dprintf((LOG, "*************************PE SECTIONS END **************************" ));
465
466 imageSize += imageVirtBase - oh.ImageBase;
467 dprintf((LOG, "Total size of Image %x", imageSize ));
468 dprintf((LOG, "imageVirtBase %x", imageVirtBase ));
469 dprintf((LOG, "imageVirtEnd %x", imageVirtEnd ));
470
471 //In case there are any gaps between sections, adjust size
472 if(imageSize != imageVirtEnd - oh.ImageBase)
473 {
474 dprintf((LOG, "imageSize != imageVirtEnd - oh.ImageBase!" ));
475 imageSize = imageVirtEnd - oh.ImageBase;
476 }
477 if(imageSize < oh.SizeOfImage) {
478 imageSize = oh.SizeOfImage;
479 }
480
481 dprintf((LOG, "OS/2 base address %x", realBaseAddress ));
482 if(oh.AddressOfEntryPoint) {
483 entryPoint = realBaseAddress + oh.AddressOfEntryPoint;
484 }
485 else {
486 dprintf((LOG, "EntryPoint == NULL" ));
487 entryPoint = NULL;
488 }
489
490 //set memory protection flags
491 if(setMemFlags() == FALSE) {
492 dprintf((LOG, "Failed to set memory protection" ));
493 lasterror = LDRERROR_MEMORY;
494 }
495
496 if(realBaseAddress != oh.ImageBase && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
497 pFixups = (PIMAGE_BASE_RELOCATION)ImageDirectoryOffset(peview, IMAGE_DIRECTORY_ENTRY_BASERELOC);
498 dwFixupSize = ImageDirectorySize(peview, IMAGE_DIRECTORY_ENTRY_BASERELOC);
499 /* commit complete section to avoid getting exceptions inside setFixups(). */
500 commitPage((ULONG)pFixups, FALSE, COMPLETE_SECTION);
501 }
502
503 if(!(dwFlags & FLAG_PELDR_LOADASDATAFILE))
504 {
505 if(tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(peview, IMAGE_DIRECTORY_ENTRY_TLS))
506 {
507 Section *sect;
508 BOOL fTLSFixups = FALSE;
509
510 sect = findSectionByAddr(tlsDir->StartAddressOfRawData);
511 //There might be fixups for the TLS structure, so search the sections
512 //by the OS/2 virtual address too
513 if(sect == NULL) {
514 sect = findSectionByOS2Addr(tlsDir->StartAddressOfRawData);
515 fTLSFixups = TRUE;
516 }
517
518 dprintf((LOG, "TLS Directory" ));
519 dprintf((LOG, "TLS Address of Index %x", tlsDir->AddressOfIndex ));
520 dprintf((LOG, "TLS Address of Callbacks %x", tlsDir->AddressOfCallBacks ));
521 dprintf((LOG, "TLS SizeOfZeroFill %x", tlsDir->SizeOfZeroFill ));
522 dprintf((LOG, "TLS Characteristics %x", tlsDir->Characteristics ));
523 if(sect == NULL) {
524 dprintf((LOG, "Couldn't find TLS section!!" ));
525 lasterror = LDRERROR_INVALID_HEADER;
526 goto failure;
527 }
528 setTLSAddress((char *)sect->realvirtaddr);
529 setTLSInitSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData);
530 setTLSTotalSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData + tlsDir->SizeOfZeroFill);
531
532 fTLSFixups = FALSE;
533 sect = findSectionByAddr((ULONG)tlsDir->AddressOfIndex);
534 //There might be fixups for the TLS structure, so search the sections
535 //by the OS/2 virtual address too
536 if(sect == NULL) {
537 sect = findSectionByOS2Addr((ULONG)tlsDir->AddressOfIndex);
538 fTLSFixups = TRUE;
539 }
540 if(sect == NULL) {
541 dprintf((LOG, "Couldn't find TLS AddressOfIndex section!!" ));
542 lasterror = LDRERROR_INVALID_HEADER;
543 goto failure;
544 }
545 if(fTLSFixups) {
546 setTLSIndexAddr((LPDWORD)tlsDir->AddressOfIndex); //no fixup required
547 }
548 else {//need to add a manual fixup
549 setTLSIndexAddr((LPDWORD)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfIndex - sect->virtaddr)));
550 }
551
552 if((ULONG)tlsDir->AddressOfCallBacks != 0)
553 {
554 fTLSFixups = FALSE;
555
556 sect = findSectionByAddr((ULONG)tlsDir->AddressOfCallBacks);
557 //There might be fixups for the TLS structure, so search the sections
558 //by the OS/2 virtual address too
559 if(sect == NULL) {
560 sect = findSectionByOS2Addr((ULONG)tlsDir->AddressOfIndex);
561 fTLSFixups = TRUE;
562 }
563 if(sect == NULL) {
564 dprintf((LOG, "Couldn't find TLS AddressOfCallBacks section!!" ));
565 lasterror = LDRERROR_INVALID_HEADER;
566 goto failure;
567 }
568 if(fTLSFixups) {
569 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)tlsDir->AddressOfCallBacks); //no fixup required
570 }
571 else {//need to add a manual fixup
572 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfCallBacks - sect->virtaddr)));
573 }
574 //modify tls callback pointers for new image base address
575 int i = 0;
576 while(tlsCallBackAddr[i])
577 {
578 fTLSFixups = FALSE;
579
580 sect = findSectionByAddr((ULONG)tlsCallBackAddr[i]);
581 //There might be fixups for the TLS structure, so search the sections
582 //by the OS/2 virtual address too
583 if(sect == NULL) {
584 sect = findSectionByOS2Addr((ULONG)tlsCallBackAddr[i]);
585 fTLSFixups = TRUE;
586 }
587 if(sect == NULL) {
588 dprintf((LOG, "Couldn't find TLS callback section!!" ));
589 lasterror = LDRERROR_INVALID_HEADER;
590 goto failure;
591 }
592 if(fTLSFixups) {
593 tlsCallBackAddr[i] = tlsCallBackAddr[i];
594 }
595 else tlsCallBackAddr[i] = (PIMAGE_TLS_CALLBACK)(realBaseAddress + ((ULONG)tlsCallBackAddr[i] - oh.ImageBase));
596 i++;
597 }
598 }
599 }
600
601#ifdef DEBUG
602 dprintf((LOG, "Image directories: "));
603 for (i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
604 {
605 char *pszName;
606
607 if(oh.DataDirectory[i].VirtualAddress && oh.DataDirectory[i].Size) {
608 switch (i)
609 {
610 case IMAGE_DIRECTORY_ENTRY_EXPORT: pszName = "Export Directory (IMAGE_DIRECTORY_ENTRY_EXPORT)"; break;
611 case IMAGE_DIRECTORY_ENTRY_IMPORT: pszName = "Import Directory (IMAGE_DIRECTORY_ENTRY_IMPORT)"; break;
612 case IMAGE_DIRECTORY_ENTRY_RESOURCE: pszName = "Resource Directory (IMAGE_DIRECTORY_ENTRY_RESOURCE)"; break;
613 case IMAGE_DIRECTORY_ENTRY_EXCEPTION: pszName = "Exception Directory (IMAGE_DIRECTORY_ENTRY_EXCEPTION)"; break;
614 case IMAGE_DIRECTORY_ENTRY_SECURITY: pszName = "Security Directory (IMAGE_DIRECTORY_ENTRY_SECURITY)"; break;
615 case IMAGE_DIRECTORY_ENTRY_BASERELOC: pszName = "Base Relocation Table (IMAGE_DIRECTORY_ENTRY_BASERELOC)"; break;
616 case IMAGE_DIRECTORY_ENTRY_DEBUG: pszName = "Debug Directory (IMAGE_DIRECTORY_ENTRY_DEBUG)"; break;
617 case IMAGE_DIRECTORY_ENTRY_COPYRIGHT: pszName = "Description String (IMAGE_DIRECTORY_ENTRY_COPYRIGHT)"; break;
618 case IMAGE_DIRECTORY_ENTRY_GLOBALPTR: pszName = "Machine Value (MIPS GP) (IMAGE_DIRECTORY_ENTRY_GLOBALPTR)"; break;
619 case IMAGE_DIRECTORY_ENTRY_TLS: pszName = "TLS Directory (IMAGE_DIRECTORY_ENTRY_TLS)"; break;
620 case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: pszName = "Load Configuration Directory (IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG)"; break;
621 case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT:pszName = "Bound Import Directory in headers (IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT)"; break;
622 case IMAGE_DIRECTORY_ENTRY_IAT: pszName = "Import Address Table (IMAGE_DIRECTORY_ENTRY_IAT)"; break;
623 default:
624 pszName = "unknown";
625 }
626 dprintf((LOG, "directory %s", pszName));
627 dprintf((LOG, " Address 0x%08x", oh.DataDirectory[i].VirtualAddress));
628 dprintf((LOG, " Size 0x%08x", oh.DataDirectory[i].Size));
629 }
630 }
631 dprintf((LOG, "\n\n"));
632#endif
633
634#ifdef COMMIT_ALL
635 for (i=0; i<nSections; i++) {
636 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
637 }
638#else
639 for (i=0; i<nSections; i++) {
640 switch(section[i].type)
641 {
642 case SECTION_IMPORT:
643 case SECTION_RELOC:
644 case SECTION_EXPORT:
645 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
646 break;
647 }
648 }
649#endif
650 if(processExports() == FALSE) {
651 dprintf((LOG, "Failed to process exported apis" ));
652 lasterror = LDRERROR_EXPORTS;
653 goto failure;
654 }
655 }
656
657#ifndef COMMIT_ALL
658 if(entryPoint) {
659 //commit code at entrypoint, since we going to call it anyway
660 commitPage((ULONG)entryPoint, FALSE);
661 }
662#endif
663
664 //PH: get pResRootDir pointer correct first, since processImports may
665 // implicitly call functions depending on it.
666 if(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress && oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size)
667 {
668 //get offset in resource object of directory entry
669 pResRootDir = (PIMAGE_RESOURCE_DIRECTORY)(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress + realBaseAddress);
670 ulRVAResourceSection = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
671 }
672
673 //Allocate TLS index for this module
674 //Must do this before dlls are loaded for this module. Some apps assume
675 //they get TLS index 0 for their main executable
676 {
677 USHORT sel = SetWin32TIB(TIB_SWITCH_FORCE_WIN32);
678 tlsAlloc();
679 tlsAttachThread(); //setup TLS (main thread)
680 SetFS(sel);
681 }
682
683 if(!(dwFlags & (FLAG_PELDR_LOADASDATAFILE | FLAG_PELDR_SKIPIMPORTS)))
684 {
685 if(processImports() == FALSE) {
686 dprintf((LOG, "Failed to process imports!" ));
687 lasterror = LDRERROR_IMPORTS;
688 goto failure;
689 }
690 }
691 return LDRERROR_SUCCESS;
692
693failure:
694 if(memmap) {
695 memmap->Release();
696 memmap = NULL;
697 }
698 if(hFile) {
699 OSLibDosClose(hFile);
700 hFile = 0;
701 }
702 errorState = ERROR_INTERNAL;
703 return lasterror;
704}
705//******************************************************************************
706//******************************************************************************
707#define DOSREAD_IDEAL_SIZE 61440
708static inline APIRET _Optlink fastDosRead(HFILE hFile,
709 PVOID pAddress,
710 ULONG ulSize,
711 PULONG pulBytesRead)
712{
713 /* we better break the DosRead into multiple calls */
714 PBYTE p = (PBYTE)pAddress;
715 ULONG ulReadBytes;
716 APIRET rc;
717
718 *pulBytesRead = ulSize;
719
720 do
721 {
722 rc = DosRead(hFile,
723 p,
724 min(DOSREAD_IDEAL_SIZE, ulSize),
725 &ulReadBytes);
726 if (rc != NO_ERROR)
727 {
728 /* in case of errors bail out */
729 *pulBytesRead = 0;
730 return rc;
731 }
732
733 // PH 2001-11-15
734 // For corrupt or misinterpreted PE headers,
735 // the preceeding DosSetFilePtr may have moved the
736 // file pointer at or behind the file's end.
737 // DosRead will then return rc=0 and ulReadBytes=0.
738 // This must NOT lead to an infinite loop.
739 if (ulReadBytes == 0)
740 {
741 return ERROR_INTERNAL;
742 }
743
744 ulSize -= ulReadBytes;
745 p += ulReadBytes;
746 }
747 while (ulSize > 0);
748
749 return NO_ERROR;
750}
751
752//******************************************************************************
753// commitPage:
754// commits image page(s) when an access violation exception is received
755// (usually called from exception.cpp; also from other methods in this file)
756//
757// Parameters:
758// virtAddress - address of exception (rounded down to page boundary)
759// fWriteAccess - type of access violation (read or write)
760// fPageCmd - SINGLE_PAGE -> commit single page
761// SECTION_PAGES -> commit default nr of pages
762// COMPLETE_SECTION -> commit entire section
763//
764// Remarks:
765// DosEnterCritSec/DosExitCritSec is used to make sure the other threads in
766// the application can't touch the pages before they are loaded from disk and
767// fixups are applied.
768//
769// TODO:
770// SECTION_PAGES: - don't load pages starting at access violation address, but
771// a region surrounding it (e.g. -32k -> + 32k)
772// this will prevent many pagefaults when the app uses
773// pages with a lower addr.
774//
775//******************************************************************************
776BOOL Win32PeLdrImage::commitPage(ULONG virtAddress, BOOL fWriteAccess, int fPageCmd)
777{
778 Section *section;
779 ULONG offset, size, sectionsize, protflags, fileoffset, range, attr;
780 ULONG ulNewPos, ulRead, orgVirtAddress = virtAddress;
781 APIRET rc;
782 BOOL fCriticalSection = FALSE;
783
784 dprintf((LOG, "Win32PeLdrImage::commitPage %x %d %d", virtAddress, fWriteAccess, fPageCmd));
785 if(virtAddress == 0) {
786 return FALSE;
787 }
788
789 //Round down to nearest page boundary
790 virtAddress = virtAddress & ~0xFFF;
791
792 section = findSectionByOS2Addr(virtAddress);
793 if(section == NULL) {
794 section = findSectionByOS2Addr(orgVirtAddress);
795 if(section) {
796 virtAddress = orgVirtAddress;
797 }
798 }
799 if(section == NULL) {
800 size = 4096;
801 sectionsize = 4096;
802 //Header page must be readonly (same as in NT)
803 protflags = PAG_READ;
804 section = findPreviousSectionByOS2Addr(virtAddress);
805 if(section == NULL) {//access to header
806 offset = 0;
807 fileoffset = virtAddress - realBaseAddress;
808 }
809 else {
810 offset = virtAddress - (section->realvirtaddr + section->virtualsize);
811 fileoffset = section->rawoffset + section->rawsize + offset;
812 }
813 }
814 else {
815 protflags = section->pageflags;
816 offset = virtAddress - section->realvirtaddr;
817 sectionsize = section->virtualsize - offset;
818
819 if(offset > section->rawsize || section->type == SECTION_UNINITDATA) {
820 //unintialized data (set to 0)
821 size = 0;
822 fileoffset = -1;
823 }
824 else {
825 size = section->rawsize-offset;
826 fileoffset = section->rawoffset + offset;
827 }
828 if(fWriteAccess & !(section->pageflags & PAG_WRITE)) {
829 dprintf((LOG, "Win32PeLdrImage::commitPage: No write access to 0%x!", virtAddress));
830 return FALSE;
831 }
832 }
833 if(fPageCmd == COMPLETE_SECTION && (section && section->type == SECTION_DEBUG)) {//ignore
834#ifdef DEBUG
835 /* check for env. var. ODIN_PELDR_COMMIT_ALL, committing it anyway if that is set. */
836 static int f = -1;
837 if (f == -1)
838 f = (getenv("ODIN_PELDR_COMMIT_ALL") != NULL);
839 if (!f)
840#endif
841 return TRUE;
842 }
843 rc = DosEnterCritSec();
844 if(rc) {
845 dprintf((LOG, "DosEnterCritSec failed with rc %d", rc));
846 goto fail;
847 }
848 //tell fail handler to call DosExitCritSec
849 fCriticalSection = TRUE;
850
851 //Check range of pages with the same attributes starting at virtAddress
852 //(some pages might already have been loaded)
853 range = sectionsize;
854 rc = DosQueryMem((PVOID)virtAddress, &range, &attr);
855 if(rc) {
856 dprintf((LOG, "Win32PeLdrImage::commitPage: DosQueryMem for %x returned %d", virtAddress, rc));
857 goto fail;
858 }
859 if(attr & PAG_COMMIT) {
860 dprintf((LOG, "Win32PeLdrImage::commitPage: Memory at 0x%x already committed!", virtAddress));
861 goto fail;
862 }
863
864 if(fPageCmd == SINGLE_PAGE) {
865 size = min(size, PAGE_SIZE);
866 sectionsize = min(sectionsize, PAGE_SIZE);
867 }
868 else
869 if(fPageCmd == SECTION_PAGES) {
870 size = min(size, DEFAULT_NR_PAGES*PAGE_SIZE);
871 sectionsize = min(sectionsize, DEFAULT_NR_PAGES*PAGE_SIZE);
872 }
873 //else complete section
874
875 size = min(size, range);
876 sectionsize = min(sectionsize, range);
877
878 if(size && fileoffset != -1) {
879 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
880 if(rc) {
881 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
882 goto fail;
883 }
884
885 if(DosSetFilePtr(hFile, ulPEOffset+fileoffset, FILE_BEGIN, &ulNewPos) == -1) {
886 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetFilePtr failed for 0x%x!", fileoffset));
887 goto fail;
888 }
889#if 1
890 // 2001-05-31 PH
891 // ensure DosRead() does not have to read more
892 // than 65535 bytes, otherwise split into two requests!
893 rc = fastDosRead(hFile, (PVOID)virtAddress, size, &ulRead);
894#else
895 rc = DosRead(hFile, (PVOID)virtAddress, size, &ulRead);
896#endif
897 if(rc) {
898 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed for 0x%x %x %x %x (rc=%d)!", virtAddress, size, ulRead, fileoffset, rc));
899 goto fail;
900 }
901 if(ulRead != size) {
902 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed to read %x (%x) bytes at %x for 0x%x!", size, ulRead, fileoffset, virtAddress));
903 goto fail;
904 }
905 setFixups(virtAddress, sectionsize);
906
907 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
908 if(rc) {
909 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
910 goto fail;
911 }
912 }
913 else {
914 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
915 if(rc) {
916 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
917 goto fail;
918 }
919 setFixups(virtAddress, sectionsize);
920
921 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
922 if(rc) {
923 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
924 goto fail;
925 }
926 }
927 DosExitCritSec();
928 return TRUE;
929
930fail:
931 if(fCriticalSection) DosExitCritSec();
932 return FALSE;
933}
934//******************************************************************************
935//******************************************************************************
936void Win32PeLdrImage::addSection(ULONG type, ULONG rawoffset, ULONG rawsize, ULONG virtaddress, ULONG virtsize, ULONG flags)
937{
938 virtsize = max(rawsize, virtsize);
939
940 section[nrsections].rawoffset = rawoffset;
941 section[nrsections].type = type;
942 section[nrsections].rawsize = rawsize;
943 section[nrsections].virtaddr = virtaddress;
944 section[nrsections].flags = flags;
945
946 virtsize = ((virtsize - 1) & ~0xFFF) + PAGE_SIZE;
947 imageSize += virtsize;
948 section[nrsections].virtualsize = virtsize;
949
950 if(virtaddress < imageVirtBase)
951 imageVirtBase = virtaddress;
952 if(virtaddress + virtsize > imageVirtEnd)
953 imageVirtEnd = virtaddress + virtsize;
954
955 nrsections++;
956}
957//******************************************************************************
958//******************************************************************************
959BOOL Win32PeLdrImage::allocSections(ULONG reservedMem)
960{
961 APIRET rc;
962 ULONG baseAddress;
963
964 realBaseAddress = 0;
965
966 //Allocated in by pe.exe
967 if(reservedMem && reservedMem == originalBaseAddress) {
968 realBaseAddress = originalBaseAddress;
969 return TRUE;
970 }
971
972 //SvL: We don't care where the image is loaded for resource lookup
973 if(Characteristics & IMAGE_FILE_RELOCS_STRIPPED && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
974 return allocFixedMem(reservedMem);
975 }
976 rc = OSLibDosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE);
977 if(rc) {
978 dprintf((LOG, "Win32PeLdrImage::allocSections, DosAllocMem returned %d", rc));
979 errorState = rc;
980 return(FALSE);
981 }
982 realBaseAddress = baseAddress;
983 return(TRUE);
984}
985//******************************************************************************
986//******************************************************************************
987Section *Win32PeLdrImage::findSection(ULONG type)
988{
989 for(int i=0;i<nrsections;i++) {
990 if(section[i].type == type) {
991 return &section[i];
992 }
993 }
994 return NULL;
995}
996//******************************************************************************
997//******************************************************************************
998Section *Win32PeLdrImage::findSectionByAddr(ULONG addr)
999{
1000 for(int i=0;i<nrsections;i++) {
1001 if(section[i].virtaddr <= addr && section[i].virtaddr + section[i].virtualsize > addr) {
1002 return &section[i];
1003 }
1004 }
1005 return NULL;
1006}
1007//******************************************************************************
1008//******************************************************************************
1009Section *Win32PeLdrImage::findSectionByOS2Addr(ULONG addr)
1010{
1011 for(int i=0;i<nrsections;i++) {
1012 if(section[i].realvirtaddr <= addr && section[i].realvirtaddr + section[i].virtualsize > addr) {
1013 return &section[i];
1014 }
1015 }
1016 return NULL;
1017}
1018//******************************************************************************
1019//******************************************************************************
1020Section *Win32PeLdrImage::findPreviousSectionByOS2Addr(ULONG addr)
1021{
1022 ULONG lowestAddr = 0xffffffff;
1023 LONG index = -1;
1024
1025 for(int i=0;i<nrsections;i++) {
1026 if(section[i].realvirtaddr <= addr) {
1027 if(section[i].realvirtaddr < lowestAddr) {
1028 lowestAddr = section[i].realvirtaddr;
1029 index = i;
1030 }
1031 }
1032 }
1033 if(index == -1)
1034 return NULL;
1035
1036 return &section[index];
1037}
1038//******************************************************************************
1039#define FALLOC_SIZE (1024*1024)
1040//NOTE: Needs testing (while loop)
1041//TODO: Free unused (parts of) reservedMem
1042//******************************************************************************
1043BOOL Win32PeLdrImage::allocFixedMem(ULONG reservedMem)
1044{
1045 ULONG address = 0;
1046 ULONG *memallocs;
1047 ULONG alloccnt = 0;
1048 ULONG diff, i, baseAddress;
1049 APIRET rc;
1050 BOOL fLowMemory = FALSE;
1051
1052 //Reserve enough space to store 4096 pointers to 1MB memory chunks
1053 memallocs = (ULONG *)malloc(4096*sizeof(ULONG *));
1054 if(memallocs == NULL) {
1055 dprintf((LOG, "allocFixedMem: MALLOC FAILED for memallocs" ));
1056 return FALSE;
1057 }
1058
1059 if(originalBaseAddress < 512*1024*1024) {
1060 fLowMemory = TRUE;
1061 }
1062 while(TRUE) {
1063 rc = OSLibDosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ, fLowMemory);
1064 if(rc) break;
1065
1066 dprintf((LOG, "DosAllocMem returned %x", address ));
1067 if(address + FALLOC_SIZE >= originalBaseAddress) {
1068 if(address > originalBaseAddress) {//we've passed it!
1069 OSLibDosFreeMem((PVOID)address);
1070 break;
1071 }
1072 //found the right address
1073 OSLibDosFreeMem((PVOID)address);
1074
1075 diff = originalBaseAddress - address;
1076 if(diff) {
1077 rc = OSLibDosAllocMem((PPVOID)&address, diff, PAG_READ, fLowMemory);
1078 if(rc) break;
1079 }
1080 rc = OSLibDosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE, fLowMemory);
1081 if(rc) break;
1082
1083 if(diff) OSLibDosFreeMem((PVOID)address);
1084
1085 realBaseAddress = baseAddress;
1086 break;
1087 }
1088 memallocs[alloccnt++] = address;
1089 }
1090 for(i=0;i<alloccnt;i++) {
1091 OSLibDosFreeMem((PVOID)memallocs[i]);
1092 }
1093 free(memallocs);
1094
1095 if(realBaseAddress == 0) //Let me guess.. MS Office app?
1096 return(FALSE);
1097
1098 return(TRUE);
1099}
1100//******************************************************************************
1101//******************************************************************************
1102BOOL Win32PeLdrImage::setMemFlags()
1103{
1104 int i;
1105
1106 // Process all the image sections
1107 for(i=0;i<nrsections;i++) {
1108 section[i].realvirtaddr = realBaseAddress + (section[i].virtaddr - originalBaseAddress);
1109 }
1110
1111 for(i=0;i<nrsections;i++) {
1112 switch(section[i].type)
1113 {
1114 case SECTION_CODE:
1115 case (SECTION_CODE | SECTION_IMPORT):
1116 section[i].pageflags = PAG_EXECUTE | PAG_READ;
1117 if(section[i].flags & IMAGE_SCN_MEM_WRITE)
1118 section[i].pageflags |= PAG_WRITE;
1119 break;
1120 case SECTION_INITDATA:
1121 case SECTION_UNINITDATA:
1122 case SECTION_IMPORT:
1123 case SECTION_TLS:
1124 section[i].pageflags = PAG_WRITE | PAG_READ;
1125 break;
1126
1127 case SECTION_RESOURCE:
1128 //TODO: GDI32 changes some bitmap structures to avoid problems in Open32
1129 // -> causes crashes if resource section is readonly
1130 // -> make it readonly again when gdi32 has been rewritten
1131 section[i].pageflags = PAG_WRITE | PAG_READ;
1132 break;
1133
1134 case SECTION_READONLYDATA:
1135 case SECTION_EXPORT:
1136 default:
1137 section[i].pageflags = PAG_READ;
1138 break;
1139 }
1140 if(section[i].flags & (IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1141 //SvL: sometimes i.e. import/export sections also contain data
1142 // must make them read/write
1143 section[i].pageflags = PAG_WRITE;
1144 }
1145 }
1146 return(TRUE);
1147}
1148//******************************************************************************
1149//******************************************************************************
1150BOOL Win32PeLdrImage::setFixups(ULONG virtAddress, ULONG size)
1151{
1152 int i, j;
1153 char *page;
1154 ULONG count, newpage;
1155 Section *section;
1156 PIMAGE_BASE_RELOCATION prel = pFixups;
1157
1158 if(realBaseAddress == originalBaseAddress || Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
1159 return(TRUE);
1160 }
1161
1162 virtAddress -= realBaseAddress;
1163 //round size to next page boundary
1164 size = (size-1) & ~0xFFF;
1165 size += PAGE_SIZE;
1166
1167 if(prel) {
1168 j = 1;
1169 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
1170 prel->VirtualAddress && prel->VirtualAddress < virtAddress)
1171 {
1172 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1173 }
1174 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
1175 prel->VirtualAddress && prel->VirtualAddress < virtAddress + size)
1176 {
1177 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
1178 count = (prel->SizeOfBlock - 8)/2;
1179 j++;
1180 for(i=0;i<count;i++) {
1181 int type = prel->TypeOffset[i] >> 12;
1182 int offset = prel->TypeOffset[i] & 0xFFF;
1183 int fixupsize = 0;
1184
1185 switch(type)
1186 {
1187 case IMAGE_REL_BASED_HIGHLOW:
1188 fixupsize = 4;
1189 break;
1190 case IMAGE_REL_BASED_HIGH:
1191 case IMAGE_REL_BASED_LOW:
1192 fixupsize = 2;
1193 break;
1194 }
1195 //If the fixup crosses the final page boundary,
1196 //then we have to load another page
1197 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
1198 {
1199 newpage = realBaseAddress + prel->VirtualAddress + offset + fixupsize;
1200 newpage &= ~0xFFF;
1201
1202 section = findSectionByOS2Addr(newpage);
1203 if(section == NULL) {
1204 //should never happen
1205 dprintf((LOG, "::setFixups -> section == NULL!!"));
1206 return FALSE;
1207 }
1208 //SvL: Read page from disk
1209 commitPage(newpage, FALSE, SINGLE_PAGE);
1210
1211 //SvL: Enable write access (TODO: may need to prevent other threads from being active)
1212 DosSetMem((PVOID)newpage, PAGE_SIZE, PAG_READ|PAG_WRITE);
1213 }
1214
1215 switch(type)
1216 {
1217 case IMAGE_REL_BASED_ABSOLUTE:
1218 break; //skip
1219 case IMAGE_REL_BASED_HIGHLOW:
1220 AddOff32Fixup(prel->VirtualAddress + offset);
1221 break;
1222 case IMAGE_REL_BASED_HIGH:
1223 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
1224 break;
1225 case IMAGE_REL_BASED_LOW:
1226 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
1227 break;
1228 case IMAGE_REL_BASED_HIGHADJ:
1229 case IMAGE_REL_BASED_MIPS_JMPADDR:
1230 default:
1231 break;
1232 }
1233 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
1234 {
1235 //SvL: Restore original page protection flags (TODO: may need to prevent other threads from being active)
1236 DosSetMem((PVOID)newpage, PAGE_SIZE, section->pageflags);
1237 }
1238 }
1239 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1240 }//while
1241 }
1242 else {
1243 dprintf((LOG, "Win32PeLdrImage::setFixups, no fixups at %x, %d", virtAddress, size));
1244 return(FALSE);
1245 }
1246 return(TRUE);
1247}
1248//******************************************************************************
1249//******************************************************************************
1250BOOL Win32PeLdrImage::setFixups(PIMAGE_BASE_RELOCATION prel)
1251{
1252 int i, j;
1253 char *page;
1254 ULONG count;
1255
1256 if(Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
1257 return(TRUE);
1258 }
1259
1260 if(prel) {
1261 j = 1;
1262 while(prel->VirtualAddress) {
1263 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
1264 count = (prel->SizeOfBlock - 8)/2;
1265 dprintf((LOG, "Page %d Address %x Count %d", j, prel->VirtualAddress, count ));
1266 j++;
1267 for(i=0;i<count;i++) {
1268 int type = prel->TypeOffset[i] >> 12;
1269 int offset = prel->TypeOffset[i] & 0xFFF;
1270 switch(type) {
1271 case IMAGE_REL_BASED_ABSOLUTE:
1272//// dprintf((LOG, "absolute fixup; unused" ));
1273 break; //skip
1274 case IMAGE_REL_BASED_HIGHLOW:
1275//// dprintf((LOG, "address ", offset << " type ", type ));
1276 AddOff32Fixup(prel->VirtualAddress + offset);
1277 break;
1278 case IMAGE_REL_BASED_HIGH:
1279 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
1280 break;
1281 case IMAGE_REL_BASED_LOW:
1282 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
1283 break;
1284 case IMAGE_REL_BASED_HIGHADJ:
1285 case IMAGE_REL_BASED_MIPS_JMPADDR:
1286 default:
1287 dprintf((LOG, "Unknown/unsupported fixup type!" ));
1288 break;
1289 }
1290 }
1291 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1292 }//while
1293 }
1294 else {
1295 dprintf((LOG, "No internal fixups found!" ));
1296 errorState = ERROR_INTERNAL;
1297 return(FALSE);
1298 }
1299 return(TRUE);
1300}
1301//******************************************************************************
1302//******************************************************************************
1303void Win32PeLdrImage::AddOff32Fixup(ULONG fixupaddr)
1304{
1305 ULONG orgaddr;
1306 ULONG *fixup;
1307
1308 fixup = (ULONG *)(fixupaddr + realBaseAddress);
1309 orgaddr = *fixup;
1310// dprintf((LOG, "AddOff32Fixup 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, realBaseAddress + (*fixup - originalBaseAddress)));
1311 *fixup = realBaseAddress + (*fixup - originalBaseAddress);
1312}
1313//******************************************************************************
1314//******************************************************************************
1315void Win32PeLdrImage::AddOff16Fixup(ULONG fixupaddr, BOOL fHighFixup)
1316{
1317 ULONG orgaddr;
1318 USHORT *fixup;
1319
1320 fixup = (USHORT *)(fixupaddr + realBaseAddress);
1321 orgaddr = *fixup;
1322 if(fHighFixup) {
1323 *fixup += (USHORT)((realBaseAddress - originalBaseAddress) >> 16);
1324// dprintf((LOG, "AddOff16FixupH 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1325 }
1326 else {
1327 *fixup += (USHORT)((realBaseAddress - originalBaseAddress) & 0xFFFF);
1328// dprintf((LOG, "AddOff16FixupL 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1329 }
1330}
1331//******************************************************************************
1332#define MISSINGOFFSET_PUSHNAME 1
1333#define MISSINGOFFSET_PUSHORDINAL 1
1334#define MISSINGOFFSET_PUSHDLLNAME 6
1335#define MISSINGOFFSET_PUSHIMPORTIMAGE 11
1336#define MISSINGOFFSET_FUNCTION 16
1337
1338char missingapicode[23] = {
1339//push ordinal/name
1340 0x68, 0x00, 0x00, 0x00, 0x00,
1341//push dllname
1342 0x68, 0x00, 0x00, 0x00, 0x00,
1343//push image loading api
1344 0x68, 0x00, 0x00, 0x00, 0x00,
1345//mov ecx, MissingApiOrd/Name
1346 0xB9, 0x99, 0x99, 0x99, 0x99,
1347//call ecx
1348 0xFF, 0xD1,
1349//ret
1350 0xC3};
1351
1352//******************************************************************************
1353void Win32PeLdrImage::StoreImportByOrd(Win32ImageBase *WinImage, ULONG ordinal, ULONG impaddr)
1354{
1355 ULONG *import;
1356 ULONG apiaddr;
1357
1358 import = (ULONG *)impaddr;
1359 apiaddr = WinImage->getApi(ordinal);
1360 if(apiaddr == 0)
1361 {
1362 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%u not found\n",
1363 WinImage->getModuleName(),
1364 ordinal));
1365
1366 dprintf((LOG, "--->>> NOT FOUND!" ));
1367 char *code = (char *)_cmalloc(sizeof(missingapicode));
1368
1369#ifdef DEBUG
1370 MissingApiOrd(WinImage->getModuleName(), getModuleName(), ordinal);
1371#endif
1372 memcpy(code, missingapicode, sizeof(missingapicode));
1373 *(DWORD *)&code[MISSINGOFFSET_PUSHIMPORTIMAGE] = (DWORD)getModuleName();
1374 *(DWORD *)&code[MISSINGOFFSET_PUSHDLLNAME] = (DWORD)WinImage->getModuleName();
1375 *(DWORD *)&code[MISSINGOFFSET_PUSHORDINAL] = ordinal;
1376 *(DWORD *)&code[MISSINGOFFSET_FUNCTION] = (DWORD)MissingApiOrd;
1377 *import = (ULONG)code;
1378 }
1379 else *import = apiaddr;
1380}
1381//******************************************************************************
1382//******************************************************************************
1383void Win32PeLdrImage::StoreImportByName(Win32ImageBase *WinImage, char *impname, ULONG impaddr)
1384{
1385 ULONG *import;
1386 ULONG apiaddr;
1387
1388 import = (ULONG *)impaddr;
1389 apiaddr = WinImage->getApi(impname);
1390 if(apiaddr == 0)
1391 {
1392 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%s not found\n",
1393 WinImage->getModuleName(),
1394 impname));
1395
1396 dprintf((LOG, "--->>> NOT FOUND!" ));
1397
1398 char *code = (char *)_cmalloc(sizeof(missingapicode));
1399
1400#ifdef DEBUG
1401 MissingApiName(WinImage->getModuleName(), getModuleName(), impname);
1402#endif
1403
1404 memcpy(code, missingapicode, sizeof(missingapicode));
1405 *(DWORD *)&code[MISSINGOFFSET_PUSHIMPORTIMAGE] = (DWORD)getModuleName();
1406 *(DWORD *)&code[MISSINGOFFSET_PUSHDLLNAME] = (DWORD)WinImage->getModuleName();
1407 *(DWORD *)&code[MISSINGOFFSET_PUSHNAME] = (DWORD)impname;
1408 *(DWORD *)&code[MISSINGOFFSET_FUNCTION] = (DWORD)MissingApiName;
1409 *import = (ULONG)code;
1410 }
1411 else *import = apiaddr;
1412}
1413//******************************************************************************
1414//Install a hook that gets called when the exports have been processed
1415//******************************************************************************
1416static ODINPROC_DLLLOAD pfnDllLoad = NULL;
1417//******************************************************************************
1418BOOL WIN32API ODIN_SetDllLoadCallback(ODINPROC_DLLLOAD pfnMyDllLoad)
1419{
1420 pfnDllLoad = pfnMyDllLoad;
1421 return TRUE;
1422}
1423//******************************************************************************
1424//******************************************************************************
1425BOOL Win32PeLdrImage::processExports()
1426{
1427 IMAGE_SECTION_HEADER sh;
1428 PIMAGE_EXPORT_DIRECTORY ped;
1429 ULONG *ptrNames, *ptrAddress;
1430 USHORT *ptrOrd;
1431 BOOL fForwarder;
1432 int i;
1433
1434 /* get section header and pointer to data directory for .edata section */
1435 if((ped = (PIMAGE_EXPORT_DIRECTORY)ImageDirectoryOffset
1436 (peview, IMAGE_DIRECTORY_ENTRY_EXPORT)) != NULL &&
1437 GetSectionHdrByImageDir(peview, IMAGE_DIRECTORY_ENTRY_EXPORT, &sh) )
1438 {
1439
1440 dprintf((LOG, "Exported Functions: " ));
1441 ptrOrd = (USHORT *)((ULONG)ped->AddressOfNameOrdinals +
1442 (ULONG)peview);
1443 ptrNames = (ULONG *)((ULONG)ped->AddressOfNames +
1444 (ULONG)peview);
1445 ptrAddress = (ULONG *)((ULONG)ped->AddressOfFunctions +
1446 (ULONG)peview);
1447 int nrOrdExports = ped->NumberOfFunctions;
1448 int nrNameExports = ped->NumberOfNames;
1449
1450 int ord, RVAExport;
1451 char *name;
1452 for(i=0;i<ped->NumberOfNames;i++)
1453 {
1454 fForwarder = FALSE;
1455 ord = ptrOrd[i] + ped->Base;
1456 name = (char *)((ULONG)ptrNames[i] + (ULONG)peview);
1457 RVAExport = ptrAddress[ptrOrd[i]];
1458
1459 /* forwarder? ulRVA within export directory. */
1460 if(RVAExport > poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1461 RVAExport < poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1462 + poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1463 {
1464 fForwarder = loadForwarder(originalBaseAddress + RVAExport, name, ord);
1465 }
1466 if(!fForwarder) {
1467 //points to code (virtual address relative to originalBaseAddress
1468 dprintf((LOG, "address 0x%x %s @%d (0x%08x)", RVAExport, name, ord, realBaseAddress + RVAExport));
1469 }
1470 }
1471 for(i=0;i<max(ped->NumberOfNames,ped->NumberOfFunctions);i++)
1472 {
1473 fForwarder = FALSE;
1474 ord = ped->Base + i; //Correct??
1475 RVAExport = ptrAddress[i];
1476 /* forwarder? ulRVA within export directory. */
1477 if(RVAExport > poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1478 RVAExport < poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1479 + poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1480 {
1481 fForwarder = loadForwarder(originalBaseAddress + RVAExport, NULL, ord);
1482 }
1483 if(!fForwarder && RVAExport) {
1484 //points to code (virtual address relative to originalBaseAddress
1485 dprintf((LOG, "ord %d at 0x%08x (0x%08x)", ord, RVAExport, realBaseAddress + RVAExport));
1486 }
1487 }
1488 }
1489
1490 //Call the dll load hook; must be done here so noone has the opportunity
1491 //to use this dll (get exports)
1492 if(pfnDllLoad) {
1493 pfnDllLoad(hinstance);
1494 }
1495
1496 return(TRUE);
1497}
1498//******************************************************************************
1499//******************************************************************************
1500BOOL Win32PeLdrImage::loadForwarder(ULONG virtaddr, char *apiname, ULONG ordinal)
1501{
1502 char *forward = (char *)(realBaseAddress + (virtaddr - originalBaseAddress));
1503 char *forwarddll, *forwardapi;
1504 Win32DllBase *WinDll;
1505 DWORD exportaddr;
1506 int forwardord;
1507 int iForwardDllLength = strlen(forward);
1508 int iForwardApiLength;
1509
1510 if(iForwardDllLength == 0)
1511 return FALSE;
1512
1513 forwarddll = (char*)alloca(iForwardDllLength);
1514 if(forwarddll == NULL) {
1515 DebugInt3();
1516 return FALSE;
1517 }
1518 memcpy(forwarddll, forward, iForwardDllLength + 1);
1519
1520 forwardapi = strchr(forwarddll, '.');
1521 if(forwardapi == NULL) {
1522 return FALSE;
1523 }
1524 *forwardapi++ = 0;
1525 iForwardApiLength = strlen(forwardapi);
1526 if(iForwardApiLength == 0) {
1527 return FALSE;
1528 }
1529 WinDll = Win32DllBase::findModule(forwarddll);
1530 if(WinDll == NULL) {
1531 WinDll = loadDll(forwarddll);
1532 if(WinDll == NULL) {
1533 dprintf((LOG, "ERROR: couldn't find forwarder %s.%s", forwarddll, forwardapi));
1534 return FALSE;
1535 }
1536 }
1537 //check if name or ordinal forwarder
1538 forwardord = 0;
1539 if(*forwardapi >= '0' && *forwardapi <= '9') {
1540 forwardord = atoi(forwardapi);
1541 }
1542 if(forwardord != 0 || (iForwardApiLength == 1 && *forwardapi == '0')) {
1543 exportaddr = WinDll->getApi(forwardord);
1544 }
1545 else exportaddr = WinDll->getApi(forwardapi);
1546
1547 if(apiname) {
1548 dprintf((LOG, "address 0x%x %s @%d (0x%08x->0x%08x) forwarder %s.%s", virtaddr - originalBaseAddress, apiname, ordinal, virtaddr, exportaddr, forwarddll, forwardapi));
1549 }
1550 else {
1551 dprintf((LOG, "address 0x%x @%d (0x%08x->0x%08x) forwarder %s.%s", virtaddr - originalBaseAddress, ordinal, virtaddr, exportaddr, forwarddll, forwardapi));
1552 }
1553 return (exportaddr != 0);
1554}
1555//******************************************************************************
1556//******************************************************************************
1557Win32DllBase *Win32PeLdrImage::loadDll(char *pszCurModule)
1558{
1559 Win32DllBase *WinDll = NULL;
1560 char modname[CCHMAXPATH];
1561
1562 strcpy(modname, pszCurModule);
1563
1564 //rename dll if necessary (i.e. OLE32 -> OLE32OS2)
1565 Win32DllBase::renameDll(modname);
1566
1567 char szModName2[CCHMAXPATH];
1568 strcpy(szModName2, modname);
1569 if (!Win32ImageBase::findDll(szModName2, modname, sizeof(modname)))
1570 {
1571 dprintf((LOG, "Module %s not found!", modname));
1572 sprintf(szErrorModule, "%s", modname);
1573 errorState = 2;
1574 return NULL;
1575 }
1576
1577 if(isPEImage(modname, NULL, NULL) != ERROR_SUCCESS_W)
1578 {//LX image, so let OS/2 do all the work for us
1579 APIRET rc;
1580 char szModuleFailure[CCHMAXPATH] = "";
1581 ULONG hInstanceNewDll;
1582
1583 rc = DosLoadModule(szModuleFailure, sizeof(szModuleFailure), modname, (HMODULE *)&hInstanceNewDll);
1584 if(rc) {
1585 dprintf((LOG, "DosLoadModule returned %X for %s", rc, szModuleFailure));
1586 sprintf(szErrorModule, "%s", szModuleFailure);
1587 errorState = rc;
1588 return NULL;
1589 }
1590 /* bird 2003-03-30: search pe2lx dlls too! */
1591 WinDll = Win32DllBase::findModuleByOS2Handle(hInstanceNewDll);
1592 if (WinDll == NULL) {//shouldn't happen!
1593 dprintf((LOG, "Just loaded the dll, but can't find it anywhere?!!?"));
1594 errorState = ERROR_INTERNAL;
1595 return NULL;
1596 }
1597 if (WinDll->isLxDll())
1598 {
1599 Win32LxDll *lxdll = (Win32LxDll *)WinDll;
1600 lxdll->setDllHandleOS2(hInstanceNewDll);
1601 if(lxdll->AddRef() == -1) {//-1 -> load failed (attachProcess)
1602 dprintf((LOG, "Dll %s refused to be loaded; aborting", modname));
1603 delete lxdll;
1604 errorState = ERROR_INTERNAL;
1605 return NULL;
1606 }
1607 WinDll = (Win32DllBase*)lxdll;
1608 }
1609 }
1610 else {
1611 Win32PeLdrDll *pedll;
1612
1613 pedll = new Win32PeLdrDll(modname, this);
1614 if(pedll == NULL) {
1615 dprintf((LOG, "pedll: Error allocating memory" ));
1616 errorState = ERROR_INTERNAL;
1617 return NULL;
1618 }
1619 dprintf((LOG, "**********************************************************************" ));
1620 dprintf((LOG, "********************** Loading Module *********************" ));
1621 dprintf((LOG, "**********************************************************************" ));
1622 if(pedll->init(0) != LDRERROR_SUCCESS) {
1623 dprintf((LOG, "Internal WinDll error ", pedll->getError() ));
1624 delete pedll;
1625 return NULL;
1626 }
1627#ifdef DEBUG
1628 pedll->AddRef(getModuleName());
1629#else
1630 pedll->AddRef();
1631#endif
1632 if(pedll->attachProcess() == FALSE) {
1633 dprintf((LOG, "attachProcess failed!" ));
1634 delete pedll;
1635 errorState = ERROR_INTERNAL;
1636 return NULL;
1637 }
1638 WinDll = (Win32DllBase*)pedll;
1639 }
1640
1641 dprintf((LOG, "**********************************************************************" ));
1642 dprintf((LOG, "********************** Finished Loading Module %s ", modname ));
1643 dprintf((LOG, "**********************************************************************" ));
1644
1645 return WinDll;
1646}
1647
1648//******************************************************************************
1649/** All initial processing of imports is done here
1650 * Should now detect most Borland styled files including the GifCon32.exe and
1651 * loader32 from SoftIce. (Stupid Borland!!!)
1652 *
1653 * knut [Jul 22 1998 2:44am]
1654 **/
1655//******************************************************************************
1656BOOL Win32PeLdrImage::processImports()
1657{
1658 PIMAGE_IMPORT_DESCRIPTOR pID;
1659 IMAGE_SECTION_HEADER shID;
1660 IMAGE_SECTION_HEADER shExtra = {0};
1661 int i,j, nrPages;
1662 BOOL fBorland = 0;
1663 int cModules;
1664 char *pszModules;
1665 char *pszCurModule;
1666 char *pszTmp;
1667 ULONG *pulImport;
1668 ULONG ulCurFixup;
1669 int Size;
1670 Win32DllBase *WinDll;
1671 Win32ImageBase *WinImage = NULL;
1672 Section *section;
1673
1674 /* "algorithm:"
1675 * 1) get module names and store them
1676 * a) check dwRVAModuleName is within .idata seg - if not find section
1677 * 2) iterate thru functions of each module
1678 * a) check OriginalFirstThunk is not 0 and that it points to a RVA.
1679 * b) if not a) borland-styled PE-file - ARG!!!
1680 * check FirstThunk
1681 * c) check OriginalFirstThunk/FirstThunk ok RVAs and find right section
1682 * d) store ordinal/name import
1683 * 3) finished
1684 */
1685
1686 /* 1) get module names */
1687 pID = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryOffset(peview, IMAGE_DIRECTORY_ENTRY_IMPORT);
1688 if (pID == NULL)
1689 return TRUE;
1690 if (!GetSectionHdrByImageDir(peview, IMAGE_DIRECTORY_ENTRY_IMPORT, &shID))
1691 return TRUE;
1692
1693 //calc size of module list
1694 i = Size = cModules = 0;
1695 while (pID[i].Name != 0)
1696 {
1697 //test RVA inside ID-Section
1698 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1699 pszTmp = (char*)(pID[i].Name + (ULONG)peview);
1700 }
1701 else {
1702 //is the "Extra"-section already found or do we have to find it?
1703 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1704 if (!GetSectionHdrByRVA(peview, &shExtra, pID[i].Name))
1705 return FALSE;
1706 }
1707 pszTmp = (char*)(pID[i].Name + (ULONG)peview);
1708 }
1709 Size += strlen(pszTmp) + 1;
1710 i++;
1711 cModules++;
1712 }
1713
1714 pszModules = (char*)alloca(Size);
1715 if(pszModules == NULL) {
1716 DebugInt3();
1717 return FALSE;
1718 }
1719 j = 0;
1720 for (i = 0; i < cModules; i++)
1721 {
1722 //test RVA inside ID-Section
1723 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1724 pszTmp = (char*)(pID[i].Name + (ULONG)peview);
1725 }
1726 else {
1727 fBorland = TRUE;
1728 //is the "Extra"-section already found or do we have to find it?
1729 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1730 {
1731 if (GetSectionHdrByRVA(peview, &shExtra, pID[i].Name)) {
1732 return FALSE;
1733 }
1734 }
1735 pszTmp = (char*)(pID[i].Name + (ULONG)peview);
1736 }
1737
1738 int iTmpLength = strlen(pszTmp) + 1;
1739 memcpy(pszModules+j, pszTmp, iTmpLength);
1740 j += iTmpLength;
1741 }
1742 if (fBorland)
1743 dprintf((LOG, "Borland-styled PE-File." ));
1744
1745 //Store modules
1746 dprintf((LOG, "%d imported Modules: ", cModules ));
1747
1748 /* 2) functions */
1749 pszCurModule = pszModules;
1750 for (i = 0; i < cModules; i++)
1751 {
1752 dprintf((LOG, "Module %s", pszCurModule ));
1753 if(pID[i].ForwarderChain) {
1754 dprintf((LOG, "ForwarderChain: %x", pID[i].ForwarderChain));
1755 }
1756 // a) check that OriginalFirstThunk not is 0 and look for Borland-styled PE
1757 if (i == 0)
1758 {
1759 //heavy borland-style test - assume array of thunks is within that style does not change
1760 if((ULONG)pID[i].u.OriginalFirstThunk == 0 ||
1761 (ULONG)pID[i].u.OriginalFirstThunk < shID.VirtualAddress ||
1762 (ULONG)pID[i].u.OriginalFirstThunk >= shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData) ||
1763 (ULONG)pID[i].u.OriginalFirstThunk >= poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress &&
1764 (ULONG)pID[i].u.OriginalFirstThunk < sizeof(*pID)*cModules + poh->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1765 {
1766 fBorland = TRUE;
1767 }
1768 }
1769 //light borland-style test
1770 if (pID[i].u.OriginalFirstThunk == 0 || fBorland) {
1771 pulImport = (ULONG*)pID[i].FirstThunk;
1772 }
1773 else pulImport = (ULONG*)pID[i].u.OriginalFirstThunk;
1774
1775 // b) check if RVA ok
1776 if (!(pulImport > 0 && (ULONG)pulImport < poh->SizeOfImage)) {
1777 dprintf((LOG, "Invalid RVA %x", pulImport ));
1778 break;
1779 }
1780 // check section
1781 if ((ULONG)pulImport < shExtra.VirtualAddress || (ULONG)pulImport >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1782 {
1783 if (!GetSectionHdrByRVA(peview, &shExtra, (ULONG)pulImport))
1784 {
1785 dprintf((LOG, "warning: could not find section for Thunk RVA %x", pulImport ));
1786 break;
1787 }
1788 }
1789
1790 //Load dll if needed
1791 dprintf((LOG, "**********************************************************************" ));
1792 dprintf((LOG, "************** Import Module %s ", pszCurModule ));
1793 dprintf((LOG, "**********************************************************************" ));
1794 WinDll = Win32DllBase::findModule(pszCurModule);
1795
1796 if(WinDll == NULL)
1797 { //not found, so load it
1798 if (WinExe != NULL && WinExe->matchModName(pszCurModule)) {
1799 WinImage = (Win32ImageBase *)WinExe;
1800 }
1801 else {
1802
1803 WinDll = loadDll(pszCurModule);
1804 if(WinDll == NULL) {
1805 return FALSE;
1806 }
1807 }
1808 }
1809 else {
1810 WinDll->AddRef();
1811 dprintf((LOG, "Already found ", pszCurModule));
1812 }
1813 if(WinDll != NULL) {
1814 //add the dll we just loaded to dependency list for this image
1815 addDependency(WinDll);
1816
1817 //Make sure the dependency list is correct (already done
1818 //in the ctor of Win32DllBase, but for LX dlls the parent is
1819 //then set to NULL; so change it here again
1820 WinDll->setUnloadOrder(this);
1821 WinImage = (Win32ImageBase *)WinDll;
1822 }
1823 else
1824 if(WinImage == NULL) {
1825 dprintf((LOG, "Unable to load dll %s", pszCurModule ));
1826 return FALSE;
1827 }
1828
1829 pulImport = (PULONG)((ULONG)pulImport + (ULONG)peview);
1830 j = 0;
1831 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)peview;
1832
1833 section = findSectionByOS2Addr(ulCurFixup);
1834 if(section == NULL) {
1835 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1836 return FALSE;
1837 }
1838 //Read page from disk
1839 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1840 //Enable write access
1841 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1842 nrPages = 1;
1843
1844 while (pulImport[j] != 0) {
1845 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1846 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1847 StoreImportByOrd(WinImage, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1848 }
1849 else { //name
1850 //check
1851 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1852 {
1853 if (!GetSectionHdrByRVA(peview, &shExtra, pulImport[j]))
1854 {
1855 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1856 break;
1857 }
1858 }
1859 //KSO - Aug 6 1998 1:15am:this eases comparing...
1860 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)peview + 2);
1861 dprintf((LOG, "0x%08x Imported function %s (0x%08x)", ulCurFixup, pszFunctionName, WinImage->getApi(pszFunctionName)));
1862 StoreImportByName(WinImage, pszFunctionName, ulCurFixup);
1863 }
1864 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1865 j++;
1866 if((ulCurFixup & 0xfff) == 0) {
1867 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1868 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1869 nrPages++;
1870 }
1871 }
1872 //SvL: And restore original protection flags
1873 ulCurFixup = (ULONG)pID[i].FirstThunk + poh->ImageBase;
1874 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1875
1876 dprintf((LOG, "**********************************************************************" ));
1877 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1878 dprintf((LOG, "**********************************************************************" ));
1879
1880 pszCurModule += strlen(pszCurModule) + 1;
1881 }//for (i = 0; i < cModules; i++)
1882 return TRUE;
1883}
1884//******************************************************************************
1885//******************************************************************************
1886BOOL Win32PeLdrImage::insideModule(ULONG address)
1887{
1888 if((address >= realBaseAddress) && (address < realBaseAddress + imageSize)) {
1889 return TRUE;
1890 }
1891 return FALSE;
1892}
1893//******************************************************************************
1894//******************************************************************************
1895BOOL Win32PeLdrImage::insideModuleCode(ULONG address)
1896{
1897 Section *sect;
1898
1899 sect = findSectionByOS2Addr(address);
1900 if(sect && (sect->pageflags & PAG_EXECUTE)) {
1901 return TRUE;
1902 }
1903 return FALSE;
1904}
1905//******************************************************************************
1906//******************************************************************************
1907ULONG Win32PeLdrImage::getImageSize()
1908{
1909 return imageSize;
1910}
1911//******************************************************************************
1912//Returns required OS version for this image
1913//******************************************************************************
1914ULONG Win32PeLdrImage::getVersion()
1915{
1916 return (poh->MajorOperatingSystemVersion << 16) | poh->MinorOperatingSystemVersion;
1917}
1918//******************************************************************************
1919//******************************************************************************
1920ULONG WIN32API MissingApiOrd(char *parentimage, char *dllname, int ordinal)
1921{
1922 char message[256];
1923
1924 sprintf(message, "The application has called the non-existing api %s->%d (loaded by %s)", dllname, ordinal, parentimage);
1925 return MissingApi(message);
1926}
1927//******************************************************************************
1928//******************************************************************************
1929ULONG WIN32API MissingApiName(char *parentimage, char *dllname, char *functionname)
1930{
1931 char message[256];
1932
1933 sprintf(message, "The application has called the non-existing api %s->%s (loaded by %s)", dllname, functionname, parentimage);
1934 return MissingApi(message);
1935}
1936//******************************************************************************
1937//******************************************************************************
1938ULONG WIN32API MissingApi(char *message)
1939{
1940 static BOOL fIgnore = FALSE;
1941 int r;
1942
1943 dprintf((LOG, "Missing api called!\n"));
1944 if(fIgnore)
1945 return(0);
1946
1947 do {
1948 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, message,
1949 "Internal Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
1950 }
1951 while(r == MBID_RETRY); //giggle
1952
1953 if( r != MBID_IGNORE )
1954 ExitProcess(987);
1955
1956 fIgnore = TRUE;
1957 return(0);
1958}
1959/******************************************************************************/
1960/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.