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 * - No, you (usually) cannot 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. For x86 the sections 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 do this. However, this could be less
33 * difficult to support... (See mm/filemap.c).
43 #include <sys/types.h>
45 #ifdef HAVE_SYS_MMAN_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 /* convert PE image VirtualAddress to Real Address */
75 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
77 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
79 void dump_exports( HMODULE hModule
)
84 u_long
*function
,*functions
;
86 unsigned int load_addr
= hModule
;
88 DWORD rva_start
= PE_HEADER(hModule
)->OptionalHeader
89 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
90 DWORD rva_end
= rva_start
+ PE_HEADER(hModule
)->OptionalHeader
91 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].Size
;
92 IMAGE_EXPORT_DIRECTORY
*pe_exports
= (IMAGE_EXPORT_DIRECTORY
*)RVA(rva_start
);
94 Module
= (char*)RVA(pe_exports
->Name
);
95 TRACE("*******EXPORT DATA*******\n");
96 TRACE("Module name is %s, %ld functions, %ld names\n",
97 Module
, pe_exports
->NumberOfFunctions
, pe_exports
->NumberOfNames
);
99 ordinal
=(u_short
*) RVA(pe_exports
->AddressOfNameOrdinals
);
100 functions
=function
=(u_long
*) RVA(pe_exports
->AddressOfFunctions
);
101 name
=(u_char
**) RVA(pe_exports
->AddressOfNames
);
103 TRACE(" Ord RVA Addr Name\n" );
104 for (i
=0;i
<pe_exports
->NumberOfFunctions
;i
++, function
++)
106 if (!*function
) continue; /* No such function */
109 DPRINTF( "%4ld %08lx %p", i
+ pe_exports
->Base
, *function
, RVA(*function
) );
110 /* Check if we have a name for it */
111 for (j
= 0; j
< pe_exports
->NumberOfNames
; j
++)
114 DPRINTF( " %s", (char*)RVA(name
[j
]) );
117 if ((*function
>= rva_start
) && (*function
<= rva_end
))
118 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function
));
124 /* Look up the specified function or ordinal in the exportlist:
126 * - look up the name in the Name list.
127 * - look up the ordinal with that index.
128 * - use the ordinal as offset into the functionlist
129 * If it is a ordinal:
130 * - use ordinal-pe_export->Base as offset into the functionlist
132 FARPROC
PE_FindExportedFunction(
133 WINE_MODREF
*wm
, /* [in] WINE modreference */
134 LPCSTR funcName
, /* [in] function name */
139 u_char
** name
, *ename
= NULL
;
141 PE_MODREF
*pem
= &(wm
->binfmt
.pe
);
142 IMAGE_EXPORT_DIRECTORY
*exports
= pem
->pe_export
;
143 unsigned int load_addr
= wm
->module
;
144 u_long rva_start
, rva_end
, addr
;
147 if (HIWORD(funcName
))
148 TRACE("(%s)\n",funcName
);
150 TRACE("(%d)\n",(int)funcName
);
152 /* Not a fatal problem, some apps do
153 * GetProcAddress(0,"RegisterPenApp") which triggers this
156 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm
->module
,wm
->modname
,pem
);
159 ordinals
= (u_short
*) RVA(exports
->AddressOfNameOrdinals
);
160 function
= (u_long
*) RVA(exports
->AddressOfFunctions
);
161 name
= (u_char
**) RVA(exports
->AddressOfNames
);
163 rva_start
= PE_HEADER(wm
->module
)->OptionalHeader
164 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
165 rva_end
= rva_start
+ PE_HEADER(wm
->module
)->OptionalHeader
166 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].Size
;
168 if (HIWORD(funcName
))
170 /* first try a binary search */
171 int min
= 0, max
= exports
->NumberOfNames
- 1;
174 int res
, pos
= (min
+ max
) / 2;
175 ename
= RVA(name
[pos
]);
176 if (!(res
= strcmp( ename
, funcName
)))
178 ordinal
= ordinals
[pos
];
181 if (res
> 0) max
= pos
- 1;
184 /* now try a linear search in case the names aren't sorted properly */
185 for (i
= 0; i
< exports
->NumberOfNames
; i
++)
187 ename
= RVA(name
[i
]);
188 if (!strcmp( ename
, funcName
))
190 ERR( "%s.%s required a linear search\n", wm
->modname
, funcName
);
191 ordinal
= ordinals
[i
];
197 else /* find by ordinal */
199 ordinal
= LOWORD(funcName
) - exports
->Base
;
200 if (snoop
&& name
) /* need to find a name for it */
202 for (i
= 0; i
< exports
->NumberOfNames
; i
++)
203 if (ordinals
[i
] == ordinal
)
205 ename
= RVA(name
[i
]);
212 if (ordinal
>= exports
->NumberOfFunctions
)
214 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
217 addr
= function
[ordinal
];
218 if (!addr
) return NULL
;
219 if ((addr
< rva_start
) || (addr
>= rva_end
))
221 FARPROC proc
= RVA(addr
);
224 if (!ename
) ename
= "@";
225 proc
= SNOOP_GetProcAddress(wm
->module
,ename
,ordinal
,proc
);
229 else /* forward entry point */
232 char *forward
= RVA(addr
);
234 char *end
= strchr(forward
, '.');
236 if (!end
) return NULL
;
237 if (end
- forward
>= sizeof(module
)) return NULL
;
238 memcpy( module
, forward
, end
- forward
);
239 module
[end
-forward
] = 0;
240 if (!(wm
= MODULE_FindModule( module
)))
242 ERR("module not found for forward '%s'\n", forward
);
245 return MODULE_GetProcAddress( wm
->module
, end
+ 1, snoop
);
249 DWORD
fixup_imports( WINE_MODREF
*wm
)
251 IMAGE_IMPORT_DESCRIPTOR
*pe_imp
;
253 unsigned int load_addr
= wm
->module
;
254 int i
,characteristics_detection
=1;
257 assert(wm
->type
==MODULE32_PE
);
258 pem
= &(wm
->binfmt
.pe
);
260 modname
= (char*) RVA(pem
->pe_export
->Name
);
262 modname
= "<unknown>";
264 /* OK, now dump the import list */
265 TRACE("Dumping imports list\n");
267 /* first, count the number of imported non-internal modules */
268 pe_imp
= pem
->pe_import
;
269 if (!pe_imp
) return 0;
271 /* We assume that we have at least one import with !0 characteristics and
272 * detect broken imports with all characteristsics 0 (notably Borland) and
273 * switch the detection off for them.
275 for (i
= 0; pe_imp
->Name
; pe_imp
++) {
276 if (!i
&& !pe_imp
->u
.Characteristics
)
277 characteristics_detection
= 0;
278 if (characteristics_detection
&& !pe_imp
->u
.Characteristics
)
282 if (!i
) return 0; /* no imports */
284 /* Allocate module dependency list */
286 wm
->deps
= HeapAlloc( GetProcessHeap(), 0, i
*sizeof(WINE_MODREF
*) );
288 /* load the imported modules. They are automatically
289 * added to the modref list of the process.
292 for (i
= 0, pe_imp
= pem
->pe_import
; pe_imp
->Name
; pe_imp
++) {
294 IMAGE_IMPORT_BY_NAME
*pe_name
;
295 PIMAGE_THUNK_DATA import_list
,thunk_list
;
296 char *name
= (char *) RVA(pe_imp
->Name
);
298 if (characteristics_detection
&& !pe_imp
->u
.Characteristics
)
301 wmImp
= MODULE_LoadLibraryExA( name
, 0, 0 );
303 ERR_(module
)("Module %s not found\n", name
);
306 wm
->deps
[i
++] = wmImp
;
308 /* FIXME: forwarder entries ... */
310 if (pe_imp
->u
.OriginalFirstThunk
!= 0) { /* original MS style */
311 TRACE("Microsoft style imports used\n");
312 import_list
=(PIMAGE_THUNK_DATA
) RVA(pe_imp
->u
.OriginalFirstThunk
);
313 thunk_list
= (PIMAGE_THUNK_DATA
) RVA(pe_imp
->FirstThunk
);
315 while (import_list
->u1
.Ordinal
) {
316 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
)) {
317 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
319 TRACE("--- Ordinal %s,%d\n", name
, ordinal
);
320 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
321 wmImp
->module
, (LPCSTR
)ordinal
, TRUE
323 if (!thunk_list
->u1
.Function
) {
324 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
326 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
328 } else { /* import by name */
329 pe_name
= (PIMAGE_IMPORT_BY_NAME
)RVA(import_list
->u1
.AddressOfData
);
330 TRACE("--- %s %s.%d\n", pe_name
->Name
, name
, pe_name
->Hint
);
331 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
332 wmImp
->module
, pe_name
->Name
, TRUE
334 if (!thunk_list
->u1
.Function
) {
335 ERR("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
336 name
,pe_name
->Hint
,pe_name
->Name
);
337 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
343 } else { /* Borland style */
344 TRACE("Borland style imports used\n");
345 thunk_list
= (PIMAGE_THUNK_DATA
) RVA(pe_imp
->FirstThunk
);
346 while (thunk_list
->u1
.Ordinal
) {
347 if (IMAGE_SNAP_BY_ORDINAL(thunk_list
->u1
.Ordinal
)) {
348 /* not sure about this branch, but it seems to work */
349 int ordinal
= IMAGE_ORDINAL(thunk_list
->u1
.Ordinal
);
351 TRACE("--- Ordinal %s.%d\n",name
,ordinal
);
352 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
353 wmImp
->module
, (LPCSTR
) ordinal
, TRUE
355 if (!thunk_list
->u1
.Function
) {
356 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
358 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
361 pe_name
=(PIMAGE_IMPORT_BY_NAME
) RVA(thunk_list
->u1
.AddressOfData
);
362 TRACE("--- %s %s.%d\n",
363 pe_name
->Name
,name
,pe_name
->Hint
);
364 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
365 wmImp
->module
, pe_name
->Name
, TRUE
367 if (!thunk_list
->u1
.Function
) {
368 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
369 name
, pe_name
->Hint
);
370 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
380 static int calc_vma_size( HMODULE hModule
)
383 IMAGE_SECTION_HEADER
*pe_seg
= PE_SECTIONS(hModule
);
385 TRACE("Dump of segment table\n");
386 TRACE(" Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
387 for (i
= 0; i
< PE_HEADER(hModule
)->FileHeader
.NumberOfSections
; i
++)
389 TRACE("%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
391 pe_seg
->Misc
.VirtualSize
,
392 pe_seg
->VirtualAddress
,
393 pe_seg
->SizeOfRawData
,
394 pe_seg
->PointerToRawData
,
395 pe_seg
->PointerToRelocations
,
396 pe_seg
->PointerToLinenumbers
,
397 pe_seg
->NumberOfRelocations
,
398 pe_seg
->NumberOfLinenumbers
,
399 pe_seg
->Characteristics
);
400 vma_size
=max(vma_size
, pe_seg
->VirtualAddress
+pe_seg
->SizeOfRawData
);
401 vma_size
=max(vma_size
, pe_seg
->VirtualAddress
+pe_seg
->Misc
.VirtualSize
);
407 static void do_relocations( unsigned int load_addr
, IMAGE_BASE_RELOCATION
*r
)
409 int delta
= load_addr
- PE_HEADER(load_addr
)->OptionalHeader
.ImageBase
;
410 int hdelta
= (delta
>> 16) & 0xFFFF;
411 int ldelta
= delta
& 0xFFFF;
416 while(r
->VirtualAddress
)
418 char *page
= (char*) RVA(r
->VirtualAddress
);
419 int count
= (r
->SizeOfBlock
- 8)/2;
421 TRACE_(fixup
)("%x relocations for page %lx\n",
422 count
, r
->VirtualAddress
);
423 /* patching in reverse order */
426 int offset
= r
->TypeOffset
[i
] & 0xFFF;
427 int type
= r
->TypeOffset
[i
] >> 12;
428 TRACE_(fixup
)("patching %x type %x\n", offset
, type
);
431 case IMAGE_REL_BASED_ABSOLUTE
: break;
432 case IMAGE_REL_BASED_HIGH
:
433 *(short*)(page
+offset
) += hdelta
;
435 case IMAGE_REL_BASED_LOW
:
436 *(short*)(page
+offset
) += ldelta
;
438 case IMAGE_REL_BASED_HIGHLOW
:
439 *(int*)(page
+offset
) += delta
;
440 /* FIXME: if this is an exported address, fire up enhanced logic */
442 case IMAGE_REL_BASED_HIGHADJ
:
443 FIXME("Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
445 case IMAGE_REL_BASED_MIPS_JMPADDR
:
446 FIXME("Is this a MIPS machine ???\n");
449 FIXME("Unknown fixup type\n");
453 r
= (IMAGE_BASE_RELOCATION
*)((char*)r
+ r
->SizeOfBlock
);
461 /**********************************************************************
463 * Load one PE format DLL/EXE into memory
465 * Unluckily we can't just mmap the sections where we want them, for
466 * (at least) Linux does only support offsets which are page-aligned.
468 * BUT we have to map the whole image anyway, for Win32 programs sometimes
469 * want to access them. (HMODULE32 point to the start of it)
471 HMODULE
PE_LoadImage( HANDLE hFile
, LPCSTR filename
, WORD
*version
)
476 IMAGE_NT_HEADERS
*nt
;
477 IMAGE_SECTION_HEADER
*pe_sec
;
478 IMAGE_DATA_DIRECTORY
*dir
;
479 BY_HANDLE_FILE_INFORMATION bhfi
;
480 int i
, rawsize
, lowest_va
, lowest_fa
, vma_size
, file_size
= 0;
481 DWORD load_addr
, aoep
, reloc
= 0;
483 /* Retrieve file size */
484 if ( GetFileInformationByHandle( hFile
, &bhfi
) )
485 file_size
= bhfi
.nFileSizeLow
; /* FIXME: 64 bit */
487 /* Map the PE file somewhere */
488 mapping
= CreateFileMappingA( hFile
, NULL
, PAGE_READONLY
| SEC_COMMIT
,
492 WARN("CreateFileMapping error %ld\n", GetLastError() );
495 hModule
= (HMODULE
)MapViewOfFile( mapping
, FILE_MAP_READ
, 0, 0, 0 );
496 CloseHandle( mapping
);
499 WARN("MapViewOfFile error %ld\n", GetLastError() );
502 if ( *(WORD
*)hModule
!=IMAGE_DOS_SIGNATURE
)
504 WARN("%s image doesn't have DOS signature, but 0x%04x\n", filename
,*(WORD
*)hModule
);
508 nt
= PE_HEADER( hModule
);
510 /* Check signature */
511 if ( nt
->Signature
!= IMAGE_NT_SIGNATURE
)
513 WARN("%s image doesn't have PE signature, but 0x%08lx\n", filename
, nt
->Signature
);
517 /* Check architecture */
518 if ( nt
->FileHeader
.Machine
!= IMAGE_FILE_MACHINE_I386
)
520 MESSAGE("Trying to load PE image for unsupported architecture (");
521 switch (nt
->FileHeader
.Machine
)
523 case IMAGE_FILE_MACHINE_UNKNOWN
: MESSAGE("Unknown"); break;
524 case IMAGE_FILE_MACHINE_I860
: MESSAGE("I860"); break;
525 case IMAGE_FILE_MACHINE_R3000
: MESSAGE("R3000"); break;
526 case IMAGE_FILE_MACHINE_R4000
: MESSAGE("R4000"); break;
527 case IMAGE_FILE_MACHINE_R10000
: MESSAGE("R10000"); break;
528 case IMAGE_FILE_MACHINE_ALPHA
: MESSAGE("Alpha"); break;
529 case IMAGE_FILE_MACHINE_POWERPC
: MESSAGE("PowerPC"); break;
530 default: MESSAGE("Unknown-%04x", nt
->FileHeader
.Machine
); break;
536 /* Find out how large this executeable should be */
537 pe_sec
= PE_SECTIONS( hModule
);
538 rawsize
= 0; lowest_va
= 0x10000; lowest_fa
= 0x10000;
539 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
541 if (lowest_va
> pe_sec
[i
].VirtualAddress
)
542 lowest_va
= pe_sec
[i
].VirtualAddress
;
543 if (pe_sec
[i
].Characteristics
& IMAGE_SCN_CNT_UNINITIALIZED_DATA
)
545 if (pe_sec
[i
].PointerToRawData
< lowest_fa
)
546 lowest_fa
= pe_sec
[i
].PointerToRawData
;
547 if (pe_sec
[i
].PointerToRawData
+pe_sec
[i
].SizeOfRawData
> rawsize
)
548 rawsize
= pe_sec
[i
].PointerToRawData
+pe_sec
[i
].SizeOfRawData
;
551 /* Check file size */
552 if ( file_size
&& file_size
< rawsize
)
554 ERR("PE module is too small (header: %d, filesize: %d), "
555 "probably truncated download?\n",
556 rawsize
, file_size
);
560 /* Check entrypoint address */
561 aoep
= nt
->OptionalHeader
.AddressOfEntryPoint
;
562 if (aoep
&& (aoep
< lowest_va
))
563 FIXME("VIRUS WARNING: '%s' has an invalid entrypoint (0x%08lx) "
564 "below the first virtual address (0x%08x) "
565 "(possibly infected by Tchernobyl/SpaceFiller virus)!\n",
566 filename
, aoep
, lowest_va
);
569 /* FIXME: Hack! While we don't really support shared sections yet,
570 * this checks for those special cases where the whole DLL
571 * consists only of shared sections and is mapped into the
572 * shared address space > 2GB. In this case, we assume that
573 * the module got mapped at its base address. Thus we simply
574 * check whether the module has actually been mapped there
575 * and use it, if so. This is needed to get Win95 USER32.DLL
576 * to work (until we support shared sections properly).
579 if ( nt
->OptionalHeader
.ImageBase
& 0x80000000 )
581 HMODULE sharedMod
= (HMODULE
)nt
->OptionalHeader
.ImageBase
;
582 IMAGE_NT_HEADERS
*sharedNt
= (PIMAGE_NT_HEADERS
)
583 ( (LPBYTE
)sharedMod
+ ((LPBYTE
)nt
- (LPBYTE
)hModule
) );
585 /* Well, this check is not really comprehensive,
586 but should be good enough for now ... */
587 if ( !IsBadReadPtr( (LPBYTE
)sharedMod
, sizeof(IMAGE_DOS_HEADER
) )
588 && memcmp( (LPBYTE
)sharedMod
, (LPBYTE
)hModule
, sizeof(IMAGE_DOS_HEADER
) ) == 0
589 && !IsBadReadPtr( sharedNt
, sizeof(IMAGE_NT_HEADERS
) )
590 && memcmp( sharedNt
, nt
, sizeof(IMAGE_NT_HEADERS
) ) == 0 )
592 UnmapViewOfFile( (LPVOID
)hModule
);
598 /* Allocate memory for module */
599 load_addr
= nt
->OptionalHeader
.ImageBase
;
600 vma_size
= calc_vma_size( hModule
);
602 load_addr
= (DWORD
)VirtualAlloc( (void*)load_addr
, vma_size
,
603 MEM_RESERVE
| MEM_COMMIT
,
604 PAGE_EXECUTE_READWRITE
);
607 /* We need to perform base relocations */
608 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_BASERELOC
;
610 reloc
= dir
->VirtualAddress
;
614 "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
616 (nt
->FileHeader
.Characteristics
&IMAGE_FILE_RELOCS_STRIPPED
)?
617 "stripped during link" : "unknown reason" );
621 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
622 * really make sure that the *new* base address is also > 2GB.
623 * Some DLLs really check the MSB of the module handle :-/
625 if ( nt
->OptionalHeader
.ImageBase
& 0x80000000 )
626 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
628 load_addr
= (DWORD
)VirtualAlloc( NULL
, vma_size
,
629 MEM_RESERVE
| MEM_COMMIT
,
630 PAGE_EXECUTE_READWRITE
);
633 "FATAL: Couldn't load module %s (out of memory, %d needed)!\n", filename
, vma_size
);
638 TRACE("Load addr is %lx (base %lx), range %x\n",
639 load_addr
, nt
->OptionalHeader
.ImageBase
, vma_size
);
640 TRACE_(segment
)("Loading %s at %lx, range %x\n",
641 filename
, load_addr
, vma_size
);
643 /* Store the NT header at the load addr */
644 *(PIMAGE_DOS_HEADER
)load_addr
= *(PIMAGE_DOS_HEADER
)hModule
;
645 *PE_HEADER( load_addr
) = *nt
;
646 memcpy( PE_SECTIONS(load_addr
), PE_SECTIONS(hModule
),
647 sizeof(IMAGE_SECTION_HEADER
) * nt
->FileHeader
.NumberOfSections
);
649 /* Copies all stuff up to the first section. Including win32 viruses. */
650 memcpy( load_addr
, hModule
, lowest_fa
);
653 /* Copy sections into module image */
654 pe_sec
= PE_SECTIONS( hModule
);
655 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, pe_sec
++)
657 /* memcpy only non-BSS segments */
658 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
659 * but it is not possible for (at least) Linux needs
660 * a page-aligned offset.
662 if(!(pe_sec
->Characteristics
& IMAGE_SCN_CNT_UNINITIALIZED_DATA
))
663 memcpy((char*)RVA(pe_sec
->VirtualAddress
),
664 (char*)(hModule
+ pe_sec
->PointerToRawData
),
665 pe_sec
->SizeOfRawData
);
667 /* not needed, memory is zero */
668 if(strcmp(pe_sec
->Name
, ".bss") == 0)
669 memset((void *)RVA(pe_sec
->VirtualAddress
), 0,
670 pe_sec
->Misc
.VirtualSize
?
671 pe_sec
->Misc
.VirtualSize
:
672 pe_sec
->SizeOfRawData
);
676 /* Perform base relocation, if necessary */
678 do_relocations( load_addr
, (IMAGE_BASE_RELOCATION
*)RVA(reloc
) );
680 /* Get expected OS / Subsystem version */
681 *version
= ( (nt
->OptionalHeader
.MajorSubsystemVersion
& 0xff) << 8 )
682 | (nt
->OptionalHeader
.MinorSubsystemVersion
& 0xff);
684 /* We don't need the orignal mapping any more */
685 UnmapViewOfFile( (LPVOID
)hModule
);
686 return (HMODULE
)load_addr
;
689 UnmapViewOfFile( (LPVOID
)hModule
);
693 /**********************************************************************
696 * Create WINE_MODREF structure for loaded HMODULE32, link it into
697 * process modref_list, and fixup all imports.
699 * Note: hModule must point to a correctly allocated PE image,
700 * with base relocations applied; the 16-bit dummy module
701 * associated to hModule must already exist.
703 * Note: This routine must always be called in the context of the
704 * process that is to own the module to be created.
706 WINE_MODREF
*PE_CreateModule( HMODULE hModule
,
707 LPCSTR filename
, DWORD flags
, BOOL builtin
)
709 DWORD load_addr
= (DWORD
)hModule
; /* for RVA */
710 IMAGE_NT_HEADERS
*nt
= PE_HEADER(hModule
);
711 IMAGE_DATA_DIRECTORY
*dir
;
712 IMAGE_IMPORT_DESCRIPTOR
*pe_import
= NULL
;
713 IMAGE_EXPORT_DIRECTORY
*pe_export
= NULL
;
714 IMAGE_RESOURCE_DIRECTORY
*pe_resource
= NULL
;
719 /* Retrieve DataDirectory entries */
721 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXPORT
;
723 pe_export
= (PIMAGE_EXPORT_DIRECTORY
)RVA(dir
->VirtualAddress
);
725 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_IMPORT
;
727 pe_import
= (PIMAGE_IMPORT_DESCRIPTOR
)RVA(dir
->VirtualAddress
);
729 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_RESOURCE
;
731 pe_resource
= (PIMAGE_RESOURCE_DIRECTORY
)RVA(dir
->VirtualAddress
);
733 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXCEPTION
;
734 if (dir
->Size
) FIXME("Exception directory ignored\n" );
736 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_SECURITY
;
737 if (dir
->Size
) FIXME("Security directory ignored\n" );
739 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
740 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
742 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_DEBUG
;
743 if (dir
->Size
) TRACE("Debug directory ignored\n" );
745 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_COPYRIGHT
;
746 if (dir
->Size
) FIXME("Copyright string ignored\n" );
748 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_GLOBALPTR
;
749 if (dir
->Size
) FIXME("Global Pointer (MIPS) ignored\n" );
751 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
753 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
;
754 if (dir
->Size
) FIXME("Load Configuration directory ignored\n" );
756 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
;
757 if (dir
->Size
) TRACE("Bound Import directory ignored\n" );
759 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_IAT
;
760 if (dir
->Size
) TRACE("Import Address Table directory ignored\n" );
762 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT
;
765 TRACE("Delayed import, stub calls LoadLibrary\n" );
767 * Nothing to do here.
772 * This code is useful to observe what the heck is going on.
775 ImgDelayDescr
*pe_delay
= NULL
;
776 pe_delay
= (PImgDelayDescr
)RVA(dir
->VirtualAddress
);
777 TRACE_(delayhlp
)("pe_delay->grAttrs = %08x\n", pe_delay
->grAttrs
);
778 TRACE_(delayhlp
)("pe_delay->szName = %s\n", pe_delay
->szName
);
779 TRACE_(delayhlp
)("pe_delay->phmod = %08x\n", pe_delay
->phmod
);
780 TRACE_(delayhlp
)("pe_delay->pIAT = %08x\n", pe_delay
->pIAT
);
781 TRACE_(delayhlp
)("pe_delay->pINT = %08x\n", pe_delay
->pINT
);
782 TRACE_(delayhlp
)("pe_delay->pBoundIAT = %08x\n", pe_delay
->pBoundIAT
);
783 TRACE_(delayhlp
)("pe_delay->pUnloadIAT = %08x\n", pe_delay
->pUnloadIAT
);
784 TRACE_(delayhlp
)("pe_delay->dwTimeStamp = %08x\n", pe_delay
->dwTimeStamp
);
786 #endif /* ImgDelayDescr */
789 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
;
790 if (dir
->Size
) FIXME("Unknown directory 14 ignored\n" );
792 dir
= nt
->OptionalHeader
.DataDirectory
+15;
793 if (dir
->Size
) FIXME("Unknown directory 15 ignored\n" );
796 /* Allocate and fill WINE_MODREF */
798 wm
= (WINE_MODREF
*)HeapAlloc( GetProcessHeap(),
799 HEAP_ZERO_MEMORY
, sizeof(*wm
) );
800 wm
->module
= hModule
;
803 wm
->flags
|= WINE_MODREF_INTERNAL
;
804 if ( flags
& DONT_RESOLVE_DLL_REFERENCES
)
805 wm
->flags
|= WINE_MODREF_DONT_RESOLVE_REFS
;
806 if ( flags
& LOAD_LIBRARY_AS_DATAFILE
)
807 wm
->flags
|= WINE_MODREF_LOAD_AS_DATAFILE
;
809 wm
->type
= MODULE32_PE
;
810 wm
->binfmt
.pe
.pe_export
= pe_export
;
811 wm
->binfmt
.pe
.pe_import
= pe_import
;
812 wm
->binfmt
.pe
.pe_resource
= pe_resource
;
813 wm
->binfmt
.pe
.tlsindex
= -1;
815 wm
->filename
= HEAP_strdupA( GetProcessHeap(), 0, filename
);
816 wm
->modname
= strrchr( wm
->filename
, '\\' );
817 if (!wm
->modname
) wm
->modname
= wm
->filename
;
820 result
= GetShortPathNameA( wm
->filename
, NULL
, 0 );
821 wm
->short_filename
= (char *)HeapAlloc( GetProcessHeap(), 0, result
+1 );
822 GetShortPathNameA( wm
->filename
, wm
->short_filename
, result
+1 );
823 wm
->short_modname
= strrchr( wm
->short_filename
, '\\' );
824 if (!wm
->short_modname
) wm
->short_modname
= wm
->short_filename
;
825 else wm
->short_modname
++;
827 /* Link MODREF into process list */
829 EnterCriticalSection( &PROCESS_Current()->crit_section
);
831 wm
->next
= PROCESS_Current()->modref_list
;
832 PROCESS_Current()->modref_list
= wm
;
833 if ( wm
->next
) wm
->next
->prev
= wm
;
835 if ( !( nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
836 && !( wm
->flags
& WINE_MODREF_LOAD_AS_DATAFILE
) )
839 if ( PROCESS_Current()->exe_modref
)
840 FIXME( "Trying to load second .EXE file: %s\n", filename
);
842 PROCESS_Current()->exe_modref
= wm
;
845 LeaveCriticalSection( &PROCESS_Current()->crit_section
);
851 dump_exports( hModule
);
856 && !( wm
->flags
& WINE_MODREF_LOAD_AS_DATAFILE
)
857 && !( wm
->flags
& WINE_MODREF_DONT_RESOLVE_REFS
)
858 && fixup_imports( wm
) )
860 /* remove entry from modref chain */
861 EnterCriticalSection( &PROCESS_Current()->crit_section
);
864 PROCESS_Current()->modref_list
= wm
->next
;
866 wm
->prev
->next
= wm
->next
;
868 if ( wm
->next
) wm
->next
->prev
= wm
->prev
;
869 wm
->next
= wm
->prev
= NULL
;
871 LeaveCriticalSection( &PROCESS_Current()->crit_section
);
873 /* FIXME: there are several more dangling references
874 * left. Including dlls loaded by this dll before the
875 * failed one. Unrolling is rather difficult with the
876 * current structure and we can leave it them lying
877 * around with no problems, so we don't care.
878 * As these might reference our wm, we don't free it.
886 /******************************************************************************
887 * The PE Library Loader frontend.
888 * FIXME: handle the flags.
890 WINE_MODREF
*PE_LoadLibraryExA (LPCSTR name
, DWORD flags
)
892 struct load_dll_request
*req
= get_req_buffer();
901 /* Search for and open PE file */
902 if ( SearchPathA( NULL
, name
, ".DLL",
903 sizeof(filename
), filename
, NULL
) == 0 ) return NULL
;
905 hFile
= CreateFileA( filename
, GENERIC_READ
, FILE_SHARE_READ
,
906 NULL
, OPEN_EXISTING
, 0, -1 );
907 if ( hFile
== INVALID_HANDLE_VALUE
) return NULL
;
910 hModule32
= PE_LoadImage( hFile
, filename
, &version
);
913 CloseHandle( hFile
);
914 SetLastError( ERROR_OUTOFMEMORY
); /* Not entirely right, but good enough */
918 /* Create 16-bit dummy module */
919 if ((hModule16
= MODULE_CreateDummyModule( filename
, version
)) < 32)
921 CloseHandle( hFile
);
922 SetLastError( (DWORD
)hModule16
); /* This should give the correct error */
925 pModule
= (NE_MODULE
*)GlobalLock16( hModule16
);
926 pModule
->flags
= NE_FFLAGS_LIBMODULE
| NE_FFLAGS_SINGLEDATA
| NE_FFLAGS_WIN32
;
927 pModule
->module32
= hModule32
;
929 /* Create 32-bit MODREF */
930 if ( !(wm
= PE_CreateModule( hModule32
, filename
, flags
, FALSE
)) )
932 ERR( "can't load %s\n", filename
);
933 FreeLibrary16( hModule16
);
934 CloseHandle( hFile
);
935 SetLastError( ERROR_OUTOFMEMORY
);
939 if (wm
->binfmt
.pe
.pe_export
)
940 SNOOP_RegisterDLL(wm
->module
,wm
->modname
,wm
->binfmt
.pe
.pe_export
->NumberOfFunctions
);
942 req
->base
= (void *)hModule32
;
945 req
->name
= &wm
->modname
;
946 server_call_noerr( REQ_LOAD_DLL
);
947 CloseHandle( hFile
);
952 /*****************************************************************************
955 * Unload the library unmapping the image and freeing the modref structure.
957 void PE_UnloadLibrary(WINE_MODREF
*wm
)
959 DWORD vma_size
= calc_vma_size( wm
->module
);
960 VirtualFree( (LPVOID
)wm
->module
, vma_size
, MEM_RELEASE
);
962 HeapFree( GetProcessHeap(), 0, wm
->filename
);
963 HeapFree( GetProcessHeap(), 0, wm
->short_filename
);
964 HeapFree( GetProcessHeap(), 0, wm
);
967 /*****************************************************************************
968 * Load the PE main .EXE. All other loading is done by PE_LoadLibraryExA
969 * FIXME: this function should use PE_LoadLibraryExA, but currently can't
970 * due to the PROCESS_Create stuff.
972 BOOL
PE_CreateProcess( HANDLE hFile
, LPCSTR filename
, LPCSTR cmd_line
, LPCSTR env
,
973 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
974 BOOL inherit
, DWORD flags
, LPSTARTUPINFOA startup
,
975 LPPROCESS_INFORMATION info
)
983 if ( (hModule32
= PE_LoadImage( hFile
, filename
, &version
)) < 32 )
985 SetLastError( hModule32
);
989 if (PE_HEADER(hModule32
)->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
991 SetLastError( 20 ); /* FIXME: not the right error code */
996 /* Create 16-bit dummy module */
997 if ( (hModule16
= MODULE_CreateDummyModule( filename
, version
)) < 32 )
999 SetLastError( hModule16
);
1002 pModule
= (NE_MODULE
*)GlobalLock16( hModule16
);
1003 pModule
->flags
= NE_FFLAGS_WIN32
;
1004 pModule
->module32
= hModule32
;
1006 /* Create new process */
1007 if ( !PROCESS_Create( pModule
, hFile
, cmd_line
, env
,
1008 psa
, tsa
, inherit
, flags
, startup
, info
) )
1011 /* Note: PE_CreateModule and the remaining process initialization will
1012 be done in the context of the new process, in TASK_CallToStart */
1017 /*********************************************************************
1018 * PE_UnloadImage [internal]
1020 int PE_UnloadImage( HMODULE hModule
)
1023 /* free resources, image, unmap */
1027 /* Called if the library is loaded or freed.
1028 * NOTE: if a thread attaches a DLL, the current thread will only do
1029 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
1032 BOOL
PE_InitDLL( WINE_MODREF
*wm
, DWORD type
, LPVOID lpReserved
)
1035 assert( wm
->type
== MODULE32_PE
);
1037 /* Is this a library? And has it got an entrypoint? */
1038 if ((PE_HEADER(wm
->module
)->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1039 (PE_HEADER(wm
->module
)->OptionalHeader
.AddressOfEntryPoint
)
1041 DLLENTRYPROC entry
= (void*)RVA_PTR( wm
->module
,OptionalHeader
.AddressOfEntryPoint
);
1042 TRACE_(relay
)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
1043 entry
, wm
->module
, type
, lpReserved
);
1045 retv
= entry( wm
->module
, type
, lpReserved
);
1051 /************************************************************************
1052 * PE_InitTls (internal)
1054 * If included, initialises the thread local storages of modules.
1055 * Pointers in those structs are not RVAs but real pointers which have been
1056 * relocated by do_relocations() already.
1059 _fixup_address(PIMAGE_OPTIONAL_HEADER opt
,int delta
,LPVOID addr
) {
1060 if ( ((DWORD
)addr
>opt
->ImageBase
) &&
1061 ((DWORD
)addr
<opt
->ImageBase
+opt
->SizeOfImage
)
1063 /* the address has not been relocated! */
1064 return (LPVOID
)(((DWORD
)addr
)+delta
);
1066 /* the address has been relocated already */
1069 void PE_InitTls( void )
1073 IMAGE_NT_HEADERS
*peh
;
1074 DWORD size
,datasize
;
1076 PIMAGE_TLS_DIRECTORY pdir
;
1079 for (wm
= PROCESS_Current()->modref_list
;wm
;wm
=wm
->next
) {
1080 if (wm
->type
!=MODULE32_PE
)
1082 pem
= &(wm
->binfmt
.pe
);
1083 peh
= PE_HEADER(wm
->module
);
1084 delta
= wm
->module
- peh
->OptionalHeader
.ImageBase
;
1085 if (!peh
->OptionalHeader
.DataDirectory
[IMAGE_FILE_THREAD_LOCAL_STORAGE
].VirtualAddress
)
1087 pdir
= (LPVOID
)(wm
->module
+ peh
->OptionalHeader
.
1088 DataDirectory
[IMAGE_FILE_THREAD_LOCAL_STORAGE
].VirtualAddress
);
1091 if ( pem
->tlsindex
== -1 ) {
1093 pem
->tlsindex
= TlsAlloc();
1094 xaddr
= _fixup_address(&(peh
->OptionalHeader
),delta
,
1095 pdir
->AddressOfIndex
1097 *xaddr
=pem
->tlsindex
;
1099 datasize
= pdir
->EndAddressOfRawData
-pdir
->StartAddressOfRawData
;
1100 size
= datasize
+ pdir
->SizeOfZeroFill
;
1101 mem
=VirtualAlloc(0,size
,MEM_RESERVE
|MEM_COMMIT
,PAGE_READWRITE
);
1102 memcpy(mem
,_fixup_address(&(peh
->OptionalHeader
),delta
,(LPVOID
)pdir
->StartAddressOfRawData
),datasize
);
1103 if (pdir
->AddressOfCallBacks
) {
1104 PIMAGE_TLS_CALLBACK
*cbs
;
1106 cbs
= _fixup_address(&(peh
->OptionalHeader
),delta
,pdir
->AddressOfCallBacks
);
1108 FIXME("TLS Callbacks aren't going to be called\n");
1111 TlsSetValue( pem
->tlsindex
, mem
);