Added missing (and now required) filename directive.
[wine.git] / loader / pe_image.c
blobac17fc70472525350c3f60c460806eb2bda2a629
1 /*
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
9 * make that:
10 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
12 /* Notes:
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
23 * NE_MODULE.module32.
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).
36 #include <errno.h>
37 #include <assert.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #ifdef HAVE_SYS_MMAN_H
44 #include <sys/mman.h>
45 #endif
46 #include "windef.h"
47 #include "winbase.h"
48 #include "winerror.h"
49 #include "callback.h"
50 #include "file.h"
51 #include "heap.h"
52 #include "neexe.h"
53 #include "peexe.h"
54 #include "process.h"
55 #include "thread.h"
56 #include "pe_image.h"
57 #include "module.h"
58 #include "global.h"
59 #include "task.h"
60 #include "snoop.h"
61 #include "debugtools.h"
63 DECLARE_DEBUG_CHANNEL(delayhlp)
64 DECLARE_DEBUG_CHANNEL(fixup)
65 DECLARE_DEBUG_CHANNEL(module)
66 DECLARE_DEBUG_CHANNEL(relay)
67 DECLARE_DEBUG_CHANNEL(segment)
68 DECLARE_DEBUG_CHANNEL(win32)
71 /* convert PE image VirtualAddress to Real Address */
72 #define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
74 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
76 void dump_exports( HMODULE hModule )
78 char *Module;
79 int i, j;
80 u_short *ordinal;
81 u_long *function,*functions;
82 u_char **name;
83 unsigned int load_addr = hModule;
85 DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
86 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
87 DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
88 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
89 IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
91 Module = (char*)RVA(pe_exports->Name);
92 TRACE_(win32)("*******EXPORT DATA*******\n");
93 TRACE_(win32)("Module name is %s, %ld functions, %ld names\n",
94 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
96 ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
97 functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
98 name=(u_char**) RVA(pe_exports->AddressOfNames);
100 TRACE_(win32)(" Ord RVA Addr Name\n" );
101 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
103 if (!*function) continue; /* No such function */
104 if (TRACE_ON(win32))
106 DPRINTF( "%4ld %08lx %08x", 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++)
109 if (ordinal[j] == i)
111 DPRINTF( " %s", (char*)RVA(name[j]) );
112 break;
114 if ((*function >= rva_start) && (*function <= rva_end))
115 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
116 DPRINTF("\n");
121 /* Look up the specified function or ordinal in the exportlist:
122 * If it is a string:
123 * - look up the name in the Name list.
124 * - look up the ordinal with that index.
125 * - use the ordinal as offset into the functionlist
126 * If it is a ordinal:
127 * - use ordinal-pe_export->Base as offset into the functionlist
129 FARPROC PE_FindExportedFunction(
130 WINE_MODREF *wm, /* [in] WINE modreference */
131 LPCSTR funcName, /* [in] function name */
132 BOOL snoop )
134 u_short * ordinal;
135 u_long * function;
136 u_char ** name, *ename;
137 int i;
138 PE_MODREF *pem = &(wm->binfmt.pe);
139 IMAGE_EXPORT_DIRECTORY *exports = pem->pe_export;
140 unsigned int load_addr = wm->module;
141 u_long rva_start, rva_end, addr;
142 char * forward;
144 if (HIWORD(funcName))
145 TRACE_(win32)("(%s)\n",funcName);
146 else
147 TRACE_(win32)("(%d)\n",(int)funcName);
148 if (!exports) {
149 /* Not a fatal problem, some apps do
150 * GetProcAddress(0,"RegisterPenApp") which triggers this
151 * case.
153 WARN_(win32)("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,pem);
154 return NULL;
156 ordinal = (u_short*) RVA(exports->AddressOfNameOrdinals);
157 function= (u_long*) RVA(exports->AddressOfFunctions);
158 name = (u_char **) RVA(exports->AddressOfNames);
159 forward = NULL;
160 rva_start = PE_HEADER(wm->module)->OptionalHeader
161 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
162 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
163 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
165 if (HIWORD(funcName)) {
166 for(i=0; i<exports->NumberOfNames; i++) {
167 ename=(char*)RVA(*name);
168 if(!strcmp(ename,funcName))
170 addr = function[*ordinal];
171 if (!addr) return NULL;
172 if ((addr < rva_start) || (addr >= rva_end))
173 return snoop? SNOOP_GetProcAddress(wm->module,ename,*ordinal,(FARPROC)RVA(addr))
174 : (FARPROC)RVA(addr);
175 forward = (char *)RVA(addr);
176 break;
178 ordinal++;
179 name++;
181 } else {
182 int i;
183 if (LOWORD(funcName)-exports->Base > exports->NumberOfFunctions) {
184 TRACE_(win32)(" ordinal %d out of range!\n",
185 LOWORD(funcName));
186 return NULL;
188 addr = function[(int)funcName-exports->Base];
189 if (!addr) return NULL;
190 ename = "";
191 if (name) {
192 for (i=0;i<exports->NumberOfNames;i++) {
193 ename = (char*)RVA(*name);
194 if (*ordinal == LOWORD(funcName)-exports->Base)
195 break;
196 ordinal++;
197 name++;
199 if (i==exports->NumberOfNames)
200 ename = "";
202 if ((addr < rva_start) || (addr >= rva_end))
203 return snoop? SNOOP_GetProcAddress(wm->module,ename,(DWORD)funcName-exports->Base,(FARPROC)RVA(addr))
204 : (FARPROC)RVA(addr);
205 forward = (char *)RVA(addr);
207 if (forward)
209 WINE_MODREF *wm;
210 char module[256];
211 char *end = strchr(forward, '.');
213 if (!end) return NULL;
214 assert(end-forward<256);
215 strncpy(module, forward, (end - forward));
216 module[end-forward] = 0;
217 if (!(wm = MODULE_FindModule( module )))
219 ERR_(win32)("module not found for forward '%s'\n", forward );
220 return NULL;
222 return MODULE_GetProcAddress( wm->module, end + 1, snoop );
224 return NULL;
227 DWORD fixup_imports( WINE_MODREF *wm )
229 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
230 PE_MODREF *pem;
231 unsigned int load_addr = wm->module;
232 int i,characteristics_detection=1;
233 char *modname;
235 assert(wm->type==MODULE32_PE);
236 pem = &(wm->binfmt.pe);
237 if (pem->pe_export)
238 modname = (char*) RVA(pem->pe_export->Name);
239 else
240 modname = "<unknown>";
242 /* OK, now dump the import list */
243 TRACE_(win32)("Dumping imports list\n");
245 /* first, count the number of imported non-internal modules */
246 pe_imp = pem->pe_import;
247 if (!pe_imp) return 0;
249 /* We assume that we have at least one import with !0 characteristics and
250 * detect broken imports with all characteristsics 0 (notably Borland) and
251 * switch the detection off for them.
253 for (i = 0; pe_imp->Name ; pe_imp++) {
254 if (!i && !pe_imp->u.Characteristics)
255 characteristics_detection = 0;
256 if (characteristics_detection && !pe_imp->u.Characteristics)
257 break;
258 i++;
260 if (!i) return 0; /* no imports */
262 /* Allocate module dependency list */
263 wm->nDeps = i;
264 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
266 /* load the imported modules. They are automatically
267 * added to the modref list of the process.
270 for (i = 0, pe_imp = pem->pe_import; pe_imp->Name ; pe_imp++) {
271 WINE_MODREF *wmImp;
272 IMAGE_IMPORT_BY_NAME *pe_name;
273 PIMAGE_THUNK_DATA import_list,thunk_list;
274 char *name = (char *) RVA(pe_imp->Name);
276 if (characteristics_detection && !pe_imp->u.Characteristics)
277 break;
279 /* don't use MODULE_Load, Win32 creates new task differently */
280 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
281 if (!wmImp) {
282 char *p,buffer[2000];
284 /* GetModuleFileName would use the wrong process, so don't use it */
285 strcpy(buffer,wm->shortname);
286 if (!(p = strrchr (buffer, '\\')))
287 p = buffer;
288 strcpy (p + 1, name);
289 wmImp = MODULE_LoadLibraryExA( buffer, 0, 0 );
291 if (!wmImp) {
292 ERR_(module)("Module %s not found\n", name);
293 return 1;
295 wm->deps[i++] = wmImp;
297 /* FIXME: forwarder entries ... */
299 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
300 TRACE_(win32)("Microsoft style imports used\n");
301 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
302 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
304 while (import_list->u1.Ordinal) {
305 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
306 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
308 TRACE_(win32)("--- Ordinal %s,%d\n", name, ordinal);
309 thunk_list->u1.Function=MODULE_GetProcAddress(
310 wmImp->module, (LPCSTR)ordinal, TRUE
312 if (!thunk_list->u1.Function) {
313 ERR_(win32)("No implementation for %s.%d, setting to 0xdeadbeef\n",
314 name, ordinal);
315 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
317 } else { /* import by name */
318 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
319 TRACE_(win32)("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
320 thunk_list->u1.Function=MODULE_GetProcAddress(
321 wmImp->module, pe_name->Name, TRUE
323 if (!thunk_list->u1.Function) {
324 ERR_(win32)("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
325 name,pe_name->Hint,pe_name->Name);
326 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
329 import_list++;
330 thunk_list++;
332 } else { /* Borland style */
333 TRACE_(win32)("Borland style imports used\n");
334 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
335 while (thunk_list->u1.Ordinal) {
336 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
337 /* not sure about this branch, but it seems to work */
338 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
340 TRACE_(win32)("--- Ordinal %s.%d\n",name,ordinal);
341 thunk_list->u1.Function=MODULE_GetProcAddress(
342 wmImp->module, (LPCSTR) ordinal, TRUE
344 if (!thunk_list->u1.Function) {
345 ERR_(win32)("No implementation for %s.%d, setting to 0xdeadbeef\n",
346 name,ordinal);
347 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
349 } else {
350 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
351 TRACE_(win32)("--- %s %s.%d\n",
352 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_(win32)("No implementation for %s.%d, setting to 0xdeadbeef\n",
358 name, pe_name->Hint);
359 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
362 thunk_list++;
366 return 0;
369 static int calc_vma_size( HMODULE hModule )
371 int i,vma_size = 0;
372 IMAGE_SECTION_HEADER *pe_seg = PE_SECTIONS(hModule);
374 TRACE_(win32)("Dump of segment table\n");
375 TRACE_(win32)(" Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
376 for (i = 0; i< PE_HEADER(hModule)->FileHeader.NumberOfSections; i++)
378 TRACE_(win32)("%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
379 pe_seg->Name,
380 pe_seg->Misc.VirtualSize,
381 pe_seg->VirtualAddress,
382 pe_seg->SizeOfRawData,
383 pe_seg->PointerToRawData,
384 pe_seg->PointerToRelocations,
385 pe_seg->PointerToLinenumbers,
386 pe_seg->NumberOfRelocations,
387 pe_seg->NumberOfLinenumbers,
388 pe_seg->Characteristics);
389 vma_size=MAX(vma_size, pe_seg->VirtualAddress+pe_seg->SizeOfRawData);
390 vma_size=MAX(vma_size, pe_seg->VirtualAddress+pe_seg->Misc.VirtualSize);
391 pe_seg++;
393 return vma_size;
396 static void do_relocations( unsigned int load_addr, IMAGE_BASE_RELOCATION *r )
398 int delta = load_addr - PE_HEADER(load_addr)->OptionalHeader.ImageBase;
399 int hdelta = (delta >> 16) & 0xFFFF;
400 int ldelta = delta & 0xFFFF;
402 if(delta == 0)
403 /* Nothing to do */
404 return;
405 while(r->VirtualAddress)
407 char *page = (char*) RVA(r->VirtualAddress);
408 int count = (r->SizeOfBlock - 8)/2;
409 int i;
410 TRACE_(fixup)("%x relocations for page %lx\n",
411 count, r->VirtualAddress);
412 /* patching in reverse order */
413 for(i=0;i<count;i++)
415 int offset = r->TypeOffset[i] & 0xFFF;
416 int type = r->TypeOffset[i] >> 12;
417 TRACE_(fixup)("patching %x type %x\n", offset, type);
418 switch(type)
420 case IMAGE_REL_BASED_ABSOLUTE: break;
421 case IMAGE_REL_BASED_HIGH:
422 *(short*)(page+offset) += hdelta;
423 break;
424 case IMAGE_REL_BASED_LOW:
425 *(short*)(page+offset) += ldelta;
426 break;
427 case IMAGE_REL_BASED_HIGHLOW:
428 *(int*)(page+offset) += delta;
429 /* FIXME: if this is an exported address, fire up enhanced logic */
430 break;
431 case IMAGE_REL_BASED_HIGHADJ:
432 FIXME_(win32)("Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
433 break;
434 case IMAGE_REL_BASED_MIPS_JMPADDR:
435 FIXME_(win32)("Is this a MIPS machine ???\n");
436 break;
437 default:
438 FIXME_(win32)("Unknown fixup type\n");
439 break;
442 r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
450 /**********************************************************************
451 * PE_LoadImage
452 * Load one PE format DLL/EXE into memory
454 * Unluckily we can't just mmap the sections where we want them, for
455 * (at least) Linux does only support offsets which are page-aligned.
457 * BUT we have to map the whole image anyway, for Win32 programs sometimes
458 * want to access them. (HMODULE32 point to the start of it)
460 HMODULE PE_LoadImage( HFILE hFile, OFSTRUCT *ofs, LPCSTR *modName )
462 HMODULE hModule;
463 HANDLE mapping;
465 IMAGE_NT_HEADERS *nt;
466 IMAGE_SECTION_HEADER *pe_sec;
467 IMAGE_DATA_DIRECTORY *dir;
468 BY_HANDLE_FILE_INFORMATION bhfi;
469 int i, rawsize, lowest_va, lowest_fa, vma_size, file_size = 0;
470 DWORD load_addr, aoep, reloc = 0;
472 /* Retrieve file size */
473 if ( GetFileInformationByHandle( hFile, &bhfi ) )
474 file_size = bhfi.nFileSizeLow; /* FIXME: 64 bit */
476 /* Map the PE file somewhere */
477 mapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY | SEC_COMMIT,
478 0, 0, NULL );
479 if (!mapping)
481 WARN_(win32)("CreateFileMapping error %ld\n", GetLastError() );
482 return 0;
484 hModule = (HMODULE)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
485 CloseHandle( mapping );
486 if (!hModule)
488 WARN_(win32)("MapViewOfFile error %ld\n", GetLastError() );
489 return 0;
491 nt = PE_HEADER( hModule );
493 /* Check signature */
494 if ( nt->Signature != IMAGE_NT_SIGNATURE )
496 WARN_(win32)("image doesn't have PE signature, but 0x%08lx\n",
497 nt->Signature );
498 goto error;
501 /* Check architecture */
502 if ( nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386 )
504 MESSAGE("Trying to load PE image for unsupported architecture (");
505 switch (nt->FileHeader.Machine)
507 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
508 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
509 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
510 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
511 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
512 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
513 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
514 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
516 MESSAGE(")\n");
517 goto error;
520 /* Find out how large this executeable should be */
521 pe_sec = PE_SECTIONS( hModule );
522 rawsize = 0; lowest_va = 0x10000; lowest_fa = 0x10000;
523 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
525 if (lowest_va > pe_sec[i].VirtualAddress)
526 lowest_va = pe_sec[i].VirtualAddress;
527 if (pe_sec[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
528 continue;
529 if (pe_sec[i].PointerToRawData < lowest_fa)
530 lowest_fa = pe_sec[i].PointerToRawData;
531 if (pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData > rawsize)
532 rawsize = pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData;
535 /* Check file size */
536 if ( file_size && file_size < rawsize )
538 ERR_(win32)("PE module is too small (header: %d, filesize: %d), "
539 "probably truncated download?\n",
540 rawsize, file_size );
541 goto error;
544 /* Check entrypoint address */
545 aoep = nt->OptionalHeader.AddressOfEntryPoint;
546 if (aoep && (aoep < lowest_va))
547 FIXME_(win32)("WARNING: '%s' has an invalid entrypoint (0x%08lx) "
548 "below the first virtual address (0x%08x) "
549 "(possible Virus Infection or broken binary)!\n",
550 ofs->szPathName, aoep, lowest_va );
553 /* FIXME: Hack! While we don't really support shared sections yet,
554 * this checks for those special cases where the whole DLL
555 * consists only of shared sections and is mapped into the
556 * shared address space > 2GB. In this case, we assume that
557 * the module got mapped at its base address. Thus we simply
558 * check whether the module has actually been mapped there
559 * and use it, if so. This is needed to get Win95 USER32.DLL
560 * to work (until we support shared sections properly).
563 if ( nt->OptionalHeader.ImageBase & 0x80000000 )
565 HMODULE sharedMod = (HMODULE)nt->OptionalHeader.ImageBase;
566 IMAGE_NT_HEADERS *sharedNt = (PIMAGE_NT_HEADERS)
567 ( (LPBYTE)sharedMod + ((LPBYTE)nt - (LPBYTE)hModule) );
569 /* Well, this check is not really comprehensive,
570 but should be good enough for now ... */
571 if ( !IsBadReadPtr( (LPBYTE)sharedMod, sizeof(IMAGE_DOS_HEADER) )
572 && memcmp( (LPBYTE)sharedMod, (LPBYTE)hModule, sizeof(IMAGE_DOS_HEADER) ) == 0
573 && !IsBadReadPtr( sharedNt, sizeof(IMAGE_NT_HEADERS) )
574 && memcmp( sharedNt, nt, sizeof(IMAGE_NT_HEADERS) ) == 0 )
576 UnmapViewOfFile( (LPVOID)hModule );
577 return sharedMod;
582 /* Allocate memory for module */
583 load_addr = nt->OptionalHeader.ImageBase;
584 vma_size = calc_vma_size( hModule );
586 load_addr = (DWORD)VirtualAlloc( (void*)load_addr, vma_size,
587 MEM_RESERVE | MEM_COMMIT,
588 PAGE_EXECUTE_READWRITE );
589 if (load_addr == 0)
591 /* We need to perform base relocations */
592 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BASERELOC;
593 if (dir->Size)
594 reloc = dir->VirtualAddress;
595 else
597 FIXME_(win32)(
598 "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
599 ofs->szPathName,
600 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
601 "stripped during link" : "unknown reason" );
602 goto error;
605 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
606 * really make sure that the *new* base address is also > 2GB.
607 * Some DLLs really check the MSB of the module handle :-/
609 if ( nt->OptionalHeader.ImageBase & 0x80000000 )
610 ERR_(win32)( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
612 load_addr = (DWORD)VirtualAlloc( NULL, vma_size,
613 MEM_RESERVE | MEM_COMMIT,
614 PAGE_EXECUTE_READWRITE );
617 TRACE_(win32)("Load addr is %lx (base %lx), range %x\n",
618 load_addr, nt->OptionalHeader.ImageBase, vma_size );
619 TRACE_(segment)("Loading %s at %lx, range %x\n",
620 ofs->szPathName, load_addr, vma_size );
622 /* Store the NT header at the load addr */
623 *(PIMAGE_DOS_HEADER)load_addr = *(PIMAGE_DOS_HEADER)hModule;
624 *PE_HEADER( load_addr ) = *nt;
625 memcpy( PE_SECTIONS(load_addr), PE_SECTIONS(hModule),
626 sizeof(IMAGE_SECTION_HEADER) * nt->FileHeader.NumberOfSections );
627 #if 0
628 /* Copies all stuff up to the first section. Including win32 viruses. */
629 memcpy( load_addr, hModule, lowest_fa );
630 #endif
632 /* Copy sections into module image */
633 pe_sec = PE_SECTIONS( hModule );
634 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, pe_sec++)
636 /* memcpy only non-BSS segments */
637 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
638 * but it is not possible for (at least) Linux needs
639 * a page-aligned offset.
641 if(!(pe_sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
642 memcpy((char*)RVA(pe_sec->VirtualAddress),
643 (char*)(hModule + pe_sec->PointerToRawData),
644 pe_sec->SizeOfRawData);
645 #if 0
646 /* not needed, memory is zero */
647 if(strcmp(pe_sec->Name, ".bss") == 0)
648 memset((void *)RVA(pe_sec->VirtualAddress), 0,
649 pe_sec->Misc.VirtualSize ?
650 pe_sec->Misc.VirtualSize :
651 pe_sec->SizeOfRawData);
652 #endif
655 /* Perform base relocation, if necessary */
656 if ( reloc )
657 do_relocations( load_addr, (IMAGE_BASE_RELOCATION *)RVA(reloc) );
659 /* Get module name */
660 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
661 if (dir->Size)
662 *modName = (LPCSTR)RVA(((PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress))->Name);
664 /* We don't need the orignal mapping any more */
665 UnmapViewOfFile( (LPVOID)hModule );
666 return (HMODULE)load_addr;
668 error:
669 UnmapViewOfFile( (LPVOID)hModule );
670 return 0;
673 /**********************************************************************
674 * PE_CreateModule
676 * Create WINE_MODREF structure for loaded HMODULE32, link it into
677 * process modref_list, and fixup all imports.
679 * Note: hModule must point to a correctly allocated PE image,
680 * with base relocations applied; the 16-bit dummy module
681 * associated to hModule must already exist.
683 * Note: This routine must always be called in the context of the
684 * process that is to own the module to be created.
686 WINE_MODREF *PE_CreateModule( HMODULE hModule,
687 OFSTRUCT *ofs, DWORD flags, BOOL builtin )
689 DWORD load_addr = (DWORD)hModule; /* for RVA */
690 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
691 IMAGE_DATA_DIRECTORY *dir;
692 IMAGE_IMPORT_DESCRIPTOR *pe_import = NULL;
693 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
694 IMAGE_RESOURCE_DIRECTORY *pe_resource = NULL;
695 WINE_MODREF *wm;
696 int result;
697 char *modname;
700 /* Retrieve DataDirectory entries */
702 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
703 if (dir->Size)
704 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
706 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IMPORT;
707 if (dir->Size)
708 pe_import = (PIMAGE_IMPORT_DESCRIPTOR)RVA(dir->VirtualAddress);
710 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_RESOURCE;
711 if (dir->Size)
712 pe_resource = (PIMAGE_RESOURCE_DIRECTORY)RVA(dir->VirtualAddress);
714 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
715 if (dir->Size) FIXME_(win32)("Exception directory ignored\n" );
717 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
718 if (dir->Size) FIXME_(win32)("Security directory ignored\n" );
720 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
721 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
723 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DEBUG;
724 if (dir->Size) TRACE_(win32)("Debug directory ignored\n" );
726 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COPYRIGHT;
727 if (dir->Size) FIXME_(win32)("Copyright string ignored\n" );
729 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
730 if (dir->Size) FIXME_(win32)("Global Pointer (MIPS) ignored\n" );
732 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
734 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
735 if (dir->Size) FIXME_(win32)("Load Configuration directory ignored\n" );
737 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
738 if (dir->Size) TRACE_(win32)("Bound Import directory ignored\n" );
740 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
741 if (dir->Size) TRACE_(win32)("Import Address Table directory ignored\n" );
743 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
744 if (dir->Size)
746 TRACE_(win32)("Delayed import, stub calls LoadLibrary\n" );
748 * Nothing to do here.
751 #ifdef ImgDelayDescr
753 * This code is useful to observe what the heck is going on.
756 ImgDelayDescr *pe_delay = NULL;
757 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
758 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
759 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
760 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
761 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
762 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
763 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
764 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
765 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
767 #endif /* ImgDelayDescr */
770 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
771 if (dir->Size) FIXME_(win32)("Unknown directory 14 ignored\n" );
773 dir = nt->OptionalHeader.DataDirectory+15;
774 if (dir->Size) FIXME_(win32)("Unknown directory 15 ignored\n" );
777 /* Allocate and fill WINE_MODREF */
779 wm = (WINE_MODREF *)HeapAlloc( GetProcessHeap(),
780 HEAP_ZERO_MEMORY, sizeof(*wm) );
781 wm->module = hModule;
783 if ( builtin )
784 wm->flags |= WINE_MODREF_INTERNAL;
785 if ( flags & DONT_RESOLVE_DLL_REFERENCES )
786 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
787 if ( flags & LOAD_LIBRARY_AS_DATAFILE )
788 wm->flags |= WINE_MODREF_LOAD_AS_DATAFILE;
790 wm->type = MODULE32_PE;
791 wm->binfmt.pe.pe_export = pe_export;
792 wm->binfmt.pe.pe_import = pe_import;
793 wm->binfmt.pe.pe_resource = pe_resource;
794 wm->binfmt.pe.tlsindex = -1;
796 if ( pe_export )
797 modname = (char *)RVA( pe_export->Name );
798 else
800 /* try to find out the name from the OFSTRUCT */
801 char *s;
802 modname = ofs->szPathName;
803 if ((s=strrchr(modname,'\\'))) modname = s+1;
805 wm->modname = HEAP_strdupA( GetProcessHeap(), 0, modname );
807 result = GetLongPathNameA( ofs->szPathName, NULL, 0 );
808 wm->longname = (char *)HeapAlloc( GetProcessHeap(), 0, result+1 );
809 GetLongPathNameA( ofs->szPathName, wm->longname, result+1 );
811 wm->shortname = HEAP_strdupA( GetProcessHeap(), 0, ofs->szPathName );
813 /* Link MODREF into process list */
815 EnterCriticalSection( &PROCESS_Current()->crit_section );
817 wm->next = PROCESS_Current()->modref_list;
818 PROCESS_Current()->modref_list = wm;
819 if ( wm->next ) wm->next->prev = wm;
821 if ( !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) )
823 if ( PROCESS_Current()->exe_modref )
824 FIXME_(win32)("overwriting old exe_modref... arrgh\n" );
825 PROCESS_Current()->exe_modref = wm;
828 LeaveCriticalSection( &PROCESS_Current()->crit_section );
831 /* Dump Exports */
833 if ( pe_export )
834 dump_exports( hModule );
836 /* Fixup Imports */
838 if ( pe_import
839 && !( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE )
840 && !( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
841 && fixup_imports( wm ) )
843 /* remove entry from modref chain */
844 EnterCriticalSection( &PROCESS_Current()->crit_section );
846 if ( !wm->prev )
847 PROCESS_Current()->modref_list = wm->next;
848 else
849 wm->prev->next = wm->next;
851 if ( wm->next ) wm->next->prev = wm->prev;
852 wm->next = wm->prev = NULL;
854 LeaveCriticalSection( &PROCESS_Current()->crit_section );
856 /* FIXME: there are several more dangling references
857 * left. Including dlls loaded by this dll before the
858 * failed one. Unrolling is rather difficult with the
859 * current structure and we can leave it them lying
860 * around with no problems, so we don't care.
861 * As these might reference our wm, we don't free it.
863 return NULL;
866 return wm;
869 /******************************************************************************
870 * The PE Library Loader frontend.
871 * FIXME: handle the flags.
873 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags, DWORD *err)
875 LPCSTR modName = NULL;
876 OFSTRUCT ofs;
877 HMODULE hModule32;
878 HMODULE16 hModule16;
879 NE_MODULE *pModule;
880 WINE_MODREF *wm;
881 char dllname[256], *p;
882 HFILE hFile;
884 /* Append .DLL to name if no extension present */
885 strcpy( dllname, name );
886 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
887 strcat( dllname, ".DLL" );
889 /* Load PE module */
890 hFile = OpenFile( dllname, &ofs, OF_READ | OF_SHARE_DENY_WRITE );
891 if ( hFile != HFILE_ERROR )
893 hModule32 = PE_LoadImage( hFile, &ofs, &modName );
894 CloseHandle( hFile );
895 if(!hModule32)
897 *err = ERROR_OUTOFMEMORY; /* Not entirely right, but good enough */
898 return NULL;
901 else
903 *err = ERROR_FILE_NOT_FOUND;
904 return NULL;
907 /* Create 16-bit dummy module */
908 if ((hModule16 = MODULE_CreateDummyModule( &ofs, modName )) < 32)
910 *err = (DWORD)hModule16; /* This should give the correct error */
911 return NULL;
913 pModule = (NE_MODULE *)GlobalLock16( hModule16 );
914 pModule->flags = NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA | NE_FFLAGS_WIN32;
915 pModule->module32 = hModule32;
917 /* Create 32-bit MODREF */
918 if ( !(wm = PE_CreateModule( hModule32, &ofs, flags, FALSE )) )
920 ERR_(win32)("can't load %s\n",ofs.szPathName);
921 FreeLibrary16( hModule16 );
922 *err = ERROR_OUTOFMEMORY;
923 return NULL;
926 if (wm->binfmt.pe.pe_export)
927 SNOOP_RegisterDLL(wm->module,wm->modname,wm->binfmt.pe.pe_export->NumberOfFunctions);
929 *err = 0;
930 return wm;
934 /*****************************************************************************
935 * PE_UnloadLibrary
937 * Unload the library unmapping the image and freeing the modref structure.
939 void PE_UnloadLibrary(WINE_MODREF *wm)
941 /* FIXME, do something here */
944 /*****************************************************************************
945 * Load the PE main .EXE. All other loading is done by PE_LoadLibraryExA
946 * FIXME: this function should use PE_LoadLibraryExA, but currently can't
947 * due to the PROCESS_Create stuff.
949 BOOL PE_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmd_line, LPCSTR env,
950 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
951 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
952 LPPROCESS_INFORMATION info )
954 LPCSTR modName = NULL;
955 HMODULE16 hModule16;
956 HMODULE hModule32;
957 NE_MODULE *pModule;
959 /* Load file */
960 if ( (hModule32 = PE_LoadImage( hFile, ofs, &modName )) < 32 )
962 SetLastError( hModule32 );
963 return FALSE;
965 #if 0
966 if (PE_HEADER(hModule32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
968 SetLastError( 20 ); /* FIXME: not the right error code */
969 return FALSE;
971 #endif
973 /* Create 16-bit dummy module */
974 if ( (hModule16 = MODULE_CreateDummyModule( ofs, modName )) < 32 )
976 SetLastError( hModule16 );
977 return FALSE;
979 pModule = (NE_MODULE *)GlobalLock16( hModule16 );
980 pModule->flags = NE_FFLAGS_WIN32;
981 pModule->module32 = hModule32;
983 /* Create new process */
984 if ( !PROCESS_Create( pModule, cmd_line, env,
985 psa, tsa, inherit, flags, startup, info ) )
986 return FALSE;
988 /* Note: PE_CreateModule and the remaining process initialization will
989 be done in the context of the new process, in TASK_CallToStart */
991 return TRUE;
994 /*********************************************************************
995 * PE_UnloadImage [internal]
997 int PE_UnloadImage( HMODULE hModule )
999 FIXME_(win32)("stub.\n");
1000 /* free resources, image, unmap */
1001 return 1;
1004 /* Called if the library is loaded or freed.
1005 * NOTE: if a thread attaches a DLL, the current thread will only do
1006 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
1007 * (SDK)
1009 BOOL PE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
1011 BOOL retv = TRUE;
1012 assert( wm->type == MODULE32_PE );
1014 /* Is this a library? And has it got an entrypoint? */
1015 if ((PE_HEADER(wm->module)->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1016 (PE_HEADER(wm->module)->OptionalHeader.AddressOfEntryPoint)
1018 DLLENTRYPROC entry = (void*)RVA_PTR( wm->module,OptionalHeader.AddressOfEntryPoint );
1019 TRACE_(relay)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
1020 entry, wm->module, type, lpReserved );
1022 retv = entry( wm->module, type, lpReserved );
1025 return retv;
1028 /************************************************************************
1029 * PE_InitTls (internal)
1031 * If included, initialises the thread local storages of modules.
1032 * Pointers in those structs are not RVAs but real pointers which have been
1033 * relocated by do_relocations() already.
1035 void PE_InitTls( void )
1037 WINE_MODREF *wm;
1038 PE_MODREF *pem;
1039 IMAGE_NT_HEADERS *peh;
1040 DWORD size,datasize;
1041 LPVOID mem;
1042 PIMAGE_TLS_DIRECTORY pdir;
1043 int delta;
1045 for (wm = PROCESS_Current()->modref_list;wm;wm=wm->next) {
1046 if (wm->type!=MODULE32_PE)
1047 continue;
1048 pem = &(wm->binfmt.pe);
1049 peh = PE_HEADER(wm->module);
1050 delta = wm->module - peh->OptionalHeader.ImageBase;
1051 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
1052 continue;
1053 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
1054 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
1057 if ( pem->tlsindex == -1 ) {
1058 pem->tlsindex = TlsAlloc();
1059 if ((((DWORD)pdir->AddressOfIndex)>peh->OptionalHeader.ImageBase)
1060 &&(((DWORD)pdir->AddressOfIndex)<peh->OptionalHeader.ImageBase+peh->OptionalHeader.SizeOfImage)
1062 *pdir->AddressOfIndex=pem->tlsindex;
1063 else
1064 *(LPDWORD)((((char*)pdir->AddressOfIndex)+delta))=pem->tlsindex;
1066 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
1067 size = datasize + pdir->SizeOfZeroFill;
1068 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
1069 memcpy(mem,(LPVOID)pdir->StartAddressOfRawData,datasize);
1070 if (pdir->AddressOfCallBacks) {
1071 PIMAGE_TLS_CALLBACK *cbs =
1072 (PIMAGE_TLS_CALLBACK *)pdir->AddressOfCallBacks;
1074 if (*cbs)
1075 FIXME_(win32)("TLS Callbacks aren't going to be called\n");
1078 TlsSetValue( pem->tlsindex, mem );