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