Release 971116
[wine] / loader / pe_image.c
1 /* 
2  *  Copyright   1994    Eric Youndale & Erik Bos
3  *  Copyright   1995    Martin von Löwis
4  *  Copyright   1996    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
13 #include <ctype.h>
14 #include <errno.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <unistd.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/mman.h>
22 #include "windows.h"
23 #include "winbase.h"
24 #include "callback.h"
25 #include "file.h"
26 #include "neexe.h"
27 #include "peexe.h"
28 #include "process.h"
29 #include "pe_image.h"
30 #include "module.h"
31 #include "global.h"
32 #include "task.h"
33 #include "ldt.h"
34 #include "stddebug.h"
35 #include "debug.h"
36 #include "xmalloc.h"
37
38 static void PE_InitDLL(PE_MODREF* modref, DWORD type, LPVOID lpReserved);
39
40 /* convert PE image VirtualAddress to Real Address */
41 #define RVA(x) ((unsigned int)load_addr+(unsigned int)(x))
42
43 void dump_exports(IMAGE_EXPORT_DIRECTORY * pe_exports, unsigned int load_addr)
44
45   char          *Module;
46   int           i, j;
47   u_short       *ordinal;
48   u_long        *function,*functions;
49   u_char        **name;
50
51   Module = (char*)RVA(pe_exports->Name);
52   dprintf_win32(stddeb,"\n*******EXPORT DATA*******\nModule name is %s, %ld functions, %ld names\n", 
53          Module,
54          pe_exports->NumberOfFunctions,
55          pe_exports->NumberOfNames);
56
57   ordinal=(u_short*) RVA(pe_exports->AddressOfNameOrdinals);
58   functions=function=(u_long*) RVA(pe_exports->AddressOfFunctions);
59   name=(u_char**) RVA(pe_exports->AddressOfNames);
60
61   dprintf_win32(stddeb," Ord  Virt Addr  Name\n" );
62   for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
63   {
64       if (!*function) continue;  /* No such function */
65       dprintf_win32( stddeb,"%4ld  %08lx", i + pe_exports->Base, *function );
66       /* Check if we have a name for it */
67       for (j = 0; j < pe_exports->NumberOfNames; j++)
68           if (ordinal[j] == i)
69               dprintf_win32( stddeb, "  %s", (char*)RVA(name[j]) );
70       dprintf_win32( stddeb,"\n" );
71   }
72 }
73
74 /* Look up the specified function or ordinal in the exportlist:
75  * If it is a string:
76  *      - look up the name in the Name list. 
77  *      - look up the ordinal with that index.
78  *      - use the ordinal as offset into the functionlist
79  * If it is a ordinal:
80  *      - use ordinal-pe_export->Base as offset into the functionlist
81  */
82 FARPROC32 PE_FindExportedFunction(struct pe_data *pe, LPCSTR funcName)
83 {
84         IMAGE_EXPORT_DIRECTORY          *exports;
85         unsigned                        load_addr;
86         u_short                         * ordinal;
87         u_long                          * function;
88         u_char                          ** name, *ename;
89         int                             i;
90         PDB32                           *process=(PDB32*)GetCurrentProcessId();
91         PE_MODREF                       *pem;
92
93         pem = process->modref_list;
94         while (pem && (pem->pe_module != pe))
95                 pem=pem->next;
96         if (!pem) {
97                 fprintf(stderr,"No MODREF found for PE_MODULE %p in process %p\n",pe,process);
98                 return NULL;
99         }
100         load_addr       = pem->load_addr;
101         exports         = pem->pe_export;
102
103         if (HIWORD(funcName))
104                 dprintf_win32(stddeb,"PE_FindExportedFunction(%s)\n",funcName);
105         else
106                 dprintf_win32(stddeb,"PE_FindExportedFunction(%d)\n",(int)funcName);
107         if (!exports) {
108                 fprintf(stderr,"Module %p/MODREF %p doesn't have a exports table.\n",pe,pem);
109                 return NULL;
110         }
111         ordinal = (u_short*)  RVA(exports->AddressOfNameOrdinals);
112         function= (u_long*)   RVA(exports->AddressOfFunctions);
113         name    = (u_char **) RVA(exports->AddressOfNames);
114
115         if (HIWORD(funcName)) {
116                 for(i=0; i<exports->NumberOfNames; i++) {
117                         ename=(char*)RVA(*name);
118                         if(!strcmp(ename,funcName))
119                                 return (FARPROC32) RVA(function[*ordinal]);
120                         ordinal++;
121                         name++;
122                 }
123         } else {
124                 if (LOWORD(funcName)-exports->Base > exports->NumberOfFunctions) {
125                         dprintf_win32(stddeb,"  ordinal %d out of range!\n",
126                                       LOWORD(funcName));
127                         return NULL;
128                 }
129                 return (FARPROC32) RVA(function[(int)funcName-exports->Base]);
130         }
131         return NULL;
132 }
133
134 void 
135 fixup_imports (PDB32 *process,PE_MODREF *pem)
136 {
137     PE_MODULE                   *pe = pem->pe_module;
138     IMAGE_IMPORT_DESCRIPTOR     *pe_imp;
139     int fixup_failed            = 0;
140     unsigned int load_addr      = pem->load_addr;
141     int                         i;
142     char                        *modname;
143     
144     if (pem->pe_export)
145         modname = (char*) RVA(pem->pe_export->Name);
146     else
147         modname = "<unknown>";
148
149     /* OK, now dump the import list */
150     dprintf_win32 (stddeb, "\nDumping imports list\n");
151
152     /* first, count the number of imported non-internal modules */
153     pe_imp = pem->pe_import;
154     if (!pe_imp) 
155         fprintf(stderr,"no import directory????\n");
156
157     /* FIXME: should terminate on 0 Characteristics */
158     for (i = 0; pe_imp->Name; pe_imp++)
159         i++;
160
161     /* load the imported modules. They are automatically 
162      * added to the modref list of the process.
163      */
164  
165     /* FIXME: should terminate on 0 Characteristics */
166     for (i = 0, pe_imp = pem->pe_import; pe_imp->Name; pe_imp++) {
167         HMODULE32       res;
168         PE_MODREF       *xpem,**ypem;
169
170
171         char *name = (char *) RVA(pe_imp->Name);
172
173         /* don't use MODULE_Load, Win32 creates new task differently */
174         res = PE_LoadLibraryEx32A( name, 0, 0 );
175         if (res <= (HMODULE32) 32) {
176             char *p, buffer[256];
177
178             /* Try with prepending the path of the current module */
179             GetModuleFileName32A (pe->mappeddll, buffer, sizeof (buffer));
180             if (!(p = strrchr (buffer, '\\')))
181                 p = buffer;
182             strcpy (p + 1, name);
183             res = PE_LoadLibraryEx32A( buffer, 0, 0 );
184         }
185         if (res <= (HMODULE32) 32) {
186             fprintf (stderr, "Module %s not found\n", name);
187             exit (0);
188         }
189         res = MODULE_HANDLEtoHMODULE32(res);
190         xpem = pem->next;
191         while (xpem) {
192                 if (xpem->pe_module->mappeddll == res)
193                         break;
194                 xpem = xpem->next;
195         }
196         if (xpem) {
197                 /* it has been loaded *BEFORE* us, so we have to init
198                  * it before us. we just swap the two modules which should
199                  * work.
200                  */
201                 /* unlink xpem from chain */
202                 ypem = &(process->modref_list);
203                 while (*ypem) {
204                         if ((*ypem)==xpem)
205                                 break;
206                         ypem = &((*ypem)->next);
207                 }
208                 *ypem           = xpem->next;
209
210                 /* link it directly before pem */
211                 ypem            = &(process->modref_list);
212                 while (*ypem) {
213                         if ((*ypem)==pem)
214                                 break;
215                         ypem = &((*ypem)->next);
216                 }
217                 *ypem           = xpem;
218                 xpem->next      = pem;
219                 
220         }
221         i++;
222     }
223     pe_imp = pem->pe_import;
224     while (pe_imp->Name) {
225         char                    *Module;
226         IMAGE_IMPORT_BY_NAME    *pe_name;
227         LPIMAGE_THUNK_DATA      import_list,thunk_list;
228
229         Module = (char *) RVA(pe_imp->Name);
230         dprintf_win32 (stddeb, "%s\n", Module);
231
232         /* FIXME: forwarder entries ... */
233
234         if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
235             dprintf_win32 (stddeb, "Microsoft style imports used\n");
236             import_list =(LPIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
237             thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
238
239             while (import_list->u1.Ordinal) {
240                 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
241                     int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
242
243                     dprintf_win32 (stddeb, "--- Ordinal %s,%d\n", Module, ordinal);
244                     thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),(LPCSTR)ordinal);
245                     if (!thunk_list->u1.Function) {
246                         fprintf(stderr,"No implementation for %s.%d, setting to NULL\n",
247                                 Module, ordinal);
248                         /* fixup_failed=1; */
249                     }
250                 } else {                /* import by name */
251                     pe_name = (LPIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
252                     dprintf_win32 (stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
253                     thunk_list->u1.Function=(LPDWORD)GetProcAddress32(
254                                                 MODULE_FindModule (Module),
255                                                 pe_name->Name);
256                     if (!thunk_list->u1.Function) {
257                         fprintf(stderr,"No implementation for %s.%d(%s), setting to NULL\n",
258                                 Module,pe_name->Hint,pe_name->Name);
259                         /* fixup_failed=1; */
260                     }
261                 }
262                 import_list++;
263                 thunk_list++;
264             }
265         } else {        /* Borland style */
266             dprintf_win32 (stddeb, "Borland style imports used\n");
267             thunk_list = (LPIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
268             while (thunk_list->u1.Ordinal) {
269                 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
270                     /* not sure about this branch, but it seems to work */
271                     int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
272
273                     dprintf_win32(stddeb,"--- Ordinal %s.%d\n",Module,ordinal);
274                     thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),
275                                                      (LPCSTR) ordinal);
276                     if (!thunk_list->u1.Function) {
277                         fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
278                                 Module,ordinal);
279                         /* fixup_failed=1; */
280                     }
281                 } else {
282                     pe_name=(LPIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
283                     dprintf_win32(stddeb,"--- %s %s.%d\n",
284                                   pe_name->Name,Module,pe_name->Hint);
285                     thunk_list->u1.Function=(LPDWORD)GetProcAddress32(MODULE_FindModule(Module),pe_name->Name);
286                     if (!thunk_list->u1.Function) {
287                         fprintf(stderr, "No implementation for %s.%d, setting to NULL\n",
288                                 Module, pe_name->Hint);
289                         /* fixup_failed=1; */
290                     }
291                 }
292                 thunk_list++;
293             }
294         }
295         pe_imp++;
296     }
297     if (fixup_failed) exit(1);
298 }
299
300 static int calc_vma_size(struct pe_data *pe)
301 {
302   int i,vma_size = 0;
303
304   dprintf_win32(stddeb, "Dump of segment table\n");
305   dprintf_win32(stddeb, "   Name    VSz  Vaddr     SzRaw   Fileadr  *Reloc *Lineum #Reloc #Linum Char\n");
306   for(i=0; i< pe->pe_header->FileHeader.NumberOfSections; i++)
307     {
308       dprintf_win32(stddeb, "%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n", 
309              pe->pe_seg[i].Name, 
310              pe->pe_seg[i].Misc.VirtualSize,
311              pe->pe_seg[i].VirtualAddress,
312              pe->pe_seg[i].SizeOfRawData,
313              pe->pe_seg[i].PointerToRawData,
314              pe->pe_seg[i].PointerToRelocations,
315              pe->pe_seg[i].PointerToLinenumbers,
316              pe->pe_seg[i].NumberOfRelocations,
317              pe->pe_seg[i].NumberOfLinenumbers,
318              pe->pe_seg[i].Characteristics);
319           vma_size = MAX(vma_size,
320                         pe->pe_seg[i].VirtualAddress + 
321                         pe->pe_seg[i].SizeOfRawData);
322     }
323     return vma_size;
324 }
325
326 static void do_relocations(PE_MODREF *pem)
327 {
328         int delta = pem->load_addr - pem->pe_module->pe_header->OptionalHeader.ImageBase;
329
330         unsigned int                    load_addr= pem->load_addr;
331         IMAGE_BASE_RELOCATION           *r = pem->pe_reloc;
332         int                             hdelta = (delta >> 16) & 0xFFFF;
333         int                             ldelta = delta & 0xFFFF;
334
335         /* int reloc_size = */
336
337         if(delta == 0)
338                 /* Nothing to do */
339                 return;
340         while(r->VirtualAddress)
341         {
342                 char *page = (char*) RVA(r->VirtualAddress);
343                 int count = (r->SizeOfBlock - 8)/2;
344                 int i;
345                 dprintf_fixup(stddeb, "%x relocations for page %lx\n",
346                         count, r->VirtualAddress);
347                 /* patching in reverse order */
348                 for(i=0;i<count;i++)
349                 {
350                         int offset = r->TypeOffset[i] & 0xFFF;
351                         int type = r->TypeOffset[i] >> 12;
352                         dprintf_fixup(stddeb,"patching %x type %x\n", offset, type);
353                         switch(type)
354                         {
355                         case IMAGE_REL_BASED_ABSOLUTE: break;
356                         case IMAGE_REL_BASED_HIGH:
357                                 *(short*)(page+offset) += hdelta;
358                                 break;
359                         case IMAGE_REL_BASED_LOW:
360                                 *(short*)(page+offset) += ldelta;
361                                 break;
362                         case IMAGE_REL_BASED_HIGHLOW:
363 #if 1
364                                 *(int*)(page+offset) += delta;
365 #else
366                                 { int h=*(unsigned short*)(page+offset);
367                                   int l=r->TypeOffset[++i];
368                                   *(unsigned int*)(page + offset) = (h<<16) + l + delta;
369                                 }
370 #endif
371                                 break;
372                         case IMAGE_REL_BASED_HIGHADJ:
373                                 fprintf(stderr, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
374                                 break;
375                         case IMAGE_REL_BASED_MIPS_JMPADDR:
376                                 fprintf(stderr, "Is this a MIPS machine ???\n");
377                                 break;
378                         default:
379                                 fprintf(stderr, "Unknown fixup type\n");
380                                 break;
381                         }
382                 }
383                 r = (IMAGE_BASE_RELOCATION*)((char*)r + r->SizeOfBlock);
384         }
385 }
386                 
387
388         
389         
390
391 /**********************************************************************
392  *                      PE_LoadImage
393  * Load one PE format DLL/EXE into memory
394  * 
395  * Unluckily we can't just mmap the sections where we want them, for 
396  * (at least) Linux does only support offsets which are page-aligned.
397  *
398  * BUT we have to map the whole image anyway, for Win32 programs sometimes
399  * want to access them. (HMODULE32 point to the start of it)
400  */
401 static PE_MODULE *PE_LoadImage( HFILE32 hFile )
402 {
403     struct pe_data *pe;
404     HMODULE32 hModule;
405     HANDLE32 mapping;
406
407     /* map the PE file somewhere */
408     mapping = CreateFileMapping32A( hFile, NULL, PAGE_READONLY | SEC_COMMIT,
409                                     0, 0, NULL );
410     if (!mapping)
411     {
412         fprintf( stderr, "PE_LoadImage: CreateFileMapping error %ld\n",
413                  GetLastError() );
414         return NULL;
415     }
416     hModule = (HMODULE32)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
417     CloseHandle( mapping );
418     if (!hModule)
419     {
420         fprintf( stderr, "PE_LoadImage: MapViewOfFile error %ld\n",
421                  GetLastError() );
422         return NULL;
423     }
424
425     /* build PE header */
426     pe = xmalloc(sizeof(struct pe_data));
427     pe->mappeddll = hModule;
428     pe->pe_header = (IMAGE_NT_HEADERS*)(pe->mappeddll+(((IMAGE_DOS_HEADER*)pe->mappeddll)->e_lfanew));
429     if (pe->pe_header->Signature!=IMAGE_NT_SIGNATURE)
430     {
431         fprintf(stderr,"image doesn't have PE signature, but 0x%08lx\n",
432                 pe->pe_header->Signature );
433         free(pe);
434         return NULL;
435     }
436
437         if (pe->pe_header->FileHeader.Machine != IMAGE_FILE_MACHINE_I386) {
438                 fprintf(stderr,"trying to load PE image for unsupported architecture (");
439                 switch (pe->pe_header->FileHeader.Machine) {
440                 case IMAGE_FILE_MACHINE_UNKNOWN:
441                         fprintf(stderr,"Unknown");break;
442                 case IMAGE_FILE_MACHINE_I860:
443                         fprintf(stderr,"I860");break;
444                 case IMAGE_FILE_MACHINE_R3000:
445                         fprintf(stderr,"R3000");break;
446                 case IMAGE_FILE_MACHINE_R4000:
447                         fprintf(stderr,"R4000");break;
448                 case IMAGE_FILE_MACHINE_R10000:
449                         fprintf(stderr,"R10000");break;
450                 case IMAGE_FILE_MACHINE_ALPHA:
451                         fprintf(stderr,"Alpha");break;
452                 case IMAGE_FILE_MACHINE_POWERPC:
453                         fprintf(stderr,"PowerPC");break;
454                 default:
455                         fprintf(stderr,"Unknown-%04x",pe->pe_header->FileHeader.Machine);break;
456                 }
457                 fprintf(stderr,")\n");
458                 return NULL;
459         }
460         pe->pe_seg = (IMAGE_SECTION_HEADER*)(((LPBYTE)(pe->pe_header+1))-
461                  (16 - pe->pe_header->OptionalHeader.NumberOfRvaAndSizes) * sizeof(IMAGE_DATA_DIRECTORY));
462
463 /* FIXME: the (16-...) is a *horrible* hack to make COMDLG32.DLL load OK. The
464  * problem needs to be fixed properly at some stage.
465  */
466         return pe;
467 }
468
469 /**********************************************************************
470  * This maps a loaded PE dll into the address space of the specified process.
471  */
472 void
473 PE_MapImage(PE_MODULE *pe,PDB32 *process, OFSTRUCT *ofs, DWORD flags) {
474         PE_MODREF               *pem;
475         int                     i, result;
476         int                     load_addr;
477         IMAGE_DATA_DIRECTORY    dir;
478         char                    *modname;
479         int                     vma_size;
480         
481         pem             = (PE_MODREF*)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,sizeof(*pem));
482         /* NOTE: fixup_imports takes care of the correct order */
483         pem->next       = process->modref_list;
484         process->modref_list = pem;
485
486         pem->pe_module  = pe;
487         if (!(pe->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL)) {
488                 if (process->exe_modref)
489                         fprintf(stderr,"overwriting old exe_modref... arrgh\n");
490                 process->exe_modref = pem;
491         }
492
493         load_addr       = pe->pe_header->OptionalHeader.ImageBase;
494         dprintf_win32(stddeb, "Load addr is %x\n",load_addr);
495         vma_size = calc_vma_size(pe);
496         load_addr       = (int) VirtualAlloc( (void*)load_addr, vma_size, MEM_RESERVE|MEM_COMMIT, PAGE_EXECUTE_READWRITE );
497         pem->load_addr  = load_addr;
498
499         dprintf_win32(stddeb, "Load addr is really %lx, range %x\n",
500                 pem->load_addr, vma_size);
501         
502
503         for(i=0; i < pe->pe_header->FileHeader.NumberOfSections; i++)
504         {
505                 /* memcpy only non-BSS segments */
506                 /* FIXME: this should be done by mmap(..MAP_PRIVATE|MAP_FIXED..)
507                  * but it is not possible for (at least) Linux needs
508                  * a page-aligned offset.
509                  */
510                 if(!(pe->pe_seg[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
511                     memcpy((char*)RVA(pe->pe_seg[i].VirtualAddress),
512                         (char*)(pe->mappeddll+pe->pe_seg[i].PointerToRawData),
513                         pe->pe_seg[i].SizeOfRawData
514                     );
515
516                 result = RVA (pe->pe_seg[i].VirtualAddress);
517 #if 1
518                 /* not needed, memory is zero */
519                 if(strcmp(pe->pe_seg[i].Name, ".bss") == 0)
520                     memset((void *)result, 0, 
521                            pe->pe_seg[i].Misc.VirtualSize ?
522                            pe->pe_seg[i].Misc.VirtualSize :
523                            pe->pe_seg[i].SizeOfRawData);
524 #endif
525
526                 if(strcmp(pe->pe_seg[i].Name, ".idata") == 0)
527                         pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) result;
528
529                 if(strcmp(pe->pe_seg[i].Name, ".edata") == 0)
530                         pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) result;
531
532                 if(strcmp(pe->pe_seg[i].Name, ".rsrc") == 0)
533                         pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) result;
534
535                 if(strcmp(pe->pe_seg[i].Name, ".reloc") == 0)
536                         pem->pe_reloc = (LPIMAGE_BASE_RELOCATION) result;
537         }
538
539         /* There is word that the actual loader does not care about the
540            section names, and only goes for the DataDirectory */
541         dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
542         if(dir.Size)
543         {
544                 if(pem->pe_export && (int)pem->pe_export!=RVA(dir.VirtualAddress))
545                         fprintf(stderr,"wrong export directory??\n");
546                 /* always trust the directory */
547                 pem->pe_export = (LPIMAGE_EXPORT_DIRECTORY) RVA(dir.VirtualAddress);
548         }
549
550         dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
551         if(dir.Size)
552         {
553                 /* 
554                 if(pem->pe_import && (int)pem->pe_import!=RVA(dir.VirtualAddress))
555                         fprintf(stderr,"wrong import directory??\n");
556                  */
557                 pem->pe_import = (LPIMAGE_IMPORT_DESCRIPTOR) RVA(dir.VirtualAddress);
558         }
559
560         dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE];
561         if(dir.Size)
562         {
563                 if(pem->pe_resource && (int)pem->pe_resource!=RVA(dir.VirtualAddress))
564                         fprintf(stderr,"wrong resource directory??\n");
565                 pem->pe_resource = (LPIMAGE_RESOURCE_DIRECTORY) RVA(dir.VirtualAddress);
566         }
567
568         if(pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION].Size)
569                 dprintf_win32(stdnimp,"Exception directory ignored\n");
570
571         if(pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size)
572                 dprintf_win32(stdnimp,"Security directory ignored\n");
573
574
575
576         dir=pe->pe_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
577         if(dir.Size)
578         {
579                 if(pem->pe_reloc && (int)pem->pe_reloc!= RVA(dir.VirtualAddress))
580                         fprintf(stderr,"wrong relocation list??\n");
581                 pem->pe_reloc = (void *) RVA(dir.VirtualAddress);
582         }
583
584         if(pe->pe_header->OptionalHeader.DataDirectory
585                 [IMAGE_DIRECTORY_ENTRY_COPYRIGHT].Size)
586                 dprintf_win32(stdnimp,"Copyright string ignored\n");
587
588         if(pe->pe_header->OptionalHeader.DataDirectory
589                 [IMAGE_DIRECTORY_ENTRY_GLOBALPTR].Size)
590                 dprintf_win32(stdnimp,"Global Pointer (MIPS) ignored\n");
591
592         if(pe->pe_header->OptionalHeader.DataDirectory
593                 [IMAGE_DIRECTORY_ENTRY_TLS].Size)
594                  fprintf(stdnimp,"Thread local storage ignored\n");
595
596         if(pe->pe_header->OptionalHeader.DataDirectory
597                 [IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size)
598                 dprintf_win32(stdnimp,"Load Configuration directory ignored\n");
599
600         if(pe->pe_header->OptionalHeader.DataDirectory
601                 [IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size)
602                 dprintf_win32(stdnimp,"Bound Import directory ignored\n");
603
604         if(pe->pe_header->OptionalHeader.DataDirectory
605                 [IMAGE_DIRECTORY_ENTRY_IAT].Size)
606                 dprintf_win32(stdnimp,"Import Address Table directory ignored\n");
607         if(pe->pe_header->OptionalHeader.DataDirectory[13].Size)
608                 dprintf_win32(stdnimp,"Unknown directory 13 ignored\n");
609         if(pe->pe_header->OptionalHeader.DataDirectory[14].Size)
610                 dprintf_win32(stdnimp,"Unknown directory 14 ignored\n");
611         if(pe->pe_header->OptionalHeader.DataDirectory[15].Size)
612                 dprintf_win32(stdnimp,"Unknown directory 15 ignored\n");
613
614         if(pem->pe_reloc)       do_relocations(pem);
615         if(pem->pe_export)      dump_exports(pem->pe_export,load_addr);
616         if(pem->pe_import)      fixup_imports(process,pem);
617                 
618         if (pem->pe_export)
619                 modname = (char*)RVA(pem->pe_export->Name);
620         else {
621                 char *s;
622                 modname = s = ofs->szPathName;
623                 while ((s=strchr(modname,'\\')))
624                         modname = s+1;
625                 if ((s=strchr(modname,'.')))
626                         *s='\0';
627         }
628 }
629
630 HINSTANCE16 MODULE_CreateInstance(HMODULE16 hModule,LOADPARAMS *params);
631
632 /******************************************************************************
633  * The PE Library Loader frontend. 
634  * FIXME: handle the flags.
635  */
636 HMODULE32 PE_LoadLibraryEx32A (LPCSTR name, HFILE32 hFile, DWORD flags) {
637         OFSTRUCT        ofs;
638         HMODULE32       hModule;
639         NE_MODULE       *pModule;
640         PE_MODREF       *pem;
641
642         if ((hModule = MODULE_FindModule( name ))) {
643                 /* the .DLL is either loaded or internal */
644                 hModule = MODULE_HANDLEtoHMODULE32(hModule);
645                 if (!HIWORD(hModule)) /* internal (or bad) */
646                         return hModule;
647                 /* check if this module is already mapped */
648                 pem     = ((PDB32*)GetCurrentProcessId())->modref_list;
649                 while (pem) {
650                         if (pem->pe_module->mappeddll == hModule)
651                                 return hModule;
652                         pem = pem->next;
653                 }
654                 pModule = MODULE_GetPtr(hModule);
655         } else {
656
657                 /* try to load builtin, enabled modules first */
658                 if ((hModule = BUILTIN_LoadModule( name, FALSE )))
659                         return hModule;
660
661                 /* try to open the specified file */
662                 if (HFILE_ERROR32==(hFile=OpenFile32(name,&ofs,OF_READ))) {
663                         /* Now try the built-in even if disabled */
664                         if ((hModule = BUILTIN_LoadModule( name, TRUE ))) {
665                                 fprintf( stderr, "Warning: could not load Windows DLL '%s', using built-in module.\n", name );
666                                 return hModule;
667                         }
668                         return 1;
669                 }
670                 if ((hModule = MODULE_CreateDummyModule( &ofs )) < 32) {
671                         _lclose32(hFile);
672                         return hModule;
673                 }
674                 pModule         = (NE_MODULE *)GlobalLock16( hModule );
675                 pModule->flags  = NE_FFLAGS_WIN32;
676                 pModule->pe_module = PE_LoadImage( hFile );
677                 CloseHandle( hFile );
678                 if (!pModule->pe_module)
679                         return 21;
680         }
681         /* recurse */
682         PE_MapImage(pModule->pe_module,(PDB32*)GetCurrentProcessId(),&ofs,flags);
683         return pModule->pe_module->mappeddll;
684 }
685
686 /*****************************************************************************
687  * Load the PE main .EXE. All other loading is done by PE_LoadLibraryEx32A
688  * FIXME: this function should use PE_LoadLibraryEx32A, but currently can't
689  * due to the TASK_CreateTask stuff.
690  */
691 HINSTANCE16 PE_LoadModule( HFILE32 hFile, OFSTRUCT *ofs, LOADPARAMS* params )
692 {
693     HMODULE16 hModule;
694     HINSTANCE16 hInstance;
695     NE_MODULE *pModule;
696
697     if ((hModule = MODULE_CreateDummyModule( ofs )) < 32) return hModule;
698     pModule = (NE_MODULE *)GlobalLock16( hModule );
699     pModule->flags = NE_FFLAGS_WIN32;
700
701     pModule->pe_module = PE_LoadImage( hFile );
702     CloseHandle( hFile );
703     if (!pModule->pe_module)
704         return 21;
705
706     hInstance = MODULE_CreateInstance( hModule, params );
707     if (!(pModule->pe_module->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL))
708     {
709         TASK_CreateTask( hModule, hInstance, 0,
710                          params->hEnvironment,
711                          (LPSTR)PTR_SEG_TO_LIN( params->cmdLine ),
712                          *((WORD*)PTR_SEG_TO_LIN(params->showCmd) + 1) );
713     }
714     PE_MapImage(pModule->pe_module,(PDB32*)GetCurrentProcessId(),ofs,0);
715     return hInstance;
716 }
717
718 int PE_UnloadImage( HMODULE32 hModule )
719 {
720         printf("PEunloadImage() called!\n");
721         /* free resources, image, unmap */
722         return 1;
723 }
724
725 /* Called if the library is loaded or freed.
726  * NOTE: if a thread attaches a DLL, the current thread will only do
727  * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
728  * (SDK)
729  */
730 static void PE_InitDLL(PE_MODREF *pem, DWORD type,LPVOID lpReserved)
731 {
732     PE_MODULE           *pe = pem->pe_module;
733     unsigned int        load_addr = pem->load_addr;
734
735     if (type==DLL_PROCESS_ATTACH)
736         pem->flags |= PE_MODREF_PROCESS_ATTACHED;
737
738     /*  DLL_ATTACH_PROCESS:
739      *          lpreserved is NULL for dynamic loads, not-NULL for static loads
740      *  DLL_DETACH_PROCESS:
741      *          lpreserved is NULL if called by FreeLibrary, not-NULL otherwise
742      *  the SDK doesn't mention anything for DLL_THREAD_*
743      */
744         
745     /* Is this a library? And has it got an entrypoint? */
746     if (        (pe->pe_header->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
747                 (pe->pe_header->OptionalHeader.AddressOfEntryPoint)
748     ) {
749         FARPROC32 entry = (FARPROC32)RVA(pe->pe_header->OptionalHeader.AddressOfEntryPoint);
750         dprintf_relay( stddeb, "CallTo32(entryproc=%p,module=%d,type=%ld,res=%p)\n",
751                        entry, pe->mappeddll, type, lpReserved );
752         entry( pe->mappeddll, type, lpReserved );
753     }
754 }
755
756 /* Call the DLLentry function of all dlls used by that process.
757  * (NOTE: this may recursively call this function (if a library calls
758  * LoadLibrary) ... but it won't matter)
759  */
760 void PE_InitializeDLLs(PDB32 *process,DWORD type,LPVOID lpReserved) {
761         PE_MODREF       *pem;
762
763         pem = process->modref_list;
764         while (pem) {
765                 if (pem->flags & PE_MODREF_NO_DLL_CALLS) {
766                         pem = pem->next;
767                         continue;
768                 }
769                 if (type==DLL_PROCESS_ATTACH) {
770                         if (pem->flags & PE_MODREF_PROCESS_ATTACHED) {
771                                 pem = pem->next;
772                                 continue;
773                         }
774                 }
775                 PE_InitDLL( pem, type, lpReserved );
776                 pem = pem->next;
777         }
778 }
779
780 void PE_InitTls(PDB32 *pdb)
781 {
782         /* FIXME: tls callbacks ??? */
783         PE_MODREF               *pem;
784         IMAGE_NT_HEADERS        *peh;
785         DWORD                   size,datasize,index;
786         LPVOID                  mem;
787         LPIMAGE_TLS_DIRECTORY   pdir;
788
789         pem = pdb->modref_list;
790         while (pem) {
791                 peh = pem->pe_module->pe_header;
792                 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress) {
793                         pem = pem->next;
794                         continue;
795                 }
796                 pdir = (LPVOID)(pem->load_addr + peh->OptionalHeader.
797                         DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
798                 index   = TlsAlloc();
799                 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
800                 size    = datasize + pdir->SizeOfZeroFill;
801                 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
802                 memcpy(mem,(LPVOID) pdir->StartAddressOfRawData, datasize);
803                 TlsSetValue(index,mem);
804                 *(pdir->AddressOfIndex)=index;   
805                 pem=pem->next;
806         }
807 }
808
809 /****************************************************************************
810  *              DisableThreadLibraryCalls (KERNEL32.74)
811  * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
812  */
813 BOOL32 WINAPI DisableThreadLibraryCalls(HMODULE32 hModule)
814 {
815         PDB32   *process = (PDB32*)GetCurrentProcessId();
816         PE_MODREF       *pem = process->modref_list;
817
818         while (pem) {
819                 if (pem->pe_module->mappeddll == hModule)
820                         pem->flags|=PE_MODREF_NO_DLL_CALLS;
821                 pem = pem->next;
822         }
823         return TRUE;
824 }
825