Made async fds nonblocking.
[wine.git] / loader / pe_image.c
blob72aa4e0130e0cb9228fe4bdec6ce4375621e6e0f
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)){
105 dbg_decl_str(win32, 1024);
107 dsprintf(win32,"%4ld %08lx %08x",
108 i + pe_exports->Base, *function, RVA(*function) );
109 /* Check if we have a name for it */
110 for (j = 0; j < pe_exports->NumberOfNames; j++)
111 if (ordinal[j] == i)
112 dsprintf(win32, " %s", (char*)RVA(name[j]) );
113 if ((*function >= rva_start) && (*function <= rva_end))
114 dsprintf(win32, " (forwarded -> %s)", (char *)RVA(*function));
115 TRACE_(win32)("%s\n", dbg_str(win32));
120 /* Look up the specified function or ordinal in the exportlist:
121 * If it is a string:
122 * - look up the name in the Name list.
123 * - look up the ordinal with that index.
124 * - use the ordinal as offset into the functionlist
125 * If it is a ordinal:
126 * - use ordinal-pe_export->Base as offset into the functionlist
128 FARPROC PE_FindExportedFunction(
129 WINE_MODREF *wm, /* [in] WINE modreference */
130 LPCSTR funcName, /* [in] function name */
131 BOOL snoop )
133 u_short * ordinal;
134 u_long * function;
135 u_char ** name, *ename;
136 int i;
137 PE_MODREF *pem = &(wm->binfmt.pe);
138 IMAGE_EXPORT_DIRECTORY *exports = pem->pe_export;
139 unsigned int load_addr = wm->module;
140 u_long rva_start, rva_end, addr;
141 char * forward;
143 if (HIWORD(funcName))
144 TRACE_(win32)("(%s)\n",funcName);
145 else
146 TRACE_(win32)("(%d)\n",(int)funcName);
147 if (!exports) {
148 /* Not a fatal problem, some apps do
149 * GetProcAddress(0,"RegisterPenApp") which triggers this
150 * case.
152 WARN_(win32)("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,pem);
153 return NULL;
155 ordinal = (u_short*) RVA(exports->AddressOfNameOrdinals);
156 function= (u_long*) RVA(exports->AddressOfFunctions);
157 name = (u_char **) RVA(exports->AddressOfNames);
158 forward = NULL;
159 rva_start = PE_HEADER(wm->module)->OptionalHeader
160 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
161 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
162 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
164 if (HIWORD(funcName)) {
165 for(i=0; i<exports->NumberOfNames; i++) {
166 ename=(char*)RVA(*name);
167 if(!strcmp(ename,funcName))
169 addr = function[*ordinal];
170 if (!addr) return NULL;
171 if ((addr < rva_start) || (addr >= rva_end))
172 return snoop? SNOOP_GetProcAddress(wm->module,ename,*ordinal,(FARPROC)RVA(addr))
173 : (FARPROC)RVA(addr);
174 forward = (char *)RVA(addr);
175 break;
177 ordinal++;
178 name++;
180 } else {
181 int i;
182 if (LOWORD(funcName)-exports->Base > exports->NumberOfFunctions) {
183 TRACE_(win32)(" ordinal %d out of range!\n",
184 LOWORD(funcName));
185 return NULL;
187 addr = function[(int)funcName-exports->Base];
188 if (!addr) return NULL;
189 ename = "";
190 if (name) {
191 for (i=0;i<exports->NumberOfNames;i++) {
192 ename = (char*)RVA(*name);
193 if (*ordinal == LOWORD(funcName)-exports->Base)
194 break;
195 ordinal++;
196 name++;
198 if (i==exports->NumberOfNames)
199 ename = "";
201 if ((addr < rva_start) || (addr >= rva_end))
202 return snoop? SNOOP_GetProcAddress(wm->module,ename,(DWORD)funcName-exports->Base,(FARPROC)RVA(addr))
203 : (FARPROC)RVA(addr);
204 forward = (char *)RVA(addr);
206 if (forward)
208 WINE_MODREF *wm;
209 char module[256];
210 char *end = strchr(forward, '.');
212 if (!end) return NULL;
213 assert(end-forward<256);
214 strncpy(module, forward, (end - forward));
215 module[end-forward] = 0;
216 if (!(wm = MODULE_FindModule( module )))
218 ERR_(win32)("module not found for forward '%s'\n", forward );
219 return NULL;
221 return MODULE_GetProcAddress( wm->module, end + 1, snoop );
223 return NULL;
226 DWORD fixup_imports( WINE_MODREF *wm )
228 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
229 PE_MODREF *pem;
230 unsigned int load_addr = wm->module;
231 int i,characteristics_detection=1;
232 char *modname;
234 assert(wm->type==MODULE32_PE);
235 pem = &(wm->binfmt.pe);
236 if (pem->pe_export)
237 modname = (char*) RVA(pem->pe_export->Name);
238 else
239 modname = "<unknown>";
241 /* OK, now dump the import list */
242 TRACE_(win32)("Dumping imports list\n");
244 /* first, count the number of imported non-internal modules */
245 pe_imp = pem->pe_import;
246 if (!pe_imp) return 0;
248 /* We assume that we have at least one import with !0 characteristics and
249 * detect broken imports with all characteristsics 0 (notably Borland) and
250 * switch the detection off for them.
252 for (i = 0; pe_imp->Name ; pe_imp++) {
253 if (!i && !pe_imp->u.Characteristics)
254 characteristics_detection = 0;
255 if (characteristics_detection && !pe_imp->u.Characteristics)
256 break;
257 i++;
259 if (!i) return 0; /* no imports */
261 /* Allocate module dependency list */
262 wm->nDeps = i;
263 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
265 /* load the imported modules. They are automatically
266 * added to the modref list of the process.
269 for (i = 0, pe_imp = pem->pe_import; pe_imp->Name ; pe_imp++) {
270 WINE_MODREF *wmImp;
271 IMAGE_IMPORT_BY_NAME *pe_name;
272 PIMAGE_THUNK_DATA import_list,thunk_list;
273 char *name = (char *) RVA(pe_imp->Name);
275 if (characteristics_detection && !pe_imp->u.Characteristics)
276 break;
278 /* don't use MODULE_Load, Win32 creates new task differently */
279 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
280 if (!wmImp) {
281 char *p,buffer[2000];
283 /* GetModuleFileName would use the wrong process, so don't use it */
284 strcpy(buffer,wm->shortname);
285 if (!(p = strrchr (buffer, '\\')))
286 p = buffer;
287 strcpy (p + 1, name);
288 wmImp = MODULE_LoadLibraryExA( buffer, 0, 0 );
290 if (!wmImp) {
291 ERR_(module)("Module %s not found\n", name);
292 return 1;
294 wm->deps[i++] = wmImp;
296 /* FIXME: forwarder entries ... */
298 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
299 TRACE_(win32)("Microsoft style imports used\n");
300 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
301 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
303 while (import_list->u1.Ordinal) {
304 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
305 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
307 TRACE_(win32)("--- Ordinal %s,%d\n", name, ordinal);
308 thunk_list->u1.Function=MODULE_GetProcAddress(
309 wmImp->module, (LPCSTR)ordinal, TRUE
311 if (!thunk_list->u1.Function) {
312 ERR_(win32)("No implementation for %s.%d, setting to 0xdeadbeef\n",
313 name, ordinal);
314 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
316 } else { /* import by name */
317 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
318 TRACE_(win32)("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
319 thunk_list->u1.Function=MODULE_GetProcAddress(
320 wmImp->module, pe_name->Name, TRUE
322 if (!thunk_list->u1.Function) {
323 ERR_(win32)("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
324 name,pe_name->Hint,pe_name->Name);
325 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
328 import_list++;
329 thunk_list++;
331 } else { /* Borland style */
332 TRACE_(win32)("Borland style imports used\n");
333 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
334 while (thunk_list->u1.Ordinal) {
335 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
336 /* not sure about this branch, but it seems to work */
337 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
339 TRACE_(win32)("--- Ordinal %s.%d\n",name,ordinal);
340 thunk_list->u1.Function=MODULE_GetProcAddress(
341 wmImp->module, (LPCSTR) ordinal, TRUE
343 if (!thunk_list->u1.Function) {
344 ERR_(win32)("No implementation for %s.%d, setting to 0xdeadbeef\n",
345 name,ordinal);
346 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
348 } else {
349 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
350 TRACE_(win32)("--- %s %s.%d\n",
351 pe_name->Name,name,pe_name->Hint);
352 thunk_list->u1.Function=MODULE_GetProcAddress(
353 wmImp->module, pe_name->Name, TRUE
355 if (!thunk_list->u1.Function) {
356 ERR_(win32)("No implementation for %s.%d, setting to 0xdeadbeef\n",
357 name, pe_name->Hint);
358 thunk_list->u1.Function = (FARPROC)0xdeadbeef;
361 thunk_list++;
365 return 0;
368 static int calc_vma_size( HMODULE hModule )
370 int i,vma_size = 0;
371 IMAGE_SECTION_HEADER *pe_seg = PE_SECTIONS(hModule);
373 TRACE_(win32)("Dump of segment table\n");
374 TRACE_(win32)(" Name VSz Vaddr SzRaw Fileadr *Reloc *Lineum #Reloc #Linum Char\n");
375 for (i = 0; i< PE_HEADER(hModule)->FileHeader.NumberOfSections; i++)
377 TRACE_(win32)("%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n",
378 pe_seg->Name,
379 pe_seg->Misc.VirtualSize,
380 pe_seg->VirtualAddress,
381 pe_seg->SizeOfRawData,
382 pe_seg->PointerToRawData,
383 pe_seg->PointerToRelocations,
384 pe_seg->PointerToLinenumbers,
385 pe_seg->NumberOfRelocations,
386 pe_seg->NumberOfLinenumbers,
387 pe_seg->Characteristics);
388 vma_size=MAX(vma_size, pe_seg->VirtualAddress+pe_seg->SizeOfRawData);
389 vma_size=MAX(vma_size, pe_seg->VirtualAddress+pe_seg->Misc.VirtualSize);
390 pe_seg++;
392 return vma_size;
395 static void do_relocations( unsigned int load_addr, IMAGE_BASE_RELOCATION *r )
397 int delta = load_addr - PE_HEADER(load_addr)->OptionalHeader.ImageBase;
398 int hdelta = (delta >> 16) & 0xFFFF;
399 int ldelta = delta & 0xFFFF;
401 if(delta == 0)
402 /* Nothing to do */
403 return;
404 while(r->VirtualAddress)
406 char *page = (char*) RVA(r->VirtualAddress);
407 int count = (r->SizeOfBlock - 8)/2;
408 int i;
409 TRACE_(fixup)("%x relocations for page %lx\n",
410 count, r->VirtualAddress);
411 /* patching in reverse order */
412 for(i=0;i<count;i++)
414 int offset = r->TypeOffset[i] & 0xFFF;
415 int type = r->TypeOffset[i] >> 12;
416 TRACE_(fixup)("patching %x type %x\n", offset, type);
417 switch(type)
419 case IMAGE_REL_BASED_ABSOLUTE: break;
420 case IMAGE_REL_BASED_HIGH:
421 *(short*)(page+offset) += hdelta;
422 break;
423 case IMAGE_REL_BASED_LOW:
424 *(short*)(page+offset) += ldelta;
425 break;
426 case IMAGE_REL_BASED_HIGHLOW:
427 *(int*)(page+offset) += delta;
428 /* FIXME: if this is an exported address, fire up enhanced logic */
429 break;
430 case IMAGE_REL_BASED_HIGHADJ:
431 FIXME_(win32)("Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
432 break;
433 case IMAGE_REL_BASED_MIPS_JMPADDR:
434 FIXME_(win32)("Is this a MIPS machine ???\n");
435 break;
436 default:
437 FIXME_(win32)("Unknown fixup type\n");
438 break;
441 r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
449 /**********************************************************************
450 * PE_LoadImage
451 * Load one PE format DLL/EXE into memory
453 * Unluckily we can't just mmap the sections where we want them, for
454 * (at least) Linux does only support offsets which are page-aligned.
456 * BUT we have to map the whole image anyway, for Win32 programs sometimes
457 * want to access them. (HMODULE32 point to the start of it)
459 HMODULE PE_LoadImage( HFILE hFile, OFSTRUCT *ofs, LPCSTR *modName )
461 HMODULE hModule;
462 HANDLE mapping;
464 IMAGE_NT_HEADERS *nt;
465 IMAGE_SECTION_HEADER *pe_sec;
466 IMAGE_DATA_DIRECTORY *dir;
467 BY_HANDLE_FILE_INFORMATION bhfi;
468 int i, rawsize, lowest_va, lowest_fa, vma_size, file_size = 0;
469 DWORD load_addr, aoep, reloc = 0;
471 /* Retrieve file size */
472 if ( GetFileInformationByHandle( hFile, &bhfi ) )
473 file_size = bhfi.nFileSizeLow; /* FIXME: 64 bit */
475 /* Map the PE file somewhere */
476 mapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY | SEC_COMMIT,
477 0, 0, NULL );
478 if (!mapping)
480 WARN_(win32)("CreateFileMapping error %ld\n", GetLastError() );
481 return 0;
483 hModule = (HMODULE)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
484 CloseHandle( mapping );
485 if (!hModule)
487 WARN_(win32)("MapViewOfFile error %ld\n", GetLastError() );
488 return 0;
490 nt = PE_HEADER( hModule );
492 /* Check signature */
493 if ( nt->Signature != IMAGE_NT_SIGNATURE )
495 WARN_(win32)("image doesn't have PE signature, but 0x%08lx\n",
496 nt->Signature );
497 goto error;
500 /* Check architecture */
501 if ( nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386 )
503 MESSAGE("Trying to load PE image for unsupported architecture (");
504 switch (nt->FileHeader.Machine)
506 case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
507 case IMAGE_FILE_MACHINE_I860: MESSAGE("I860"); break;
508 case IMAGE_FILE_MACHINE_R3000: MESSAGE("R3000"); break;
509 case IMAGE_FILE_MACHINE_R4000: MESSAGE("R4000"); break;
510 case IMAGE_FILE_MACHINE_R10000: MESSAGE("R10000"); break;
511 case IMAGE_FILE_MACHINE_ALPHA: MESSAGE("Alpha"); break;
512 case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
513 default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
515 MESSAGE(")\n");
516 goto error;
519 /* Find out how large this executeable should be */
520 pe_sec = PE_SECTIONS( hModule );
521 rawsize = 0; lowest_va = 0x10000; lowest_fa = 0x10000;
522 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
524 if (lowest_va > pe_sec[i].VirtualAddress)
525 lowest_va = pe_sec[i].VirtualAddress;
526 if (pe_sec[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
527 continue;
528 if (pe_sec[i].PointerToRawData < lowest_fa)
529 lowest_fa = pe_sec[i].PointerToRawData;
530 if (pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData > rawsize)
531 rawsize = pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData;
534 /* Check file size */
535 if ( file_size && file_size < rawsize )
537 ERR_(win32)("PE module is too small (header: %d, filesize: %d), "
538 "probably truncated download?\n",
539 rawsize, file_size );
540 goto error;
543 /* Check entrypoint address */
544 aoep = nt->OptionalHeader.AddressOfEntryPoint;
545 if (aoep && (aoep < lowest_va))
546 FIXME_(win32)("WARNING: '%s' has an invalid entrypoint (0x%08lx) "
547 "below the first virtual address (0x%08x) "
548 "(possible Virus Infection or broken binary)!\n",
549 ofs->szPathName, aoep, lowest_va );
552 /* FIXME: Hack! While we don't really support shared sections yet,
553 * this checks for those special cases where the whole DLL
554 * consists only of shared sections and is mapped into the
555 * shared address space > 2GB. In this case, we assume that
556 * the module got mapped at its base address. Thus we simply
557 * check whether the module has actually been mapped there
558 * and use it, if so. This is needed to get Win95 USER32.DLL
559 * to work (until we support shared sections properly).
562 if ( nt->OptionalHeader.ImageBase & 0x80000000 )
564 HMODULE sharedMod = (HMODULE)nt->OptionalHeader.ImageBase;
565 IMAGE_NT_HEADERS *sharedNt = (PIMAGE_NT_HEADERS)
566 ( (LPBYTE)sharedMod + ((LPBYTE)nt - (LPBYTE)hModule) );
568 /* Well, this check is not really comprehensive,
569 but should be good enough for now ... */
570 if ( !IsBadReadPtr( (LPBYTE)sharedMod, sizeof(IMAGE_DOS_HEADER) )
571 && memcmp( (LPBYTE)sharedMod, (LPBYTE)hModule, sizeof(IMAGE_DOS_HEADER) ) == 0
572 && !IsBadReadPtr( sharedNt, sizeof(IMAGE_NT_HEADERS) )
573 && memcmp( sharedNt, nt, sizeof(IMAGE_NT_HEADERS) ) == 0 )
575 UnmapViewOfFile( (LPVOID)hModule );
576 return sharedMod;
581 /* Allocate memory for module */
582 load_addr = nt->OptionalHeader.ImageBase;
583 vma_size = calc_vma_size( hModule );
585 load_addr = (DWORD)VirtualAlloc( (void*)load_addr, vma_size,
586 MEM_RESERVE | MEM_COMMIT,
587 PAGE_EXECUTE_READWRITE );
588 if (load_addr == 0)
590 /* We need to perform base relocations */
591 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BASERELOC;
592 if (dir->Size)
593 reloc = dir->VirtualAddress;
594 else
596 FIXME_(win32)(
597 "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
598 ofs->szPathName,
599 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
600 "stripped during link" : "unknown reason" );
601 goto error;
604 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
605 * really make sure that the *new* base address is also > 2GB.
606 * Some DLLs really check the MSB of the module handle :-/
608 if ( nt->OptionalHeader.ImageBase & 0x80000000 )
609 ERR_(win32)( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
611 load_addr = (DWORD)VirtualAlloc( NULL, vma_size,
612 MEM_RESERVE | MEM_COMMIT,
613 PAGE_EXECUTE_READWRITE );
616 TRACE_(win32)("Load addr is %lx (base %lx), range %x\n",
617 load_addr, nt->OptionalHeader.ImageBase, vma_size );
618 TRACE_(segment)("Loading %s at %lx, range %x\n",
619 ofs->szPathName, load_addr, vma_size );
621 /* Store the NT header at the load addr */
622 *(PIMAGE_DOS_HEADER)load_addr = *(PIMAGE_DOS_HEADER)hModule;
623 *PE_HEADER( load_addr ) = *nt;
624 memcpy( PE_SECTIONS(load_addr), PE_SECTIONS(hModule),
625 sizeof(IMAGE_SECTION_HEADER) * nt->FileHeader.NumberOfSections );
626 #if 0
627 /* Copies all stuff up to the first section. Including win32 viruses. */
628 memcpy( load_addr, hModule, lowest_fa );
629 #endif
631 /* Copy sections into module image */
632 pe_sec = PE_SECTIONS( hModule );
633 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, pe_sec++)
635 /* memcpy only non-BSS segments */
636 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
637 * but it is not possible for (at least) Linux needs
638 * a page-aligned offset.
640 if(!(pe_sec->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
641 memcpy((char*)RVA(pe_sec->VirtualAddress),
642 (char*)(hModule + pe_sec->PointerToRawData),
643 pe_sec->SizeOfRawData);
644 #if 0
645 /* not needed, memory is zero */
646 if(strcmp(pe_sec->Name, ".bss") == 0)
647 memset((void *)RVA(pe_sec->VirtualAddress), 0,
648 pe_sec->Misc.VirtualSize ?
649 pe_sec->Misc.VirtualSize :
650 pe_sec->SizeOfRawData);
651 #endif
654 /* Perform base relocation, if necessary */
655 if ( reloc )
656 do_relocations( load_addr, (IMAGE_BASE_RELOCATION *)RVA(reloc) );
658 /* Get module name */
659 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
660 if (dir->Size)
661 *modName = (LPCSTR)RVA(((PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress))->Name);
663 /* We don't need the orignal mapping any more */
664 UnmapViewOfFile( (LPVOID)hModule );
665 return (HMODULE)load_addr;
667 error:
668 UnmapViewOfFile( (LPVOID)hModule );
669 return 0;
672 /**********************************************************************
673 * PE_CreateModule
675 * Create WINE_MODREF structure for loaded HMODULE32, link it into
676 * process modref_list, and fixup all imports.
678 * Note: hModule must point to a correctly allocated PE image,
679 * with base relocations applied; the 16-bit dummy module
680 * associated to hModule must already exist.
682 * Note: This routine must always be called in the context of the
683 * process that is to own the module to be created.
685 WINE_MODREF *PE_CreateModule( HMODULE hModule,
686 OFSTRUCT *ofs, DWORD flags, BOOL builtin )
688 DWORD load_addr = (DWORD)hModule; /* for RVA */
689 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
690 IMAGE_DATA_DIRECTORY *dir;
691 IMAGE_IMPORT_DESCRIPTOR *pe_import = NULL;
692 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
693 IMAGE_RESOURCE_DIRECTORY *pe_resource = NULL;
694 WINE_MODREF *wm;
695 int result;
696 char *modname;
699 /* Retrieve DataDirectory entries */
701 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
702 if (dir->Size)
703 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
705 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IMPORT;
706 if (dir->Size)
707 pe_import = (PIMAGE_IMPORT_DESCRIPTOR)RVA(dir->VirtualAddress);
709 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_RESOURCE;
710 if (dir->Size)
711 pe_resource = (PIMAGE_RESOURCE_DIRECTORY)RVA(dir->VirtualAddress);
713 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
714 if (dir->Size) FIXME_(win32)("Exception directory ignored\n" );
716 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
717 if (dir->Size) FIXME_(win32)("Security directory ignored\n" );
719 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
720 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
722 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DEBUG;
723 if (dir->Size) TRACE_(win32)("Debug directory ignored\n" );
725 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COPYRIGHT;
726 if (dir->Size) FIXME_(win32)("Copyright string ignored\n" );
728 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
729 if (dir->Size) FIXME_(win32)("Global Pointer (MIPS) ignored\n" );
731 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
733 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
734 if (dir->Size) FIXME_(win32)("Load Configuration directory ignored\n" );
736 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
737 if (dir->Size) TRACE_(win32)("Bound Import directory ignored\n" );
739 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
740 if (dir->Size) TRACE_(win32)("Import Address Table directory ignored\n" );
742 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
743 if (dir->Size)
745 TRACE_(win32)("Delayed import, stub calls LoadLibrary\n" );
747 * Nothing to do here.
750 #ifdef ImgDelayDescr
752 * This code is useful to observe what the heck is going on.
755 ImgDelayDescr *pe_delay = NULL;
756 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
757 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
758 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
759 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
760 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
761 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
762 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
763 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
764 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
766 #endif /* ImgDelayDescr */
769 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
770 if (dir->Size) FIXME_(win32)("Unknown directory 14 ignored\n" );
772 dir = nt->OptionalHeader.DataDirectory+15;
773 if (dir->Size) FIXME_(win32)("Unknown directory 15 ignored\n" );
776 /* Allocate and fill WINE_MODREF */
778 wm = (WINE_MODREF *)HeapAlloc( GetProcessHeap(),
779 HEAP_ZERO_MEMORY, sizeof(*wm) );
780 wm->module = hModule;
782 if ( builtin )
783 wm->flags |= WINE_MODREF_INTERNAL;
784 if ( flags & DONT_RESOLVE_DLL_REFERENCES )
785 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
786 if ( flags & LOAD_LIBRARY_AS_DATAFILE )
787 wm->flags |= WINE_MODREF_LOAD_AS_DATAFILE;
789 wm->type = MODULE32_PE;
790 wm->binfmt.pe.pe_export = pe_export;
791 wm->binfmt.pe.pe_import = pe_import;
792 wm->binfmt.pe.pe_resource = pe_resource;
793 wm->binfmt.pe.tlsindex = -1;
795 if ( pe_export )
796 modname = (char *)RVA( pe_export->Name );
797 else
799 /* try to find out the name from the OFSTRUCT */
800 char *s;
801 modname = ofs->szPathName;
802 if ((s=strrchr(modname,'\\'))) modname = s+1;
804 wm->modname = HEAP_strdupA( GetProcessHeap(), 0, modname );
806 result = GetLongPathNameA( ofs->szPathName, NULL, 0 );
807 wm->longname = (char *)HeapAlloc( GetProcessHeap(), 0, result+1 );
808 GetLongPathNameA( ofs->szPathName, wm->longname, result+1 );
810 wm->shortname = HEAP_strdupA( GetProcessHeap(), 0, ofs->szPathName );
812 /* Link MODREF into process list */
814 EnterCriticalSection( &PROCESS_Current()->crit_section );
816 wm->next = PROCESS_Current()->modref_list;
817 PROCESS_Current()->modref_list = wm;
818 if ( wm->next ) wm->next->prev = wm;
820 if ( !(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) )
822 if ( PROCESS_Current()->exe_modref )
823 FIXME_(win32)("overwriting old exe_modref... arrgh\n" );
824 PROCESS_Current()->exe_modref = wm;
827 LeaveCriticalSection( &PROCESS_Current()->crit_section );
830 /* Dump Exports */
832 if ( pe_export )
833 dump_exports( hModule );
835 /* Fixup Imports */
837 if ( pe_import && fixup_imports( wm )
838 && !( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE )
839 && !( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS ) )
841 /* remove entry from modref chain */
842 EnterCriticalSection( &PROCESS_Current()->crit_section );
844 if ( !wm->prev )
845 PROCESS_Current()->modref_list = wm->next;
846 else
847 wm->prev->next = wm->next;
849 if ( wm->next ) wm->next->prev = wm->prev;
850 wm->next = wm->prev = NULL;
852 LeaveCriticalSection( &PROCESS_Current()->crit_section );
854 /* FIXME: there are several more dangling references
855 * left. Including dlls loaded by this dll before the
856 * failed one. Unrolling is rather difficult with the
857 * current structure and we can leave it them lying
858 * around with no problems, so we don't care.
859 * As these might reference our wm, we don't free it.
861 return NULL;
864 return wm;
867 /******************************************************************************
868 * The PE Library Loader frontend.
869 * FIXME: handle the flags.
871 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags, DWORD *err)
873 LPCSTR modName = NULL;
874 OFSTRUCT ofs;
875 HMODULE hModule32;
876 HMODULE16 hModule16;
877 NE_MODULE *pModule;
878 WINE_MODREF *wm;
879 char dllname[256], *p;
880 HFILE hFile;
882 /* Append .DLL to name if no extension present */
883 strcpy( dllname, name );
884 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
885 strcat( dllname, ".DLL" );
887 /* Load PE module */
888 hFile = OpenFile( dllname, &ofs, OF_READ | OF_SHARE_DENY_WRITE );
889 if ( hFile != HFILE_ERROR )
891 hModule32 = PE_LoadImage( hFile, &ofs, &modName );
892 CloseHandle( hFile );
893 if(!hModule32)
895 *err = ERROR_OUTOFMEMORY; /* Not entirely right, but good enough */
896 return NULL;
899 else
901 *err = ERROR_FILE_NOT_FOUND;
902 return NULL;
905 /* Create 16-bit dummy module */
906 if ((hModule16 = MODULE_CreateDummyModule( &ofs, modName )) < 32)
908 *err = (DWORD)hModule16; /* This should give the correct error */
909 return NULL;
911 pModule = (NE_MODULE *)GlobalLock16( hModule16 );
912 pModule->flags = NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA | NE_FFLAGS_WIN32;
913 pModule->module32 = hModule32;
915 /* Create 32-bit MODREF */
916 if ( !(wm = PE_CreateModule( hModule32, &ofs, flags, FALSE )) )
918 ERR_(win32)("can't load %s\n",ofs.szPathName);
919 FreeLibrary16( hModule16 );
920 *err = ERROR_OUTOFMEMORY;
921 return NULL;
924 if (wm->binfmt.pe.pe_export)
925 SNOOP_RegisterDLL(wm->module,wm->modname,wm->binfmt.pe.pe_export->NumberOfFunctions);
927 *err = 0;
928 return wm;
932 /*****************************************************************************
933 * PE_UnloadLibrary
935 * Unload the library unmapping the image and freeing the modref structure.
937 void PE_UnloadLibrary(WINE_MODREF *wm)
939 /* FIXME, do something here */
942 /*****************************************************************************
943 * Load the PE main .EXE. All other loading is done by PE_LoadLibraryExA
944 * FIXME: this function should use PE_LoadLibraryExA, but currently can't
945 * due to the PROCESS_Create stuff.
947 BOOL PE_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmd_line, LPCSTR env,
948 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
949 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
950 LPPROCESS_INFORMATION info )
952 LPCSTR modName = NULL;
953 HMODULE16 hModule16;
954 HMODULE hModule32;
955 NE_MODULE *pModule;
957 /* Load file */
958 if ( (hModule32 = PE_LoadImage( hFile, ofs, &modName )) < 32 )
960 SetLastError( hModule32 );
961 return FALSE;
963 #if 0
964 if (PE_HEADER(hModule32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
966 SetLastError( 20 ); /* FIXME: not the right error code */
967 return FALSE;
969 #endif
971 /* Create 16-bit dummy module */
972 if ( (hModule16 = MODULE_CreateDummyModule( ofs, modName )) < 32 )
974 SetLastError( hModule16 );
975 return FALSE;
977 pModule = (NE_MODULE *)GlobalLock16( hModule16 );
978 pModule->flags = NE_FFLAGS_WIN32;
979 pModule->module32 = hModule32;
981 /* Create new process */
982 if ( !PROCESS_Create( pModule, cmd_line, env,
983 psa, tsa, inherit, flags, startup, info ) )
984 return FALSE;
986 /* Note: PE_CreateModule and the remaining process initialization will
987 be done in the context of the new process, in TASK_CallToStart */
989 return TRUE;
992 /*********************************************************************
993 * PE_UnloadImage [internal]
995 int PE_UnloadImage( HMODULE hModule )
997 FIXME_(win32)("stub.\n");
998 /* free resources, image, unmap */
999 return 1;
1002 /* Called if the library is loaded or freed.
1003 * NOTE: if a thread attaches a DLL, the current thread will only do
1004 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
1005 * (SDK)
1007 BOOL PE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
1009 BOOL retv = TRUE;
1010 assert( wm->type == MODULE32_PE );
1012 /* Is this a library? And has it got an entrypoint? */
1013 if ((PE_HEADER(wm->module)->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1014 (PE_HEADER(wm->module)->OptionalHeader.AddressOfEntryPoint)
1016 DLLENTRYPROC entry = (void*)RVA_PTR( wm->module,OptionalHeader.AddressOfEntryPoint );
1017 TRACE_(relay)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
1018 entry, wm->module, type, lpReserved );
1020 retv = entry( wm->module, type, lpReserved );
1023 return retv;
1026 /************************************************************************
1027 * PE_InitTls (internal)
1029 * If included, initialises the thread local storages of modules.
1030 * Pointers in those structs are not RVAs but real pointers which have been
1031 * relocated by do_relocations() already.
1033 void PE_InitTls( void )
1035 WINE_MODREF *wm;
1036 PE_MODREF *pem;
1037 IMAGE_NT_HEADERS *peh;
1038 DWORD size,datasize;
1039 LPVOID mem;
1040 PIMAGE_TLS_DIRECTORY pdir;
1041 int delta;
1043 for (wm = PROCESS_Current()->modref_list;wm;wm=wm->next) {
1044 if (wm->type!=MODULE32_PE)
1045 continue;
1046 pem = &(wm->binfmt.pe);
1047 peh = PE_HEADER(wm->module);
1048 delta = wm->module - peh->OptionalHeader.ImageBase;
1049 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
1050 continue;
1051 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
1052 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
1055 if ( pem->tlsindex == -1 ) {
1056 pem->tlsindex = TlsAlloc();
1057 *pdir->AddressOfIndex=pem->tlsindex;
1059 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
1060 size = datasize + pdir->SizeOfZeroFill;
1061 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
1062 memcpy(mem,(LPVOID)pdir->StartAddressOfRawData,datasize);
1063 if (pdir->AddressOfCallBacks) {
1064 PIMAGE_TLS_CALLBACK *cbs =
1065 (PIMAGE_TLS_CALLBACK *)pdir->AddressOfCallBacks;
1067 if (*cbs)
1068 FIXME_(win32)("TLS Callbacks aren't going to be called\n");
1071 TlsSetValue( pem->tlsindex, mem );