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

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

Unmap memory view when deleting PE dll object

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