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