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

Last change on this file since 5848 was 5848, checked in by phaller, 24 years ago

Revert to old but optimized loader

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