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