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

Last change on this file since 8914 was 8914, checked in by sandervl, 23 years ago

bugfix for pe offset when mapping view

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