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

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

ordinal lookup made faster

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