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

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

TLS fix

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