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

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

Check executable too when searching for imported modules

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