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

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

exe loader fixes + updates

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