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

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

Allow all sections to be accessed when loading an executable/dll with LOAD_LIBRARY_AS_DATAFILE

File size: 77.8 KB
Line 
1/* $Id: winimagepeldr.cpp,v 1.93 2001-12-20 15:08: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 *
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 *dllname, int ordinal);
79ULONG WIN32API MissingApiName(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_PUSHORDINAL 1
1281#define MISSINGOFFSET_PUSHNAME 1
1282#define MISSINGOFFSET_PUSHDLLNAME 6
1283#define MISSINGOFFSET_FUNCTION 11
1284
1285char missingapicode[18] = {
1286//push dllname
1287 0x68, 0x00, 0x00, 0x00, 0x00,
1288//push ordinal/name
1289 0x68, 0x00, 0x00, 0x00, 0x00,
1290//mov ecx, MissingApiOrd/Name
1291 0xB9, 0x99, 0x99, 0x99, 0x99,
1292//call ecx
1293 0xFF, 0xD1,
1294//ret
1295 0xC3};
1296
1297//******************************************************************************
1298void Win32PeLdrImage::StoreImportByOrd(Win32ImageBase *WinImage, ULONG ordinal, ULONG impaddr)
1299{
1300 ULONG *import;
1301 ULONG apiaddr;
1302
1303 import = (ULONG *)impaddr;
1304 apiaddr = WinImage->getApi(ordinal);
1305 if(apiaddr == 0)
1306 {
1307 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%u not found\n",
1308 WinImage->getModuleName(),
1309 ordinal));
1310
1311 dprintf((LOG, "--->>> NOT FOUND!" ));
1312 char *code = (char *)_cmalloc(sizeof(missingapicode));
1313
1314 memcpy(code, missingapicode, sizeof(missingapicode));
1315 *(DWORD *)&code[MISSINGOFFSET_PUSHDLLNAME] = (DWORD)WinImage->getModuleName();
1316 *(DWORD *)&code[MISSINGOFFSET_PUSHORDINAL] = ordinal;
1317 *(DWORD *)&code[MISSINGOFFSET_FUNCTION] = (DWORD)MissingApiOrd;
1318 *import = (ULONG)code;
1319 }
1320 else *import = apiaddr;
1321}
1322//******************************************************************************
1323//******************************************************************************
1324void Win32PeLdrImage::StoreImportByName(Win32ImageBase *WinImage, char *impname, ULONG impaddr)
1325{
1326 ULONG *import;
1327 ULONG apiaddr;
1328
1329 import = (ULONG *)impaddr;
1330 apiaddr = WinImage->getApi(impname);
1331 if(apiaddr == 0)
1332 {
1333 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%s not found\n",
1334 WinImage->getModuleName(),
1335 impname));
1336
1337 dprintf((LOG, "--->>> NOT FOUND!" ));
1338
1339 char *code = (char *)_cmalloc(sizeof(missingapicode));
1340
1341 memcpy(code, missingapicode, sizeof(missingapicode));
1342 *(DWORD *)&code[MISSINGOFFSET_PUSHDLLNAME] = (DWORD)WinImage->getModuleName();
1343 *(DWORD *)&code[MISSINGOFFSET_PUSHNAME] = (DWORD)impname;
1344 *(DWORD *)&code[MISSINGOFFSET_FUNCTION] = (DWORD)MissingApiName;
1345 *import = (ULONG)code;
1346 }
1347 else *import = apiaddr;
1348}
1349//******************************************************************************
1350//******************************************************************************
1351BOOL Win32PeLdrImage::processExports(char *win32file)
1352{
1353 IMAGE_SECTION_HEADER sh;
1354 PIMAGE_EXPORT_DIRECTORY ped;
1355 ULONG *ptrNames, *ptrAddress;
1356 USHORT *ptrOrd;
1357 BOOL fForwarder;
1358 int i;
1359
1360 /* get section header and pointer to data directory for .edata section */
1361 if((ped = (PIMAGE_EXPORT_DIRECTORY)ImageDirectoryOffset
1362 (win32file, IMAGE_DIRECTORY_ENTRY_EXPORT)) != NULL &&
1363 GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_EXPORT, &sh) ) {
1364
1365 dprintf((LOG, "Exported Functions: " ));
1366 ptrOrd = (USHORT *)((ULONG)ped->AddressOfNameOrdinals +
1367 (ULONG)win32file);
1368 ptrNames = (ULONG *)((ULONG)ped->AddressOfNames +
1369 (ULONG)win32file);
1370 ptrAddress = (ULONG *)((ULONG)ped->AddressOfFunctions +
1371 (ULONG)win32file);
1372 nrOrdExports = ped->NumberOfFunctions;
1373 nrNameExports = ped->NumberOfNames;
1374
1375 int ord, RVAExport;
1376 char *name;
1377 for(i=0;i<ped->NumberOfNames;i++)
1378 {
1379 fForwarder = FALSE;
1380 ord = ptrOrd[i] + ped->Base;
1381 name = (char *)((ULONG)ptrNames[i] + (ULONG)win32file);
1382 RVAExport = ptrAddress[ptrOrd[i]];
1383
1384 /* forwarder? ulRVA within export directory. */
1385 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1386 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1387 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1388 {
1389 fForwarder = AddForwarder(oh.ImageBase + RVAExport, name, ord);
1390 }
1391 if(!fForwarder) {
1392 //points to code (virtual address relative to oh.ImageBase
1393 AddNameExport(oh.ImageBase + RVAExport, name, ord);
1394 dprintf((LOG, "address 0x%x %s @%d (0x%08x)", RVAExport, name, ord, realBaseAddress + RVAExport));
1395 }
1396 }
1397 for(i=0;i<max(ped->NumberOfNames,ped->NumberOfFunctions);i++)
1398 {
1399 fForwarder = FALSE;
1400 ord = ped->Base + i; //Correct??
1401 RVAExport = ptrAddress[i];
1402 /* forwarder? ulRVA within export directory. */
1403 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1404 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1405 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1406 {
1407 fForwarder = AddForwarder(oh.ImageBase + RVAExport, NULL, ord);
1408 }
1409 if(!fForwarder && RVAExport) {
1410 //points to code (virtual address relative to oh.ImageBase
1411 dprintf((LOG, "ord %d at 0x%08x (0x%08x)", ord, RVAExport, realBaseAddress + RVAExport));
1412 AddOrdExport(oh.ImageBase + RVAExport, ord);
1413 }
1414 }
1415 }
1416
1417 return(TRUE);
1418}
1419//******************************************************************************
1420//******************************************************************************
1421void Win32PeLdrImage::AddNameExport(ULONG virtaddr, char *apiname, ULONG ordinal, BOOL fAbsoluteAddress)
1422{
1423 ULONG nsize;
1424 int iApiNameLength = strlen(apiname);
1425
1426 if(nameexports == NULL) {
1427 // think of a maximum of bytes per export name,
1428 // verify if this is true for MFC-DLLs, etc.
1429 nameExportSize = nrNameExports * (sizeof(NameExport) + 32);
1430
1431 nameexports = (NameExport *)malloc(nameExportSize);
1432 curnameexport = nameexports;
1433 }
1434 nsize = (ULONG)curnameexport - (ULONG)nameexports;
1435 if(nsize + sizeof(NameExport) + iApiNameLength > nameExportSize) {
1436 nameExportSize += 4096;
1437 char *tmp = (char *)nameexports;
1438 nameexports = (NameExport *)malloc(nameExportSize);
1439 memcpy(nameexports, tmp, nsize);
1440 curnameexport = (NameExport *)((ULONG)nameexports + nsize);
1441 free(tmp);
1442 }
1443 if(fAbsoluteAddress) {//forwarders use absolute address
1444 curnameexport->virtaddr = virtaddr;
1445 }
1446 else curnameexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1447 curnameexport->ordinal = ordinal;
1448 *(ULONG *)curnameexport->name = 0;
1449
1450 curnameexport->nlength = iApiNameLength + 1;
1451 memcpy(curnameexport->name, apiname, curnameexport->nlength);
1452
1453 if(curnameexport->nlength < sizeof(curnameexport->name))
1454 curnameexport->nlength = sizeof(curnameexport->name);
1455
1456 curnameexport = (NameExport *)((ULONG)curnameexport->name + curnameexport->nlength);
1457}
1458//******************************************************************************
1459//******************************************************************************
1460void Win32PeLdrImage::AddOrdExport(ULONG virtaddr, ULONG ordinal, BOOL fAbsoluteAddress)
1461{
1462 if(ordexports == NULL) {
1463 ordexports = (OrdExport *)malloc(nrOrdExports * sizeof(OrdExport));
1464 curordexport = ordexports;
1465 }
1466 if(fAbsoluteAddress) {//forwarders use absolute address
1467 curordexport->virtaddr = virtaddr;
1468 }
1469 else curordexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1470
1471 curordexport->ordinal = ordinal;
1472 curordexport++;
1473 nrOrdExportsRegistered++;
1474}
1475//******************************************************************************
1476//******************************************************************************
1477BOOL Win32PeLdrImage::AddForwarder(ULONG virtaddr, char *apiname, ULONG ordinal)
1478{
1479 char *forward = (char *)(realBaseAddress + (virtaddr - oh.ImageBase));
1480 char *forwarddll, *forwardapi;
1481 Win32DllBase *WinDll;
1482 DWORD exportaddr;
1483 int forwardord;
1484 int iForwardDllLength = strlen(forward);
1485 int iForwardApiLength;
1486
1487 if(iForwardDllLength == 0)
1488 return FALSE;
1489
1490 forwarddll = (char*)alloca(iForwardDllLength);
1491 if(forwarddll == NULL) {
1492 DebugInt3();
1493 return FALSE;
1494 }
1495 memcpy(forwarddll, forward, iForwardDllLength + 1);
1496
1497 forwardapi = strchr(forwarddll, '.');
1498 if(forwardapi == NULL) {
1499 return FALSE;
1500 }
1501 *forwardapi++ = 0;
1502 iForwardApiLength = strlen(forwardapi);
1503 if(iForwardApiLength == 0) {
1504 return FALSE;
1505 }
1506 WinDll = Win32DllBase::findModule(forwarddll);
1507 if(WinDll == NULL) {
1508 WinDll = loadDll(forwarddll);
1509 if(WinDll == NULL) {
1510 dprintf((LOG, "ERROR: couldn't find forwarder %s.%s", forwarddll, forwardapi));
1511 return FALSE;
1512 }
1513 }
1514 //check if name or ordinal forwarder
1515 forwardord = 0;
1516 if(*forwardapi >= '0' && *forwardapi <= '9') {
1517 forwardord = atoi(forwardapi);
1518 }
1519 if(forwardord != 0 || (iForwardApiLength == 1 && *forwardapi == '0')) {
1520 exportaddr = WinDll->getApi(forwardord);
1521 }
1522 else exportaddr = WinDll->getApi(forwardapi);
1523
1524 if(apiname) {
1525 dprintf((LOG, "address 0x%x %s @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, apiname, ordinal, virtaddr, forwarddll, forwardapi));
1526 AddNameExport(exportaddr, apiname, ordinal, TRUE);
1527 }
1528 else {
1529 dprintf((LOG, "address 0x%x @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, ordinal, virtaddr, forwarddll, forwardapi));
1530 AddOrdExport(exportaddr, ordinal, TRUE);
1531 }
1532 return TRUE;
1533}
1534//******************************************************************************
1535//******************************************************************************
1536Win32DllBase *Win32PeLdrImage::loadDll(char *pszCurModule)
1537{
1538 Win32DllBase *WinDll = NULL;
1539 char modname[CCHMAXPATH];
1540
1541 strcpy(modname, pszCurModule);
1542
1543 //rename dll if necessary (i.e. OLE32 -> OLE32OS2)
1544 Win32DllBase::renameDll(modname);
1545
1546 char szModName2[CCHMAXPATH];
1547 strcpy(szModName2, modname);
1548 if (!Win32ImageBase::findDll(szModName2, modname, sizeof(modname)))
1549 {
1550 dprintf((LOG, "Module %s not found!", modname));
1551 sprintf(szErrorModule, "%s", modname);
1552 errorState = 2;
1553 return NULL;
1554 }
1555
1556 if(isPEImage(modname, NULL, NULL) != ERROR_SUCCESS_W)
1557 {//LX image, so let OS/2 do all the work for us
1558 APIRET rc;
1559 char szModuleFailure[CCHMAXPATH] = "";
1560 ULONG hInstanceNewDll;
1561 Win32LxDll *lxdll;
1562
1563 char *dot = strchr(modname, '.');
1564 if(dot == NULL) {
1565 strcat(modname, DLL_EXTENSION);
1566 }
1567 rc = DosLoadModule(szModuleFailure, sizeof(szModuleFailure), modname, (HMODULE *)&hInstanceNewDll);
1568 if(rc) {
1569 dprintf((LOG, "DosLoadModule returned %X for %s", rc, szModuleFailure));
1570 sprintf(szErrorModule, "%s", szModuleFailure);
1571 errorState = rc;
1572 return NULL;
1573 }
1574 lxdll = Win32LxDll::findModuleByOS2Handle(hInstanceNewDll);
1575 if(lxdll == NULL) {//shouldn't happen!
1576 dprintf((LOG, "Just loaded the dll, but can't find it anywhere?!!?"));
1577 errorState = ERROR_INTERNAL;
1578 return NULL;
1579 }
1580 lxdll->setDllHandleOS2(hInstanceNewDll);
1581 if(lxdll->AddRef() == -1) {//-1 -> load failed (attachProcess)
1582 dprintf((LOG, "Dll %s refused to be loaded; aborting", modname));
1583 delete lxdll;
1584 errorState = ERROR_INTERNAL;
1585 return NULL;
1586 }
1587 WinDll = (Win32DllBase*)lxdll;
1588 }
1589 else {
1590 Win32PeLdrDll *pedll;
1591
1592 pedll = new Win32PeLdrDll(modname, this);
1593 if(pedll == NULL) {
1594 dprintf((LOG, "pedll: Error allocating memory" ));
1595 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szMemErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
1596 errorState = ERROR_INTERNAL;
1597 return NULL;
1598 }
1599 dprintf((LOG, "**********************************************************************" ));
1600 dprintf((LOG, "********************** Loading Module *********************" ));
1601 dprintf((LOG, "**********************************************************************" ));
1602 if(pedll->init(0) == FALSE) {
1603 dprintf((LOG, "Internal WinDll error ", pedll->getError() ));
1604 delete pedll;
1605 return NULL;
1606 }
1607#ifdef DEBUG
1608 pedll->AddRef(getModuleName());
1609#else
1610 pedll->AddRef();
1611#endif
1612 if(pedll->attachProcess() == FALSE) {
1613 dprintf((LOG, "attachProcess failed!" ));
1614 delete pedll;
1615 errorState = ERROR_INTERNAL;
1616 return NULL;
1617 }
1618 WinDll = (Win32DllBase*)pedll;
1619 }
1620
1621 dprintf((LOG, "**********************************************************************" ));
1622 dprintf((LOG, "********************** Finished Loading Module %s ", modname ));
1623 dprintf((LOG, "**********************************************************************" ));
1624
1625 return WinDll;
1626}
1627
1628//******************************************************************************
1629/** All initial processing of imports is done here
1630 * Should now detect most Borland styled files including the GifCon32.exe and
1631 * loader32 from SoftIce. (Stupid Borland!!!)
1632 *
1633 * knut [Jul 22 1998 2:44am]
1634 **/
1635//******************************************************************************
1636BOOL Win32PeLdrImage::processImports(char *win32file)
1637{
1638 PIMAGE_IMPORT_DESCRIPTOR pID;
1639 IMAGE_SECTION_HEADER shID;
1640 IMAGE_SECTION_HEADER shExtra = {0};
1641 PIMAGE_OPTIONAL_HEADER pOH;
1642 int i,j, nrPages;
1643 BOOL fBorland = 0;
1644 int cModules;
1645 char *pszModules;
1646 char *pszCurModule;
1647 char *pszTmp;
1648 ULONG *pulImport;
1649 ULONG ulCurFixup;
1650 int Size;
1651 Win32DllBase *WinDll;
1652 Win32ImageBase *WinImage = NULL;
1653 Section *section;
1654
1655 /* "algorithm:"
1656 * 1) get module names and store them
1657 * a) check dwRVAModuleName is within .idata seg - if not find section
1658 * 2) iterate thru functions of each module
1659 * a) check OriginalFirstThunk is not 0 and that it points to a RVA.
1660 * b) if not a) borland-styled PE-file - ARG!!!
1661 * check FirstThunk
1662 * c) check OriginalFirstThunk/FirstThunk ok RVAs and find right section
1663 * d) store ordinal/name import
1664 * 3) finished
1665 */
1666
1667 /* 1) get module names */
1668 pID = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT);
1669 if (pID == NULL)
1670 return TRUE;
1671 if (!GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT, &shID))
1672 return TRUE;
1673
1674 //calc size of module list
1675 i = Size = cModules = 0;
1676 while (pID[i].Name != 0)
1677 {
1678 //test RVA inside ID-Section
1679 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1680 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1681 }
1682 else {
1683 //is the "Extra"-section already found or do we have to find it?
1684 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1685 if (!GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name))
1686 return FALSE;
1687 }
1688 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1689 }
1690 Size += strlen(pszTmp) + 1;
1691 i++;
1692 cModules++;
1693 }
1694
1695 pszModules = (char*)alloca(Size);
1696 if(pszModules == NULL) {
1697 DebugInt3();
1698 return FALSE;
1699 }
1700 j = 0;
1701 for (i = 0; i < cModules; i++)
1702 {
1703 //test RVA inside ID-Section
1704 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1705 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1706 }
1707 else {
1708 fBorland = TRUE;
1709 //is the "Extra"-section already found or do we have to find it?
1710 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1711 {
1712 if (GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name)) {
1713 return FALSE;
1714 }
1715 }
1716 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1717 }
1718
1719 int iTmpLength = strlen(pszTmp) + 1;
1720 memcpy(pszModules+j, pszTmp, iTmpLength);
1721 j += iTmpLength;
1722 }
1723 if (fBorland)
1724 dprintf((LOG, "Borland-styled PE-File." ));
1725
1726 //Store modules
1727 dprintf((LOG, "%d imported Modules: ", cModules ));
1728
1729 /* 2) functions */
1730 pszCurModule = pszModules;
1731 pOH = (PIMAGE_OPTIONAL_HEADER)OPTHEADEROFF(win32file);
1732 for (i = 0; i < cModules; i++)
1733 {
1734 dprintf((LOG, "Module %s", pszCurModule ));
1735 if(pID[i].ForwarderChain) {
1736 dprintf((LOG, "ForwarderChain: %x", pID[i].ForwarderChain));
1737 }
1738 // a) check that OriginalFirstThunk not is 0 and look for Borland-styled PE
1739 if (i == 0)
1740 {
1741 //heavy borland-style test - assume array of thunks is within that style does not change
1742 if((ULONG)pID[i].u.OriginalFirstThunk == 0 ||
1743 (ULONG)pID[i].u.OriginalFirstThunk < shID.VirtualAddress ||
1744 (ULONG)pID[i].u.OriginalFirstThunk >= shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData) ||
1745 (ULONG)pID[i].u.OriginalFirstThunk >= pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress &&
1746 (ULONG)pID[i].u.OriginalFirstThunk < sizeof(*pID)*cModules + pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1747 {
1748 fBorland = TRUE;
1749 }
1750 }
1751 //light borland-style test
1752 if (pID[i].u.OriginalFirstThunk == 0 || fBorland) {
1753 pulImport = (ULONG*)pID[i].FirstThunk;
1754 }
1755 else pulImport = (ULONG*)pID[i].u.OriginalFirstThunk;
1756
1757 // b) check if RVA ok
1758 if (!(pulImport > 0 && (ULONG)pulImport < pOH->SizeOfImage)) {
1759 dprintf((LOG, "Invalid RVA %x", pulImport ));
1760 break;
1761 }
1762 // check section
1763 if ((ULONG)pulImport < shExtra.VirtualAddress || (ULONG)pulImport >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1764 {
1765 if (!GetSectionHdrByRVA(win32file, &shExtra, (ULONG)pulImport))
1766 {
1767 dprintf((LOG, "warning: could not find section for Thunk RVA %x", pulImport ));
1768 break;
1769 }
1770 }
1771
1772 //Load dll if needed
1773 dprintf((LOG, "**********************************************************************" ));
1774 dprintf((LOG, "************** Import Module %s ", pszCurModule ));
1775 dprintf((LOG, "**********************************************************************" ));
1776 WinDll = Win32DllBase::findModule(pszCurModule);
1777
1778 if(WinDll == NULL)
1779 { //not found, so load it
1780 if (WinExe != NULL && WinExe->matchModName(pszCurModule)) {
1781 WinImage = (Win32ImageBase *)WinExe;
1782 }
1783 else {
1784 WinDll = loadDll(pszCurModule);
1785 if(WinDll == NULL) {
1786 return FALSE;
1787 }
1788 }
1789 }
1790 else {
1791 WinDll->AddRef();
1792 dprintf((LOG, "Already found ", pszCurModule));
1793 }
1794 if(WinDll != NULL) {
1795 //add the dll we just loaded to dependency list for this image
1796 addDependency(WinDll);
1797
1798 //Make sure the dependency list is correct (already done
1799 //in the ctor of Win32DllBase, but for LX dlls the parent is
1800 //then set to NULL; so change it here again
1801 WinDll->setUnloadOrder(this);
1802 WinImage = (Win32ImageBase *)WinDll;
1803 }
1804 else
1805 if(WinImage == NULL) {
1806 dprintf((LOG, "Unable to load dll %s", pszCurModule ));
1807 return FALSE;
1808 }
1809
1810 pulImport = (PULONG)((ULONG)pulImport + (ULONG)win32file);
1811 j = 0;
1812 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)win32file;
1813
1814 section = findSectionByOS2Addr(ulCurFixup);
1815 if(section == NULL) {
1816 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1817 return FALSE;
1818 }
1819 //Read page from disk
1820 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1821 //Enable write access
1822 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1823 nrPages = 1;
1824
1825 while (pulImport[j] != 0) {
1826 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1827 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1828 StoreImportByOrd(WinImage, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1829 }
1830 else { //name
1831 //check
1832 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1833 {
1834 if (!GetSectionHdrByRVA(win32file, &shExtra, pulImport[j]))
1835 {
1836 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1837 break;
1838 }
1839 }
1840 //KSO - Aug 6 1998 1:15am:this eases comparing...
1841 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)win32file + 2);
1842 dprintf((LOG, "0x%08x Imported function %s (0x%08x)", ulCurFixup, pszFunctionName, WinImage->getApi(pszFunctionName)));
1843 StoreImportByName(WinImage, pszFunctionName, ulCurFixup);
1844 }
1845 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1846 j++;
1847 if((ulCurFixup & 0xfff) == 0) {
1848 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1849 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1850 nrPages++;
1851 }
1852 }
1853 //SvL: And restore original protection flags
1854 ulCurFixup = (ULONG)pID[i].FirstThunk + pOH->ImageBase;
1855 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1856
1857 dprintf((LOG, "**********************************************************************" ));
1858 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1859 dprintf((LOG, "**********************************************************************" ));
1860
1861 pszCurModule += strlen(pszCurModule) + 1;
1862 }//for (i = 0; i < cModules; i++)
1863 return TRUE;
1864}
1865//******************************************************************************
1866//******************************************************************************
1867BOOL Win32PeLdrImage::insideModule(ULONG address)
1868{
1869 if((address >= realBaseAddress) && (address < realBaseAddress + imageSize)) {
1870 return TRUE;
1871 }
1872 return FALSE;
1873}
1874//******************************************************************************
1875//******************************************************************************
1876BOOL Win32PeLdrImage::insideModuleCode(ULONG address)
1877{
1878 Section *sect;
1879
1880 sect = findSectionByOS2Addr(address);
1881 if(sect && (sect->pageflags & PAG_EXECUTE)) {
1882 return TRUE;
1883 }
1884 return FALSE;
1885}
1886//******************************************************************************
1887//******************************************************************************
1888ULONG Win32PeLdrImage::getImageSize()
1889{
1890 return imageSize;
1891}
1892//******************************************************************************
1893//******************************************************************************
1894ULONG Win32PeLdrImage::getApi(char *name)
1895{
1896 ULONG apiaddr, i, apilen;
1897 char *apiname;
1898 char tmp[4];
1899 NameExport *curexport;
1900 ULONG ulAPIOrdinal; /* api requested by ordinal */
1901
1902 apilen = strlen(name) + 1;
1903 if(apilen < 4)
1904 {
1905 *(ULONG *)tmp = 0;
1906 strcpy(tmp, name);
1907 apiname = tmp;
1908 apilen = 4;
1909 }
1910 else apiname = name;
1911
1912 curexport = nameexports;
1913 for(i=0; i<nrNameExports; i++)
1914 {
1915 if(apilen == curexport->nlength &&
1916 *(ULONG *)curexport->name == *(ULONG *)apiname)
1917 {
1918 if(strcmp(curexport->name, apiname) == 0)
1919 return(curexport->virtaddr);
1920 }
1921 curexport = (NameExport *)((ULONG)curexport->name + curexport->nlength);
1922 }
1923 return(0);
1924}
1925//******************************************************************************
1926//******************************************************************************
1927ULONG Win32PeLdrImage::getApi(int ordinal)
1928{
1929 ULONG apiaddr, i;
1930 OrdExport *curexport;
1931 NameExport *nexport;
1932
1933 curexport = ordexports;
1934
1935 /* accelerated resolving of ordinal exports
1936 * is based on the assumption the ordinal export
1937 * table is always sorted ascending.
1938 *
1939 * When the step size is too small, we continue
1940 * with the linear search.
1941 */
1942
1943 // start in the middle of the tree
1944 i = nrOrdExportsRegistered >> 1;
1945 int iStep = i;
1946
1947 for(;;)
1948 {
1949 int iThisExport = curexport[i].ordinal;
1950
1951 iStep >>= 1; // next step will be narrower
1952
1953 if (iThisExport < ordinal)
1954 i += min(iStep, (ordinal-iThisExport)); // move farther down the list
1955 else
1956 if (iThisExport == ordinal) // found the export?
1957 return curexport[i].virtaddr;
1958 else
1959 i -= min(iStep, (iThisExport-ordinal)); // move farther up the list
1960
1961 // if we're in the direct neighbourhood search linearly
1962 if (iStep <= 1)
1963 {
1964 // decide if we're to search backward or forward
1965 if (ordinal > curexport[i].ordinal)
1966 {
1967 // As a certain number of exports are 0 at the end
1968 // of the array, this case will hit fairly often.
1969 // the last comparison will send the loop off into the
1970 // wrong direction!
1971#ifdef DEBUG
1972 if (curexport[i].ordinal == 0)
1973 {
1974 DebugInt3();
1975 }
1976#endif
1977
1978 for (;i<nrOrdExports;i++) // scan forward
1979 {
1980 iThisExport = curexport[i].ordinal;
1981 if(iThisExport == ordinal)
1982 return(curexport[i].virtaddr);
1983 else
1984 if (iThisExport > ordinal)
1985 {
1986 // Oops, cannot find the ordinal in the sorted list
1987 break;
1988 }
1989 }
1990 }
1991 else
1992 {
1993 for (;i>=0;i--) // scan backward
1994 {
1995 iThisExport = curexport[i].ordinal;
1996 if(curexport[i].ordinal == ordinal)
1997 return(curexport[i].virtaddr);
1998 else
1999 if (iThisExport < ordinal)
2000 // Oops, cannot find the ordinal in the sorted list
2001 break;
2002 }
2003 }
2004
2005 // not found yet.
2006 break;
2007 }
2008 }
2009
2010 //Name exports also contain an ordinal, so check this
2011 nexport = nameexports;
2012 for(i=0;i<nrNameExports;i++) {
2013 if(nexport->ordinal == ordinal)
2014 return(nexport->virtaddr);
2015
2016 nexport = (NameExport *)((ULONG)nexport->name + nexport->nlength);
2017 }
2018 return(0);
2019}
2020//******************************************************************************
2021//Returns required OS version for this image
2022//******************************************************************************
2023ULONG Win32PeLdrImage::getVersion()
2024{
2025 return (oh.MajorOperatingSystemVersion << 16) | oh.MinorOperatingSystemVersion;
2026}
2027//******************************************************************************
2028//******************************************************************************
2029ULONG WIN32API MissingApiOrd(char *dllname, int ordinal)
2030{
2031 char message[128];
2032
2033 sprintf(message, "The application has called the non-existing api %s->%d", dllname, ordinal);
2034 return MissingApi(message);
2035}
2036//******************************************************************************
2037//******************************************************************************
2038ULONG WIN32API MissingApiName(char *dllname, char *functionname)
2039{
2040 char message[128];
2041
2042 sprintf(message, "The application has called the non-existing api %s->%s", dllname, functionname);
2043 return MissingApi(message);
2044}
2045//******************************************************************************
2046//******************************************************************************
2047ULONG WIN32API MissingApi(char *message)
2048{
2049 static BOOL fIgnore = FALSE;
2050 int r;
2051
2052 dprintf((LOG, "Missing api called!\n"));
2053 if(fIgnore)
2054 return(0);
2055
2056 do {
2057 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, message,
2058 "Internal Odin Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
2059 }
2060 while(r == MBID_RETRY); //giggle
2061
2062 if( r != MBID_IGNORE )
2063 ExitProcess(987);
2064
2065 fIgnore = TRUE;
2066 return(0);
2067}
2068/******************************************************************************/
2069/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.