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