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

Last change on this file since 2859 was 2859, checked in by sandervl, 26 years ago

* empty log message *

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