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