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

Last change on this file since 5959 was 5959, checked in by sandervl, 24 years ago

CreateProcess: launch win16 loader for NE executables

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