Clear the remainder of the page when mapping a section whose size on
[wine] / loader / pe_image.c
1 /* 
2  *  Copyright   1994    Eric Youndale & Erik Bos
3  *  Copyright   1995    Martin von Löwis
4  *  Copyright   1996-98 Marcus Meissner
5  *
6  *      based on Eric Youndale's pe-test and:
7  *
8  *      ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
9  * make that:
10  *      ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
11  */
12 /* Notes:
13  * Before you start changing something in this file be aware of the following:
14  *
15  * - There are several functions called recursively. In a very subtle and 
16  *   obscure way. DLLs can reference each other recursively etc.
17  * - If you want to enhance, speed up or clean up something in here, think
18  *   twice WHY it is implemented in that strange way. There is usually a reason.
19  *   Though sometimes it might just be lazyness ;)
20  * - In PE_MapImage, right before fixup_imports() all external and internal 
21  *   state MUST be correct since this function can be called with the SAME image
22  *   AGAIN. (Thats recursion for you.) That means MODREF.module and
23  *   NE_MODULE.module32.
24  * - Sometimes, we can't use Linux mmap() to mmap() the images directly.
25  *
26  *   The problem is, that there is not direct 1:1 mapping from a diskimage and
27  *   a memoryimage. The headers at the start are mapped linear, but the sections
28  *   are not. Older x86 pe binaries are 512 byte aligned in file and 4096 byte
29  *   aligned in memory. Linux likes them 4096 byte aligned in memory (due to
30  *   x86 pagesize, this cannot be fixed without a rather large kernel rewrite)
31  *   and 'blocksize' file-aligned (offsets). Since we have 512/1024/2048 (CDROM)
32  *   and other byte blocksizes, we can't always do this.  We *can* do this for
33  *   newer pe binaries produced by MSVC 5 and later, since they are also aligned
34  *   to 4096 byte boundaries on disk.
35  */
36
37 #include "config.h"
38
39 #include <errno.h>
40 #include <assert.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #ifdef HAVE_SYS_MMAN_H
47 #include <sys/mman.h>
48 #endif
49 #include "windef.h"
50 #include "winbase.h"
51 #include "winerror.h"
52 #include "callback.h"
53 #include "file.h"
54 #include "heap.h"
55 #include "neexe.h"
56 #include "process.h"
57 #include "thread.h"
58 #include "pe_image.h"
59 #include "module.h"
60 #include "global.h"
61 #include "task.h"
62 #include "snoop.h"
63 #include "server.h"
64 #include "debugtools.h"
65
66 DEFAULT_DEBUG_CHANNEL(win32)
67 DECLARE_DEBUG_CHANNEL(delayhlp)
68 DECLARE_DEBUG_CHANNEL(fixup)
69 DECLARE_DEBUG_CHANNEL(module)
70 DECLARE_DEBUG_CHANNEL(relay)
71 DECLARE_DEBUG_CHANNEL(segment)
72
73
74 /* convert PE image VirtualAddress to Real Address */
75 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
76
77 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
78
79 void dump_exports( HMODULE hModule )
80
81   char          *Module;
82   int           i, j;
83   u_short       *ordinal;
84   u_long        *function,*functions;
85   u_char        **name;
86   unsigned int load_addr = hModule;
87
88   DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
89                    .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
90   DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
91                    .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
92   IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
93
94   Module = (char*)RVA(pe_exports->Name);
95   TRACE("*******EXPORT DATA*******\n");
96   TRACE("Module name is %s, %ld functions, %ld names\n", 
97         Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
98
99   ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
100   functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
101   name=(u_char**) RVA(pe_exports->AddressOfNames);
102
103   TRACE(" Ord    RVA     Addr   Name\n" );
104   for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
105   {
106       if (!*function) continue;  /* No such function */
107       if (TRACE_ON(win32))
108       {
109         DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
110         /* Check if we have a name for it */
111         for (j = 0; j < pe_exports->NumberOfNames; j++)
112           if (ordinal[j] == i)
113           {
114               DPRINTF( "  %s", (char*)RVA(name[j]) );
115               break;
116           }
117         if ((*function >= rva_start) && (*function <= rva_end))
118           DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
119         DPRINTF("\n");
120       }
121   }
122 }
123
124 /* Look up the specified function or ordinal in the exportlist:
125  * If it is a string:
126  *      - look up the name in the Name list. 
127  *      - look up the ordinal with that index.
128  *      - use the ordinal as offset into the functionlist
129  * If it is a ordinal:
130  *      - use ordinal-pe_export->Base as offset into the functionlist
131  */
132 FARPROC PE_FindExportedFunction( 
133         WINE_MODREF *wm,        /* [in] WINE modreference */
134         LPCSTR funcName,        /* [in] function name */
135         BOOL snoop )
136 {
137         u_short                         * ordinals;
138         u_long                          * function;
139         u_char                          ** name, *ename = NULL;
140         int                             i, ordinal;
141         PE_MODREF                       *pem = &(wm->binfmt.pe);
142         IMAGE_EXPORT_DIRECTORY          *exports = pem->pe_export;
143         unsigned int                    load_addr = wm->module;
144         u_long                          rva_start, rva_end, addr;
145         char                            * forward;
146
147         if (HIWORD(funcName))
148                 TRACE("(%s)\n",funcName);
149         else
150                 TRACE("(%d)\n",(int)funcName);
151         if (!exports) {
152                 /* Not a fatal problem, some apps do
153                  * GetProcAddress(0,"RegisterPenApp") which triggers this
154                  * case.
155                  */
156                 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,pem);
157                 return NULL;
158         }
159         ordinals= (u_short*)  RVA(exports->AddressOfNameOrdinals);
160         function= (u_long*)   RVA(exports->AddressOfFunctions);
161         name    = (u_char **) RVA(exports->AddressOfNames);
162         forward = NULL;
163         rva_start = PE_HEADER(wm->module)->OptionalHeader
164                 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
165         rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
166                 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
167
168         if (HIWORD(funcName))
169         {
170             /* first try a binary search */
171             int min = 0, max = exports->NumberOfNames - 1;
172             while (min <= max)
173             {
174                 int res, pos = (min + max) / 2;
175                 ename = RVA(name[pos]);
176                 if (!(res = strcmp( ename, funcName )))
177                 {
178                     ordinal = ordinals[pos];
179                     goto found;
180                 }
181                 if (res > 0) max = pos - 1;
182                 else min = pos + 1;
183             }
184             /* now try a linear search in case the names aren't sorted properly */
185             for (i = 0; i < exports->NumberOfNames; i++)
186             {
187                 ename = RVA(name[i]);
188                 if (!strcmp( ename, funcName ))
189                 {
190                     ERR( "%s.%s required a linear search\n", wm->modname, funcName );
191                     ordinal = ordinals[i];
192                     goto found;
193                 }
194             }
195             return NULL;
196         }
197         else  /* find by ordinal */
198         {
199             ordinal = LOWORD(funcName) - exports->Base;
200             if (snoop && name)  /* need to find a name for it */
201             {
202                 for (i = 0; i < exports->NumberOfNames; i++)
203                     if (ordinals[i] == ordinal)
204                     {
205                         ename = RVA(name[i]);
206                         break;
207                     }
208             }
209         }
210
211  found:
212         if (ordinal >= exports->NumberOfFunctions)
213         {
214             TRACE("     ordinal %ld out of range!\n", ordinal + exports->Base );
215             return NULL;
216         }
217         addr = function[ordinal];
218         if (!addr) return NULL;
219         if ((addr < rva_start) || (addr >= rva_end))
220         {
221             FARPROC proc = RVA(addr);
222             if (snoop)
223             {
224                 if (!ename) ename = "@";
225                 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
226             }
227             return proc;
228         }
229         else  /* forward entry point */
230         {
231                 WINE_MODREF *wm;
232                 char *forward = RVA(addr);
233                 char module[256];
234                 char *end = strchr(forward, '.');
235
236                 if (!end) return NULL;
237                 if (end - forward >= sizeof(module)) return NULL;
238                 memcpy( module, forward, end - forward );
239                 module[end-forward] = 0;
240                 if (!(wm = MODULE_FindModule( module )))
241                 {
242                     ERR("module not found for forward '%s'\n", forward );
243                     return NULL;
244                 }
245                 return MODULE_GetProcAddress( wm->module, end + 1, snoop );
246         }
247 }
248
249 DWORD fixup_imports( WINE_MODREF *wm )
250 {
251     IMAGE_IMPORT_DESCRIPTOR     *pe_imp;
252     PE_MODREF                   *pem;
253     unsigned int load_addr      = wm->module;
254     int                         i,characteristics_detection=1;
255     char                        *modname;
256     
257     assert(wm->type==MODULE32_PE);
258     pem = &(wm->binfmt.pe);
259     if (pem->pe_export)
260         modname = (char*) RVA(pem->pe_export->Name);
261     else
262         modname = "<unknown>";
263
264     /* OK, now dump the import list */
265     TRACE("Dumping imports list\n");
266
267     /* first, count the number of imported non-internal modules */
268     pe_imp = pem->pe_import;
269     if (!pe_imp) return 0;
270
271     /* We assume that we have at least one import with !0 characteristics and
272      * detect broken imports with all characteristsics 0 (notably Borland) and
273      * switch the detection off for them.
274      */
275     for (i = 0; pe_imp->Name ; pe_imp++) {
276         if (!i && !pe_imp->u.Characteristics)
277                 characteristics_detection = 0;
278         if (characteristics_detection && !pe_imp->u.Characteristics)
279                 break;
280         i++;
281     }
282     if (!i) return 0;  /* no imports */
283
284     /* Allocate module dependency list */
285     wm->nDeps = i;
286     wm->deps  = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
287
288     /* load the imported modules. They are automatically 
289      * added to the modref list of the process.
290      */
291  
292     for (i = 0, pe_imp = pem->pe_import; pe_imp->Name ; pe_imp++) {
293         WINE_MODREF             *wmImp;
294         IMAGE_IMPORT_BY_NAME    *pe_name;
295         PIMAGE_THUNK_DATA       import_list,thunk_list;
296         char                    *name = (char *) RVA(pe_imp->Name);
297
298         if (characteristics_detection && !pe_imp->u.Characteristics)
299                 break;
300
301         wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
302         if (!wmImp) {
303             ERR_(module)("Module %s not found\n", name);
304             return 1;
305         }
306         wm->deps[i++] = wmImp;
307
308         /* FIXME: forwarder entries ... */
309
310         if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
311             TRACE("Microsoft style imports used\n");
312             import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
313             thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
314
315             while (import_list->u1.Ordinal) {
316                 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
317                     int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
318
319                     TRACE("--- Ordinal %s,%d\n", name, ordinal);
320                     thunk_list->u1.Function=MODULE_GetProcAddress(
321                         wmImp->module, (LPCSTR)ordinal, TRUE
322                     );
323                     if (!thunk_list->u1.Function) {
324                         ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
325                                 name, ordinal);
326                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
327                     }
328                 } else {                /* import by name */
329                     pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
330                     TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
331                     thunk_list->u1.Function=MODULE_GetProcAddress(
332                         wmImp->module, pe_name->Name, TRUE
333                     );
334                     if (!thunk_list->u1.Function) {
335                         ERR("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
336                                 name,pe_name->Hint,pe_name->Name);
337                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
338                     }
339                 }
340                 import_list++;
341                 thunk_list++;
342             }
343         } else {        /* Borland style */
344             TRACE("Borland style imports used\n");
345             thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
346             while (thunk_list->u1.Ordinal) {
347                 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
348                     /* not sure about this branch, but it seems to work */
349                     int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
350
351                     TRACE("--- Ordinal %s.%d\n",name,ordinal);
352                     thunk_list->u1.Function=MODULE_GetProcAddress(
353                         wmImp->module, (LPCSTR) ordinal, TRUE
354                     );
355                     if (!thunk_list->u1.Function) {
356                         ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
357                                 name,ordinal);
358                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
359                     }
360                 } else {
361                     pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
362                     TRACE("--- %s %s.%d\n",
363                                   pe_name->Name,name,pe_name->Hint);
364                     thunk_list->u1.Function=MODULE_GetProcAddress(
365                         wmImp->module, pe_name->Name, TRUE
366                     );
367                     if (!thunk_list->u1.Function) {
368                         ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
369                                 name, pe_name->Hint);
370                         thunk_list->u1.Function = (FARPROC)0xdeadbeef;
371                     }
372                 }
373                 thunk_list++;
374             }
375         }
376     }
377     return 0;
378 }
379
380 static int calc_vma_size( HMODULE hModule )
381 {
382     int i,vma_size = 0;
383     IMAGE_SECTION_HEADER *pe_seg = PE_SECTIONS(hModule);
384
385     TRACE("Dump of segment table\n");
386     TRACE("   Name    VSz  Vaddr     SzRaw   Fileadr  *Reloc *Lineum #Reloc #Linum Char\n");
387     for (i = 0; i< PE_HEADER(hModule)->FileHeader.NumberOfSections; i++)
388     {
389         TRACE("%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n", 
390                       pe_seg->Name, 
391                       pe_seg->Misc.VirtualSize,
392                       pe_seg->VirtualAddress,
393                       pe_seg->SizeOfRawData,
394                       pe_seg->PointerToRawData,
395                       pe_seg->PointerToRelocations,
396                       pe_seg->PointerToLinenumbers,
397                       pe_seg->NumberOfRelocations,
398                       pe_seg->NumberOfLinenumbers,
399                       pe_seg->Characteristics);
400         vma_size=max(vma_size, pe_seg->VirtualAddress+pe_seg->SizeOfRawData);
401         vma_size=max(vma_size, pe_seg->VirtualAddress+pe_seg->Misc.VirtualSize);
402         pe_seg++;
403     }
404     return vma_size;
405 }
406
407 static void do_relocations( unsigned int load_addr, IMAGE_BASE_RELOCATION *r )
408 {
409     int delta = load_addr - PE_HEADER(load_addr)->OptionalHeader.ImageBase;
410     int hdelta = (delta >> 16) & 0xFFFF;
411     int ldelta = delta & 0xFFFF;
412
413         if(delta == 0)
414                 /* Nothing to do */
415                 return;
416         while(r->VirtualAddress)
417         {
418                 char *page = (char*) RVA(r->VirtualAddress);
419                 int count = (r->SizeOfBlock - 8)/2;
420                 int i;
421                 TRACE_(fixup)("%x relocations for page %lx\n",
422                         count, r->VirtualAddress);
423                 /* patching in reverse order */
424                 for(i=0;i<count;i++)
425                 {
426                         int offset = r->TypeOffset[i] & 0xFFF;
427                         int type = r->TypeOffset[i] >> 12;
428                         TRACE_(fixup)("patching %x type %x\n", offset, type);
429                         switch(type)
430                         {
431                         case IMAGE_REL_BASED_ABSOLUTE: break;
432                         case IMAGE_REL_BASED_HIGH:
433                                 *(short*)(page+offset) += hdelta;
434                                 break;
435                         case IMAGE_REL_BASED_LOW:
436                                 *(short*)(page+offset) += ldelta;
437                                 break;
438                         case IMAGE_REL_BASED_HIGHLOW:
439                                 *(int*)(page+offset) += delta;
440                                 /* FIXME: if this is an exported address, fire up enhanced logic */
441                                 break;
442                         case IMAGE_REL_BASED_HIGHADJ:
443                                 FIXME("Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
444                                 break;
445                         case IMAGE_REL_BASED_MIPS_JMPADDR:
446                                 FIXME("Is this a MIPS machine ???\n");
447                                 break;
448                         default:
449                                 FIXME("Unknown fixup type\n");
450                                 break;
451                         }
452                 }
453                 r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
454         }
455 }
456                 
457
458         
459         
460
461 /**********************************************************************
462  *                      PE_LoadImage
463  * Load one PE format DLL/EXE into memory
464  * 
465  * Unluckily we can't just mmap the sections where we want them, for 
466  * (at least) Linux does only support offsets which are page-aligned.
467  *
468  * BUT we have to map the whole image anyway, for Win32 programs sometimes
469  * want to access them. (HMODULE32 point to the start of it)
470  */
471 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, WORD *version )
472 {
473     HMODULE     hModule;
474     HANDLE      mapping;
475
476     IMAGE_NT_HEADERS *nt;
477     IMAGE_SECTION_HEADER *pe_sec;
478     IMAGE_DATA_DIRECTORY *dir;
479     BY_HANDLE_FILE_INFORMATION bhfi;
480     int i, rawsize, lowest_va, vma_size, file_size = 0;
481     DWORD load_addr = 0, aoep, reloc = 0;
482     struct get_read_fd_request *req = get_req_buffer();
483     int unix_handle = -1;
484     int page_size = VIRTUAL_GetPageSize();
485
486     /* Retrieve file size */
487     if ( GetFileInformationByHandle( hFile, &bhfi ) ) 
488         file_size = bhfi.nFileSizeLow; /* FIXME: 64 bit */
489
490     /* Map the PE file somewhere */
491     mapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY | SEC_COMMIT,
492                                     0, 0, NULL );
493     if (!mapping)
494     {
495         WARN("CreateFileMapping error %ld\n", GetLastError() );
496         return 0;
497     }
498     hModule = (HMODULE)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
499     CloseHandle( mapping );
500     if (!hModule)
501     {
502         WARN("MapViewOfFile error %ld\n", GetLastError() );
503         return 0;
504     }
505     if ( *(WORD*)hModule !=IMAGE_DOS_SIGNATURE)
506     {
507         WARN("%s image doesn't have DOS signature, but 0x%04x\n", filename,*(WORD*)hModule);
508         goto error;
509     }
510
511     nt = PE_HEADER( hModule );
512
513     /* Check signature */
514     if ( nt->Signature != IMAGE_NT_SIGNATURE )
515     {
516         WARN("%s image doesn't have PE signature, but 0x%08lx\n", filename, nt->Signature );
517         goto error;
518     }
519
520     /* Check architecture */
521     if ( nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386 )
522     {
523         MESSAGE("Trying to load PE image for unsupported architecture (");
524         switch (nt->FileHeader.Machine)
525         {
526         case IMAGE_FILE_MACHINE_UNKNOWN: MESSAGE("Unknown"); break;
527         case IMAGE_FILE_MACHINE_I860:    MESSAGE("I860"); break;
528         case IMAGE_FILE_MACHINE_R3000:   MESSAGE("R3000"); break;
529         case IMAGE_FILE_MACHINE_R4000:   MESSAGE("R4000"); break;
530         case IMAGE_FILE_MACHINE_R10000:  MESSAGE("R10000"); break;
531         case IMAGE_FILE_MACHINE_ALPHA:   MESSAGE("Alpha"); break;
532         case IMAGE_FILE_MACHINE_POWERPC: MESSAGE("PowerPC"); break;
533         default: MESSAGE("Unknown-%04x", nt->FileHeader.Machine); break;
534         }
535         MESSAGE(")\n");
536         goto error;
537     }
538
539     /* Find out how large this executeable should be */
540     pe_sec = PE_SECTIONS( hModule );
541     rawsize = 0; lowest_va = 0x10000;
542     for (i = 0; i < nt->FileHeader.NumberOfSections; i++) 
543     {
544         if (lowest_va > pe_sec[i].VirtualAddress)
545            lowest_va = pe_sec[i].VirtualAddress;
546         if (pe_sec[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
547             continue;
548         if (pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData > rawsize)
549             rawsize = pe_sec[i].PointerToRawData+pe_sec[i].SizeOfRawData;
550     }
551  
552     /* Check file size */
553     if ( file_size && file_size < rawsize )
554     {
555         ERR("PE module is too small (header: %d, filesize: %d), "
556                     "probably truncated download?\n", 
557                     rawsize, file_size );
558         goto error;
559     }
560
561     /* Check entrypoint address */
562     aoep = nt->OptionalHeader.AddressOfEntryPoint;
563     if (aoep && (aoep < lowest_va))
564         FIXME("VIRUS WARNING: '%s' has an invalid entrypoint (0x%08lx) "
565                       "below the first virtual address (0x%08x) "
566                       "(possibly infected by Tchernobyl/SpaceFiller virus)!\n",
567                        filename, aoep, lowest_va );
568
569
570     /* FIXME:  Hack!  While we don't really support shared sections yet,
571      *         this checks for those special cases where the whole DLL
572      *         consists only of shared sections and is mapped into the
573      *         shared address space > 2GB.  In this case, we assume that
574      *         the module got mapped at its base address. Thus we simply
575      *         check whether the module has actually been mapped there
576      *         and use it, if so.  This is needed to get Win95 USER32.DLL
577      *         to work (until we support shared sections properly).
578      */
579
580     if ( nt->OptionalHeader.ImageBase & 0x80000000 )
581     {
582         HMODULE sharedMod = (HMODULE)nt->OptionalHeader.ImageBase; 
583         IMAGE_NT_HEADERS *sharedNt = (PIMAGE_NT_HEADERS)
584                ( (LPBYTE)sharedMod + ((LPBYTE)nt - (LPBYTE)hModule) );
585
586         /* Well, this check is not really comprehensive, 
587            but should be good enough for now ... */
588         if (    !IsBadReadPtr( (LPBYTE)sharedMod, sizeof(IMAGE_DOS_HEADER) )
589              && memcmp( (LPBYTE)sharedMod, (LPBYTE)hModule, sizeof(IMAGE_DOS_HEADER) ) == 0
590              && !IsBadReadPtr( sharedNt, sizeof(IMAGE_NT_HEADERS) )
591              && memcmp( sharedNt, nt, sizeof(IMAGE_NT_HEADERS) ) == 0 )
592         {
593             UnmapViewOfFile( (LPVOID)hModule );
594             return sharedMod;
595         }
596     }
597
598
599     /* Allocate memory for module */
600     load_addr = nt->OptionalHeader.ImageBase;
601     vma_size = calc_vma_size( hModule );
602
603     load_addr = (DWORD)VirtualAlloc( (void*)load_addr, vma_size,
604                                      MEM_RESERVE | MEM_COMMIT,
605                                      PAGE_EXECUTE_READWRITE );
606     if (load_addr == 0) 
607     {
608         /* We need to perform base relocations */
609         FIXME("We need to perform base relocations for %s\n", filename);
610         dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BASERELOC;
611         if (dir->Size)
612             reloc = dir->VirtualAddress;
613         else 
614         {
615             FIXME( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
616                    filename,
617                    (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
618                    "stripped during link" : "unknown reason" );
619             goto error;
620         }
621
622         /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
623          *        really make sure that the *new* base address is also > 2GB.
624          *        Some DLLs really check the MSB of the module handle :-/
625          */
626         if ( nt->OptionalHeader.ImageBase & 0x80000000 )
627             ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
628
629         load_addr = (DWORD)VirtualAlloc( NULL, vma_size,
630                                          MEM_RESERVE | MEM_COMMIT,
631                                          PAGE_EXECUTE_READWRITE );
632         if (!load_addr) {
633             FIXME_(win32)(
634                    "FATAL: Couldn't load module %s (out of memory, %d needed)!\n", filename, vma_size);
635             goto error;
636         }
637     }
638
639     TRACE("Load addr is %lx (base %lx), range %x\n",
640           load_addr, nt->OptionalHeader.ImageBase, vma_size );
641     TRACE_(segment)("Loading %s at %lx, range %x\n",
642                     filename, load_addr, vma_size );
643
644 #if 0
645     /* Store the NT header at the load addr */
646     *(PIMAGE_DOS_HEADER)load_addr = *(PIMAGE_DOS_HEADER)hModule;
647     *PE_HEADER( load_addr ) = *nt;
648     memcpy( PE_SECTIONS(load_addr), PE_SECTIONS(hModule),
649             sizeof(IMAGE_SECTION_HEADER) * nt->FileHeader.NumberOfSections );
650
651     /* Copies all stuff up to the first section. Including win32 viruses. */
652     memcpy( load_addr, hModule, lowest_fa );
653 #endif
654
655     req->handle = hFile;
656     server_call_fd( REQ_GET_READ_FD, -1, &unix_handle );
657     if (unix_handle == -1) goto error;
658
659     /* Map the header */
660     if (FILE_dommap( unix_handle, (void *)load_addr, 0, nt->OptionalHeader.SizeOfHeaders,
661                      0, 0, PROT_EXEC | PROT_WRITE | PROT_READ,
662                      MAP_PRIVATE | MAP_FIXED ) != (void*)load_addr)
663     {
664         ERR_(win32)( "Critical Error: failed to map PE header to necessary address.\n");        
665         goto error;
666     }
667
668     /* Copy sections into module image */
669     pe_sec = PE_SECTIONS( hModule );
670     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, pe_sec++)
671     {
672         if (!pe_sec->SizeOfRawData || !pe_sec->PointerToRawData) continue;
673         TRACE("%s: mmaping section %s at %p off %lx size %lx/%lx\n",
674               filename, pe_sec->Name, (void*)RVA(pe_sec->VirtualAddress),
675               pe_sec->PointerToRawData, pe_sec->SizeOfRawData, pe_sec->Misc.VirtualSize );
676         if (FILE_dommap( unix_handle, (void*)RVA(pe_sec->VirtualAddress),
677                          0, pe_sec->SizeOfRawData, 0, pe_sec->PointerToRawData,
678                          PROT_EXEC | PROT_WRITE | PROT_READ,
679                          MAP_PRIVATE | MAP_FIXED ) != (void*)RVA(pe_sec->VirtualAddress))
680         {
681             /* We failed to map to the right place (huh?) */
682             ERR_(win32)( "Critical Error: failed to map PE section to necessary address.\n");
683             goto error;
684         }
685         if ((pe_sec->SizeOfRawData < pe_sec->Misc.VirtualSize) &&
686             (pe_sec->SizeOfRawData & (page_size-1)))
687         {
688             DWORD end = (pe_sec->SizeOfRawData & ~(page_size-1)) + page_size;
689             if (end > pe_sec->Misc.VirtualSize) end = pe_sec->Misc.VirtualSize;
690             TRACE("clearing %p - %p\n",
691                   RVA(pe_sec->VirtualAddress) + pe_sec->SizeOfRawData,
692                   RVA(pe_sec->VirtualAddress) + end );
693             memset( (char*)RVA(pe_sec->VirtualAddress) + pe_sec->SizeOfRawData, 0,
694                     end - pe_sec->SizeOfRawData );
695         }
696     }
697
698     /* Perform base relocation, if necessary */
699     if ( reloc )
700         do_relocations( load_addr, (IMAGE_BASE_RELOCATION *)RVA(reloc) );
701
702     /* Get expected OS / Subsystem version */
703     *version =   ( (nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 )
704                |   (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
705
706     /* We don't need the orignal mapping any more */
707     UnmapViewOfFile( (LPVOID)hModule );
708     return (HMODULE)load_addr;
709
710 error:
711     if (unix_handle != -1) close( unix_handle );
712     if (load_addr) VirtualFree( (LPVOID)load_addr, 0, MEM_RELEASE );
713     UnmapViewOfFile( (LPVOID)hModule );
714     return 0;
715 }
716
717 /**********************************************************************
718  *                 PE_CreateModule
719  *
720  * Create WINE_MODREF structure for loaded HMODULE32, link it into
721  * process modref_list, and fixup all imports.
722  *
723  * Note: hModule must point to a correctly allocated PE image,
724  *       with base relocations applied; the 16-bit dummy module
725  *       associated to hModule must already exist.
726  *
727  * Note: This routine must always be called in the context of the
728  *       process that is to own the module to be created.
729  */
730 WINE_MODREF *PE_CreateModule( HMODULE hModule, 
731                               LPCSTR filename, DWORD flags, BOOL builtin )
732 {
733     DWORD load_addr = (DWORD)hModule;  /* for RVA */
734     IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
735     IMAGE_DATA_DIRECTORY *dir;
736     IMAGE_IMPORT_DESCRIPTOR *pe_import = NULL;
737     IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
738     IMAGE_RESOURCE_DIRECTORY *pe_resource = NULL;
739     WINE_MODREF *wm;
740     int result;
741
742
743     /* Retrieve DataDirectory entries */
744
745     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
746     if (dir->Size)
747         pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
748
749     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IMPORT;
750     if (dir->Size)
751         pe_import = (PIMAGE_IMPORT_DESCRIPTOR)RVA(dir->VirtualAddress);
752
753     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_RESOURCE;
754     if (dir->Size)
755         pe_resource = (PIMAGE_RESOURCE_DIRECTORY)RVA(dir->VirtualAddress);
756
757     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
758     if (dir->Size) FIXME("Exception directory ignored\n" );
759
760     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
761     if (dir->Size) FIXME("Security directory ignored\n" );
762
763     /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
764     /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
765
766     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DEBUG;
767     if (dir->Size) TRACE("Debug directory ignored\n" );
768
769     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COPYRIGHT;
770     if (dir->Size) FIXME("Copyright string ignored\n" );
771
772     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
773     if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
774
775     /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
776
777     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
778     if (dir->Size) FIXME("Load Configuration directory ignored\n" );
779
780     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
781     if (dir->Size) TRACE("Bound Import directory ignored\n" );
782
783     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
784     if (dir->Size) TRACE("Import Address Table directory ignored\n" );
785
786     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
787     if (dir->Size)
788     {
789                 TRACE("Delayed import, stub calls LoadLibrary\n" );
790                 /*
791                  * Nothing to do here.
792                  */
793
794 #ifdef ImgDelayDescr
795                 /*
796                  * This code is useful to observe what the heck is going on.
797                  */
798                 {
799                 ImgDelayDescr *pe_delay = NULL;
800         pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
801         TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
802         TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
803         TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
804         TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
805         TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
806         TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
807         TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
808         TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
809         }
810 #endif /* ImgDelayDescr */
811         }
812
813     dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
814     if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
815
816     dir = nt->OptionalHeader.DataDirectory+15;
817     if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
818
819
820     /* Allocate and fill WINE_MODREF */
821
822     wm = (WINE_MODREF *)HeapAlloc( GetProcessHeap(), 
823                                    HEAP_ZERO_MEMORY, sizeof(*wm) );
824     wm->module = hModule;
825
826     if ( builtin ) 
827         wm->flags |= WINE_MODREF_INTERNAL;
828     if ( flags & DONT_RESOLVE_DLL_REFERENCES )
829         wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
830     if ( flags & LOAD_LIBRARY_AS_DATAFILE )
831         wm->flags |= WINE_MODREF_LOAD_AS_DATAFILE;
832
833     wm->type = MODULE32_PE;
834     wm->binfmt.pe.pe_export = pe_export;
835     wm->binfmt.pe.pe_import = pe_import;
836     wm->binfmt.pe.pe_resource = pe_resource;
837     wm->binfmt.pe.tlsindex = -1;
838
839     wm->filename = HEAP_strdupA( GetProcessHeap(), 0, filename );
840     wm->modname = strrchr( wm->filename, '\\' );
841     if (!wm->modname) wm->modname = wm->filename;
842     else wm->modname++;
843
844     result = GetShortPathNameA( wm->filename, NULL, 0 );
845     wm->short_filename = (char *)HeapAlloc( GetProcessHeap(), 0, result+1 );
846     GetShortPathNameA( wm->filename, wm->short_filename, result+1 );
847     wm->short_modname = strrchr( wm->short_filename, '\\' );
848     if (!wm->short_modname) wm->short_modname = wm->short_filename;
849     else wm->short_modname++;
850
851     /* Link MODREF into process list */
852
853     EnterCriticalSection( &PROCESS_Current()->crit_section );
854
855     wm->next = PROCESS_Current()->modref_list;
856     PROCESS_Current()->modref_list = wm;
857     if ( wm->next ) wm->next->prev = wm;
858
859     if (    !( nt->FileHeader.Characteristics & IMAGE_FILE_DLL )
860          && !( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
861
862     {
863         if ( PROCESS_Current()->exe_modref )
864             FIXME( "Trying to load second .EXE file: %s\n", filename );
865         else
866             PROCESS_Current()->exe_modref = wm;
867     }
868
869     LeaveCriticalSection( &PROCESS_Current()->crit_section );
870
871
872     /* Dump Exports */
873
874     if ( pe_export )
875         dump_exports( hModule );
876
877     /* Fixup Imports */
878
879     if (    pe_import
880          && !( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE )
881          && !( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS ) 
882          && fixup_imports( wm ) ) 
883     {
884         /* remove entry from modref chain */
885         EnterCriticalSection( &PROCESS_Current()->crit_section );
886
887         if ( !wm->prev )
888             PROCESS_Current()->modref_list = wm->next;
889         else
890             wm->prev->next = wm->next;
891
892         if ( wm->next ) wm->next->prev = wm->prev;
893         wm->next = wm->prev = NULL;
894
895         LeaveCriticalSection( &PROCESS_Current()->crit_section );
896
897         /* FIXME: there are several more dangling references
898          * left. Including dlls loaded by this dll before the
899          * failed one. Unrolling is rather difficult with the
900          * current structure and we can leave it them lying
901          * around with no problems, so we don't care.
902          * As these might reference our wm, we don't free it.
903          */
904          return NULL;
905     }
906
907     return wm;
908 }
909
910 /******************************************************************************
911  * The PE Library Loader frontend. 
912  * FIXME: handle the flags.
913  */
914 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
915 {
916         struct load_dll_request *req = get_req_buffer();
917         HMODULE         hModule32;
918         HMODULE16       hModule16;
919         WINE_MODREF     *wm;
920         char            filename[256];
921         HANDLE          hFile;
922         WORD            version = 0;
923
924         /* Search for and open PE file */
925         if ( SearchPathA( NULL, name, ".DLL", 
926                           sizeof(filename), filename, NULL ) == 0 ) return NULL;
927        
928         hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
929                              NULL, OPEN_EXISTING, 0, -1 );
930         if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
931         
932         /* Load PE module */
933         hModule32 = PE_LoadImage( hFile, filename, &version );
934         if (!hModule32)
935         {
936                 CloseHandle( hFile );
937                 SetLastError( ERROR_OUTOFMEMORY );      /* Not entirely right, but good enough */
938                 return NULL;
939         }
940
941         /* Create 16-bit dummy module */
942         if ((hModule16 = MODULE_CreateDummyModule( filename, hModule32 )) < 32)
943         {
944                 CloseHandle( hFile );
945                 SetLastError( (DWORD)hModule16 );       /* This should give the correct error */
946                 return NULL;
947         }
948
949         /* Create 32-bit MODREF */
950         if ( !(wm = PE_CreateModule( hModule32, filename, flags, FALSE )) )
951         {
952                 ERR( "can't load %s\n", filename );
953                 FreeLibrary16( hModule16 );
954                 CloseHandle( hFile );
955                 SetLastError( ERROR_OUTOFMEMORY );
956                 return NULL;
957         }
958
959         if (wm->binfmt.pe.pe_export)
960                 SNOOP_RegisterDLL(wm->module,wm->modname,wm->binfmt.pe.pe_export->NumberOfFunctions);
961         req->handle     = hFile;
962         req->base       = (void *)hModule32;
963         req->dbg_offset = 0;
964         req->dbg_size   = 0;
965         req->name       = &wm->modname;
966         server_call_noerr( REQ_LOAD_DLL );
967         CloseHandle( hFile );
968         return wm;
969 }
970
971
972 /*****************************************************************************
973  *      PE_UnloadLibrary
974  *
975  * Unload the library unmapping the image and freeing the modref structure.
976  */
977 void PE_UnloadLibrary(WINE_MODREF *wm)
978 {
979     TRACE(" unloading %s\n", wm->filename);
980 /*    VirtualFree( (LPVOID)wm->module, 0, MEM_RELEASE ); */  /* FIXME */
981     HeapFree( GetProcessHeap(), 0, wm->filename );
982     HeapFree( GetProcessHeap(), 0, wm->short_filename );
983     HeapFree( GetProcessHeap(), 0, wm );
984 }
985
986 /*****************************************************************************
987  * Load the PE main .EXE. All other loading is done by PE_LoadLibraryExA
988  * FIXME: this function should use PE_LoadLibraryExA, but currently can't
989  * due to the PROCESS_Create stuff.
990  */
991 BOOL PE_CreateProcess( HANDLE hFile, LPCSTR filename, LPCSTR cmd_line, LPCSTR env, 
992                        LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
993                        BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
994                        LPPROCESS_INFORMATION info )
995 {
996     WORD version = 0;
997     HMODULE16 hModule16;
998     HMODULE hModule32;
999     NE_MODULE *pModule;
1000
1001     /* Load file */
1002     if ( (hModule32 = PE_LoadImage( hFile, filename, &version )) < 32 )
1003     {
1004         SetLastError( hModule32 );
1005         return FALSE;
1006     }
1007 #if 0
1008     if (PE_HEADER(hModule32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
1009     {
1010         SetLastError( 20 );  /* FIXME: not the right error code */
1011         return FALSE;
1012     }
1013 #endif
1014
1015     /* Create 16-bit dummy module */
1016     if ( (hModule16 = MODULE_CreateDummyModule( filename, hModule32 )) < 32 ) 
1017     {
1018         SetLastError( hModule16 );
1019         return FALSE;
1020     }
1021     pModule = (NE_MODULE *)GlobalLock16( hModule16 );
1022
1023     /* Create new process */
1024     if ( !PROCESS_Create( pModule, hFile, cmd_line, env,
1025                           psa, tsa, inherit, flags, startup, info ) )
1026         return FALSE;
1027
1028     /* Note: PE_CreateModule and the remaining process initialization will
1029              be done in the context of the new process, in TASK_CallToStart */
1030
1031     return TRUE;
1032 }
1033
1034
1035 /* Called if the library is loaded or freed.
1036  * NOTE: if a thread attaches a DLL, the current thread will only do
1037  * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
1038  * (SDK)
1039  */
1040 BOOL PE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
1041 {
1042     BOOL retv = TRUE;
1043     assert( wm->type == MODULE32_PE );
1044
1045     /* Is this a library? And has it got an entrypoint? */
1046     if ((PE_HEADER(wm->module)->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1047         (PE_HEADER(wm->module)->OptionalHeader.AddressOfEntryPoint)
1048     ) {
1049         DLLENTRYPROC entry = (void*)RVA_PTR( wm->module,OptionalHeader.AddressOfEntryPoint );
1050         TRACE_(relay)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
1051                        entry, wm->module, type, lpReserved );
1052
1053         retv = entry( wm->module, type, lpReserved );
1054     }
1055
1056     return retv;
1057 }
1058
1059 /************************************************************************
1060  *      PE_InitTls                      (internal)
1061  *
1062  * If included, initialises the thread local storages of modules.
1063  * Pointers in those structs are not RVAs but real pointers which have been
1064  * relocated by do_relocations() already.
1065  */
1066 static LPVOID
1067 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
1068         if (    ((DWORD)addr>opt->ImageBase) &&
1069                 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
1070         )
1071                 /* the address has not been relocated! */
1072                 return (LPVOID)(((DWORD)addr)+delta);
1073         else
1074                 /* the address has been relocated already */
1075                 return addr;
1076 }
1077 void PE_InitTls( void )
1078 {
1079         WINE_MODREF             *wm;
1080         PE_MODREF               *pem;
1081         IMAGE_NT_HEADERS        *peh;
1082         DWORD                   size,datasize;
1083         LPVOID                  mem;
1084         PIMAGE_TLS_DIRECTORY    pdir;
1085         int delta;
1086         
1087         for (wm = PROCESS_Current()->modref_list;wm;wm=wm->next) {
1088                 if (wm->type!=MODULE32_PE)
1089                         continue;
1090                 pem = &(wm->binfmt.pe);
1091                 peh = PE_HEADER(wm->module);
1092                 delta = wm->module - peh->OptionalHeader.ImageBase;
1093                 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
1094                         continue;
1095                 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
1096                         DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
1097                 
1098                 
1099                 if ( pem->tlsindex == -1 ) {
1100                         LPDWORD xaddr;
1101                         pem->tlsindex = TlsAlloc();
1102                         xaddr = _fixup_address(&(peh->OptionalHeader),delta,
1103                                         pdir->AddressOfIndex
1104                         );
1105                         *xaddr=pem->tlsindex;
1106                 }
1107                 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
1108                 size    = datasize + pdir->SizeOfZeroFill;
1109                 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
1110                 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
1111                 if (pdir->AddressOfCallBacks) {
1112                      PIMAGE_TLS_CALLBACK *cbs; 
1113
1114                      cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
1115                      if (*cbs)
1116                        FIXME("TLS Callbacks aren't going to be called\n");
1117                 }
1118
1119                 TlsSetValue( pem->tlsindex, mem );
1120         }
1121 }
1122