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

Last change on this file since 5168 was 5128, checked in by sandervl, 25 years ago

TLS index allocation + RtlUnwind fixes

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