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

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

Fixed bug in commitPage (winimagepeldr.cpp)

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