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

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

protect larger part of on demand page handler (DosEnterCritSec)

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