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