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

Last change on this file since 7670 was 7670, checked in by sandervl, 24 years ago

More information about about missing api

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