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