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