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).
41 #include <sys/types.h>
59 #include "debugtools.h"
61 DECLARE_DEBUG_CHANNEL(delayhlp
)
62 DECLARE_DEBUG_CHANNEL(fixup
)
63 DECLARE_DEBUG_CHANNEL(module
)
64 DECLARE_DEBUG_CHANNEL(relay
)
65 DECLARE_DEBUG_CHANNEL(segment
)
66 DECLARE_DEBUG_CHANNEL(win32
)
69 /* convert PE image VirtualAddress to Real Address */
70 #define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
72 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
74 void dump_exports( HMODULE hModule
)
79 u_long
*function
,*functions
;
81 unsigned int load_addr
= hModule
;
83 DWORD rva_start
= PE_HEADER(hModule
)->OptionalHeader
84 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
85 DWORD rva_end
= rva_start
+ PE_HEADER(hModule
)->OptionalHeader
86 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].Size
;
87 IMAGE_EXPORT_DIRECTORY
*pe_exports
= (IMAGE_EXPORT_DIRECTORY
*)RVA(rva_start
);
89 Module
= (char*)RVA(pe_exports
->Name
);
90 TRACE_(win32
)("*******EXPORT DATA*******\n");
91 TRACE_(win32
)("Module name is %s, %ld functions, %ld names\n",
92 Module
, pe_exports
->NumberOfFunctions
, pe_exports
->NumberOfNames
);
94 ordinal
=(u_short
*) RVA(pe_exports
->AddressOfNameOrdinals
);
95 functions
=function
=(u_long
*) RVA(pe_exports
->AddressOfFunctions
);
96 name
=(u_char
**) RVA(pe_exports
->AddressOfNames
);
98 TRACE_(win32
)(" Ord RVA Addr Name\n" );
99 for (i
=0;i
<pe_exports
->NumberOfFunctions
;i
++, function
++)
101 if (!*function
) continue; /* No such function */
102 if (TRACE_ON(win32
)){
103 dbg_decl_str(win32
, 1024);
105 dsprintf(win32
,"%4ld %08lx %08x",
106 i
+ pe_exports
->Base
, *function
, RVA(*function
) );
107 /* Check if we have a name for it */
108 for (j
= 0; j
< pe_exports
->NumberOfNames
; j
++)
110 dsprintf(win32
, " %s", (char*)RVA(name
[j
]) );
111 if ((*function
>= rva_start
) && (*function
<= rva_end
))
112 dsprintf(win32
, " (forwarded -> %s)", (char *)RVA(*function
));
113 TRACE_(win32
)("%s\n", dbg_str(win32
));
118 /* Look up the specified function or ordinal in the exportlist:
120 * - look up the name in the Name list.
121 * - look up the ordinal with that index.
122 * - use the ordinal as offset into the functionlist
123 * If it is a ordinal:
124 * - use ordinal-pe_export->Base as offset into the functionlist
126 FARPROC
PE_FindExportedFunction(
127 WINE_MODREF
*wm
, /* [in] WINE modreference */
128 LPCSTR funcName
, /* [in] function name */
133 u_char
** name
, *ename
;
135 PE_MODREF
*pem
= &(wm
->binfmt
.pe
);
136 IMAGE_EXPORT_DIRECTORY
*exports
= pem
->pe_export
;
137 unsigned int load_addr
= wm
->module
;
138 u_long rva_start
, rva_end
, addr
;
141 if (HIWORD(funcName
))
142 TRACE_(win32
)("(%s)\n",funcName
);
144 TRACE_(win32
)("(%d)\n",(int)funcName
);
146 /* Not a fatal problem, some apps do
147 * GetProcAddress(0,"RegisterPenApp") which triggers this
150 WARN_(win32
)("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm
->module
,wm
->modname
,pem
);
153 ordinal
= (u_short
*) RVA(exports
->AddressOfNameOrdinals
);
154 function
= (u_long
*) RVA(exports
->AddressOfFunctions
);
155 name
= (u_char
**) RVA(exports
->AddressOfNames
);
157 rva_start
= PE_HEADER(wm
->module
)->OptionalHeader
158 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].VirtualAddress
;
159 rva_end
= rva_start
+ PE_HEADER(wm
->module
)->OptionalHeader
160 .DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT
].Size
;
162 if (HIWORD(funcName
)) {
163 for(i
=0; i
<exports
->NumberOfNames
; i
++) {
164 ename
=(char*)RVA(*name
);
165 if(!strcmp(ename
,funcName
))
167 addr
= function
[*ordinal
];
168 if (!addr
) return NULL
;
169 if ((addr
< rva_start
) || (addr
>= rva_end
))
170 return snoop
? SNOOP_GetProcAddress(wm
->module
,ename
,*ordinal
,(FARPROC
)RVA(addr
))
171 : (FARPROC
)RVA(addr
);
172 forward
= (char *)RVA(addr
);
180 if (LOWORD(funcName
)-exports
->Base
> exports
->NumberOfFunctions
) {
181 TRACE_(win32
)(" ordinal %d out of range!\n",
185 addr
= function
[(int)funcName
-exports
->Base
];
186 if (!addr
) return NULL
;
189 for (i
=0;i
<exports
->NumberOfNames
;i
++) {
190 ename
= (char*)RVA(*name
);
191 if (*ordinal
== LOWORD(funcName
)-exports
->Base
)
196 if (i
==exports
->NumberOfNames
)
199 if ((addr
< rva_start
) || (addr
>= rva_end
))
200 return snoop
? SNOOP_GetProcAddress(wm
->module
,ename
,(DWORD
)funcName
-exports
->Base
,(FARPROC
)RVA(addr
))
201 : (FARPROC
)RVA(addr
);
202 forward
= (char *)RVA(addr
);
208 char *end
= strchr(forward
, '.');
210 if (!end
) return NULL
;
211 assert(end
-forward
<256);
212 strncpy(module
, forward
, (end
- forward
));
213 module
[end
-forward
] = 0;
214 if (!(wm
= MODULE_FindModule( module
)))
216 ERR_(win32
)("module not found for forward '%s'\n", forward
);
219 return MODULE_GetProcAddress( wm
->module
, end
+ 1, snoop
);
224 DWORD
fixup_imports( WINE_MODREF
*wm
)
226 IMAGE_IMPORT_DESCRIPTOR
*pe_imp
;
228 unsigned int load_addr
= wm
->module
;
229 int i
,characteristics_detection
=1;
232 assert(wm
->type
==MODULE32_PE
);
233 pem
= &(wm
->binfmt
.pe
);
235 modname
= (char*) RVA(pem
->pe_export
->Name
);
237 modname
= "<unknown>";
239 /* OK, now dump the import list */
240 TRACE_(win32
)("Dumping imports list\n");
242 /* first, count the number of imported non-internal modules */
243 pe_imp
= pem
->pe_import
;
244 if (!pe_imp
) return 0;
246 /* We assume that we have at least one import with !0 characteristics and
247 * detect broken imports with all characteristsics 0 (notably Borland) and
248 * switch the detection off for them.
250 for (i
= 0; pe_imp
->Name
; pe_imp
++) {
251 if (!i
&& !pe_imp
->u
.Characteristics
)
252 characteristics_detection
= 0;
253 if (characteristics_detection
&& !pe_imp
->u
.Characteristics
)
257 if (!i
) return 0; /* no imports */
259 /* Allocate module dependency list */
261 wm
->deps
= HeapAlloc( GetProcessHeap(), 0, i
*sizeof(WINE_MODREF
*) );
263 /* load the imported modules. They are automatically
264 * added to the modref list of the process.
267 for (i
= 0, pe_imp
= pem
->pe_import
; pe_imp
->Name
; pe_imp
++) {
269 IMAGE_IMPORT_BY_NAME
*pe_name
;
270 PIMAGE_THUNK_DATA import_list
,thunk_list
;
271 char *name
= (char *) RVA(pe_imp
->Name
);
273 if (characteristics_detection
&& !pe_imp
->u
.Characteristics
)
276 /* don't use MODULE_Load, Win32 creates new task differently */
277 wmImp
= MODULE_LoadLibraryExA( name
, 0, 0 );
279 char *p
,buffer
[2000];
281 /* GetModuleFileName would use the wrong process, so don't use it */
282 strcpy(buffer
,wm
->shortname
);
283 if (!(p
= strrchr (buffer
, '\\')))
285 strcpy (p
+ 1, name
);
286 wmImp
= MODULE_LoadLibraryExA( buffer
, 0, 0 );
289 ERR_(module
)("Module %s not found\n", name
);
292 wm
->deps
[i
++] = wmImp
;
294 /* FIXME: forwarder entries ... */
296 if (pe_imp
->u
.OriginalFirstThunk
!= 0) { /* original MS style */
297 TRACE_(win32
)("Microsoft style imports used\n");
298 import_list
=(PIMAGE_THUNK_DATA
) RVA(pe_imp
->u
.OriginalFirstThunk
);
299 thunk_list
= (PIMAGE_THUNK_DATA
) RVA(pe_imp
->FirstThunk
);
301 while (import_list
->u1
.Ordinal
) {
302 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
)) {
303 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
305 TRACE_(win32
)("--- Ordinal %s,%d\n", name
, ordinal
);
306 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
307 wmImp
->module
, (LPCSTR
)ordinal
, TRUE
309 if (!thunk_list
->u1
.Function
) {
310 ERR_(win32
)("No implementation for %s.%d, setting to 0xdeadbeef\n",
312 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
314 } else { /* import by name */
315 pe_name
= (PIMAGE_IMPORT_BY_NAME
)RVA(import_list
->u1
.AddressOfData
);
316 TRACE_(win32
)("--- %s %s.%d\n", pe_name
->Name
, name
, pe_name
->Hint
);
317 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
318 wmImp
->module
, pe_name
->Name
, TRUE
320 if (!thunk_list
->u1
.Function
) {
321 ERR_(win32
)("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
322 name
,pe_name
->Hint
,pe_name
->Name
);
323 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
329 } else { /* Borland style */
330 TRACE_(win32
)("Borland style imports used\n");
331 thunk_list
= (PIMAGE_THUNK_DATA
) RVA(pe_imp
->FirstThunk
);
332 while (thunk_list
->u1
.Ordinal
) {
333 if (IMAGE_SNAP_BY_ORDINAL(thunk_list
->u1
.Ordinal
)) {
334 /* not sure about this branch, but it seems to work */
335 int ordinal
= IMAGE_ORDINAL(thunk_list
->u1
.Ordinal
);
337 TRACE_(win32
)("--- Ordinal %s.%d\n",name
,ordinal
);
338 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
339 wmImp
->module
, (LPCSTR
) ordinal
, TRUE
341 if (!thunk_list
->u1
.Function
) {
342 ERR_(win32
)("No implementation for %s.%d, setting to 0xdeadbeef\n",
344 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
347 pe_name
=(PIMAGE_IMPORT_BY_NAME
) RVA(thunk_list
->u1
.AddressOfData
);
348 TRACE_(win32
)("--- %s %s.%d\n",
349 pe_name
->Name
,name
,pe_name
->Hint
);
350 thunk_list
->u1
.Function
=MODULE_GetProcAddress(
351 wmImp
->module
, pe_name
->Name
, TRUE
353 if (!thunk_list
->u1
.Function
) {
354 ERR_(win32
)("No implementation for %s.%d, setting to 0xdeadbeef\n",
355 name
, pe_name
->Hint
);
356 thunk_list
->u1
.Function
= (FARPROC
)0xdeadbeef;
366 static int calc_vma_size( HMODULE hModule
)
369 IMAGE_SECTION_HEADER
*pe_seg
= PE_SECTIONS(hModule
);
371 TRACE_(win32
)("Dump of segment table\n");
372 TRACE_(win32
)(" Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
373 for (i
= 0; i
< PE_HEADER(hModule
)->FileHeader
.NumberOfSections
; i
++)
375 TRACE_(win32
)("%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
377 pe_seg
->Misc
.VirtualSize
,
378 pe_seg
->VirtualAddress
,
379 pe_seg
->SizeOfRawData
,
380 pe_seg
->PointerToRawData
,
381 pe_seg
->PointerToRelocations
,
382 pe_seg
->PointerToLinenumbers
,
383 pe_seg
->NumberOfRelocations
,
384 pe_seg
->NumberOfLinenumbers
,
385 pe_seg
->Characteristics
);
386 vma_size
=MAX(vma_size
, pe_seg
->VirtualAddress
+pe_seg
->SizeOfRawData
);
387 vma_size
=MAX(vma_size
, pe_seg
->VirtualAddress
+pe_seg
->Misc
.VirtualSize
);
393 static void do_relocations( unsigned int load_addr
, IMAGE_BASE_RELOCATION
*r
)
395 int delta
= load_addr
- PE_HEADER(load_addr
)->OptionalHeader
.ImageBase
;
396 int hdelta
= (delta
>> 16) & 0xFFFF;
397 int ldelta
= delta
& 0xFFFF;
402 while(r
->VirtualAddress
)
404 char *page
= (char*) RVA(r
->VirtualAddress
);
405 int count
= (r
->SizeOfBlock
- 8)/2;
407 TRACE_(fixup
)("%x relocations for page %lx\n",
408 count
, r
->VirtualAddress
);
409 /* patching in reverse order */
412 int offset
= r
->TypeOffset
[i
] & 0xFFF;
413 int type
= r
->TypeOffset
[i
] >> 12;
414 TRACE_(fixup
)("patching %x type %x\n", offset
, type
);
417 case IMAGE_REL_BASED_ABSOLUTE
: break;
418 case IMAGE_REL_BASED_HIGH
:
419 *(short*)(page
+offset
) += hdelta
;
421 case IMAGE_REL_BASED_LOW
:
422 *(short*)(page
+offset
) += ldelta
;
424 case IMAGE_REL_BASED_HIGHLOW
:
425 *(int*)(page
+offset
) += delta
;
426 /* FIXME: if this is an exported address, fire up enhanced logic */
428 case IMAGE_REL_BASED_HIGHADJ
:
429 FIXME_(win32
)("Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
431 case IMAGE_REL_BASED_MIPS_JMPADDR
:
432 FIXME_(win32
)("Is this a MIPS machine ???\n");
435 FIXME_(win32
)("Unknown fixup type\n");
439 r
= (IMAGE_BASE_RELOCATION
*)((char*)r
+ r
->SizeOfBlock
);
447 /**********************************************************************
449 * Load one PE format DLL/EXE into memory
451 * Unluckily we can't just mmap the sections where we want them, for
452 * (at least) Linux does only support offsets which are page-aligned.
454 * BUT we have to map the whole image anyway, for Win32 programs sometimes
455 * want to access them. (HMODULE32 point to the start of it)
457 HMODULE
PE_LoadImage( HFILE hFile
, OFSTRUCT
*ofs
, LPCSTR
*modName
)
462 IMAGE_NT_HEADERS
*nt
;
463 IMAGE_SECTION_HEADER
*pe_sec
;
464 IMAGE_DATA_DIRECTORY
*dir
;
465 BY_HANDLE_FILE_INFORMATION bhfi
;
466 int i
, rawsize
, lowest_va
, lowest_fa
, vma_size
, file_size
= 0;
467 DWORD load_addr
, aoep
, reloc
= 0;
469 /* Retrieve file size */
470 if ( GetFileInformationByHandle( hFile
, &bhfi
) )
471 file_size
= bhfi
.nFileSizeLow
; /* FIXME: 64 bit */
473 /* Map the PE file somewhere */
474 mapping
= CreateFileMappingA( hFile
, NULL
, PAGE_READONLY
| SEC_COMMIT
,
478 WARN_(win32
)("CreateFileMapping error %ld\n", GetLastError() );
481 hModule
= (HMODULE
)MapViewOfFile( mapping
, FILE_MAP_READ
, 0, 0, 0 );
482 CloseHandle( mapping
);
485 WARN_(win32
)("MapViewOfFile error %ld\n", GetLastError() );
488 nt
= PE_HEADER( hModule
);
490 /* Check signature */
491 if ( nt
->Signature
!= IMAGE_NT_SIGNATURE
)
493 WARN_(win32
)("image doesn't have PE signature, but 0x%08lx\n",
498 /* Check architecture */
499 if ( nt
->FileHeader
.Machine
!= IMAGE_FILE_MACHINE_I386
)
501 MESSAGE("Trying to load PE image for unsupported architecture (");
502 switch (nt
->FileHeader
.Machine
)
504 case IMAGE_FILE_MACHINE_UNKNOWN
: MESSAGE("Unknown"); break;
505 case IMAGE_FILE_MACHINE_I860
: MESSAGE("I860"); break;
506 case IMAGE_FILE_MACHINE_R3000
: MESSAGE("R3000"); break;
507 case IMAGE_FILE_MACHINE_R4000
: MESSAGE("R4000"); break;
508 case IMAGE_FILE_MACHINE_R10000
: MESSAGE("R10000"); break;
509 case IMAGE_FILE_MACHINE_ALPHA
: MESSAGE("Alpha"); break;
510 case IMAGE_FILE_MACHINE_POWERPC
: MESSAGE("PowerPC"); break;
511 default: MESSAGE("Unknown-%04x", nt
->FileHeader
.Machine
); break;
517 /* Find out how large this executeable should be */
518 pe_sec
= PE_SECTIONS( hModule
);
519 rawsize
= 0; lowest_va
= 0x10000; lowest_fa
= 0x10000;
520 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
522 if (lowest_va
> pe_sec
[i
].VirtualAddress
)
523 lowest_va
= pe_sec
[i
].VirtualAddress
;
524 if (pe_sec
[i
].Characteristics
& IMAGE_SCN_CNT_UNINITIALIZED_DATA
)
526 if (pe_sec
[i
].PointerToRawData
< lowest_fa
)
527 lowest_fa
= pe_sec
[i
].PointerToRawData
;
528 if (pe_sec
[i
].PointerToRawData
+pe_sec
[i
].SizeOfRawData
> rawsize
)
529 rawsize
= pe_sec
[i
].PointerToRawData
+pe_sec
[i
].SizeOfRawData
;
532 /* Check file size */
533 if ( file_size
&& file_size
< rawsize
)
535 ERR_(win32
)("PE module is too small (header: %d, filesize: %d), "
536 "probably truncated download?\n",
537 rawsize
, file_size
);
541 /* Check entrypoint address */
542 aoep
= nt
->OptionalHeader
.AddressOfEntryPoint
;
543 if (aoep
&& (aoep
< lowest_va
))
544 FIXME_(win32
)("WARNING: '%s' has an invalid entrypoint (0x%08lx) "
545 "below the first virtual address (0x%08x) "
546 "(possible Virus Infection or broken binary)!\n",
547 ofs
->szPathName
, aoep
, lowest_va
);
550 /* FIXME: Hack! While we don't really support shared sections yet,
551 * this checks for those special cases where the whole DLL
552 * consists only of shared sections and is mapped into the
553 * shared address space > 2GB. In this case, we assume that
554 * the module got mapped at its base address. Thus we simply
555 * check whether the module has actually been mapped there
556 * and use it, if so. This is needed to get Win95 USER32.DLL
557 * to work (until we support shared sections properly).
560 if ( nt
->OptionalHeader
.ImageBase
& 0x80000000 )
562 HMODULE sharedMod
= (HMODULE
)nt
->OptionalHeader
.ImageBase
;
563 IMAGE_NT_HEADERS
*sharedNt
= (PIMAGE_NT_HEADERS
)
564 ( (LPBYTE
)sharedMod
+ ((LPBYTE
)nt
- (LPBYTE
)hModule
) );
566 /* Well, this check is not really comprehensive,
567 but should be good enough for now ... */
568 if ( !IsBadReadPtr( (LPBYTE
)sharedMod
, sizeof(IMAGE_DOS_HEADER
) )
569 && memcmp( (LPBYTE
)sharedMod
, (LPBYTE
)hModule
, sizeof(IMAGE_DOS_HEADER
) ) == 0
570 && !IsBadReadPtr( sharedNt
, sizeof(IMAGE_NT_HEADERS
) )
571 && memcmp( sharedNt
, nt
, sizeof(IMAGE_NT_HEADERS
) ) == 0 )
573 UnmapViewOfFile( (LPVOID
)hModule
);
579 /* Allocate memory for module */
580 load_addr
= nt
->OptionalHeader
.ImageBase
;
581 vma_size
= calc_vma_size( hModule
);
583 load_addr
= (DWORD
)VirtualAlloc( (void*)load_addr
, vma_size
,
584 MEM_RESERVE
| MEM_COMMIT
,
585 PAGE_EXECUTE_READWRITE
);
588 /* We need to perform base relocations */
589 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_BASERELOC
;
591 reloc
= dir
->VirtualAddress
;
595 "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
597 (nt
->FileHeader
.Characteristics
&IMAGE_FILE_RELOCS_STRIPPED
)?
598 "stripped during link" : "unknown reason" );
602 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
603 * really make sure that the *new* base address is also > 2GB.
604 * Some DLLs really check the MSB of the module handle :-/
606 if ( nt
->OptionalHeader
.ImageBase
& 0x80000000 )
607 ERR_(win32
)( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
609 load_addr
= (DWORD
)VirtualAlloc( NULL
, vma_size
,
610 MEM_RESERVE
| MEM_COMMIT
,
611 PAGE_EXECUTE_READWRITE
);
614 TRACE_(win32
)("Load addr is %lx (base %lx), range %x\n",
615 load_addr
, nt
->OptionalHeader
.ImageBase
, vma_size
);
616 TRACE_(segment
)("Loading %s at %lx, range %x\n",
617 ofs
->szPathName
, load_addr
, vma_size
);
619 /* Store the NT header at the load addr */
620 *(PIMAGE_DOS_HEADER
)load_addr
= *(PIMAGE_DOS_HEADER
)hModule
;
621 *PE_HEADER( load_addr
) = *nt
;
622 memcpy( PE_SECTIONS(load_addr
), PE_SECTIONS(hModule
),
623 sizeof(IMAGE_SECTION_HEADER
) * nt
->FileHeader
.NumberOfSections
);
625 /* Copies all stuff up to the first section. Including win32 viruses. */
626 memcpy( load_addr
, hModule
, lowest_fa
);
629 /* Copy sections into module image */
630 pe_sec
= PE_SECTIONS( hModule
);
631 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, pe_sec
++)
633 /* memcpy only non-BSS segments */
634 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
635 * but it is not possible for (at least) Linux needs
636 * a page-aligned offset.
638 if(!(pe_sec
->Characteristics
& IMAGE_SCN_CNT_UNINITIALIZED_DATA
))
639 memcpy((char*)RVA(pe_sec
->VirtualAddress
),
640 (char*)(hModule
+ pe_sec
->PointerToRawData
),
641 pe_sec
->SizeOfRawData
);
643 /* not needed, memory is zero */
644 if(strcmp(pe_sec
->Name
, ".bss") == 0)
645 memset((void *)RVA(pe_sec
->VirtualAddress
), 0,
646 pe_sec
->Misc
.VirtualSize
?
647 pe_sec
->Misc
.VirtualSize
:
648 pe_sec
->SizeOfRawData
);
652 /* Perform base relocation, if necessary */
654 do_relocations( load_addr
, (IMAGE_BASE_RELOCATION
*)RVA(reloc
) );
656 /* Get module name */
657 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXPORT
;
659 *modName
= (LPCSTR
)RVA(((PIMAGE_EXPORT_DIRECTORY
)RVA(dir
->VirtualAddress
))->Name
);
661 /* We don't need the orignal mapping any more */
662 UnmapViewOfFile( (LPVOID
)hModule
);
663 return (HMODULE
)load_addr
;
666 UnmapViewOfFile( (LPVOID
)hModule
);
670 /**********************************************************************
673 * Create WINE_MODREF structure for loaded HMODULE32, link it into
674 * process modref_list, and fixup all imports.
676 * Note: hModule must point to a correctly allocated PE image,
677 * with base relocations applied; the 16-bit dummy module
678 * associated to hModule must already exist.
680 * Note: This routine must always be called in the context of the
681 * process that is to own the module to be created.
683 WINE_MODREF
*PE_CreateModule( HMODULE hModule
,
684 OFSTRUCT
*ofs
, DWORD flags
, BOOL builtin
)
686 DWORD load_addr
= (DWORD
)hModule
; /* for RVA */
687 IMAGE_NT_HEADERS
*nt
= PE_HEADER(hModule
);
688 IMAGE_DATA_DIRECTORY
*dir
;
689 IMAGE_IMPORT_DESCRIPTOR
*pe_import
= NULL
;
690 IMAGE_EXPORT_DIRECTORY
*pe_export
= NULL
;
691 IMAGE_RESOURCE_DIRECTORY
*pe_resource
= NULL
;
697 /* Retrieve DataDirectory entries */
699 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXPORT
;
701 pe_export
= (PIMAGE_EXPORT_DIRECTORY
)RVA(dir
->VirtualAddress
);
703 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_IMPORT
;
705 pe_import
= (PIMAGE_IMPORT_DESCRIPTOR
)RVA(dir
->VirtualAddress
);
707 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_RESOURCE
;
709 pe_resource
= (PIMAGE_RESOURCE_DIRECTORY
)RVA(dir
->VirtualAddress
);
711 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_EXCEPTION
;
712 if (dir
->Size
) FIXME_(win32
)("Exception directory ignored\n" );
714 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_SECURITY
;
715 if (dir
->Size
) FIXME_(win32
)("Security directory ignored\n" );
717 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
718 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
720 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_DEBUG
;
721 if (dir
->Size
) TRACE_(win32
)("Debug directory ignored\n" );
723 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_COPYRIGHT
;
724 if (dir
->Size
) FIXME_(win32
)("Copyright string ignored\n" );
726 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_GLOBALPTR
;
727 if (dir
->Size
) FIXME_(win32
)("Global Pointer (MIPS) ignored\n" );
729 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
731 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
;
732 if (dir
->Size
) FIXME_(win32
)("Load Configuration directory ignored\n" );
734 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
;
735 if (dir
->Size
) TRACE_(win32
)("Bound Import directory ignored\n" );
737 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_IAT
;
738 if (dir
->Size
) TRACE_(win32
)("Import Address Table directory ignored\n" );
740 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT
;
743 TRACE_(win32
)("Delayed import, stub calls LoadLibrary\n" );
745 * Nothing to do here.
750 * This code is useful to observe what the heck is going on.
753 ImgDelayDescr
*pe_delay
= NULL
;
754 pe_delay
= (PImgDelayDescr
)RVA(dir
->VirtualAddress
);
755 TRACE_(delayhlp
)("pe_delay->grAttrs = %08x\n", pe_delay
->grAttrs
);
756 TRACE_(delayhlp
)("pe_delay->szName = %s\n", pe_delay
->szName
);
757 TRACE_(delayhlp
)("pe_delay->phmod = %08x\n", pe_delay
->phmod
);
758 TRACE_(delayhlp
)("pe_delay->pIAT = %08x\n", pe_delay
->pIAT
);
759 TRACE_(delayhlp
)("pe_delay->pINT = %08x\n", pe_delay
->pINT
);
760 TRACE_(delayhlp
)("pe_delay->pBoundIAT = %08x\n", pe_delay
->pBoundIAT
);
761 TRACE_(delayhlp
)("pe_delay->pUnloadIAT = %08x\n", pe_delay
->pUnloadIAT
);
762 TRACE_(delayhlp
)("pe_delay->dwTimeStamp = %08x\n", pe_delay
->dwTimeStamp
);
764 #endif /* ImgDelayDescr */
767 dir
= nt
->OptionalHeader
.DataDirectory
+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
;
768 if (dir
->Size
) FIXME_(win32
)("Unknown directory 14 ignored\n" );
770 dir
= nt
->OptionalHeader
.DataDirectory
+15;
771 if (dir
->Size
) FIXME_(win32
)("Unknown directory 15 ignored\n" );
774 /* Allocate and fill WINE_MODREF */
776 wm
= (WINE_MODREF
*)HeapAlloc( GetProcessHeap(),
777 HEAP_ZERO_MEMORY
, sizeof(*wm
) );
778 wm
->module
= hModule
;
781 wm
->flags
|= WINE_MODREF_INTERNAL
;
782 if ( flags
& DONT_RESOLVE_DLL_REFERENCES
)
783 wm
->flags
|= WINE_MODREF_DONT_RESOLVE_REFS
;
784 if ( flags
& LOAD_LIBRARY_AS_DATAFILE
)
785 wm
->flags
|= WINE_MODREF_LOAD_AS_DATAFILE
;
787 wm
->type
= MODULE32_PE
;
788 wm
->binfmt
.pe
.pe_export
= pe_export
;
789 wm
->binfmt
.pe
.pe_import
= pe_import
;
790 wm
->binfmt
.pe
.pe_resource
= pe_resource
;
791 wm
->binfmt
.pe
.tlsindex
= -1;
794 modname
= (char *)RVA( pe_export
->Name
);
797 /* try to find out the name from the OFSTRUCT */
799 modname
= ofs
->szPathName
;
800 if ((s
=strrchr(modname
,'\\'))) modname
= s
+1;
802 wm
->modname
= HEAP_strdupA( GetProcessHeap(), 0, modname
);
804 result
= GetLongPathNameA( ofs
->szPathName
, NULL
, 0 );
805 wm
->longname
= (char *)HeapAlloc( GetProcessHeap(), 0, result
+1 );
806 GetLongPathNameA( ofs
->szPathName
, wm
->longname
, result
+1 );
808 wm
->shortname
= HEAP_strdupA( GetProcessHeap(), 0, ofs
->szPathName
);
810 /* Link MODREF into process list */
812 EnterCriticalSection( &PROCESS_Current()->crit_section
);
814 wm
->next
= PROCESS_Current()->modref_list
;
815 PROCESS_Current()->modref_list
= wm
;
816 if ( wm
->next
) wm
->next
->prev
= wm
;
818 if ( !(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) )
820 if ( PROCESS_Current()->exe_modref
)
821 FIXME_(win32
)("overwriting old exe_modref... arrgh\n" );
822 PROCESS_Current()->exe_modref
= wm
;
825 LeaveCriticalSection( &PROCESS_Current()->crit_section
);
831 dump_exports( hModule
);
835 if ( pe_import
&& fixup_imports( wm
)
836 && !( wm
->flags
& WINE_MODREF_LOAD_AS_DATAFILE
)
837 && !( wm
->flags
& WINE_MODREF_DONT_RESOLVE_REFS
) )
839 /* remove entry from modref chain */
840 EnterCriticalSection( &PROCESS_Current()->crit_section
);
843 PROCESS_Current()->modref_list
= wm
->next
;
845 wm
->prev
->next
= wm
->next
;
847 if ( wm
->next
) wm
->next
->prev
= wm
->prev
;
848 wm
->next
= wm
->prev
= NULL
;
850 LeaveCriticalSection( &PROCESS_Current()->crit_section
);
852 /* FIXME: there are several more dangling references
853 * left. Including dlls loaded by this dll before the
854 * failed one. Unrolling is rather difficult with the
855 * current structure and we can leave it them lying
856 * around with no problems, so we don't care.
857 * As these might reference our wm, we don't free it.
865 /******************************************************************************
866 * The PE Library Loader frontend.
867 * FIXME: handle the flags.
869 WINE_MODREF
*PE_LoadLibraryExA (LPCSTR name
, DWORD flags
, DWORD
*err
)
871 LPCSTR modName
= NULL
;
877 char dllname
[256], *p
;
880 /* Append .DLL to name if no extension present */
881 strcpy( dllname
, name
);
882 if (!(p
= strrchr( dllname
, '.')) || strchr( p
, '/' ) || strchr( p
, '\\'))
883 strcat( dllname
, ".DLL" );
886 hFile
= OpenFile( dllname
, &ofs
, OF_READ
| OF_SHARE_DENY_WRITE
);
887 if ( hFile
!= HFILE_ERROR
)
889 hModule32
= PE_LoadImage( hFile
, &ofs
, &modName
);
890 CloseHandle( hFile
);
893 *err
= ERROR_OUTOFMEMORY
; /* Not entirely right, but good enough */
899 *err
= ERROR_FILE_NOT_FOUND
;
903 /* Create 16-bit dummy module */
904 if ((hModule16
= MODULE_CreateDummyModule( &ofs
, modName
)) < 32)
906 *err
= (DWORD
)hModule16
; /* This should give the correct error */
909 pModule
= (NE_MODULE
*)GlobalLock16( hModule16
);
910 pModule
->flags
= NE_FFLAGS_LIBMODULE
| NE_FFLAGS_SINGLEDATA
| NE_FFLAGS_WIN32
;
911 pModule
->module32
= hModule32
;
913 /* Create 32-bit MODREF */
914 if ( !(wm
= PE_CreateModule( hModule32
, &ofs
, flags
, FALSE
)) )
916 ERR_(win32
)("can't load %s\n",ofs
.szPathName
);
917 FreeLibrary16( hModule16
);
918 *err
= ERROR_OUTOFMEMORY
;
922 if (wm
->binfmt
.pe
.pe_export
)
923 SNOOP_RegisterDLL(wm
->module
,wm
->modname
,wm
->binfmt
.pe
.pe_export
->NumberOfFunctions
);
930 /*****************************************************************************
933 * Unload the library unmapping the image and freeing the modref structure.
935 void PE_UnloadLibrary(WINE_MODREF
*wm
)
937 /* FIXME, do something here */
940 /*****************************************************************************
941 * Load the PE main .EXE. All other loading is done by PE_LoadLibraryExA
942 * FIXME: this function should use PE_LoadLibraryExA, but currently can't
943 * due to the PROCESS_Create stuff.
945 BOOL
PE_CreateProcess( HFILE hFile
, OFSTRUCT
*ofs
, LPCSTR cmd_line
, LPCSTR env
,
946 LPSECURITY_ATTRIBUTES psa
, LPSECURITY_ATTRIBUTES tsa
,
947 BOOL inherit
, DWORD flags
, LPSTARTUPINFOA startup
,
948 LPPROCESS_INFORMATION info
)
950 LPCSTR modName
= NULL
;
956 if ( (hModule32
= PE_LoadImage( hFile
, ofs
, &modName
)) < 32 )
958 SetLastError( hModule32
);
962 if (PE_HEADER(hModule32
)->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
964 SetLastError( 20 ); /* FIXME: not the right error code */
969 /* Create 16-bit dummy module */
970 if ( (hModule16
= MODULE_CreateDummyModule( ofs
, modName
)) < 32 )
972 SetLastError( hModule16
);
975 pModule
= (NE_MODULE
*)GlobalLock16( hModule16
);
976 pModule
->flags
= NE_FFLAGS_WIN32
;
977 pModule
->module32
= hModule32
;
979 /* Create new process */
980 if ( !PROCESS_Create( pModule
, cmd_line
, env
,
981 psa
, tsa
, inherit
, flags
, startup
, info
) )
984 /* Note: PE_CreateModule and the remaining process initialization will
985 be done in the context of the new process, in TASK_CallToStart */
990 /*********************************************************************
991 * PE_UnloadImage [internal]
993 int PE_UnloadImage( HMODULE hModule
)
995 FIXME_(win32
)("stub.\n");
996 /* free resources, image, unmap */
1000 /* Called if the library is loaded or freed.
1001 * NOTE: if a thread attaches a DLL, the current thread will only do
1002 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
1005 BOOL
PE_InitDLL( WINE_MODREF
*wm
, DWORD type
, LPVOID lpReserved
)
1008 assert( wm
->type
== MODULE32_PE
);
1010 /* Is this a library? And has it got an entrypoint? */
1011 if ((PE_HEADER(wm
->module
)->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1012 (PE_HEADER(wm
->module
)->OptionalHeader
.AddressOfEntryPoint
)
1014 DLLENTRYPROC entry
= (void*)RVA_PTR( wm
->module
,OptionalHeader
.AddressOfEntryPoint
);
1015 TRACE_(relay
)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
1016 entry
, wm
->module
, type
, lpReserved
);
1018 retv
= entry( wm
->module
, type
, lpReserved
);
1024 /************************************************************************
1025 * PE_InitTls (internal)
1027 * If included, initialises the thread local storages of modules.
1028 * Pointers in those structs are not RVAs but real pointers which have been
1029 * relocated by do_relocations() already.
1031 void PE_InitTls( void )
1035 IMAGE_NT_HEADERS
*peh
;
1036 DWORD size
,datasize
;
1038 PIMAGE_TLS_DIRECTORY pdir
;
1041 for (wm
= PROCESS_Current()->modref_list
;wm
;wm
=wm
->next
) {
1042 if (wm
->type
!=MODULE32_PE
)
1044 pem
= &(wm
->binfmt
.pe
);
1045 peh
= PE_HEADER(wm
->module
);
1046 delta
= wm
->module
- peh
->OptionalHeader
.ImageBase
;
1047 if (!peh
->OptionalHeader
.DataDirectory
[IMAGE_FILE_THREAD_LOCAL_STORAGE
].VirtualAddress
)
1049 pdir
= (LPVOID
)(wm
->module
+ peh
->OptionalHeader
.
1050 DataDirectory
[IMAGE_FILE_THREAD_LOCAL_STORAGE
].VirtualAddress
);
1053 if ( pem
->tlsindex
== -1 ) {
1054 pem
->tlsindex
= TlsAlloc();
1055 *pdir
->AddressOfIndex
=pem
->tlsindex
;
1057 datasize
= pdir
->EndAddressOfRawData
-pdir
->StartAddressOfRawData
;
1058 size
= datasize
+ pdir
->SizeOfZeroFill
;
1059 mem
=VirtualAlloc(0,size
,MEM_RESERVE
|MEM_COMMIT
,PAGE_READWRITE
);
1060 memcpy(mem
,(LPVOID
)pdir
->StartAddressOfRawData
,datasize
);
1061 if (pdir
->AddressOfCallBacks
) {
1062 PIMAGE_TLS_CALLBACK
*cbs
=
1063 (PIMAGE_TLS_CALLBACK
*)pdir
->AddressOfCallBacks
;
1066 FIXME_(win32
)("TLS Callbacks aren't going to be called\n");
1069 TlsSetValue( pem
->tlsindex
, mem
);