2 * Copyright 1994 Eric Youndale & Erik Bos
3 * Copyright 1995 Martin von Löwis
4 * Copyright 1996-98 Marcus Meissner
6 * based on Eric Youndale's pe-test and:
8 * ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
10 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
13 * Before you start changing something in this file be aware of the following:
15 * - There are several functions called recursively. In a very subtle and
16 * obscure way. DLLs can reference each other recursively etc.
17 * - If you want to enhance, speed up or clean up something in here, think
18 * twice WHY it is implemented in that strange way. There is usually a reason.
19 * Though sometimes it might just be lazyness ;)
20 * - In PE_MapImage, right before fixup_imports() all external and internal
21 * state MUST be correct since this function can be called with the SAME image
22 * AGAIN. (Thats recursion for you.) That means MODREF.module and
24 * - Sometimes, we can't use Linux mmap() to mmap() the images directly.
26 * The problem is, that there is not direct 1:1 mapping from a diskimage and
27 * a memoryimage. The headers at the start are mapped linear, but the sections
28 * are not. Older x86 pe binaries are 512 byte aligned in file and 4096 byte
29 * aligned in memory. Linux likes them 4096 byte aligned in memory (due to
30 * x86 pagesize, this cannot be fixed without a rather large kernel rewrite)
31 * and 'blocksize' file-aligned (offsets). Since we have 512/1024/2048 (CDROM)
32 * and other byte blocksizes, we can't always do this. We *can* do this for
33 * newer pe binaries produced by MSVC 5 and later, since they are also aligned
34 * to 4096 byte boundaries on disk.
44 #include <sys/types.h>
46 #ifdef HAVE_SYS_MMAN_H
51 #include "wine/winbase16.h"
64 #include "debugtools.h"
66 DEFAULT_DEBUG_CHANNEL(win32
);
67 DECLARE_DEBUG_CHANNEL(delayhlp
);
68 DECLARE_DEBUG_CHANNEL(fixup
);
69 DECLARE_DEBUG_CHANNEL(module
);
70 DECLARE_DEBUG_CHANNEL(relay
);
71 DECLARE_DEBUG_CHANNEL(segment
);
74 static IMAGE_EXPORT_DIRECTORY
*get_exports( HMODULE hmod
)
76 IMAGE_EXPORT_DIRECTORY
*ret
= NULL
;
77 IMAGE_DATA_DIRECTORY
*dir
= PE_HEADER(hmod
)->OptionalHeader
.DataDirectory
78 + IMAGE_DIRECTORY_ENTRY_EXPORT
;
79 if (dir
->Size
&& dir
->VirtualAddress
)
80 ret
= (IMAGE_EXPORT_DIRECTORY
*)((char *)hmod
+ dir
->VirtualAddress
);
84 static IMAGE_IMPORT_DESCRIPTOR
*get_imports( HMODULE hmod
)
86 IMAGE_IMPORT_DESCRIPTOR
*ret
= NULL
;
87 IMAGE_DATA_DIRECTORY
*dir
= PE_HEADER(hmod
)->OptionalHeader
.DataDirectory
88 + IMAGE_DIRECTORY_ENTRY_IMPORT
;
89 if (dir
->Size
&& dir
->VirtualAddress
)
90 ret
= (IMAGE_IMPORT_DESCRIPTOR
*)((char *)hmod
+ dir
->VirtualAddress
);
95 /* convert PE image VirtualAddress to Real Address */
96 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
98 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
100 void dump_exports( HMODULE hModule
)
105 u_long
*function
,*functions
;
107 unsigned int load_addr
= hModule
;
109 DWORD rva_start
= PE_HEADER(hModule
)->OptionalHeader
110 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
111 DWORD rva_end
= rva_start
+ PE_HEADER(hModule
)->OptionalHeader
112 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].Size
;
113 IMAGE_EXPORT_DIRECTORY
*pe_exports
= (IMAGE_EXPORT_DIRECTORY
*)RVA(rva_start
);
115 Module
= (char*)RVA(pe_exports
->Name
);
116 TRACE("*******EXPORT DATA*******\n");
117 TRACE("Module name is %s, %ld functions, %ld names\n",
118 Module
, pe_exports
->NumberOfFunctions
, pe_exports
->NumberOfNames
);
120 ordinal
=(u_short
*) RVA(pe_exports
->AddressOfNameOrdinals
);
121 functions
=function
=(u_long
*) RVA(pe_exports
->AddressOfFunctions
);
122 name
=(u_char
**) RVA(pe_exports
->AddressOfNames
);
124 TRACE(" Ord RVA Addr Name\n" );
125 for (i
=0;i
<pe_exports
->NumberOfFunctions
;i
++, function
++)
127 if (!*function
) continue; /* No such function */
130 DPRINTF( "%4ld %08lx %p", i
+ pe_exports
->Base
, *function
, RVA(*function
) );
131 /* Check if we have a name for it */
132 for (j
= 0; j
< pe_exports
->NumberOfNames
; j
++)
135 DPRINTF( " %s", (char*)RVA(name
[j
]) );
138 if ((*function
>= rva_start
) && (*function
<= rva_end
))
139 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function
));
145 /* Look up the specified function or ordinal in the exportlist:
147 * - look up the name in the Name list.
148 * - look up the ordinal with that index.
149 * - use the ordinal as offset into the functionlist
150 * If it is a ordinal:
151 * - use ordinal-pe_export->Base as offset into the functionlist
153 static FARPROC
PE_FindExportedFunction(
154 WINE_MODREF
*wm
, /* [in] WINE modreference */
155 LPCSTR funcName
, /* [in] function name */
160 u_char
** name
, *ename
= NULL
;
162 unsigned int load_addr
= wm
->module
;
163 u_long rva_start
, rva_end
, addr
;
165 IMAGE_EXPORT_DIRECTORY
*exports
= get_exports(wm
->module
);
167 if (HIWORD(funcName
))
168 TRACE("(%s)\n",funcName
);
170 TRACE("(%d)\n",(int)funcName
);
172 /* Not a fatal problem, some apps do
173 * GetProcAddress(0,"RegisterPenApp") which triggers this
176 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm
->module
,wm
->modname
,wm
);
179 ordinals
= (u_short
*) RVA(exports
->AddressOfNameOrdinals
);
180 function
= (u_long
*) RVA(exports
->AddressOfFunctions
);
181 name
= (u_char
**) RVA(exports
->AddressOfNames
);
183 rva_start
= PE_HEADER(wm
->module
)->OptionalHeader
184 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
185 rva_end
= rva_start
+ PE_HEADER(wm
->module
)->OptionalHeader
186 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].Size
;
188 if (HIWORD(funcName
))
190 /* first try a binary search */
191 int min
= 0, max
= exports
->NumberOfNames
- 1;
194 int res
, pos
= (min
+ max
) / 2;
195 ename
= RVA(name
[pos
]);
196 if (!(res
= strcmp( ename
, funcName
)))
198 ordinal
= ordinals
[pos
];
201 if (res
> 0) max
= pos
- 1;
204 /* now try a linear search in case the names aren't sorted properly */
205 for (i
= 0; i
< exports
->NumberOfNames
; i
++)
207 ename
= RVA(name
[i
]);
208 if (!strcmp( ename
, funcName
))
210 ERR( "%s.%s required a linear search\n", wm
->modname
, funcName
);
211 ordinal
= ordinals
[i
];
217 else /* find by ordinal */
219 ordinal
= LOWORD(funcName
) - exports
->Base
;
220 if (snoop
&& name
) /* need to find a name for it */
222 for (i
= 0; i
< exports
->NumberOfNames
; i
++)
223 if (ordinals
[i
] == ordinal
)
225 ename
= RVA(name
[i
]);
232 if (ordinal
>= exports
->NumberOfFunctions
)
234 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
237 addr
= function
[ordinal
];
238 if (!addr
) return NULL
;
239 if ((addr
< rva_start
) || (addr
>= rva_end
))
241 FARPROC proc
= RVA(addr
);
244 if (!ename
) ename
= "@";
245 proc
= SNOOP_GetProcAddress(wm
->module
,ename
,ordinal
,proc
);
249 else /* forward entry point */
253 char *forward
= RVA(addr
);
255 char *end
= strchr(forward
, '.');
257 if (!end
) return NULL
;
258 if (end
- forward
>= sizeof(module
)) return NULL
;
259 memcpy( module
, forward
, end
- forward
);
260 module
[end
-forward
] = 0;
261 if (!(wm
= MODULE_FindModule( module
)))
263 ERR("module not found for forward '%s'\n", forward
);
266 if (!(proc
= MODULE_GetProcAddress( wm
->module
, end
+ 1, snoop
)))
267 ERR("function not found for forward '%s'\n", forward
);
272 DWORD
fixup_imports( WINE_MODREF
*wm
)
274 IMAGE_IMPORT_DESCRIPTOR
*pe_imp
;
275 unsigned int load_addr
= wm
->module
;
276 int i
,characteristics_detection
=1;
278 IMAGE_EXPORT_DIRECTORY
*exports
= get_exports(wm
->module
);
279 IMAGE_IMPORT_DESCRIPTOR
*imports
= get_imports(wm
->module
);
282 modname
= (char*) RVA(exports
->Name
);
284 modname
= "<unknown>";
286 /* first, count the number of imported non-internal modules */
288 if (!pe_imp
) return 0;
290 /* OK, now dump the import list */
291 TRACE("Dumping imports list\n");
293 /* We assume that we have at least one import with !0 characteristics and
294 * detect broken imports with all characteristics 0 (notably Borland) and
295 * switch the detection off for them.
297 for (i
= 0; pe_imp
->Name
; pe_imp
++) {
298 if (!i
&& !pe_imp
->u
.Characteristics
)
299 characteristics_detection
= 0;
300 if (characteristics_detection
&& !pe_imp
->u
.Characteristics
)
304 if (!i
) return 0; /* no imports */
306 /* Allocate module dependency list */
308 wm
->deps
= HeapAlloc( GetProcessHeap(), 0, i
*sizeof(WINE_MODREF
*) );
310 /* load the imported modules. They are automatically
311 * added to the modref list of the process.
314 for (i
= 0, pe_imp
= imports
; pe_imp
->Name
; pe_imp
++) {
316 IMAGE_IMPORT_BY_NAME
*pe_name
;
317 PIMAGE_THUNK_DATA import_list
,thunk_list
;
318 char *name
= (char *) RVA(pe_imp
->Name
);
320 if (characteristics_detection
&& !pe_imp
->u
.Characteristics
)
323 wmImp
= MODULE_LoadLibraryExA( name
, 0, 0 );
325 ERR_(module
)("Module (file) %s needed by %s not found\n", name
, wm
->filename
);
328 wm
->deps
[i
++] = wmImp
;
330 /* FIXME: forwarder entries ... */
332 if (pe_imp
->u
.OriginalFirstThunk
!= 0) { /* original MS style */
333 TRACE("Microsoft style imports used\n");
334 import_list
=(PIMAGE_THUNK_DATA
) RVA(pe_imp
->u
.OriginalFirstThunk
);
335 thunk_list
= (PIMAGE_THUNK_DATA
) RVA(pe_imp
->FirstThunk
);
337 while (import_list
->u1
.Ordinal
) {
338 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
)) {
339 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
341 TRACE("--- Ordinal %s,%d\n", name
, ordinal
);
342 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
343 wmImp
->module
, (LPCSTR
)ordinal
, TRUE
345 if (!thunk_list
->u1
.Function
) {
346 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
348 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
350 } else { /* import by name */
351 pe_name
= (PIMAGE_IMPORT_BY_NAME
)RVA(import_list
->u1
.AddressOfData
);
352 TRACE("--- %s %s.%d\n", pe_name
->Name
, name
, pe_name
->Hint
);
353 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
354 wmImp
->module
, pe_name
->Name
, TRUE
356 if (!thunk_list
->u1
.Function
) {
357 ERR("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
358 name
,pe_name
->Hint
,pe_name
->Name
);
359 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
365 } else { /* Borland style */
366 TRACE("Borland style imports used\n");
367 thunk_list
= (PIMAGE_THUNK_DATA
) RVA(pe_imp
->FirstThunk
);
368 while (thunk_list
->u1
.Ordinal
) {
369 if (IMAGE_SNAP_BY_ORDINAL(thunk_list
->u1
.Ordinal
)) {
370 /* not sure about this branch, but it seems to work */
371 int ordinal
= IMAGE_ORDINAL(thunk_list
->u1
.Ordinal
);
373 TRACE("--- Ordinal %s.%d\n",name
,ordinal
);
374 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
375 wmImp
->module
, (LPCSTR
) ordinal
, TRUE
377 if (!thunk_list
->u1
.Function
) {
378 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
380 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
383 pe_name
=(PIMAGE_IMPORT_BY_NAME
) RVA(thunk_list
->u1
.AddressOfData
);
384 TRACE("--- %s %s.%d\n",
385 pe_name
->Name
,name
,pe_name
->Hint
);
386 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
387 wmImp
->module
, pe_name
->Name
, TRUE
389 if (!thunk_list
->u1
.Function
) {
390 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
391 name
, pe_name
->Hint
);
392 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
402 static int calc_vma_size( HMODULE hModule
)
405 IMAGE_SECTION_HEADER
*pe_seg
= PE_SECTIONS(hModule
);
407 TRACE("Dump of segment table\n");
408 TRACE(" Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
409 for (i
= 0; i
< PE_HEADER(hModule
)->FileHeader
.NumberOfSections
; i
++)
411 TRACE("%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
413 pe_seg
->Misc
.VirtualSize
,
414 pe_seg
->VirtualAddress
,
415 pe_seg
->SizeOfRawData
,
416 pe_seg
->PointerToRawData
,
417 pe_seg
->PointerToRelocations
,
418 pe_seg
->PointerToLinenumbers
,
419 pe_seg
->NumberOfRelocations
,
420 pe_seg
->NumberOfLinenumbers
,
421 pe_seg
->Characteristics
);
422 vma_size
=max(vma_size
, pe_seg
->VirtualAddress
+pe_seg
->SizeOfRawData
);
423 vma_size
=max(vma_size
, pe_seg
->VirtualAddress
+pe_seg
->Misc
.VirtualSize
);
429 static void do_relocations( unsigned int load_addr
, IMAGE_BASE_RELOCATION
*r
)
431 int delta
= load_addr
- PE_HEADER(load_addr
)->OptionalHeader
.ImageBase
;
432 int hdelta
= (delta
>> 16) & 0xFFFF;
433 int ldelta
= delta
& 0xFFFF;
438 while(r
->VirtualAddress
)
440 char *page
= (char*) RVA(r
->VirtualAddress
);
441 int count
= (r
->SizeOfBlock
- 8)/2;
443 TRACE_(fixup
)("%x relocations for page %lx\n",
444 count
, r
->VirtualAddress
);
445 /* patching in reverse order */
448 int offset
= r
->TypeOffset
[i
] & 0xFFF;
449 int type
= r
->TypeOffset
[i
] >> 12;
450 TRACE_(fixup
)("patching %x type %x\n", offset
, type
);
453 case IMAGE_REL_BASED_ABSOLUTE
: break;
454 case IMAGE_REL_BASED_HIGH
:
455 *(short*)(page
+offset
) += hdelta
;
457 case IMAGE_REL_BASED_LOW
:
458 *(short*)(page
+offset
) += ldelta
;
460 case IMAGE_REL_BASED_HIGHLOW
:
461 *(int*)(page
+offset
) += delta
;
462 /* FIXME: if this is an exported address, fire up enhanced logic */
464 case IMAGE_REL_BASED_HIGHADJ
:
465 FIXME("Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
467 case IMAGE_REL_BASED_MIPS_JMPADDR
:
468 FIXME("Is this a MIPS machine ???\n");
471 FIXME("Unknown fixup type %d.\n", type
);
475 r
= (IMAGE_BASE_RELOCATION
*)((char*)r
+ r
->SizeOfBlock
);
483 /**********************************************************************
485 * Load one PE format DLL/EXE into memory
487 * Unluckily we can't just mmap the sections where we want them, for
488 * (at least) Linux does only support offsets which are page-aligned.
490 * BUT we have to map the whole image anyway, for Win32 programs sometimes
491 * want to access them. (HMODULE32 point to the start of it)
493 HMODULE
PE_LoadImage( HANDLE hFile
, LPCSTR filename
, DWORD flags
)
498 IMAGE_NT_HEADERS
*nt
;
499 IMAGE_SECTION_HEADER
*pe_sec
;
500 IMAGE_DATA_DIRECTORY
*dir
;
501 BY_HANDLE_FILE_INFORMATION bhfi
;
502 int i
, rawsize
, lowest_va
, vma_size
, file_size
= 0;
503 DWORD load_addr
= 0, aoep
, reloc
= 0;
504 struct get_read_fd_request
*req
= get_req_buffer();
505 int unix_handle
= -1;
506 int page_size
= VIRTUAL_GetPageSize();
508 /* Retrieve file size */
509 if ( GetFileInformationByHandle( hFile
, &bhfi
) )
510 file_size
= bhfi
.nFileSizeLow
; /* FIXME: 64 bit */
512 /* Map the PE file somewhere */
513 mapping
= CreateFileMappingA( hFile
, NULL
, PAGE_READONLY
| SEC_COMMIT
,
517 WARN("CreateFileMapping error %ld\n", GetLastError() );
520 hModule
= (HMODULE
)MapViewOfFile( mapping
, FILE_MAP_READ
, 0, 0, 0 );
521 CloseHandle( mapping
);
524 WARN("MapViewOfFile error %ld\n", GetLastError() );
527 if ( *(WORD
*)hModule
!=IMAGE_DOS_SIGNATURE
)
529 WARN("%s image doesn't have DOS signature, but 0x%04x\n", filename
,*(WORD
*)hModule
);
530 SetLastError( ERROR_BAD_EXE_FORMAT
);
534 nt
= PE_HEADER( hModule
);
536 /* Check signature */
537 if ( nt
->Signature
!= IMAGE_NT_SIGNATURE
)
539 WARN("%s image doesn't have PE signature, but 0x%08lx\n", filename
, nt
->Signature
);
540 SetLastError( ERROR_BAD_EXE_FORMAT
);
544 /* Check architecture */
545 if ( nt
->FileHeader
.Machine
!= IMAGE_FILE_MACHINE_I386
)
547 MESSAGE("Trying to load PE image for unsupported architecture (");
548 switch (nt
->FileHeader
.Machine
)
550 case IMAGE_FILE_MACHINE_UNKNOWN
: MESSAGE("Unknown"); break;
551 case IMAGE_FILE_MACHINE_I860
: MESSAGE("I860"); break;
552 case IMAGE_FILE_MACHINE_R3000
: MESSAGE("R3000"); break;
553 case IMAGE_FILE_MACHINE_R4000
: MESSAGE("R4000"); break;
554 case IMAGE_FILE_MACHINE_R10000
: MESSAGE("R10000"); break;
555 case IMAGE_FILE_MACHINE_ALPHA
: MESSAGE("Alpha"); break;
556 case IMAGE_FILE_MACHINE_POWERPC
: MESSAGE("PowerPC"); break;
557 default: MESSAGE("Unknown-%04x", nt
->FileHeader
.Machine
); break;
560 SetLastError( ERROR_BAD_EXE_FORMAT
);
564 /* Find out how large this executeable should be */
565 pe_sec
= PE_SECTIONS( hModule
);
566 rawsize
= 0; lowest_va
= 0x10000;
567 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
569 if (lowest_va
> pe_sec
[i
].VirtualAddress
)
570 lowest_va
= pe_sec
[i
].VirtualAddress
;
571 if (pe_sec
[i
].Characteristics
& IMAGE_SCN_CNT_UNINITIALIZED_DATA
)
573 if (pe_sec
[i
].PointerToRawData
+pe_sec
[i
].SizeOfRawData
> rawsize
)
574 rawsize
= pe_sec
[i
].PointerToRawData
+pe_sec
[i
].SizeOfRawData
;
577 /* Check file size */
578 if ( file_size
&& file_size
< rawsize
)
580 ERR("PE module is too small (header: %d, filesize: %d), "
581 "probably truncated download?\n",
582 rawsize
, file_size
);
583 SetLastError( ERROR_BAD_EXE_FORMAT
);
587 /* Check entrypoint address */
588 aoep
= nt
->OptionalHeader
.AddressOfEntryPoint
;
589 if (aoep
&& (aoep
< lowest_va
))
590 MESSAGE("VIRUS WARNING: '%s' has an invalid entrypoint (0x%08lx) "
591 "below the first virtual address (0x%08x) "
592 "(possibly infected by Tchernobyl/SpaceFiller virus)!\n",
593 filename
, aoep
, lowest_va
);
597 /* FIXME: Hack! While we don't really support shared sections yet,
598 * this checks for those special cases where the whole DLL
599 * consists only of shared sections and is mapped into the
600 * shared address space > 2GB. In this case, we assume that
601 * the module got mapped at its base address. Thus we simply
602 * check whether the module has actually been mapped there
603 * and use it, if so. This is needed to get Win95 USER32.DLL
604 * to work (until we support shared sections properly).
607 if ( nt
->OptionalHeader
.ImageBase
& 0x80000000 )
609 HMODULE sharedMod
= (HMODULE
)nt
->OptionalHeader
.ImageBase
;
610 IMAGE_NT_HEADERS
*sharedNt
= (PIMAGE_NT_HEADERS
)
611 ( (LPBYTE
)sharedMod
+ ((LPBYTE
)nt
- (LPBYTE
)hModule
) );
613 /* Well, this check is not really comprehensive,
614 but should be good enough for now ... */
615 if ( !IsBadReadPtr( (LPBYTE
)sharedMod
, sizeof(IMAGE_DOS_HEADER
) )
616 && memcmp( (LPBYTE
)sharedMod
, (LPBYTE
)hModule
, sizeof(IMAGE_DOS_HEADER
) ) == 0
617 && !IsBadReadPtr( sharedNt
, sizeof(IMAGE_NT_HEADERS
) )
618 && memcmp( sharedNt
, nt
, sizeof(IMAGE_NT_HEADERS
) ) == 0 )
620 UnmapViewOfFile( (LPVOID
)hModule
);
626 /* Allocate memory for module */
627 load_addr
= nt
->OptionalHeader
.ImageBase
;
628 vma_size
= calc_vma_size( hModule
);
630 load_addr
= (DWORD
)VirtualAlloc( (void*)load_addr
, vma_size
,
631 MEM_RESERVE
| MEM_COMMIT
,
632 PAGE_EXECUTE_READWRITE
);
635 load_addr
= (DWORD
)VirtualAlloc( NULL
, vma_size
,
636 MEM_RESERVE
| MEM_COMMIT
,
637 PAGE_EXECUTE_READWRITE
);
641 "FATAL: Couldn't load module %s (out of memory, %d needed)!\n", filename
, vma_size
);
646 if (load_addr
!= nt
->OptionalHeader
.ImageBase
&& !(flags
& LOAD_LIBRARY_AS_DATAFILE
))
648 /* We need to perform base relocations */
649 WARN("Info: base relocations needed for %s\n", filename
);
650 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_BASERELOC
;
652 reloc
= dir
->VirtualAddress
;
655 if (nt
->OptionalHeader
.ImageBase
== 0x400000)
656 ERR("Standard load address for a Win32 program not available - patched kernel ?\n");
657 FIXME( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
659 (nt
->FileHeader
.Characteristics
&IMAGE_FILE_RELOCS_STRIPPED
)?
660 "stripped during link" : "unknown reason" );
661 SetLastError( ERROR_BAD_EXE_FORMAT
);
665 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
666 * really make sure that the *new* base address is also > 2GB.
667 * Some DLLs really check the MSB of the module handle :-/
669 if ((nt
->OptionalHeader
.ImageBase
& 0x80000000) && !(load_addr
& 0x80000000))
670 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
673 TRACE("Load addr is %lx (base %lx), range %x\n",
674 load_addr
, nt
->OptionalHeader
.ImageBase
, vma_size
);
675 TRACE_(segment
)("Loading %s at %lx, range %x\n",
676 filename
, load_addr
, vma_size
);
679 server_call_fd( REQ_GET_READ_FD
, -1, &unix_handle
);
680 if (unix_handle
== -1) goto error
;
683 if (FILE_dommap( unix_handle
, (void *)load_addr
, 0, nt
->OptionalHeader
.SizeOfHeaders
,
684 0, 0, PROT_EXEC
| PROT_WRITE
| PROT_READ
,
685 MAP_PRIVATE
| MAP_FIXED
) != (void*)load_addr
)
687 ERR_(win32
)( "Critical Error: failed to map PE header to necessary address.\n");
691 /* Copy sections into module image */
692 pe_sec
= PE_SECTIONS( hModule
);
693 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, pe_sec
++)
695 if (!pe_sec
->SizeOfRawData
|| !pe_sec
->PointerToRawData
) continue;
696 TRACE("%s: mmaping section %s at %p off %lx size %lx/%lx\n",
697 filename
, pe_sec
->Name
, (void*)RVA(pe_sec
->VirtualAddress
),
698 pe_sec
->PointerToRawData
, pe_sec
->SizeOfRawData
, pe_sec
->Misc
.VirtualSize
);
699 if (FILE_dommap( unix_handle
, (void*)RVA(pe_sec
->VirtualAddress
),
700 0, pe_sec
->SizeOfRawData
, 0, pe_sec
->PointerToRawData
,
701 PROT_EXEC
| PROT_WRITE
| PROT_READ
,
702 MAP_PRIVATE
| MAP_FIXED
) != (void*)RVA(pe_sec
->VirtualAddress
))
704 /* We failed to map to the right place (huh?) */
705 ERR_(win32
)( "Critical Error: failed to map PE section to necessary address.\n");
708 if ((pe_sec
->SizeOfRawData
< pe_sec
->Misc
.VirtualSize
) &&
709 (pe_sec
->SizeOfRawData
& (page_size
-1)))
711 DWORD end
= (pe_sec
->SizeOfRawData
& ~(page_size
-1)) + page_size
;
712 if (end
> pe_sec
->Misc
.VirtualSize
) end
= pe_sec
->Misc
.VirtualSize
;
713 TRACE("clearing %p - %p\n",
714 RVA(pe_sec
->VirtualAddress
) + pe_sec
->SizeOfRawData
,
715 RVA(pe_sec
->VirtualAddress
) + end
);
716 memset( (char*)RVA(pe_sec
->VirtualAddress
) + pe_sec
->SizeOfRawData
, 0,
717 end
- pe_sec
->SizeOfRawData
);
721 /* Perform base relocation, if necessary */
723 do_relocations( load_addr
, (IMAGE_BASE_RELOCATION
*)RVA(reloc
) );
725 /* We don't need the orignal mapping any more */
726 UnmapViewOfFile( (LPVOID
)hModule
);
727 close( unix_handle
);
728 return (HMODULE
)load_addr
;
731 if (unix_handle
!= -1) close( unix_handle
);
732 if (load_addr
) VirtualFree( (LPVOID
)load_addr
, 0, MEM_RELEASE
);
733 UnmapViewOfFile( (LPVOID
)hModule
);
737 /**********************************************************************
740 * Create WINE_MODREF structure for loaded HMODULE32, link it into
741 * process modref_list, and fixup all imports.
743 * Note: hModule must point to a correctly allocated PE image,
744 * with base relocations applied; the 16-bit dummy module
745 * associated to hModule must already exist.
747 * Note: This routine must always be called in the context of the
748 * process that is to own the module to be created.
750 * Note: Assumes that the process critical section is held
752 WINE_MODREF
*PE_CreateModule( HMODULE hModule
, LPCSTR filename
, DWORD flags
,
753 HFILE hFile
, BOOL builtin
)
755 DWORD load_addr
= (DWORD
)hModule
; /* for RVA */
756 IMAGE_NT_HEADERS
*nt
= PE_HEADER(hModule
);
757 IMAGE_DATA_DIRECTORY
*dir
;
758 IMAGE_EXPORT_DIRECTORY
*pe_export
= NULL
;
762 /* Retrieve DataDirectory entries */
764 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXPORT
;
766 pe_export
= (PIMAGE_EXPORT_DIRECTORY
)RVA(dir
->VirtualAddress
);
768 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXCEPTION
;
769 if (dir
->Size
) FIXME("Exception directory ignored\n" );
771 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_SECURITY
;
772 if (dir
->Size
) FIXME("Security directory ignored\n" );
774 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
775 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
777 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_GLOBALPTR
;
778 if (dir
->Size
) FIXME("Global Pointer (MIPS) ignored\n" );
780 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
782 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
;
783 if (dir
->Size
) FIXME("Load Configuration directory ignored\n" );
785 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
;
786 if (dir
->Size
) TRACE("Bound Import directory ignored\n" );
788 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_IAT
;
789 if (dir
->Size
) TRACE("Import Address Table directory ignored\n" );
791 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT
;
794 TRACE("Delayed import, stub calls LoadLibrary\n" );
796 * Nothing to do here.
801 * This code is useful to observe what the heck is going on.
804 ImgDelayDescr
*pe_delay
= NULL
;
805 pe_delay
= (PImgDelayDescr
)RVA(dir
->VirtualAddress
);
806 TRACE_(delayhlp
)("pe_delay->grAttrs = %08x\n", pe_delay
->grAttrs
);
807 TRACE_(delayhlp
)("pe_delay->szName = %s\n", pe_delay
->szName
);
808 TRACE_(delayhlp
)("pe_delay->phmod = %08x\n", pe_delay
->phmod
);
809 TRACE_(delayhlp
)("pe_delay->pIAT = %08x\n", pe_delay
->pIAT
);
810 TRACE_(delayhlp
)("pe_delay->pINT = %08x\n", pe_delay
->pINT
);
811 TRACE_(delayhlp
)("pe_delay->pBoundIAT = %08x\n", pe_delay
->pBoundIAT
);
812 TRACE_(delayhlp
)("pe_delay->pUnloadIAT = %08x\n", pe_delay
->pUnloadIAT
);
813 TRACE_(delayhlp
)("pe_delay->dwTimeStamp = %08x\n", pe_delay
->dwTimeStamp
);
815 #endif /* ImgDelayDescr */
818 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
;
819 if (dir
->Size
) FIXME("Unknown directory 14 ignored\n" );
821 dir
= nt
->OptionalHeader
.DataDirectory
+15;
822 if (dir
->Size
) FIXME("Unknown directory 15 ignored\n" );
824 /* Create 16-bit dummy module */
826 if ((hModule16
= MODULE_CreateDummyModule( filename
, hModule
)) < 32)
828 SetLastError( (DWORD
)hModule16
); /* This should give the correct error */
832 /* Allocate and fill WINE_MODREF */
834 if (!(wm
= MODULE_AllocModRef( hModule
, filename
)))
836 FreeLibrary16( hModule16
);
842 NE_MODULE
*pModule
= (NE_MODULE
*)GlobalLock16( hModule16
);
843 pModule
->flags
|= NE_FFLAGS_BUILTIN
;
844 wm
->flags
|= WINE_MODREF_INTERNAL
;
847 if ( flags
& DONT_RESOLVE_DLL_REFERENCES
)
848 wm
->flags
|= WINE_MODREF_DONT_RESOLVE_REFS
;
850 wm
->find_export
= PE_FindExportedFunction
;
855 dump_exports( hModule
);
857 /* The exe_modref must be in place, before implicit linked DLLs are loaded
858 by fixup_imports, otherwhise GetModuleFileName will not work and modules
859 in the executables directory can not be found */
861 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
863 if ( PROCESS_Current()->exe_modref
)
864 FIXME( "Trying to load second .EXE file: %s\n", filename
);
867 PROCESS_Current()->exe_modref
= wm
;
868 PROCESS_Current()->module
= wm
->module
;
874 if (!(wm
->flags
& WINE_MODREF_DONT_RESOLVE_REFS
) && fixup_imports( wm
))
876 /* remove entry from modref chain */
879 PROCESS_Current()->modref_list
= wm
->next
;
881 wm
->prev
->next
= wm
->next
;
883 if ( wm
->next
) wm
->next
->prev
= wm
->prev
;
884 wm
->next
= wm
->prev
= NULL
;
886 /* FIXME: there are several more dangling references
887 * left. Including dlls loaded by this dll before the
888 * failed one. Unrolling is rather difficult with the
889 * current structure and we can leave it them lying
890 * around with no problems, so we don't care.
891 * As these might reference our wm, we don't free it.
897 SNOOP_RegisterDLL( hModule
, wm
->modname
, pe_export
->NumberOfFunctions
);
899 /* Send DLL load event */
900 /* we don't need to send a dll event for the main exe */
902 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
904 struct load_dll_request
*req
= get_req_buffer();
906 req
->base
= (void *)hModule
;
907 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
908 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
909 req
->name
= &wm
->filename
;
910 server_call_noerr( REQ_LOAD_DLL
);
916 /******************************************************************************
917 * The PE Library Loader frontend.
918 * FIXME: handle the flags.
920 WINE_MODREF
*PE_LoadLibraryExA (LPCSTR name
, DWORD flags
)
927 /* Search for and open PE file */
928 if ( SearchPathA( NULL
, name
, ".DLL",
929 sizeof(filename
), filename
, NULL
) == 0 ) return NULL
;
931 hFile
= CreateFileA( filename
, GENERIC_READ
, FILE_SHARE_READ
,
932 NULL
, OPEN_EXISTING
, 0, -1 );
933 if ( hFile
== INVALID_HANDLE_VALUE
) return NULL
;
936 hModule32
= PE_LoadImage( hFile
, filename
, flags
);
939 CloseHandle( hFile
);
943 /* Create 32-bit MODREF */
944 if ( !(wm
= PE_CreateModule( hModule32
, filename
, flags
, -1, FALSE
)) )
946 ERR( "can't load %s\n", filename
);
947 CloseHandle( hFile
);
948 SetLastError( ERROR_OUTOFMEMORY
);
952 CloseHandle( hFile
);
957 /* Called if the library is loaded or freed.
958 * NOTE: if a thread attaches a DLL, the current thread will only do
959 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
962 typedef DWORD
CALLBACK(*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
964 BOOL
PE_InitDLL( HMODULE module
, DWORD type
, LPVOID lpReserved
)
967 IMAGE_NT_HEADERS
*nt
= PE_HEADER(module
);
969 /* Is this a library? And has it got an entrypoint? */
970 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
971 (nt
->OptionalHeader
.AddressOfEntryPoint
))
973 DLLENTRYPROC entry
= (void*)((char*)module
+ nt
->OptionalHeader
.AddressOfEntryPoint
);
974 TRACE_(relay
)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
975 entry
, module
, type
, lpReserved
);
977 retv
= entry( module
, type
, lpReserved
);
983 /************************************************************************
984 * PE_InitTls (internal)
986 * If included, initialises the thread local storages of modules.
987 * Pointers in those structs are not RVAs but real pointers which have been
988 * relocated by do_relocations() already.
991 _fixup_address(PIMAGE_OPTIONAL_HEADER opt
,int delta
,LPVOID addr
) {
992 if ( ((DWORD
)addr
>opt
->ImageBase
) &&
993 ((DWORD
)addr
<opt
->ImageBase
+opt
->SizeOfImage
)
995 /* the address has not been relocated! */
996 return (LPVOID
)(((DWORD
)addr
)+delta
);
998 /* the address has been relocated already */
1001 void PE_InitTls( void )
1004 IMAGE_NT_HEADERS
*peh
;
1005 DWORD size
,datasize
;
1007 PIMAGE_TLS_DIRECTORY pdir
;
1010 for (wm
= PROCESS_Current()->modref_list
;wm
;wm
=wm
->next
) {
1011 peh
= PE_HEADER(wm
->module
);
1012 delta
= wm
->module
- peh
->OptionalHeader
.ImageBase
;
1013 if (!peh
->OptionalHeader
.DataDirectory
[IMAGE_FILE_THREAD_LOCAL_STORAGE
].VirtualAddress
)
1015 pdir
= (LPVOID
)(wm
->module
+ peh
->OptionalHeader
.
1016 DataDirectory
[IMAGE_FILE_THREAD_LOCAL_STORAGE
].VirtualAddress
);
1019 if ( wm
->tlsindex
== -1 ) {
1021 wm
->tlsindex
= TlsAlloc();
1022 xaddr
= _fixup_address(&(peh
->OptionalHeader
),delta
,
1023 pdir
->AddressOfIndex
1025 *xaddr
=wm
->tlsindex
;
1027 datasize
= pdir
->EndAddressOfRawData
-pdir
->StartAddressOfRawData
;
1028 size
= datasize
+ pdir
->SizeOfZeroFill
;
1029 mem
=VirtualAlloc(0,size
,MEM_RESERVE
|MEM_COMMIT
,PAGE_READWRITE
);
1030 memcpy(mem
,_fixup_address(&(peh
->OptionalHeader
),delta
,(LPVOID
)pdir
->StartAddressOfRawData
),datasize
);
1031 if (pdir
->AddressOfCallBacks
) {
1032 PIMAGE_TLS_CALLBACK
*cbs
;
1034 cbs
= _fixup_address(&(peh
->OptionalHeader
),delta
,pdir
->AddressOfCallBacks
);
1036 FIXME("TLS Callbacks aren't going to be called\n");
1039 TlsSetValue( wm
->tlsindex
, mem
);