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