Changed CONTEXT into CONTEXT86 everywhere we really want an i386
[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 "debugtools.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 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
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         MESSAGE( "**** %04x is not a module handle\n", hModule );
73         return;
74     }
75
76       /* Dump the module info */
77     DPRINTF( "---\n" );
78     DPRINTF( "Module %04x:\n", hModule );
79     DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
80           pModule->count, pModule->flags,
81           pModule->heap_size, pModule->stack_size );
82     DPRINTF( "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     DPRINTF( "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         DPRINTF( "PE module=%08x\n", pModule->module32 );
90
91       /* Dump the file info */
92     DPRINTF( "---\n" );
93     DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
94
95       /* Dump the segment table */
96     DPRINTF( "---\n" );
97     DPRINTF( "Segment table:\n" );
98     pSeg = NE_SEG_TABLE( pModule );
99     for (i = 0; i < pModule->seg_count; i++, pSeg++)
100         DPRINTF( "%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     DPRINTF( "---\n" );
106     DPRINTF( "Resource table:\n" );
107     if (pModule->res_table)
108     {
109         pword = (WORD *)((BYTE *)pModule + pModule->res_table);
110         DPRINTF( "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             DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
116             for (i = 0; i < ptr->count; i++, pname++)
117                 DPRINTF( "offset=%d len=%d id=%04x\n",
118                       pname->offset, pname->length, pname->id );
119             pword = (WORD *)pname;
120         }
121     }
122     else DPRINTF( "None\n" );
123
124       /* Dump the resident name table */
125     DPRINTF( "---\n" );
126     DPRINTF( "Resident-name table:\n" );
127     pstr = (char *)pModule + pModule->name_table;
128     while (*pstr)
129     {
130         DPRINTF( "%*.*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     DPRINTF( "---\n" );
137     DPRINTF( "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             DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
146         }
147     }
148     else DPRINTF( "None\n" );
149
150       /* Dump the entry table */
151     DPRINTF( "---\n" );
152     DPRINTF( "Entry table:\n" );
153     bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);    
154     do {
155         entry = (ET_ENTRY *)((BYTE *)bundle+6);
156         DPRINTF( "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                 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
162             else
163                 DPRINTF("%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     DPRINTF( "---\n" );
171     DPRINTF( "Non-resident names table:\n" );
172     if (pModule->nrname_handle)
173     {
174         pstr = (char *)GlobalLock16( pModule->nrname_handle );
175         while (*pstr)
176         {
177             DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
178                    *(WORD *)(pstr + *pstr + 1) );
179             pstr += *pstr + 1 + sizeof(WORD);
180         }
181     }
182     DPRINTF( "\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     MESSAGE( "Module Flags Name\n" );
195     while (hModule)
196     {
197         NE_MODULE *pModule = NE_GetPtr( hModule );
198         if (!pModule)
199         {
200             MESSAGE( "Bad module %04x in list\n", hModule );
201             return;
202         }
203         MESSAGE( " %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("(%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("  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("  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("(%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         MESSAGE( "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("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       MESSAGE("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("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("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("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("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("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("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("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("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                 MESSAGE( "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       {
818        NE_FreeModule(hModule,0);
819         return 2;
820       }
821
822     /* Load the segments */
823
824     NE_LoadAllSegments( pModule );
825
826     /* Fixup the functions prologs */
827
828     NE_FixupPrologs( pModule );
829
830     /* Make sure the usage count is 1 on the first loading of  */
831     /* the module, even if it contains circular DLL references */
832
833     pModule->count = 1;
834
835     return hInstance;
836 }
837
838 /**********************************************************************
839  *          NE_LoadModule
840  *
841  * Load first instance of NE module, deciding whether to use
842  * built-in module or load module from file.
843  * (Note: caller is responsible for ensuring the module isn't
844  *        already loaded!)
845  */
846 HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL implicit )
847 {
848     HINSTANCE16 hInstance;
849     HFILE16 hFile;
850     OFSTRUCT ofs;
851
852     if ((hFile = OpenFile16( name, &ofs, OF_READ )) == HFILE_ERROR16)
853     {
854         char    buffer[260];
855
856         if(implicit)
857         {
858             /* 4 == strlen(".dll") */
859             strncpy(buffer, name, sizeof(buffer) - 1 - 4);
860             strcat(buffer, ".dll");
861             if ((hFile = OpenFile16( buffer, &ofs, OF_READ )) == HFILE_ERROR16)
862                 return 2;  /* File not found */
863         }
864     }
865
866     hInstance = NE_LoadFileModule( hFile, &ofs, implicit );
867     _lclose16( hFile );
868
869     return hInstance;
870 }
871
872
873 /**********************************************************************
874  *          MODULE_LoadModule16
875  *
876  * Load a NE module in the order of the loadorder specification.
877  * The caller is responsible that the module is not loaded already.
878  *
879  */
880 HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit )
881 {
882         HINSTANCE16 hinst;
883         int i;
884         module_loadorder_t *plo;
885
886         plo = MODULE_GetLoadOrder(libname);
887
888         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
889         {
890                 switch(plo->loadorder[i])
891                 {
892                 case MODULE_LOADORDER_DLL:
893                         TRACE("Trying native dll '%s'\n", libname);
894                         hinst = NE_LoadModule(libname, implicit);
895                         break;
896
897                 case MODULE_LOADORDER_ELFDLL:
898                         TRACE("Trying elfdll '%s'\n", libname);
899                         hinst = ELFDLL_LoadModule16(libname, implicit);
900                         break;
901
902                 case MODULE_LOADORDER_BI:
903                         TRACE("Trying built-in '%s'\n", libname);
904                         hinst = fnBUILTIN_LoadModule(libname, TRUE);
905                         break;
906
907                 default:
908                         ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
909                 /* Fall through */
910
911                 case MODULE_LOADORDER_SO:       /* This is not supported for NE modules */
912                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
913                         hinst = 2;
914                         break;
915                 }
916
917                 if(hinst >= 32)
918                 {
919                         if(!implicit)
920                         {
921                                 HMODULE16 hModule;
922                                 NE_MODULE *pModule;
923
924                                 hModule = GetModuleHandle16(libname);
925                                 if(!hModule)
926                                 {
927                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle\n",
928                                                 libname, hinst);
929                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
930                                 }
931
932                                 pModule = NE_GetPtr(hModule);
933                                 if(!pModule)
934                                 {
935                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
936                                                 libname, hinst);
937                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
938                                 }
939
940                                 TRACE("Loaded module '%s' at 0x%04x, \n", libname, hinst);
941
942                                 /*
943                                  * Call initialization routines for all loaded DLLs. Note that
944                                  * when we load implicitly linked DLLs this will be done by InitTask().
945                                  */
946                                 if(pModule->flags & NE_FFLAGS_LIBMODULE)
947                                         NE_InitializeDLLs(hModule);
948                         }
949                         return hinst;
950                 }
951
952                 if(hinst != 2)
953                 {
954                         /* We quit searching when we get another error than 'File not found' */
955                         break;
956                 }
957         }
958         return hinst;   /* The last error that occured */
959 }
960
961
962 /**********************************************************************
963  *          LoadModule16    (KERNEL.45)
964  */
965 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
966 {
967     BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
968     LOADPARAMS16 *params;
969     LPSTR cmd_line, new_cmd_line;
970     LPCVOID env = NULL;
971     STARTUPINFOA startup;
972     PROCESS_INFORMATION info;
973     HINSTANCE16 hInstance, hPrevInstance = 0;
974     HMODULE16 hModule;
975     NE_MODULE *pModule;
976     PDB *pdb;
977
978     /* Load module */
979
980     if ( (hModule = GetModuleHandle16(name) ) != 0 )
981     {
982         /* Special case: second instance of an already loaded NE module */
983
984         if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
985         if ( pModule->module32 ) return (HINSTANCE16)21;
986
987         hInstance = NE_CreateInstance( pModule, &hPrevInstance, lib_only );
988         if ( hInstance != hPrevInstance )  /* not a library */
989             NE_LoadSegment( pModule, pModule->dgroup );
990
991         pModule->count++;
992     }
993     else
994     {
995         /* Main case: load first instance of NE module */
996
997         if ( (hInstance = MODULE_LoadModule16( name, FALSE )) < 32 )
998             return hInstance;
999
1000         if ( !(pModule = NE_GetPtr( hInstance )) )
1001             return (HINSTANCE16)11;
1002     }
1003
1004     /* If library module, we're finished */
1005
1006     if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1007         return hInstance;
1008
1009     /* Create a task for this instance */
1010
1011     pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1012
1013     params = (LOADPARAMS16 *)paramBlock;
1014     cmd_line = (LPSTR)PTR_SEG_TO_LIN( params->cmdLine );
1015     if (!cmd_line) cmd_line = "";
1016     else if (*cmd_line) cmd_line++;  /* skip the length byte */
1017
1018     if (!(new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1019                                     strlen(cmd_line)+strlen(name)+2 )))
1020         return 0;
1021     strcpy( new_cmd_line, name );
1022     strcat( new_cmd_line, " " );
1023     strcat( new_cmd_line, cmd_line );
1024
1025     if (params->hEnvironment) env = GlobalLock16( params->hEnvironment );
1026
1027     memset( &info, '\0', sizeof(info) );
1028     memset( &startup, '\0', sizeof(startup) );
1029     startup.cb = sizeof(startup);
1030     if (params->showCmd)
1031     {
1032         startup.dwFlags = STARTF_USESHOWWINDOW;
1033         startup.wShowWindow = ((UINT16 *)PTR_SEG_TO_LIN(params->showCmd))[1];
1034     }
1035
1036     SYSLEVEL_ReleaseWin16Lock();
1037     pdb = PROCESS_Create( pModule, new_cmd_line, env,
1038                           hInstance, hPrevInstance, 
1039                           NULL, NULL, TRUE, 0, &startup, &info );
1040     SYSLEVEL_RestoreWin16Lock();
1041
1042     CloseHandle( info.hThread );
1043     CloseHandle( info.hProcess );
1044
1045     if (params->hEnvironment) GlobalUnlock16( params->hEnvironment );
1046     HeapFree( GetProcessHeap(), 0, new_cmd_line );
1047     return hInstance;
1048 }
1049
1050 /**********************************************************************
1051  *          NE_CreateProcess
1052  */
1053 BOOL NE_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmd_line, LPCSTR env, 
1054                        LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1055                        BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1056                        LPPROCESS_INFORMATION info )
1057 {
1058     HINSTANCE16 hInstance, hPrevInstance = 0;
1059     HMODULE16 hModule;
1060     NE_MODULE *pModule;
1061     HFILE16 hFile16;
1062
1063     /* Special case: second instance of an already loaded NE module */
1064
1065     if ( ( hModule = GetModuleHandle16( ofs->szPathName ) ) != 0 )
1066     {
1067         if (   !( pModule = NE_GetPtr( hModule) )
1068             ||  ( pModule->flags & NE_FFLAGS_LIBMODULE )
1069             ||  pModule->module32 )
1070         {
1071             SetLastError( ERROR_BAD_FORMAT );
1072             return FALSE;
1073         }
1074
1075         hInstance = NE_CreateInstance( pModule, &hPrevInstance, FALSE );
1076         if ( hInstance != hPrevInstance )  /* not a library */
1077             NE_LoadSegment( pModule, pModule->dgroup );
1078
1079         pModule->count++;
1080     }
1081
1082     /* Main case: load first instance of NE module */
1083     else
1084     {
1085         /* If we didn't get a file handle, return */
1086
1087         if ( hFile == HFILE_ERROR )
1088             return FALSE;
1089
1090         /* Allocate temporary HFILE16 for NE_LoadFileModule */
1091
1092         if (!DuplicateHandle( GetCurrentProcess(), hFile,
1093                               GetCurrentProcess(), &hFile,
1094                               0, FALSE, DUPLICATE_SAME_ACCESS ))
1095         {
1096             SetLastError( ERROR_INVALID_HANDLE );
1097             return FALSE;
1098         }
1099         hFile16 = FILE_AllocDosHandle( hFile );
1100
1101         /* Load module */
1102
1103         hInstance = NE_LoadFileModule( hFile16, ofs, TRUE );
1104         _lclose16( hFile16 );
1105
1106         if ( hInstance < 32 )
1107         {
1108             SetLastError( hInstance );
1109             return FALSE;
1110         }
1111
1112         if (   !( pModule = NE_GetPtr( hInstance ) )
1113             ||  ( pModule->flags & NE_FFLAGS_LIBMODULE) )
1114         {
1115             /* FIXME: cleanup */
1116             SetLastError( ERROR_BAD_FORMAT );
1117             return FALSE;
1118         }
1119     }
1120
1121     /* Create a task for this instance */
1122
1123     pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1124
1125     if ( !PROCESS_Create( pModule, cmd_line, env,
1126                           hInstance, hPrevInstance, 
1127                           psa, tsa, inherit, flags, startup, info ) )
1128         return FALSE;
1129
1130     return TRUE;
1131 }
1132
1133 /***********************************************************************
1134  *           LoadLibrary16   (KERNEL.95)
1135  *
1136  * In Win95 LoadLibrary16("c:/junkname/user.foo") returns the HINSTANCE 
1137  * to user.exe. As GetModuleHandle as of 990425 explicitly asks _not_ 
1138  * to change its handling of extensions, we have to try a stripped down
1139  * libname here too (bon 990425)   
1140  */
1141 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1142 {
1143     char strippedname[256];
1144     char *dirsep1,*dirsep2;
1145     HINSTANCE16 ret;
1146
1147     dirsep1=strrchr(libname,'\\');
1148     dirsep2=strrchr(libname,'/');
1149     dirsep1=MAX(dirsep1,dirsep2);
1150     if (!dirsep1)
1151       dirsep1 =(LPSTR)libname;
1152     else
1153       dirsep1++;
1154     lstrcpynA(strippedname,dirsep1,256);
1155     dirsep1=strchr(strippedname,'.');
1156     if (dirsep1)
1157       *dirsep1=0;
1158
1159     TRACE("looking for (%p) %s and %s \n", 
1160            libname, libname,strippedname );
1161
1162     /* Load library module */
1163     ret= LoadModule16( strippedname, (LPVOID)-1 );
1164     if (ret > HINSTANCE_ERROR)
1165       return ret;
1166     return LoadModule16(libname, (LPVOID)-1 );
1167 }
1168
1169
1170 /**********************************************************************
1171  *          MODULE_CallWEP
1172  *
1173  * Call a DLL's WEP, allowing it to shut down.
1174  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1175  */
1176 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1177 {
1178     FARPROC16 WEP = (FARPROC16)0;
1179     WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
1180
1181     if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
1182     if (!WEP)
1183     {
1184         WARN("module %04x doesn't have a WEP\n", hModule );
1185         return FALSE;
1186     }
1187     return Callbacks->CallWindowsExitProc( WEP, WEP_FREE_DLL );
1188 }
1189
1190
1191 /**********************************************************************
1192  *          NE_FreeModule
1193  *
1194  * Implementation of FreeModule16().
1195  */
1196 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1197 {
1198     HMODULE16 *hPrevModule;
1199     NE_MODULE *pModule;
1200     HMODULE16 *pModRef;
1201     int i;
1202
1203     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1204     hModule = pModule->self;
1205
1206     TRACE("%04x count %d\n", hModule, pModule->count );
1207
1208     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1209     else pModule->count = 0;
1210
1211     if (pModule->flags & NE_FFLAGS_BUILTIN)
1212         return FALSE;  /* Can't free built-in module */
1213
1214     if (call_wep)
1215     {
1216         if (pModule->flags & NE_FFLAGS_LIBMODULE)
1217         {
1218             TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1219             MODULE_CallWEP( hModule );
1220
1221             /* Free the objects owned by the DLL module */
1222
1223             if (pTask && pTask->userhandler)
1224                 pTask->userhandler( hModule, USIG16_DLL_UNLOAD, 0,
1225                                     pTask->hInstance, pTask->hQueue );
1226
1227             PROCESS_CallUserSignalProc( USIG_DLL_UNLOAD_WIN16, hModule );
1228         }
1229         else
1230             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
1231     }
1232     
1233
1234     /* Clear magic number just in case */
1235
1236     pModule->magic = pModule->self = 0;
1237
1238       /* Remove it from the linked list */
1239
1240     hPrevModule = &hFirstModule;
1241     while (*hPrevModule && (*hPrevModule != hModule))
1242     {
1243         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1244     }
1245     if (*hPrevModule) *hPrevModule = pModule->next;
1246
1247     /* Free the referenced modules */
1248
1249     pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1250     for (i = 0; i < pModule->modref_count; i++, pModRef++)
1251     {
1252         NE_FreeModule( *pModRef, call_wep );
1253     }
1254
1255     /* Free the module storage */
1256
1257     GlobalFreeAll16( hModule );
1258
1259     /* Remove module from cache */
1260
1261     if (pCachedModule == pModule) pCachedModule = NULL;
1262     return TRUE;
1263 }
1264
1265
1266 /**********************************************************************
1267  *          FreeModule16    (KERNEL.46)
1268  */
1269 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1270 {
1271     return NE_FreeModule( hModule, TRUE );
1272 }
1273
1274
1275 /***********************************************************************
1276  *           FreeLibrary16   (KERNEL.96)
1277  */
1278 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1279 {
1280     TRACE("%04x\n", handle );
1281     FreeModule16( handle );
1282 }
1283
1284
1285 /**********************************************************************
1286  *          GetModuleName    (KERNEL.27)
1287  */
1288 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1289 {
1290     NE_MODULE *pModule;
1291     BYTE *p;
1292
1293     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1294     p = (BYTE *)pModule + pModule->name_table;
1295     if (count > *p) count = *p + 1;
1296     if (count > 0)
1297     {
1298         memcpy( buf, p + 1, count - 1 );
1299         buf[count-1] = '\0';
1300     }
1301     return TRUE;
1302 }
1303
1304
1305 /**********************************************************************
1306  *          GetModuleUsage    (KERNEL.48)
1307  */
1308 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1309 {
1310     NE_MODULE *pModule = NE_GetPtr( hModule );
1311     return pModule ? pModule->count : 0;
1312 }
1313
1314
1315 /**********************************************************************
1316  *          GetExpWinVer    (KERNEL.167)
1317  */
1318 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1319 {
1320     NE_MODULE *pModule = NE_GetPtr( hModule );
1321     return pModule ? pModule->expected_version : 0;
1322 }
1323
1324
1325 /**********************************************************************
1326  *          GetModuleFileName16    (KERNEL.49)
1327  */
1328 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1329                                   INT16 nSize )
1330 {
1331     NE_MODULE *pModule;
1332
1333     if (!hModule) hModule = GetCurrentTask();
1334     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1335     lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1336     TRACE("%s\n", lpFileName );
1337     return strlen(lpFileName);
1338 }
1339
1340
1341 /**********************************************************************
1342  *          GetModuleHandle16    (KERNEL.47)
1343  *
1344  * Find a module from a module name.
1345  *
1346  * NOTE: The current implementation works the same way the Windows 95 one
1347  *       does. Do not try to 'fix' it, fix the callers.
1348  *       + It does not do ANY extension handling (except that strange .EXE bit)!
1349  *       + It does not care about paths, just about basenames. (same as Windows)
1350  *
1351  * RETURNS
1352  *   LOWORD:
1353  *      the win16 module handle if found
1354  *      0 if not
1355  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1356  *      Always hFirstModule
1357  */
1358 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1359 {
1360     if (HIWORD(name) == 0)
1361         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1362     return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1363 }
1364
1365 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1366 {
1367     HMODULE16   hModule = hFirstModule;
1368     LPSTR       s;
1369     BYTE        len, *name_table;
1370     char        tmpstr[128];
1371     NE_MODULE *pModule;
1372
1373     TRACE("(%s)\n", name);
1374
1375     if (!HIWORD(name))
1376         return GetExePtr(LOWORD(name));
1377
1378     len = strlen(name);
1379     if (!len)
1380         return 0;
1381
1382     strncpy(tmpstr, name, sizeof(tmpstr));
1383     tmpstr[sizeof(tmpstr)-1] = '\0';
1384
1385     /* If 'name' matches exactly the module name of a module:
1386      * Return its handle.
1387      */
1388     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1389     {
1390         pModule = NE_GetPtr( hModule );
1391         if (!pModule) break;
1392
1393         name_table = (BYTE *)pModule + pModule->name_table;
1394         if ((*name_table == len) && !strncmp(name, name_table+1, len))
1395             return hModule;
1396     }
1397
1398     /* If uppercased 'name' matches exactly the module name of a module:
1399      * Return its handle
1400      */
1401     for (s = tmpstr; *s; s++)
1402         *s = toupper(*s);
1403
1404     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1405     {
1406         pModule = NE_GetPtr( hModule );
1407         if (!pModule) break;
1408
1409         name_table = (BYTE *)pModule + pModule->name_table;
1410         if ((*name_table == len) && !strncmp(tmpstr, name_table+1, len))
1411             return hModule;
1412     }
1413
1414     /* If the base filename of 'name' matches the base filename of the module
1415      * filename of some module (case-insensitive compare):
1416      * Return its handle.
1417      */
1418
1419     /* basename: search backwards in passed name to \ / or : */
1420     s = tmpstr + strlen(tmpstr);
1421     while (s > tmpstr)
1422     {
1423         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1424                 break;
1425         s--;
1426     }
1427
1428     /* search this in loaded filename list */
1429     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1430     {
1431         char            *loadedfn;
1432         OFSTRUCT        *ofs;
1433
1434         pModule = NE_GetPtr( hModule );
1435         if (!pModule) break;
1436         if (!pModule->fileinfo) continue;
1437
1438         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1439         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1440         /* basename: search backwards in pathname to \ / or : */
1441         while (loadedfn > (char*)ofs->szPathName)
1442         {
1443             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1444                     break;
1445             loadedfn--;
1446         }
1447         /* case insensitive compare ... */
1448         if (!lstrcmpiA(loadedfn, s))
1449             return hModule;
1450     }
1451
1452     /* If the extension of 'name' is '.EXE' and the base filename of 'name'
1453      * matches the base filename of the module filename of some 32-bit module:
1454      * Return the corresponding 16-bit dummy module handle. 
1455      */
1456     if (len >= 4 && !strcasecmp(name+len-4, ".EXE"))
1457     {
1458         HMODULE hModule = GetModuleHandleA( name );
1459         if ( hModule )
1460             return MapHModuleLS( hModule );
1461     }
1462
1463     if (!strcmp(tmpstr,"MSDOS"))
1464         return 1;
1465
1466     if (!strcmp(tmpstr,"TIMER"))
1467     {
1468         FIXME("Eh... Should return caller's code segment, expect crash\n");
1469         return 0;
1470     }
1471
1472     return 0;
1473 }
1474
1475
1476 /**********************************************************************
1477  *          ModuleFirst    (TOOLHELP.59)
1478  */
1479 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1480 {
1481     lpme->wNext = hFirstModule;
1482     return ModuleNext16( lpme );
1483 }
1484
1485
1486 /**********************************************************************
1487  *          ModuleNext    (TOOLHELP.60)
1488  */
1489 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1490 {
1491     NE_MODULE *pModule;
1492     char *name;
1493
1494     if (!lpme->wNext) return FALSE;
1495     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1496     name = (char *)pModule + pModule->name_table;
1497     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1498     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1499     lpme->hModule = lpme->wNext;
1500     lpme->wcUsage = pModule->count;
1501     lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1502     lpme->wNext = pModule->next;
1503     return TRUE;
1504 }
1505
1506
1507 /**********************************************************************
1508  *          ModuleFindName    (TOOLHELP.61)
1509  */
1510 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1511 {
1512     lpme->wNext = GetModuleHandle16( name );
1513     return ModuleNext16( lpme );
1514 }
1515
1516
1517 /**********************************************************************
1518  *          ModuleFindHandle    (TOOLHELP.62)
1519  */
1520 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1521 {
1522     hModule = GetExePtr( hModule );
1523     lpme->wNext = hModule;
1524     return ModuleNext16( lpme );
1525 }
1526
1527
1528 /***************************************************************************
1529  *              MapHModuleLS                    (KERNEL32.520)
1530  */
1531 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod) {
1532         NE_MODULE       *pModule;
1533
1534         if (!hmod)
1535                 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1536         if (!HIWORD(hmod))
1537                 return hmod; /* we already have a 16 bit module handle */
1538         pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1539         while (pModule)  {
1540                 if (pModule->module32 == hmod)
1541                         return pModule->self;
1542                 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1543         }
1544         return 0;
1545 }
1546
1547 /***************************************************************************
1548  *              MapHModuleSL                    (KERNEL32.521)
1549  */
1550 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod) {
1551         NE_MODULE       *pModule;
1552
1553         if (!hmod) {
1554                 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1555
1556                 hmod = pTask->hModule;
1557         }
1558         pModule = (NE_MODULE*)GlobalLock16(hmod);
1559         if (    (pModule->magic!=IMAGE_OS2_SIGNATURE)   ||
1560                 !(pModule->flags & NE_FFLAGS_WIN32)
1561         )
1562                 return 0;
1563         return pModule->module32;
1564 }
1565
1566 /***************************************************************************
1567  *              MapHInstLS                      (KERNEL32.516)
1568  */
1569 void WINAPI REGS_FUNC(MapHInstLS)( CONTEXT *context )
1570 {
1571 #ifdef __i386__
1572         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1573 #endif
1574 }
1575
1576 /***************************************************************************
1577  *              MapHInstSL                      (KERNEL32.518)
1578  */
1579 void WINAPI REGS_FUNC(MapHInstSL)( CONTEXT *context )
1580 {
1581 #ifdef __i386__
1582         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1583 #endif
1584 }
1585
1586 /***************************************************************************
1587  *              MapHInstLS_PN                   (KERNEL32.517)
1588  */
1589 void WINAPI REGS_FUNC(MapHInstLS_PN)( CONTEXT *context )
1590 {
1591 #ifdef __i386__
1592         if (EAX_reg(context))
1593             EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1594 #endif
1595 }
1596
1597 /***************************************************************************
1598  *              MapHInstSL_PN                   (KERNEL32.519)
1599  */
1600 void WINAPI REGS_FUNC(MapHInstSL_PN)( CONTEXT *context )
1601 {
1602 #ifdef __i386__
1603         if (EAX_reg(context))
1604             EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1605 #endif
1606 }
1607
1608 /***************************************************************************
1609  *              WIN16_MapHInstLS                (KERNEL.472)
1610  */
1611 VOID WINAPI WIN16_MapHInstLS( CONTEXT86 *context )
1612 {
1613         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1614 }
1615
1616 /***************************************************************************
1617  *              WIN16_MapHInstSL                (KERNEL.473)
1618  */
1619 VOID WINAPI WIN16_MapHInstSL( CONTEXT86 *context )
1620 {
1621         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1622 }