Release 960705
[wine] / loader / pe_image.c
1 #ifndef WINELIB
2 /* 
3  *  Copyright   1994    Eric Youndale & Erik Bos
4  *  Copyright   1995    Martin von Löwis
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 <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18 #include <sys/types.h>
19 #include <sys/mman.h>
20 #include "windows.h"
21 #include "winbase.h"
22 #include "callback.h"
23 #include "neexe.h"
24 #include "peexe.h"
25 #include "pe_image.h"
26 #include "module.h"
27 #include "global.h"
28 #include "task.h"
29 #include "ldt.h"
30 #include "registers.h"
31 #include "stddebug.h"
32 #include "debug.h"
33 #include "xmalloc.h"
34
35 void my_wcstombs(char * result, u_short * source, int len)
36 {
37   while(len--) {
38     /* this used to be isascii, but see isascii implementation in Linux'
39            ctype.h */
40     if(*source<255) *result++ = *source++;
41     else {
42       printf("Unable to handle unicode right now\n");
43       exit(0);
44     }
45   };
46 }
47
48 #if 0
49 char * xmmap(char * vaddr, unsigned int v_size, unsigned int r_size,
50         int prot, int flags, int fd, unsigned int file_offset)
51 {
52   char * result;
53   /* .bss has no associated storage in the PE file */
54   if(r_size)
55     v_size=r_size;
56   else
57 #if defined(__svr4__) || defined(_SCO_DS)
58     fprintf(stderr,"xmmap: %s line %d doesn't support MAP_ANON\n",__FILE__, __LINE__);
59 #else
60     flags |= MAP_ANON;
61 #endif
62   result = mmap(vaddr, v_size, prot, flags, fd, file_offset);
63   if((unsigned int) result != 0xffffffff) return result;
64
65   /* Sigh.  Alignment must be wrong for mmap.  Do this the hard way. */
66   if(!(flags & MAP_FIXED)) {
67     vaddr = (char *)0x40000000;
68     flags |= MAP_FIXED;
69   };
70
71   mmap(vaddr, v_size, prot, MAP_ANONYMOUS | flags, 0, 0);
72   lseek(fd, file_offset, SEEK_SET);
73   read(fd, vaddr, v_size);
74   return vaddr;
75 };
76 #endif
77
78 void dump_exports(struct PE_Export_Directory * pe_exports, unsigned int load_addr)
79
80   char * Module;
81   int i;
82   u_short * ordinal;
83   u_long * function;
84   u_char ** name, *ename;
85
86   Module = ((char *) load_addr) + pe_exports->Name;
87   dprintf_win32(stddeb,"\n*******EXPORT DATA*******\nModule name is %s, %ld functions, %ld names\n", 
88          Module,
89          pe_exports->Number_Of_Functions,
90          pe_exports->Number_Of_Names);
91
92   ordinal = (u_short *) (((char *) load_addr) + (int) pe_exports->Address_Of_Name_Ordinals);
93   function = (u_long *)  (((char *) load_addr) + (int) pe_exports->AddressOfFunctions);
94   name = (u_char **)  (((char *) load_addr) + (int) pe_exports->AddressOfNames);
95
96   dprintf_win32(stddeb,"%-32s Ordinal Virt Addr\n", "Function Name");
97   for(i=0; i< pe_exports->Number_Of_Functions; i++)
98     {
99       ename =  (char *) (((char *) load_addr) + (int) *name++);
100       dprintf_win32(stddeb,"%-32s %4d    %8.8lx\n", ename, *ordinal++, *function++);
101     }
102 }
103
104 static DWORD PE_FindExportedFunction(struct pe_data *pe, char* funcName)
105 {
106         struct PE_Export_Directory * exports = pe->pe_export;
107         unsigned load_addr = pe->load_addr;
108         u_short * ordinal;
109         u_long * function;
110         u_char ** name, *ename;
111         int i;
112         if(!exports)return 0;
113         ordinal = (u_short *) (((char *) load_addr) + (int) exports->Address_Of_Name_Ordinals);
114         function = (u_long *)  (((char *) load_addr) + (int) exports->AddressOfFunctions);
115         name = (u_char **)  (((char *) load_addr) + (int) exports->AddressOfNames);
116         for(i=0; i<exports->Number_Of_Functions; i++)
117         {
118                 if(HIWORD(funcName))
119                 {
120                         ename =  (char *) (((char *) load_addr) + (int) *name);
121                         if(strcmp(ename,funcName)==0)
122                                 return load_addr+*function;
123                 }else{
124                         if(funcName == (int)*ordinal + exports->Base)
125                                 return load_addr+*function;
126                 }
127                 function++;
128                 ordinal++;
129                 name++;
130         }
131         return 0;
132 }
133
134 DWORD PE_GetProcAddress(HMODULE hModule, char* function)
135 {
136     NE_MODULE *pModule;
137
138     if (!(pModule = MODULE_GetPtr( hModule ))) return 0;
139     if (!(pModule->flags & NE_FFLAGS_WIN32) || !pModule->pe_module) return 0;
140     if (pModule->flags & NE_FFLAGS_BUILTIN)
141         return BUILTIN_GetProcAddress32( pModule, function );
142     return PE_FindExportedFunction( pModule->pe_module, function );
143 }
144
145 void fixup_imports(struct pe_data *pe, HMODULE hModule)
146
147   struct PE_Import_Directory * pe_imp;
148   int fixup_failed=0;
149   unsigned int load_addr = pe->load_addr;
150   int i;
151   NE_MODULE *ne_mod;
152   HMODULE *mod_ptr;
153
154  /* OK, now dump the import list */
155   dprintf_win32(stddeb, "\nDumping imports list\n");
156
157   /* first, count the number of imported non-internal modules */
158   pe_imp = pe->pe_import;
159   for(i=0;pe_imp->ModuleName;pe_imp++)
160         i++;
161
162   /* Now, allocate memory for dlls_to_init */
163   ne_mod = GlobalLock16(hModule);
164   ne_mod->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,(i+1) * sizeof(HMODULE),
165                                       hModule, FALSE, FALSE, FALSE );
166   mod_ptr = GlobalLock16(ne_mod->dlls_to_init);
167   /* load the modules and put their handles into the list */
168   for(i=0,pe_imp = pe->pe_import;pe_imp->ModuleName;pe_imp++)
169   {
170         char *name = (char*)load_addr+pe_imp->ModuleName;
171         mod_ptr[i] = LoadModule(name,(LPVOID)-1);
172         if(mod_ptr[i]<=(HMODULE)32)
173         {
174             char *p, buffer[256];
175
176             /* Try with prepending the path of the current module */
177             GetModuleFileName( hModule, buffer, sizeof(buffer) );
178             if (!(p = strrchr( buffer, '\\' ))) p = buffer;
179             strcpy( p + 1, name );
180             mod_ptr[i] = LoadModule( buffer, (LPVOID)-1 );
181         }
182         if(mod_ptr[i]<=(HMODULE)32)
183         {
184                 fprintf(stderr,"Module %s not found\n",name);
185                 exit(0);
186         }
187         i++;
188   }
189   pe_imp = pe->pe_import;
190   while (pe_imp->ModuleName)
191     {
192       char * Module;
193       struct pe_import_name * pe_name;
194       unsigned int * import_list, *thunk_list;
195
196       Module = ((char *) load_addr) + pe_imp->ModuleName;
197       dprintf_win32(stddeb, "%s\n", Module);
198
199    if(pe_imp->Import_List != 0) { /* original microsoft style */
200       dprintf_win32(stddeb, "Microsoft style imports used\n");
201       import_list = (unsigned int *) 
202         (((unsigned int) load_addr) + pe_imp->Import_List);
203           thunk_list = (unsigned int *)
204           (((unsigned int) load_addr) + pe_imp->Thunk_List);
205
206
207     while(*import_list)
208         {
209           pe_name = (struct pe_import_name *) ((int) load_addr + ((unsigned)*import_list & ~0x80000000));
210           if((unsigned)*import_list & 0x80000000)
211           {
212                 int ordinal=*import_list & (0x80000000-1);
213                 dprintf_win32(stddeb,"--- Ordinal %s,%d\n", Module, ordinal);
214                 *thunk_list = WIN32_GetProcAddress(MODULE_FindModule(Module),
215                         ordinal);
216                 if(!*thunk_list)
217                 {
218                         fprintf(stderr,"No implementation for %s.%d\n",Module, 
219                                 ordinal);
220                         fixup_failed=1;
221                 }
222           }else{ /* import by name */
223           dprintf_win32(stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
224 #ifndef WINELIB /* FIXME: JBP: Should this happen in libwine.a? */
225                 *thunk_list = WIN32_GetProcAddress(MODULE_FindModule(Module),
226                                 pe_name->Name);
227           if(!*thunk_list)
228           {
229                 fprintf(stderr,"No implementation for %s.%d(%s)\n",Module, 
230                         pe_name->Hint, pe_name->Name);
231                 fixup_failed=1;
232           }
233
234 #else
235           fprintf(stderr,"JBP: Call to RELAY32_GetEntryPoint being ignored.\n");
236 #endif
237                 }
238
239           import_list++;
240           thunk_list++;
241         }
242     } else { /* Borland style */
243       dprintf_win32(stddeb, "Borland style imports used\n");
244       thunk_list = (unsigned int *)
245         (((unsigned int) load_addr) + pe_imp->Thunk_List);
246       while(*thunk_list) {
247         pe_name = (struct pe_import_name *) ((int) load_addr + *thunk_list);
248         if((unsigned)pe_name & 0x80000000) {
249           fprintf(stderr,"Import by ordinal not supported\n");
250           exit(0);
251         }
252         dprintf_win32(stddeb, "--- %s %s.%d\n", pe_name->Name, Module, pe_name->Hint);
253 #ifndef WINELIB /* FIXME: JBP: Should this happen in libwine.a? */
254         /* FIXME: Both calls should be unified into GetProcAddress */
255         *thunk_list = WIN32_GetProcAddress(MODULE_FindModule(Module),
256                                            pe_name->Name);
257 #else
258         fprintf(stderr,"JBP: Call to RELAY32_GetEntryPoint being ignored.\n");
259 #endif
260         if(!*thunk_list) {
261           fprintf(stderr,"No implementation for %s.%d\n",Module, pe_name->Hint);
262           fixup_failed=1;
263         }
264         thunk_list++;
265       }
266     }
267     pe_imp++;
268   }
269   if(fixup_failed)exit(1);
270 }
271
272 static void calc_vma_size(struct pe_data *pe)
273 {
274   int i;
275
276   dprintf_win32(stddeb, "Dump of segment table\n");
277   dprintf_win32(stddeb, "   Name    VSz  Vaddr     SzRaw   Fileadr  *Reloc *Lineum #Reloc #Linum Char\n");
278   for(i=0; i< pe->pe_header->coff.NumberOfSections; i++)
279     {
280       dprintf_win32(stddeb, "%8s: %4.4lx %8.8lx %8.8lx %8.8lx %8.8lx %8.8lx %4.4x %4.4x %8.8lx\n", 
281              pe->pe_seg[i].Name, 
282              pe->pe_seg[i].Virtual_Size,
283              pe->pe_seg[i].Virtual_Address,
284              pe->pe_seg[i].Size_Of_Raw_Data,
285              pe->pe_seg[i].PointerToRawData,
286              pe->pe_seg[i].PointerToRelocations,
287              pe->pe_seg[i].PointerToLinenumbers,
288              pe->pe_seg[i].NumberOfRelocations,
289              pe->pe_seg[i].NumberOfLinenumbers,
290              pe->pe_seg[i].Characteristics);
291           pe->vma_size = MAX(pe->vma_size,
292                         pe->pe_seg[i].Virtual_Address + 
293                         pe->pe_seg[i].Size_Of_Raw_Data);
294     }
295 }
296
297 static void do_relocations(struct pe_data *pe)
298 {
299         int delta = pe->load_addr - pe->base_addr;
300         struct PE_Reloc_Block *r = pe->pe_reloc;
301         int hdelta = (delta >> 16) & 0xFFFF;
302         int ldelta = delta & 0xFFFF;
303         /* int reloc_size = */
304         if(delta == 0)
305                 /* Nothing to do */
306                 return;
307         while(r->PageRVA)
308         {
309                 char *page = (char*)pe->load_addr + r->PageRVA;
310                 int count = (r->BlockSize - 8)/2;
311                 int i;
312                 dprintf_fixup(stddeb, "%x relocations for page %lx\n",
313                         count, r->PageRVA);
314                 /* patching in reverse order */
315                 for(i=0;i<count;i++)
316                 {
317                         int offset = r->Relocations[i] & 0xFFF;
318                         int type = r->Relocations[i] >> 12;
319                         dprintf_fixup(stddeb,"patching %x type %x\n", offset, type);
320                         switch(type)
321                         {
322                         case IMAGE_REL_BASED_ABSOLUTE: break;
323                         case IMAGE_REL_BASED_HIGH:
324                                 *(short*)(page+offset) += hdelta;
325                                 break;
326                         case IMAGE_REL_BASED_LOW:
327                                 *(short*)(page+offset) += ldelta;
328                                 break;
329                         case IMAGE_REL_BASED_HIGHLOW:
330 #if 1
331                                 *(int*)(page+offset) += delta;
332 #else
333                                 { int h=*(unsigned short*)(page+offset);
334                                   int l=r->Relocations[++i];
335                                   *(unsigned int*)(page + offset) = (h<<16) + l + delta;
336                                 }
337 #endif
338                                 break;
339                         case IMAGE_REL_BASED_HIGHADJ:
340                                 fprintf(stderr, "Don't know what to do with IMAGE_REL_BASED_HIGHADJ\n");
341                                 break;
342                         case IMAGE_REL_BASED_MIPS_JMPADDR:
343                                 fprintf(stderr, "Is this a MIPS machine ???\n");
344                                 break;
345                         default:
346                                 fprintf(stderr, "Unknown fixup type\n");
347                                 break;
348                         }
349                 }
350                 r = (struct PE_Reloc_Block*)((char*)r + r->BlockSize);
351         }
352 }
353                 
354
355         
356         
357
358 /**********************************************************************
359  *                      PE_LoadImage
360  * Load one PE format executable into memory
361  */
362 static struct pe_data *PE_LoadImage( int fd, HMODULE hModule, WORD offset )
363 {
364     struct pe_data *pe;
365     int i, result;
366     unsigned int load_addr;
367     struct Directory dir;
368
369         pe = xmalloc(sizeof(struct pe_data));
370         memset(pe,0,sizeof(struct pe_data));
371         pe->pe_header = xmalloc(sizeof(struct pe_header_s));
372
373         /* read PE header */
374         lseek( fd, offset, SEEK_SET);
375         read( fd, pe->pe_header, sizeof(struct pe_header_s));
376
377         /* read sections */
378         pe->pe_seg = xmalloc(sizeof(struct pe_segment_table) * 
379                                    pe->pe_header->coff.NumberOfSections);
380         read( fd, pe->pe_seg, sizeof(struct pe_segment_table) * 
381                         pe->pe_header->coff.NumberOfSections);
382
383         load_addr = pe->pe_header->opt_coff.BaseOfImage;
384         pe->base_addr=load_addr;
385         pe->vma_size=0;
386         dprintf_win32(stddeb, "Load addr is %x\n",load_addr);
387         calc_vma_size(pe);
388
389         /* We use malloc here, while a huge part of that address space does
390            not be supported by actual memory. It has to be contiguous, though.
391            I don't know if mmap("/dev/null"); would do any better.
392            What I'd really like to do is a Win32 style VirtualAlloc/MapViewOfFile
393            sequence */
394         load_addr = pe->load_addr = malloc(pe->vma_size);
395         dprintf_win32(stddeb, "Load addr is really %x, range %x\n",
396                 pe->load_addr, pe->vma_size);
397
398
399         for(i=0; i < pe->pe_header->coff.NumberOfSections; i++)
400         {
401                 /* load only non-BSS segments */
402                 if(pe->pe_seg[i].Characteristics & 
403                         ~ IMAGE_SCN_TYPE_CNT_UNINITIALIZED_DATA)
404                 if(lseek(fd,pe->pe_seg[i].PointerToRawData,SEEK_SET) == -1
405                 || read(fd,load_addr + pe->pe_seg[i].Virtual_Address,
406                                 pe->pe_seg[i].Size_Of_Raw_Data) 
407                                 != pe->pe_seg[i].Size_Of_Raw_Data)
408                 {
409                         fprintf(stderr,"Failed to load section %x\n", i);
410                         exit(0);
411                 }
412                 result = load_addr + pe->pe_seg[i].Virtual_Address;
413 #if 0
414         if(!load_addr) {
415                 
416                 result = (int)xmmap((char *)0, pe->pe_seg[i].Virtual_Size,
417                         pe->pe_seg[i].Size_Of_Raw_Data, 7,
418                         MAP_PRIVATE, fd, pe->pe_seg[i].PointerToRawData);
419                 load_addr = (unsigned int) result -  pe->pe_seg[i].Virtual_Address;
420         } else {
421                 result = (int)xmmap((char *) load_addr + pe->pe_seg[i].Virtual_Address, 
422                           pe->pe_seg[i].Virtual_Size,
423                       pe->pe_seg[i].Size_Of_Raw_Data, 7, MAP_PRIVATE | MAP_FIXED, 
424                       fd, pe->pe_seg[i].PointerToRawData);
425         }
426         if(result==-1){
427                 fprintf(stderr,"Could not load section %x to desired address %lx\n",
428                         i, load_addr+pe->pe_seg[i].Virtual_Address);
429                 fprintf(stderr,"Need to implement relocations now\n");
430                 exit(0);
431         }
432 #endif
433
434         if(strcmp(pe->pe_seg[i].Name, ".bss") == 0)
435             memset((void *)result, 0, 
436                    pe->pe_seg[i].Virtual_Size ?
437                    pe->pe_seg[i].Virtual_Size :
438                    pe->pe_seg[i].Size_Of_Raw_Data);
439
440         if(strcmp(pe->pe_seg[i].Name, ".idata") == 0)
441                 pe->pe_import = (struct PE_Import_Directory *) result;
442
443         if(strcmp(pe->pe_seg[i].Name, ".edata") == 0)
444                 pe->pe_export = (struct PE_Export_Directory *) result;
445
446         if(strcmp(pe->pe_seg[i].Name, ".rsrc") == 0) {
447             pe->pe_resource = (struct PE_Resource_Directory *) result;
448 #if 0
449 /* FIXME pe->resource_offset should be deleted from structure if this
450  ifdef doesn't break anything */
451             /* save offset for PE_FindResource */
452             pe->resource_offset = pe->pe_seg[i].Virtual_Address - 
453                                         pe->pe_seg[i].PointerToRawData;
454 #endif  
455             }
456         if(strcmp(pe->pe_seg[i].Name, ".reloc") == 0)
457                 pe->pe_reloc = (struct PE_Reloc_Block *) result;
458
459         }
460
461         /* There is word that the actual loader does not care about the
462            section names, and only goes for the DataDirectory */
463         dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
464         if(dir.Size)
465         {
466                 if(pe->pe_export && 
467                         pe->pe_export!=load_addr+dir.Virtual_address)
468                         fprintf(stderr,"wrong export directory??\n");
469                 /* always trust the directory */
470                 pe->pe_export = load_addr+dir.Virtual_address;
471         }
472
473         dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
474         if(dir.Size)
475         {
476                 if(pe->pe_import && 
477                         pe->pe_import!=load_addr+dir.Virtual_address)
478                         fprintf(stderr,"wrong import directory??\n");
479                 pe->pe_import = load_addr+dir.Virtual_address;
480         }
481
482         dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
483         if(dir.Size)
484         {
485                 if(pe->pe_resource && 
486                         pe->pe_resource!=load_addr+dir.Virtual_address)
487                         fprintf(stderr,"wrong resource directory??\n");
488                 pe->pe_resource = load_addr+dir.Virtual_address;
489         }
490
491         dir=pe->pe_header->opt_coff.DataDirectory[IMAGE_FILE_BASE_RELOCATION_TABLE];
492         if(dir.Size)
493         {
494                 if(pe->pe_reloc && 
495                         pe->pe_reloc!=load_addr+dir.Virtual_address)
496                         fprintf(stderr,"wrong relocation list??\n");
497                 pe->pe_reloc = load_addr+dir.Virtual_address;
498         }
499
500         if(pe->pe_header->opt_coff.DataDirectory
501                 [IMAGE_FILE_EXCEPTION_DIRECTORY].Size)
502                 dprintf_win32(stdnimp,"Exception directory ignored\n");
503
504         if(pe->pe_header->opt_coff.DataDirectory
505                 [IMAGE_FILE_SECURITY_DIRECTORY].Size)
506                 dprintf_win32(stdnimp,"Security directory ignored\n");
507
508         if(pe->pe_header->opt_coff.DataDirectory
509                 [IMAGE_FILE_DEBUG_DIRECTORY].Size)
510                 dprintf_win32(stdnimp,"Debug directory ignored\n");
511
512         if(pe->pe_header->opt_coff.DataDirectory
513                 [IMAGE_FILE_DESCRIPTION_STRING].Size)
514                 dprintf_win32(stdnimp,"Description string ignored\n");
515
516         if(pe->pe_header->opt_coff.DataDirectory
517                 [IMAGE_FILE_MACHINE_VALUE].Size)
518                 dprintf_win32(stdnimp,"Machine Value ignored\n");
519
520         if(pe->pe_header->opt_coff.DataDirectory
521                 [IMAGE_FILE_THREAD_LOCAL_STORAGE].Size)
522                  dprintf_win32(stdnimp,"Thread local storage ignored\n");
523
524         if(pe->pe_header->opt_coff.DataDirectory
525                 [IMAGE_FILE_CALLBACK_DIRECTORY].Size)
526                 dprintf_win32(stdnimp,"Callback directory ignored\n");
527
528
529         if(pe->pe_import) fixup_imports(pe, hModule);
530         if(pe->pe_export) dump_exports(pe->pe_export,load_addr);
531         if(pe->pe_reloc) do_relocations(pe);
532         return pe;
533 }
534
535 HINSTANCE MODULE_CreateInstance(HMODULE hModule,LOADPARAMS *params);
536 void InitTask(SIGCONTEXT context);
537
538 HINSTANCE PE_LoadModule( int fd, OFSTRUCT *ofs, LOADPARAMS* params )
539 {
540         PE_MODULE *pe;
541         int size, of_size;
542         NE_MODULE *pModule;
543         SEGTABLEENTRY *pSegment;
544         char *pStr;
545         DWORD cts;
546         HMODULE hModule;
547         HINSTANCE hInstance;
548         struct mz_header_s mz_header;
549
550         lseek(fd,0,SEEK_SET);
551         read( fd, &mz_header, sizeof(mz_header) );
552
553         of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
554                   + strlen(ofs->szPathName) + 1;
555         size = sizeof(NE_MODULE) +
556                /* loaded file info */
557                of_size +
558                /* segment table: DS,CS */
559                2 * sizeof(SEGTABLEENTRY) +
560                /* name table */
561                9 +
562                /* several empty tables */
563                8;
564
565         hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
566         if (!hModule) return (HINSTANCE)11;  /* invalid exe */
567
568         FarSetOwner( hModule, hModule );
569         
570         pModule = (NE_MODULE*)GlobalLock16(hModule);
571
572         /* Set all used entries */
573         pModule->magic=NE_SIGNATURE;
574         pModule->count=1;
575         pModule->next=0;
576         pModule->flags=NE_FFLAGS_WIN32;
577         pModule->dgroup=1;
578         pModule->ss=1;
579         pModule->cs=2;
580         /* Who wants to LocalAlloc for a PE Module? */
581         pModule->heap_size=0x1000;
582         pModule->stack_size=0xF000;
583         pModule->seg_count=1;
584         pModule->modref_count=0;
585         pModule->nrname_size=0;
586         pModule->fileinfo=sizeof(NE_MODULE);
587         pModule->os_flags=NE_OSFLAGS_WINDOWS;
588         pModule->expected_version=0x30A;
589         pModule->self = hModule;
590
591         /* Set loaded file information */
592         memcpy( pModule + 1, ofs, of_size );
593         ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
594
595         pSegment=(SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
596         pModule->seg_table=pModule->dgroup_entry=(int)pSegment-(int)pModule;
597         pSegment->size=0;
598         pSegment->flags=NE_SEGFLAGS_DATA;
599         pSegment->minsize=0x1000;
600         pSegment++;
601
602         cts=(DWORD)MODULE_GetWndProcEntry16("Win32CallToStart");
603 #ifdef WINELIB32
604         pSegment->selector=(void*)cts;
605         pModule->ip=0;
606 #else
607         pSegment->selector=cts>>16;  /* FIXME!! */
608         pModule->ip=cts & 0xFFFF;
609 #endif
610         pSegment++;
611
612         pStr=(char*)pSegment;
613         pModule->name_table=(int)pStr-(int)pModule;
614         strcpy(pStr,"\x08W32SXXXX");
615         pStr+=9;
616
617         /* All tables zero terminated */
618         pModule->res_table=pModule->import_table=pModule->entry_table=
619                 (int)pStr-(int)pModule;
620
621         MODULE_RegisterModule( pModule );
622
623         pe = PE_LoadImage( fd, hModule, mz_header.ne_offset );
624
625         pModule->pe_module = pe;
626         pModule->heap_size=0x1000;
627         pModule->stack_size=0xE000;
628
629         /* CreateInstance allocates now 64KB */
630         hInstance=MODULE_CreateInstance(hModule,NULL /* FIX: NULL? really? */);
631
632         /* FIXME: Is this really the correct place to initialise the DLL? */
633         if ((pe->pe_header->coff.Characteristics & IMAGE_FILE_DLL)) {
634 /*            PE_InitDLL(hModule); */
635         } else {
636             TASK_CreateTask(hModule,hInstance,0,
637                 params->hEnvironment,(LPSTR)PTR_SEG_TO_LIN(params->cmdLine),
638                 *((WORD*)PTR_SEG_TO_LIN(params->showCmd)+1));
639             PE_InitializeDLLs(hModule);
640         }
641         return hInstance;
642 }
643
644 int USER_InitApp(HINSTANCE hInstance);
645 void PE_InitTEB(int hTEB);
646
647 void PE_Win32CallToStart(SIGCONTEXT context)
648 {
649     int fs;
650     HMODULE hModule;
651     NE_MODULE *pModule;
652
653     dprintf_win32(stddeb,"Going to start Win32 program\n");     
654     InitTask(context);
655     hModule = GetExePtr( GetCurrentTask() );
656     pModule = MODULE_GetPtr( hModule );
657     USER_InitApp( hModule );
658     fs=(int)GlobalAlloc16(GHND,0x10000);
659     PE_InitTEB(fs);
660     __asm__ __volatile__("movw %w0,%%fs"::"r" (fs));
661     CallTaskStart32( (FARPROC)(pModule->pe_module->load_addr + 
662                                pModule->pe_module->pe_header->opt_coff.AddressOfEntryPoint) );
663 }
664
665 int PE_UnloadImage( HMODULE hModule )
666 {
667         printf("PEunloadImage() called!\n");
668         /* free resources, image, unmap */
669         return 1;
670 }
671
672 static void PE_InitDLL(HMODULE hModule)
673 {
674     NE_MODULE *pModule;
675     PE_MODULE *pe;
676
677     hModule = GetExePtr(hModule);
678     if (!(pModule = MODULE_GetPtr(hModule))) return;
679     if (!(pModule->flags & NE_FFLAGS_WIN32) || !(pe = pModule->pe_module))
680         return;
681
682     /* FIXME: What are the correct values for parameters 2 and 3? */
683         
684     /* Is this a library? */
685     if (pe->pe_header->coff.Characteristics & IMAGE_FILE_DLL)
686     {
687         printf("InitPEDLL() called!\n");
688         CallDLLEntryProc32( (FARPROC)(pe->load_addr + 
689                                   pe->pe_header->opt_coff.AddressOfEntryPoint),
690                             hModule, 0, 0 );
691     }
692 }
693
694
695 /* FIXME: This stuff is all on a "well it works" basis. An implementation
696 based on some kind of documentation would be greatly appreciated :-) */
697
698 typedef struct
699 {
700     void        *Except;
701     void        *stack;
702     int         dummy1[4];
703     struct TEB  *TEBDSAlias;
704     int         dummy2[2];
705     int         taskid;
706 } TEB;
707
708 void PE_InitTEB(int hTEB)
709 {
710     TDB *pTask;
711     TEB *pTEB;
712
713     pTask = (TDB *)(GlobalLock16(GetCurrentTask() & 0xffff));
714     pTEB = (TEB *)(PTR_SEG_OFF_TO_LIN(hTEB, 0));
715     pTEB->stack = (void *)(GlobalLock16(pTask->hStack32));
716     pTEB->Except = (void *)(-1); 
717     pTEB->TEBDSAlias = pTEB;
718     pTEB->taskid = getpid();
719 }
720
721 void PE_InitializeDLLs(HMODULE hModule)
722 {
723         NE_MODULE *pModule;
724         HMODULE *pDLL;
725         pModule = MODULE_GetPtr( GetExePtr(hModule) );
726         if (pModule->dlls_to_init)
727         {
728                 HANDLE to_init = pModule->dlls_to_init;
729                 pModule->dlls_to_init = 0;
730                 for (pDLL = (HMODULE *)GlobalLock16( to_init ); *pDLL; pDLL++)
731                 {
732                         PE_InitializeDLLs( *pDLL );
733                         PE_InitDLL( *pDLL );
734                 }
735                 GlobalFree16( to_init );
736         }
737         PE_InitDLL( hModule );
738 }
739 #endif /* WINELIB */