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

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

GetFileAttributes, pe loader & command line fixes

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