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