Perform NE_InitProcess in the context of the new task.
[wine] / loader / ne / module.c
1 /*
2  * NE modules
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <ctype.h>
13 #include "wine/winbase16.h"
14 #include "winerror.h"
15 #include "module.h"
16 #include "neexe.h"
17 #include "toolhelp.h"
18 #include "file.h"
19 #include "ldt.h"
20 #include "callback.h"
21 #include "heap.h"
22 #include "task.h"
23 #include "global.h"
24 #include "process.h"
25 #include "snoop.h"
26 #include "syslevel.h"
27 #include "builtin16.h"
28 #include "stackframe.h"
29 #include "debugtools.h"
30 #include "loadorder.h"
31 #include "elfdll.h"
32 #include "server.h"
33
34 DEFAULT_DEBUG_CHANNEL(module);
35
36 #define hFirstModule (pThhook->hExeHead)
37
38 static NE_MODULE *pCachedModule = 0;  /* Module cached by NE_OpenFile */
39
40 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
41 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
42 static void NE_InitProcess(void) WINE_NORETURN;
43
44 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
45
46 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
47
48 /***********************************************************************
49  *           NE_GetPtr
50  */
51 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
52 {
53     return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
54 }
55
56
57 /***********************************************************************
58  *           NE_DumpModule
59  */
60 void NE_DumpModule( HMODULE16 hModule )
61 {
62     int i, ordinal;
63     SEGTABLEENTRY *pSeg;
64     BYTE *pstr;
65     WORD *pword;
66     NE_MODULE *pModule;
67     ET_BUNDLE *bundle;
68     ET_ENTRY *entry;
69
70     if (!(pModule = NE_GetPtr( hModule )))
71     {
72         MESSAGE( "**** %04x is not a module handle\n", hModule );
73         return;
74     }
75
76       /* Dump the module info */
77     DPRINTF( "---\n" );
78     DPRINTF( "Module %04x:\n", hModule );
79     DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
80           pModule->count, pModule->flags,
81           pModule->heap_size, pModule->stack_size );
82     DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
83           pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
84           pModule->seg_count, pModule->modref_count );
85     DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
86           pModule->os_flags, pModule->min_swap_area,
87           pModule->expected_version );
88     if (pModule->flags & NE_FFLAGS_WIN32)
89         DPRINTF( "PE module=%08x\n", pModule->module32 );
90
91       /* Dump the file info */
92     DPRINTF( "---\n" );
93     DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
94
95       /* Dump the segment table */
96     DPRINTF( "---\n" );
97     DPRINTF( "Segment table:\n" );
98     pSeg = NE_SEG_TABLE( pModule );
99     for (i = 0; i < pModule->seg_count; i++, pSeg++)
100         DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
101               i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
102               pSeg->minsize, pSeg->hSeg );
103
104       /* Dump the resource table */
105     DPRINTF( "---\n" );
106     DPRINTF( "Resource table:\n" );
107     if (pModule->res_table)
108     {
109         pword = (WORD *)((BYTE *)pModule + pModule->res_table);
110         DPRINTF( "Alignment: %d\n", *pword++ );
111         while (*pword)
112         {
113             struct resource_typeinfo_s *ptr = (struct resource_typeinfo_s *)pword;
114             struct resource_nameinfo_s *pname = (struct resource_nameinfo_s *)(ptr + 1);
115             DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
116             for (i = 0; i < ptr->count; i++, pname++)
117                 DPRINTF( "offset=%d len=%d id=%04x\n",
118                       pname->offset, pname->length, pname->id );
119             pword = (WORD *)pname;
120         }
121     }
122     else DPRINTF( "None\n" );
123
124       /* Dump the resident name table */
125     DPRINTF( "---\n" );
126     DPRINTF( "Resident-name table:\n" );
127     pstr = (char *)pModule + pModule->name_table;
128     while (*pstr)
129     {
130         DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
131               *(WORD *)(pstr + *pstr + 1) );
132         pstr += *pstr + 1 + sizeof(WORD);
133     }
134
135       /* Dump the module reference table */
136     DPRINTF( "---\n" );
137     DPRINTF( "Module ref table:\n" );
138     if (pModule->modref_table)
139     {
140         pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
141         for (i = 0; i < pModule->modref_count; i++, pword++)
142         {
143             char name[10];
144             GetModuleName16( *pword, name, sizeof(name) );
145             DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
146         }
147     }
148     else DPRINTF( "None\n" );
149
150       /* Dump the entry table */
151     DPRINTF( "---\n" );
152     DPRINTF( "Entry table:\n" );
153     bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);    
154     do {
155         entry = (ET_ENTRY *)((BYTE *)bundle+6);
156         DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
157         ordinal = bundle->first;
158         while (ordinal < bundle->last)
159         {
160             if (entry->type == 0xff)
161                 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
162             else
163                 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
164             entry++;
165     }
166     } while ( (bundle->next)
167            && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
168
169     /* Dump the non-resident names table */
170     DPRINTF( "---\n" );
171     DPRINTF( "Non-resident names table:\n" );
172     if (pModule->nrname_handle)
173     {
174         pstr = (char *)GlobalLock16( pModule->nrname_handle );
175         while (*pstr)
176         {
177             DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
178                    *(WORD *)(pstr + *pstr + 1) );
179             pstr += *pstr + 1 + sizeof(WORD);
180         }
181     }
182     DPRINTF( "\n" );
183 }
184
185
186 /***********************************************************************
187  *           NE_WalkModules
188  *
189  * Walk the module list and print the modules.
190  */
191 void NE_WalkModules(void)
192 {
193     HMODULE16 hModule = hFirstModule;
194     MESSAGE( "Module Flags Name\n" );
195     while (hModule)
196     {
197         NE_MODULE *pModule = NE_GetPtr( hModule );
198         if (!pModule)
199         {
200             MESSAGE( "Bad module %04x in list\n", hModule );
201             return;
202         }
203         MESSAGE( " %04x  %04x  %.*s\n", hModule, pModule->flags,
204                  *((char *)pModule + pModule->name_table),
205                  (char *)pModule + pModule->name_table + 1 );
206         hModule = pModule->next;
207     }
208 }
209
210
211 /**********************************************************************
212  *           NE_RegisterModule
213  */
214 void NE_RegisterModule( NE_MODULE *pModule )
215 {
216     pModule->next = hFirstModule;
217     hFirstModule = pModule->self;
218 }
219
220
221 /***********************************************************************
222  *           NE_GetOrdinal
223  *
224  * Lookup the ordinal for a given name.
225  */
226 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
227 {
228     unsigned char buffer[256], *cpnt;
229     BYTE len;
230     NE_MODULE *pModule;
231
232     if (!(pModule = NE_GetPtr( hModule ))) return 0;
233     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
234
235     TRACE("(%04x,'%s')\n", hModule, name );
236
237       /* First handle names of the form '#xxxx' */
238
239     if (name[0] == '#') return atoi( name + 1 );
240
241       /* Now copy and uppercase the string */
242
243     strcpy( buffer, name );
244     CharUpperA( buffer );
245     len = strlen( buffer );
246
247       /* First search the resident names */
248
249     cpnt = (char *)pModule + pModule->name_table;
250
251       /* Skip the first entry (module name) */
252     cpnt += *cpnt + 1 + sizeof(WORD);
253     while (*cpnt)
254     {
255         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
256         {
257             TRACE("  Found: ordinal=%d\n",
258                             *(WORD *)(cpnt + *cpnt + 1) );
259             return *(WORD *)(cpnt + *cpnt + 1);
260         }
261         cpnt += *cpnt + 1 + sizeof(WORD);
262     }
263
264       /* Now search the non-resident names table */
265
266     if (!pModule->nrname_handle) return 0;  /* No non-resident table */
267     cpnt = (char *)GlobalLock16( pModule->nrname_handle );
268
269       /* Skip the first entry (module description string) */
270     cpnt += *cpnt + 1 + sizeof(WORD);
271     while (*cpnt)
272     {
273         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
274         {
275             TRACE("  Found: ordinal=%d\n",
276                             *(WORD *)(cpnt + *cpnt + 1) );
277             return *(WORD *)(cpnt + *cpnt + 1);
278         }
279         cpnt += *cpnt + 1 + sizeof(WORD);
280     }
281     return 0;
282 }
283
284
285 /***********************************************************************
286  *           NE_GetEntryPoint   (WPROCS.27)
287  *
288  * Return the entry point for a given ordinal.
289  */
290 FARPROC16 WINAPI WIN16_NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
291 {
292     FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
293     CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
294     return ret;
295 }
296 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
297 {
298     return NE_GetEntryPointEx( hModule, ordinal, TRUE );
299 }
300 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
301 {
302     NE_MODULE *pModule;
303     WORD sel, offset, i;
304
305     ET_ENTRY *entry;
306     ET_BUNDLE *bundle;
307
308     if (!(pModule = NE_GetPtr( hModule ))) return 0;
309     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
310
311     bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
312     while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
313     {
314         if (!(bundle->next))
315             return 0;
316         bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
317     }
318
319     entry = (ET_ENTRY *)((BYTE *)bundle+6);
320     for (i=0; i < (ordinal - bundle->first - 1); i++)
321         entry++;
322
323     sel = entry->segnum;
324     offset = entry->offs;
325
326     if (sel == 0xfe) sel = 0xffff;  /* constant entry */
327     else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
328     if (sel==0xffff)
329         return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
330     if (!snoop)
331         return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
332     else
333         return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset ));
334 }
335
336
337 /***********************************************************************
338  *           NE_SetEntryPoint
339  *
340  * Change the value of an entry point. Use with caution!
341  * It can only change the offset value, not the selector.
342  */
343 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
344 {
345     NE_MODULE *pModule;
346     ET_ENTRY *entry;
347     ET_BUNDLE *bundle;
348     int i;
349
350     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
351     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
352
353     bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
354     while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
355         {
356         bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
357         if (!(bundle->next))
358             return 0;
359     }
360
361     entry = (ET_ENTRY *)((BYTE *)bundle+6);
362     for (i=0; i < (ordinal - bundle->first - 1); i++)
363         entry++;
364
365     entry->offs = offset;
366     return TRUE;
367 }
368
369
370 /***********************************************************************
371  *           NE_OpenFile
372  */
373 HANDLE NE_OpenFile( NE_MODULE *pModule )
374 {
375     char *name;
376
377     static HANDLE cachedfd = -1;
378
379     TRACE("(%p) cache: mod=%p fd=%d\n",
380            pModule, pCachedModule, cachedfd );
381     if (pCachedModule == pModule) return cachedfd;
382     CloseHandle( cachedfd );
383     pCachedModule = pModule;
384     name = NE_MODULE_NAME( pModule );
385     if ((cachedfd = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
386                                    NULL, OPEN_EXISTING, 0, -1 )) == -1)
387         MESSAGE( "Can't open file '%s' for module %04x\n", name, pModule->self );
388     TRACE("opened '%s' -> %d\n",
389                     name, cachedfd );
390     return cachedfd;
391 }
392
393
394 /***********************************************************************
395  *           NE_LoadExeHeader
396  */
397 static HMODULE16 NE_LoadExeHeader( LPCSTR filename )
398 {
399     IMAGE_DOS_HEADER mz_header;
400     IMAGE_OS2_HEADER ne_header;
401     int size;
402     HMODULE16 hModule;
403     NE_MODULE *pModule;
404     BYTE *pData, *pTempEntryTable;
405     char *buffer, *fastload = NULL;
406     int fastload_offset = 0, fastload_length = 0;
407     ET_ENTRY *entry;
408     ET_BUNDLE *bundle, *oldbundle;
409     HFILE16 hFile;
410     OFSTRUCT ofs;
411
412     /* Open file */
413     if ((hFile = OpenFile16( filename, &ofs, OF_READ )) == HFILE_ERROR16)
414         return (HMODULE16)2;  /* File not found */
415
416   /* Read a block from either the file or the fast-load area. */
417 #define READ(offset,size,buffer) \
418        ((fastload && ((offset) >= fastload_offset) && \
419          ((offset)+(size) <= fastload_offset+fastload_length)) ? \
420         (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
421         (_llseek16( hFile, (offset), SEEK_SET), \
422          _hread16( hFile, (buffer), (size) ) == (size)))
423
424     _llseek16( hFile, 0, SEEK_SET );
425     if ((_hread16(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
426         (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
427     {
428         _lclose16( hFile );
429         return (HMODULE16)11;  /* invalid exe */
430     }
431
432     _llseek16( hFile, mz_header.e_lfanew, SEEK_SET );
433     if (_hread16( hFile, &ne_header, sizeof(ne_header) ) != sizeof(ne_header))
434     {
435         _lclose16( hFile );
436         return (HMODULE16)11;  /* invalid exe */
437     }
438
439     if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21;  /* win32 exe */
440     if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11;  /* invalid exe */
441
442     if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
443       MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
444       _lclose16( hFile );
445       return (HMODULE16)12;
446     }
447
448     /* We now have a valid NE header */
449
450     size = sizeof(NE_MODULE) +
451              /* segment table */
452            ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
453              /* resource table */
454            ne_header.ne_restab - ne_header.ne_rsrctab +
455              /* resident names table */
456            ne_header.ne_modtab - ne_header.ne_restab +
457              /* module ref table */
458            ne_header.ne_cmod * sizeof(WORD) + 
459              /* imported names table */
460            ne_header.ne_enttab - ne_header.ne_imptab +
461              /* entry table length */
462            ne_header.ne_cbenttab +
463              /* entry table extra conversion space */
464            sizeof(ET_BUNDLE) +
465            2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
466              /* loaded file info */
467            sizeof(OFSTRUCT)-sizeof(ofs.szPathName)+strlen(ofs.szPathName)+1;
468
469     hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
470     if (!hModule) 
471     {
472         _lclose16( hFile );
473         return (HMODULE16)11;  /* invalid exe */
474     }
475
476     FarSetOwner16( hModule, hModule );
477     pModule = (NE_MODULE *)GlobalLock16( hModule );
478     memcpy( pModule, &ne_header, sizeof(ne_header) );
479     pModule->count = 0;
480     /* check *programs* for default minimal stack size */
481     if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
482                 && (pModule->stack_size < 0x1400) )
483                 pModule->stack_size = 0x1400;
484     pModule->module32 = 0;
485     pModule->self = hModule;
486     pModule->self_loading_sel = 0;
487     pData = (BYTE *)(pModule + 1);
488
489     /* Clear internal Wine flags in case they are set in the EXE file */
490
491     pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
492
493     /* Read the fast-load area */
494
495     if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
496     {
497         fastload_offset=ne_header.fastload_offset << ne_header.ne_align;
498         fastload_length=ne_header.fastload_length << ne_header.ne_align;
499         TRACE("Using fast-load area offset=%x len=%d\n",
500                         fastload_offset, fastload_length );
501         if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
502         {
503             _llseek16( hFile, fastload_offset, SEEK_SET);
504             if (_hread16(hFile, fastload, fastload_length) != fastload_length)
505             {
506                 HeapFree( GetProcessHeap(), 0, fastload );
507                 WARN("Error reading fast-load area!\n");
508                 fastload = NULL;
509             }
510         }
511     }
512
513     /* Get the segment table */
514
515     pModule->seg_table = (int)pData - (int)pModule;
516     buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
517                                       sizeof(struct ne_segment_table_entry_s));
518     if (buffer)
519     {
520         int i;
521         struct ne_segment_table_entry_s *pSeg;
522
523         if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
524              ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
525              buffer ))
526         {
527             HeapFree( GetProcessHeap(), 0, buffer );
528             if (fastload)
529                 HeapFree( GetProcessHeap(), 0, fastload );
530             GlobalFree16( hModule );
531             _lclose16( hFile );
532             return (HMODULE16)11;  /* invalid exe */
533         }
534         pSeg = (struct ne_segment_table_entry_s *)buffer;
535         for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
536         {
537             memcpy( pData, pSeg, sizeof(*pSeg) );
538             pData += sizeof(SEGTABLEENTRY);
539         }
540         HeapFree( GetProcessHeap(), 0, buffer );
541     }
542     else
543     {
544         if (fastload)
545             HeapFree( GetProcessHeap(), 0, fastload );
546         GlobalFree16( hModule );
547         _lclose16( hFile );
548         return (HMODULE16)11;  /* invalid exe */
549     }
550
551     /* Get the resource table */
552
553     if (ne_header.ne_rsrctab < ne_header.ne_restab)
554     {
555         pModule->res_table = (int)pData - (int)pModule;
556         if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
557                   ne_header.ne_restab - ne_header.ne_rsrctab,
558                   pData )) 
559         {
560             _lclose16( hFile );
561             return (HMODULE16)11;  /* invalid exe */
562         }
563         pData += ne_header.ne_restab - ne_header.ne_rsrctab;
564         NE_InitResourceHandler( hModule );
565     }
566     else pModule->res_table = 0;  /* No resource table */
567
568     /* Get the resident names table */
569
570     pModule->name_table = (int)pData - (int)pModule;
571     if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
572                ne_header.ne_modtab - ne_header.ne_restab,
573                pData ))
574     {
575         if (fastload)
576             HeapFree( GetProcessHeap(), 0, fastload );
577         GlobalFree16( hModule );
578         _lclose16( hFile );
579         return (HMODULE16)11;  /* invalid exe */
580     }
581     pData += ne_header.ne_modtab - ne_header.ne_restab;
582
583     /* Get the module references table */
584
585     if (ne_header.ne_cmod > 0)
586     {
587         pModule->modref_table = (int)pData - (int)pModule;
588         if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
589                   ne_header.ne_cmod * sizeof(WORD),
590                   pData ))
591         {
592             if (fastload)
593                 HeapFree( GetProcessHeap(), 0, fastload );
594             GlobalFree16( hModule );
595             _lclose16( hFile );
596             return (HMODULE16)11;  /* invalid exe */
597         }
598         pData += ne_header.ne_cmod * sizeof(WORD);
599     }
600     else pModule->modref_table = 0;  /* No module references */
601
602     /* Get the imported names table */
603
604     pModule->import_table = (int)pData - (int)pModule;
605     if (!READ( mz_header.e_lfanew + ne_header.ne_imptab, 
606                ne_header.ne_enttab - ne_header.ne_imptab,
607                pData ))
608     {
609         if (fastload)
610             HeapFree( GetProcessHeap(), 0, fastload );
611         GlobalFree16( hModule );
612         _lclose16( hFile );
613         return (HMODULE16)11;  /* invalid exe */
614     }
615     pData += ne_header.ne_enttab - ne_header.ne_imptab;
616
617     /* Load entry table, convert it to the optimized version used by Windows */
618
619     if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
620     {
621         BYTE nr_entries, type, *s;
622
623         TRACE("Converting entry table.\n");
624     pModule->entry_table = (int)pData - (int)pModule;
625     if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
626                 ne_header.ne_cbenttab, pTempEntryTable ))
627     {
628             HeapFree( GetProcessHeap(), 0, pTempEntryTable );
629             if (fastload)
630                 HeapFree( GetProcessHeap(), 0, fastload );
631         GlobalFree16( hModule );
632         _lclose16( hFile );
633         return (HMODULE16)11;  /* invalid exe */
634     }
635
636         s = pTempEntryTable;
637         TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
638
639         bundle = (ET_BUNDLE *)pData;
640         TRACE("first bundle: %p\n", bundle);
641         memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
642         entry = (ET_ENTRY *)((BYTE *)bundle+6);
643
644         while ((nr_entries = *s++))
645         {
646             if ((type = *s++))
647             {
648                 bundle->last += nr_entries;
649                 if (type == 0xff)
650                 while (nr_entries--)
651                 {
652                     entry->type   = type;
653                     entry->flags  = *s++;
654                     s += 2;
655                     entry->segnum = *s++;
656                     entry->offs   = *(WORD *)s; s += 2;
657                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
658                     entry++;
659                 }
660                 else
661                 while (nr_entries--)
662                 {
663                     entry->type   = type;
664                     entry->flags  = *s++;
665                     entry->segnum = type;
666                     entry->offs   = *(WORD *)s; s += 2;
667                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
668                     entry++;
669                 }
670             }
671             else
672             {
673                 if (bundle->first == bundle->last)
674                 {
675                     bundle->first += nr_entries;
676                     bundle->last += nr_entries;
677                 }
678                 else
679                 {
680                     oldbundle = bundle;
681                     oldbundle->next = ((int)entry - (int)pModule);
682                     bundle = (ET_BUNDLE *)entry;
683                     TRACE("new bundle: %p\n", bundle);
684                     bundle->first = bundle->last =
685                         oldbundle->last + nr_entries;
686                     bundle->next = 0;
687                     (BYTE *)entry += sizeof(ET_BUNDLE);
688                 }
689             }
690         }
691         HeapFree( GetProcessHeap(), 0, pTempEntryTable );
692     }
693     else
694     {
695         if (fastload)
696             HeapFree( GetProcessHeap(), 0, fastload );
697         GlobalFree16( hModule );
698         _lclose16( hFile );
699         return (HMODULE16)11;  /* invalid exe */
700     }
701
702     pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
703              2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
704
705     if ((DWORD)entry > (DWORD)pData)
706        ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
707
708     /* Store the filename information */
709
710     pModule->fileinfo = (int)pData - (int)pModule;
711     size = sizeof(OFSTRUCT)-sizeof(ofs.szPathName)+strlen(ofs.szPathName)+1;
712     ofs.cBytes = size - 1;
713     memcpy( pData, &ofs, size );
714     pData += size;
715
716     /* Free the fast-load area */
717
718 #undef READ
719     if (fastload)
720         HeapFree( GetProcessHeap(), 0, fastload );
721
722     /* Get the non-resident names table */
723
724     if (ne_header.ne_cbnrestab)
725     {
726         pModule->nrname_handle = GLOBAL_Alloc( 0, ne_header.ne_cbnrestab,
727                                                hModule, FALSE, FALSE, FALSE );
728         if (!pModule->nrname_handle)
729         {
730             GlobalFree16( hModule );
731             _lclose16( hFile );
732             return (HMODULE16)11;  /* invalid exe */
733         }
734         buffer = GlobalLock16( pModule->nrname_handle );
735         _llseek16( hFile, ne_header.ne_nrestab, SEEK_SET );
736         if (_hread16( hFile, buffer, ne_header.ne_cbnrestab )
737               != ne_header.ne_cbnrestab)
738         {
739             GlobalFree16( pModule->nrname_handle );
740             GlobalFree16( hModule );
741             _lclose16( hFile );
742             return (HMODULE16)11;  /* invalid exe */
743         }
744     }
745     else pModule->nrname_handle = 0;
746
747     /* Allocate a segment for the implicitly-loaded DLLs */
748
749     if (pModule->modref_count)
750     {
751         pModule->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,
752                                     (pModule->modref_count+1)*sizeof(HMODULE16),
753                                     hModule, FALSE, FALSE, FALSE );
754         if (!pModule->dlls_to_init)
755         {
756             if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
757             GlobalFree16( hModule );
758             _lclose16( hFile );
759             return (HMODULE16)11;  /* invalid exe */
760         }
761     }
762     else pModule->dlls_to_init = 0;
763
764     NE_RegisterModule( pModule );
765     SNOOP16_RegisterDLL(pModule,ofs.szPathName);
766
767     _lclose16( hFile );
768     return hModule;
769 }
770
771
772 /***********************************************************************
773  *           NE_LoadDLLs
774  *
775  * Load all DLLs implicitly linked to a module.
776  */
777 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
778 {
779     int i;
780     WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
781     WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
782
783     for (i = 0; i < pModule->modref_count; i++, pModRef++)
784     {
785         char buffer[260], *p;
786         BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
787         memcpy( buffer, pstr + 1, *pstr );
788         *(buffer + *pstr) = 0; /* terminate it */
789
790         TRACE("Loading '%s'\n", buffer );
791         if (!(*pModRef = GetModuleHandle16( buffer )))
792         {
793             /* If the DLL is not loaded yet, load it and store */
794             /* its handle in the list of DLLs to initialize.   */
795             HMODULE16 hDLL;
796
797             /* Append .DLL to name if no extension present */
798             if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
799                     strcat( buffer, ".DLL" );
800
801             if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
802             {
803                 /* FIXME: cleanup what was done */
804
805                 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
806                      buffer, *((BYTE*)pModule + pModule->name_table),
807                      (char *)pModule + pModule->name_table + 1, hDLL );
808                 return FALSE;
809             }
810             *pModRef = GetExePtr( hDLL );
811             *pDLLs++ = *pModRef;
812         }
813         else  /* Increment the reference count of the DLL */
814         {
815             NE_MODULE *pOldDLL;
816
817             pOldDLL = NE_GetPtr( *pModRef );
818             if (pOldDLL) pOldDLL->count++;
819         }
820     }
821     return TRUE;
822 }
823
824
825 /**********************************************************************
826  *          NE_DoLoadModule
827  *
828  * Load first instance of NE module from file.
829  *
830  * pModule must point to a module structure prepared by NE_LoadExeHeader.
831  * This routine must never be called twice on a module.
832  *
833  */
834 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
835 {
836     /* Allocate the segments for this module */
837
838     if (!NE_CreateAllSegments( pModule ))
839         return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
840
841     /* Load the referenced DLLs */
842
843     if (!NE_LoadDLLs( pModule ))
844         return ERROR_FILE_NOT_FOUND; /* 2 */
845
846     /* Load the segments */
847
848     NE_LoadAllSegments( pModule );
849
850     /* Make sure the usage count is 1 on the first loading of  */
851     /* the module, even if it contains circular DLL references */
852
853     pModule->count = 1;
854
855     return NE_GetInstance( pModule );
856 }
857
858 /**********************************************************************
859  *          NE_LoadModule
860  *
861  * Load first instance of NE module. (Note: caller is responsible for 
862  * ensuring the module isn't already loaded!)
863  *
864  * If the module turns out to be an executable module, only a 
865  * handle to a module stub is returned; this needs to be initialized
866  * by calling NE_DoLoadModule later, in the context of the newly
867  * created process.
868  *
869  * If lib_only is TRUE, however, the module is perforce treated
870  * like a DLL module, even if it is an executable module.
871  * 
872  */
873 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
874 {
875     NE_MODULE *pModule;
876     HMODULE16 hModule;
877     HINSTANCE16 hInstance;
878
879     hModule = NE_LoadExeHeader( name );
880     if (hModule < 32) return hModule;
881
882     pModule = NE_GetPtr( hModule );
883     if ( !pModule ) return hModule;
884
885     if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
886         return hModule;
887
888     hInstance = NE_DoLoadModule( pModule );
889     if ( hInstance < 32 )
890     {
891         /* cleanup ... */
892         NE_FreeModule( hModule, 0 );
893     }
894
895     return hInstance;
896 }
897
898
899 /**********************************************************************
900  *          MODULE_LoadModule16
901  *
902  * Load a NE module in the order of the loadorder specification.
903  * The caller is responsible that the module is not loaded already.
904  *
905  */
906 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
907 {
908         HINSTANCE16 hinst;
909         int i;
910         module_loadorder_t *plo;
911
912         plo = MODULE_GetLoadOrder(libname);
913
914         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
915         {
916                 switch(plo->loadorder[i])
917                 {
918                 case MODULE_LOADORDER_DLL:
919                         TRACE("Trying native dll '%s'\n", libname);
920                         hinst = NE_LoadModule(libname, lib_only);
921                         break;
922
923                 case MODULE_LOADORDER_ELFDLL:
924                         TRACE("Trying elfdll '%s'\n", libname);
925                         hinst = ELFDLL_LoadModule16(libname);
926                         break;
927
928                 case MODULE_LOADORDER_BI:
929                         TRACE("Trying built-in '%s'\n", libname);
930                         hinst = BUILTIN_LoadModule(libname);
931                         break;
932
933                 default:
934                         ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
935                 /* Fall through */
936
937                 case MODULE_LOADORDER_SO:       /* This is not supported for NE modules */
938                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
939                         hinst = 2;
940                         break;
941                 }
942
943                 if(hinst >= 32)
944                 {
945                         if(!implicit)
946                         {
947                                 HMODULE16 hModule;
948                                 NE_MODULE *pModule;
949
950                                 hModule = GetModuleHandle16(libname);
951                                 if(!hModule)
952                                 {
953                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
954                                                 libname, hinst);
955                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
956                                 }
957
958                                 pModule = NE_GetPtr(hModule);
959                                 if(!pModule)
960                                 {
961                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
962                                                 libname, hinst);
963                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
964                                 }
965
966                                 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
967
968                                 /*
969                                  * Call initialization routines for all loaded DLLs. Note that
970                                  * when we load implicitly linked DLLs this will be done by InitTask().
971                                  */
972                                 if(pModule->flags & NE_FFLAGS_LIBMODULE)
973                                 {
974                                         NE_InitializeDLLs(hModule);
975                                         NE_DllProcessAttach(hModule);
976                                 }
977                         }
978                         return hinst;
979                 }
980
981                 if(hinst != 2)
982                 {
983                         /* We quit searching when we get another error than 'File not found' */
984                         break;
985                 }
986         }
987         return hinst;   /* The last error that occured */
988 }
989
990
991 /**********************************************************************
992  *          LoadModule16    (KERNEL.45)
993  */
994 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
995 {
996     struct new_thread_request *req = get_req_buffer();
997     TEB *teb = NULL;
998     BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
999     LOADPARAMS16 *params;
1000     HINSTANCE16 instance = 0;
1001     HMODULE16 hModule;
1002     NE_MODULE *pModule;
1003     HTASK hTask;
1004     TDB *pTask;
1005     LPSTR cmdline;
1006     WORD cmdShow;
1007     int socket;
1008
1009     /* Load module */
1010
1011     if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1012     {
1013         /* Special case: second instance of an already loaded NE module */
1014
1015         if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1016         if ( pModule->module32 ) return (HINSTANCE16)21;
1017
1018         /* Increment refcount */
1019
1020         pModule->count++;
1021     }
1022     else
1023     {
1024         /* Main case: load first instance of NE module */
1025
1026         if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1027             return hModule;
1028
1029         if ( !(pModule = NE_GetPtr( hModule )) )
1030             return (HINSTANCE16)11;
1031     }
1032
1033     /* If library module, we just retrieve the instance handle */
1034
1035     if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1036         return NE_GetInstance( pModule );
1037
1038     /*
1039      *  At this point, we need to create a new process.
1040      *
1041      *  pModule points either to an already loaded module, whose refcount
1042      *  has already been incremented (to avoid having the module vanish 
1043      *  in the meantime), or else to a stub module which contains only header 
1044      *  information.
1045      */
1046
1047     /* Create the main thread */
1048
1049     req->suspend = 0;
1050     req->inherit = 0;
1051     if (server_call_fd( REQ_NEW_THREAD, -1, &socket )) return 0;
1052     CloseHandle( req->handle );
1053
1054     if (!(teb = THREAD_Create( socket, 0, FALSE ))) goto error;
1055     teb->startup = NE_InitProcess;
1056
1057     /* Create a task for this process */
1058
1059     params = (LOADPARAMS16 *)paramBlock;
1060     cmdShow = ((WORD *)PTR_SEG_TO_LIN(params->showCmd))[1];
1061     cmdline = PTR_SEG_TO_LIN( params->cmdLine );
1062     if (!TASK_Create( pModule, cmdShow, teb, cmdline + 1, *cmdline )) goto error;
1063
1064     hTask = teb->htask16;
1065
1066     if (SYSDEPS_SpawnThread( teb ) == -1) goto error;
1067
1068     /* Post event to start the task */
1069     PostEvent16( hTask );
1070
1071     /* Wait until we get the instance handle */
1072     do
1073     {
1074         DirectedYield16( hTask );
1075         if (!IsTask16( hTask )) break;
1076         if (!(pTask = (TDB *)GlobalLock16( hTask ))) break;
1077         instance = pTask->hInstance;
1078         GlobalUnlock16( hTask );
1079     } while (!instance);
1080
1081     return instance;
1082
1083  error:
1084     /* FIXME: free TEB and task */
1085     close( socket );
1086     return 0;  /* FIXME */
1087 }
1088
1089
1090 /**********************************************************************
1091  *          NE_InitProcess
1092  */
1093 static void NE_InitProcess(void)
1094 {
1095     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1096     NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1097     HINSTANCE16 hInstance, hPrevInstance;
1098     SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1099     WORD sp;
1100
1101     SYSLEVEL_EnterWin16Lock();
1102
1103     if ( pModule->count > 0 )
1104     {
1105         /* Second instance of an already loaded NE module */
1106         /* Note that the refcount was already incremented by the parent */
1107
1108         hPrevInstance = NE_GetInstance( pModule );
1109
1110         if ( pModule->dgroup )
1111             if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1112                 NE_LoadSegment( pModule, pModule->dgroup );
1113
1114         hInstance = NE_GetInstance( pModule );
1115         TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1116
1117     }
1118     else
1119     {
1120         /* Load first instance of NE module */
1121
1122         pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1123
1124         hInstance = NE_DoLoadModule( pModule );
1125         hPrevInstance = 0;
1126     }
1127
1128     if ( hInstance >= 32 )
1129     {
1130         CONTEXT86 context;
1131
1132         /* Enter instance handles into task struct */
1133
1134         pTask->hInstance = hInstance;
1135         pTask->hPrevInstance = hPrevInstance;
1136
1137         /* Use DGROUP for 16-bit stack */
1138  
1139         if (!(sp = pModule->sp))
1140             sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1141         sp &= ~1;
1142         sp -= sizeof(STACK16FRAME);
1143         pTask->teb->cur_stack = PTR_SEG_OFF_TO_SEGPTR( GlobalHandleToSel16(hInstance), sp );
1144
1145         /* Registers at initialization must be:
1146          * ax   zero
1147          * bx   stack size in bytes
1148          * cx   heap size in bytes
1149          * si   previous app instance
1150          * di   current app instance
1151          * bp   zero
1152          * es   selector to the PSP
1153          * ds   dgroup of the application
1154          * ss   stack selector
1155          * sp   top of the stack
1156          */
1157         memset( &context, 0, sizeof(context) );
1158         CS_reg(&context)  = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1159         DS_reg(&context)  = GlobalHandleToSel16(pTask->hInstance);
1160         ES_reg(&context)  = pTask->hPDB;
1161         EIP_reg(&context) = pModule->ip;
1162         EBX_reg(&context) = pModule->stack_size;
1163         ECX_reg(&context) = pModule->heap_size;
1164         EDI_reg(&context) = pTask->hInstance;
1165         ESI_reg(&context) = pTask->hPrevInstance;
1166
1167         /* Now call 16-bit entry point */
1168
1169         TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1170               CS_reg(&context), EIP_reg(&context), DS_reg(&context),
1171               SELECTOROF(pTask->teb->cur_stack),
1172               OFFSETOF(pTask->teb->cur_stack) );
1173
1174         ExitThread( Callbacks->CallRegisterShortProc( &context, 0 ) );
1175     }
1176
1177     SYSLEVEL_LeaveWin16Lock();
1178     ExitThread( hInstance );
1179 }
1180
1181 /***********************************************************************
1182  *           LoadLibrary16   (KERNEL.95)
1183  */
1184 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1185 {
1186     return LoadModule16(libname, (LPVOID)-1 );
1187 }
1188
1189
1190 /**********************************************************************
1191  *          MODULE_CallWEP
1192  *
1193  * Call a DLL's WEP, allowing it to shut down.
1194  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1195  */
1196 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1197 {
1198     FARPROC16 WEP = (FARPROC16)0;
1199     WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
1200
1201     if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
1202     if (!WEP)
1203     {
1204         WARN("module %04x doesn't have a WEP\n", hModule );
1205         return FALSE;
1206     }
1207     return Callbacks->CallWindowsExitProc( WEP, WEP_FREE_DLL );
1208 }
1209
1210
1211 /**********************************************************************
1212  *          NE_FreeModule
1213  *
1214  * Implementation of FreeModule16().
1215  */
1216 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1217 {
1218     HMODULE16 *hPrevModule;
1219     NE_MODULE *pModule;
1220     HMODULE16 *pModRef;
1221     int i;
1222
1223     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1224     hModule = pModule->self;
1225
1226     TRACE("%04x count %d\n", hModule, pModule->count );
1227
1228     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1229     else pModule->count = 0;
1230
1231     if (pModule->flags & NE_FFLAGS_BUILTIN)
1232         return FALSE;  /* Can't free built-in module */
1233
1234     if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1235     {
1236         if (pModule->flags & NE_FFLAGS_LIBMODULE)
1237         {
1238             MODULE_CallWEP( hModule );
1239
1240             /* Free the objects owned by the DLL module */
1241             TASK_CallTaskSignalProc( USIG16_DLL_UNLOAD, hModule );
1242             PROCESS_CallUserSignalProc( USIG_DLL_UNLOAD_WIN16, hModule );
1243         }
1244         else
1245             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
1246     }
1247     
1248
1249     /* Clear magic number just in case */
1250
1251     pModule->magic = pModule->self = 0;
1252
1253       /* Remove it from the linked list */
1254
1255     hPrevModule = &hFirstModule;
1256     while (*hPrevModule && (*hPrevModule != hModule))
1257     {
1258         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1259     }
1260     if (*hPrevModule) *hPrevModule = pModule->next;
1261
1262     /* Free the referenced modules */
1263
1264     pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1265     for (i = 0; i < pModule->modref_count; i++, pModRef++)
1266     {
1267         NE_FreeModule( *pModRef, call_wep );
1268     }
1269
1270     /* Free the module storage */
1271
1272     GlobalFreeAll16( hModule );
1273
1274     /* Remove module from cache */
1275
1276     if (pCachedModule == pModule) pCachedModule = NULL;
1277     return TRUE;
1278 }
1279
1280
1281 /**********************************************************************
1282  *          FreeModule16    (KERNEL.46)
1283  */
1284 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1285 {
1286     return NE_FreeModule( hModule, TRUE );
1287 }
1288
1289
1290 /***********************************************************************
1291  *           FreeLibrary16   (KERNEL.96)
1292  */
1293 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1294 {
1295     TRACE("%04x\n", handle );
1296     FreeModule16( handle );
1297 }
1298
1299
1300 /**********************************************************************
1301  *          GetModuleName    (KERNEL.27)
1302  */
1303 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1304 {
1305     NE_MODULE *pModule;
1306     BYTE *p;
1307
1308     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1309     p = (BYTE *)pModule + pModule->name_table;
1310     if (count > *p) count = *p + 1;
1311     if (count > 0)
1312     {
1313         memcpy( buf, p + 1, count - 1 );
1314         buf[count-1] = '\0';
1315     }
1316     return TRUE;
1317 }
1318
1319
1320 /**********************************************************************
1321  *          GetModuleUsage    (KERNEL.48)
1322  */
1323 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1324 {
1325     NE_MODULE *pModule = NE_GetPtr( hModule );
1326     return pModule ? pModule->count : 0;
1327 }
1328
1329
1330 /**********************************************************************
1331  *          GetExpWinVer    (KERNEL.167)
1332  */
1333 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1334 {
1335     NE_MODULE *pModule = NE_GetPtr( hModule );
1336     if ( !pModule ) return 0;
1337
1338     /* 
1339      * For built-in modules, fake the expected version the module should
1340      * have according to the Windows version emulated by Wine
1341      */
1342     if ( !pModule->expected_version )
1343     {
1344         OSVERSIONINFOA versionInfo;
1345         versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1346
1347         if ( GetVersionExA( &versionInfo ) )
1348             pModule->expected_version =   
1349                      (versionInfo.dwMajorVersion & 0xff) << 8
1350                    | (versionInfo.dwMinorVersion & 0xff);
1351     }
1352
1353     return pModule->expected_version;
1354 }
1355
1356
1357 /**********************************************************************
1358  *          GetModuleFileName16    (KERNEL.49)
1359  *
1360  * Comment: see GetModuleFileNameA
1361  *
1362  * Even if invoked by second instance of a program,
1363  * it still returns path of first one.
1364  */
1365 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1366                                   INT16 nSize )
1367 {
1368     NE_MODULE *pModule;
1369
1370     /* Win95 does not query hModule if set to 0 !
1371      * Is this wrong or maybe Win3.1 only ? */
1372     if (!hModule) hModule = GetCurrentTask();
1373
1374     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1375     lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1376     if (pModule->expected_version >= 0x400)
1377         GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1378     TRACE("%04x -> '%s'\n", hModule, lpFileName );
1379     return strlen(lpFileName);
1380 }
1381
1382
1383 /**********************************************************************
1384  *          GetModuleHandle    (KERNEL.47)
1385  *
1386  * Find a module from a module name.
1387  *
1388  * NOTE: The current implementation works the same way the Windows 95 one
1389  *       does. Do not try to 'fix' it, fix the callers.
1390  *       + It does not do ANY extension handling (except that strange .EXE bit)!
1391  *       + It does not care about paths, just about basenames. (same as Windows)
1392  *
1393  * RETURNS
1394  *   LOWORD:
1395  *      the win16 module handle if found
1396  *      0 if not
1397  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1398  *      Always hFirstModule
1399  */
1400 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1401 {
1402     if (HIWORD(name) == 0)
1403         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1404     return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1405 }
1406
1407 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1408 {
1409     HMODULE16   hModule = hFirstModule;
1410     LPSTR       s;
1411     BYTE        len, *name_table;
1412     char        tmpstr[MAX_PATH];
1413     NE_MODULE *pModule;
1414
1415     TRACE("(%s)\n", name);
1416
1417     if (!HIWORD(name))
1418         return GetExePtr(LOWORD(name));
1419
1420     len = strlen(name);
1421     if (!len)
1422         return 0;
1423
1424     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1425
1426     /* If 'name' matches exactly the module name of a module:
1427      * Return its handle.
1428      */
1429     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1430     {
1431         pModule = NE_GetPtr( hModule );
1432         if (!pModule) break;
1433         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1434
1435         name_table = (BYTE *)pModule + pModule->name_table;
1436         if ((*name_table == len) && !strncmp(name, name_table+1, len))
1437             return hModule;
1438     }
1439
1440     /* If uppercased 'name' matches exactly the module name of a module:
1441      * Return its handle
1442      */
1443     for (s = tmpstr; *s; s++)
1444         *s = toupper(*s);
1445
1446     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1447     {
1448         pModule = NE_GetPtr( hModule );
1449         if (!pModule) break;
1450         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1451
1452         name_table = (BYTE *)pModule + pModule->name_table;
1453         /* FIXME: the lstrncmpiA is WRONG. It should not be case insensitive,
1454          * but case sensitive! (Unfortunately Winword 6 and subdlls have
1455          * lowercased module names, but try to load uppercase DLLs, so this
1456          * 'i' compare is just a quickfix until the loader handles that
1457          * correctly. -MM 990705
1458          */
1459         if ((*name_table == len) && !lstrncmpiA(tmpstr, name_table+1, len))
1460             return hModule;
1461     }
1462
1463     /* If the base filename of 'name' matches the base filename of the module
1464      * filename of some module (case-insensitive compare):
1465      * Return its handle.
1466      */
1467
1468     /* basename: search backwards in passed name to \ / or : */
1469     s = tmpstr + strlen(tmpstr);
1470     while (s > tmpstr)
1471     {
1472         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1473                 break;
1474         s--;
1475     }
1476
1477     /* search this in loaded filename list */
1478     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1479     {
1480         char            *loadedfn;
1481         OFSTRUCT        *ofs;
1482
1483         pModule = NE_GetPtr( hModule );
1484         if (!pModule) break;
1485         if (!pModule->fileinfo) continue;
1486         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1487
1488         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1489         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1490         /* basename: search backwards in pathname to \ / or : */
1491         while (loadedfn > (char*)ofs->szPathName)
1492         {
1493             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1494                     break;
1495             loadedfn--;
1496         }
1497         /* case insensitive compare ... */
1498         if (!lstrcmpiA(loadedfn, s))
1499             return hModule;
1500     }
1501
1502     /* If the extension of 'name' is '.EXE' and the base filename of 'name'
1503      * matches the base filename of the module filename of some 32-bit module:
1504      * Return the corresponding 16-bit dummy module handle. 
1505      */
1506     if (len >= 4 && !strcasecmp(name+len-4, ".EXE"))
1507     {
1508         HMODULE hModule = GetModuleHandleA( name );
1509         if ( hModule )
1510             return MapHModuleLS( hModule );
1511     }
1512
1513     if (!strcmp(tmpstr,"MSDOS"))
1514         return 1;
1515
1516     if (!strcmp(tmpstr,"TIMER"))
1517     {
1518         FIXME("Eh... Should return caller's code segment, expect crash\n");
1519         return 0;
1520     }
1521
1522     return 0;
1523 }
1524
1525 /**********************************************************************
1526  *          NE_GetModuleByFilename
1527  */
1528 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1529 {
1530     HMODULE16   hModule;
1531     LPSTR       s, p;
1532     BYTE        len, *name_table;
1533     char        tmpstr[MAX_PATH];
1534     NE_MODULE *pModule;
1535
1536     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1537
1538     /* If the base filename of 'name' matches the base filename of the module
1539      * filename of some module (case-insensitive compare):
1540      * Return its handle.
1541      */
1542
1543     /* basename: search backwards in passed name to \ / or : */
1544     s = tmpstr + strlen(tmpstr);
1545     while (s > tmpstr)
1546     {
1547         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1548                 break;
1549         s--;
1550     }
1551
1552     /* search this in loaded filename list */
1553     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1554     {
1555         char            *loadedfn;
1556         OFSTRUCT        *ofs;
1557
1558         pModule = NE_GetPtr( hModule );
1559         if (!pModule) break;
1560         if (!pModule->fileinfo) continue;
1561         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1562
1563         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1564         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1565         /* basename: search backwards in pathname to \ / or : */
1566         while (loadedfn > (char*)ofs->szPathName)
1567         {
1568             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1569                     break;
1570             loadedfn--;
1571         }
1572         /* case insensitive compare ... */
1573         if (!lstrcmpiA(loadedfn, s))
1574             return hModule;
1575     }
1576
1577     /* If basename (without ext) matches the module name of a module:
1578      * Return its handle.
1579      */
1580
1581     if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1582     len = strlen(s);
1583
1584     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1585     {
1586         pModule = NE_GetPtr( hModule );
1587         if (!pModule) break;
1588         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1589
1590         name_table = (BYTE *)pModule + pModule->name_table;
1591         if ((*name_table == len) && !lstrncmpiA(s, name_table+1, len))
1592             return hModule;
1593     }
1594
1595     return 0;
1596 }
1597
1598 /**********************************************************************
1599  *          ModuleFirst    (TOOLHELP.59)
1600  */
1601 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1602 {
1603     lpme->wNext = hFirstModule;
1604     return ModuleNext16( lpme );
1605 }
1606
1607
1608 /**********************************************************************
1609  *          ModuleNext    (TOOLHELP.60)
1610  */
1611 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1612 {
1613     NE_MODULE *pModule;
1614     char *name;
1615
1616     if (!lpme->wNext) return FALSE;
1617     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1618     name = (char *)pModule + pModule->name_table;
1619     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1620     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1621     lpme->hModule = lpme->wNext;
1622     lpme->wcUsage = pModule->count;
1623     lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1624     lpme->wNext = pModule->next;
1625     return TRUE;
1626 }
1627
1628
1629 /**********************************************************************
1630  *          ModuleFindName    (TOOLHELP.61)
1631  */
1632 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1633 {
1634     lpme->wNext = GetModuleHandle16( name );
1635     return ModuleNext16( lpme );
1636 }
1637
1638
1639 /**********************************************************************
1640  *          ModuleFindHandle    (TOOLHELP.62)
1641  */
1642 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1643 {
1644     hModule = GetExePtr( hModule );
1645     lpme->wNext = hModule;
1646     return ModuleNext16( lpme );
1647 }
1648
1649
1650 /***************************************************************************
1651  *          IsRomModule16    (KERNEL.323)
1652  */
1653 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1654 {
1655     return FALSE;
1656 }
1657
1658 /***************************************************************************
1659  *          IsRomFile16    (KERNEL.326)
1660  */
1661 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1662 {
1663     return FALSE;
1664 }
1665
1666 /***************************************************************************
1667  *              MapHModuleLS                    (KERNEL32.520)
1668  */
1669 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod) {
1670         NE_MODULE       *pModule;
1671
1672         if (!hmod)
1673                 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1674         if (!HIWORD(hmod))
1675                 return hmod; /* we already have a 16 bit module handle */
1676         pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1677         while (pModule)  {
1678                 if (pModule->module32 == hmod)
1679                         return pModule->self;
1680                 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1681         }
1682         return 0;
1683 }
1684
1685 /***************************************************************************
1686  *              MapHModuleSL                    (KERNEL32.521)
1687  */
1688 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod) {
1689         NE_MODULE       *pModule;
1690
1691         if (!hmod) {
1692                 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1693
1694                 hmod = pTask->hModule;
1695         }
1696         pModule = (NE_MODULE*)GlobalLock16(hmod);
1697         if (    (pModule->magic!=IMAGE_OS2_SIGNATURE)   ||
1698                 !(pModule->flags & NE_FFLAGS_WIN32)
1699         )
1700                 return 0;
1701         return pModule->module32;
1702 }
1703
1704 /***************************************************************************
1705  *              MapHInstLS                      (KERNEL32.516)(KERNEL.472)
1706  */
1707 void WINAPI MapHInstLS( CONTEXT86 *context )
1708 {
1709         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1710 }
1711
1712 /***************************************************************************
1713  *              MapHInstSL                      (KERNEL32.518)(KERNEL.473)
1714  */
1715 void WINAPI MapHInstSL( CONTEXT86 *context )
1716 {
1717         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1718 }
1719
1720 /***************************************************************************
1721  *              MapHInstLS_PN                   (KERNEL32.517)
1722  */
1723 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
1724 {
1725         if (EAX_reg(context))
1726             EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1727 }
1728
1729 /***************************************************************************
1730  *              MapHInstSL_PN                   (KERNEL32.519)
1731  */
1732 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
1733 {
1734         if (EAX_reg(context))
1735             EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1736 }
1737