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

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

findresource cleanup

File size: 55.0 KB
Line 
1/* $Id: winimagepeldr.cpp,v 1.49 2000-06-28 18:08:36 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), dwFixupSize(0)
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 dwFixupSize = ImageDirectorySize(win32file, IMAGE_DIRECTORY_ENTRY_BASERELOC);
468 commitPage((ULONG)pFixups, FALSE);
469 }
470#ifdef COMMIT_ALL
471 for (i=0; i<nSections; i++) {
472 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
473 }
474#else
475 for (i=0; i<nSections; i++) {
476 switch(section[i].type)
477 {
478 case SECTION_IMPORT:
479 case SECTION_RELOC:
480 case SECTION_EXPORT:
481 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
482 break;
483 }
484 }
485#endif
486 if(processExports((char *)win32file) == FALSE) {
487 dprintf((LOG, "Failed to process exported apis" ));
488 goto failure;
489 }
490 }
491#ifdef COMMIT_ALL
492 else {
493 commitPage((ULONG)section[0].realvirtaddr, FALSE, COMPLETE_SECTION);
494 }
495#endif
496
497 //SvL: Use pointer to image header as module handle now. Some apps needs this
498 hinstance = (HINSTANCE)realBaseAddress;
499
500 //SvL: Set instance handle in process database structure
501 SetPDBInstance(hinstance);
502
503 //PH: get pResRootDir pointer correct first, since processImports may
504 // implicitly call functions depending on it.
505 if(GetSectionHdrByName (win32file, &sh, ".rsrc")) {
506 //get offset in resource object of directory entry
507 pResRootDir = (PIMAGE_RESOURCE_DIRECTORY)(sh.VirtualAddress + realBaseAddress);
508 ulRVAResourceSection = sh.VirtualAddress;
509 }
510
511 if (loadType == REAL_LOAD)
512 {
513 if(processImports((char *)win32file) == FALSE) {
514 dprintf((LOG, "Failed to process imports!" ));
515 goto failure;
516 }
517 }
518
519 return(TRUE);
520failure:
521 if(memmap) {
522 delete memmap;
523 memmap = NULL;
524 }
525 if(hFile) {
526 OSLibDosClose(hFile);
527 hFile = 0;
528 }
529 errorState = ERROR_INTERNAL;
530 return FALSE;
531}
532//******************************************************************************
533//commits image page(s) when an access violation exception is dispatched
534//virtAddress = address of exception (rounded down to page boundary)
535//******************************************************************************
536BOOL Win32PeLdrImage::commitPage(ULONG virtAddress, BOOL fWriteAccess, int fPageCmd)
537{
538 Section *section;
539 ULONG offset, size, sectionsize, protflags, fileoffset, range, attr;
540 ULONG ulNewPos, ulRead;
541 APIRET rc;
542
543 //Round down to nearest page boundary
544 virtAddress = virtAddress & ~0xFFF;
545
546 section = findSectionByOS2Addr(virtAddress);
547 if(section == NULL) {
548 size = 4096;
549 sectionsize = 4096;
550 protflags = PAG_READ|PAG_WRITE; //readonly?
551 section = findPreviousSectionByOS2Addr(virtAddress);
552 if(section == NULL) {//access to header
553 offset = 0;
554 fileoffset = virtAddress - realBaseAddress;
555 }
556 else {
557 offset = virtAddress - (section->realvirtaddr + section->virtualsize);
558 fileoffset = section->rawoffset + section->rawsize + offset;
559 }
560 }
561 else {
562 protflags = section->pageflags;
563 offset = virtAddress - section->realvirtaddr;
564 sectionsize = section->virtualsize - offset;
565
566 if(offset > section->rawsize || section->type == SECTION_UNINITDATA) {
567 //unintialized data (set to 0)
568 size = 0;
569 fileoffset = -1;
570 }
571 else {
572 size = section->rawsize-offset;
573 fileoffset = section->rawoffset + offset;
574 }
575 if(fWriteAccess & !(section->pageflags & PAG_WRITE)) {
576 dprintf((LOG, "Win32PeLdrImage::commitPage: No write access to 0%x!", virtAddress));
577 return FALSE;
578 }
579 }
580 //Check range of pages with the same attributes starting at virtAddress
581 //(some pages might already have been loaded)
582 range = sectionsize;
583 rc = DosQueryMem((PVOID)virtAddress, &range, &attr);
584 if(rc) {
585 dprintf((LOG, "Win32PeLdrImage::commitPage: DosQueryMem for %x returned %d", virtAddress, rc));
586 return FALSE;
587 }
588 if(attr & PAG_COMMIT) {
589 dprintf((LOG, "Win32PeLdrImage::commitPage: Memory at 0x%x already committed!", virtAddress));
590 return FALSE;
591 }
592
593 if(fPageCmd == SINGLE_PAGE) {
594 size = min(size, PAGE_SIZE);
595 sectionsize = min(sectionsize, PAGE_SIZE);
596 }
597 else
598 if(fPageCmd == SECTION_PAGES) {
599 size = min(size, DEFAULT_NR_PAGES*PAGE_SIZE);
600 sectionsize = min(sectionsize, DEFAULT_NR_PAGES*PAGE_SIZE);
601 }
602 size = min(size, range);
603 sectionsize = min(sectionsize, range);
604
605 if(fileoffset != -1) {
606 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
607 if(rc) {
608 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
609 return FALSE;
610 }
611
612 if(DosSetFilePtr(hFile, fileoffset, FILE_BEGIN, &ulNewPos) == -1) {
613 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetFilePtr failed for 0x%x!", fileoffset));
614 return FALSE;
615 }
616 if(DosRead(hFile, (PVOID)virtAddress, size, &ulRead)) {
617 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed for 0x%x!", virtAddress));
618 return FALSE;
619 }
620 if(ulRead != size) {
621 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed to read %x (%x) bytes at %x for 0x%x!", size, ulRead, fileoffset, virtAddress));
622 return FALSE;
623 }
624 setFixups(virtAddress, sectionsize);
625
626 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
627 if(rc) {
628 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
629 return FALSE;
630 }
631 }
632 else {
633 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
634 if(rc) {
635 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
636 return FALSE;
637 }
638 setFixups(virtAddress, sectionsize);
639
640 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
641 if(rc) {
642 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
643 return FALSE;
644 }
645 }
646 return TRUE;
647}
648//******************************************************************************
649//******************************************************************************
650void Win32PeLdrImage::addSection(ULONG type, ULONG rawoffset, ULONG rawsize, ULONG virtaddress, ULONG virtsize, ULONG flags)
651{
652 virtsize = max(rawsize, virtsize);
653
654 section[nrsections].rawoffset = rawoffset;
655 section[nrsections].type = type;
656 section[nrsections].rawsize = rawsize;
657 section[nrsections].virtaddr = virtaddress;
658 section[nrsections].flags = flags;
659
660 virtsize = ((virtsize - 1) & ~0xFFF) + PAGE_SIZE;
661 imageSize += virtsize;
662 section[nrsections].virtualsize = virtsize;
663
664 if(virtaddress < imageVirtBase)
665 imageVirtBase = virtaddress;
666 if(virtaddress + virtsize > imageVirtEnd)
667 imageVirtEnd = virtaddress + virtsize;
668
669 nrsections++;
670}
671//******************************************************************************
672//******************************************************************************
673BOOL Win32PeLdrImage::allocSections(ULONG reservedMem)
674{
675 APIRET rc;
676 ULONG baseAddress;
677
678 //SvL: We don't care where the image is loaded for resource lookup
679 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED && loadType == REAL_LOAD) {
680 return allocFixedMem(reservedMem);
681 }
682 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | flAllocMem);
683 if(rc) {
684 dprintf((LOG, "Win32PeLdrImage::allocSections, DosAllocMem returned %d", rc));
685 errorState = rc;
686 return(FALSE);
687 }
688 realBaseAddress = baseAddress;
689 return(TRUE);
690}
691//******************************************************************************
692//******************************************************************************
693Section *Win32PeLdrImage::findSection(ULONG type)
694{
695 for(int i=0;i<nrsections;i++) {
696 if(section[i].type == type) {
697 return &section[i];
698 }
699 }
700 return NULL;
701}
702//******************************************************************************
703//******************************************************************************
704Section *Win32PeLdrImage::findSectionByAddr(ULONG addr)
705{
706 for(int i=0;i<nrsections;i++) {
707 if(section[i].virtaddr <= addr && section[i].virtaddr + section[i].virtualsize > addr) {
708 return &section[i];
709 }
710 }
711 return NULL;
712}
713//******************************************************************************
714//******************************************************************************
715Section *Win32PeLdrImage::findSectionByOS2Addr(ULONG addr)
716{
717 for(int i=0;i<nrsections;i++) {
718 if(section[i].realvirtaddr <= addr && section[i].realvirtaddr + section[i].virtualsize > addr) {
719 return &section[i];
720 }
721 }
722 return NULL;
723}
724//******************************************************************************
725//******************************************************************************
726Section *Win32PeLdrImage::findPreviousSectionByOS2Addr(ULONG addr)
727{
728 ULONG lowestAddr = 0xffffffff;
729 ULONG index = -1;
730
731 for(int i=0;i<nrsections;i++) {
732 if(section[i].realvirtaddr > addr) {
733 if(section[i].realvirtaddr < lowestAddr) {
734 lowestAddr = section[i].realvirtaddr;
735 index = i;
736 }
737 }
738 }
739 if(index == -1)
740 return NULL;
741
742 return &section[index];
743}
744//******************************************************************************
745#define FALLOC_SIZE (1024*1024)
746//NOTE: Needs testing (while loop)
747//TODO: Free unused (parts of) reservedMem
748//******************************************************************************
749BOOL Win32PeLdrImage::allocFixedMem(ULONG reservedMem)
750{
751 ULONG address = 0;
752 ULONG *memallocs;
753 ULONG alloccnt = 0;
754 ULONG diff, i, baseAddress;
755 APIRET rc;
756 BOOL allocFlags = flAllocMem;
757
758 realBaseAddress = 0;
759
760 //Allocated in peldr.dll
761 if(reservedMem && reservedMem == oh.ImageBase) {
762 realBaseAddress = oh.ImageBase;
763 return TRUE;
764 }
765
766 //Reserve enough space to store 4096 pointers to 1MB memory chunks
767 memallocs = (ULONG *)malloc(4096*sizeof(ULONG *));
768 if(memallocs == NULL) {
769 dprintf((LOG, "allocFixedMem: MALLOC FAILED for memallocs" ));
770 return FALSE;
771 }
772
773 if(oh.ImageBase < 512*1024*1024) {
774 allocFlags = 0;
775 }
776 while(TRUE) {
777 rc = DosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ | allocFlags);
778 if(rc) break;
779
780 dprintf((LOG, "DosAllocMem returned %x", address ));
781 if(address + FALLOC_SIZE >= oh.ImageBase) {
782 if(address > oh.ImageBase) {//we've passed it!
783 DosFreeMem((PVOID)address);
784 break;
785 }
786 //found the right address
787 DosFreeMem((PVOID)address);
788
789 diff = oh.ImageBase - address;
790 if(diff) {
791 rc = DosAllocMem((PPVOID)&address, diff, PAG_READ | allocFlags);
792 if(rc) break;
793 }
794 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | allocFlags);
795 if(rc) break;
796
797 if(diff) DosFreeMem((PVOID)address);
798
799 realBaseAddress = baseAddress;
800 break;
801 }
802 memallocs[alloccnt++] = address;
803 }
804 for(i=0;i<alloccnt;i++) {
805 DosFreeMem((PVOID)memallocs[i]);
806 }
807 free(memallocs);
808
809 if(realBaseAddress == 0) //Let me guess.. MS Office app?
810 return(FALSE);
811
812 return(TRUE);
813}
814//******************************************************************************
815//******************************************************************************
816BOOL Win32PeLdrImage::setMemFlags()
817{
818 int i;
819 WINIMAGE_LOOKUP *imgLookup;
820
821 imgLookup = WINIMAGE_LOOKUPADDR(realBaseAddress);
822 imgLookup->magic1 = MAGIC_WINIMAGE;
823 imgLookup->image = this;
824 imgLookup->magic2 = MAGIC_WINIMAGE;
825
826 // Process all the image sections
827 for(i=0;i<nrsections;i++) {
828 section[i].realvirtaddr = realBaseAddress + (section[i].virtaddr - oh.ImageBase);
829 }
830
831 for(i=0;i<nrsections;i++) {
832 switch(section[i].type)
833 {
834 case SECTION_CODE:
835 case (SECTION_CODE | SECTION_IMPORT):
836 section[i].pageflags = PAG_EXECUTE | PAG_READ;
837 if(section[i].flags & IMAGE_SCN_MEM_WRITE)
838 section[i].pageflags |= PAG_WRITE;
839 break;
840 case SECTION_INITDATA:
841 case SECTION_UNINITDATA:
842 case SECTION_IMPORT: //TODO: read only?
843 section[i].pageflags = PAG_WRITE | PAG_READ;
844 break;
845
846 case SECTION_RESOURCE:
847 //TODO: GDI32 changes some bitmap structures to avoid problems in Open32
848 // -> causes crashes if resource section is readonly
849 // -> make it readonly again when gdi32 has been rewritten
850 section[i].pageflags = PAG_WRITE | PAG_READ;
851 break;
852
853 case SECTION_READONLYDATA:
854 case SECTION_TLS:
855 default:
856 section[i].pageflags = PAG_READ;
857 break;
858 }
859 }
860 return(TRUE);
861}
862//******************************************************************************
863//******************************************************************************
864BOOL Win32PeLdrImage::setFixups(ULONG virtAddress, ULONG size)
865{
866 int i, j;
867 char *page;
868 ULONG count, newpage;
869 Section *section;
870 PIMAGE_BASE_RELOCATION prel = pFixups;
871
872 if(realBaseAddress == oh.ImageBase || fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
873 return(TRUE);
874 }
875
876 virtAddress -= realBaseAddress;
877 //round size to next page boundary
878 size = (size-1) & ~0xFFF;
879 size += PAGE_SIZE;
880
881 if(prel) {
882 j = 1;
883 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
884 prel->VirtualAddress && prel->VirtualAddress < virtAddress)
885 {
886 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
887 }
888 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
889 prel->VirtualAddress && prel->VirtualAddress < virtAddress + size)
890 {
891 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
892 count = (prel->SizeOfBlock - 8)/2;
893 j++;
894 for(i=0;i<count;i++) {
895 int type = prel->TypeOffset[i] >> 12;
896 int offset = prel->TypeOffset[i] & 0xFFF;
897 int fixupsize = 0;
898
899 switch(type)
900 {
901 case IMAGE_REL_BASED_HIGHLOW:
902 fixupsize = 4;
903 break;
904 case IMAGE_REL_BASED_HIGH:
905 case IMAGE_REL_BASED_LOW:
906 fixupsize = 2;
907 break;
908 }
909 //If the fixup crosses the final page boundary,
910 //then we have to load another page
911 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
912 {
913 newpage = realBaseAddress + prel->VirtualAddress + offset + fixupsize;
914 newpage &= ~0xFFF;
915
916 section = findSectionByOS2Addr(newpage);
917 if(section == NULL) {
918 //should never happen
919 dprintf((LOG, "::setFixups -> section == NULL!!"));
920 return FALSE;
921 }
922 //SvL: Read page from disk
923 commitPage(newpage, FALSE, SINGLE_PAGE);
924
925 //SvL: Enable write access
926 DosSetMem((PVOID)newpage, PAGE_SIZE, PAG_READ|PAG_WRITE);
927 }
928
929 switch(type)
930 {
931 case IMAGE_REL_BASED_ABSOLUTE:
932 break; //skip
933 case IMAGE_REL_BASED_HIGHLOW:
934 AddOff32Fixup(prel->VirtualAddress + offset);
935 break;
936 case IMAGE_REL_BASED_HIGH:
937 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
938 break;
939 case IMAGE_REL_BASED_LOW:
940 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
941 break;
942 case IMAGE_REL_BASED_HIGHADJ:
943 case IMAGE_REL_BASED_MIPS_JMPADDR:
944 default:
945 break;
946 }
947 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
948 {
949 //SvL: Restore original page protection flags
950 DosSetMem((PVOID)newpage, PAGE_SIZE, section->pageflags);
951 }
952 }
953 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
954 }//while
955 }
956 else {
957 dprintf((LOG, "Win32PeLdrImage::setFixups, no fixups at %x, %d", virtAddress, size));
958 return(FALSE);
959 }
960 return(TRUE);
961}
962//******************************************************************************
963//******************************************************************************
964BOOL Win32PeLdrImage::setFixups(PIMAGE_BASE_RELOCATION prel)
965{
966 int i, j;
967 char *page;
968 ULONG count;
969
970 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
971 return(TRUE);
972 }
973
974 if(prel) {
975 j = 1;
976 while(prel->VirtualAddress) {
977 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
978 count = (prel->SizeOfBlock - 8)/2;
979 dprintf((LOG, "Page %d Address %x Count %d", j, prel->VirtualAddress, count ));
980 j++;
981 for(i=0;i<count;i++) {
982 int type = prel->TypeOffset[i] >> 12;
983 int offset = prel->TypeOffset[i] & 0xFFF;
984 switch(type) {
985 case IMAGE_REL_BASED_ABSOLUTE:
986//// dprintf((LOG, "absolute fixup; unused" ));
987 break; //skip
988 case IMAGE_REL_BASED_HIGHLOW:
989//// dprintf((LOG, "address ", offset << " type ", type ));
990 AddOff32Fixup(prel->VirtualAddress + offset);
991 break;
992 case IMAGE_REL_BASED_HIGH:
993 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
994 break;
995 case IMAGE_REL_BASED_LOW:
996 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
997 break;
998 case IMAGE_REL_BASED_HIGHADJ:
999 case IMAGE_REL_BASED_MIPS_JMPADDR:
1000 default:
1001 dprintf((LOG, "Unknown/unsupported fixup type!" ));
1002 break;
1003 }
1004 }
1005 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1006 }//while
1007 }
1008 else {
1009 dprintf((LOG, "No internal fixups found!" ));
1010 errorState = ERROR_INTERNAL;
1011 return(FALSE);
1012 }
1013 return(TRUE);
1014}
1015//******************************************************************************
1016//******************************************************************************
1017void Win32PeLdrImage::AddOff32Fixup(ULONG fixupaddr)
1018{
1019 ULONG orgaddr;
1020 ULONG *fixup;
1021
1022 fixup = (ULONG *)(fixupaddr + realBaseAddress);
1023 orgaddr = *fixup;
1024// dprintf((LOG, "AddOff32Fixup 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, realBaseAddress + (*fixup - oh.ImageBase)));
1025 *fixup = realBaseAddress + (*fixup - oh.ImageBase);
1026}
1027//******************************************************************************
1028//******************************************************************************
1029void Win32PeLdrImage::AddOff16Fixup(ULONG fixupaddr, BOOL fHighFixup)
1030{
1031 ULONG orgaddr;
1032 USHORT *fixup;
1033
1034 fixup = (USHORT *)(fixupaddr + realBaseAddress);
1035 orgaddr = *fixup;
1036 if(fHighFixup) {
1037 *fixup += (USHORT)((realBaseAddress - oh.ImageBase) >> 16);
1038// dprintf((LOG, "AddOff16FixupH 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1039 }
1040 else {
1041 *fixup += (USHORT)((realBaseAddress - oh.ImageBase) & 0xFFFF);
1042// dprintf((LOG, "AddOff16FixupL 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1043 }
1044}
1045//******************************************************************************
1046//******************************************************************************
1047void Win32PeLdrImage::StoreImportByOrd(Win32DllBase *WinDll, ULONG ordinal, ULONG impaddr)
1048{
1049 ULONG *import;
1050 ULONG apiaddr;
1051
1052 import = (ULONG *)impaddr;
1053 apiaddr = WinDll->getApi(ordinal);
1054 if(apiaddr == 0)
1055 {
1056 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%u not found\n",
1057 WinDll->getName(),
1058 ordinal));
1059
1060 dprintf((LOG, "--->>> NOT FOUND!" ));
1061 *import = (ULONG)MissingApi;
1062 }
1063 else *import = apiaddr;
1064}
1065//******************************************************************************
1066//******************************************************************************
1067void Win32PeLdrImage::StoreImportByName(Win32DllBase *WinDll, char *impname, ULONG impaddr)
1068{
1069 ULONG *import;
1070 ULONG apiaddr;
1071
1072 import = (ULONG *)impaddr;
1073 apiaddr = WinDll->getApi(impname);
1074 if(apiaddr == 0)
1075 {
1076 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%s not found\n",
1077 WinDll->getName(),
1078 impname));
1079
1080 dprintf((LOG, "--->>> NOT FOUND!" ));
1081 *import = (ULONG)MissingApi;
1082 }
1083 else *import = apiaddr;
1084}
1085//******************************************************************************
1086//******************************************************************************
1087BOOL Win32PeLdrImage::processExports(char *win32file)
1088{
1089 IMAGE_SECTION_HEADER sh;
1090 PIMAGE_EXPORT_DIRECTORY ped;
1091 ULONG *ptrNames, *ptrAddress;
1092 USHORT *ptrOrd;
1093 int i;
1094
1095 /* get section header and pointer to data directory for .edata section */
1096 if((ped = (PIMAGE_EXPORT_DIRECTORY)ImageDirectoryOffset
1097 (win32file, IMAGE_DIRECTORY_ENTRY_EXPORT)) != NULL &&
1098 GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_EXPORT, &sh) ) {
1099
1100 dprintf((LOG, "Exported Functions: " ));
1101 ptrOrd = (USHORT *)((ULONG)ped->AddressOfNameOrdinals +
1102 (ULONG)win32file);
1103 ptrNames = (ULONG *)((ULONG)ped->AddressOfNames +
1104 (ULONG)win32file);
1105 ptrAddress = (ULONG *)((ULONG)ped->AddressOfFunctions +
1106 (ULONG)win32file);
1107 nrOrdExports = ped->NumberOfFunctions;
1108 nrNameExports = ped->NumberOfNames;
1109
1110 int ord, RVAExport;
1111 char *name;
1112 for(i=0;i<ped->NumberOfNames;i++) {
1113 ord = ptrOrd[i] + ped->Base;
1114 name = (char *)((ULONG)ptrNames[i] + (ULONG)win32file);
1115 RVAExport = ptrAddress[ptrOrd[i]];
1116#ifdef FORWARDERS
1117 if(RVAExport < sh.VirtualAddress || RVAExport > sh.VirtualAddress + sh.SizeOfRawData) {
1118#endif
1119 //points to code (virtual address relative to oh.ImageBase
1120 AddNameExport(oh.ImageBase + RVAExport, name, ord);
1121 dprintf((LOG, "address 0x%x %s @%d", RVAExport, name, ord));
1122#ifdef FORWARDERS
1123
1124 }
1125 else {//forwarder
1126 char *forward = (char *)((ULONG)RVAExport + (ULONG)win32file);
1127 fout << RVAExport << " ", name << " @", ord << " is forwarder to ", (int)forward ));
1128 }
1129#endif
1130 }
1131 for(i=0;i<max(ped->NumberOfNames,ped->NumberOfFunctions);i++) {
1132 ord = ped->Base + i; //Correct??
1133 RVAExport = ptrAddress[i];
1134#ifdef FORWARDERS
1135 if(RVAExport < sh.VirtualAddress || RVAExport > sh.VirtualAddress + sh.SizeOfRawData) {
1136#endif
1137 if(RVAExport) {
1138 //points to code (virtual address relative to oh.ImageBase
1139 dprintf((LOG, "ord %d at 0x%x", ord, RVAExport));
1140 AddOrdExport(oh.ImageBase + RVAExport, ord);
1141 }
1142#ifdef FORWARDERS
1143 }
1144 else {//forwarder or empty
1145 char *forward = (char *)((ULONG)RVAExport + (ULONG)win32file);
1146 dprintf((LOG, "ord ", ord << " at 0x";
1147 fout << RVAExport << " is forwarder to 0x", (int)forward ));
1148 }
1149#endif
1150 }
1151 }
1152 return(TRUE);
1153}
1154//******************************************************************************
1155//******************************************************************************
1156void Win32PeLdrImage::AddNameExport(ULONG virtaddr, char *apiname, ULONG ordinal)
1157{
1158 ULONG nsize;
1159
1160 if(nameexports == NULL) {
1161 nameExportSize= 4096;
1162 nameexports = (NameExport *)malloc(nameExportSize);
1163 curnameexport = nameexports;
1164 }
1165 nsize = (ULONG)curnameexport - (ULONG)nameexports;
1166 if(nsize + sizeof(NameExport) + strlen(apiname) > nameExportSize) {
1167 nameExportSize += 4096;
1168 char *tmp = (char *)nameexports;
1169 nameexports = (NameExport *)malloc(nameExportSize);
1170 memcpy(nameexports, tmp, nsize);
1171 curnameexport = (NameExport *)((ULONG)nameexports + nsize);
1172 free(tmp);
1173 }
1174 curnameexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1175 curnameexport->ordinal = ordinal;
1176 *(ULONG *)curnameexport->name = 0;
1177 strcpy(curnameexport->name, apiname);
1178
1179 curnameexport->nlength = strlen(apiname) + 1;
1180 if(curnameexport->nlength < sizeof(curnameexport->name))
1181 curnameexport->nlength = sizeof(curnameexport->name);
1182
1183 curnameexport = (NameExport *)((ULONG)curnameexport->name + curnameexport->nlength);
1184}
1185//******************************************************************************
1186//******************************************************************************
1187void Win32PeLdrImage::AddOrdExport(ULONG virtaddr, ULONG ordinal)
1188{
1189 if(ordexports == NULL) {
1190 ordexports = (OrdExport *)malloc(nrOrdExports * sizeof(OrdExport));
1191 curordexport = ordexports;
1192 }
1193 curordexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1194 curordexport->ordinal = ordinal;
1195 curordexport++;
1196}
1197//******************************************************************************
1198/** All initial processing of imports is done here
1199 * Should now detect most Borland styled files including the GifCon32.exe and
1200 * loader32 from SoftIce. (Stupid Borland!!!)
1201 *
1202 * knut [Jul 22 1998 2:44am]
1203 **/
1204//******************************************************************************
1205BOOL Win32PeLdrImage::processImports(char *win32file)
1206{
1207 PIMAGE_IMPORT_DESCRIPTOR pID;
1208 IMAGE_SECTION_HEADER shID;
1209 IMAGE_SECTION_HEADER shExtra = {0};
1210 PIMAGE_OPTIONAL_HEADER pOH;
1211 int i,j, nrPages;
1212 BOOL fBorland = 0;
1213 int cModules;
1214 char *pszModules;
1215 char *pszCurModule;
1216 char *pszTmp;
1217 ULONG *pulImport;
1218 ULONG ulCurFixup;
1219 int Size;
1220 Win32PeLdrDll *WinDll;
1221 Section *section;
1222
1223/* "algorithm:"
1224 * 1) get module names and store them
1225 * a) check dwRVAModuleName is within .idata seg - if not find section
1226 * 2) iterate thru functions of each module
1227 * a) check OriginalFirstThunk is not 0 and that it points to a RVA.
1228 * b) if not a) borland-styled PE-file - ARG!!!
1229 * check FirstThunk
1230 * c) check OriginalFirstThunk/FirstThunk ok RVAs and find right section
1231 * d) store ordinal/name import
1232 * 3) finished
1233 */
1234
1235 /* 1) get module names */
1236 pID = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT);
1237 if (pID == NULL)
1238 return TRUE;
1239 if (!GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT, &shID))
1240 return TRUE;
1241
1242 //calc size of module list
1243 i = Size = cModules = 0;
1244 while (pID[i].Name != 0)
1245 {
1246 //test RVA inside ID-Section
1247 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1248 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1249 }
1250 else {
1251 //is the "Extra"-section already found or do we have to find it?
1252 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1253 if (!GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name))
1254 return FALSE;
1255 }
1256 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1257 }
1258 Size += strlen(pszTmp) + 1;
1259 i++;
1260 cModules++;
1261 }
1262
1263 pszModules = (char*)malloc(Size);
1264 assert(pszModules != NULL);
1265 j = 0;
1266 for (i = 0; i < cModules; i++)
1267 {
1268 //test RVA inside ID-Section
1269 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1270 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1271 }
1272 else {
1273 fBorland = TRUE;
1274 //is the "Extra"-section already found or do we have to find it?
1275 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1276 {
1277 if (GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name)) {
1278 free(pszModules);
1279 return FALSE;
1280 }
1281 }
1282 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1283 }
1284
1285 strcpy(pszModules+j, pszTmp);
1286 j += strlen(pszTmp) + 1;
1287 }
1288 if (fBorland)
1289 dprintf((LOG, "Borland-styled PE-File." ));
1290 //Store modules
1291 dprintf((LOG, "%d imported Modules: ", cModules ));
1292
1293 /* 2) functions */
1294 pszCurModule = pszModules;
1295 pOH = (PIMAGE_OPTIONAL_HEADER)OPTHEADEROFF(win32file);
1296 for (i = 0; i < cModules; i++)
1297 {
1298 dprintf((LOG, "Module %s", pszCurModule ));
1299 // a) check that OriginalFirstThunk not is 0 and look for Borland-styled PE
1300 if (i == 0)
1301 {
1302 //heavy borland-style test - assume array of thunks is within that style does not change
1303 if((ULONG)pID[i].u.OriginalFirstThunk == 0 ||
1304 (ULONG)pID[i].u.OriginalFirstThunk < shID.VirtualAddress ||
1305 (ULONG)pID[i].u.OriginalFirstThunk >= shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData) ||
1306 (ULONG)pID[i].u.OriginalFirstThunk >= pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress &&
1307 (ULONG)pID[i].u.OriginalFirstThunk < sizeof(*pID)*cModules + pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1308 {
1309 fBorland = TRUE;
1310 }
1311 }
1312 //light borland-style test
1313 if (pID[i].u.OriginalFirstThunk == 0 || fBorland) {
1314 pulImport = (ULONG*)pID[i].FirstThunk;
1315 }
1316 else pulImport = (ULONG*)pID[i].u.OriginalFirstThunk;
1317
1318 // b) check if RVA ok
1319 if (!(pulImport > 0 && (ULONG)pulImport < pOH->SizeOfImage)) {
1320 dprintf((LOG, "Invalid RVA %x", pulImport ));
1321 break;
1322 }
1323 // check section
1324 if ((ULONG)pulImport < shExtra.VirtualAddress || (ULONG)pulImport >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1325 {
1326 if (!GetSectionHdrByRVA(win32file, &shExtra, (ULONG)pulImport))
1327 {
1328 dprintf((LOG, "warning: could not find section for Thunk RVA %x", pulImport ));
1329 break;
1330 }
1331 }
1332
1333 //SvL: Load dll if needed
1334 dprintf((LOG, "**********************************************************************" ));
1335 dprintf((LOG, "************** Import Module %s ", pszCurModule ));
1336 dprintf((LOG, "**********************************************************************" ));
1337 WinDll = (Win32PeLdrDll *)Win32DllBase::findModule(pszCurModule);
1338
1339 if(WinDll == NULL)
1340 { //not found, so load it
1341 char modname[CCHMAXPATH];
1342
1343 strcpy(modname, pszCurModule);
1344 //rename dll if necessary (i.e. OLE32 -> OLE32OS2)
1345 Win32DllBase::renameDll(modname);
1346
1347 if(isPEImage(modname) != ERROR_SUCCESS_W)
1348 {//LX image, so let OS/2 do all the work for us
1349 APIRET rc;
1350 char szModuleFailure[CCHMAXPATH] = "";
1351 ULONG hInstanceNewDll;
1352
1353 char *dot = strchr(modname, '.');
1354 if(dot) {
1355 *dot = 0;
1356 }
1357 strcat(modname, ".DLL");
1358 rc = DosLoadModule(szModuleFailure, sizeof(szModuleFailure), modname, (HMODULE *)&hInstanceNewDll);
1359 if(rc) {
1360 dprintf((LOG, "DosLoadModule returned %X for %s\n", rc, szModuleFailure));
1361 sprintf(szErrorModule, "%s.DLL", szModuleFailure);
1362 errorState = rc;
1363 return(FALSE);
1364 }
1365 WinDll = (Win32PeLdrDll *)Win32DllBase::findModule(hInstanceNewDll);
1366 if(WinDll == NULL) {//shouldn't happen!
1367 dprintf((LOG, "Just loaded the dll, but can't find it anywhere?!!?"));
1368 errorState = ERROR_INTERNAL;
1369 return(FALSE);
1370 }
1371 //Mark this dll as loaded by DosLoadModule
1372 WinDll->setLoadLibrary();
1373 WinDll->AddRef();
1374 }
1375 else {
1376 WinDll = new Win32PeLdrDll(modname, this);
1377
1378 if(WinDll == NULL) {
1379 dprintf((LOG, "WinDll: Error allocating memory" ));
1380 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szMemErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
1381 errorState = ERROR_INTERNAL;
1382 return(FALSE);
1383 }
1384 dprintf((LOG, "**********************************************************************" ));
1385 dprintf((LOG, "********************** Loading Module *********************" ));
1386 dprintf((LOG, "**********************************************************************" ));
1387 if(WinDll->init(0) == FALSE) {
1388 dprintf((LOG, "Internal WinDll error ", WinDll->getError() ));
1389 return(FALSE);
1390 }
1391#ifdef DEBUG
1392 WinDll->AddRef(getModuleName());
1393#else
1394 WinDll->AddRef();
1395#endif
1396 if(WinDll->attachProcess() == FALSE) {
1397 dprintf((LOG, "attachProcess failed!" ));
1398 delete WinDll;
1399 errorState = ERROR_INTERNAL;
1400 return(FALSE);
1401 }
1402 }
1403
1404 dprintf((LOG, "**********************************************************************" ));
1405 dprintf((LOG, "********************** Finished Loading Module *********************" ));
1406 dprintf((LOG, "**********************************************************************" ));
1407 }
1408 else {
1409 if(WinDll->isLxDll() && !WinDll->isLoaded()) {
1410 //can happen with i.e. wininet
1411 //wininet depends on wsock32; when the app loads wsock32 afterwards
1412 //with LoadLibrary or as a child of another dll, we need to make
1413 //sure it's loaded once with DosLoadModule
1414 WinDll->loadLibrary();
1415 }
1416 WinDll->AddRef();
1417
1418 dprintf((LOG, "Already found ", pszCurModule));
1419 }
1420 //add the dll we just loaded to dependency list for this image
1421 addDependency((Win32DllBase *)WinDll);
1422
1423 //Make sure the dependency list is correct (already done
1424 //in the ctor of Win32DllBase, but for LX dlls the parent is
1425 //then set to NULL; so change it here again
1426 WinDll->setUnloadOrder(this);
1427
1428 pulImport = (PULONG)((ULONG)pulImport + (ULONG)win32file);
1429 j = 0;
1430 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)win32file;
1431
1432 section = findSectionByOS2Addr(ulCurFixup);
1433 if(section == NULL) {
1434 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1435 return FALSE;
1436 }
1437 //SvL: Read page from disk
1438 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1439 //SvL: Enable write access
1440 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1441 nrPages = 1;
1442
1443 while (pulImport[j] != 0) {
1444 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1445 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1446 StoreImportByOrd(WinDll, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1447 }
1448 else { //name
1449 //check
1450 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1451 if (!GetSectionHdrByRVA(win32file, &shExtra, pulImport[j]))
1452 {
1453 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1454 break;
1455 }
1456 }
1457 //KSO - Aug 6 1998 1:15am:this eases comparing...
1458 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)win32file + 2);
1459 dprintf((LOG, "0x%08x Imported function %s", ulCurFixup, pszFunctionName ));
1460 StoreImportByName(WinDll, pszFunctionName, ulCurFixup);
1461 }
1462 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1463 j++;
1464 if((ulCurFixup & 0xfff) == 0) {
1465 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1466 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1467 nrPages++;
1468 }
1469 }
1470 //SvL: And restore original protection flags
1471 ulCurFixup = (ULONG)pID[i].FirstThunk + pOH->ImageBase;
1472 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1473
1474 dprintf((LOG, "**********************************************************************" ));
1475 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1476 dprintf((LOG, "**********************************************************************" ));
1477
1478 pszCurModule += strlen(pszCurModule) + 1;
1479 }//for (i = 0; i < cModules; i++)
1480
1481 free(pszModules);
1482 return TRUE;
1483}
1484//******************************************************************************
1485//******************************************************************************
1486BOOL Win32PeLdrImage::insideModule(ULONG address)
1487{
1488 if((address >= realBaseAddress) && (address < realBaseAddress + imageSize)) {
1489 return TRUE;
1490 }
1491 return FALSE;
1492}
1493//******************************************************************************
1494//******************************************************************************
1495BOOL Win32PeLdrImage::insideModuleCode(ULONG address)
1496{
1497 Section *sect;
1498
1499 sect = findSectionByOS2Addr(address);
1500 if(sect && (sect->pageflags & PAG_EXECUTE)) {
1501 return TRUE;
1502 }
1503 return FALSE;
1504}
1505//******************************************************************************
1506//******************************************************************************
1507ULONG Win32PeLdrImage::getImageSize()
1508{
1509 return imageSize;
1510}
1511//******************************************************************************
1512//******************************************************************************
1513ULONG Win32PeLdrImage::getApi(char *name)
1514{
1515 ULONG apiaddr, i, apilen;
1516 char *apiname;
1517 char tmp[4];
1518 NameExport *curexport;
1519 ULONG ulAPIOrdinal; /* api requested by ordinal */
1520
1521 apilen = strlen(name) + 1;
1522 if(apilen < 4)
1523 {
1524 *(ULONG *)tmp = 0;
1525 strcpy(tmp, name);
1526 apiname = tmp;
1527 apilen = 4;
1528 }
1529 else apiname = name;
1530
1531 curexport = nameexports;
1532 for(i=0; i<nrNameExports; i++)
1533 {
1534 if(apilen == curexport->nlength &&
1535 *(ULONG *)curexport->name == *(ULONG *)apiname)
1536 {
1537 if(strcmp(curexport->name, apiname) == 0)
1538 return(curexport->virtaddr);
1539 }
1540 curexport = (NameExport *)((ULONG)curexport->name + curexport->nlength);
1541 }
1542 return(0);
1543}
1544//******************************************************************************
1545//******************************************************************************
1546ULONG Win32PeLdrImage::getApi(int ordinal)
1547{
1548 ULONG apiaddr, i;
1549 OrdExport *curexport;
1550 NameExport *nexport;
1551
1552 curexport = ordexports;
1553 for(i=0;i<nrOrdExports;i++) {
1554 if(curexport->ordinal == ordinal)
1555 return(curexport->virtaddr);
1556 curexport++;
1557 }
1558 //Name exports also contain an ordinal, so check this
1559 nexport = nameexports;
1560 for(i=0;i<nrNameExports;i++) {
1561 if(nexport->ordinal == ordinal)
1562 return(nexport->virtaddr);
1563
1564 nexport = (NameExport *)((ULONG)nexport->name + nexport->nlength);
1565 }
1566 return(0);
1567}
1568//******************************************************************************
1569//Returns required OS version for this image
1570//******************************************************************************
1571ULONG Win32PeLdrImage::getVersion()
1572{
1573 return (oh.MajorOperatingSystemVersion << 16) | oh.MinorOperatingSystemVersion;
1574}
1575//******************************************************************************
1576//******************************************************************************
1577ULONG MissingApi()
1578{
1579 static BOOL fIgnore = FALSE;
1580 int r;
1581
1582 dprintf((LOG, "Missing api called!\n"));
1583 if(fIgnore)
1584 return(0);
1585
1586 do {
1587 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, "The application has called a non-existing api\n",
1588 "Internal Odin Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
1589 }
1590 while(r == MBID_RETRY); //giggle
1591
1592 if( r != MBID_IGNORE )
1593 ExitProcess(987);
1594
1595 fIgnore = TRUE;
1596 return(0);
1597}
1598/******************************************************************************/
1599/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.