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

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

SetWin32TIB update + force change to win32 FS selector for calling PE image entrypoints

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