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