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