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

Last change on this file since 9826 was 9826, checked in by sandervl, 23 years ago

updates

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