Implemented SEC_IMAGE mappings and shared PE sections (with the help
[wine] / loader / pe_image.c
1 /* 
2  *  Copyright   1994    Eric Youndale & Erik Bos
3  *  Copyright   1995    Martin von Löwis
4  *  Copyright   1996-98 Marcus Meissner
5  *
6  *      based on Eric Youndale's pe-test and:
7  *
8  *      ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
9  * make that:
10  *      ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
11  */
12 /* Notes:
13  * Before you start changing something in this file be aware of the following:
14  *
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  */
25
26 #include "config.h"
27
28 #include <errno.h>
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #ifdef HAVE_SYS_MMAN_H
36 #include <sys/mman.h>
37 #endif
38 #include "windef.h"
39 #include "winbase.h"
40 #include "wine/winbase16.h"
41 #include "winerror.h"
42 #include "callback.h"
43 #include "file.h"
44 #include "heap.h"
45 #include "neexe.h"
46 #include "process.h"
47 #include "thread.h"
48 #include "module.h"
49 #include "global.h"
50 #include "task.h"
51 #include "snoop.h"
52 #include "server.h"
53 #include "debugtools.h"
54
55 DEFAULT_DEBUG_CHANNEL(win32);
56 DECLARE_DEBUG_CHANNEL(delayhlp);
57 DECLARE_DEBUG_CHANNEL(fixup);
58 DECLARE_DEBUG_CHANNEL(module);
59 DECLARE_DEBUG_CHANNEL(relay);
60 DECLARE_DEBUG_CHANNEL(segment);
61
62
63 static IMAGE_EXPORT_DIRECTORY *get_exports( HMODULE hmod )
64 {
65     IMAGE_EXPORT_DIRECTORY *ret = NULL;
66     IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
67                                 + IMAGE_DIRECTORY_ENTRY_EXPORT;
68     if (dir->Size && dir->VirtualAddress)
69         ret = (IMAGE_EXPORT_DIRECTORY *)((char *)hmod + dir->VirtualAddress);
70     return ret;
71 }
72
73 static IMAGE_IMPORT_DESCRIPTOR *get_imports( HMODULE hmod )
74 {
75     IMAGE_IMPORT_DESCRIPTOR *ret = NULL;
76     IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
77                                 + IMAGE_DIRECTORY_ENTRY_IMPORT;
78     if (dir->Size && dir->VirtualAddress)
79         ret = (IMAGE_IMPORT_DESCRIPTOR *)((char *)hmod + dir->VirtualAddress);
80     return ret;
81 }
82
83
84 /* convert PE image VirtualAddress to Real Address */
85 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
86
87 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
88
89 void dump_exports( HMODULE hModule )
90
91   char          *Module;
92   int           i, j;
93   u_short       *ordinal;
94   u_long        *function,*functions;
95   u_char        **name;
96   unsigned int load_addr = hModule;
97
98   DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
99                    .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
100   DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
101                    .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
102   IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
103
104   Module = (char*)RVA(pe_exports->Name);
105   TRACE("*******EXPORT DATA*******\n");
106   TRACE("Module name is %s, %ld functions, %ld names\n", 
107         Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
108
109   ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
110   functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
111   name=(u_char**) RVA(pe_exports->AddressOfNames);
112
113   TRACE(" Ord    RVA     Addr   Name\n" );
114   for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
115   {
116       if (!*function) continue;  /* No such function */
117       if (TRACE_ON(win32))
118       {
119         DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
120         /* Check if we have a name for it */
121         for (j = 0; j < pe_exports->NumberOfNames; j++)
122           if (ordinal[j] == i)
123           {
124               DPRINTF( "  %s", (char*)RVA(name[j]) );
125               break;
126           }
127         if ((*function >= rva_start) && (*function <= rva_end))
128           DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
129         DPRINTF("\n");
130       }
131   }
132 }
133
134 /* Look up the specified function or ordinal in the exportlist:
135  * If it is a string:
136  *      - look up the name in the Name list. 
137  *      - look up the ordinal with that index.
138  *      - use the ordinal as offset into the functionlist
139  * If it is a ordinal:
140  *      - use ordinal-pe_export->Base as offset into the functionlist
141  */
142 static FARPROC PE_FindExportedFunction( 
143         WINE_MODREF *wm,        /* [in] WINE modreference */
144         LPCSTR funcName,        /* [in] function name */
145         BOOL snoop )
146 {
147         u_short                         * ordinals;
148         u_long                          * function;
149         u_char                          ** name, *ename = NULL;
150         int                             i, ordinal;
151         unsigned int                    load_addr = wm->module;
152         u_long                          rva_start, rva_end, addr;
153         char                            * forward;
154         IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
155
156         if (HIWORD(funcName))
157                 TRACE("(%s)\n",funcName);
158         else
159                 TRACE("(%d)\n",(int)funcName);
160         if (!exports) {
161                 /* Not a fatal problem, some apps do
162                  * GetProcAddress(0,"RegisterPenApp") which triggers this
163                  * case.
164                  */
165                 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
166                 return NULL;
167         }
168         ordinals= (u_short*)  RVA(exports->AddressOfNameOrdinals);
169         function= (u_long*)   RVA(exports->AddressOfFunctions);
170         name    = (u_char **) RVA(exports->AddressOfNames);
171         forward = NULL;
172         rva_start = PE_HEADER(wm->module)->OptionalHeader
173                 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
174         rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
175                 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
176
177         if (HIWORD(funcName))
178         {
179             /* first try a binary search */
180             int min = 0, max = exports->NumberOfNames - 1;
181             while (min <= max)
182             {
183                 int res, pos = (min + max) / 2;
184                 ename = RVA(name[pos]);
185                 if (!(res = strcmp( ename, funcName )))
186                 {
187                     ordinal = ordinals[pos];
188                     goto found;
189                 }
190                 if (res > 0) max = pos - 1;
191                 else min = pos + 1;
192             }
193             /* now try a linear search in case the names aren't sorted properly */
194             for (i = 0; i < exports->NumberOfNames; i++)
195             {
196                 ename = RVA(name[i]);
197                 if (!strcmp( ename, funcName ))
198                 {
199                     ERR( "%s.%s required a linear search\n", wm->modname, funcName );
200                     ordinal = ordinals[i];
201                     goto found;
202                 }
203             }
204             return NULL;
205         }
206         else  /* find by ordinal */
207         {
208             ordinal = LOWORD(funcName) - exports->Base;
209             if (snoop && name)  /* need to find a name for it */
210             {
211                 for (i = 0; i < exports->NumberOfNames; i++)
212                     if (ordinals[i] == ordinal)
213                     {
214                         ename = RVA(name[i]);
215                         break;
216                     }
217             }
218         }
219
220  found:
221         if (ordinal >= exports->NumberOfFunctions)
222         {
223             TRACE("     ordinal %ld out of range!\n", ordinal + exports->Base );
224             return NULL;
225         }
226         addr = function[ordinal];
227         if (!addr) return NULL;
228         if ((addr < rva_start) || (addr >= rva_end))
229         {
230             FARPROC proc = RVA(addr);
231             if (snoop)
232             {
233                 if (!ename) ename = "@";
234                 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
235             }
236             return proc;
237         }
238         else  /* forward entry point */
239         {
240                 WINE_MODREF *wm;
241                 FARPROC proc;
242                 char *forward = RVA(addr);
243                 char module[256];
244                 char *end = strchr(forward, '.');
245
246                 if (!end) return NULL;
247                 if (end - forward >= sizeof(module)) return NULL;
248                 memcpy( module, forward, end - forward );
249                 module[end-forward] = 0;
250                 if (!(wm = MODULE_FindModule( module )))
251                 {
252                     ERR("module not found for forward '%s'\n", forward );
253                     return NULL;
254                 }
255                 if (!(proc = MODULE_GetProcAddress( wm->module, end + 1, snoop )))
256                     ERR("function not found for forward '%s'\n", forward );
257                 return proc;
258         }
259 }
260
261 DWORD fixup_imports( WINE_MODREF *wm )
262 {
263     IMAGE_IMPORT_DESCRIPTOR     *pe_imp;
264     unsigned int load_addr      = wm->module;
265     int                         i,characteristics_detection=1;
266     char                        *modname;
267     IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
268     IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
269     
270     if (exports)
271         modname = (char*) RVA(exports->Name);
272     else
273         modname = "<unknown>";
274
275     /* first, count the number of imported non-internal modules */
276     pe_imp = imports;
277     if (!pe_imp) return 0;
278
279     /* OK, now dump the import list */
280     TRACE("Dumping imports list\n");
281
282     /* We assume that we have at least one import with !0 characteristics and
283      * detect broken imports with all characteristics 0 (notably Borland) and
284      * switch the detection off for them.
285      */
286     for (i = 0; pe_imp->Name ; pe_imp++) {
287         if (!i && !pe_imp->u.Characteristics)
288                 characteristics_detection = 0;
289         if (characteristics_detection && !pe_imp->u.Characteristics)
290                 break;
291         i++;
292     }
293     if (!i) return 0;  /* no imports */
294
295     /* Allocate module dependency list */
296     wm->nDeps = i;
297     wm->deps  = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
298
299     /* load the imported modules. They are automatically 
300      * added to the modref list of the process.
301      */
302  
303     for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
304         WINE_MODREF             *wmImp;
305         IMAGE_IMPORT_BY_NAME    *pe_name;
306         PIMAGE_THUNK_DATA       import_list,thunk_list;
307         char                    *name = (char *) RVA(pe_imp->Name);
308
309         if (characteristics_detection && !pe_imp->u.Characteristics)
310                 break;
311
312         wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
313         if (!wmImp) {
314             ERR_(module)("Module (file) %s needed by %s not found\n", name, wm->filename);
315             return 1;
316         }
317         wm->deps[i++] = wmImp;
318
319         /* FIXME: forwarder entries ... */
320
321         if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
322             TRACE("Microsoft style imports used\n");
323             import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
324             thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
325
326             while (import_list->u1.Ordinal) {
327                 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
328                     int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
329
330                     TRACE("--- Ordinal %s,%d\n", name, ordinal);
331                     thunk_list->u1.Function=MODULE_GetProcAddress(
332                         wmImp->module, (LPCSTR)ordinal, TRUE
333                     );
334                     if (!thunk_list->u1.Function) {
335                         ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
336                                 name, ordinal);
337                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
338                     }
339                 } else {                /* import by name */
340                     pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
341                     TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
342                     thunk_list->u1.Function=MODULE_GetProcAddress(
343                         wmImp->module, pe_name->Name, TRUE
344                     );
345                     if (!thunk_list->u1.Function) {
346                         ERR("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
347                                 name,pe_name->Hint,pe_name->Name);
348                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
349                     }
350                 }
351                 import_list++;
352                 thunk_list++;
353             }
354         } else {        /* Borland style */
355             TRACE("Borland style imports used\n");
356             thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
357             while (thunk_list->u1.Ordinal) {
358                 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
359                     /* not sure about this branch, but it seems to work */
360                     int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
361
362                     TRACE("--- Ordinal %s.%d\n",name,ordinal);
363                     thunk_list->u1.Function=MODULE_GetProcAddress(
364                         wmImp->module, (LPCSTR) ordinal, TRUE
365                     );
366                     if (!thunk_list->u1.Function) {
367                         ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
368                                 name,ordinal);
369                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
370                     }
371                 } else {
372                     pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
373                     TRACE("--- %s %s.%d\n",
374                                   pe_name->Name,name,pe_name->Hint);
375                     thunk_list->u1.Function=MODULE_GetProcAddress(
376                         wmImp->module, pe_name->Name, TRUE
377                     );
378                     if (!thunk_list->u1.Function) {
379                         ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
380                                 name, pe_name->Hint);
381                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
382                     }
383                 }
384                 thunk_list++;
385             }
386         }
387     }
388     return 0;
389 }
390
391 /***********************************************************************
392  *           do_relocations
393  *
394  * Apply the relocations to a mapped PE image
395  */
396 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
397 {
398     const IMAGE_DATA_DIRECTORY *dir;
399     const IMAGE_BASE_RELOCATION *rel;
400     int delta = base - (char *)nt->OptionalHeader.ImageBase;
401
402     dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
403     rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
404
405     WARN("Info: base relocations needed for %s\n", filename);
406     if (!dir->VirtualAddress || !dir->Size)
407     {
408         if (nt->OptionalHeader.ImageBase == 0x400000)
409             ERR("Standard load address for a Win32 program not available - patched kernel ?\n");
410         ERR( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
411              filename,
412              (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
413              "stripped during link" : "unknown reason" );
414         return 0;
415     }
416
417     /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
418      *        really make sure that the *new* base address is also > 2GB.
419      *        Some DLLs really check the MSB of the module handle :-/
420      */
421     if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
422         ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
423
424     while (rel->VirtualAddress)
425     {
426         char *page = base + rel->VirtualAddress;
427         int i, count = (rel->SizeOfBlock - 8) / sizeof(rel->TypeOffset);
428
429         /* sanity checks */
430         if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
431             page > base + nt->OptionalHeader.SizeOfImage)
432         {
433             ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
434                          rel, rel->VirtualAddress, rel->SizeOfBlock,
435                          base, dir->VirtualAddress, dir->Size );
436             return 0;
437         }
438
439         TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
440
441         /* patching in reverse order */
442         for (i = 0 ; i < count; i++)
443         {
444             int offset = rel->TypeOffset[i] & 0xFFF;
445             int type = rel->TypeOffset[i] >> 12;
446             switch(type)
447             {
448             case IMAGE_REL_BASED_ABSOLUTE:
449                 break;
450             case IMAGE_REL_BASED_HIGH:
451                 *(short*)(page+offset) += HIWORD(delta);
452                 break;
453             case IMAGE_REL_BASED_LOW:
454                 *(short*)(page+offset) += LOWORD(delta);
455                 break;
456             case IMAGE_REL_BASED_HIGHLOW:
457                 *(int*)(page+offset) += delta;
458                 /* FIXME: if this is an exported address, fire up enhanced logic */
459                 break;
460             default:
461                 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
462                 break;
463             }
464         }
465         rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock);
466     }
467     return 1;
468 }
469
470
471 /**********************************************************************
472  *                      PE_LoadImage
473  * Load one PE format DLL/EXE into memory
474  * 
475  * Unluckily we can't just mmap the sections where we want them, for 
476  * (at least) Linux does only support offsets which are page-aligned.
477  *
478  * BUT we have to map the whole image anyway, for Win32 programs sometimes
479  * want to access them. (HMODULE32 point to the start of it)
480  */
481 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
482 {
483     IMAGE_NT_HEADERS *nt;
484     HMODULE hModule;
485     HANDLE mapping;
486     void *base;
487
488     TRACE_(module)( "loading %s\n", filename );
489
490     mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
491     base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
492     CloseHandle( mapping );
493     if (!base) return 0;
494
495     hModule = (HMODULE)base;
496     if (flags & LOAD_LIBRARY_AS_DATAFILE) return hModule;  /* nothing else to do */
497
498     /* perform base relocation, if necessary */
499
500     nt = PE_HEADER( hModule );
501     if (hModule != nt->OptionalHeader.ImageBase)
502     {
503         if (!do_relocations( base, nt, filename ))
504         {
505             UnmapViewOfFile( base );
506             SetLastError( ERROR_BAD_EXE_FORMAT );
507             return 0;
508         }
509     }
510
511     /* virus check */
512
513     if (nt->OptionalHeader.AddressOfEntryPoint)
514     {
515         int i;
516         IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
517                                                             nt->FileHeader.SizeOfOptionalHeader);
518         for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
519         {
520             if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
521                 continue;
522             if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->Misc.VirtualSize)
523                 break;
524         }
525         if (i == nt->FileHeader.NumberOfSections)
526             MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
527                     "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
528                     nt->OptionalHeader.AddressOfEntryPoint );
529     }
530
531     return hModule;
532 }
533
534 /**********************************************************************
535  *                 PE_CreateModule
536  *
537  * Create WINE_MODREF structure for loaded HMODULE32, link it into
538  * process modref_list, and fixup all imports.
539  *
540  * Note: hModule must point to a correctly allocated PE image,
541  *       with base relocations applied; the 16-bit dummy module
542  *       associated to hModule must already exist.
543  *
544  * Note: This routine must always be called in the context of the
545  *       process that is to own the module to be created.
546  *
547  * Note: Assumes that the process critical section is held
548  */
549 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
550                               HFILE hFile, BOOL builtin )
551 {
552     DWORD load_addr = (DWORD)hModule;  /* for RVA */
553     IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
554     IMAGE_DATA_DIRECTORY *dir;
555     IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
556     WINE_MODREF *wm;
557     HMODULE16 hModule16;
558
559     /* Retrieve DataDirectory entries */
560
561     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
562     if (dir->Size)
563         pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
564
565     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
566     if (dir->Size) FIXME("Exception directory ignored\n" );
567
568     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
569     if (dir->Size) FIXME("Security directory ignored\n" );
570
571     /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
572     /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
573
574     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
575     if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
576
577     /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
578
579     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
580     if (dir->Size) FIXME("Load Configuration directory ignored\n" );
581
582     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
583     if (dir->Size) TRACE("Bound Import directory ignored\n" );
584
585     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
586     if (dir->Size) TRACE("Import Address Table directory ignored\n" );
587
588     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
589     if (dir->Size)
590     {
591                 TRACE("Delayed import, stub calls LoadLibrary\n" );
592                 /*
593                  * Nothing to do here.
594                  */
595
596 #ifdef ImgDelayDescr
597                 /*
598                  * This code is useful to observe what the heck is going on.
599                  */
600                 {
601                 ImgDelayDescr *pe_delay = NULL;
602         pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
603         TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
604         TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
605         TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
606         TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
607         TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
608         TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
609         TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
610         TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
611         }
612 #endif /* ImgDelayDescr */
613         }
614
615     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
616     if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
617
618     dir = nt->OptionalHeader.DataDirectory+15;
619     if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
620
621     /* Create 16-bit dummy module */
622
623     if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
624     {
625         SetLastError( (DWORD)hModule16 );       /* This should give the correct error */
626         return NULL;
627     }
628
629     /* Allocate and fill WINE_MODREF */
630
631     if (!(wm = MODULE_AllocModRef( hModule, filename )))
632     {
633         FreeLibrary16( hModule16 );
634         return NULL;
635     }
636
637     if ( builtin ) 
638     {
639         NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
640         pModule->flags |= NE_FFLAGS_BUILTIN;
641         wm->flags |= WINE_MODREF_INTERNAL;
642     }
643
644     if ( flags & DONT_RESOLVE_DLL_REFERENCES )
645         wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
646
647     wm->find_export = PE_FindExportedFunction;
648
649     /* Dump Exports */
650
651     if ( pe_export )
652         dump_exports( hModule );
653
654     /* The exe_modref must be in place, before implicit linked DLLs are loaded 
655        by fixup_imports, otherwhise GetModuleFileName will not work and modules 
656        in the executables directory can not be found */
657
658     if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
659     {
660       if ( PROCESS_Current()->exe_modref )
661         FIXME( "Trying to load second .EXE file: %s\n", filename );
662       else  
663       {
664         PROCESS_Current()->exe_modref = wm;
665         PROCESS_Current()->module = wm->module;
666       }
667     }
668
669     /* Fixup Imports */
670
671     if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) && fixup_imports( wm ))
672     {
673         /* remove entry from modref chain */
674
675         if ( !wm->prev )
676             PROCESS_Current()->modref_list = wm->next;
677         else
678             wm->prev->next = wm->next;
679
680         if ( wm->next ) wm->next->prev = wm->prev;
681         wm->next = wm->prev = NULL;
682
683         /* FIXME: there are several more dangling references
684          * left. Including dlls loaded by this dll before the
685          * failed one. Unrolling is rather difficult with the
686          * current structure and we can leave it them lying
687          * around with no problems, so we don't care.
688          * As these might reference our wm, we don't free it.
689          */
690          return NULL;
691     }
692
693     if (pe_export)
694         SNOOP_RegisterDLL( hModule, wm->modname, pe_export->NumberOfFunctions );
695
696     /* Send DLL load event */
697     /* we don't need to send a dll event for the main exe */
698
699     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
700     {
701         struct load_dll_request *req = get_req_buffer();
702         req->handle     = hFile;
703         req->base       = (void *)hModule;
704         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
705         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
706         req->name       = &wm->filename;
707         server_call_noerr( REQ_LOAD_DLL );
708     }
709
710     return wm;
711 }
712
713 /******************************************************************************
714  * The PE Library Loader frontend. 
715  * FIXME: handle the flags.
716  */
717 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
718 {
719         HMODULE         hModule32;
720         WINE_MODREF     *wm;
721         char            filename[256];
722         HANDLE          hFile;
723
724         /* Search for and open PE file */
725         if ( SearchPathA( NULL, name, ".DLL", 
726                           sizeof(filename), filename, NULL ) == 0 ) return NULL;
727        
728         hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
729                              NULL, OPEN_EXISTING, 0, -1 );
730         if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
731         
732         /* Load PE module */
733         hModule32 = PE_LoadImage( hFile, filename, flags );
734         if (!hModule32)
735         {
736                 CloseHandle( hFile );
737                 return NULL;
738         }
739
740         /* Create 32-bit MODREF */
741         if ( !(wm = PE_CreateModule( hModule32, filename, flags, -1, FALSE )) )
742         {
743                 ERR( "can't load %s\n", filename );
744                 CloseHandle( hFile );
745                 SetLastError( ERROR_OUTOFMEMORY );
746                 return NULL;
747         }
748
749         CloseHandle( hFile );
750         return wm;
751 }
752
753
754 /* Called if the library is loaded or freed.
755  * NOTE: if a thread attaches a DLL, the current thread will only do
756  * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
757  * (SDK)
758  */
759 typedef DWORD CALLBACK(*DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
760
761 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
762 {
763     BOOL retv = TRUE;
764     IMAGE_NT_HEADERS *nt = PE_HEADER(module);
765
766     /* Is this a library? And has it got an entrypoint? */
767     if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
768         (nt->OptionalHeader.AddressOfEntryPoint))
769     {
770         DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
771         TRACE_(relay)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
772                        entry, module, type, lpReserved );
773
774         retv = entry( module, type, lpReserved );
775     }
776
777     return retv;
778 }
779
780 /************************************************************************
781  *      PE_InitTls                      (internal)
782  *
783  * If included, initialises the thread local storages of modules.
784  * Pointers in those structs are not RVAs but real pointers which have been
785  * relocated by do_relocations() already.
786  */
787 static LPVOID
788 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
789         if (    ((DWORD)addr>opt->ImageBase) &&
790                 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
791         )
792                 /* the address has not been relocated! */
793                 return (LPVOID)(((DWORD)addr)+delta);
794         else
795                 /* the address has been relocated already */
796                 return addr;
797 }
798 void PE_InitTls( void )
799 {
800         WINE_MODREF             *wm;
801         IMAGE_NT_HEADERS        *peh;
802         DWORD                   size,datasize;
803         LPVOID                  mem;
804         PIMAGE_TLS_DIRECTORY    pdir;
805         int delta;
806         
807         for (wm = PROCESS_Current()->modref_list;wm;wm=wm->next) {
808                 peh = PE_HEADER(wm->module);
809                 delta = wm->module - peh->OptionalHeader.ImageBase;
810                 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
811                         continue;
812                 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
813                         DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
814                 
815                 
816                 if ( wm->tlsindex == -1 ) {
817                         LPDWORD xaddr;
818                         wm->tlsindex = TlsAlloc();
819                         xaddr = _fixup_address(&(peh->OptionalHeader),delta,
820                                         pdir->AddressOfIndex
821                         );
822                         *xaddr=wm->tlsindex;
823                 }
824                 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
825                 size    = datasize + pdir->SizeOfZeroFill;
826                 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
827                 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
828                 if (pdir->AddressOfCallBacks) {
829                      PIMAGE_TLS_CALLBACK *cbs; 
830
831                      cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
832                      if (*cbs)
833                        FIXME("TLS Callbacks aren't going to be called\n");
834                 }
835
836                 TlsSetValue( wm->tlsindex, mem );
837         }
838 }
839