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