source: trunk/src/kernel32/winimage.cpp@ 712

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

Implemented multiple views of memory mapped files + some bugfixes to PE loader code

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