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