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

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

dprintf2's for cursor/icon conversion

File size: 53.0 KB
Line 
1/* $Id: winimagepeldr.cpp,v 1.27 1999-12-29 12:39:09 sandervl Exp $ */
2
3/*
4 * Win32 PE loader Image base class
5 *
6 * Copyright 1998-1999 Sander van Leeuwen (sandervl@xs4all.nl)
7 * Copyright 1998 Knut St. Osmundsen
8 *
9 * Project Odin Software License can be found in LICENSE.TXT
10 *
11 * TODO: Check psh[i].Characteristics for more than only the code section
12 *
13 * NOTE: RSRC_LOAD is a special flag to only load the resource directory
14 * of a PE image. Processing imports, sections etc is not done.
15 * Nor is it put into the linked list of dlls (if it's a dll).
16 * This is useful for GetVersionSize/Resource in case it wants to
17 * get version info of an image that is not loaded.
18 * So an instance of this type can't be used for anything but resource lookup!
19 *
20 */
21
22#define INCL_DOSFILEMGR /* File Manager values */
23#define INCL_DOSMODULEMGR
24#define INCL_DOSERRORS /* DOS Error values */
25#define INCL_DOSPROCESS /* DOS Process values */
26#define INCL_DOSMISC /* DOS Miscellanous values */
27#define INCL_WIN
28#define INCL_BASE
29#include <os2wrap.h> //Odin32 OS/2 api wrappers
30
31#include <stdio.h>
32#include <string.h>
33#include <stdlib.h>
34
35#include <assert.h>
36//use a different logfile
37#define PRIVATE_LOGGING
38#include <misc.h>
39#include <win32type.h>
40#include <winimagebase.h>
41#include <winimagepeldr.h>
42#include <windllpeldr.h>
43#include <pefile.h>
44#include <unicode.h>
45#include <winres.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#ifndef max
68#define max(a, b) ((a>b) ? a : b)
69#endif
70
71static FILE *_privateLogFile = NULL;
72
73ULONG MissingApi();
74extern ULONG flAllocMem; /*Tue 03.03.1998: knut */
75
76//******************************************************************************
77//******************************************************************************
78void OpenPrivateLogFilePE()
79{
80 char logname[CCHMAXPATH];
81
82 sprintf(logname, "pe_%d.log", loadNr);
83 _privateLogFile = fopen(logname, "w");
84 if(_privateLogFile == NULL) {
85 sprintf(logname, "%spe_%d.log", kernel32Path, loadNr);
86 _privateLogFile = fopen(logname, "w");
87 }
88 dprintfGlobal(("PE LOGFILE : %s", logname));
89}
90//******************************************************************************
91//******************************************************************************
92void ClosePrivateLogFilePE()
93{
94 if(_privateLogFile) {
95 fclose(_privateLogFile);
96 _privateLogFile = NULL;
97 }
98}
99//******************************************************************************
100//******************************************************************************
101Win32PeLdrImage::Win32PeLdrImage(char *pszFileName, BOOL isExe, int loadtype) :
102 Win32ImageBase(-1),
103 nrsections(0), imageSize(0),
104 imageVirtBase(-1), realBaseAddress(0), imageVirtEnd(0),
105 nrNameExports(0), nrOrdExports(0), nameexports(NULL), ordexports(NULL),
106 memmap(NULL), pFixups(NULL)
107{
108 HFILE dllfile;
109
110 loadType = loadtype;
111
112 strcpy(szFileName, pszFileName);
113 strupr(szFileName);
114 if(isExe) {
115 if(!strchr(szFileName, '.')) {
116 strcat(szFileName,".EXE");
117 }
118 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
119 if(dllfile == NULL) {
120 if(!strstr(szFileName, ".EXE")) {
121 strcat(szFileName,".EXE");
122 }
123 }
124 else OSLibDosClose(dllfile);
125 }
126 else {
127 if(!strchr(szFileName, '.')) {
128 strcat(szFileName,".DLL");
129 }
130 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
131 if(dllfile == NULL) {//search in libpath for dll
132 strcpy(szModule, kernel32Path);
133 strcat(szModule, szFileName);
134 strcpy(szFileName, szModule);
135
136 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
137 if(dllfile == NULL) {
138 if(!strstr(szFileName, ".DLL")) {
139 strcat(szFileName,".DLL");
140 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
141 if(dllfile == NULL) {
142 strcpy(szModule, kernel32Path);
143 strcat(szModule, szFileName);
144 strcpy(szFileName, szModule);
145 }
146 else OSLibDosClose(dllfile);
147 }
148 }
149 else OSLibDosClose(dllfile);
150 }
151 else OSLibDosClose(dllfile);
152 }
153 strcpy(szModule, OSLibStripPath(szFileName));
154 strupr(szModule);
155 char *dot = strstr(szModule, ".");
156 while(dot) {
157 char *newdot = strstr(dot+1, ".");
158 if(newdot == NULL) break;
159 dot = newdot;
160 }
161 if(dot)
162 *dot = 0;
163}
164//******************************************************************************
165//******************************************************************************
166Win32PeLdrImage::~Win32PeLdrImage()
167{
168 if(memmap)
169 delete memmap;
170
171 if(hFile) {
172 OSLibDosClose(hFile);
173 hFile = 0;
174 }
175
176 if(realBaseAddress)
177 DosFreeMem((PVOID)realBaseAddress);
178
179 if(nameexports)
180 free(nameexports);
181
182 if(ordexports)
183 free(ordexports);
184}
185//******************************************************************************
186//******************************************************************************
187BOOL Win32PeLdrImage::init(ULONG reservedMem)
188{
189 LPVOID win32file = NULL;
190 ULONG filesize, ulRead, ulNewPos;
191 PIMAGE_SECTION_HEADER psh;
192 IMAGE_SECTION_HEADER sh;
193 IMAGE_TLS_DIRECTORY *tlsDir = NULL;
194 int nSections, i;
195 char szFullPath[CCHMAXPATH] = "";
196 IMAGE_DOS_HEADER doshdr;
197 ULONG signature;
198
199 hFile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
200
201 //default error:
202 strcpy(szErrorModule, OSLibStripPath(szFileName));
203 if(hFile == NULL) {
204 goto failure;
205 }
206 //read dos header
207 if(DosRead(hFile, (LPVOID)&doshdr, sizeof(doshdr), &ulRead)) {
208 goto failure;
209 }
210 if(OSLibDosSetFilePtr(hFile, doshdr.e_lfanew, OSLIB_SETPTR_FILE_BEGIN) == -1) {
211 goto failure;
212 }
213 //read signature dword
214 if(DosRead(hFile, (LPVOID)&signature, sizeof(signature), &ulRead)) {
215 goto failure;
216 }
217 //read pe header
218 if(DosRead(hFile, (LPVOID)&fh, sizeof(fh), &ulRead)) {
219 goto failure;
220 }
221 //read optional header
222 if(DosRead(hFile, (LPVOID)&oh, sizeof(oh), &ulRead)) {
223 goto failure;
224 }
225 if(doshdr.e_magic != IMAGE_DOS_SIGNATURE || signature != IMAGE_NT_SIGNATURE) {
226 dprintf((LOG, "Not a valid PE file (probably a 16 bits windows exe/dll)!"));
227 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szPEErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
228 goto failure;
229 }
230
231 if(oh.SizeOfImage == 0) {//just in case
232 oh.SizeOfImage = OSLibDosGetFileSize(hFile);
233 }
234
235 imageSize = oh.SizeOfImage;
236 //Allocate memory to hold the entire image
237 if(allocSections(reservedMem) == FALSE) {
238 dprintf((LOG, "Failed to allocate image memory, rc %d", errorState));;
239 goto failure;
240 }
241
242 memmap = new Win32MemMap(this, realBaseAddress, imageSize);
243 if(memmap == NULL || !memmap->Init(0)) {
244 goto failure;
245 }
246 win32file = memmap->mapViewOfFile(0, 0, 2);
247
248 if(DosQueryPathInfo(szFileName, FIL_QUERYFULLNAME, szFullPath, sizeof(szFullPath)) == 0) {
249 setFullPath(szFullPath);
250 }
251
252 if(!(fh.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) {//not valid
253 dprintf((LOG, "Not a valid PE file!"));
254 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szPEErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
255 goto failure;
256 }
257 if(fh.Machine != IMAGE_FILE_MACHINE_I386) {
258 dprintf((LOG, "Doesn't run on x86 processors!"));
259 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szCPUErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
260 goto failure;
261 }
262 //IMAGE_FILE_SYSTEM == only drivers (device/file system/video etc)?
263 if(fh.Characteristics & IMAGE_FILE_SYSTEM) {
264 dprintf((LOG, "Can't convert system files"));
265 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szExeErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
266 goto failure;
267 }
268
269 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
270 dprintf((LOG, "No fixups, might not run!"));
271 }
272
273 dprintf((LOG, "PE file : %s", szFileName));
274 dprintf((LOG, "PE Optional header: "));
275 dprintf((LOG, "Preferred address : %d", oh.ImageBase ));
276 dprintf((LOG, "Base Of Code : %d", oh.BaseOfCode ));
277 dprintf((LOG, "CodeSize : %d", oh.SizeOfCode ));
278 dprintf((LOG, "Base Of Data : %d", oh.BaseOfData ));
279 dprintf((LOG, "Data Size (uninit): %d", oh.SizeOfUninitializedData ));
280 dprintf((LOG, "Data Size (init) : %d", oh.SizeOfInitializedData ));
281 dprintf((LOG, "Entry Point : %d", oh.AddressOfEntryPoint ));
282 dprintf((LOG, "Section Alignment : %d", oh.SectionAlignment ));
283 dprintf((LOG, "Stack Reserve size: %d", oh.SizeOfStackReserve ));
284 dprintf((LOG, "Stack Commit size : %d", oh.SizeOfStackCommit ));
285 dprintf((LOG, "SizeOfHeapReserve : %d", oh.SizeOfHeapReserve ));
286 dprintf((LOG, "SizeOfHeapCommit : %d", oh.SizeOfHeapCommit ));
287 dprintf((LOG, "FileAlignment : %d", oh.FileAlignment ));
288 dprintf((LOG, "Subsystem : %d", oh.Subsystem ));
289 dprintf((LOG, "Image Size : %d", oh.SizeOfImage ));
290 dprintf((LOG, "Header Size : %d", oh.SizeOfHeaders ));
291 dprintf((LOG, "MajorImageVersion : %d", oh.MajorImageVersion ));
292 dprintf((LOG, "MinorImageVersion : %d", oh.MinorImageVersion ));
293
294 //get header page
295 commitPage(realBaseAddress, FALSE);
296
297 nSections = NR_SECTIONS(win32file);
298
299 if(loadType == REAL_LOAD)
300 {
301 imageSize = 0;
302 if ((psh = (PIMAGE_SECTION_HEADER)SECTIONHDROFF (win32file)) != NULL) {
303 dprintf((LOG, "*************************PE SECTIONS START**************************" ));
304 for (i=0; i<nSections; i++) {
305 dprintf((LOG, "Raw data size: %x", psh[i].SizeOfRawData ));
306 dprintf((LOG, "Virtual Address: %x", psh[i].VirtualAddress ));
307 dprintf((LOG, "Virtual Address Start:%x", psh[i].VirtualAddress+oh.ImageBase ));
308 dprintf((LOG, "Virtual Address End: %x", psh[i].VirtualAddress+oh.ImageBase+psh[i].Misc.VirtualSize ));
309 dprintf((LOG, "Virtual Size: %x", psh[i].Misc.VirtualSize ));
310 dprintf((LOG, "Pointer to raw data: %x", psh[i].PointerToRawData ));
311 dprintf((LOG, "Section flags: %x\n\n", psh[i].Characteristics ));
312 if(strcmp(psh[i].Name, ".reloc") == 0) {
313 dprintf((LOG, ".reloc" ));
314 addSection(SECTION_RELOC, psh[i].PointerToRawData,
315 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
316 psh[i].Misc.VirtualSize, psh[i].Characteristics);
317 continue;
318 }
319 if(strcmp(psh[i].Name, ".edata") == 0) {
320 dprintf((LOG, ".edata" ));
321 addSection(SECTION_EXPORT, psh[i].PointerToRawData,
322 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
323 psh[i].Misc.VirtualSize, psh[i].Characteristics);
324 continue;
325 }
326 if(strcmp(psh[i].Name, ".rsrc") == 0) {
327 dprintf((LOG, ".rsrc" ));
328 addSection(SECTION_RESOURCE, 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(strcmp(psh[i].Name, ".tls") == 0)
334 {
335 tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_TLS);
336 if(tlsDir) {
337 addSection(SECTION_TLS, psh[i].PointerToRawData,
338 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
339 psh[i].Misc.VirtualSize, psh[i].Characteristics);
340 }
341 continue;
342 }
343
344 if(strcmp(psh[i].Name, ".debug") == 0) {
345 dprintf((LOG, ".rdebug" ));
346 addSection(SECTION_DEBUG, psh[i].PointerToRawData,
347 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
348 psh[i].Misc.VirtualSize, psh[i].Characteristics);
349 continue;
350 }
351 if(IsImportSection(win32file, &psh[i]))
352 {
353 int type = SECTION_IMPORT;
354 dprintf((LOG, "Import Data Section" ));
355 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE) {
356 dprintf((LOG, "Also Code Section"));
357 type |= SECTION_CODE;
358 }
359 addSection(type, psh[i].PointerToRawData,
360 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
361 psh[i].Misc.VirtualSize, psh[i].Characteristics);
362 continue;
363 }
364
365 //KSO Sun 1998-08-09: Borland does not alway set the CODE flag for its "CODE" section
366 if( psh[i].Characteristics & IMAGE_SCN_CNT_CODE ||
367 (psh[i].Characteristics & IMAGE_SCN_MEM_EXECUTE &&
368 !(psh[i].Characteristics & (IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_CNT_INITIALIZED_DATA))) //KSO: make sure its not marked as a datasection
369 )
370 {
371 dprintf((LOG, "Code Section"));
372 addSection(SECTION_CODE, psh[i].PointerToRawData,
373 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
374 psh[i].Misc.VirtualSize, psh[i].Characteristics);
375 continue;
376 }
377 if(!(psh[i].Characteristics & IMAGE_SCN_MEM_WRITE)) { //read only data section
378 dprintf((LOG, "Read Only Data Section" ));
379 addSection(SECTION_READONLYDATA, psh[i].PointerToRawData,
380 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
381 psh[i].Misc.VirtualSize, psh[i].Characteristics);
382 continue;
383 }
384 if(psh[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
385 dprintf((LOG, "Uninitialized Data Section" ));
386 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
387 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
388 psh[i].Misc.VirtualSize, psh[i].Characteristics);
389 continue;
390 }
391 if(psh[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) {
392 dprintf((LOG, "Initialized Data Section" ));
393 addSection(SECTION_INITDATA, psh[i].PointerToRawData,
394 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
395 psh[i].Misc.VirtualSize, psh[i].Characteristics);
396 continue;
397 }
398 if(psh[i].Characteristics & (IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ)) {
399 dprintf((LOG, "Other Section, stored as read/write uninit data" ));
400 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
401 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
402 psh[i].Misc.VirtualSize, psh[i].Characteristics);
403 continue;
404 }
405 dprintf((LOG, "Unknown section" ));
406 goto failure;
407 }
408 }
409 }
410 else {
411 if(GetSectionHdrByName (win32file, &sh, ".rsrc"))
412 {
413 addSection(SECTION_RESOURCE, sh.PointerToRawData,
414 sh.SizeOfRawData, sh.VirtualAddress + oh.ImageBase,
415 sh.Misc.VirtualSize, sh.Characteristics);
416 }
417 }
418 dprintf((LOG, "*************************PE SECTIONS END **************************" ));
419 imageSize += imageVirtBase - oh.ImageBase;
420 dprintf((LOG, "Total size of Image %x", imageSize ));
421 dprintf((LOG, "imageVirtBase %x", imageVirtBase ));
422 dprintf((LOG, "imageVirtEnd %x", imageVirtEnd ));
423
424 //In case there are any gaps between sections, adjust size
425 if(imageSize != imageVirtEnd - oh.ImageBase) {
426 dprintf((LOG, "imageSize != imageVirtEnd - oh.ImageBase!" ));
427 imageSize = imageVirtEnd - oh.ImageBase;
428 }
429 if(imageSize < oh.SizeOfImage) {
430 imageSize = oh.SizeOfImage;
431 }
432
433 dprintf((LOG, "OS/2 base address %x", realBaseAddress ));
434 if(oh.AddressOfEntryPoint) {
435 entryPoint = realBaseAddress + oh.AddressOfEntryPoint;
436 }
437 else {
438 dprintf((LOG, "EntryPoint == NULL" ));
439 entryPoint = NULL;
440 }
441
442 //set memory protection flags
443 if(setMemFlags() == FALSE) {
444 dprintf((LOG, "Failed to set memory protection" ));
445 goto failure;
446 }
447
448 if(loadType == REAL_LOAD)
449 {
450 if(tlsDir != NULL) {
451 Section *sect = findSection(SECTION_TLS);
452
453 if(sect == NULL) {
454 dprintf((LOG, "Couldn't find TLS section!!" ));
455 goto failure;
456 }
457 dprintf((LOG, "TLS Directory" ));
458 dprintf((LOG, "TLS Address of Index %x", tlsDir->AddressOfIndex ));
459 dprintf((LOG, "TLS Address of Callbacks %x", tlsDir->AddressOfCallBacks ));
460 dprintf((LOG, "TLS SizeOfZeroFill %x", tlsDir->SizeOfZeroFill ));
461 dprintf((LOG, "TLS Characteristics %x", tlsDir->Characteristics ));
462 setTLSAddress((char *)sect->realvirtaddr);
463 setTLSInitSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData);
464 setTLSTotalSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData + tlsDir->SizeOfZeroFill);
465
466 sect = findSectionByAddr((ULONG)tlsDir->AddressOfIndex);
467 if(sect == NULL) {
468 dprintf((LOG, "Couldn't find TLS AddressOfIndex section!!" ));
469 goto failure;
470 }
471 setTLSIndexAddr((LPDWORD)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfIndex - sect->virtaddr)));
472
473 if((ULONG)tlsDir->AddressOfCallBacks != 0) {
474 sect = findSectionByAddr((ULONG)tlsDir->AddressOfCallBacks);
475 if(sect == NULL) {
476 dprintf((LOG, "Couldn't find TLS AddressOfCallBacks section!!" ));
477 goto failure;
478 }
479 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfCallBacks - sect->virtaddr)));
480 }
481 }
482
483 if(realBaseAddress != oh.ImageBase) {
484 pFixups = (PIMAGE_BASE_RELOCATION)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_BASERELOC);
485 commitPage((ULONG)pFixups, FALSE);
486 }
487#ifdef COMMIT_ALL
488 for (i=0; i<nSections; i++) {
489 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
490 }
491#else
492 for (i=0; i<nSections; i++) {
493 switch(section[i].type)
494 {
495 case SECTION_IMPORT:
496 case SECTION_RELOC:
497 case SECTION_EXPORT:
498 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
499 break;
500 }
501 }
502#endif
503 if(processExports((char *)win32file) == FALSE) {
504 dprintf((LOG, "Failed to process exported apis" ));
505 goto failure;
506 }
507 }
508#ifdef COMMIT_ALL
509 else {
510 commitPage((ULONG)section[0].realvirtaddr, FALSE, COMPLETE_SECTION);
511 }
512#endif
513
514 //SvL: Use pointer to image header as module handle now. Some apps needs this
515 hinstance = (HINSTANCE)realBaseAddress;
516
517 //SvL: Set instance handle in process database structure
518 SetPDBInstance(hinstance);
519
520 //PH: get pResDir pointer correct first, since processImports may
521 // implicitly call functions depending on it.
522 if(GetSectionHdrByName (win32file, &sh, ".rsrc")) {
523 //get offset in resource object of directory entry
524 pResDir = (PIMAGE_RESOURCE_DIRECTORY)(sh.VirtualAddress + realBaseAddress);
525 ulRVAResourceSection = sh.VirtualAddress;
526 }
527
528 if (loadType == REAL_LOAD)
529 {
530 if(processImports((char *)win32file) == FALSE) {
531 dprintf((LOG, "Failed to process imports!" ));
532 goto failure;
533 }
534 }
535
536 return(TRUE);
537failure:
538 if(memmap) {
539 delete memmap;
540 memmap = NULL;
541 }
542 if(hFile) {
543 OSLibDosClose(hFile);
544 hFile = 0;
545 }
546 errorState = ERROR_INTERNAL;
547 return FALSE;
548}
549//******************************************************************************
550//commits image page(s) when an access violation exception is dispatched
551//virtAddress = address of exception (rounded down to page boundary)
552//******************************************************************************
553BOOL Win32PeLdrImage::commitPage(ULONG virtAddress, BOOL fWriteAccess, int fPageCmd)
554{
555 Section *section;
556 ULONG offset, size, sectionsize, protflags, fileoffset, range, attr;
557 ULONG ulNewPos, ulRead;
558 APIRET rc;
559
560 rc = DosQueryMem((PVOID)virtAddress, &range, &attr);
561 if(rc) {
562 dprintf((LOG, "Win32PeLdrImage::commitPage: DosQueryMem for %x returned %d", virtAddress, rc));
563 return FALSE;
564 }
565 if(attr & PAG_COMMIT) {
566 dprintf((LOG, "Win32PeLdrImage::commitPage: Memory at 0x%x already committed!", virtAddress));
567 return FALSE;
568 }
569
570 section = findSectionByOS2Addr(virtAddress);
571 if(section == NULL) {
572 size = 4096;
573 sectionsize = 4096;
574 protflags = PAG_READ|PAG_WRITE; //readonly?
575 section = findPreviousSectionByOS2Addr(virtAddress);
576 if(section == NULL) {//access to header
577 fileoffset = virtAddress - realBaseAddress;
578 }
579 else {
580 offset = virtAddress - (section->realvirtaddr + section->virtualsize);
581 fileoffset = section->rawoffset + section->rawsize + offset;
582 }
583 }
584 else {
585 protflags = section->pageflags;
586 offset = virtAddress - section->realvirtaddr;
587 sectionsize = section->virtualsize - offset;
588 if(offset > section->rawsize || section->type == SECTION_UNINITDATA) {
589 //unintialized data (set to 0)
590 size = 0;
591 fileoffset = -1;
592 }
593 else {
594 size = section->rawsize-offset;
595 fileoffset = section->rawoffset + offset;
596 }
597 if(fWriteAccess & !(section->pageflags & PAG_WRITE)) {
598 dprintf((LOG, "Win32PeLdrImage::commitPage: No write access to 0%x!", virtAddress));
599 return FALSE;
600 }
601 }
602 if(fPageCmd == SINGLE_PAGE) {
603 size = min(size, PAGE_SIZE);
604 sectionsize = min(sectionsize, PAGE_SIZE);
605 }
606 else
607 if(fPageCmd == SECTION_PAGES) {
608 size = min(size, DEFAULT_NR_PAGES*PAGE_SIZE);
609 sectionsize = min(sectionsize, DEFAULT_NR_PAGES*PAGE_SIZE);
610 }
611 size = min(size, range);
612 sectionsize = min(sectionsize, range);
613
614 if(fileoffset != -1) {
615 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
616 if(rc) {
617 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
618 return FALSE;
619 }
620
621 if(DosSetFilePtr(hFile, fileoffset, FILE_BEGIN, &ulNewPos) == -1) {
622 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetFilePtr failed for 0x%x!", fileoffset));
623 return FALSE;
624 }
625 if(DosRead(hFile, (PVOID)virtAddress, size, &ulRead)) {
626 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed for 0x%x!", virtAddress));
627 return FALSE;
628 }
629 if(ulRead != size) {
630 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed to read %x (%x) bytes at %x for 0x%x!", size, ulRead, fileoffset, virtAddress));
631 return FALSE;
632 }
633 if(realBaseAddress != oh.ImageBase) {
634 setFixups(virtAddress, sectionsize);
635 }
636
637 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
638 if(rc) {
639 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
640 return FALSE;
641 }
642 }
643 else {
644 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
645 if(rc) {
646 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
647 return FALSE;
648 }
649 if(realBaseAddress != oh.ImageBase) {
650 setFixups(virtAddress, sectionsize);
651 }
652 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
653 if(rc) {
654 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
655 return FALSE;
656 }
657 }
658 return TRUE;
659}
660//******************************************************************************
661//******************************************************************************
662void Win32PeLdrImage::addSection(ULONG type, ULONG rawoffset, ULONG rawsize, ULONG virtaddress, ULONG virtsize, ULONG flags)
663{
664 virtsize = max(rawsize, virtsize);
665
666 section[nrsections].rawoffset = rawoffset;
667 section[nrsections].type = type;
668 section[nrsections].rawsize = rawsize;
669 section[nrsections].virtaddr = virtaddress;
670 section[nrsections].flags = flags;
671
672 virtsize = ((virtsize - 1) & ~0xFFF) + PAGE_SIZE;
673 imageSize += virtsize;
674 section[nrsections].virtualsize = virtsize;
675
676 if(virtaddress < imageVirtBase)
677 imageVirtBase = virtaddress;
678 if(virtaddress + virtsize > imageVirtEnd)
679 imageVirtEnd = virtaddress + virtsize;
680
681 nrsections++;
682}
683//******************************************************************************
684//******************************************************************************
685BOOL Win32PeLdrImage::allocSections(ULONG reservedMem)
686{
687 APIRET rc;
688 ULONG baseAddress;
689
690 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
691 return allocFixedMem(reservedMem);
692 }
693 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | flAllocMem);
694 if(rc) {
695 dprintf((LOG, "Win32PeLdrImage::allocSections, DosAllocMem returned %d", rc));
696 errorState = rc;
697 return(FALSE);
698 }
699 realBaseAddress = baseAddress;
700 return(TRUE);
701}
702//******************************************************************************
703//******************************************************************************
704Section *Win32PeLdrImage::findSection(ULONG type)
705{
706 for(int i=0;i<nrsections;i++) {
707 if(section[i].type == type) {
708 return &section[i];
709 }
710 }
711 return NULL;
712}
713//******************************************************************************
714//******************************************************************************
715Section *Win32PeLdrImage::findSectionByAddr(ULONG addr)
716{
717 for(int i=0;i<nrsections;i++) {
718 if(section[i].virtaddr <= addr && section[i].virtaddr + section[i].virtualsize > addr) {
719 return &section[i];
720 }
721 }
722 return NULL;
723}
724//******************************************************************************
725//******************************************************************************
726Section *Win32PeLdrImage::findSectionByOS2Addr(ULONG addr)
727{
728 for(int i=0;i<nrsections;i++) {
729 if(section[i].realvirtaddr <= addr && section[i].realvirtaddr + section[i].virtualsize > addr) {
730 return &section[i];
731 }
732 }
733 return NULL;
734}
735//******************************************************************************
736//******************************************************************************
737Section *Win32PeLdrImage::findPreviousSectionByOS2Addr(ULONG addr)
738{
739 ULONG lowestAddr = 0xffffffff;
740 ULONG index = -1;
741
742 for(int i=0;i<nrsections;i++) {
743 if(section[i].realvirtaddr > addr) {
744 if(section[i].realvirtaddr < lowestAddr) {
745 lowestAddr = section[i].realvirtaddr;
746 index = i;
747 }
748 }
749 }
750 if(index == -1)
751 return NULL;
752
753 return &section[index];
754}
755//******************************************************************************
756#define FALLOC_SIZE (1024*1024)
757//NOTE: Needs testing (while loop)
758//TODO: Free unused (parts of) reservedMem
759//******************************************************************************
760BOOL Win32PeLdrImage::allocFixedMem(ULONG reservedMem)
761{
762 ULONG address = 0;
763 ULONG *memallocs;
764 ULONG alloccnt = 0;
765 ULONG diff, i, baseAddress;
766 APIRET rc;
767 BOOL allocFlags = flAllocMem;
768
769 realBaseAddress = 0;
770
771 if(reservedMem && reservedMem <= oh.ImageBase &&
772 ((oh.ImageBase - reservedMem) + imageSize < PELDR_RESERVEDMEMSIZE))
773 {
774 //ok, it fits perfectly
775 realBaseAddress = oh.ImageBase;
776 return TRUE;
777 }
778
779 //Reserve enough space to store 4096 pointers to 1MB memory chunks
780 memallocs = (ULONG *)malloc(4096*sizeof(ULONG *));
781 if(memallocs == NULL) {
782 dprintf((LOG, "allocFixedMem: MALLOC FAILED for memallocs" ));
783 return FALSE;
784 }
785
786 if(oh.ImageBase < 512*1024*124) {
787 allocFlags = 0;
788 }
789 while(TRUE) {
790 rc = DosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ | allocFlags);
791 if(rc) break;
792
793 dprintf((LOG, "DosAllocMem returned %x", address ));
794 if(address + FALLOC_SIZE >= oh.ImageBase) {
795 if(address > oh.ImageBase) {//we've passed it!
796 DosFreeMem((PVOID)address);
797 break;
798 }
799 //found the right address
800 DosFreeMem((PVOID)address);
801
802 diff = oh.ImageBase - address;
803 if(diff) {
804 rc = DosAllocMem((PPVOID)&address, diff, PAG_READ | allocFlags);
805 if(rc) break;
806 }
807 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | allocFlags);
808 if(rc) break;
809
810 if(diff) DosFreeMem((PVOID)address);
811
812 realBaseAddress = baseAddress;
813 break;
814 }
815 memallocs[alloccnt++] = address;
816 }
817 for(i=0;i<alloccnt;i++) {
818 DosFreeMem((PVOID)memallocs[i]);
819 }
820 free(memallocs);
821
822 if(realBaseAddress == 0) //Let me guess.. MS Office app?
823 return(FALSE);
824
825 return(TRUE);
826}
827//******************************************************************************
828//******************************************************************************
829BOOL Win32PeLdrImage::setMemFlags()
830{
831 int i;
832 WINIMAGE_LOOKUP *imgLookup;
833
834 imgLookup = WINIMAGE_LOOKUPADDR(realBaseAddress);
835 imgLookup->magic1 = MAGIC_WINIMAGE;
836 imgLookup->image = this;
837 imgLookup->magic2 = MAGIC_WINIMAGE;
838
839 // Process all the image sections
840 for(i=0;i<nrsections;i++) {
841 section[i].realvirtaddr = realBaseAddress + (section[i].virtaddr - oh.ImageBase);
842 }
843
844 for(i=0;i<nrsections;i++) {
845 switch(section[i].type)
846 {
847 case SECTION_CODE:
848 case (SECTION_CODE | SECTION_IMPORT):
849 section[i].pageflags = PAG_EXECUTE | PAG_READ;
850 if(section[i].flags & IMAGE_SCN_MEM_WRITE)
851 section[i].pageflags |= PAG_WRITE;
852 break;
853 case SECTION_INITDATA:
854 case SECTION_UNINITDATA:
855 case SECTION_IMPORT: //TODO: read only?
856 section[i].pageflags = PAG_WRITE | PAG_READ;
857 break;
858 case SECTION_READONLYDATA:
859 case SECTION_RESOURCE:
860 case SECTION_TLS:
861 default:
862 section[i].pageflags = PAG_READ;
863 break;
864 }
865 }
866 return(TRUE);
867}
868//******************************************************************************
869//******************************************************************************
870BOOL Win32PeLdrImage::setFixups(ULONG virtAddress, ULONG size)
871{
872 int i, j;
873 char *page;
874 ULONG count, newpage;
875 Section *section;
876 PIMAGE_BASE_RELOCATION prel = pFixups;
877
878 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
879 return(TRUE);
880 }
881
882 virtAddress -= realBaseAddress;
883
884 if(prel) {
885 j = 1;
886 while(prel->VirtualAddress && prel->VirtualAddress < virtAddress) {
887 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
888 }
889 while(prel->VirtualAddress && prel->VirtualAddress < virtAddress + size) {
890 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
891 count = (prel->SizeOfBlock - 8)/2;
892 j++;
893 for(i=0;i<count;i++) {
894 int type = prel->TypeOffset[i] >> 12;
895 int offset = prel->TypeOffset[i] & 0xFFF;
896 int fixupsize = 0;
897
898 switch(type)
899 {
900 case IMAGE_REL_BASED_HIGHLOW:
901 fixupsize = 4;
902 break;
903 case IMAGE_REL_BASED_HIGH:
904 case IMAGE_REL_BASED_LOW:
905 fixupsize = 2;
906 break;
907 }
908 //If the fixup crosses the final page boundary,
909 //then we have to load another page
910 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
911 {
912 newpage = realBaseAddress + prel->VirtualAddress + offset + fixupsize;
913 newpage &= ~0xFFF;
914
915 section = findSectionByOS2Addr(newpage);
916 if(section == NULL) {
917 //should never happen
918 dprintf((LOG, "::setFixups -> section == NULL!!"));
919 return FALSE;
920 }
921 //SvL: Read page from disk
922 commitPage(newpage, FALSE, SINGLE_PAGE);
923
924 //SvL: Enable write access
925 DosSetMem((PVOID)newpage, PAGE_SIZE, PAG_READ|PAG_WRITE);
926 }
927
928 switch(type)
929 {
930 case IMAGE_REL_BASED_ABSOLUTE:
931 break; //skip
932 case IMAGE_REL_BASED_HIGHLOW:
933 AddOff32Fixup(prel->VirtualAddress + offset);
934 break;
935 case IMAGE_REL_BASED_HIGH:
936 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
937 break;
938 case IMAGE_REL_BASED_LOW:
939 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
940 break;
941 case IMAGE_REL_BASED_HIGHADJ:
942 case IMAGE_REL_BASED_MIPS_JMPADDR:
943 default:
944 break;
945 }
946 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
947 {
948 //SvL: Restore original page protection flags
949 DosSetMem((PVOID)newpage, PAGE_SIZE, section->pageflags);
950 }
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) == FALSE)
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 }
1372 else {
1373 WinDll = new Win32PeLdrDll(modname, this);
1374
1375 if(WinDll == NULL) {
1376 dprintf((LOG, "WinDll: Error allocating memory" ));
1377 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szMemErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
1378 errorState = ERROR_INTERNAL;
1379 return(FALSE);
1380 }
1381 dprintf((LOG, "**********************************************************************" ));
1382 dprintf((LOG, "********************** Loading Module *********************" ));
1383 dprintf((LOG, "**********************************************************************" ));
1384 if(WinDll->init(0) == FALSE) {
1385 dprintf((LOG, "Internal WinDll error ", WinDll->getError() ));
1386 return(FALSE);
1387 }
1388 if(WinDll->attachProcess() == FALSE) {
1389 dprintf((LOG, "attachProcess failed!" ));
1390 errorState = ERROR_INTERNAL;
1391 return(FALSE);
1392 }
1393 WinDll->AddRef();
1394 }
1395 dprintf((LOG, "**********************************************************************" ));
1396 dprintf((LOG, "********************** Finished Loading Module *********************" ));
1397 dprintf((LOG, "**********************************************************************" ));
1398 }
1399 else dprintf((LOG, "Already found ", pszCurModule ));
1400
1401 WinDll->AddRef();
1402
1403 pulImport = (PULONG)((ULONG)pulImport + (ULONG)win32file);
1404 j = 0;
1405 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)win32file;
1406
1407 section = findSectionByOS2Addr(ulCurFixup);
1408 if(section == NULL) {
1409 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1410 return FALSE;
1411 }
1412 //SvL: Read page from disk
1413 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1414 //SvL: Enable write access
1415 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1416 nrPages = 1;
1417
1418 while (pulImport[j] != 0) {
1419 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1420 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1421 StoreImportByOrd(WinDll, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1422 }
1423 else { //name
1424 //check
1425 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1426 if (!GetSectionHdrByRVA(win32file, &shExtra, pulImport[j]))
1427 {
1428 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1429 break;
1430 }
1431 }
1432 //KSO - Aug 6 1998 1:15am:this eases comparing...
1433 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)win32file + 2);
1434 dprintf((LOG, "0x%08x Imported function %s", ulCurFixup, pszFunctionName ));
1435 StoreImportByName(WinDll, pszFunctionName, ulCurFixup);
1436 }
1437 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1438 j++;
1439 if((ulCurFixup & 0xfff) == 0) {
1440 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1441 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1442 nrPages++;
1443 }
1444 }
1445 //SvL: And restore original protection flags
1446 ulCurFixup = (ULONG)pID[i].FirstThunk + pOH->ImageBase;
1447 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1448
1449 dprintf((LOG, "**********************************************************************" ));
1450 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1451 dprintf((LOG, "**********************************************************************" ));
1452
1453 pszCurModule += strlen(pszCurModule) + 1;
1454 }//for (i = 0; i < cModules; i++)
1455
1456 free(pszModules);
1457 return TRUE;
1458}
1459//******************************************************************************
1460//******************************************************************************
1461ULONG Win32PeLdrImage::getApi(char *name)
1462{
1463 ULONG apiaddr, i, apilen;
1464 char *apiname;
1465 char tmp[4];
1466 NameExport *curexport;
1467 ULONG ulAPIOrdinal; /* api requested by ordinal */
1468
1469 apilen = strlen(name) + 1;
1470 if(apilen < 4)
1471 {
1472 *(ULONG *)tmp = 0;
1473 strcpy(tmp, name);
1474 apiname = tmp;
1475 }
1476 else apiname = name;
1477
1478 curexport = nameexports;
1479 for(i=0; i<nrNameExports; i++)
1480 {
1481 if(apilen == curexport->nlength &&
1482 *(ULONG *)curexport->name == *(ULONG *)name)
1483 {
1484 if(strcmp(curexport->name, name) == 0)
1485 return(curexport->virtaddr);
1486 }
1487 curexport = (NameExport *)((ULONG)curexport->name + curexport->nlength);
1488 }
1489 return(0);
1490}
1491//******************************************************************************
1492//******************************************************************************
1493ULONG Win32PeLdrImage::getApi(int ordinal)
1494{
1495 ULONG apiaddr, i;
1496 OrdExport *curexport;
1497 NameExport *nexport;
1498
1499 curexport = ordexports;
1500 for(i=0;i<nrOrdExports;i++) {
1501 if(curexport->ordinal == ordinal)
1502 return(curexport->virtaddr);
1503 curexport++;
1504 }
1505 //Name exports also contain an ordinal, so check this
1506 nexport = nameexports;
1507 for(i=0;i<nrNameExports;i++) {
1508 if(nexport->ordinal == ordinal)
1509 return(nexport->virtaddr);
1510
1511 nexport = (NameExport *)((ULONG)nexport->name + nexport->nlength);
1512 }
1513 return(0);
1514}
1515//******************************************************************************
1516//Returns required OS version for this image
1517//******************************************************************************
1518ULONG Win32PeLdrImage::getVersion()
1519{
1520 return (oh.MajorOperatingSystemVersion << 16) | oh.MinorOperatingSystemVersion;
1521}
1522//******************************************************************************
1523//******************************************************************************
1524ULONG MissingApi()
1525{
1526 static BOOL fIgnore = FALSE;
1527 int r;
1528
1529 dprintf((LOG, "Missing api called!\n"));
1530 if(fIgnore)
1531 return(0);
1532
1533 do {
1534 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, "The application has called a non-existing api\n",
1535 "Internal Odin Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
1536 }
1537 while(r == MBID_RETRY); //giggle
1538
1539 if( r != MBID_IGNORE )
1540 exit(987);
1541
1542 fIgnore = TRUE;
1543 return(0);
1544}
1545/******************************************************************************/
1546/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.