Added LGPL standard comment, and copyright notices where necessary.
[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   TRACE("*******EXPORT DATA*******\n");
101   TRACE("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   TRACE(" Ord    RVA     Addr   Name\n" );
109   for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
110   {
111       if (!*function) continue;  /* No such function */
112       if (TRACE_ON(win32))
113       {
114         DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
115         /* Check if we have a name for it */
116         for (j = 0; j < pe_exports->NumberOfNames; j++)
117           if (ordinal[j] == i)
118           {
119               DPRINTF( "  %s", (char*)RVA(name[j]) );
120               break;
121           }
122         if ((*function >= rva_start) && (*function <= rva_end))
123           DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
124         DPRINTF("\n");
125       }
126   }
127 }
128
129 /* Look up the specified function or ordinal in the export list:
130  * If it is a string:
131  *      - look up the name in the name list. 
132  *      - look up the ordinal with that index.
133  *      - use the ordinal as offset into the functionlist
134  * If it is an ordinal:
135  *      - use ordinal-pe_export->Base as offset into the function list
136  */
137 static FARPROC PE_FindExportedFunction( 
138         WINE_MODREF *wm,        /* [in] WINE modreference */
139         LPCSTR funcName,        /* [in] function name */
140         BOOL snoop )
141 {
142         WORD                            * ordinals;
143         DWORD                           * function;
144         BYTE                            ** name, *ename = NULL;
145         int                             i, ordinal;
146         unsigned int                    load_addr = wm->module;
147         DWORD                           rva_start, rva_end, addr;
148         char                            * forward;
149         IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
150
151         if (HIWORD(funcName))
152                 TRACE("(%s)\n",funcName);
153         else
154                 TRACE("(%d)\n",(int)funcName);
155         if (!exports) {
156                 /* Not a fatal problem, some apps do
157                  * GetProcAddress(0,"RegisterPenApp") which triggers this
158                  * case.
159                  */
160                 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
161                 return NULL;
162         }
163         ordinals= RVA(exports->AddressOfNameOrdinals);
164         function= RVA(exports->AddressOfFunctions);
165         name    = RVA(exports->AddressOfNames);
166         forward = NULL;
167         rva_start = PE_HEADER(wm->module)->OptionalHeader
168                 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
169         rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
170                 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
171
172         if (HIWORD(funcName))
173         {
174             /* first try a binary search */
175             int min = 0, max = exports->NumberOfNames - 1;
176             while (min <= max)
177             {
178                 int res, pos = (min + max) / 2;
179                 ename = RVA(name[pos]);
180                 if (!(res = strcmp( ename, funcName )))
181                 {
182                     ordinal = ordinals[pos];
183                     goto found;
184                 }
185                 if (res > 0) max = pos - 1;
186                 else min = pos + 1;
187             }
188             /* now try a linear search in case the names aren't sorted properly */
189             for (i = 0; i < exports->NumberOfNames; i++)
190             {
191                 ename = RVA(name[i]);
192                 if (!strcmp( ename, funcName ))
193                 {
194                     ERR( "%s.%s required a linear search\n", wm->modname, funcName );
195                     ordinal = ordinals[i];
196                     goto found;
197                 }
198             }
199             return NULL;
200         }
201         else  /* find by ordinal */
202         {
203             ordinal = LOWORD(funcName) - exports->Base;
204             if (snoop && name)  /* need to find a name for it */
205             {
206                 for (i = 0; i < exports->NumberOfNames; i++)
207                     if (ordinals[i] == ordinal)
208                     {
209                         ename = RVA(name[i]);
210                         break;
211                     }
212             }
213         }
214
215  found:
216         if (ordinal >= exports->NumberOfFunctions)
217         {
218             TRACE("     ordinal %ld out of range!\n", ordinal + exports->Base );
219             return NULL;
220         }
221         addr = function[ordinal];
222         if (!addr) return NULL;
223         if ((addr < rva_start) || (addr >= rva_end))
224         {
225             FARPROC proc = RVA(addr);
226             if (snoop)
227             {
228                 if (!ename) ename = "@";
229                 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
230             }
231             return proc;
232         }
233         else  /* forward entry point */
234         {
235                 WINE_MODREF *wm_fw;
236                 FARPROC proc;
237                 char *forward = RVA(addr);
238                 char module[256];
239                 char *end = strchr(forward, '.');
240
241                 if (!end) return NULL;
242                 if (end - forward >= sizeof(module)) return NULL;
243                 memcpy( module, forward, end - forward );
244                 module[end-forward] = 0;
245                 if (!(wm_fw = MODULE_FindModule( module )))
246                 {
247                     ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
248                     return NULL;
249                 }
250                 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, snoop )))
251                     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 );
252                 return proc;
253         }
254 }
255
256 /****************************************************************
257  *      PE_fixup_imports
258  */
259 DWORD PE_fixup_imports( WINE_MODREF *wm )
260 {
261     IMAGE_IMPORT_DESCRIPTOR     *pe_imp;
262     unsigned int load_addr      = wm->module;
263     int                         i,characteristics_detection=1;
264     IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
265
266     /* first, count the number of imported non-internal modules */
267     pe_imp = imports;
268     if (!pe_imp) return 0;
269
270     /* OK, now dump the import list */
271     TRACE("Dumping imports list\n");
272
273     /* We assume that we have at least one import with !0 characteristics and
274      * detect broken imports with all characteristics 0 (notably Borland) and
275      * switch the detection off for them.
276      */
277     for (i = 0; pe_imp->Name ; pe_imp++) {
278         if (!i && !pe_imp->u.Characteristics)
279                 characteristics_detection = 0;
280         if (characteristics_detection && !pe_imp->u.Characteristics)
281                 break;
282         i++;
283     }
284     if (!i) return 0;  /* no imports */
285
286     /* Allocate module dependency list */
287     wm->nDeps = i;
288     wm->deps  = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
289
290     /* load the imported modules. They are automatically 
291      * added to the modref list of the process.
292      */
293  
294     for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
295         WINE_MODREF             *wmImp;
296         IMAGE_IMPORT_BY_NAME    *pe_name;
297         PIMAGE_THUNK_DATA       import_list,thunk_list;
298         char                    *name = (char *) RVA(pe_imp->Name);
299
300         if (characteristics_detection && !pe_imp->u.Characteristics)
301                 break;
302
303         wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
304         if (!wmImp) {
305             ERR_(module)("Module (file) %s (which is needed by %s) not found\n", name, wm->filename);
306             return 1;
307         }
308         wm->deps[i++] = wmImp;
309
310         /* FIXME: forwarder entries ... */
311
312         if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
313             TRACE("Microsoft style imports used\n");
314             import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
315             thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
316
317             while (import_list->u1.Ordinal) {
318                 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
319                     int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
320
321                     TRACE("--- Ordinal %s,%d\n", name, ordinal);
322                     thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
323                         wmImp->module, (LPCSTR)ordinal, TRUE
324                     );
325                     if (!thunk_list->u1.Function) {
326                         ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
327                                 name, ordinal, wm->filename );
328                         thunk_list->u1.Function = (PDWORD)0xdeadbeef;
329                     }
330                 } else {                /* import by name */
331                     pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
332                     TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
333                     thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
334                         wmImp->module, pe_name->Name, TRUE
335                     );
336                     if (!thunk_list->u1.Function) {
337                         ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
338                                 name,pe_name->Hint,pe_name->Name,wm->filename);
339                         thunk_list->u1.Function = (PDWORD)0xdeadbeef;
340                     }
341                 }
342                 import_list++;
343                 thunk_list++;
344             }
345         } else {        /* Borland style */
346             TRACE("Borland style imports used\n");
347             thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
348             while (thunk_list->u1.Ordinal) {
349                 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
350                     /* not sure about this branch, but it seems to work */
351                     int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
352
353                     TRACE("--- Ordinal %s.%d\n",name,ordinal);
354                     thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
355                         wmImp->module, (LPCSTR) ordinal, TRUE
356                     );
357                     if (!thunk_list->u1.Function) {
358                         ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
359                                 name,ordinal, wm->filename);
360                         thunk_list->u1.Function = (PDWORD)0xdeadbeef;
361                     }
362                 } else {
363                     pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
364                     TRACE("--- %s %s.%d\n",
365                                   pe_name->Name,name,pe_name->Hint);
366                     thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
367                         wmImp->module, pe_name->Name, TRUE
368                     );
369                     if (!thunk_list->u1.Function) {
370                         ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
371                                 name, pe_name->Hint, pe_name->Name, wm->filename);
372                         thunk_list->u1.Function = (PDWORD)0xdeadbeef;
373                     }
374                 }
375                 thunk_list++;
376             }
377         }
378     }
379     return 0;
380 }
381
382 /***********************************************************************
383  *           do_relocations
384  *
385  * Apply the relocations to a mapped PE image
386  */
387 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
388 {
389     const IMAGE_DATA_DIRECTORY *dir;
390     const IMAGE_BASE_RELOCATION *rel;
391     int delta = base - (char *)nt->OptionalHeader.ImageBase;
392
393     dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
394     rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
395
396     WARN("Info: base relocations needed for %s\n", filename);
397     if (!dir->VirtualAddress || !dir->Size)
398     {
399         if (nt->OptionalHeader.ImageBase == 0x400000)
400             ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
401         ERR( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
402              filename,
403              (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
404              "stripped during link" : "unknown reason" );
405         return 0;
406     }
407
408     /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
409      *        really make sure that the *new* base address is also > 2GB.
410      *        Some DLLs really check the MSB of the module handle :-/
411      */
412     if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
413         ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
414
415     for ( ; ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
416           rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock))
417     {
418         char *page = base + rel->VirtualAddress;
419         WORD *TypeOffset = (WORD *)(rel + 1);
420         int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
421
422         if (!count) continue;
423
424         /* sanity checks */
425         if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
426             page > base + nt->OptionalHeader.SizeOfImage)
427         {
428             ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
429                          rel, rel->VirtualAddress, rel->SizeOfBlock,
430                          base, dir->VirtualAddress, dir->Size );
431             return 0;
432         }
433
434         TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
435
436         /* patching in reverse order */
437         for (i = 0 ; i < count; i++)
438         {
439             int offset = TypeOffset[i] & 0xFFF;
440             int type = TypeOffset[i] >> 12;
441             switch(type)
442             {
443             case IMAGE_REL_BASED_ABSOLUTE:
444                 break;
445             case IMAGE_REL_BASED_HIGH:
446                 *(short*)(page+offset) += HIWORD(delta);
447                 break;
448             case IMAGE_REL_BASED_LOW:
449                 *(short*)(page+offset) += LOWORD(delta);
450                 break;
451             case IMAGE_REL_BASED_HIGHLOW:
452                 *(int*)(page+offset) += delta;
453                 /* FIXME: if this is an exported address, fire up enhanced logic */
454                 break;
455             default:
456                 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
457                 break;
458             }
459         }
460     }
461     return 1;
462 }
463
464
465 /**********************************************************************
466  *                      PE_LoadImage
467  * Load one PE format DLL/EXE into memory
468  * 
469  * Unluckily we can't just mmap the sections where we want them, for 
470  * (at least) Linux does only support offsets which are page-aligned.
471  *
472  * BUT we have to map the whole image anyway, for Win32 programs sometimes
473  * want to access them. (HMODULE points to the start of it)
474  */
475 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
476 {
477     IMAGE_NT_HEADERS *nt;
478     HMODULE hModule;
479     HANDLE mapping;
480     void *base;
481
482     TRACE_(module)( "loading %s\n", filename );
483
484     mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
485     if (!mapping) return 0;
486     base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
487     CloseHandle( mapping );
488     if (!base) return 0;
489
490     hModule = (HMODULE)base;
491
492     /* perform base relocation, if necessary */
493
494     nt = PE_HEADER( hModule );
495     if (hModule != nt->OptionalHeader.ImageBase)
496     {
497         if (!do_relocations( base, nt, filename ))
498         {
499             UnmapViewOfFile( base );
500             SetLastError( ERROR_BAD_EXE_FORMAT );
501             return 0;
502         }
503     }
504
505     /* virus check */
506
507     if (nt->OptionalHeader.AddressOfEntryPoint)
508     {
509         int i;
510         IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
511                                                             nt->FileHeader.SizeOfOptionalHeader);
512         for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
513         {
514             if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
515                 continue;
516             if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
517                 break;
518         }
519         if (i == nt->FileHeader.NumberOfSections)
520             MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
521                     "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
522                     nt->OptionalHeader.AddressOfEntryPoint );
523     }
524
525     return hModule;
526 }
527
528 /**********************************************************************
529  *                 PE_CreateModule
530  *
531  * Create WINE_MODREF structure for loaded HMODULE32, link it into
532  * process modref_list, and fixup all imports.
533  *
534  * Note: hModule must point to a correctly allocated PE image,
535  *       with base relocations applied; the 16-bit dummy module
536  *       associated to hModule must already exist.
537  *
538  * Note: This routine must always be called in the context of the
539  *       process that is to own the module to be created.
540  *
541  * Note: Assumes that the process critical section is held
542  */
543 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
544                               HANDLE hFile, BOOL builtin )
545 {
546     DWORD load_addr = (DWORD)hModule;  /* for RVA */
547     IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
548     IMAGE_DATA_DIRECTORY *dir;
549     IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
550     WINE_MODREF *wm;
551     HMODULE16 hModule16;
552
553     /* Retrieve DataDirectory entries */
554
555     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
556     if (dir->Size)
557         pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
558
559     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
560     if (dir->Size) FIXME("Exception directory ignored\n" );
561
562     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
563     if (dir->Size) FIXME("Security directory ignored\n" );
564
565     /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
566     /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
567
568     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
569     if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
570
571     /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
572
573     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
574     if (dir->Size) FIXME("Load Configuration directory ignored\n" );
575
576     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
577     if (dir->Size) TRACE("Bound Import directory ignored\n" );
578
579     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
580     if (dir->Size) TRACE("Import Address Table directory ignored\n" );
581
582     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
583     if (dir->Size)
584     {
585                 TRACE("Delayed import, stub calls LoadLibrary\n" );
586                 /*
587                  * Nothing to do here.
588                  */
589
590 #ifdef ImgDelayDescr
591                 /*
592                  * This code is useful to observe what the heck is going on.
593                  */
594                 {
595                 ImgDelayDescr *pe_delay = NULL;
596         pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
597         TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
598         TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
599         TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
600         TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
601         TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
602         TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
603         TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
604         TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
605         }
606 #endif /* ImgDelayDescr */
607         }
608
609     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
610     if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
611
612     dir = nt->OptionalHeader.DataDirectory+15;
613     if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
614
615     /* Create 16-bit dummy module */
616
617     if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
618     {
619         SetLastError( (DWORD)hModule16 );       /* This should give the correct error */
620         return NULL;
621     }
622
623     /* Allocate and fill WINE_MODREF */
624
625     if (!(wm = MODULE_AllocModRef( hModule, filename )))
626     {
627         FreeLibrary16( hModule16 );
628         return NULL;
629     }
630     wm->hDummyMod = hModule16;
631
632     if ( builtin ) 
633     {
634         NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
635         pModule->flags |= NE_FFLAGS_BUILTIN;
636         wm->flags |= WINE_MODREF_INTERNAL;
637     }
638     else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
639         wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
640
641     wm->find_export = PE_FindExportedFunction;
642
643     /* Dump Exports */
644
645     if ( pe_export )
646         dump_exports( hModule );
647
648     /* Fixup Imports */
649
650     if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
651         PE_fixup_imports( wm ))
652     {
653         /* remove entry from modref chain */
654
655         if ( !wm->prev )
656             MODULE_modref_list = wm->next;
657         else
658             wm->prev->next = wm->next;
659
660         if ( wm->next ) wm->next->prev = wm->prev;
661         wm->next = wm->prev = NULL;
662
663         /* FIXME: there are several more dangling references
664          * left. Including dlls loaded by this dll before the
665          * failed one. Unrolling is rather difficult with the
666          * current structure and we can leave it them lying
667          * around with no problems, so we don't care.
668          * As these might reference our wm, we don't free it.
669          */
670          return NULL;
671     }
672
673     if (!builtin && pe_export)
674         SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
675
676     /* Send DLL load event */
677     /* we don't need to send a dll event for the main exe */
678
679     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
680     {
681         if (hFile)
682         {
683             UINT drive_type = GetDriveTypeA( wm->short_filename );
684             /* don't keep the file handle open on removable media */
685             if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
686         }
687         SERVER_START_REQ( load_dll )
688         {
689             req->handle     = hFile;
690             req->base       = (void *)hModule;
691             req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
692             req->dbg_size   = nt->FileHeader.NumberOfSymbols;
693             req->name       = &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 new 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 }
826