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

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

TLS callback fixes

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