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

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

mutex fixes + added vsemaphore class

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