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

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

Vio fix for high memory + fixes&updates for dll name lookup with extension

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