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

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

TLS fixes

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