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

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

resource directory location fix

File size: 66.2 KB
Line 
1/* $Id: winimagepeldr.cpp,v 1.65 2000-12-05 20:41:43 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(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress && oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size)
605 {
606 //get offset in resource object of directory entry
607 pResRootDir = (PIMAGE_RESOURCE_DIRECTORY)(oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress + realBaseAddress);
608 ulRVAResourceSection = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
609 }
610
611 if(!(dwFlags & (FLAG_PELDR_LOADASDATAFILE | FLAG_PELDR_SKIPIMPORTS)))
612 {
613 if(processImports((char *)win32file) == FALSE) {
614 dprintf((LOG, "Failed to process imports!" ));
615 goto failure;
616 }
617 }
618 return(TRUE);
619
620failure:
621 if(memmap) {
622 delete memmap;
623 memmap = NULL;
624 }
625 if(hFile) {
626 OSLibDosClose(hFile);
627 hFile = 0;
628 }
629 errorState = ERROR_INTERNAL;
630 return FALSE;
631}
632//******************************************************************************
633//commits image page(s) when an access violation exception is dispatched
634//virtAddress = address of exception (rounded down to page boundary)
635//******************************************************************************
636BOOL Win32PeLdrImage::commitPage(ULONG virtAddress, BOOL fWriteAccess, int fPageCmd)
637{
638 Section *section;
639 ULONG offset, size, sectionsize, protflags, fileoffset, range, attr;
640 ULONG ulNewPos, ulRead;
641 APIRET rc;
642
643 //Round down to nearest page boundary
644 virtAddress = virtAddress & ~0xFFF;
645
646 section = findSectionByOS2Addr(virtAddress);
647 if(section == NULL) {
648 size = 4096;
649 sectionsize = 4096;
650 protflags = PAG_READ|PAG_WRITE; //readonly?
651 section = findPreviousSectionByOS2Addr(virtAddress);
652 if(section == NULL) {//access to header
653 offset = 0;
654 fileoffset = virtAddress - realBaseAddress;
655 }
656 else {
657 offset = virtAddress - (section->realvirtaddr + section->virtualsize);
658 fileoffset = section->rawoffset + section->rawsize + offset;
659 }
660 }
661 else {
662 protflags = section->pageflags;
663 offset = virtAddress - section->realvirtaddr;
664 sectionsize = section->virtualsize - offset;
665
666 if(offset > section->rawsize || section->type == SECTION_UNINITDATA) {
667 //unintialized data (set to 0)
668 size = 0;
669 fileoffset = -1;
670 }
671 else {
672 size = section->rawsize-offset;
673 fileoffset = section->rawoffset + offset;
674 }
675 if(fWriteAccess & !(section->pageflags & PAG_WRITE)) {
676 dprintf((LOG, "Win32PeLdrImage::commitPage: No write access to 0%x!", virtAddress));
677 return FALSE;
678 }
679 }
680 //Check range of pages with the same attributes starting at virtAddress
681 //(some pages might already have been loaded)
682 range = sectionsize;
683 rc = DosQueryMem((PVOID)virtAddress, &range, &attr);
684 if(rc) {
685 dprintf((LOG, "Win32PeLdrImage::commitPage: DosQueryMem for %x returned %d", virtAddress, rc));
686 return FALSE;
687 }
688 if(attr & PAG_COMMIT) {
689 dprintf((LOG, "Win32PeLdrImage::commitPage: Memory at 0x%x already committed!", virtAddress));
690 return FALSE;
691 }
692
693 if(fPageCmd == SINGLE_PAGE) {
694 size = min(size, PAGE_SIZE);
695 sectionsize = min(sectionsize, PAGE_SIZE);
696 }
697 else
698 if(fPageCmd == SECTION_PAGES) {
699 size = min(size, DEFAULT_NR_PAGES*PAGE_SIZE);
700 sectionsize = min(sectionsize, DEFAULT_NR_PAGES*PAGE_SIZE);
701 }
702 size = min(size, range);
703 sectionsize = min(sectionsize, range);
704
705 if(fileoffset != -1) {
706 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
707 if(rc) {
708 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
709 return FALSE;
710 }
711
712 if(DosSetFilePtr(hFile, fileoffset, FILE_BEGIN, &ulNewPos) == -1) {
713 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetFilePtr failed for 0x%x!", fileoffset));
714 return FALSE;
715 }
716 if(DosRead(hFile, (PVOID)virtAddress, size, &ulRead)) {
717 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed for 0x%x!", virtAddress));
718 return FALSE;
719 }
720 if(ulRead != size) {
721 dprintf((LOG, "Win32PeLdrImage::commitPage: DosRead failed to read %x (%x) bytes at %x for 0x%x!", size, ulRead, fileoffset, virtAddress));
722 return FALSE;
723 }
724 setFixups(virtAddress, sectionsize);
725
726 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
727 if(rc) {
728 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
729 return FALSE;
730 }
731 }
732 else {
733 rc = DosSetMem((PVOID)virtAddress, sectionsize, PAG_READ|PAG_WRITE|PAG_COMMIT);
734 if(rc) {
735 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
736 return FALSE;
737 }
738 setFixups(virtAddress, sectionsize);
739
740 rc = DosSetMem((PVOID)virtAddress, sectionsize, protflags);
741 if(rc) {
742 dprintf((LOG, "Win32PeLdrImage::commitPage: DosSetMem failed (%d)!", rc));
743 return FALSE;
744 }
745 }
746 return TRUE;
747}
748//******************************************************************************
749//******************************************************************************
750void Win32PeLdrImage::addSection(ULONG type, ULONG rawoffset, ULONG rawsize, ULONG virtaddress, ULONG virtsize, ULONG flags)
751{
752 virtsize = max(rawsize, virtsize);
753
754 section[nrsections].rawoffset = rawoffset;
755 section[nrsections].type = type;
756 section[nrsections].rawsize = rawsize;
757 section[nrsections].virtaddr = virtaddress;
758 section[nrsections].flags = flags;
759
760 virtsize = ((virtsize - 1) & ~0xFFF) + PAGE_SIZE;
761 imageSize += virtsize;
762 section[nrsections].virtualsize = virtsize;
763
764 if(virtaddress < imageVirtBase)
765 imageVirtBase = virtaddress;
766 if(virtaddress + virtsize > imageVirtEnd)
767 imageVirtEnd = virtaddress + virtsize;
768
769 nrsections++;
770}
771//******************************************************************************
772//******************************************************************************
773BOOL Win32PeLdrImage::allocSections(ULONG reservedMem)
774{
775 APIRET rc;
776 ULONG baseAddress;
777
778 realBaseAddress = 0;
779
780 //Allocated in by pe.exe
781 if(reservedMem && reservedMem == oh.ImageBase) {
782 realBaseAddress = oh.ImageBase;
783 return TRUE;
784 }
785
786 //SvL: We don't care where the image is loaded for resource lookup
787 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED && !(dwFlags & FLAG_PELDR_LOADASDATAFILE)) {
788 return allocFixedMem(reservedMem);
789 }
790 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | flAllocMem);
791 if(rc) {
792 dprintf((LOG, "Win32PeLdrImage::allocSections, DosAllocMem returned %d", rc));
793 errorState = rc;
794 return(FALSE);
795 }
796 realBaseAddress = baseAddress;
797 return(TRUE);
798}
799//******************************************************************************
800//******************************************************************************
801Section *Win32PeLdrImage::findSection(ULONG type)
802{
803 for(int i=0;i<nrsections;i++) {
804 if(section[i].type == type) {
805 return &section[i];
806 }
807 }
808 return NULL;
809}
810//******************************************************************************
811//******************************************************************************
812Section *Win32PeLdrImage::findSectionByAddr(ULONG addr)
813{
814 for(int i=0;i<nrsections;i++) {
815 if(section[i].virtaddr <= addr && section[i].virtaddr + section[i].virtualsize > addr) {
816 return &section[i];
817 }
818 }
819 return NULL;
820}
821//******************************************************************************
822//******************************************************************************
823Section *Win32PeLdrImage::findSectionByOS2Addr(ULONG addr)
824{
825 for(int i=0;i<nrsections;i++) {
826 if(section[i].realvirtaddr <= addr && section[i].realvirtaddr + section[i].virtualsize > addr) {
827 return &section[i];
828 }
829 }
830 return NULL;
831}
832//******************************************************************************
833//******************************************************************************
834Section *Win32PeLdrImage::findPreviousSectionByOS2Addr(ULONG addr)
835{
836 ULONG lowestAddr = 0xffffffff;
837 ULONG index = -1;
838
839 for(int i=0;i<nrsections;i++) {
840 if(section[i].realvirtaddr > addr) {
841 if(section[i].realvirtaddr < lowestAddr) {
842 lowestAddr = section[i].realvirtaddr;
843 index = i;
844 }
845 }
846 }
847 if(index == -1)
848 return NULL;
849
850 return &section[index];
851}
852//******************************************************************************
853#define FALLOC_SIZE (1024*1024)
854//NOTE: Needs testing (while loop)
855//TODO: Free unused (parts of) reservedMem
856//******************************************************************************
857BOOL Win32PeLdrImage::allocFixedMem(ULONG reservedMem)
858{
859 ULONG address = 0;
860 ULONG *memallocs;
861 ULONG alloccnt = 0;
862 ULONG diff, i, baseAddress;
863 APIRET rc;
864 BOOL allocFlags = flAllocMem;
865
866 //Reserve enough space to store 4096 pointers to 1MB memory chunks
867 memallocs = (ULONG *)malloc(4096*sizeof(ULONG *));
868 if(memallocs == NULL) {
869 dprintf((LOG, "allocFixedMem: MALLOC FAILED for memallocs" ));
870 return FALSE;
871 }
872
873 if(oh.ImageBase < 512*1024*1024) {
874 allocFlags = 0;
875 }
876 while(TRUE) {
877 rc = DosAllocMem((PPVOID)&address, FALLOC_SIZE, PAG_READ | allocFlags);
878 if(rc) break;
879
880 dprintf((LOG, "DosAllocMem returned %x", address ));
881 if(address + FALLOC_SIZE >= oh.ImageBase) {
882 if(address > oh.ImageBase) {//we've passed it!
883 DosFreeMem((PVOID)address);
884 break;
885 }
886 //found the right address
887 DosFreeMem((PVOID)address);
888
889 diff = oh.ImageBase - address;
890 if(diff) {
891 rc = DosAllocMem((PPVOID)&address, diff, PAG_READ | allocFlags);
892 if(rc) break;
893 }
894 rc = DosAllocMem((PPVOID)&baseAddress, imageSize, PAG_READ | PAG_WRITE | allocFlags);
895 if(rc) break;
896
897 if(diff) DosFreeMem((PVOID)address);
898
899 realBaseAddress = baseAddress;
900 break;
901 }
902 memallocs[alloccnt++] = address;
903 }
904 for(i=0;i<alloccnt;i++) {
905 DosFreeMem((PVOID)memallocs[i]);
906 }
907 free(memallocs);
908
909 if(realBaseAddress == 0) //Let me guess.. MS Office app?
910 return(FALSE);
911
912 return(TRUE);
913}
914//******************************************************************************
915//******************************************************************************
916BOOL Win32PeLdrImage::setMemFlags()
917{
918 int i;
919 WINIMAGE_LOOKUP *imgLookup;
920
921 imgLookup = WINIMAGE_LOOKUPADDR(realBaseAddress);
922 imgLookup->magic1 = MAGIC_WINIMAGE;
923 imgLookup->image = this;
924 imgLookup->magic2 = MAGIC_WINIMAGE;
925
926 // Process all the image sections
927 for(i=0;i<nrsections;i++) {
928 section[i].realvirtaddr = realBaseAddress + (section[i].virtaddr - oh.ImageBase);
929 }
930
931 for(i=0;i<nrsections;i++) {
932 switch(section[i].type)
933 {
934 case SECTION_CODE:
935 case (SECTION_CODE | SECTION_IMPORT):
936 section[i].pageflags = PAG_EXECUTE | PAG_READ;
937 if(section[i].flags & IMAGE_SCN_MEM_WRITE)
938 section[i].pageflags |= PAG_WRITE;
939 break;
940 case SECTION_INITDATA:
941 case SECTION_UNINITDATA:
942 case SECTION_IMPORT:
943 case SECTION_TLS:
944 section[i].pageflags = PAG_WRITE | PAG_READ;
945 break;
946
947 case SECTION_RESOURCE:
948 //TODO: GDI32 changes some bitmap structures to avoid problems in Open32
949 // -> causes crashes if resource section is readonly
950 // -> make it readonly again when gdi32 has been rewritten
951 section[i].pageflags = PAG_WRITE | PAG_READ;
952 break;
953
954 case SECTION_READONLYDATA:
955 case SECTION_EXPORT:
956 default:
957 section[i].pageflags = PAG_READ;
958 break;
959 }
960 if(section[i].flags & (IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_CNT_UNINITIALIZED_DATA)) {
961 //SvL: sometimes i.e. import/export sections also contain data
962 // must make them read/write
963 section[i].pageflags = PAG_WRITE;
964 }
965
966 }
967 return(TRUE);
968}
969//******************************************************************************
970//******************************************************************************
971BOOL Win32PeLdrImage::setFixups(ULONG virtAddress, ULONG size)
972{
973 int i, j;
974 char *page;
975 ULONG count, newpage;
976 Section *section;
977 PIMAGE_BASE_RELOCATION prel = pFixups;
978
979 if(realBaseAddress == oh.ImageBase || fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
980 return(TRUE);
981 }
982
983 virtAddress -= realBaseAddress;
984 //round size to next page boundary
985 size = (size-1) & ~0xFFF;
986 size += PAGE_SIZE;
987
988 if(prel) {
989 j = 1;
990 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
991 prel->VirtualAddress && prel->VirtualAddress < virtAddress)
992 {
993 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
994 }
995 while(((ULONG)prel < (ULONG)pFixups+dwFixupSize) &&
996 prel->VirtualAddress && prel->VirtualAddress < virtAddress + size)
997 {
998 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
999 count = (prel->SizeOfBlock - 8)/2;
1000 j++;
1001 for(i=0;i<count;i++) {
1002 int type = prel->TypeOffset[i] >> 12;
1003 int offset = prel->TypeOffset[i] & 0xFFF;
1004 int fixupsize = 0;
1005
1006 switch(type)
1007 {
1008 case IMAGE_REL_BASED_HIGHLOW:
1009 fixupsize = 4;
1010 break;
1011 case IMAGE_REL_BASED_HIGH:
1012 case IMAGE_REL_BASED_LOW:
1013 fixupsize = 2;
1014 break;
1015 }
1016 //If the fixup crosses the final page boundary,
1017 //then we have to load another page
1018 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
1019 {
1020 newpage = realBaseAddress + prel->VirtualAddress + offset + fixupsize;
1021 newpage &= ~0xFFF;
1022
1023 section = findSectionByOS2Addr(newpage);
1024 if(section == NULL) {
1025 //should never happen
1026 dprintf((LOG, "::setFixups -> section == NULL!!"));
1027 return FALSE;
1028 }
1029 //SvL: Read page from disk
1030 commitPage(newpage, FALSE, SINGLE_PAGE);
1031
1032 //SvL: Enable write access
1033 DosSetMem((PVOID)newpage, PAGE_SIZE, PAG_READ|PAG_WRITE);
1034 }
1035
1036 switch(type)
1037 {
1038 case IMAGE_REL_BASED_ABSOLUTE:
1039 break; //skip
1040 case IMAGE_REL_BASED_HIGHLOW:
1041 AddOff32Fixup(prel->VirtualAddress + offset);
1042 break;
1043 case IMAGE_REL_BASED_HIGH:
1044 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
1045 break;
1046 case IMAGE_REL_BASED_LOW:
1047 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
1048 break;
1049 case IMAGE_REL_BASED_HIGHADJ:
1050 case IMAGE_REL_BASED_MIPS_JMPADDR:
1051 default:
1052 break;
1053 }
1054 if(prel->VirtualAddress + offset + fixupsize > virtAddress + size)
1055 {
1056 //SvL: Restore original page protection flags
1057 DosSetMem((PVOID)newpage, PAGE_SIZE, section->pageflags);
1058 }
1059 }
1060 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1061 }//while
1062 }
1063 else {
1064 dprintf((LOG, "Win32PeLdrImage::setFixups, no fixups at %x, %d", virtAddress, size));
1065 return(FALSE);
1066 }
1067 return(TRUE);
1068}
1069//******************************************************************************
1070//******************************************************************************
1071BOOL Win32PeLdrImage::setFixups(PIMAGE_BASE_RELOCATION prel)
1072{
1073 int i, j;
1074 char *page;
1075 ULONG count;
1076
1077 if(fh.Characteristics & IMAGE_FILE_RELOCS_STRIPPED) {
1078 return(TRUE);
1079 }
1080
1081 if(prel) {
1082 j = 1;
1083 while(prel->VirtualAddress) {
1084 page = (char *)((char *)prel + (ULONG)prel->VirtualAddress);
1085 count = (prel->SizeOfBlock - 8)/2;
1086 dprintf((LOG, "Page %d Address %x Count %d", j, prel->VirtualAddress, count ));
1087 j++;
1088 for(i=0;i<count;i++) {
1089 int type = prel->TypeOffset[i] >> 12;
1090 int offset = prel->TypeOffset[i] & 0xFFF;
1091 switch(type) {
1092 case IMAGE_REL_BASED_ABSOLUTE:
1093//// dprintf((LOG, "absolute fixup; unused" ));
1094 break; //skip
1095 case IMAGE_REL_BASED_HIGHLOW:
1096//// dprintf((LOG, "address ", offset << " type ", type ));
1097 AddOff32Fixup(prel->VirtualAddress + offset);
1098 break;
1099 case IMAGE_REL_BASED_HIGH:
1100 AddOff16Fixup(prel->VirtualAddress + offset, TRUE);
1101 break;
1102 case IMAGE_REL_BASED_LOW:
1103 AddOff16Fixup(prel->VirtualAddress + offset, FALSE);
1104 break;
1105 case IMAGE_REL_BASED_HIGHADJ:
1106 case IMAGE_REL_BASED_MIPS_JMPADDR:
1107 default:
1108 dprintf((LOG, "Unknown/unsupported fixup type!" ));
1109 break;
1110 }
1111 }
1112 prel = (PIMAGE_BASE_RELOCATION)((char*)prel + prel->SizeOfBlock);
1113 }//while
1114 }
1115 else {
1116 dprintf((LOG, "No internal fixups found!" ));
1117 errorState = ERROR_INTERNAL;
1118 return(FALSE);
1119 }
1120 return(TRUE);
1121}
1122//******************************************************************************
1123//******************************************************************************
1124void Win32PeLdrImage::AddOff32Fixup(ULONG fixupaddr)
1125{
1126 ULONG orgaddr;
1127 ULONG *fixup;
1128
1129 fixup = (ULONG *)(fixupaddr + realBaseAddress);
1130 orgaddr = *fixup;
1131// dprintf((LOG, "AddOff32Fixup 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, realBaseAddress + (*fixup - oh.ImageBase)));
1132 *fixup = realBaseAddress + (*fixup - oh.ImageBase);
1133}
1134//******************************************************************************
1135//******************************************************************************
1136void Win32PeLdrImage::AddOff16Fixup(ULONG fixupaddr, BOOL fHighFixup)
1137{
1138 ULONG orgaddr;
1139 USHORT *fixup;
1140
1141 fixup = (USHORT *)(fixupaddr + realBaseAddress);
1142 orgaddr = *fixup;
1143 if(fHighFixup) {
1144 *fixup += (USHORT)((realBaseAddress - oh.ImageBase) >> 16);
1145// dprintf((LOG, "AddOff16FixupH 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1146 }
1147 else {
1148 *fixup += (USHORT)((realBaseAddress - oh.ImageBase) & 0xFFFF);
1149// dprintf((LOG, "AddOff16FixupL 0x%x org 0x%x -> new 0x%x", fixup, orgaddr, *fixup));
1150 }
1151}
1152//******************************************************************************
1153//******************************************************************************
1154void Win32PeLdrImage::StoreImportByOrd(Win32DllBase *WinDll, ULONG ordinal, ULONG impaddr)
1155{
1156 ULONG *import;
1157 ULONG apiaddr;
1158
1159 import = (ULONG *)impaddr;
1160 apiaddr = WinDll->getApi(ordinal);
1161 if(apiaddr == 0)
1162 {
1163 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%u not found\n",
1164 WinDll->getName(),
1165 ordinal));
1166
1167 dprintf((LOG, "--->>> NOT FOUND!" ));
1168 *import = (ULONG)MissingApi;
1169 }
1170 else *import = apiaddr;
1171}
1172//******************************************************************************
1173//******************************************************************************
1174void Win32PeLdrImage::StoreImportByName(Win32DllBase *WinDll, char *impname, ULONG impaddr)
1175{
1176 ULONG *import;
1177 ULONG apiaddr;
1178
1179 import = (ULONG *)impaddr;
1180 apiaddr = WinDll->getApi(impname);
1181 if(apiaddr == 0)
1182 {
1183 dprintf((LOG, "KERNEL32:Win32PeLdrImage - %s.%s not found\n",
1184 WinDll->getName(),
1185 impname));
1186
1187 dprintf((LOG, "--->>> NOT FOUND!" ));
1188 *import = (ULONG)MissingApi;
1189 }
1190 else *import = apiaddr;
1191}
1192//******************************************************************************
1193//******************************************************************************
1194BOOL Win32PeLdrImage::processExports(char *win32file)
1195{
1196 IMAGE_SECTION_HEADER sh;
1197 PIMAGE_EXPORT_DIRECTORY ped;
1198 ULONG *ptrNames, *ptrAddress;
1199 USHORT *ptrOrd;
1200 BOOL fForwarder;
1201 int i;
1202
1203 /* get section header and pointer to data directory for .edata section */
1204 if((ped = (PIMAGE_EXPORT_DIRECTORY)ImageDirectoryOffset
1205 (win32file, IMAGE_DIRECTORY_ENTRY_EXPORT)) != NULL &&
1206 GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_EXPORT, &sh) ) {
1207
1208 dprintf((LOG, "Exported Functions: " ));
1209 ptrOrd = (USHORT *)((ULONG)ped->AddressOfNameOrdinals +
1210 (ULONG)win32file);
1211 ptrNames = (ULONG *)((ULONG)ped->AddressOfNames +
1212 (ULONG)win32file);
1213 ptrAddress = (ULONG *)((ULONG)ped->AddressOfFunctions +
1214 (ULONG)win32file);
1215 nrOrdExports = ped->NumberOfFunctions;
1216 nrNameExports = ped->NumberOfNames;
1217
1218 int ord, RVAExport;
1219 char *name;
1220 for(i=0;i<ped->NumberOfNames;i++)
1221 {
1222 fForwarder = FALSE;
1223 ord = ptrOrd[i] + ped->Base;
1224 name = (char *)((ULONG)ptrNames[i] + (ULONG)win32file);
1225 RVAExport = ptrAddress[ptrOrd[i]];
1226
1227 /* forwarder? ulRVA within export directory. */
1228 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1229 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1230 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1231 {
1232 fForwarder = AddForwarder(oh.ImageBase + RVAExport, name, ord);
1233 }
1234 if(!fForwarder) {
1235 //points to code (virtual address relative to oh.ImageBase
1236 AddNameExport(oh.ImageBase + RVAExport, name, ord);
1237 dprintf((LOG, "address 0x%x %s @%d (0x%08x)", RVAExport, name, ord, realBaseAddress + RVAExport));
1238 }
1239 }
1240 for(i=0;i<max(ped->NumberOfNames,ped->NumberOfFunctions);i++)
1241 {
1242 fForwarder = FALSE;
1243 ord = ped->Base + i; //Correct??
1244 RVAExport = ptrAddress[i];
1245 /* forwarder? ulRVA within export directory. */
1246 if(RVAExport > oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &&
1247 RVAExport < oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress
1248 + oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)
1249 {
1250 fForwarder = AddForwarder(oh.ImageBase + RVAExport, NULL, ord);
1251 }
1252 if(!fForwarder && RVAExport) {
1253 //points to code (virtual address relative to oh.ImageBase
1254 dprintf((LOG, "ord %d at 0x%08x (0x%08x)", ord, RVAExport, realBaseAddress + RVAExport));
1255 AddOrdExport(oh.ImageBase + RVAExport, ord);
1256 }
1257 }
1258 }
1259 return(TRUE);
1260}
1261//******************************************************************************
1262//******************************************************************************
1263void Win32PeLdrImage::AddNameExport(ULONG virtaddr, char *apiname, ULONG ordinal, BOOL fAbsoluteAddress)
1264{
1265 ULONG nsize;
1266
1267 if(nameexports == NULL) {
1268 nameExportSize= 4096;
1269 nameexports = (NameExport *)malloc(nameExportSize);
1270 curnameexport = nameexports;
1271 }
1272 nsize = (ULONG)curnameexport - (ULONG)nameexports;
1273 if(nsize + sizeof(NameExport) + strlen(apiname) > nameExportSize) {
1274 nameExportSize += 4096;
1275 char *tmp = (char *)nameexports;
1276 nameexports = (NameExport *)malloc(nameExportSize);
1277 memcpy(nameexports, tmp, nsize);
1278 curnameexport = (NameExport *)((ULONG)nameexports + nsize);
1279 free(tmp);
1280 }
1281 if(fAbsoluteAddress) {//forwarders use absolute address
1282 curnameexport->virtaddr = virtaddr;
1283 }
1284 else curnameexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1285 curnameexport->ordinal = ordinal;
1286 *(ULONG *)curnameexport->name = 0;
1287 strcpy(curnameexport->name, apiname);
1288
1289 curnameexport->nlength = strlen(apiname) + 1;
1290 if(curnameexport->nlength < sizeof(curnameexport->name))
1291 curnameexport->nlength = sizeof(curnameexport->name);
1292
1293 curnameexport = (NameExport *)((ULONG)curnameexport->name + curnameexport->nlength);
1294}
1295//******************************************************************************
1296//******************************************************************************
1297void Win32PeLdrImage::AddOrdExport(ULONG virtaddr, ULONG ordinal, BOOL fAbsoluteAddress)
1298{
1299 if(ordexports == NULL) {
1300 ordexports = (OrdExport *)malloc(nrOrdExports * sizeof(OrdExport));
1301 curordexport = ordexports;
1302 }
1303 if(fAbsoluteAddress) {//forwarders use absolute address
1304 curordexport->virtaddr = virtaddr;
1305 }
1306 else curordexport->virtaddr = realBaseAddress + (virtaddr - oh.ImageBase);
1307 curordexport->ordinal = ordinal;
1308 curordexport++;
1309}
1310//******************************************************************************
1311//******************************************************************************
1312BOOL Win32PeLdrImage::AddForwarder(ULONG virtaddr, char *apiname, ULONG ordinal)
1313{
1314 char *forward = (char *)(realBaseAddress + (virtaddr - oh.ImageBase));
1315 char *forwarddll, *forwardapi;
1316 Win32DllBase *WinDll;
1317 DWORD exportaddr;
1318 int forwardord;
1319
1320 forwarddll = strdup(forward);
1321 if(forwarddll == NULL) {
1322 return FALSE;
1323 }
1324 forwardapi = strchr(forwarddll, '.');
1325 if(forwardapi == NULL) {
1326 goto fail;
1327 }
1328 *forwardapi++ = 0;
1329 if(strlen(forwarddll) == 0 || strlen(forwardapi) == 0) {
1330 goto fail;
1331 }
1332 WinDll = Win32DllBase::findModule(forwarddll);
1333 if(WinDll == NULL) {
1334 WinDll = loadDll(forwarddll);
1335 if(WinDll == NULL) {
1336 dprintf((LOG, "ERROR: couldn't find forwarder %s.%s", forwarddll, forwardapi));
1337 goto fail;
1338 }
1339 }
1340 //check if name or ordinal forwarder
1341 forwardord = 0;
1342 if(*forwardapi >= '0' && *forwardapi <= '9') {
1343 forwardord = atoi(forwardapi);
1344 }
1345 if(forwardord != 0 || (strlen(forwardapi) == 1 && *forwardapi == '0')) {
1346 exportaddr = WinDll->getApi(forwardord);
1347 }
1348 else exportaddr = WinDll->getApi(forwardapi);
1349
1350 if(apiname) {
1351 dprintf((LOG, "address 0x%x %s @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, apiname, ordinal, virtaddr, forwarddll, forwardapi));
1352 AddNameExport(exportaddr, apiname, ordinal, TRUE);
1353 }
1354 else {
1355 dprintf((LOG, "address 0x%x @%d (0x%08x) forwarder %s.%s", virtaddr - oh.ImageBase, ordinal, virtaddr, forwarddll, forwardapi));
1356 AddOrdExport(exportaddr, ordinal, TRUE);
1357 }
1358 free(forwarddll);
1359 return TRUE;
1360
1361fail:
1362 free(forwarddll);
1363 return FALSE;
1364}
1365//******************************************************************************
1366//******************************************************************************
1367Win32DllBase *Win32PeLdrImage::loadDll(char *pszCurModule)
1368{
1369 Win32DllBase *WinDll = NULL;
1370 char modname[CCHMAXPATH];
1371
1372 strcpy(modname, pszCurModule);
1373
1374 //rename dll if necessary (i.e. OLE32 -> OLE32OS2)
1375 Win32DllBase::renameDll(modname);
1376
1377 char szModName2[CCHMAXPATH];
1378 strcpy(szModName2, modname);
1379 if (!Win32ImageBase::findDll(szModName2, modname, sizeof(modname)))
1380 {
1381 dprintf((LOG, "Module %s not found!", modname));
1382 sprintf(szErrorModule, "%s", modname);
1383 errorState = 2;
1384 return NULL;
1385 }
1386
1387 if(isPEImage(modname) != ERROR_SUCCESS_W)
1388 {//LX image, so let OS/2 do all the work for us
1389 APIRET rc;
1390 char szModuleFailure[CCHMAXPATH] = "";
1391 ULONG hInstanceNewDll;
1392 Win32LxDll *lxdll;
1393
1394 char *dot = strchr(modname, '.');
1395 if(dot == NULL) {
1396 strcat(modname, DLL_EXTENSION);
1397 }
1398 rc = DosLoadModule(szModuleFailure, sizeof(szModuleFailure), modname, (HMODULE *)&hInstanceNewDll);
1399 if(rc) {
1400 dprintf((LOG, "DosLoadModule returned %X for %s", rc, szModuleFailure));
1401 sprintf(szErrorModule, "%s", szModuleFailure);
1402 errorState = rc;
1403 return NULL;
1404 }
1405 lxdll = Win32LxDll::findModuleByOS2Handle(hInstanceNewDll);
1406 if(lxdll == NULL) {//shouldn't happen!
1407 dprintf((LOG, "Just loaded the dll, but can't find it anywhere?!!?"));
1408 errorState = ERROR_INTERNAL;
1409 return NULL;
1410 }
1411 lxdll->setDllHandleOS2(hInstanceNewDll);
1412 if(lxdll->AddRef() == -1) {//-1 -> load failed (attachProcess)
1413 dprintf((LOG, "Dll %s refused to be loaded; aborting", modname));
1414 delete lxdll;
1415 errorState = ERROR_INTERNAL;
1416 return NULL;
1417 }
1418 WinDll = (Win32DllBase*)lxdll;
1419 }
1420 else {
1421 Win32PeLdrDll *pedll;
1422
1423 pedll = new Win32PeLdrDll(modname, this);
1424 if(pedll == NULL) {
1425 dprintf((LOG, "pedll: Error allocating memory" ));
1426 WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, szMemErrorMsg, szErrorTitle, 0, MB_OK | MB_ERROR | MB_MOVEABLE);
1427 errorState = ERROR_INTERNAL;
1428 return NULL;
1429 }
1430 dprintf((LOG, "**********************************************************************" ));
1431 dprintf((LOG, "********************** Loading Module *********************" ));
1432 dprintf((LOG, "**********************************************************************" ));
1433 if(pedll->init(0) == FALSE) {
1434 dprintf((LOG, "Internal WinDll error ", pedll->getError() ));
1435 delete pedll;
1436 return NULL;
1437 }
1438#ifdef DEBUG
1439 pedll->AddRef(getModuleName());
1440#else
1441 pedll->AddRef();
1442#endif
1443 if(pedll->attachProcess() == FALSE) {
1444 dprintf((LOG, "attachProcess failed!" ));
1445 delete pedll;
1446 errorState = ERROR_INTERNAL;
1447 return NULL;
1448 }
1449 WinDll = (Win32DllBase*)pedll;
1450 }
1451
1452 dprintf((LOG, "**********************************************************************" ));
1453 dprintf((LOG, "********************** Finished Loading Module %s ", modname ));
1454 dprintf((LOG, "**********************************************************************" ));
1455
1456 return WinDll;
1457}
1458//******************************************************************************
1459/** All initial processing of imports is done here
1460 * Should now detect most Borland styled files including the GifCon32.exe and
1461 * loader32 from SoftIce. (Stupid Borland!!!)
1462 *
1463 * knut [Jul 22 1998 2:44am]
1464 **/
1465//******************************************************************************
1466BOOL Win32PeLdrImage::processImports(char *win32file)
1467{
1468 PIMAGE_IMPORT_DESCRIPTOR pID;
1469 IMAGE_SECTION_HEADER shID;
1470 IMAGE_SECTION_HEADER shExtra = {0};
1471 PIMAGE_OPTIONAL_HEADER pOH;
1472 int i,j, nrPages;
1473 BOOL fBorland = 0;
1474 int cModules;
1475 char *pszModules;
1476 char *pszCurModule;
1477 char *pszTmp;
1478 ULONG *pulImport;
1479 ULONG ulCurFixup;
1480 int Size;
1481 Win32DllBase *WinDll;
1482 Section *section;
1483
1484/* "algorithm:"
1485 * 1) get module names and store them
1486 * a) check dwRVAModuleName is within .idata seg - if not find section
1487 * 2) iterate thru functions of each module
1488 * a) check OriginalFirstThunk is not 0 and that it points to a RVA.
1489 * b) if not a) borland-styled PE-file - ARG!!!
1490 * check FirstThunk
1491 * c) check OriginalFirstThunk/FirstThunk ok RVAs and find right section
1492 * d) store ordinal/name import
1493 * 3) finished
1494 */
1495
1496 /* 1) get module names */
1497 pID = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryOffset(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT);
1498 if (pID == NULL)
1499 return TRUE;
1500 if (!GetSectionHdrByImageDir(win32file, IMAGE_DIRECTORY_ENTRY_IMPORT, &shID))
1501 return TRUE;
1502
1503 //calc size of module list
1504 i = Size = cModules = 0;
1505 while (pID[i].Name != 0)
1506 {
1507 //test RVA inside ID-Section
1508 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1509 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1510 }
1511 else {
1512 //is the "Extra"-section already found or do we have to find it?
1513 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1514 if (!GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name))
1515 return FALSE;
1516 }
1517 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1518 }
1519 Size += strlen(pszTmp) + 1;
1520 i++;
1521 cModules++;
1522 }
1523
1524 pszModules = (char*)malloc(Size);
1525 assert(pszModules != NULL);
1526 j = 0;
1527 for (i = 0; i < cModules; i++)
1528 {
1529 //test RVA inside ID-Section
1530 if (pID[i].Name >= shID.VirtualAddress && pID[i].Name < shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData)) {
1531 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1532 }
1533 else {
1534 fBorland = TRUE;
1535 //is the "Extra"-section already found or do we have to find it?
1536 if (pID[i].Name < shExtra.VirtualAddress || pID[i].Name >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1537 {
1538 if (GetSectionHdrByRVA(win32file, &shExtra, pID[i].Name)) {
1539 free(pszModules);
1540 return FALSE;
1541 }
1542 }
1543 pszTmp = (char*)(pID[i].Name + (ULONG)win32file);
1544 }
1545
1546 strcpy(pszModules+j, pszTmp);
1547 j += strlen(pszTmp) + 1;
1548 }
1549 if (fBorland)
1550 dprintf((LOG, "Borland-styled PE-File." ));
1551 //Store modules
1552 dprintf((LOG, "%d imported Modules: ", cModules ));
1553
1554 /* 2) functions */
1555 pszCurModule = pszModules;
1556 pOH = (PIMAGE_OPTIONAL_HEADER)OPTHEADEROFF(win32file);
1557 for (i = 0; i < cModules; i++)
1558 {
1559 dprintf((LOG, "Module %s", pszCurModule ));
1560 if(pID[i].ForwarderChain) {
1561 dprintf((LOG, "ForwarderChain: %x", pID[i].ForwarderChain));
1562 }
1563 // a) check that OriginalFirstThunk not is 0 and look for Borland-styled PE
1564 if (i == 0)
1565 {
1566 //heavy borland-style test - assume array of thunks is within that style does not change
1567 if((ULONG)pID[i].u.OriginalFirstThunk == 0 ||
1568 (ULONG)pID[i].u.OriginalFirstThunk < shID.VirtualAddress ||
1569 (ULONG)pID[i].u.OriginalFirstThunk >= shID.VirtualAddress + max(shID.Misc.VirtualSize, shID.SizeOfRawData) ||
1570 (ULONG)pID[i].u.OriginalFirstThunk >= pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress &&
1571 (ULONG)pID[i].u.OriginalFirstThunk < sizeof(*pID)*cModules + pOH->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress)
1572 {
1573 fBorland = TRUE;
1574 }
1575 }
1576 //light borland-style test
1577 if (pID[i].u.OriginalFirstThunk == 0 || fBorland) {
1578 pulImport = (ULONG*)pID[i].FirstThunk;
1579 }
1580 else pulImport = (ULONG*)pID[i].u.OriginalFirstThunk;
1581
1582 // b) check if RVA ok
1583 if (!(pulImport > 0 && (ULONG)pulImport < pOH->SizeOfImage)) {
1584 dprintf((LOG, "Invalid RVA %x", pulImport ));
1585 break;
1586 }
1587 // check section
1588 if ((ULONG)pulImport < shExtra.VirtualAddress || (ULONG)pulImport >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData))
1589 {
1590 if (!GetSectionHdrByRVA(win32file, &shExtra, (ULONG)pulImport))
1591 {
1592 dprintf((LOG, "warning: could not find section for Thunk RVA %x", pulImport ));
1593 break;
1594 }
1595 }
1596
1597 //SvL: Load dll if needed
1598 dprintf((LOG, "**********************************************************************" ));
1599 dprintf((LOG, "************** Import Module %s ", pszCurModule ));
1600 dprintf((LOG, "**********************************************************************" ));
1601 WinDll = Win32DllBase::findModule(pszCurModule);
1602
1603 if(WinDll == NULL)
1604 { //not found, so load it
1605 WinDll = loadDll(pszCurModule);
1606 if(WinDll == NULL) {
1607 return FALSE;
1608 }
1609 }
1610 else {
1611 WinDll->AddRef();
1612 dprintf((LOG, "Already found ", pszCurModule));
1613 }
1614 //add the dll we just loaded to dependency list for this image
1615 addDependency(WinDll);
1616
1617 //Make sure the dependency list is correct (already done
1618 //in the ctor of Win32DllBase, but for LX dlls the parent is
1619 //then set to NULL; so change it here again
1620 WinDll->setUnloadOrder(this);
1621
1622 pulImport = (PULONG)((ULONG)pulImport + (ULONG)win32file);
1623 j = 0;
1624 ulCurFixup = (ULONG)pID[i].FirstThunk + (ULONG)win32file;
1625
1626 section = findSectionByOS2Addr(ulCurFixup);
1627 if(section == NULL) {
1628 dprintf((LOG, "Unable to find section for %x", ulCurFixup ));
1629 return FALSE;
1630 }
1631 //SvL: Read page from disk
1632 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1633 //SvL: Enable write access
1634 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1635 nrPages = 1;
1636
1637 while (pulImport[j] != 0) {
1638 if (pulImport[j] & IMAGE_ORDINAL_FLAG) { //ordinal
1639 dprintf((LOG, "0x%08x Imported function %s @%d", ulCurFixup , pszCurModule, (pulImport[j] & ~IMAGE_ORDINAL_FLAG) ));
1640 StoreImportByOrd(WinDll, pulImport[j] & ~IMAGE_ORDINAL_FLAG, ulCurFixup);
1641 }
1642 else { //name
1643 //check
1644 if (pulImport[j] < shExtra.VirtualAddress || pulImport[j] >= shExtra.VirtualAddress + max(shExtra.Misc.VirtualSize, shExtra.SizeOfRawData)) {
1645 if (!GetSectionHdrByRVA(win32file, &shExtra, pulImport[j]))
1646 {
1647 dprintf((LOG, "warning: could not find section for Import Name RVA ", pulImport[j] ));
1648 break;
1649 }
1650 }
1651 //KSO - Aug 6 1998 1:15am:this eases comparing...
1652 char *pszFunctionName = (char*)(pulImport[j] + (ULONG)win32file + 2);
1653 dprintf((LOG, "0x%08x Imported function %s (0x%08x)", ulCurFixup, pszFunctionName, WinDll->getApi(pszFunctionName)));
1654 StoreImportByName(WinDll, pszFunctionName, ulCurFixup);
1655 }
1656 ulCurFixup += sizeof(IMAGE_THUNK_DATA);
1657 j++;
1658 if((ulCurFixup & 0xfff) == 0) {
1659 commitPage(ulCurFixup & ~0xfff, FALSE, SINGLE_PAGE);
1660 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE, PAG_READ|PAG_WRITE);
1661 nrPages++;
1662 }
1663 }
1664 //SvL: And restore original protection flags
1665 ulCurFixup = (ULONG)pID[i].FirstThunk + pOH->ImageBase;
1666 DosSetMem((PVOID)(ulCurFixup & ~0xfff), PAGE_SIZE*nrPages, section->pageflags);
1667
1668 dprintf((LOG, "**********************************************************************" ));
1669 dprintf((LOG, "************** End Import Module %s ", pszCurModule ));
1670 dprintf((LOG, "**********************************************************************" ));
1671
1672 pszCurModule += strlen(pszCurModule) + 1;
1673 }//for (i = 0; i < cModules; i++)
1674
1675 free(pszModules);
1676 return TRUE;
1677}
1678//******************************************************************************
1679//******************************************************************************
1680BOOL Win32PeLdrImage::insideModule(ULONG address)
1681{
1682 if((address >= realBaseAddress) && (address < realBaseAddress + imageSize)) {
1683 return TRUE;
1684 }
1685 return FALSE;
1686}
1687//******************************************************************************
1688//******************************************************************************
1689BOOL Win32PeLdrImage::insideModuleCode(ULONG address)
1690{
1691 Section *sect;
1692
1693 sect = findSectionByOS2Addr(address);
1694 if(sect && (sect->pageflags & PAG_EXECUTE)) {
1695 return TRUE;
1696 }
1697 return FALSE;
1698}
1699//******************************************************************************
1700//******************************************************************************
1701ULONG Win32PeLdrImage::getImageSize()
1702{
1703 return imageSize;
1704}
1705//******************************************************************************
1706//******************************************************************************
1707ULONG Win32PeLdrImage::getApi(char *name)
1708{
1709 ULONG apiaddr, i, apilen;
1710 char *apiname;
1711 char tmp[4];
1712 NameExport *curexport;
1713 ULONG ulAPIOrdinal; /* api requested by ordinal */
1714
1715 apilen = strlen(name) + 1;
1716 if(apilen < 4)
1717 {
1718 *(ULONG *)tmp = 0;
1719 strcpy(tmp, name);
1720 apiname = tmp;
1721 apilen = 4;
1722 }
1723 else apiname = name;
1724
1725 curexport = nameexports;
1726 for(i=0; i<nrNameExports; i++)
1727 {
1728 if(apilen == curexport->nlength &&
1729 *(ULONG *)curexport->name == *(ULONG *)apiname)
1730 {
1731 if(strcmp(curexport->name, apiname) == 0)
1732 return(curexport->virtaddr);
1733 }
1734 curexport = (NameExport *)((ULONG)curexport->name + curexport->nlength);
1735 }
1736 return(0);
1737}
1738//******************************************************************************
1739//******************************************************************************
1740ULONG Win32PeLdrImage::getApi(int ordinal)
1741{
1742 ULONG apiaddr, i;
1743 OrdExport *curexport;
1744 NameExport *nexport;
1745
1746 curexport = ordexports;
1747 for(i=0;i<nrOrdExports;i++) {
1748 if(curexport->ordinal == ordinal)
1749 return(curexport->virtaddr);
1750 curexport++;
1751 }
1752 //Name exports also contain an ordinal, so check this
1753 nexport = nameexports;
1754 for(i=0;i<nrNameExports;i++) {
1755 if(nexport->ordinal == ordinal)
1756 return(nexport->virtaddr);
1757
1758 nexport = (NameExport *)((ULONG)nexport->name + nexport->nlength);
1759 }
1760 return(0);
1761}
1762//******************************************************************************
1763//Returns required OS version for this image
1764//******************************************************************************
1765ULONG Win32PeLdrImage::getVersion()
1766{
1767 return (oh.MajorOperatingSystemVersion << 16) | oh.MinorOperatingSystemVersion;
1768}
1769//******************************************************************************
1770//******************************************************************************
1771ULONG MissingApi()
1772{
1773 static BOOL fIgnore = FALSE;
1774 int r;
1775
1776 dprintf((LOG, "Missing api called!\n"));
1777 if(fIgnore)
1778 return(0);
1779
1780 do {
1781 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, "The application has called a non-existing api\n",
1782 "Internal Odin Error", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
1783 }
1784 while(r == MBID_RETRY); //giggle
1785
1786 if( r != MBID_IGNORE )
1787 ExitProcess(987);
1788
1789 fIgnore = TRUE;
1790 return(0);
1791}
1792/******************************************************************************/
1793/******************************************************************************/
Note: See TracBrowser for help on using the repository browser.