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