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