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