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

Last change on this file since 5011 was 5011, checked in by sandervl, 25 years ago

memory map + handle manager fixes

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