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

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

Image header page must be readonly + disabled high memory usage for heap

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