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

Last change on this file since 3993 was 3993, checked in by sandervl, 25 years ago

Updates for fake system dll headers

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