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