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