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