source: trunk/src/kernel32/winimagepeldr_new.cpp@ 5841

Last change on this file since 5841 was 5841, checked in by phaller, 24 years ago

.

File size: 75.1 KB
Line 
1/* $Id: winimagepeldr_new.cpp,v 1.2 2001-05-30 18:32:15 phaller 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 * TODO: Make resource section readonly when GDI32 is fixed
13 * TODO: Loading of forwarder dlls before handling imports might not be correct
14 * (circular dependencies; have to check what NT does)
15 * TODO: Two LoadLibrary calls in two threads at the same time won't be handled properly (rare but possible)
16 *
17 * NOTE: FLAG_PELDR_LOADASDATAFILE is a special flag to only load the resource directory
18 * of a PE image. Processing imports, sections etc is not done.
19 * This is useful for GetVersionSize/Resource in case it wants to
20 * get version info of an image that is not loaded.
21 * So an instance of this type can't be used for anything but resource lookup!
22 *
23 *
24 */
25#define INCL_DOSFILEMGR /* File Manager values */
26#define INCL_DOSMODULEMGR
27#define INCL_DOSERRORS /* DOS Error values */
28#define INCL_DOSPROCESS /* DOS Process values */
29#define INCL_DOSMISC /* DOS Miscellanous values */
30#define INCL_WIN
31#define INCL_BASE
32#include <os2wrap.h> //Odin32 OS/2 api wrappers
33
34#include <stdio.h>
35#include <string.h>
36#include <stdlib.h>
37
38#include <assert.h>
39//use a different logfile
40#define PRIVATE_LOGGING
41#include <misc.h>
42#include <win32api.h>
43#include "winimagebase.h"
44#include "winimagepeldr.h"
45#include "windllpeldr.h"
46#include "windlllx.h"
47#include "winexebase.h"
48#include <pefile.h>
49#include <unicode.h>
50#include "oslibmisc.h"
51#include "initterm.h"
52#include <win\virtual.h>
53#include "oslibdos.h"
54#include "mmap.h"
55#include <wprocess.h>
56
57#include <ccollection.h>
58
59//Define COMMIT_ALL to let the pe loader commit all sections of the image
60//This is very useful during debugging as you'll get lots of exceptions
61//otherwise.
62//#ifdef DEBUG
63#define COMMIT_ALL
64//#endif
65
66char szErrorTitle[] = "Odin";
67char szMemErrorMsg[] = "Memory allocation failure";
68char szFileErrorMsg[] = "File IO error";
69char szPEErrorMsg[] = "Not a valid win32 exe. (perhaps 16 bits windows)";
70char szCPUErrorMsg[] = "Executable doesn't run on x86 machines";
71char szExeErrorMsg[] = "File isn't an executable";
72char szInteralErrorMsg[]= "Internal Error";
73char szErrorModule[128] = "";
74
75#ifdef DEBUG
76static FILE *_privateLogFile = NULL;
77#endif
78
79ULONG MissingApi();
80
81//******************************************************************************
82//******************************************************************************
83void OpenPrivateLogFilePE()
84{
85#ifdef DEBUG
86 char logname[CCHMAXPATH];
87
88 sprintf(logname, "pe_%d.log", loadNr);
89 _privateLogFile = fopen(logname, "w");
90 if(_privateLogFile == NULL) {
91 sprintf(logname, "%spe_%d.log", kernel32Path, loadNr);
92 _privateLogFile = fopen(logname, "w");
93 }
94 dprintfGlobal(("PE LOGFILE : %s", logname));
95#endif
96}
97//******************************************************************************
98//******************************************************************************
99void ClosePrivateLogFilePE()
100{
101#ifdef DEBUG
102 if(_privateLogFile) {
103 fclose(_privateLogFile);
104 _privateLogFile = NULL;
105 }
106#endif
107}
108//******************************************************************************
109//******************************************************************************
110Win32PeLdrImage::Win32PeLdrImage(char *pszFileName, BOOL isExe) :
111 Win32ImageBase(-1),
112 nrsections(0), imageSize(0), dwFlags(0), section(NULL),
113 imageVirtBase(-1), realBaseAddress(0), imageVirtEnd(0),
114 nrNameExports(0), nrOrdExports(0),
115#ifdef VERIFY_LOADER
116 nameexports(NULL), ordexports(NULL),
117 curnameexport(NULL), curordexport(NULL),
118#endif
119 memmap(NULL), pFixups(NULL), dwFixupSize(0)
120{
121 HFILE dllfile;
122
123 strcpy(szFileName, pszFileName);
124 strupr(szFileName);
125 if(isExe) {
126 if(!strchr(szFileName, '.')) {
127 strcat(szFileName,".EXE");
128 }
129 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
130 if(dllfile == NULL) {
131 if(!strstr(szFileName, ".EXE")) {
132 strcat(szFileName,".EXE");
133 }
134 dllfile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
135 if(dllfile == NULL) {
136 OSLibDosSearchPath(OSLIB_SEARCHENV, "PATH", szFileName, szFileName, sizeof(szFileName));
137 }
138 }
139 else OSLibDosClose(dllfile);
140 }
141 else {
142 findDll(szFileName, szModule, sizeof(szModule));
143 strcpy(szFileName, szModule);
144 }
145 strcpy(szModule, OSLibStripPath(szFileName));
146 strupr(szModule);
147
148 // create objects for fast API lookup
149 pLookupOrdinal = new CIndexLookupLimit(0, 65535);
150 pLookupName = new CHashtableLookup(503);
151}
152//******************************************************************************
153//******************************************************************************
154Win32PeLdrImage::~Win32PeLdrImage()
155{
156 if (pLookupName)
157 delete pLookupName;
158
159 if (pLookupOrdinal)
160 delete pLookupOrdinal;
161
162 if(memmap)
163 delete memmap;
164
165 if(hFile) {
166 OSLibDosClose(hFile);
167 hFile = 0;
168 }
169
170 if(realBaseAddress)
171 DosFreeMem((PVOID)realBaseAddress);
172
173#ifdef VERIFY_LOADER
174 if(nameexports)
175 free(nameexports);
176
177 if(ordexports)
178 free(ordexports);
179#endif
180
181 if(section)
182 free(section);
183}
184//******************************************************************************
185//******************************************************************************
186BOOL Win32PeLdrImage::init(ULONG reservedMem)
187{
188 LPVOID win32file = NULL;
189 ULONG filesize, ulRead, ulNewPos;
190 PIMAGE_SECTION_HEADER psh;
191 IMAGE_SECTION_HEADER sh;
192 IMAGE_TLS_DIRECTORY *tlsDir = NULL;
193 int nSections, i;
194 char szFullPath[CCHMAXPATH] = "";
195 IMAGE_DOS_HEADER doshdr;
196 ULONG signature;
197
198 hFile = OSLibDosOpen(szFileName, OSLIB_ACCESS_READONLY|OSLIB_ACCESS_SHAREDENYNONE);
199
200 //default error:
201 strcpy(szErrorModule, OSLibStripPath(szFileName));
202 if(hFile == NULL) {
203 goto failure;
204 }
205 //read dos header
206 if(DosRead(hFile, (LPVOID)&doshdr, sizeof(doshdr), &ulRead)) {
207 goto failure;
208 }
209 if(OSLibDosSetFilePtr(hFile, doshdr.e_lfanew, OSLIB_SETPTR_FILE_BEGIN) == -1) {
210 goto failure;
211 }
212 //read signature dword
213 if(DosRead(hFile, (LPVOID)&signature, sizeof(signature), &ulRead)) {
214 goto failure;
215 }
216 //read pe header
217 if(DosRead(hFile, (LPVOID)&fh, sizeof(fh), &ulRead)) {
218 goto failure;
219 }
220 //read optional header
221 if(DosRead(hFile, (LPVOID)&oh, sizeof(oh), &ulRead)) {
222 goto failure;
223 }
224 if(doshdr.e_magic != IMAGE_DOS_SIGNATURE || signature != IMAGE_NT_SIGNATURE) {
225 dprintf((LOG, "Not a valid PE file (probably a 16 bits windows exe/dll)!"));
226 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szPEErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
227 goto failure;
228 }
229
230 if(oh.SizeOfImage == 0) {//just in case
231 oh.SizeOfImage = OSLibDosGetFileSize(hFile, NULL);
232 }
233
234 imageSize = oh.SizeOfImage;
235 //Allocate memory to hold the entire image
236 if(allocSections(reservedMem) == FALSE) {
237 dprintf((LOG, "Failed to allocate image memory for %s at %x, rc %d", szFileName, oh.ImageBase, errorState));;
238 goto failure;
239 }
240
241 memmap = new Win32MemMap(this, realBaseAddress, imageSize);
242 if(memmap == NULL || !memmap->Init()) {
243 goto failure;
244 }
245 win32file = memmap->mapViewOfFile(0, 0, 2);
246
247 if(DosQueryPathInfo(szFileName, FIL_QUERYFULLNAME, szFullPath, sizeof(szFullPath)) == 0) {
248 setFullPath(szFullPath);
249 }
250
251 if(!(fh.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)) {//not valid
252 dprintf((LOG, "Not a valid PE file!"));
253 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szPEErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
254 goto failure;
255 }
256 if(fh.Machine != IMAGE_FILE_MACHINE_I386) {
257 dprintf((LOG, "Doesn't run on x86 processors!"));
258 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szCPUErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
259 goto failure;
260 }
261 //IMAGE_FILE_SYSTEM == only drivers (device/file system/video etc)?
262 if(fh.Characteristics & IMAGE_FILE_SYSTEM) {
263 dprintf((LOG, "Can't convert system files"));
264 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szExeErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
265 goto failure;
266 }
267
268 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
269 dprintf((LOG, "No fixups, might not run!"));
270 }
271
272 dprintf((LOG, "PE file : %s", szFileName));
273 dprintf((LOG, "PE Optional header: "));
274 dprintf((LOG, "Preferred address : %d", oh.ImageBase ));
275 dprintf((LOG, "Base Of Code : %d", oh.BaseOfCode ));
276 dprintf((LOG, "CodeSize : %d", oh.SizeOfCode ));
277 dprintf((LOG, "Base Of Data : %d", oh.BaseOfData ));
278 dprintf((LOG, "Data Size (uninit): %d", oh.SizeOfUninitializedData ));
279 dprintf((LOG, "Data Size (init) : %d", oh.SizeOfInitializedData ));
280 dprintf((LOG, "Entry Point : %d", oh.AddressOfEntryPoint ));
281 dprintf((LOG, "Section Alignment : %d", oh.SectionAlignment ));
282 dprintf((LOG, "Stack Reserve size: %d", oh.SizeOfStackReserve ));
283 dprintf((LOG, "Stack Commit size : %d", oh.SizeOfStackCommit ));
284 dprintf((LOG, "SizeOfHeapReserve : %d", oh.SizeOfHeapReserve ));
285 dprintf((LOG, "SizeOfHeapCommit : %d", oh.SizeOfHeapCommit ));
286 dprintf((LOG, "FileAlignment : %d", oh.FileAlignment ));
287 dprintf((LOG, "Subsystem : %d", oh.Subsystem ));
288 dprintf((LOG, "Image Size : %d", oh.SizeOfImage ));
289 dprintf((LOG, "Header Size : %d", oh.SizeOfHeaders ));
290 dprintf((LOG, "MajorImageVersion : %d", oh.MajorImageVersion ));
291 dprintf((LOG, "MinorImageVersion : %d", oh.MinorImageVersion ));
292
293 //get header page
294 commitPage(realBaseAddress, FALSE);
295
296 nSections = NR_SECTIONS(win32file);
297 section = (Section *)malloc(nSections*sizeof(Section));
298 if(section == NULL) {
299 DebugInt3();
300 goto failure;
301 }
302 memset(section, 0, nSections*sizeof(Section));
303
304 if(!(dwFlags & FLAG_PELDR_LOADASDATAFILE))
305 {
306 imageSize = 0;
307 if ((psh = (PIMAGE_SECTION_HEADER)SECTIONHDROFF (win32file)) != NULL)
308 {
309 dprintf((LOG, "*************************PE SECTIONS START**************************" ));
310 for (i=0; i<nSections; i++)
311 {
312 dprintf((LOG, "Raw data size: %x", psh[i].SizeOfRawData ));
313 dprintf((LOG, "Virtual Address: %x", psh[i].VirtualAddress ));
314 dprintf((LOG, "Virtual Address Start:%x", psh[i].VirtualAddress+oh.ImageBase ));
315 dprintf((LOG, "Virtual Address End: %x", psh[i].VirtualAddress+oh.ImageBase+psh[i].Misc.VirtualSize ));
316 dprintf((LOG, "Virtual Size: %x", psh[i].Misc.VirtualSize ));
317 dprintf((LOG, "Pointer to raw data: %x", psh[i].PointerToRawData ));
318 dprintf((LOG, "Section flags: %x\n\n", psh[i].Characteristics ));
319
320 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_BASERELOC))
321 {
322 dprintf((LOG, ".reloc" ));
323 addSection(SECTION_RELOC, psh[i].PointerToRawData,
324 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
325 psh[i].Misc.VirtualSize, psh[i].Characteristics);
326 continue;
327 }
328 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_EXPORT))
329 {
330 //SvL: Angus.exe has empty export section that's really an
331 // uninitialized data section
332 if(psh[i].SizeOfRawData) {
333 dprintf((LOG, ".edata" ));
334 addSection(SECTION_EXPORT, psh[i].PointerToRawData,
335 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
336 psh[i].Misc.VirtualSize, psh[i].Characteristics);
337 continue;
338 }
339 }
340 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_RESOURCE))
341 {
342 dprintf((LOG, ".rsrc" ));
343 addSection(SECTION_RESOURCE, psh[i].PointerToRawData,
344 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
345 psh[i].Misc.VirtualSize, psh[i].Characteristics);
346 continue;
347 }
348 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_TLS))
349 {
350 dprintf((LOG, "TLS section"));
351 tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_TLS);
352 if(tlsDir) {
353 addSection(SECTION_TLS, psh[i].PointerToRawData,
354 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
355 psh[i].Misc.VirtualSize, psh[i].Characteristics);
356 }
357 continue;
358 }
359 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_DEBUG))
360 {
361 dprintf((LOG, ".rdebug" ));
362 addSection(SECTION_DEBUG, psh[i].PointerToRawData,
363 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
364 psh[i].Misc.VirtualSize, psh[i].Characteristics);
365 continue;
366 }
367 if(IsSectionType(win32file, &psh[i], IMAGE_DIRECTORY_ENTRY_IMPORT))
368 {
369 int type = SECTION_IMPORT;
370
371 dprintf((LOG, "Import Data Section" ));
372 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE) {
373 dprintf((LOG, "Also Code Section"));
374 type |= SECTION_CODE;
375 }
376 addSection(type, psh[i].PointerToRawData,
377 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
378 psh[i].Misc.VirtualSize, psh[i].Characteristics);
379 continue;
380 }
381
382 //KSO Sun 1998-08-09: Borland does not alway set the CODE flag for its "CODE" section
383 if(psh[i].Characteristics & IMAGE_SCN_CNT_CODE ||
384 (psh[i].Characteristics & IMAGE_SCN_MEM_EXECUTE &&
385 !(psh[i].Characteristics & (IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_CNT_INITIALIZED_DATA))) //KSO: make sure its not marked as a datasection
386 )
387 {
388 dprintf((LOG, "Code Section"));
389 addSection(SECTION_CODE, psh[i].PointerToRawData,
390 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
391 psh[i].Misc.VirtualSize, psh[i].Characteristics);
392 continue;
393 }
394 if(!(psh[i].Characteristics & IMAGE_SCN_MEM_WRITE)) { //read only data section
395 dprintf((LOG, "Read Only Data Section" ));
396 addSection(SECTION_READONLYDATA, psh[i].PointerToRawData,
397 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
398 psh[i].Misc.VirtualSize, psh[i].Characteristics);
399 continue;
400 }
401 if(psh[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
402 dprintf((LOG, "Uninitialized Data Section" ));
403 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
404 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
405 psh[i].Misc.VirtualSize, psh[i].Characteristics);
406 continue;
407 }
408 if(psh[i].Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) {
409 dprintf((LOG, "Initialized Data Section" ));
410 addSection(SECTION_INITDATA, psh[i].PointerToRawData,
411 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
412 psh[i].Misc.VirtualSize, psh[i].Characteristics);
413 continue;
414 }
415 if(psh[i].Characteristics & (IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ)) {
416 dprintf((LOG, "Other Section, stored as read/write uninit data" ));
417 addSection(SECTION_UNINITDATA, psh[i].PointerToRawData,
418 psh[i].SizeOfRawData, psh[i].VirtualAddress + oh.ImageBase,
419 psh[i].Misc.VirtualSize, psh[i].Characteristics);
420 continue;
421 }
422 dprintf((LOG, "Unknown section" ));
423 goto failure;
424 }
425 }
426 }
427 else {
428 if(GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_RESOURCE, &sh))
429 {
430 dprintf((LOG, "*************************PE SECTIONS START**************************" ));
431 dprintf((LOG, "Raw data size: %x", sh.SizeOfRawData ));
432 dprintf((LOG, "Virtual Address: %x", sh.VirtualAddress ));
433 dprintf((LOG, "Virtual Address Start:%x", sh.VirtualAddress+oh.ImageBase ));
434 dprintf((LOG, "Virtual Address End: %x", sh.VirtualAddress+oh.ImageBase+sh.Misc.VirtualSize ));
435 dprintf((LOG, "Virtual Size: %x", sh.Misc.VirtualSize ));
436 dprintf((LOG, "Pointer to raw data: %x", sh.PointerToRawData ));
437 dprintf((LOG, "Section flags: %x\n\n", sh.Characteristics ));
438 addSection(SECTION_RESOURCE, sh.PointerToRawData,
439 sh.SizeOfRawData, sh.VirtualAddress + oh.ImageBase,
440 sh.Misc.VirtualSize, sh.Characteristics);
441 }
442 }
443 dprintf((LOG, "*************************PE SECTIONS END **************************" ));
444
445 imageSize += imageVirtBase - oh.ImageBase;
446 dprintf((LOG, "Total size of Image %x", imageSize ));
447 dprintf((LOG, "imageVirtBase %x", imageVirtBase ));
448 dprintf((LOG, "imageVirtEnd %x", imageVirtEnd ));
449
450 //In case there are any gaps between sections, adjust size
451 if(imageSize != imageVirtEnd - oh.ImageBase)
452 {
453 dprintf((LOG, "imageSize != imageVirtEnd - oh.ImageBase!" ));
454 imageSize = imageVirtEnd - oh.ImageBase;
455 }
456 if(imageSize < oh.SizeOfImage) {
457 imageSize = oh.SizeOfImage;
458 }
459
460 dprintf((LOG, "OS/2 base address %x", realBaseAddress ));
461 if(oh.AddressOfEntryPoint) {
462 entryPoint = realBaseAddress + oh.AddressOfEntryPoint;
463 }
464 else {
465 dprintf((LOG, "EntryPoint == NULL" ));
466 entryPoint = NULL;
467 }
468
469 //set memory protection flags
470 if(setMemFlags() == FALSE) {
471 dprintf((LOG, "Failed to set memory protection" ));
472 goto failure;
473 }
474
475 if(realBaseAddress != oh.ImageBase && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
476 pFixups = (PIMAGE_BASE_RELOCATION)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_BASERELOC);
477 dwFixupSize = ImageDirectorySize(win32file, IMAGE_DIRECTORY_ENTRY_BASERELOC);
478 commitPage((ULONG)pFixups, FALSE);
479 }
480
481 if(!(dwFlags & FLAG_PELDR_LOADASDATAFILE))
482 {
483 if(tlsDir = (IMAGE_TLS_DIRECTORY *)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_TLS))
484 {
485 Section *sect;
486 BOOL fTLSFixups = FALSE;
487
488 sect = findSectionByAddr(tlsDir->StartAddressOfRawData);
489 //There might be fixups for the TLS structure, so search the sections
490 //by the OS/2 virtual address too
491 if(sect == NULL) {
492 sect = findSectionByOS2Addr(tlsDir->StartAddressOfRawData);
493 fTLSFixups = TRUE;
494 }
495
496 dprintf((LOG, "TLS Directory" ));
497 dprintf((LOG, "TLS Address of Index %x", tlsDir->AddressOfIndex ));
498 dprintf((LOG, "TLS Address of Callbacks %x", tlsDir->AddressOfCallBacks ));
499 dprintf((LOG, "TLS SizeOfZeroFill %x", tlsDir->SizeOfZeroFill ));
500 dprintf((LOG, "TLS Characteristics %x", tlsDir->Characteristics ));
501 if(sect == NULL) {
502 dprintf((LOG, "Couldn't find TLS section!!" ));
503 goto failure;
504 }
505 setTLSAddress((char *)sect->realvirtaddr);
506 setTLSInitSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData);
507 setTLSTotalSize(tlsDir->EndAddressOfRawData - tlsDir->StartAddressOfRawData + tlsDir->SizeOfZeroFill);
508
509 fTLSFixups = FALSE;
510 sect = findSectionByAddr((ULONG)tlsDir->AddressOfIndex);
511 //There might be fixups for the TLS structure, so search the sections
512 //by the OS/2 virtual address too
513 if(sect == NULL) {
514 sect = findSectionByOS2Addr((ULONG)tlsDir->AddressOfIndex);
515 fTLSFixups = TRUE;
516 }
517 if(sect == NULL) {
518 dprintf((LOG, "Couldn't find TLS AddressOfIndex section!!" ));
519 goto failure;
520 }
521 if(fTLSFixups) {
522 setTLSIndexAddr((LPDWORD)tlsDir->AddressOfIndex); //no fixup required
523 }
524 else {//need to add a manual fixup
525 setTLSIndexAddr((LPDWORD)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfIndex - sect->virtaddr)));
526 }
527
528 if((ULONG)tlsDir->AddressOfCallBacks != 0)
529 {
530 fTLSFixups = FALSE;
531
532 sect = findSectionByAddr((ULONG)tlsDir->AddressOfCallBacks);
533 //There might be fixups for the TLS structure, so search the sections
534 //by the OS/2 virtual address too
535 if(sect == NULL) {
536 sect = findSectionByOS2Addr((ULONG)tlsDir->AddressOfIndex);
537 fTLSFixups = TRUE;
538 }
539 if(sect == NULL) {
540 dprintf((LOG, "Couldn't find TLS AddressOfCallBacks section!!" ));
541 goto failure;
542 }
543 if(fTLSFixups) {
544 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)tlsDir->AddressOfCallBacks); //no fixup required
545 }
546 else {//need to add a manual fixup
547 setTLSCallBackAddr((PIMAGE_TLS_CALLBACK *)(sect->realvirtaddr + ((ULONG)tlsDir->AddressOfCallBacks - sect->virtaddr)));
548 }
549 //modify tls callback pointers for new image base address
550 int i = 0;
551 while(tlsCallBackAddr[i])
552 {
553 fTLSFixups = FALSE;
554
555 sect = findSectionByAddr((ULONG)tlsCallBackAddr[i]);
556 //There might be fixups for the TLS structure, so search the sections
557 //by the OS/2 virtual address too
558 if(sect == NULL) {
559 sect = findSectionByOS2Addr((ULONG)tlsCallBackAddr[i]);
560 fTLSFixups = TRUE;
561 }
562 if(sect == NULL) {
563 dprintf((LOG, "Couldn't find TLS callback section!!" ));
564 goto failure;
565 }
566 if(fTLSFixups) {
567 tlsCallBackAddr[i] = tlsCallBackAddr[i];
568 }
569 else tlsCallBackAddr[i] = (PIMAGE_TLS_CALLBACK)(realBaseAddress + ((ULONG)tlsCallBackAddr[i] - oh.ImageBase));
570 i++;
571 }
572 }
573 }
574
575#ifdef DEBUG
576 dprintf((LOG, "Image directories: "));
577 for (i = 0; i < IMAGE_NUMBEROF_DIRECTORY_ENTRIES; i++)
578 {
579 char *pszName;
580
581 if(oh.DataDirectory[i].VirtualAddress && oh.DataDirectory[i].Size) {
582 switch (i)
583 {
584 case IMAGE_DIRECTORY_ENTRY_EXPORT: pszName = "Export Directory (IMAGE_DIRECTORY_ENTRY_EXPORT)"; break;
585 case IMAGE_DIRECTORY_ENTRY_IMPORT: pszName = "Import Directory (IMAGE_DIRECTORY_ENTRY_IMPORT)"; break;
586 case IMAGE_DIRECTORY_ENTRY_RESOURCE: pszName = "Resource Directory (IMAGE_DIRECTORY_ENTRY_RESOURCE)"; break;
587 case IMAGE_DIRECTORY_ENTRY_EXCEPTION: pszName = "Exception Directory (IMAGE_DIRECTORY_ENTRY_EXCEPTION)"; break;
588 case IMAGE_DIRECTORY_ENTRY_SECURITY: pszName = "Security Directory (IMAGE_DIRECTORY_ENTRY_SECURITY)"; break;
589 case IMAGE_DIRECTORY_ENTRY_BASERELOC: pszName = "Base Relocation Table (IMAGE_DIRECTORY_ENTRY_BASERELOC)"; break;
590 case IMAGE_DIRECTORY_ENTRY_DEBUG: pszName = "Debug Directory (IMAGE_DIRECTORY_ENTRY_DEBUG)"; break;
591 case IMAGE_DIRECTORY_ENTRY_COPYRIGHT: pszName = "Description String (IMAGE_DIRECTORY_ENTRY_COPYRIGHT)"; break;
592 case IMAGE_DIRECTORY_ENTRY_GLOBALPTR: pszName = "Machine Value (MIPS GP) (IMAGE_DIRECTORY_ENTRY_GLOBALPTR)"; break;
593 case IMAGE_DIRECTORY_ENTRY_TLS: pszName = "TLS Directory (IMAGE_DIRECTORY_ENTRY_TLS)"; break;
594 case IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG: pszName = "Load Configuration Directory (IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG)"; break;
595 case IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT:pszName = "Bound Import Directory in headers (IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT)"; break;
596 case IMAGE_DIRECTORY_ENTRY_IAT: pszName = "Import Address Table (IMAGE_DIRECTORY_ENTRY_IAT)"; break;
597 default:
598 pszName = "unknown";
599 }
600 dprintf((LOG, "directory %s", pszName));
601 dprintf((LOG, " Address 0x%08x", oh.DataDirectory[i].VirtualAddress));
602 dprintf((LOG, " Size 0x%08x", oh.DataDirectory[i].Size));
603 }
604 }
605 dprintf((LOG, "\n\n"));
606#endif
607
608#ifdef COMMIT_ALL
609 for (i=0; i<nSections; i++) {
610 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
611 }
612#else
613 for (i=0; i<nSections; i++) {
614 switch(section[i].type)
615 {
616 case SECTION_IMPORT:
617 case SECTION_RELOC:
618 case SECTION_EXPORT:
619 commitPage((ULONG)section[i].realvirtaddr, FALSE, COMPLETE_SECTION);
620 break;
621 }
622 }
623#endif
624 if(processExports((char *)win32file) == FALSE) {
625 dprintf((LOG, "Failed to process exported apis" ));
626 goto failure;
627 }
628 }
629#ifdef COMMIT_ALL
630 else {
631 commitPage((ULONG)section[0].realvirtaddr, FALSE, COMPLETE_SECTION);
632 }
633#endif
634
635#ifndef COMMIT_ALL
636 if(entryPoint) {
637 //commit code at entrypoint, since we going to call it anyway
638 commitPage((ULONG)entryPoint, FALSE);
639 }
640#endif
641
642 //SvL: Use pointer to image header as module handle now. Some apps needs this
643 hinstance = (HINSTANCE)realBaseAddress;
644
645 //SvL: Set instance handle in process database structure
646 SetPDBInstance(hinstance);
647
648 //PH: get pResRootDir pointer correct first, since processImports may
649 // implicitly call functions depending on it.
650 if(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress && oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size)
651 {
652 //get offset in resource object of directory entry
653 pResRootDir = (PIMAGE_RESOURCE_DIRECTORY)(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress + realBaseAddress);
654 ulRVAResourceSection = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
655 }
656
657 //Allocate TLS index for this module
658 //Must do this before dlls are loaded for this module. Some apps assume
659 //they get TLS index 0 for their main executable
660 tlsAlloc();
661 tlsAttachThread(); //setup TLS (main thread)
662
663 if(!(dwFlags & (FLAG_PELDR_LOADASDATAFILE | FLAG_PELDR_SKIPIMPORTS)))
664 {
665 if(processImports((char *)win32file) == FALSE) {
666 dprintf((LOG, "Failed to process imports!" ));
667 goto failure;
668 }
669 }
670 return(TRUE);
671
672failure:
673 if(memmap) {
674 delete memmap;
675 memmap = NULL;
676 }
677 if(hFile) {
678 OSLibDosClose(hFile);
679 hFile = 0;
680 }
681 errorState = ERROR_INTERNAL;
682 return FALSE;
683}
684//******************************************************************************
685// commitPage:
686// commits image page(s) when an access violation exception is received
687// (usually called from exception.cpp; also from other methods in this file)
688//
689// Parameters:
690// virtAddress - address of exception (rounded down to page boundary)
691// fWriteAccess - type of access violation (read or write)
692// fPageCmd - SINGLE_PAGE -> commit single page
693// SECTION_PAGES -> commit default nr of pages
694// COMPLETE_SECTION -> commit entire section
695//
696// Remarks:
697// DosEnterCritSec/DosExitCritSec is used to make sure the other threads in
698// the application can't touch the pages before they are loaded from disk and
699// fixups are applied.
700//
701// TODO:
702// SECTION_PAGES: - don't load pages starting at access violation address, but
703// a region surrounding it (e.g. -32k -> + 32k)
704// this will prevent many pagefaults when the app uses
705// pages with a lower addr.
706//
707//******************************************************************************
708BOOL Win32PeLdrImage::commitPage(ULONG virtAddress, BOOL fWriteAccess, int fPageCmd)
709{
710 Section *section;
711 ULONG offset, size, sectionsize, protflags, fileoffset, range, attr;
712 ULONG ulNewPos, ulRead, orgVirtAddress = virtAddress;
713 APIRET rc;
714
715 //Round down to nearest page boundary
716 virtAddress = virtAddress & ~0xFFF;
717
718 section = findSectionByOS2Addr(virtAddress);
719 if(section == NULL) {
720 section = findSectionByOS2Addr(orgVirtAddress);
721 if(section) {
722 virtAddress = orgVirtAddress;
723 }
724 }
725 if(section == NULL) {
726 size = 4096;
727 sectionsize = 4096;
728 protflags = PAG_READ|PAG_WRITE; //readonly?
729 section = findPreviousSectionByOS2Addr(virtAddress);
730 if(section == NULL) {//access to header
731 offset = 0;
732 fileoffset = virtAddress - realBaseAddress;
733 }
734 else {
735 offset = virtAddress - (section->realvirtaddr + section->virtualsize);
736 fileoffset = section->rawoffset + section->rawsize + offset;
737 }
738 }
739 else {
740 protflags = section->pageflags;
741 offset = virtAddress - section->realvirtaddr;
742 sectionsize = section->virtualsize - offset;
743
744 if(offset > section->rawsize || section->type == SECTION_UNINITDATA) {
745 //unintialized data (set to 0)
746 size = 0;
747 fileoffset = -1;
748 }
749 else {
750 size = section->rawsize-offset;
751 fileoffset = section->rawoffset + offset;
752 }
753 if(fWriteAccess & !(section->pageflags & PAG_WRITE)) {
754 dprintf((LOG, "Win32PeLdrImage::commitPage: No write access to 0%x!", virtAddress));
755 return FALSE;
756 }
757 }
758 //Check range of pages with the same attributes starting at virtAddress
759 //(some pages might already have been loaded)
760 range = sectionsize;
761 rc = DosQueryMem((PVOID)virtAddress, &range, &attr);
762 if(rc) {
763 dprintf((LOG, "Win32PeLdrImage::commitPage: DosQueryMem for %x returned %d", virtAddress, rc));
764 return FALSE;
765 }
766 if(attr & PAG_COMMIT) {
767 dprintf((LOG, "Win32PeLdrImage::commitPage: Memory at 0x%x already committed!", virtAddress));
768 return FALSE;
769 }
770
771 if(fPageCmd == SINGLE_PAGE) {
772 size = min(size, PAGE_SIZE);
773 sectionsize = min(sectionsize, PAGE_SIZE);
774 }
775 else
776 if(fPageCmd == SECTION_PAGES) {
777 size = min(size, DEFAULT_NR_PAGES*PAGE_SIZE);
778 sectionsize = min(sectionsize, DEFAULT_NR_PAGES*PAGE_SIZE);
779 }
780 //else complete section
781
782 size = min(size, range);
783 sectionsize = min(sectionsize, range);
784
785 if(fileoffset != -1) {
786 rc = DosEnterCritSec();
787 if(rc) {
788 dprintf((LOG, "DosEnterCritSec failed with rc %d", rc));
789 goto fail;
790 }
791 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
792 if(rc) {
793 DosExitCritSec();
794 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
795 goto fail;
796 }
797
798 if(DosSetFilePtr(hFile, fileoffset, FILE_BEGIN, &ulNewPos) == -1) {
799 DosExitCritSec();
800 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetFilePtr failed for 0x%x!", fileoffset));
801 goto fail;
802 }
803 rc = DosRead(hFile, (PVOID)virtAddress, size, &ulRead);
804 if(rc) {
805 DosExitCritSec();
806 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed for 0x%x %x %x %x (rc=%d)!", virtAddress, size, ulRead, fileoffset, rc));
807 goto fail;
808 }
809 if(ulRead != size) {
810 DosExitCritSec();
811 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed to read %x (%x) bytes at %x for 0x%x!", size, ulRead, fileoffset, virtAddress));
812 goto fail;
813 }
814 setFixups(virtAddress, sectionsize);
815
816 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
817 DosExitCritSec();
818 if(rc) {
819 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
820 goto fail;
821 }
822 }
823 else {
824 rc = DosEnterCritSec();
825 if(rc) {
826 dprintf((LOG, "DosEnterCritSec failed with rc %d", rc));
827 goto fail;
828 }
829
830 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
831 if(rc) {
832 DosExitCritSec();
833 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
834 goto fail;
835 }
836 setFixups(virtAddress, sectionsize);
837
838 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
839 DosExitCritSec();
840 if(rc) {
841 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
842 goto fail;
843 }
844 }
845 return TRUE;
846
847fail:
848 return FALSE;
849}
850//******************************************************************************
851//******************************************************************************
852void Win32PeLdrImage::addSection(ULONG type, ULONG rawoffset, ULONG rawsize, ULONG virtaddress, ULONG virtsize, ULONG flags)
853{
854 virtsize = max(rawsize, virtsize);
855
856 section[nrsections].rawoffset = rawoffset;
857 section[nrsections].type = type;
858 section[nrsections].rawsize = rawsize;
859 section[nrsections].virtaddr = virtaddress;
860 section[nrsections].flags = flags;
861
862 virtsize = ((virtsize - 1) & ~0xFFF) + PAGE_SIZE;
863 imageSize += virtsize;
864 section[nrsections].virtualsize = virtsize;
865
866 if(virtaddress < imageVirtBase)
867 imageVirtBase = virtaddress;
868 if(virtaddress + virtsize > imageVirtEnd)
869 imageVirtEnd = virtaddress + virtsize;
870
871 nrsections++;
872}
873//******************************************************************************
874//******************************************************************************
875BOOL Win32PeLdrImage::allocSections(ULONG reservedMem)
876{
877 APIRET rc;
878 ULONG baseAddress;
879
880 realBaseAddress = 0;
881
882 //Allocated in by pe.exe
883 if(reservedMem && reservedMem == oh.ImageBase) {
884 realBaseAddress = oh.ImageBase;
885 return TRUE;
886 }
887
888 //SvL: We don't care where the image is loaded for resource lookup
889 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
890 return allocFixedMem(reservedMem);
891 }
892 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | flAllocMem);
893 if(rc) {
894 dprintf((LOG, "Win32PeLdrImage::allocSections, DosAllocMem returned %d", rc));
895 errorState = rc;
896 return(FALSE);
897 }
898 realBaseAddress = baseAddress;
899 return(TRUE);
900}
901//******************************************************************************
902//******************************************************************************
903Section *Win32PeLdrImage::findSection(ULONG type)
904{
905 for(int i=0;i<nrsections;i++) {
906 if(section[i].type == type) {
907 return &section[i];
908 }
909 }
910 return NULL;
911}
912//******************************************************************************
913//******************************************************************************
914Section *Win32PeLdrImage::findSectionByAddr(ULONG addr)
915{
916 for(int i=0;i<nrsections;i++) {
917 if(section[i].virtaddr <= addr && section[i].virtaddr + section[i].virtualsize > addr) {
918 return &section[i];
919 }
920 }
921 return NULL;
922}
923//******************************************************************************
924//******************************************************************************
925Section *Win32PeLdrImage::findSectionByOS2Addr(ULONG addr)
926{
927 for(int i=0;i<nrsections;i++) {
928 if(section[i].realvirtaddr <= addr && section[i].realvirtaddr + section[i].virtualsize > addr) {
929 return &section[i];
930 }
931 }
932 return NULL;
933}
934//******************************************************************************
935//******************************************************************************
936Section *Win32PeLdrImage::findPreviousSectionByOS2Addr(ULONG addr)
937{
938 ULONG lowestAddr = 0xffffffff;
939 ULONG index = -1;
940
941 for(int i=0;i<nrsections;i++) {
942 if(section[i].realvirtaddr > addr) {
943 if(section[i].realvirtaddr < lowestAddr) {
944 lowestAddr = section[i].realvirtaddr;
945 index = i;
946 }
947 }
948 }
949 if(index == -1)
950 return NULL;
951
952 return &section[index];
953}
954//******************************************************************************
955#define FALLOC_SIZE (1024*1024)
956//NOTE: Needs testing (while loop)
957//TODO: Free unused (parts of) reservedMem
958//******************************************************************************
959BOOL Win32PeLdrImage::allocFixedMem(ULONG reservedMem)
960{
961 ULONG address = 0;
962 ULONG *memallocs;
963 ULONG alloccnt = 0;
964 ULONG diff, i, baseAddress;
965 APIRET rc;
966 BOOL allocFlags = flAllocMem;
967
968 //Reserve enough space to store 4096 pointers to 1MB memory chunks
969 memallocs = (ULONG *)malloc(4096*sizeof(ULONG *));
970 if(memallocs == NULL) {
971 dprintf((LOG, "allocFixedMem: MALLOC FAILED for memallocs" ));
972 return FALSE;
973 }
974
975 if(oh.ImageBase < 512*1024*1024) {
976 allocFlags = 0;
977 }
978 while(TRUE) {
979 rc = DosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ | allocFlags);
980 if(rc) break;
981
982 dprintf((LOG, "DosAllocMem returned %x", address ));
983 if(address + FALLOC_SIZE >= oh.ImageBase) {
984 if(address > oh.ImageBase) {//we've passed it!
985 DosFreeMem((PVOID)address);
986 break;
987 }
988 //found the right address
989 DosFreeMem((PVOID)address);
990
991 diff = oh.ImageBase - address;
992 if(diff) {
993 rc = DosAllocMem((PPVOID)&address, diff, PAG_READ | allocFlags);
994 if(rc) break;
995 }
996 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | allocFlags);
997 if(rc) break;
998
999 if(diff) DosFreeMem((PVOID)address);
1000
1001 realBaseAddress = baseAddress;
1002 break;
1003 }
1004 memallocs[alloccnt++] = address;
1005 }
1006 for(i=0;i<alloccnt;i++) {
1007 DosFreeMem((PVOID)memallocs[i]);
1008 }
1009 free(memallocs);
1010
1011 if(realBaseAddress == 0) //Let me guess.. MS Office app?
1012 return(FALSE);
1013
1014 return(TRUE);
1015}
1016//******************************************************************************
1017//******************************************************************************
1018BOOL Win32PeLdrImage::setMemFlags()
1019{
1020 int i;
1021 WINIMAGE_LOOKUP *imgLookup;
1022
1023 imgLookup = WINIMAGE_LOOKUPADDR(realBaseAddress);
1024 imgLookup->magic1 = MAGIC_WINIMAGE;
1025 imgLookup->image = this;
1026 imgLookup->magic2 = MAGIC_WINIMAGE;
1027
1028 // Process all the image sections
1029 for(i=0;i<nrsections;i++) {
1030 section[i].realvirtaddr = realBaseAddress + (section[i].virtaddr - oh.ImageBase);
1031 }
1032
1033 for(i=0;i<nrsections;i++) {
1034 switch(section[i].type)
1035 {
1036 case SECTION_CODE:
1037 case (SECTION_CODE | SECTION_IMPORT):
1038 section[i].pageflags = PAG_EXECUTE | PAG_READ;
1039 if(section[i].flags & IMAGE_SCN_MEM_WRITE)
1040 section[i].pageflags |= PAG_WRITE;
1041 break;
1042 case SECTION_INITDATA:
1043 case SECTION_UNINITDATA:
1044 case SECTION_IMPORT:
1045 case SECTION_TLS:
1046 section[i].pageflags = PAG_WRITE | PAG_READ;
1047 break;
1048
1049 case SECTION_RESOURCE:
1050 //TODO: GDI32 changes some bitmap structures to avoid problems in Open32
1051 // -> causes crashes if resource section is readonly
1052 // -> make it readonly again when gdi32 has been rewritten
1053 section[i].pageflags = PAG_WRITE | PAG_READ;
1054 break;
1055
1056 case SECTION_READONLYDATA:
1057 case SECTION_EXPORT:
1058 default:
1059 section[i].pageflags = PAG_READ;
1060 break;
1061 }
1062 if(section[i].flags & (IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
1063 //SvL: sometimes i.e. import/export sections also contain data
1064 // must make them read/write
1065 section[i].pageflags = PAG_WRITE;
1066 }
1067 }
1068 return(TRUE);
1069}
1070//******************************************************************************
1071//******************************************************************************
1072BOOL Win32PeLdrImage::setFixups(ULONG virtAddress, ULONG size)
1073{
1074 int i, j;
1075 char *page;
1076 ULONG count, newpage;
1077 Section *section;
1078 PIMAGE_BASE_RELOCATION prel = pFixups;
1079
1080 if(realBaseAddress == oh.ImageBase || fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
1081 return(TRUE);
1082 }
1083
1084 virtAddress -= realBaseAddress;
1085 //round size to next page boundary
1086 size = (size-1) & ~0xFFF;
1087 size += PAGE_SIZE;
1088
1089 if(prel) {
1090 j = 1;
1091 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
1092 prel->VirtualAddress && prel->VirtualAddress < virtAddress)
1093 {
1094 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1095 }
1096 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
1097 prel->VirtualAddress && prel->VirtualAddress < virtAddress + size)
1098 {
1099 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
1100 count = (prel->SizeOfBlock - 8)/2;
1101 j++;
1102 for(i=0;i<count;i++) {
1103 int type = prel->TypeOffset[i] >> 12;
1104 int offset = prel->TypeOffset[i] & 0xFFF;
1105 int fixupsize = 0;
1106
1107 switch(type)
1108 {
1109 case IMAGE_REL_BASED_HIGHLOW:
1110 fixupsize = 4;
1111 break;
1112 case IMAGE_REL_BASED_HIGH:
1113 case IMAGE_REL_BASED_LOW:
1114 fixupsize = 2;
1115 break;
1116 }
1117 //If the fixup crosses the final page boundary,
1118 //then we have to load another page
1119 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
1120 {
1121 newpage = realBaseAddress + prel->VirtualAddress + offset + fixupsize;
1122 newpage &= ~0xFFF;
1123
1124 section = findSectionByOS2Addr(newpage);
1125 if(section == NULL) {
1126 //should never happen
1127 dprintf((LOG, "::setFixups -> section == NULL!!"));
1128 return FALSE;
1129 }
1130 //SvL: Read page from disk
1131 commitPage(newpage, FALSE, SINGLE_PAGE);
1132
1133 //SvL: Enable write access (TODO: may need to prevent other threads from being active)
1134 DosSetMem((PVOID)newpage, PAGE_SIZE, PAG_READ|PAG_WRITE);
1135 }
1136
1137 switch(type)
1138 {
1139 case IMAGE_REL_BASED_ABSOLUTE:
1140 break; //skip
1141 case IMAGE_REL_BASED_HIGHLOW:
1142 AddOff32Fixup(prel->VirtualAddress + offset);
1143 break;
1144 case IMAGE_REL_BASED_HIGH:
1145 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
1146 break;
1147 case IMAGE_REL_BASED_LOW:
1148 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
1149 break;
1150 case IMAGE_REL_BASED_HIGHADJ:
1151 case IMAGE_REL_BASED_MIPS_JMPADDR:
1152 default:
1153 break;
1154 }
1155 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
1156 {
1157 //SvL: Restore original page protection flags (TODO: may need to prevent other threads from being active)
1158 DosSetMem((PVOID)newpage, PAGE_SIZE, section->pageflags);
1159 }
1160 }
1161 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1162 }//while
1163 }
1164 else {
1165 dprintf((LOG, "Win32PeLdrImage::setFixups, no fixups at %x, %d", virtAddress, size));
1166 return(FALSE);
1167 }
1168 return(TRUE);
1169}
1170//******************************************************************************
1171//******************************************************************************
1172BOOL Win32PeLdrImage::setFixups(PIMAGE_BASE_RELOCATION prel)
1173{
1174 int i, j;
1175 char *page;
1176 ULONG count;
1177
1178 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
1179 return(TRUE);
1180 }
1181
1182 if(prel) {
1183 j = 1;
1184 while(prel->VirtualAddress) {
1185 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
1186 count = (prel->SizeOfBlock - 8)/2;
1187 dprintf((LOG, "Page %d Address %x Count %d", j, prel->VirtualAddress, count ));
1188 j++;
1189 for(i=0;i<count;i++) {
1190 int type = prel->TypeOffset[i] >> 12;
1191 int offset = prel->TypeOffset[i] & 0xFFF;
1192 switch(type) {
1193 case IMAGE_REL_BASED_ABSOLUTE:
1194//// dprintf((LOG, "absolute fixup; unused" ));
1195 break; //skip
1196 case IMAGE_REL_BASED_HIGHLOW:
1197//// dprintf((LOG, "address ", offset << " type ", type ));
1198 AddOff32Fixup(prel->VirtualAddress + offset);
1199 break;
1200 case IMAGE_REL_BASED_HIGH:
1201 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
1202 break;
1203 case IMAGE_REL_BASED_LOW:
1204 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
1205 break;
1206 case IMAGE_REL_BASED_HIGHADJ:
1207 case IMAGE_REL_BASED_MIPS_JMPADDR:
1208 default:
1209 dprintf((LOG, "Unknown/unsupported fixup type!" ));
1210 break;
1211 }
1212 }
1213 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1214 }//while
1215 }
1216 else {
1217 dprintf((LOG, "No internal fixups found!" ));
1218 errorState = ERROR_INTERNAL;
1219 return(FALSE);
1220 }
1221 return(TRUE);
1222}
1223//******************************************************************************
1224//******************************************************************************
1225void Win32PeLdrImage::AddOff32Fixup(ULONG fixupaddr)
1226{
1227 ULONG orgaddr;
1228 ULONG *fixup;
1229
1230 fixup = (ULONG *)(fixupaddr + realBaseAddress);
1231 orgaddr = *fixup;
1232// dprintf((LOG, "AddOff32Fixup 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, realBaseAddress + (*fixup - oh.ImageBase)));
1233 *fixup = realBaseAddress + (*fixup - oh.ImageBase);
1234}
1235//******************************************************************************
1236//******************************************************************************
1237void Win32PeLdrImage::AddOff16Fixup(ULONG fixupaddr, BOOL fHighFixup)
1238{
1239 ULONG orgaddr;
1240 USHORT *fixup;
1241
1242 fixup = (USHORT *)(fixupaddr + realBaseAddress);
1243 orgaddr = *fixup;
1244 if(fHighFixup) {
1245 *fixup += (USHORT)((realBaseAddress - oh.ImageBase) >> 16);
1246// dprintf((LOG, "AddOff16FixupH 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1247 }
1248 else {
1249 *fixup += (USHORT)((realBaseAddress - oh.ImageBase) & 0xFFFF);
1250// dprintf((LOG, "AddOff16FixupL 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1251 }
1252}
1253//******************************************************************************
1254//******************************************************************************
1255void Win32PeLdrImage::StoreImportByOrd(Win32ImageBase *WinImage, ULONG ordinal, ULONG impaddr)
1256{
1257 ULONG *import;
1258 ULONG apiaddr;
1259
1260 import = (ULONG *)impaddr;
1261 apiaddr = WinImage->getApi(ordinal);
1262 if(apiaddr == 0)
1263 {
1264 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%u not found\n",
1265 WinImage->getModuleName(),
1266 ordinal));
1267
1268 dprintf((LOG, "--->>> NOT FOUND!" ));
1269 *import = (ULONG)MissingApi;
1270 }
1271 else *import = apiaddr;
1272}
1273//******************************************************************************
1274//******************************************************************************
1275void Win32PeLdrImage::StoreImportByName(Win32ImageBase *WinImage, char *impname, ULONG impaddr)
1276{
1277 ULONG *import;
1278 ULONG apiaddr;
1279
1280 import = (ULONG *)impaddr;
1281 apiaddr = WinImage->getApi(impname);
1282 if(apiaddr == 0)
1283 {
1284 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%s not found\n",
1285 WinImage->getModuleName(),
1286 impname));
1287
1288 dprintf((LOG, "--->>> NOT FOUND!" ));
1289 *import = (ULONG)MissingApi;
1290 }
1291 else *import = apiaddr;
1292}
1293//******************************************************************************
1294//******************************************************************************
1295BOOL Win32PeLdrImage::processExports(char *win32file)
1296{
1297 IMAGE_SECTION_HEADER sh;
1298 PIMAGE_EXPORT_DIRECTORY ped;
1299 ULONG *ptrNames, *ptrAddress;
1300 USHORT *ptrOrd;
1301 BOOL fForwarder;
1302 int i;
1303
1304 /* get section header and pointer to data directory for .edata section */
1305 if((ped = (PIMAGE_EXPORT_DIRECTORY)ImageDirectoryOffset
1306 (win32file, IMAGE_DIRECTORY_ENTRY_EXPORT)) != NULL &&
1307 GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_EXPORT, &sh) ) {
1308
1309 dprintf((LOG, "Exported Functions: " ));
1310 ptrOrd = (USHORT *)((ULONG)ped->AddressOfNameOrdinals +
1311 (ULONG)win32file);
1312 ptrNames = (ULONG *)((ULONG)ped->AddressOfNames +
1313 (ULONG)win32file);
1314 ptrAddress = (ULONG *)((ULONG)ped->AddressOfFunctions +
1315 (ULONG)win32file);
1316 nrOrdExports = ped->NumberOfFunctions;
1317 nrNameExports = ped->NumberOfNames;
1318
1319 // as we now know the exact size of the export caches, resize them
1320 pLookupName->setSize(nrNameExports);
1321
1322 int ord, RVAExport;
1323 char *name;
1324 for(i=0;i<ped->NumberOfNames;i++)
1325 {
1326 fForwarder = FALSE;
1327 ord = ptrOrd[i] + ped->Base;
1328 name = (char *)((ULONG)ptrNames[i] + (ULONG)win32file);
1329 RVAExport = ptrAddress[ptrOrd[i]];
1330
1331 /* forwarder? ulRVA within export directory. */
1332 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1333 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1334 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1335 {
1336 fForwarder = AddForwarder(oh.ImageBase + RVAExport, name, ord);
1337 }
1338 if(!fForwarder) {
1339 //points to code (virtual address relative to oh.ImageBase
1340 AddNameExport(oh.ImageBase + RVAExport, name, ord);
1341 dprintf((LOG, "address 0x%x %s @%d (0x%08x)", RVAExport, name, ord, realBaseAddress + RVAExport));
1342 }
1343 }
1344 for(i=0;i<max(ped->NumberOfNames,ped->NumberOfFunctions);i++)
1345 {
1346 fForwarder = FALSE;
1347 ord = ped->Base + i; //Correct??
1348 RVAExport = ptrAddress[i];
1349 /* forwarder? ulRVA within export directory. */
1350 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1351 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1352 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1353 {
1354 fForwarder = AddForwarder(oh.ImageBase + RVAExport, NULL, ord);
1355 }
1356 if(!fForwarder && RVAExport) {
1357 //points to code (virtual address relative to oh.ImageBase
1358 dprintf((LOG, "ord %d at 0x%08x (0x%08x)", ord, RVAExport, realBaseAddress + RVAExport));
1359 AddOrdExport(oh.ImageBase + RVAExport, ord);
1360 }
1361 }
1362 }
1363
1364 // resize the caches
1365 pLookupOrdinal->shrink();
1366 pLookupName->rehash();
1367
1368 return(TRUE);
1369}
1370//******************************************************************************
1371//******************************************************************************
1372void Win32PeLdrImage::AddNameExport(ULONG virtaddr, char *apiname, ULONG ordinal, BOOL fAbsoluteAddress)
1373{
1374 ULONG uv;
1375
1376 if(fAbsoluteAddress) //forwarders use absolute address
1377 uv = virtaddr;
1378 else
1379 uv = realBaseAddress + (virtaddr - oh.ImageBase);
1380
1381 // add named export to the lookup cache
1382 pLookupName->addElement(apiname, (void*)uv);
1383
1384 // also add the ordinal export to the lookup cache
1385 pLookupOrdinal->addElement(ordinal, (void*)uv);
1386
1387#ifdef VERIFY_LOADER
1388 ULONG nsize;
1389
1390 if(nameexports == NULL) {
1391 nameExportSize= 4096;
1392 nameexports = (NameExport *)malloc(nameExportSize);
1393 curnameexport = nameexports;
1394 }
1395 nsize = (ULONG)curnameexport - (ULONG)nameexports;
1396 if(nsize + sizeof(NameExport) + strlen(apiname) > nameExportSize) {
1397 nameExportSize += 4096;
1398 char *tmp = (char *)nameexports;
1399 nameexports = (NameExport *)malloc(nameExportSize);
1400 memcpy(nameexports, tmp, nsize);
1401 curnameexport = (NameExport *)((ULONG)nameexports + nsize);
1402 free(tmp);
1403 }
1404 if(fAbsoluteAddress) {//forwarders use absolute address
1405 curnameexport->virtaddr = virtaddr;
1406 }
1407 else curnameexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1408 curnameexport->ordinal = ordinal;
1409 *(ULONG *)curnameexport->name = 0;
1410 strcpy(curnameexport->name, apiname);
1411
1412 curnameexport->nlength = strlen(apiname) + 1;
1413 if(curnameexport->nlength < sizeof(curnameexport->name))
1414 curnameexport->nlength = sizeof(curnameexport->name);
1415
1416 curnameexport = (NameExport *)((ULONG)curnameexport->name + curnameexport->nlength);
1417#endif
1418}
1419//******************************************************************************
1420//******************************************************************************
1421void Win32PeLdrImage::AddOrdExport(ULONG virtaddr, ULONG ordinal, BOOL fAbsoluteAddress)
1422{
1423 ULONG uv;
1424 if(fAbsoluteAddress)
1425 { //forwarders use absolute address
1426 uv = virtaddr;
1427 }
1428 else
1429 {
1430 uv = realBaseAddress + (virtaddr - oh.ImageBase);
1431 }
1432
1433 // add ordinal export to the lookup cache
1434 pLookupOrdinal->addElement((int)ordinal, (void*)uv);
1435
1436
1437#ifdef VERIFY_LOADER
1438 if(ordexports == NULL) {
1439 ordexports = (OrdExport *)malloc(nrOrdExports * sizeof(OrdExport));
1440 curordexport = ordexports;
1441 }
1442 if(fAbsoluteAddress) {//forwarders use absolute address
1443 curordexport->virtaddr = virtaddr;
1444 }
1445 else curordexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1446
1447 curordexport->ordinal = ordinal;
1448 curordexport++;
1449#endif
1450}
1451//******************************************************************************
1452//******************************************************************************
1453BOOL Win32PeLdrImage::AddForwarder(ULONG virtaddr, char *apiname, ULONG ordinal)
1454{
1455 char *forward = (char *)(realBaseAddress + (virtaddr - oh.ImageBase));
1456 char *forwarddll, *forwardapi;
1457 Win32DllBase *WinDll;
1458 DWORD exportaddr;
1459 int forwardord;
1460
1461 forwarddll = strdup(forward);
1462 if(forwarddll == NULL) {
1463 return FALSE;
1464 }
1465 forwardapi = strchr(forwarddll, '.');
1466 if(forwardapi == NULL) {
1467 goto fail;
1468 }
1469 *forwardapi++ = 0;
1470 if(strlen(forwarddll) == 0 || strlen(forwardapi) == 0) {
1471 goto fail;
1472 }
1473 WinDll = Win32DllBase::findModule(forwarddll);
1474 if(WinDll == NULL) {
1475 WinDll = loadDll(forwarddll);
1476 if(WinDll == NULL) {
1477 dprintf((LOG, "ERROR: couldn't find forwarder %s.%s", forwarddll, forwardapi));
1478 goto fail;
1479 }
1480 }
1481 //check if name or ordinal forwarder
1482 forwardord = 0;
1483 if(*forwardapi >= '0' && *forwardapi <= '9') {
1484 forwardord = atoi(forwardapi);
1485 }
1486 if(forwardord != 0 || (strlen(forwardapi) == 1 && *forwardapi == '0')) {
1487 exportaddr = WinDll->getApi(forwardord);
1488 }
1489 else exportaddr = WinDll->getApi(forwardapi);
1490
1491 if(apiname) {
1492 dprintf((LOG, "address 0x%x %s @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, apiname, ordinal, virtaddr, forwarddll, forwardapi));
1493 AddNameExport(exportaddr, apiname, ordinal, TRUE);
1494 }
1495 else {
1496 dprintf((LOG, "address 0x%x @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, ordinal, virtaddr, forwarddll, forwardapi));
1497 AddOrdExport(exportaddr, ordinal, TRUE);
1498 }
1499 free(forwarddll);
1500 return TRUE;
1501
1502fail:
1503 free(forwarddll);
1504 return FALSE;
1505}
1506//******************************************************************************
1507//******************************************************************************
1508Win32DllBase *Win32PeLdrImage::loadDll(char *pszCurModule)
1509{
1510 Win32DllBase *WinDll = NULL;
1511 char modname[CCHMAXPATH];
1512
1513 strcpy(modname, pszCurModule);
1514
1515 //rename dll if necessary (i.e. OLE32 -> OLE32OS2)
1516 Win32DllBase::renameDll(modname);
1517
1518 char szModName2[CCHMAXPATH];
1519 strcpy(szModName2, modname);
1520 if (!Win32ImageBase::findDll(szModName2, modname, sizeof(modname)))
1521 {
1522 dprintf((LOG, "Module %s not found!", modname));
1523 sprintf(szErrorModule, "%s", modname);
1524 errorState = 2;
1525 return NULL;
1526 }
1527
1528 if(isPEImage(modname, NULL) != ERROR_SUCCESS_W)
1529 {//LX image, so let OS/2 do all the work for us
1530 APIRET rc;
1531 char szModuleFailure[CCHMAXPATH] = "";
1532 ULONG hInstanceNewDll;
1533 Win32LxDll *lxdll;
1534
1535 char *dot = strchr(modname, '.');
1536 if(dot == NULL) {
1537 strcat(modname, DLL_EXTENSION);
1538 }
1539 rc = DosLoadModule(szModuleFailure, sizeof(szModuleFailure), modname, (HMODULE *)&hInstanceNewDll);
1540 if(rc) {
1541 dprintf((LOG, "DosLoadModule returned %X for %s", rc, szModuleFailure));
1542 sprintf(szErrorModule, "%s", szModuleFailure);
1543 errorState = rc;
1544 return NULL;
1545 }
1546 lxdll = Win32LxDll::findModuleByOS2Handle(hInstanceNewDll);
1547 if(lxdll == NULL) {//shouldn't happen!
1548 dprintf((LOG, "Just loaded the dll, but can't find it anywhere?!!?"));
1549 errorState = ERROR_INTERNAL;
1550 return NULL;
1551 }
1552 lxdll->setDllHandleOS2(hInstanceNewDll);
1553 if(lxdll->AddRef() == -1) {//-1 -> load failed (attachProcess)
1554 dprintf((LOG, "Dll %s refused to be loaded; aborting", modname));
1555 delete lxdll;
1556 errorState = ERROR_INTERNAL;
1557 return NULL;
1558 }
1559 WinDll = (Win32DllBase*)lxdll;
1560 }
1561 else {
1562 Win32PeLdrDll *pedll;
1563
1564 pedll = new Win32PeLdrDll(modname, this);
1565 if(pedll == NULL) {
1566 dprintf((LOG, "pedll: Error allocating memory" ));
1567 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szMemErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
1568 errorState = ERROR_INTERNAL;
1569 return NULL;
1570 }
1571 dprintf((LOG, "**********************************************************************" ));
1572 dprintf((LOG, "********************** Loading Module *********************" ));
1573 dprintf((LOG, "**********************************************************************" ));
1574 if(pedll->init(0) == FALSE) {
1575 dprintf((LOG, "Internal WinDll error ", pedll->getError() ));
1576 delete pedll;
1577 return NULL;
1578 }
1579#ifdef DEBUG
1580 pedll->AddRef(getModuleName());
1581#else
1582 pedll->AddRef();
1583#endif
1584 if(pedll->attachProcess() == FALSE) {
1585 dprintf((LOG, "attachProcess failed!" ));
1586 delete pedll;
1587 errorState = ERROR_INTERNAL;
1588 return NULL;
1589 }
1590 WinDll = (Win32DllBase*)pedll;
1591 }
1592
1593 dprintf((LOG, "**********************************************************************" ));
1594 dprintf((LOG, "********************** Finished Loading Module %s ", modname ));
1595 dprintf((LOG, "**********************************************************************" ));
1596
1597 return WinDll;
1598}
1599//******************************************************************************
1600/** All initial processing of imports is done here
1601 * Should now detect most Borland styled files including the GifCon32.exe and
1602 * loader32 from SoftIce. (Stupid Borland!!!)
1603 *
1604 * knut [Jul 22 1998 2:44am]
1605 **/
1606//******************************************************************************
1607BOOL Win32PeLdrImage::processImports(char *win32file)
1608{
1609 PIMAGE_IMPORT_DESCRIPTOR pID;
1610 IMAGE_SECTION_HEADER shID;
1611 IMAGE_SECTION_HEADER shExtra = {0};
1612 PIMAGE_OPTIONAL_HEADER pOH;
1613 int i,j, nrPages;
1614 BOOL fBorland = 0;
1615 int cModules;
1616 char *pszModules;
1617 char *pszCurModule;
1618 char *pszTmp;
1619 ULONG *pulImport;
1620 ULONG ulCurFixup;
1621 int Size;
1622 Win32DllBase *WinDll;
1623 Win32ImageBase *WinImage = NULL;
1624 Section *section;
1625
1626/* "algorithm:"
1627 * 1) get module names and store them
1628 * a) check dwRVAModuleName is within .idata seg - if not find section
1629 * 2) iterate thru functions of each module
1630 * a) check OriginalFirstThunk is not 0 and that it points to a RVA.
1631 * b) if not a) borland-styled PE-file - ARG!!!
1632 * check FirstThunk
1633 * c) check OriginalFirstThunk/FirstThunk ok RVAs and find right section
1634 * d) store ordinal/name import
1635 * 3) finished
1636 */
1637
1638 /* 1) get module names */
1639 pID = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT);
1640 if (pID == NULL)
1641 return TRUE;
1642 if (!GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT, &shID))
1643 return TRUE;
1644
1645 //calc size of module list
1646 i = Size = cModules = 0;
1647 while (pID[i].Name != 0)
1648 {
1649 //test RVA inside ID-Section
1650 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1651 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1652 }
1653 else {
1654 //is the "Extra"-section already found or do we have to find it?
1655 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1656 if (!GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name))
1657 return FALSE;
1658 }
1659 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1660 }
1661 Size += strlen(pszTmp) + 1;
1662 i++;
1663 cModules++;
1664 }
1665
1666 pszModules = (char*)malloc(Size);
1667 assert(pszModules != NULL);
1668 j = 0;
1669 for (i = 0; i < cModules; i++)
1670 {
1671 //test RVA inside ID-Section
1672 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1673 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1674 }
1675 else {
1676 fBorland = TRUE;
1677 //is the "Extra"-section already found or do we have to find it?
1678 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1679 {
1680 if (GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name)) {
1681 free(pszModules);
1682 return FALSE;
1683 }
1684 }
1685 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1686 }
1687
1688 strcpy(pszModules+j, pszTmp);
1689 j += strlen(pszTmp) + 1;
1690 }
1691 if (fBorland)
1692 dprintf((LOG, "Borland-styled PE-File." ));
1693
1694 //Store modules
1695 dprintf((LOG, "%d imported Modules: ", cModules ));
1696
1697 /* 2) functions */
1698 pszCurModule = pszModules;
1699 pOH = (PIMAGE_OPTIONAL_HEADER)OPTHEADEROFF(win32file);
1700 for (i = 0; i < cModules; i++)
1701 {
1702 dprintf((LOG, "Module %s", pszCurModule ));
1703 if(pID[i].ForwarderChain) {
1704 dprintf((LOG, "ForwarderChain: %x", pID[i].ForwarderChain));
1705 }
1706 // a) check that OriginalFirstThunk not is 0 and look for Borland-styled PE
1707 if (i == 0)
1708 {
1709 //heavy borland-style test - assume array of thunks is within that style does not change
1710 if((ULONG)pID[i].u.OriginalFirstThunk == 0 ||
1711 (ULONG)pID[i].u.OriginalFirstThunk < shID.VirtualAddress ||
1712 (ULONG)pID[i].u.OriginalFirstThunk >= shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData) ||
1713 (ULONG)pID[i].u.OriginalFirstThunk >= pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress &&
1714 (ULONG)pID[i].u.OriginalFirstThunk < sizeof(*pID)*cModules + pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1715 {
1716 fBorland = TRUE;
1717 }
1718 }
1719 //light borland-style test
1720 if (pID[i].u.OriginalFirstThunk == 0 || fBorland) {
1721 pulImport = (ULONG*)pID[i].FirstThunk;
1722 }
1723 else pulImport = (ULONG*)pID[i].u.OriginalFirstThunk;
1724
1725 // b) check if RVA ok
1726 if (!(pulImport > 0 && (ULONG)pulImport < pOH->SizeOfImage)) {
1727 dprintf((LOG, "Invalid RVA %x", pulImport ));
1728 break;
1729 }
1730 // check section
1731 if ((ULONG)pulImport < shExtra.VirtualAddress || (ULONG)pulImport >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1732 {
1733 if (!GetSectionHdrByRVA(win32file, &shExtra, (ULONG)pulImport))
1734 {
1735 dprintf((LOG, "warning: could not find section for Thunk RVA %x", pulImport ));
1736 break;
1737 }
1738 }
1739
1740 //SvL: Load dll if needed
1741 dprintf((LOG, "**********************************************************************" ));
1742 dprintf((LOG, "************** Import Module %s ", pszCurModule ));
1743 dprintf((LOG, "**********************************************************************" ));
1744 WinDll = Win32DllBase::findModule(pszCurModule);
1745
1746 if(WinDll == NULL)
1747 { //not found, so load it
1748 if (WinExe != NULL && WinExe->matchModName(pszCurModule)) {
1749 WinImage = (Win32ImageBase *)WinExe;
1750 }
1751 else {
1752 WinDll = loadDll(pszCurModule);
1753 if(WinDll == NULL) {
1754 return FALSE;
1755 }
1756 }
1757 }
1758 else {
1759 WinDll->AddRef();
1760 dprintf((LOG, "Already found ", pszCurModule));
1761 }
1762 if(WinDll != NULL) {
1763 //add the dll we just loaded to dependency list for this image
1764 addDependency(WinDll);
1765
1766 //Make sure the dependency list is correct (already done
1767 //in the ctor of Win32DllBase, but for LX dlls the parent is
1768 //then set to NULL; so change it here again
1769 WinDll->setUnloadOrder(this);
1770 WinImage = (Win32ImageBase *)WinDll;
1771 }
1772 else
1773 if(WinImage == NULL) {
1774 dprintf((LOG, "Unable to load dll %s", pszCurModule ));
1775 return FALSE;
1776 }
1777
1778 pulImport = (PULONG)((ULONG)pulImport + (ULONG)win32file);
1779 j = 0;
1780 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)win32file;
1781
1782 section = findSectionByOS2Addr(ulCurFixup);
1783 if(section == NULL) {
1784 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1785 return FALSE;
1786 }
1787 //SvL: Read page from disk
1788 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1789 //SvL: Enable write access
1790 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1791 nrPages = 1;
1792
1793 while (pulImport[j] != 0) {
1794 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1795 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1796 StoreImportByOrd(WinImage, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1797 }
1798 else { //name
1799 //check
1800 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1801 if (!GetSectionHdrByRVA(win32file, &shExtra, pulImport[j]))
1802 {
1803 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1804 break;
1805 }
1806 }
1807 //KSO - Aug 6 1998 1:15am:this eases comparing...
1808 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)win32file + 2);
1809 dprintf((LOG, "0x%08x Imported function %s (0x%08x)", ulCurFixup, pszFunctionName, WinImage->getApi(pszFunctionName)));
1810 StoreImportByName(WinImage, pszFunctionName, ulCurFixup);
1811 }
1812 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1813 j++;
1814 if((ulCurFixup & 0xfff) == 0) {
1815 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1816 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1817 nrPages++;
1818 }
1819 }
1820 //SvL: And restore original protection flags
1821 ulCurFixup = (ULONG)pID[i].FirstThunk + pOH->ImageBase;
1822 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1823
1824 dprintf((LOG, "**********************************************************************" ));
1825 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1826 dprintf((LOG, "**********************************************************************" ));
1827
1828 pszCurModule += strlen(pszCurModule) + 1;
1829 }//for (i = 0; i < cModules; i++)
1830
1831 free(pszModules);
1832 return TRUE;
1833}
1834//******************************************************************************
1835//******************************************************************************
1836BOOL Win32PeLdrImage::insideModule(ULONG address)
1837{
1838 if((address >= realBaseAddress) && (address < realBaseAddress + imageSize)) {
1839 return TRUE;
1840 }
1841 return FALSE;
1842}
1843//******************************************************************************
1844//******************************************************************************
1845BOOL Win32PeLdrImage::insideModuleCode(ULONG address)
1846{
1847 Section *sect;
1848
1849 sect = findSectionByOS2Addr(address);
1850 if(sect && (sect->pageflags & PAG_EXECUTE)) {
1851 return TRUE;
1852 }
1853 return FALSE;
1854}
1855//******************************************************************************
1856//******************************************************************************
1857ULONG Win32PeLdrImage::getImageSize()
1858{
1859 return imageSize;
1860}
1861//******************************************************************************
1862//******************************************************************************
1863#ifdef VERIFY_LOADER
1864ULONG Win32PeLdrImage::new_getApi(char *name)
1865#else
1866ULONG Win32PeLdrImage::getApi(char *name)
1867#endif
1868{
1869 // ordinal export from the lookup cache
1870 return (ULONG)pLookupName->getElement(name);
1871}
1872//******************************************************************************
1873//******************************************************************************
1874#ifdef VERIFY_LOADER
1875ULONG Win32PeLdrImage::new_getApi(int ordinal)
1876#else
1877ULONG Win32PeLdrImage::getApi(int ordinal)
1878#endif
1879{
1880 // ordinal export from the lookup cache
1881 return (ULONG)pLookupOrdinal->getElement(ordinal);
1882}
1883//******************************************************************************
1884//******************************************************************************
1885#ifdef VERIFY_LOADER
1886ULONG Win32PeLdrImage::getApi(char *name)
1887{
1888 ULONG ulVerify1 = new_getApi(name);
1889 ULONG ulVerify2 = old_getApi(name);
1890
1891 if (ulVerify1 != ulVerify2)
1892 dprintf((LOG,
1893 "WinImagePeLdr::getApi(%s) difference: ulVerify1=%08xh, ulVerify2=%08xh\n",
1894 name,
1895 ulVerify1,
1896 ulVerify2));
1897
1898 return ulVerify2;
1899}
1900
1901
1902ULONG Win32PeLdrImage::getApi(int ordinal)
1903{
1904 ULONG ulVerify1 = new_getApi(ordinal);
1905 ULONG ulVerify2 = old_getApi(ordinal);
1906
1907 if (ulVerify1 != ulVerify2)
1908 dprintf((LOG,
1909 "WinImagePeLdr::getApi(%d) difference: ulVerify1=%08xh, ulVerify2=%08xh\n",
1910 ordinal,
1911 ulVerify1,
1912 ulVerify2));
1913
1914 return ulVerify2;
1915}
1916
1917
1918
1919
1920ULONG Win32PeLdrImage::old_getApi(char *name)
1921{
1922 ULONG apiaddr, i, apilen;
1923 char *apiname;
1924 char tmp[4];
1925 NameExport *curexport;
1926 ULONG ulAPIOrdinal; /* api requested by ordinal */
1927
1928 apilen = strlen(name) + 1;
1929 if(apilen < 4)
1930 {
1931 *(ULONG *)tmp = 0;
1932 strcpy(tmp, name);
1933 apiname = tmp;
1934 apilen = 4;
1935 }
1936 else apiname = name;
1937
1938 curexport = nameexports;
1939 for(i=0; i<nrNameExports; i++)
1940 {
1941 if(apilen == curexport->nlength &&
1942 *(ULONG *)curexport->name == *(ULONG *)apiname)
1943 {
1944 if(strcmp(curexport->name, apiname) == 0)
1945 return(curexport->virtaddr);
1946 }
1947 curexport = (NameExport *)((ULONG)curexport->name + curexport->nlength);
1948 }
1949 return(0);
1950}
1951//******************************************************************************
1952//******************************************************************************
1953ULONG Win32PeLdrImage::old_getApi(int ordinal)
1954{
1955 ULONG apiaddr, i;
1956 OrdExport *curexport;
1957 NameExport *nexport;
1958
1959 curexport = ordexports;
1960 for(i=0;i<nrOrdExports;i++) {
1961 if(curexport->ordinal == ordinal)
1962 return(curexport->virtaddr);
1963 curexport++;
1964 }
1965 //Name exports also contain an ordinal, so check this
1966 nexport = nameexports;
1967 for(i=0;i<nrNameExports;i++) {
1968 if(nexport->ordinal == ordinal)
1969 return(nexport->virtaddr);
1970
1971 nexport = (NameExport *)((ULONG)nexport->name + nexport->nlength);
1972 }
1973 return(0);
1974}
1975#endif
1976//******************************************************************************
1977//Returns required OS version for this image
1978//******************************************************************************
1979ULONG Win32PeLdrImage::getVersion()
1980{
1981 return (oh.MajorOperatingSystemVersion << 16) | oh.MinorOperatingSystemVersion;
1982}
1983//******************************************************************************
1984//******************************************************************************
1985ULONG MissingApi()
1986{
1987 static BOOL fIgnore = FALSE;
1988 int r;
1989
1990 dprintf((LOG, "Missing api called!\n"));
1991 if(fIgnore)
1992 return(0);
1993
1994 do {
1995 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, "The application has called a non-existing api\n",
1996 "Internal Odin Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
1997 }
1998 while(r == MBID_RETRY); //giggle
1999
2000 if( r != MBID_IGNORE )
2001 ExitProcess(987);
2002
2003 fIgnore = TRUE;
2004 return(0);
2005}
2006/******************************************************************************/
2007/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.