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

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

Rewrote file io apis

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