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