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