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