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

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

added support for private logfiles

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