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