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

Last change on this file since 5914 was 5914, checked in by phaller, 24 years ago

.

File size: 74.6 KB
Line 
1/* $Id: winimagepeldr.cpp,v 1.84 2001-06-06 10:01:48 phaller 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, "Raw data size: %x", psh[i].SizeOfRawData ));
296 dprintf((LOG, "Virtual Address: %x", psh[i].VirtualAddress ));
297 dprintf((LOG, "Virtual Address Start:%x", psh[i].VirtualAddress+oh.ImageBase ));
298 dprintf((LOG, "Virtual Address End: %x", psh[i].VirtualAddress+oh.ImageBase+psh[i].Misc.VirtualSize ));
299 dprintf((LOG, "Virtual Size: %x", psh[i].Misc.VirtualSize ));
300 dprintf((LOG, "Pointer to raw data: %x", psh[i].PointerToRawData ));
301 dprintf((LOG, "Section flags: %x\n\n", psh[i].Characteristics ));
302
303 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_BASERELOC))
304 {
305 dprintf((LOG, ".reloc" ));
306 addSection(SECTION_RELOC, psh[i].PointerToRawData,
307 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
308 psh[i].Misc.VirtualSize, psh[i].Characteristics);
309 continue;
310 }
311 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_EXPORT))
312 {
313 //SvL: Angus.exe has empty export section that's really an
314 // uninitialized data section
315 if(psh[i].SizeOfRawData) {
316 dprintf((LOG, ".edata" ));
317 addSection(SECTION_EXPORT, psh[i].PointerToRawData,
318 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
319 psh[i].Misc.VirtualSize, psh[i].Characteristics);
320 continue;
321 }
322 }
323 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_RESOURCE))
324 {
325 dprintf((LOG, ".rsrc" ));
326 addSection(SECTION_RESOURCE, psh[i].PointerToRawData,
327 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
328 psh[i].Misc.VirtualSize, psh[i].Characteristics);
329 continue;
330 }
331 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_TLS))
332 {
333 dprintf((LOG, "TLS section"));
334 tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_TLS);
335 if(tlsDir) {
336 addSection(SECTION_TLS, psh[i].PointerToRawData,
337 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
338 psh[i].Misc.VirtualSize, psh[i].Characteristics);
339 }
340 continue;
341 }
342 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_DEBUG))
343 {
344 dprintf((LOG, ".rdebug" ));
345 addSection(SECTION_DEBUG, psh[i].PointerToRawData,
346 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
347 psh[i].Misc.VirtualSize, psh[i].Characteristics);
348 continue;
349 }
350 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_IMPORT))
351 {
352 int type = SECTION_IMPORT;
353
354 dprintf((LOG, "Import Data Section" ));
355 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE) {
356 dprintf((LOG, "Also Code Section"));
357 type |= SECTION_CODE;
358 }
359 addSection(type, psh[i].PointerToRawData,
360 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
361 psh[i].Misc.VirtualSize, psh[i].Characteristics);
362 continue;
363 }
364
365 //KSO Sun 1998-08-09: Borland does not alway set the CODE flag for its "CODE" section
366 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE ||
367 (psh[i].Characteristics & IMAGE_SCN_MEM_EXECUTE &&
368 !(psh[i].Characteristics & (IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_CNT_INITIALIZED_DATA))) //KSO: make sure its not marked as a datasection
369 )
370 {
371 dprintf((LOG, "Code Section"));
372 addSection(SECTION_CODE, psh[i].PointerToRawData,
373 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
374 psh[i].Misc.VirtualSize, psh[i].Characteristics);
375 continue;
376 }
377 if(!(psh[i].Characteristics & IMAGE_SCN_MEM_WRITE)) { //read only data section
378 dprintf((LOG, "Read Only Data Section" ));
379 addSection(SECTION_READONLYDATA, psh[i].PointerToRawData,
380 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
381 psh[i].Misc.VirtualSize, psh[i].Characteristics);
382 continue;
383 }
384 if(psh[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
385 dprintf((LOG, "Uninitialized Data Section" ));
386 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
387 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
388 psh[i].Misc.VirtualSize, psh[i].Characteristics);
389 continue;
390 }
391 if(psh[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) {
392 dprintf((LOG, "Initialized Data Section" ));
393 addSection(SECTION_INITDATA, psh[i].PointerToRawData,
394 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
395 psh[i].Misc.VirtualSize, psh[i].Characteristics);
396 continue;
397 }
398 if(psh[i].Characteristics & (IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ)) {
399 dprintf((LOG, "Other Section, stored as read/write uninit data" ));
400 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
401 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
402 psh[i].Misc.VirtualSize, psh[i].Characteristics);
403 continue;
404 }
405 dprintf((LOG, "Unknown section" ));
406 goto failure;
407 }
408 }
409 }
410 else {
411 if(GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_RESOURCE, &sh))
412 {
413 dprintf((LOG, "*************************PE SECTIONS START**************************" ));
414 dprintf((LOG, "Raw data size: %x", sh.SizeOfRawData ));
415 dprintf((LOG, "Virtual Address: %x", sh.VirtualAddress ));
416 dprintf((LOG, "Virtual Address Start:%x", sh.VirtualAddress+oh.ImageBase ));
417 dprintf((LOG, "Virtual Address End: %x", sh.VirtualAddress+oh.ImageBase+sh.Misc.VirtualSize ));
418 dprintf((LOG, "Virtual Size: %x", sh.Misc.VirtualSize ));
419 dprintf((LOG, "Pointer to raw data: %x", sh.PointerToRawData ));
420 dprintf((LOG, "Section flags: %x\n\n", sh.Characteristics ));
421 addSection(SECTION_RESOURCE, sh.PointerToRawData,
422 sh.SizeOfRawData, sh.VirtualAddress + oh.ImageBase,
423 sh.Misc.VirtualSize, sh.Characteristics);
424 }
425 }
426 dprintf((LOG, "*************************PE SECTIONS END **************************" ));
427
428 imageSize += imageVirtBase - oh.ImageBase;
429 dprintf((LOG, "Total size of Image %x", imageSize ));
430 dprintf((LOG, "imageVirtBase %x", imageVirtBase ));
431 dprintf((LOG, "imageVirtEnd %x", imageVirtEnd ));
432
433 //In case there are any gaps between sections, adjust size
434 if(imageSize != imageVirtEnd - oh.ImageBase)
435 {
436 dprintf((LOG, "imageSize != imageVirtEnd - oh.ImageBase!" ));
437 imageSize = imageVirtEnd - oh.ImageBase;
438 }
439 if(imageSize < oh.SizeOfImage) {
440 imageSize = oh.SizeOfImage;
441 }
442
443 dprintf((LOG, "OS/2 base address %x", realBaseAddress ));
444 if(oh.AddressOfEntryPoint) {
445 entryPoint = realBaseAddress + oh.AddressOfEntryPoint;
446 }
447 else {
448 dprintf((LOG, "EntryPoint == NULL" ));
449 entryPoint = NULL;
450 }
451
452 //set memory protection flags
453 if(setMemFlags() == FALSE) {
454 dprintf((LOG, "Failed to set memory protection" ));
455 goto failure;
456 }
457
458 if(realBaseAddress != oh.ImageBase && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
459 pFixups = (PIMAGE_BASE_RELOCATION)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_BASERELOC);
460 dwFixupSize = ImageDirectorySize(win32file, IMAGE_DIRECTORY_ENTRY_BASERELOC);
461 commitPage((ULONG)pFixups, FALSE);
462 }
463
464 if(!(dwFlags & FLAG_PELDR_LOADASDATAFILE))
465 {
466 if(tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_TLS))
467 {
468 Section *sect;
469 BOOL fTLSFixups = FALSE;
470
471 sect = findSectionByAddr(tlsDir->StartAddressOfRawData);
472 //There might be fixups for the TLS structure, so search the sections
473 //by the OS/2 virtual address too
474 if(sect == NULL) {
475 sect = findSectionByOS2Addr(tlsDir->StartAddressOfRawData);
476 fTLSFixups = TRUE;
477 }
478
479 dprintf((LOG, "TLS Directory" ));
480 dprintf((LOG, "TLS Address of Index %x", tlsDir->AddressOfIndex ));
481 dprintf((LOG, "TLS Address of Callbacks %x", tlsDir->AddressOfCallBacks ));
482 dprintf((LOG, "TLS SizeOfZeroFill %x", tlsDir->SizeOfZeroFill ));
483 dprintf((LOG, "TLS Characteristics %x", tlsDir->Characteristics ));
484 if(sect == NULL) {
485 dprintf((LOG, "Couldn't find TLS section!!" ));
486 goto failure;
487 }
488 setTLSAddress((char *)sect->realvirtaddr);
489 setTLSInitSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData);
490 setTLSTotalSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData + tlsDir->SizeOfZeroFill);
491
492 fTLSFixups = FALSE;
493 sect = findSectionByAddr((ULONG)tlsDir->AddressOfIndex);
494 //There might be fixups for the TLS structure, so search the sections
495 //by the OS/2 virtual address too
496 if(sect == NULL) {
497 sect = findSectionByOS2Addr((ULONG)tlsDir->AddressOfIndex);
498 fTLSFixups = TRUE;
499 }
500 if(sect == NULL) {
501 dprintf((LOG, "Couldn't find TLS AddressOfIndex section!!" ));
502 goto failure;
503 }
504 if(fTLSFixups) {
505 setTLSIndexAddr((LPDWORD)tlsDir->AddressOfIndex); //no fixup required
506 }
507 else {//need to add a manual fixup
508 setTLSIndexAddr((LPDWORD)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfIndex - sect->virtaddr)));
509 }
510
511 if((ULONG)tlsDir->AddressOfCallBacks != 0)
512 {
513 fTLSFixups = FALSE;
514
515 sect = findSectionByAddr((ULONG)tlsDir->AddressOfCallBacks);
516 //There might be fixups for the TLS structure, so search the sections
517 //by the OS/2 virtual address too
518 if(sect == NULL) {
519 sect = findSectionByOS2Addr((ULONG)tlsDir->AddressOfIndex);
520 fTLSFixups = TRUE;
521 }
522 if(sect == NULL) {
523 dprintf((LOG, "Couldn't find TLS AddressOfCallBacks section!!" ));
524 goto failure;
525 }
526 if(fTLSFixups) {
527 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)tlsDir->AddressOfCallBacks); //no fixup required
528 }
529 else {//need to add a manual fixup
530 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfCallBacks - sect->virtaddr)));
531 }
532 //modify tls callback pointers for new image base address
533 int i = 0;
534 while(tlsCallBackAddr[i])
535 {
536 fTLSFixups = FALSE;
537
538 sect = findSectionByAddr((ULONG)tlsCallBackAddr[i]);
539 //There might be fixups for the TLS structure, so search the sections
540 //by the OS/2 virtual address too
541 if(sect == NULL) {
542 sect = findSectionByOS2Addr((ULONG)tlsCallBackAddr[i]);
543 fTLSFixups = TRUE;
544 }
545 if(sect == NULL) {
546 dprintf((LOG, "Couldn't find TLS callback section!!" ));
547 goto failure;
548 }
549 if(fTLSFixups) {
550 tlsCallBackAddr[i] = tlsCallBackAddr[i];
551 }
552 else tlsCallBackAddr[i] = (PIMAGE_TLS_CALLBACK)(realBaseAddress + ((ULONG)tlsCallBackAddr[i] - oh.ImageBase));
553 i++;
554 }
555 }
556 }
557
558#ifdef DEBUG
559 dprintf((LOG, "Image directories: "));
560 for (i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
561 {
562 char *pszName;
563
564 if(oh.DataDirectory[i].VirtualAddress && oh.DataDirectory[i].Size) {
565 switch (i)
566 {
567 case IMAGE_DIRECTORY_ENTRY_EXPORT: pszName = "Export Directory (IMAGE_DIRECTORY_ENTRY_EXPORT)"; break;
568 case IMAGE_DIRECTORY_ENTRY_IMPORT: pszName = "Import Directory (IMAGE_DIRECTORY_ENTRY_IMPORT)"; break;
569 case IMAGE_DIRECTORY_ENTRY_RESOURCE: pszName = "Resource Directory (IMAGE_DIRECTORY_ENTRY_RESOURCE)"; break;
570 case IMAGE_DIRECTORY_ENTRY_EXCEPTION: pszName = "Exception Directory (IMAGE_DIRECTORY_ENTRY_EXCEPTION)"; break;
571 case IMAGE_DIRECTORY_ENTRY_SECURITY: pszName = "Security Directory (IMAGE_DIRECTORY_ENTRY_SECURITY)"; break;
572 case IMAGE_DIRECTORY_ENTRY_BASERELOC: pszName = "Base Relocation Table (IMAGE_DIRECTORY_ENTRY_BASERELOC)"; break;
573 case IMAGE_DIRECTORY_ENTRY_DEBUG: pszName = "Debug Directory (IMAGE_DIRECTORY_ENTRY_DEBUG)"; break;
574 case IMAGE_DIRECTORY_ENTRY_COPYRIGHT: pszName = "Description String (IMAGE_DIRECTORY_ENTRY_COPYRIGHT)"; break;
575 case IMAGE_DIRECTORY_ENTRY_GLOBALPTR: pszName = "Machine Value (MIPS GP) (IMAGE_DIRECTORY_ENTRY_GLOBALPTR)"; break;
576 case IMAGE_DIRECTORY_ENTRY_TLS: pszName = "TLS Directory (IMAGE_DIRECTORY_ENTRY_TLS)"; break;
577 case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: pszName = "Load Configuration Directory (IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG)"; break;
578 case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT:pszName = "Bound Import Directory in headers (IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT)"; break;
579 case IMAGE_DIRECTORY_ENTRY_IAT: pszName = "Import Address Table (IMAGE_DIRECTORY_ENTRY_IAT)"; break;
580 default:
581 pszName = "unknown";
582 }
583 dprintf((LOG, "directory %s", pszName));
584 dprintf((LOG, " Address 0x%08x", oh.DataDirectory[i].VirtualAddress));
585 dprintf((LOG, " Size 0x%08x", oh.DataDirectory[i].Size));
586 }
587 }
588 dprintf((LOG, "\n\n"));
589#endif
590
591#ifdef COMMIT_ALL
592 for (i=0; i<nSections; i++) {
593 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
594 }
595#else
596 for (i=0; i<nSections; i++) {
597 switch(section[i].type)
598 {
599 case SECTION_IMPORT:
600 case SECTION_RELOC:
601 case SECTION_EXPORT:
602 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
603 break;
604 }
605 }
606#endif
607 if(processExports((char *)win32file) == FALSE) {
608 dprintf((LOG, "Failed to process exported apis" ));
609 goto failure;
610 }
611 }
612#ifdef COMMIT_ALL
613 else {
614 commitPage((ULONG)section[0].realvirtaddr, FALSE, COMPLETE_SECTION);
615 }
616#endif
617
618#ifndef COMMIT_ALL
619 if(entryPoint) {
620 //commit code at entrypoint, since we going to call it anyway
621 commitPage((ULONG)entryPoint, FALSE);
622 }
623#endif
624
625 //SvL: Use pointer to image header as module handle now. Some apps needs this
626 hinstance = (HINSTANCE)realBaseAddress;
627
628 //SvL: Set instance handle in process database structure
629 SetPDBInstance(hinstance);
630
631 //PH: get pResRootDir pointer correct first, since processImports may
632 // implicitly call functions depending on it.
633 if(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress && oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size)
634 {
635 //get offset in resource object of directory entry
636 pResRootDir = (PIMAGE_RESOURCE_DIRECTORY)(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress + realBaseAddress);
637 ulRVAResourceSection = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
638 }
639
640 //Allocate TLS index for this module
641 //Must do this before dlls are loaded for this module. Some apps assume
642 //they get TLS index 0 for their main executable
643 tlsAlloc();
644 tlsAttachThread(); //setup TLS (main thread)
645
646 if(!(dwFlags & (FLAG_PELDR_LOADASDATAFILE | FLAG_PELDR_SKIPIMPORTS)))
647 {
648 if(processImports((char *)win32file) == FALSE) {
649 dprintf((LOG, "Failed to process imports!" ));
650 goto failure;
651 }
652 }
653 return(TRUE);
654
655failure:
656 if(memmap) {
657 delete memmap;
658 memmap = NULL;
659 }
660 if(hFile) {
661 OSLibDosClose(hFile);
662 hFile = 0;
663 }
664 errorState = ERROR_INTERNAL;
665 return FALSE;
666}
667//******************************************************************************
668//******************************************************************************
669#define DOSREAD_IDEAL_SIZE 61440
670static inline APIRET _Optlink fastDosRead(HFILE hFile,
671 PVOID pAddress,
672 ULONG ulSize,
673 PULONG pulBytesRead)
674{
675 /* we better break the DosRead into multiple calls */
676 PBYTE p = (PBYTE)pAddress;
677 ULONG ulReadBytes;
678 APIRET rc;
679
680 *pulBytesRead = ulSize;
681
682 do
683 {
684 rc = DosRead(hFile,
685 p,
686 min(DOSREAD_IDEAL_SIZE, ulSize),
687 &ulReadBytes);
688 if (rc != NO_ERROR)
689 {
690 /* in case of errors bail out */
691 *pulBytesRead = 0;
692 return rc;
693 }
694
695 ulSize -= ulReadBytes;
696 p += ulReadBytes;
697 }
698 while (ulSize > 0);
699
700 return NO_ERROR;
701}
702
703//******************************************************************************
704// commitPage:
705// commits image page(s) when an access violation exception is received
706// (usually called from exception.cpp; also from other methods in this file)
707//
708// Parameters:
709// virtAddress - address of exception (rounded down to page boundary)
710// fWriteAccess - type of access violation (read or write)
711// fPageCmd - SINGLE_PAGE -> commit single page
712// SECTION_PAGES -> commit default nr of pages
713// COMPLETE_SECTION -> commit entire section
714//
715// Remarks:
716// DosEnterCritSec/DosExitCritSec is used to make sure the other threads in
717// the application can't touch the pages before they are loaded from disk and
718// fixups are applied.
719//
720// TODO:
721// SECTION_PAGES: - don't load pages starting at access violation address, but
722// a region surrounding it (e.g. -32k -> + 32k)
723// this will prevent many pagefaults when the app uses
724// pages with a lower addr.
725//
726//******************************************************************************
727BOOL Win32PeLdrImage::commitPage(ULONG virtAddress, BOOL fWriteAccess, int fPageCmd)
728{
729 Section *section;
730 ULONG offset, size, sectionsize, protflags, fileoffset, range, attr;
731 ULONG ulNewPos, ulRead, orgVirtAddress = virtAddress;
732 APIRET rc;
733
734 //Round down to nearest page boundary
735 virtAddress = virtAddress & ~0xFFF;
736
737 section = findSectionByOS2Addr(virtAddress);
738 if(section == NULL) {
739 section = findSectionByOS2Addr(orgVirtAddress);
740 if(section) {
741 virtAddress = orgVirtAddress;
742 }
743 }
744 if(section == NULL) {
745 size = 4096;
746 sectionsize = 4096;
747 protflags = PAG_READ|PAG_WRITE; //readonly?
748 section = findPreviousSectionByOS2Addr(virtAddress);
749 if(section == NULL) {//access to header
750 offset = 0;
751 fileoffset = virtAddress - realBaseAddress;
752 }
753 else {
754 offset = virtAddress - (section->realvirtaddr + section->virtualsize);
755 fileoffset = section->rawoffset + section->rawsize + offset;
756 }
757 }
758 else {
759 protflags = section->pageflags;
760 offset = virtAddress - section->realvirtaddr;
761 sectionsize = section->virtualsize - offset;
762
763 if(offset > section->rawsize || section->type == SECTION_UNINITDATA) {
764 //unintialized data (set to 0)
765 size = 0;
766 fileoffset = -1;
767 }
768 else {
769 size = section->rawsize-offset;
770 fileoffset = section->rawoffset + offset;
771 }
772 if(fWriteAccess & !(section->pageflags & PAG_WRITE)) {
773 dprintf((LOG, "Win32PeLdrImage::commitPage: No write access to 0%x!", virtAddress));
774 return FALSE;
775 }
776 }
777 //Check range of pages with the same attributes starting at virtAddress
778 //(some pages might already have been loaded)
779 range = sectionsize;
780 rc = DosQueryMem((PVOID)virtAddress, &range, &attr);
781 if(rc) {
782 dprintf((LOG, "Win32PeLdrImage::commitPage: DosQueryMem for %x returned %d", virtAddress, rc));
783 return FALSE;
784 }
785 if(attr & PAG_COMMIT) {
786 dprintf((LOG, "Win32PeLdrImage::commitPage: Memory at 0x%x already committed!", virtAddress));
787 return FALSE;
788 }
789
790 if(fPageCmd == SINGLE_PAGE) {
791 size = min(size, PAGE_SIZE);
792 sectionsize = min(sectionsize, PAGE_SIZE);
793 }
794 else
795 if(fPageCmd == SECTION_PAGES) {
796 size = min(size, DEFAULT_NR_PAGES*PAGE_SIZE);
797 sectionsize = min(sectionsize, DEFAULT_NR_PAGES*PAGE_SIZE);
798 }
799 //else complete section
800
801 size = min(size, range);
802 sectionsize = min(sectionsize, range);
803
804 if(fileoffset != -1) {
805 rc = DosEnterCritSec();
806 if(rc) {
807 dprintf((LOG, "DosEnterCritSec failed with rc %d", rc));
808 goto fail;
809 }
810 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
811 if(rc) {
812 DosExitCritSec();
813 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
814 goto fail;
815 }
816
817 if(DosSetFilePtr(hFile, fileoffset, FILE_BEGIN, &ulNewPos) == -1) {
818 DosExitCritSec();
819 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetFilePtr failed for 0x%x!", fileoffset));
820 goto fail;
821 }
822#if 1
823 // 2001-05-31 PH
824 // ensure DosRead() does not have to read more
825 // than 65535 bytes, otherwise split into two requests!
826 rc = fastDosRead(hFile, (PVOID)virtAddress, size, &ulRead);
827#else
828 rc = DosRead(hFile, (PVOID)virtAddress, size, &ulRead);
829#endif
830 if(rc) {
831 DosExitCritSec();
832 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed for 0x%x %x %x %x (rc=%d)!", virtAddress, size, ulRead, fileoffset, rc));
833 goto fail;
834 }
835 if(ulRead != size) {
836 DosExitCritSec();
837 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed to read %x (%x) bytes at %x for 0x%x!", size, ulRead, fileoffset, virtAddress));
838 goto fail;
839 }
840 setFixups(virtAddress, sectionsize);
841
842 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
843 DosExitCritSec();
844 if(rc) {
845 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
846 goto fail;
847 }
848 }
849 else {
850 rc = DosEnterCritSec();
851 if(rc) {
852 dprintf((LOG, "DosEnterCritSec failed with rc %d", rc));
853 goto fail;
854 }
855
856 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
857 if(rc) {
858 DosExitCritSec();
859 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
860 goto fail;
861 }
862 setFixups(virtAddress, sectionsize);
863
864 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
865 DosExitCritSec();
866 if(rc) {
867 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
868 goto fail;
869 }
870 }
871 return TRUE;
872
873fail:
874 return FALSE;
875}
876//******************************************************************************
877//******************************************************************************
878void Win32PeLdrImage::addSection(ULONG type, ULONG rawoffset, ULONG rawsize, ULONG virtaddress, ULONG virtsize, ULONG flags)
879{
880 virtsize = max(rawsize, virtsize);
881
882 section[nrsections].rawoffset = rawoffset;
883 section[nrsections].type = type;
884 section[nrsections].rawsize = rawsize;
885 section[nrsections].virtaddr = virtaddress;
886 section[nrsections].flags = flags;
887
888 virtsize = ((virtsize - 1) & ~0xFFF) + PAGE_SIZE;
889 imageSize += virtsize;
890 section[nrsections].virtualsize = virtsize;
891
892 if(virtaddress < imageVirtBase)
893 imageVirtBase = virtaddress;
894 if(virtaddress + virtsize > imageVirtEnd)
895 imageVirtEnd = virtaddress + virtsize;
896
897 nrsections++;
898}
899//******************************************************************************
900//******************************************************************************
901BOOL Win32PeLdrImage::allocSections(ULONG reservedMem)
902{
903 APIRET rc;
904 ULONG baseAddress;
905
906 realBaseAddress = 0;
907
908 //Allocated in by pe.exe
909 if(reservedMem && reservedMem == oh.ImageBase) {
910 realBaseAddress = oh.ImageBase;
911 return TRUE;
912 }
913
914 //SvL: We don't care where the image is loaded for resource lookup
915 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
916 return allocFixedMem(reservedMem);
917 }
918 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | flAllocMem);
919 if(rc) {
920 dprintf((LOG, "Win32PeLdrImage::allocSections, DosAllocMem returned %d", rc));
921 errorState = rc;
922 return(FALSE);
923 }
924 realBaseAddress = baseAddress;
925 return(TRUE);
926}
927//******************************************************************************
928//******************************************************************************
929Section *Win32PeLdrImage::findSection(ULONG type)
930{
931 for(int i=0;i<nrsections;i++) {
932 if(section[i].type == type) {
933 return &section[i];
934 }
935 }
936 return NULL;
937}
938//******************************************************************************
939//******************************************************************************
940Section *Win32PeLdrImage::findSectionByAddr(ULONG addr)
941{
942 for(int i=0;i<nrsections;i++) {
943 if(section[i].virtaddr <= addr && section[i].virtaddr + section[i].virtualsize > addr) {
944 return &section[i];
945 }
946 }
947 return NULL;
948}
949//******************************************************************************
950//******************************************************************************
951Section *Win32PeLdrImage::findSectionByOS2Addr(ULONG addr)
952{
953 for(int i=0;i<nrsections;i++) {
954 if(section[i].realvirtaddr <= addr && section[i].realvirtaddr + section[i].virtualsize > addr) {
955 return &section[i];
956 }
957 }
958 return NULL;
959}
960//******************************************************************************
961//******************************************************************************
962Section *Win32PeLdrImage::findPreviousSectionByOS2Addr(ULONG addr)
963{
964 ULONG lowestAddr = 0xffffffff;
965 ULONG index = -1;
966
967 for(int i=0;i<nrsections;i++) {
968 if(section[i].realvirtaddr > addr) {
969 if(section[i].realvirtaddr < lowestAddr) {
970 lowestAddr = section[i].realvirtaddr;
971 index = i;
972 }
973 }
974 }
975 if(index == -1)
976 return NULL;
977
978 return &section[index];
979}
980//******************************************************************************
981#define FALLOC_SIZE (1024*1024)
982//NOTE: Needs testing (while loop)
983//TODO: Free unused (parts of) reservedMem
984//******************************************************************************
985BOOL Win32PeLdrImage::allocFixedMem(ULONG reservedMem)
986{
987 ULONG address = 0;
988 ULONG *memallocs;
989 ULONG alloccnt = 0;
990 ULONG diff, i, baseAddress;
991 APIRET rc;
992 BOOL allocFlags = flAllocMem;
993
994 //Reserve enough space to store 4096 pointers to 1MB memory chunks
995 memallocs = (ULONG *)malloc(4096*sizeof(ULONG *));
996 if(memallocs == NULL) {
997 dprintf((LOG, "allocFixedMem: MALLOC FAILED for memallocs" ));
998 return FALSE;
999 }
1000
1001 if(oh.ImageBase < 512*1024*1024) {
1002 allocFlags = 0;
1003 }
1004 while(TRUE) {
1005 rc = DosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ | allocFlags);
1006 if(rc) break;
1007
1008 dprintf((LOG, "DosAllocMem returned %x", address ));
1009 if(address + FALLOC_SIZE >= oh.ImageBase) {
1010 if(address > oh.ImageBase) {//we've passed it!
1011 DosFreeMem((PVOID)address);
1012 break;
1013 }
1014 //found the right address
1015 DosFreeMem((PVOID)address);
1016
1017 diff = oh.ImageBase - address;
1018 if(diff) {
1019 rc = DosAllocMem((PPVOID)&address, diff, PAG_READ | allocFlags);
1020 if(rc) break;
1021 }
1022 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | allocFlags);
1023 if(rc) break;
1024
1025 if(diff) DosFreeMem((PVOID)address);
1026
1027 realBaseAddress = baseAddress;
1028 break;
1029 }
1030 memallocs[alloccnt++] = address;
1031 }
1032 for(i=0;i<alloccnt;i++) {
1033 DosFreeMem((PVOID)memallocs[i]);
1034 }
1035 free(memallocs);
1036
1037 if(realBaseAddress == 0) //Let me guess.. MS Office app?
1038 return(FALSE);
1039
1040 return(TRUE);
1041}
1042//******************************************************************************
1043//******************************************************************************
1044BOOL Win32PeLdrImage::setMemFlags()
1045{
1046 int i;
1047 WINIMAGE_LOOKUP *imgLookup;
1048
1049 imgLookup = WINIMAGE_LOOKUPADDR(realBaseAddress);
1050 imgLookup->magic1 = MAGIC_WINIMAGE;
1051 imgLookup->image = this;
1052 imgLookup->magic2 = MAGIC_WINIMAGE;
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//******************************************************************************
1281void Win32PeLdrImage::StoreImportByOrd(Win32ImageBase *WinImage, ULONG ordinal, ULONG impaddr)
1282{
1283 ULONG *import;
1284 ULONG apiaddr;
1285
1286 import = (ULONG *)impaddr;
1287 apiaddr = WinImage->getApi(ordinal);
1288 if(apiaddr == 0)
1289 {
1290 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%u not found\n",
1291 WinImage->getModuleName(),
1292 ordinal));
1293
1294 dprintf((LOG, "--->>> NOT FOUND!" ));
1295 *import = (ULONG)MissingApi;
1296 }
1297 else *import = apiaddr;
1298}
1299//******************************************************************************
1300//******************************************************************************
1301void Win32PeLdrImage::StoreImportByName(Win32ImageBase *WinImage, char *impname, ULONG impaddr)
1302{
1303 ULONG *import;
1304 ULONG apiaddr;
1305
1306 import = (ULONG *)impaddr;
1307 apiaddr = WinImage->getApi(impname);
1308 if(apiaddr == 0)
1309 {
1310 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%s not found\n",
1311 WinImage->getModuleName(),
1312 impname));
1313
1314 dprintf((LOG, "--->>> NOT FOUND!" ));
1315 *import = (ULONG)MissingApi;
1316 }
1317 else *import = apiaddr;
1318}
1319//******************************************************************************
1320//******************************************************************************
1321BOOL Win32PeLdrImage::processExports(char *win32file)
1322{
1323 IMAGE_SECTION_HEADER sh;
1324 PIMAGE_EXPORT_DIRECTORY ped;
1325 ULONG *ptrNames, *ptrAddress;
1326 USHORT *ptrOrd;
1327 BOOL fForwarder;
1328 int i;
1329
1330 /* get section header and pointer to data directory for .edata section */
1331 if((ped = (PIMAGE_EXPORT_DIRECTORY)ImageDirectoryOffset
1332 (win32file, IMAGE_DIRECTORY_ENTRY_EXPORT)) != NULL &&
1333 GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_EXPORT, &sh) ) {
1334
1335 dprintf((LOG, "Exported Functions: " ));
1336 ptrOrd = (USHORT *)((ULONG)ped->AddressOfNameOrdinals +
1337 (ULONG)win32file);
1338 ptrNames = (ULONG *)((ULONG)ped->AddressOfNames +
1339 (ULONG)win32file);
1340 ptrAddress = (ULONG *)((ULONG)ped->AddressOfFunctions +
1341 (ULONG)win32file);
1342 nrOrdExports = ped->NumberOfFunctions;
1343 nrNameExports = ped->NumberOfNames;
1344
1345 int ord, RVAExport;
1346 char *name;
1347 for(i=0;i<ped->NumberOfNames;i++)
1348 {
1349 fForwarder = FALSE;
1350 ord = ptrOrd[i] + ped->Base;
1351 name = (char *)((ULONG)ptrNames[i] + (ULONG)win32file);
1352 RVAExport = ptrAddress[ptrOrd[i]];
1353
1354 /* forwarder? ulRVA within export directory. */
1355 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1356 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1357 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1358 {
1359 fForwarder = AddForwarder(oh.ImageBase + RVAExport, name, ord);
1360 }
1361 if(!fForwarder) {
1362 //points to code (virtual address relative to oh.ImageBase
1363 AddNameExport(oh.ImageBase + RVAExport, name, ord);
1364 dprintf((LOG, "address 0x%x %s @%d (0x%08x)", RVAExport, name, ord, realBaseAddress + RVAExport));
1365 }
1366 }
1367 for(i=0;i<max(ped->NumberOfNames,ped->NumberOfFunctions);i++)
1368 {
1369 fForwarder = FALSE;
1370 ord = ped->Base + i; //Correct??
1371 RVAExport = ptrAddress[i];
1372 /* forwarder? ulRVA within export directory. */
1373 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1374 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1375 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1376 {
1377 fForwarder = AddForwarder(oh.ImageBase + RVAExport, NULL, ord);
1378 }
1379 if(!fForwarder && RVAExport) {
1380 //points to code (virtual address relative to oh.ImageBase
1381 dprintf((LOG, "ord %d at 0x%08x (0x%08x)", ord, RVAExport, realBaseAddress + RVAExport));
1382 AddOrdExport(oh.ImageBase + RVAExport, ord);
1383 }
1384 }
1385 }
1386
1387 return(TRUE);
1388}
1389//******************************************************************************
1390//******************************************************************************
1391void Win32PeLdrImage::AddNameExport(ULONG virtaddr, char *apiname, ULONG ordinal, BOOL fAbsoluteAddress)
1392{
1393 ULONG nsize;
1394
1395 if(nameexports == NULL) {
1396 nameExportSize= 4096;
1397 nameexports = (NameExport *)malloc(nameExportSize);
1398 curnameexport = nameexports;
1399 }
1400 nsize = (ULONG)curnameexport - (ULONG)nameexports;
1401 if(nsize + sizeof(NameExport) + strlen(apiname) > nameExportSize) {
1402 nameExportSize += 4096;
1403 char *tmp = (char *)nameexports;
1404 nameexports = (NameExport *)malloc(nameExportSize);
1405 memcpy(nameexports, tmp, nsize);
1406 curnameexport = (NameExport *)((ULONG)nameexports + nsize);
1407 free(tmp);
1408 }
1409 if(fAbsoluteAddress) {//forwarders use absolute address
1410 curnameexport->virtaddr = virtaddr;
1411 }
1412 else curnameexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1413 curnameexport->ordinal = ordinal;
1414 *(ULONG *)curnameexport->name = 0;
1415 strcpy(curnameexport->name, apiname);
1416
1417 curnameexport->nlength = strlen(apiname) + 1;
1418 if(curnameexport->nlength < sizeof(curnameexport->name))
1419 curnameexport->nlength = sizeof(curnameexport->name);
1420
1421 curnameexport = (NameExport *)((ULONG)curnameexport->name + curnameexport->nlength);
1422}
1423//******************************************************************************
1424//******************************************************************************
1425void Win32PeLdrImage::AddOrdExport(ULONG virtaddr, ULONG ordinal, BOOL fAbsoluteAddress)
1426{
1427 if(ordexports == NULL) {
1428 ordexports = (OrdExport *)malloc(nrOrdExports * sizeof(OrdExport));
1429 curordexport = ordexports;
1430 }
1431 if(fAbsoluteAddress) {//forwarders use absolute address
1432 curordexport->virtaddr = virtaddr;
1433 }
1434 else curordexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1435
1436 curordexport->ordinal = ordinal;
1437 curordexport++;
1438 nrOrdExportsRegistered++;
1439}
1440//******************************************************************************
1441//******************************************************************************
1442BOOL Win32PeLdrImage::AddForwarder(ULONG virtaddr, char *apiname, ULONG ordinal)
1443{
1444 char *forward = (char *)(realBaseAddress + (virtaddr - oh.ImageBase));
1445 char *forwarddll, *forwardapi;
1446 Win32DllBase *WinDll;
1447 DWORD exportaddr;
1448 int forwardord;
1449
1450 forwarddll = strdup(forward);
1451 if(forwarddll == NULL) {
1452 return FALSE;
1453 }
1454 forwardapi = strchr(forwarddll, '.');
1455 if(forwardapi == NULL) {
1456 goto fail;
1457 }
1458 *forwardapi++ = 0;
1459 if(strlen(forwarddll) == 0 || strlen(forwardapi) == 0) {
1460 goto fail;
1461 }
1462 WinDll = Win32DllBase::findModule(forwarddll);
1463 if(WinDll == NULL) {
1464 WinDll = loadDll(forwarddll);
1465 if(WinDll == NULL) {
1466 dprintf((LOG, "ERROR: couldn't find forwarder %s.%s", forwarddll, forwardapi));
1467 goto fail;
1468 }
1469 }
1470 //check if name or ordinal forwarder
1471 forwardord = 0;
1472 if(*forwardapi >= '0' && *forwardapi <= '9') {
1473 forwardord = atoi(forwardapi);
1474 }
1475 if(forwardord != 0 || (strlen(forwardapi) == 1 && *forwardapi == '0')) {
1476 exportaddr = WinDll->getApi(forwardord);
1477 }
1478 else exportaddr = WinDll->getApi(forwardapi);
1479
1480 if(apiname) {
1481 dprintf((LOG, "address 0x%x %s @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, apiname, ordinal, virtaddr, forwarddll, forwardapi));
1482 AddNameExport(exportaddr, apiname, ordinal, TRUE);
1483 }
1484 else {
1485 dprintf((LOG, "address 0x%x @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, ordinal, virtaddr, forwarddll, forwardapi));
1486 AddOrdExport(exportaddr, ordinal, TRUE);
1487 }
1488 free(forwarddll);
1489 return TRUE;
1490
1491fail:
1492 free(forwarddll);
1493 return FALSE;
1494}
1495//******************************************************************************
1496//******************************************************************************
1497Win32DllBase *Win32PeLdrImage::loadDll(char *pszCurModule)
1498{
1499 Win32DllBase *WinDll = NULL;
1500 char modname[CCHMAXPATH];
1501
1502 strcpy(modname, pszCurModule);
1503
1504 //rename dll if necessary (i.e. OLE32 -> OLE32OS2)
1505 Win32DllBase::renameDll(modname);
1506
1507 char szModName2[CCHMAXPATH];
1508 strcpy(szModName2, modname);
1509 if (!Win32ImageBase::findDll(szModName2, modname, sizeof(modname)))
1510 {
1511 dprintf((LOG, "Module %s not found!", modname));
1512 sprintf(szErrorModule, "%s", modname);
1513 errorState = 2;
1514 return NULL;
1515 }
1516
1517 if(isPEImage(modname, NULL) != ERROR_SUCCESS_W)
1518 {//LX image, so let OS/2 do all the work for us
1519 APIRET rc;
1520 char szModuleFailure[CCHMAXPATH] = "";
1521 ULONG hInstanceNewDll;
1522 Win32LxDll *lxdll;
1523
1524 char *dot = strchr(modname, '.');
1525 if(dot == NULL) {
1526 strcat(modname, DLL_EXTENSION);
1527 }
1528 rc = DosLoadModule(szModuleFailure, sizeof(szModuleFailure), modname, (HMODULE *)&hInstanceNewDll);
1529 if(rc) {
1530 dprintf((LOG, "DosLoadModule returned %X for %s", rc, szModuleFailure));
1531 sprintf(szErrorModule, "%s", szModuleFailure);
1532 errorState = rc;
1533 return NULL;
1534 }
1535 lxdll = Win32LxDll::findModuleByOS2Handle(hInstanceNewDll);
1536 if(lxdll == NULL) {//shouldn't happen!
1537 dprintf((LOG, "Just loaded the dll, but can't find it anywhere?!!?"));
1538 errorState = ERROR_INTERNAL;
1539 return NULL;
1540 }
1541 lxdll->setDllHandleOS2(hInstanceNewDll);
1542 if(lxdll->AddRef() == -1) {//-1 -> load failed (attachProcess)
1543 dprintf((LOG, "Dll %s refused to be loaded; aborting", modname));
1544 delete lxdll;
1545 errorState = ERROR_INTERNAL;
1546 return NULL;
1547 }
1548 WinDll = (Win32DllBase*)lxdll;
1549 }
1550 else {
1551 Win32PeLdrDll *pedll;
1552
1553 pedll = new Win32PeLdrDll(modname, this);
1554 if(pedll == NULL) {
1555 dprintf((LOG, "pedll: Error allocating memory" ));
1556 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szMemErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
1557 errorState = ERROR_INTERNAL;
1558 return NULL;
1559 }
1560 dprintf((LOG, "**********************************************************************" ));
1561 dprintf((LOG, "********************** Loading Module *********************" ));
1562 dprintf((LOG, "**********************************************************************" ));
1563 if(pedll->init(0) == FALSE) {
1564 dprintf((LOG, "Internal WinDll error ", pedll->getError() ));
1565 delete pedll;
1566 return NULL;
1567 }
1568#ifdef DEBUG
1569 pedll->AddRef(getModuleName());
1570#else
1571 pedll->AddRef();
1572#endif
1573 if(pedll->attachProcess() == FALSE) {
1574 dprintf((LOG, "attachProcess failed!" ));
1575 delete pedll;
1576 errorState = ERROR_INTERNAL;
1577 return NULL;
1578 }
1579 WinDll = (Win32DllBase*)pedll;
1580 }
1581
1582 dprintf((LOG, "**********************************************************************" ));
1583 dprintf((LOG, "********************** Finished Loading Module %s ", modname ));
1584 dprintf((LOG, "**********************************************************************" ));
1585
1586 return WinDll;
1587}
1588//******************************************************************************
1589/** All initial processing of imports is done here
1590 * Should now detect most Borland styled files including the GifCon32.exe and
1591 * loader32 from SoftIce. (Stupid Borland!!!)
1592 *
1593 * knut [Jul 22 1998 2:44am]
1594 **/
1595//******************************************************************************
1596BOOL Win32PeLdrImage::processImports(char *win32file)
1597{
1598 PIMAGE_IMPORT_DESCRIPTOR pID;
1599 IMAGE_SECTION_HEADER shID;
1600 IMAGE_SECTION_HEADER shExtra = {0};
1601 PIMAGE_OPTIONAL_HEADER pOH;
1602 int i,j, nrPages;
1603 BOOL fBorland = 0;
1604 int cModules;
1605 char *pszModules;
1606 char *pszCurModule;
1607 char *pszTmp;
1608 ULONG *pulImport;
1609 ULONG ulCurFixup;
1610 int Size;
1611 Win32DllBase *WinDll;
1612 Win32ImageBase *WinImage = NULL;
1613 Section *section;
1614
1615/* "algorithm:"
1616 * 1) get module names and store them
1617 * a) check dwRVAModuleName is within .idata seg - if not find section
1618 * 2) iterate thru functions of each module
1619 * a) check OriginalFirstThunk is not 0 and that it points to a RVA.
1620 * b) if not a) borland-styled PE-file - ARG!!!
1621 * check FirstThunk
1622 * c) check OriginalFirstThunk/FirstThunk ok RVAs and find right section
1623 * d) store ordinal/name import
1624 * 3) finished
1625 */
1626
1627 /* 1) get module names */
1628 pID = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT);
1629 if (pID == NULL)
1630 return TRUE;
1631 if (!GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT, &shID))
1632 return TRUE;
1633
1634 //calc size of module list
1635 i = Size = cModules = 0;
1636 while (pID[i].Name != 0)
1637 {
1638 //test RVA inside ID-Section
1639 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1640 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1641 }
1642 else {
1643 //is the "Extra"-section already found or do we have to find it?
1644 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1645 if (!GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name))
1646 return FALSE;
1647 }
1648 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1649 }
1650 Size += strlen(pszTmp) + 1;
1651 i++;
1652 cModules++;
1653 }
1654
1655 pszModules = (char*)malloc(Size);
1656 assert(pszModules != NULL);
1657 j = 0;
1658 for (i = 0; i < cModules; i++)
1659 {
1660 //test RVA inside ID-Section
1661 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1662 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1663 }
1664 else {
1665 fBorland = TRUE;
1666 //is the "Extra"-section already found or do we have to find it?
1667 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1668 {
1669 if (GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name)) {
1670 free(pszModules);
1671 return FALSE;
1672 }
1673 }
1674 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1675 }
1676
1677 strcpy(pszModules+j, pszTmp);
1678 j += strlen(pszTmp) + 1;
1679 }
1680 if (fBorland)
1681 dprintf((LOG, "Borland-styled PE-File." ));
1682
1683 //Store modules
1684 dprintf((LOG, "%d imported Modules: ", cModules ));
1685
1686 /* 2) functions */
1687 pszCurModule = pszModules;
1688 pOH = (PIMAGE_OPTIONAL_HEADER)OPTHEADEROFF(win32file);
1689 for (i = 0; i < cModules; i++)
1690 {
1691 dprintf((LOG, "Module %s", pszCurModule ));
1692 if(pID[i].ForwarderChain) {
1693 dprintf((LOG, "ForwarderChain: %x", pID[i].ForwarderChain));
1694 }
1695 // a) check that OriginalFirstThunk not is 0 and look for Borland-styled PE
1696 if (i == 0)
1697 {
1698 //heavy borland-style test - assume array of thunks is within that style does not change
1699 if((ULONG)pID[i].u.OriginalFirstThunk == 0 ||
1700 (ULONG)pID[i].u.OriginalFirstThunk < shID.VirtualAddress ||
1701 (ULONG)pID[i].u.OriginalFirstThunk >= shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData) ||
1702 (ULONG)pID[i].u.OriginalFirstThunk >= pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress &&
1703 (ULONG)pID[i].u.OriginalFirstThunk < sizeof(*pID)*cModules + pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1704 {
1705 fBorland = TRUE;
1706 }
1707 }
1708 //light borland-style test
1709 if (pID[i].u.OriginalFirstThunk == 0 || fBorland) {
1710 pulImport = (ULONG*)pID[i].FirstThunk;
1711 }
1712 else pulImport = (ULONG*)pID[i].u.OriginalFirstThunk;
1713
1714 // b) check if RVA ok
1715 if (!(pulImport > 0 && (ULONG)pulImport < pOH->SizeOfImage)) {
1716 dprintf((LOG, "Invalid RVA %x", pulImport ));
1717 break;
1718 }
1719 // check section
1720 if ((ULONG)pulImport < shExtra.VirtualAddress || (ULONG)pulImport >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1721 {
1722 if (!GetSectionHdrByRVA(win32file, &shExtra, (ULONG)pulImport))
1723 {
1724 dprintf((LOG, "warning: could not find section for Thunk RVA %x", pulImport ));
1725 break;
1726 }
1727 }
1728
1729 //SvL: Load dll if needed
1730 dprintf((LOG, "**********************************************************************" ));
1731 dprintf((LOG, "************** Import Module %s ", pszCurModule ));
1732 dprintf((LOG, "**********************************************************************" ));
1733 WinDll = Win32DllBase::findModule(pszCurModule);
1734
1735 if(WinDll == NULL)
1736 { //not found, so load it
1737 if (WinExe != NULL && WinExe->matchModName(pszCurModule)) {
1738 WinImage = (Win32ImageBase *)WinExe;
1739 }
1740 else {
1741 WinDll = loadDll(pszCurModule);
1742 if(WinDll == NULL) {
1743 return FALSE;
1744 }
1745 }
1746 }
1747 else {
1748 WinDll->AddRef();
1749 dprintf((LOG, "Already found ", pszCurModule));
1750 }
1751 if(WinDll != NULL) {
1752 //add the dll we just loaded to dependency list for this image
1753 addDependency(WinDll);
1754
1755 //Make sure the dependency list is correct (already done
1756 //in the ctor of Win32DllBase, but for LX dlls the parent is
1757 //then set to NULL; so change it here again
1758 WinDll->setUnloadOrder(this);
1759 WinImage = (Win32ImageBase *)WinDll;
1760 }
1761 else
1762 if(WinImage == NULL) {
1763 dprintf((LOG, "Unable to load dll %s", pszCurModule ));
1764 return FALSE;
1765 }
1766
1767 pulImport = (PULONG)((ULONG)pulImport + (ULONG)win32file);
1768 j = 0;
1769 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)win32file;
1770
1771 section = findSectionByOS2Addr(ulCurFixup);
1772 if(section == NULL) {
1773 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1774 return FALSE;
1775 }
1776 //SvL: Read page from disk
1777 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1778 //SvL: Enable write access
1779 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1780 nrPages = 1;
1781
1782 while (pulImport[j] != 0) {
1783 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1784 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1785 StoreImportByOrd(WinImage, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1786 }
1787 else { //name
1788 //check
1789 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1790 if (!GetSectionHdrByRVA(win32file, &shExtra, pulImport[j]))
1791 {
1792 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1793 break;
1794 }
1795 }
1796 //KSO - Aug 6 1998 1:15am:this eases comparing...
1797 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)win32file + 2);
1798 dprintf((LOG, "0x%08x Imported function %s (0x%08x)", ulCurFixup, pszFunctionName, WinImage->getApi(pszFunctionName)));
1799 StoreImportByName(WinImage, pszFunctionName, ulCurFixup);
1800 }
1801 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1802 j++;
1803 if((ulCurFixup & 0xfff) == 0) {
1804 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1805 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1806 nrPages++;
1807 }
1808 }
1809 //SvL: And restore original protection flags
1810 ulCurFixup = (ULONG)pID[i].FirstThunk + pOH->ImageBase;
1811 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1812
1813 dprintf((LOG, "**********************************************************************" ));
1814 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1815 dprintf((LOG, "**********************************************************************" ));
1816
1817 pszCurModule += strlen(pszCurModule) + 1;
1818 }//for (i = 0; i < cModules; i++)
1819
1820 free(pszModules);
1821 return TRUE;
1822}
1823//******************************************************************************
1824//******************************************************************************
1825BOOL Win32PeLdrImage::insideModule(ULONG address)
1826{
1827 if((address >= realBaseAddress) && (address < realBaseAddress + imageSize)) {
1828 return TRUE;
1829 }
1830 return FALSE;
1831}
1832//******************************************************************************
1833//******************************************************************************
1834BOOL Win32PeLdrImage::insideModuleCode(ULONG address)
1835{
1836 Section *sect;
1837
1838 sect = findSectionByOS2Addr(address);
1839 if(sect && (sect->pageflags & PAG_EXECUTE)) {
1840 return TRUE;
1841 }
1842 return FALSE;
1843}
1844//******************************************************************************
1845//******************************************************************************
1846ULONG Win32PeLdrImage::getImageSize()
1847{
1848 return imageSize;
1849}
1850//******************************************************************************
1851//******************************************************************************
1852ULONG Win32PeLdrImage::getApi(char *name)
1853{
1854 ULONG apiaddr, i, apilen;
1855 char *apiname;
1856 char tmp[4];
1857 NameExport *curexport;
1858 ULONG ulAPIOrdinal; /* api requested by ordinal */
1859
1860 apilen = strlen(name) + 1;
1861 if(apilen < 4)
1862 {
1863 *(ULONG *)tmp = 0;
1864 strcpy(tmp, name);
1865 apiname = tmp;
1866 apilen = 4;
1867 }
1868 else apiname = name;
1869
1870 curexport = nameexports;
1871 for(i=0; i<nrNameExports; i++)
1872 {
1873 if(apilen == curexport->nlength &&
1874 *(ULONG *)curexport->name == *(ULONG *)apiname)
1875 {
1876 if(strcmp(curexport->name, apiname) == 0)
1877 return(curexport->virtaddr);
1878 }
1879 curexport = (NameExport *)((ULONG)curexport->name + curexport->nlength);
1880 }
1881 return(0);
1882}
1883//******************************************************************************
1884//******************************************************************************
1885ULONG Win32PeLdrImage::getApi(int ordinal)
1886{
1887 ULONG apiaddr, i;
1888 OrdExport *curexport;
1889 NameExport *nexport;
1890 register int iDiff;
1891
1892 curexport = ordexports;
1893
1894 i = 0;
1895 if (nrOrdExportsRegistered > 1000)
1896 {
1897 for(i=0;i<nrOrdExportsRegistered;i+=1000) {
1898 iDiff = curexport[i].ordinal - ordinal;
1899 if(iDiff > 0) {
1900 if(i) i -= 1000;
1901 break;
1902 }
1903 else
1904 if(iDiff == 0)
1905 return(curexport[i].virtaddr);
1906 }
1907 if (i > nrOrdExportsRegistered) i -= 1000;
1908 }
1909
1910 if (nrOrdExportsRegistered > 100)
1911 {
1912 for(i;i<nrOrdExportsRegistered;i+=100) {
1913 iDiff = curexport[i].ordinal - ordinal;
1914 if(iDiff > 0) {
1915 if(i) i -= 100;
1916 break;
1917 }
1918 else
1919 if(iDiff == 0)
1920 return(curexport[i].virtaddr);
1921 }
1922 if (i > nrOrdExportsRegistered) i -= 100;
1923 }
1924
1925 if (nrOrdExportsRegistered > 10)
1926 {
1927 for(i;i<nrOrdExportsRegistered;i+=10) {
1928 iDiff = curexport[i].ordinal - ordinal;
1929 if(iDiff > 0) {
1930 if(i) i -= 10;
1931 break;
1932 }
1933 else
1934 if(iDiff == 0)
1935 return(curexport[i].virtaddr);
1936 }
1937 if (i > nrOrdExportsRegistered) i -= 10;
1938 }
1939
1940 for(i;i<nrOrdExportsRegistered;i++) {
1941 if(curexport[i].ordinal == ordinal)
1942 return(curexport[i].virtaddr);
1943 }
1944
1945 //Name exports also contain an ordinal, so check this
1946 nexport = nameexports;
1947 for(i=0;i<nrNameExports;i++) {
1948 if(nexport->ordinal == ordinal)
1949 return(nexport->virtaddr);
1950
1951 nexport = (NameExport *)((ULONG)nexport->name + nexport->nlength);
1952 }
1953 return(0);
1954}
1955//******************************************************************************
1956//Returns required OS version for this image
1957//******************************************************************************
1958ULONG Win32PeLdrImage::getVersion()
1959{
1960 return (oh.MajorOperatingSystemVersion << 16) | oh.MinorOperatingSystemVersion;
1961}
1962//******************************************************************************
1963//******************************************************************************
1964ULONG MissingApi()
1965{
1966 static BOOL fIgnore = FALSE;
1967 int r;
1968
1969 dprintf((LOG, "Missing api called!\n"));
1970 if(fIgnore)
1971 return(0);
1972
1973 do {
1974 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, "The application has called a non-existing api\n",
1975 "Internal Odin Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
1976 }
1977 while(r == MBID_RETRY); //giggle
1978
1979 if( r != MBID_IGNORE )
1980 ExitProcess(987);
1981
1982 fIgnore = TRUE;
1983 return(0);
1984}
1985/******************************************************************************/
1986/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.