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

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

search in path for dlls if not found

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