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

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

Rewrote algorithm for 64kb alignment in VirtualAlloc'ed memory; allocation changes for heap (in 64kb chunks) & PE image (align at 64kb)

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