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