NE_MODULE.stack_size was set to a ridiculously small value of 5.
[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 "module.h"
13 #include "file.h"
14 #include "ldt.h"
15 #include "callback.h"
16 #include "heap.h"
17 #include "task.h"
18 #include "global.h"
19 #include "process.h"
20 #include "toolhelp.h"
21 #include "snoop.h"
22 #include "stackframe.h"
23 #include "debug.h"
24
25 FARPROC16 (*fnSNOOP16_GetProcAddress16)(HMODULE16,DWORD,FARPROC16) = NULL;
26 void (*fnSNOOP16_RegisterDLL)(NE_MODULE*,LPCSTR) = NULL;
27
28 #define hFirstModule (pThhook->hExeHead)
29
30 static NE_MODULE *pCachedModule = 0;  /* Module cached by NE_OpenFile */
31
32 static HMODULE16 NE_LoadBuiltin(LPCSTR name,BOOL32 force) { return 0; }
33 HMODULE16 (*fnBUILTIN_LoadModule)(LPCSTR name,BOOL32 force) = NE_LoadBuiltin;
34
35
36 /***********************************************************************
37  *           NE_GetPtr
38  */
39 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
40 {
41     return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
42 }
43
44
45 /***********************************************************************
46  *           NE_DumpModule
47  */
48 void NE_DumpModule( HMODULE16 hModule )
49 {
50     int i, ordinal;
51     SEGTABLEENTRY *pSeg;
52     BYTE *pstr;
53     WORD *pword;
54     NE_MODULE *pModule;
55
56     if (!(pModule = NE_GetPtr( hModule )))
57     {
58         MSG( "**** %04x is not a module handle\n", hModule );
59         return;
60     }
61
62       /* Dump the module info */
63     DUMP( "---\n" );
64     DUMP( "Module %04x:\n", hModule );
65     DUMP( "count=%d flags=%04x heap=%d stack=%d\n",
66           pModule->count, pModule->flags,
67           pModule->heap_size, pModule->stack_size );
68     DUMP( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
69           pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
70           pModule->seg_count, pModule->modref_count );
71     DUMP( "os_flags=%d swap_area=%d version=%04x\n",
72           pModule->os_flags, pModule->min_swap_area,
73           pModule->expected_version );
74     if (pModule->flags & NE_FFLAGS_WIN32)
75         DUMP( "PE module=%08x\n", pModule->module32 );
76
77       /* Dump the file info */
78     DUMP( "---\n" );
79     DUMP( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
80
81       /* Dump the segment table */
82     DUMP( "---\n" );
83     DUMP( "Segment table:\n" );
84     pSeg = NE_SEG_TABLE( pModule );
85     for (i = 0; i < pModule->seg_count; i++, pSeg++)
86         DUMP( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
87               i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
88               pSeg->minsize, pSeg->hSeg );
89
90       /* Dump the resource table */
91     DUMP( "---\n" );
92     DUMP( "Resource table:\n" );
93     if (pModule->res_table)
94     {
95         pword = (WORD *)((BYTE *)pModule + pModule->res_table);
96         DUMP( "Alignment: %d\n", *pword++ );
97         while (*pword)
98         {
99             struct resource_typeinfo_s *ptr = (struct resource_typeinfo_s *)pword;
100             struct resource_nameinfo_s *pname = (struct resource_nameinfo_s *)(ptr + 1);
101             DUMP( "id=%04x count=%d\n", ptr->type_id, ptr->count );
102             for (i = 0; i < ptr->count; i++, pname++)
103                 DUMP( "offset=%d len=%d id=%04x\n",
104                       pname->offset, pname->length, pname->id );
105             pword = (WORD *)pname;
106         }
107     }
108     else DUMP( "None\n" );
109
110       /* Dump the resident name table */
111     DUMP( "---\n" );
112     DUMP( "Resident-name table:\n" );
113     pstr = (char *)pModule + pModule->name_table;
114     while (*pstr)
115     {
116         DUMP( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
117               *(WORD *)(pstr + *pstr + 1) );
118         pstr += *pstr + 1 + sizeof(WORD);
119     }
120
121       /* Dump the module reference table */
122     DUMP( "---\n" );
123     DUMP( "Module ref table:\n" );
124     if (pModule->modref_table)
125     {
126         pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
127         for (i = 0; i < pModule->modref_count; i++, pword++)
128         {
129             char name[10];
130             GetModuleName( *pword, name, sizeof(name) );
131             DUMP( "%d: %04x -> '%s'\n", i, *pword, name );
132         }
133     }
134     else DUMP( "None\n" );
135
136       /* Dump the entry table */
137     DUMP( "---\n" );
138     DUMP( "Entry table:\n" );
139     pstr = (char *)pModule + pModule->entry_table;
140     ordinal = 1;
141     while (*pstr)
142     {
143         DUMP( "Bundle %d-%d: %02x\n", ordinal, ordinal + *pstr - 1, pstr[1]);
144         if (!pstr[1])
145         {
146             ordinal += *pstr;
147             pstr += 2;
148         }
149         else if ((BYTE)pstr[1] == 0xff)  /* moveable */
150         {
151             i = *pstr;
152             pstr += 2;
153             while (i--)
154             {
155                 DUMP( "%d: %02x:%04x (moveable)\n",
156                       ordinal++, pstr[3], *(WORD *)(pstr + 4) );
157                 pstr += 6;
158             }
159         }
160         else  /* fixed */
161         {
162             i = *pstr;
163             pstr += 2;
164             while (i--)
165             {
166                 DUMP( "%d: %04x (fixed)\n",
167                       ordinal++, *(WORD *)(pstr + 1) );
168                 pstr += 3;
169             }
170         }
171     }
172
173     /* Dump the non-resident names table */
174     DUMP( "---\n" );
175     DUMP( "Non-resident names table:\n" );
176     if (pModule->nrname_handle)
177     {
178         pstr = (char *)GlobalLock16( pModule->nrname_handle );
179         while (*pstr)
180         {
181             DUMP( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
182                    *(WORD *)(pstr + *pstr + 1) );
183             pstr += *pstr + 1 + sizeof(WORD);
184         }
185     }
186     DUMP( "\n" );
187 }
188
189
190 /***********************************************************************
191  *           NE_WalkModules
192  *
193  * Walk the module list and print the modules.
194  */
195 void NE_WalkModules(void)
196 {
197     HMODULE16 hModule = hFirstModule;
198     MSG( "Module Flags Name\n" );
199     while (hModule)
200     {
201         NE_MODULE *pModule = NE_GetPtr( hModule );
202         if (!pModule)
203         {
204             MSG( "Bad module %04x in list\n", hModule );
205             return;
206         }
207         MSG( " %04x  %04x  %.*s\n", hModule, pModule->flags,
208                  *((char *)pModule + pModule->name_table),
209                  (char *)pModule + pModule->name_table + 1 );
210         hModule = pModule->next;
211     }
212 }
213
214
215 /**********************************************************************
216  *           NE_RegisterModule
217  */
218 void NE_RegisterModule( NE_MODULE *pModule )
219 {
220     pModule->next = hFirstModule;
221     hFirstModule = pModule->self;
222 }
223
224
225 /***********************************************************************
226  *           NE_GetOrdinal
227  *
228  * Lookup the ordinal for a given name.
229  */
230 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
231 {
232     unsigned char buffer[256], *cpnt;
233     BYTE len;
234     NE_MODULE *pModule;
235
236     if (!(pModule = NE_GetPtr( hModule ))) return 0;
237     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
238
239     TRACE( module, "(%04x,'%s')\n", hModule, name );
240
241       /* First handle names of the form '#xxxx' */
242
243     if (name[0] == '#') return atoi( name + 1 );
244
245       /* Now copy and uppercase the string */
246
247     strcpy( buffer, name );
248     CharUpper32A( buffer );
249     len = strlen( buffer );
250
251       /* First search the resident names */
252
253     cpnt = (char *)pModule + pModule->name_table;
254
255       /* Skip the first entry (module name) */
256     cpnt += *cpnt + 1 + sizeof(WORD);
257     while (*cpnt)
258     {
259         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
260         {
261             TRACE(module, "  Found: ordinal=%d\n",
262                             *(WORD *)(cpnt + *cpnt + 1) );
263             return *(WORD *)(cpnt + *cpnt + 1);
264         }
265         cpnt += *cpnt + 1 + sizeof(WORD);
266     }
267
268       /* Now search the non-resident names table */
269
270     if (!pModule->nrname_handle) return 0;  /* No non-resident table */
271     cpnt = (char *)GlobalLock16( pModule->nrname_handle );
272
273       /* Skip the first entry (module description string) */
274     cpnt += *cpnt + 1 + sizeof(WORD);
275     while (*cpnt)
276     {
277         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
278         {
279             TRACE(module, "  Found: ordinal=%d\n",
280                             *(WORD *)(cpnt + *cpnt + 1) );
281             return *(WORD *)(cpnt + *cpnt + 1);
282         }
283         cpnt += *cpnt + 1 + sizeof(WORD);
284     }
285     return 0;
286 }
287
288
289 /***********************************************************************
290  *           NE_GetEntryPoint   (WPROCS.27)
291  *
292  * Return the entry point for a given ordinal.
293  */
294 FARPROC16 NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
295 {
296     return NE_GetEntryPointEx( hModule, ordinal, TRUE );
297 }
298 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
299 {
300     NE_MODULE *pModule;
301     WORD curOrdinal = 1;
302     BYTE *p;
303     WORD sel, offset;
304
305     if (!(pModule = NE_GetPtr( hModule ))) return 0;
306     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
307
308     p = (BYTE *)pModule + pModule->entry_table;
309     while (*p && (curOrdinal + *p <= ordinal))
310     {
311           /* Skipping this bundle */
312         curOrdinal += *p;
313         switch(p[1])
314         {
315             case 0:    p += 2; break;  /* unused */
316             case 0xff: p += 2 + *p * 6; break;  /* moveable */
317             default:   p += 2 + *p * 3; break;  /* fixed */
318         }
319     }
320     if (!*p) return 0;
321
322     switch(p[1])
323     {
324         case 0:  /* unused */
325             return 0;
326         case 0xff:  /* moveable */
327             p += 2 + 6 * (ordinal - curOrdinal);
328             sel = p[3];
329             offset = *(WORD *)(p + 4);
330             break;
331         default:  /* fixed */
332             sel = p[1];
333             p += 2 + 3 * (ordinal - curOrdinal);
334             offset = *(WORD *)(p + 1);
335             break;
336     }
337
338     if (sel == 0xfe) sel = 0xffff;  /* constant entry */
339     else sel = GlobalHandleToSel(NE_SEG_TABLE(pModule)[sel-1].hSeg);
340     if (sel==0xffff)
341         return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
342     if (!snoop || !fnSNOOP16_GetProcAddress16)
343         return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
344     else
345         return (FARPROC16)fnSNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset ));
346 }
347
348
349 /***********************************************************************
350  *           NE_SetEntryPoint
351  *
352  * Change the value of an entry point. Use with caution!
353  * It can only change the offset value, not the selector.
354  */
355 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
356 {
357     NE_MODULE *pModule;
358     WORD curOrdinal = 1;
359     BYTE *p;
360
361     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
362     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
363
364     p = (BYTE *)pModule + pModule->entry_table;
365     while (*p && (curOrdinal + *p <= ordinal))
366     {
367           /* Skipping this bundle */
368         curOrdinal += *p;
369         switch(p[1])
370         {
371             case 0:    p += 2; break;  /* unused */
372             case 0xff: p += 2 + *p * 6; break;  /* moveable */
373             default:   p += 2 + *p * 3; break;  /* fixed */
374         }
375     }
376     if (!*p) return FALSE;
377
378     switch(p[1])
379     {
380         case 0:  /* unused */
381             return FALSE;
382         case 0xff:  /* moveable */
383             p += 2 + 6 * (ordinal - curOrdinal);
384             *(WORD *)(p + 4) = offset;
385             break;
386         default:  /* fixed */
387             p += 2 + 3 * (ordinal - curOrdinal);
388             *(WORD *)(p + 1) = offset;
389             break;
390     }
391     return TRUE;
392 }
393
394
395 /***********************************************************************
396  *           NE_OpenFile
397  */
398 int NE_OpenFile( NE_MODULE *pModule )
399 {
400     DOS_FULL_NAME full_name;
401     char *name;
402
403     static int cachedfd = -1;
404
405     TRACE( module, "(%p) cache: mod=%p fd=%d\n",
406            pModule, pCachedModule, cachedfd );
407     if (pCachedModule == pModule) return cachedfd;
408     close( cachedfd );
409     pCachedModule = pModule;
410     name = NE_MODULE_NAME( pModule );
411     if (!DOSFS_GetFullName( name, TRUE, &full_name ) ||
412         (cachedfd = open( full_name.long_name, O_RDONLY )) == -1)
413         MSG( "Can't open file '%s' for module %04x\n", name, pModule->self );
414     TRACE(module, "opened '%s' -> %d\n",
415                     name, cachedfd );
416     return cachedfd;
417 }
418
419
420 /***********************************************************************
421  *           NE_LoadExeHeader
422  */
423 static HMODULE16 NE_LoadExeHeader( HFILE16 hFile, OFSTRUCT *ofs )
424 {
425     IMAGE_DOS_HEADER mz_header;
426     IMAGE_OS2_HEADER ne_header;
427     int size;
428     HMODULE16 hModule;
429     NE_MODULE *pModule;
430     BYTE *pData;
431     char *buffer, *fastload = NULL;
432     int fastload_offset = 0, fastload_length = 0;
433
434   /* Read a block from either the file or the fast-load area. */
435 #define READ(offset,size,buffer) \
436        ((fastload && ((offset) >= fastload_offset) && \
437          ((offset)+(size) <= fastload_offset+fastload_length)) ? \
438         (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
439         (_llseek16( hFile, (offset), SEEK_SET), \
440          _hread16( hFile, (buffer), (size) ) == (size)))
441
442     _llseek16( hFile, 0, SEEK_SET );
443     if ((_hread16(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
444         (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
445         return (HMODULE16)11;  /* invalid exe */
446
447     _llseek16( hFile, mz_header.e_lfanew, SEEK_SET );
448     if (_hread16( hFile, &ne_header, sizeof(ne_header) ) != sizeof(ne_header))
449         return (HMODULE16)11;  /* invalid exe */
450
451     if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21;  /* win32 exe */
452     if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11;  /* invalid exe */
453
454     if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
455       MSG("Sorry, this is an OS/2 linear executable (LX) file !\n");
456       return (HMODULE16)12;
457     }
458
459     /* We now have a valid NE header */
460
461     size = sizeof(NE_MODULE) +
462              /* segment table */
463            ne_header.n_segment_tab * sizeof(SEGTABLEENTRY) +
464              /* resource table */
465            ne_header.rname_tab_offset - ne_header.resource_tab_offset +
466              /* resident names table */
467            ne_header.moduleref_tab_offset - ne_header.rname_tab_offset +
468              /* module ref table */
469            ne_header.n_mod_ref_tab * sizeof(WORD) + 
470              /* imported names table */
471            ne_header.entry_tab_offset - ne_header.iname_tab_offset +
472              /* entry table length */
473            ne_header.entry_tab_length +
474              /* loaded file info */
475            sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1;
476
477     hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
478     if (!hModule) return (HMODULE16)11;  /* invalid exe */
479     FarSetOwner( hModule, hModule );
480     pModule = (NE_MODULE *)GlobalLock16( hModule );
481     memcpy( pModule, &ne_header, sizeof(ne_header) );
482     pModule->count = 0;
483     /* check *programs* for default minimal stack size */
484     if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
485                 && (pModule->stack_size < 0x1400) )
486                 pModule->stack_size = 0x1400;
487     pModule->module32 = 0;
488     pModule->self = hModule;
489     pModule->self_loading_sel = 0;
490     pData = (BYTE *)(pModule + 1);
491
492     /* Clear internal Wine flags in case they are set in the EXE file */
493
494     pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
495
496     /* Read the fast-load area */
497
498     if (ne_header.additional_flags & NE_AFLAGS_FASTLOAD)
499     {
500         fastload_offset=ne_header.fastload_offset<<ne_header.align_shift_count;
501         fastload_length=ne_header.fastload_length<<ne_header.align_shift_count;
502         TRACE(module, "Using fast-load area offset=%x len=%d\n",
503                         fastload_offset, fastload_length );
504         if ((fastload = HeapAlloc( SystemHeap, 0, fastload_length )) != NULL)
505         {
506             _llseek16( hFile, fastload_offset, SEEK_SET);
507             if (_hread16(hFile, fastload, fastload_length) != fastload_length)
508             {
509                 HeapFree( SystemHeap, 0, fastload );
510                 WARN( module, "Error reading fast-load area!\n");
511                 fastload = NULL;
512             }
513         }
514     }
515
516     /* Get the segment table */
517
518     pModule->seg_table = (int)pData - (int)pModule;
519     buffer = HeapAlloc( SystemHeap, 0, ne_header.n_segment_tab *
520                                       sizeof(struct ne_segment_table_entry_s));
521     if (buffer)
522     {
523         int i;
524         struct ne_segment_table_entry_s *pSeg;
525
526         if (!READ( mz_header.e_lfanew + ne_header.segment_tab_offset,
527              ne_header.n_segment_tab * sizeof(struct ne_segment_table_entry_s),
528              buffer ))
529         {
530             HeapFree( SystemHeap, 0, buffer );
531             if (fastload) HeapFree( SystemHeap, 0, fastload );
532             GlobalFree16( hModule );
533             return (HMODULE16)11;  /* invalid exe */
534         }
535         pSeg = (struct ne_segment_table_entry_s *)buffer;
536         for (i = ne_header.n_segment_tab; i > 0; i--, pSeg++)
537         {
538             memcpy( pData, pSeg, sizeof(*pSeg) );
539             pData += sizeof(SEGTABLEENTRY);
540         }
541         HeapFree( SystemHeap, 0, buffer );
542     }
543     else
544     {
545         if (fastload) HeapFree( SystemHeap, 0, fastload );
546         GlobalFree16( hModule );
547         return (HMODULE16)11;  /* invalid exe */
548     }
549
550     /* Get the resource table */
551
552     if (ne_header.resource_tab_offset < ne_header.rname_tab_offset)
553     {
554         pModule->res_table = (int)pData - (int)pModule;
555         if (!READ(mz_header.e_lfanew + ne_header.resource_tab_offset,
556                   ne_header.rname_tab_offset - ne_header.resource_tab_offset,
557                   pData )) return (HMODULE16)11;  /* invalid exe */
558         pData += ne_header.rname_tab_offset - ne_header.resource_tab_offset;
559         NE_InitResourceHandler( hModule );
560     }
561     else pModule->res_table = 0;  /* No resource table */
562
563     /* Get the resident names table */
564
565     pModule->name_table = (int)pData - (int)pModule;
566     if (!READ( mz_header.e_lfanew + ne_header.rname_tab_offset,
567                ne_header.moduleref_tab_offset - ne_header.rname_tab_offset,
568                pData ))
569     {
570         if (fastload) HeapFree( SystemHeap, 0, fastload );
571         GlobalFree16( hModule );
572         return (HMODULE16)11;  /* invalid exe */
573     }
574     pData += ne_header.moduleref_tab_offset - ne_header.rname_tab_offset;
575
576     /* Get the module references table */
577
578     if (ne_header.n_mod_ref_tab > 0)
579     {
580         pModule->modref_table = (int)pData - (int)pModule;
581         if (!READ( mz_header.e_lfanew + ne_header.moduleref_tab_offset,
582                   ne_header.n_mod_ref_tab * sizeof(WORD),
583                   pData ))
584         {
585             if (fastload) HeapFree( SystemHeap, 0, fastload );
586             GlobalFree16( hModule );
587             return (HMODULE16)11;  /* invalid exe */
588         }
589         pData += ne_header.n_mod_ref_tab * sizeof(WORD);
590     }
591     else pModule->modref_table = 0;  /* No module references */
592
593     /* Get the imported names table */
594
595     pModule->import_table = (int)pData - (int)pModule;
596     if (!READ( mz_header.e_lfanew + ne_header.iname_tab_offset, 
597                ne_header.entry_tab_offset - ne_header.iname_tab_offset,
598                pData ))
599     {
600         if (fastload) HeapFree( SystemHeap, 0, fastload );
601         GlobalFree16( hModule );
602         return (HMODULE16)11;  /* invalid exe */
603     }
604     pData += ne_header.entry_tab_offset - ne_header.iname_tab_offset;
605
606     /* Get the entry table */
607
608     pModule->entry_table = (int)pData - (int)pModule;
609     if (!READ( mz_header.e_lfanew + ne_header.entry_tab_offset,
610                ne_header.entry_tab_length,
611                pData ))
612     {
613         if (fastload) HeapFree( SystemHeap, 0, fastload );
614         GlobalFree16( hModule );
615         return (HMODULE16)11;  /* invalid exe */
616     }
617     pData += ne_header.entry_tab_length;
618
619     /* Store the filename information */
620
621     pModule->fileinfo = (int)pData - (int)pModule;
622     size = sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1;
623     memcpy( pData, ofs, size );
624     ((OFSTRUCT *)pData)->cBytes = size - 1;
625     pData += size;
626
627     /* Free the fast-load area */
628
629 #undef READ
630     if (fastload) HeapFree( SystemHeap, 0, fastload );
631
632     /* Get the non-resident names table */
633
634     if (ne_header.nrname_tab_length)
635     {
636         pModule->nrname_handle = GLOBAL_Alloc( 0, ne_header.nrname_tab_length,
637                                                hModule, FALSE, FALSE, FALSE );
638         if (!pModule->nrname_handle)
639         {
640             GlobalFree16( hModule );
641             return (HMODULE16)11;  /* invalid exe */
642         }
643         buffer = GlobalLock16( pModule->nrname_handle );
644         _llseek16( hFile, ne_header.nrname_tab_offset, SEEK_SET );
645         if (_hread16( hFile, buffer, ne_header.nrname_tab_length )
646               != ne_header.nrname_tab_length)
647         {
648             GlobalFree16( pModule->nrname_handle );
649             GlobalFree16( hModule );
650             return (HMODULE16)11;  /* invalid exe */
651         }
652     }
653     else pModule->nrname_handle = 0;
654
655     /* Allocate a segment for the implicitly-loaded DLLs */
656
657     if (pModule->modref_count)
658     {
659         pModule->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,
660                                     (pModule->modref_count+1)*sizeof(HMODULE16),
661                                     hModule, FALSE, FALSE, FALSE );
662         if (!pModule->dlls_to_init)
663         {
664             if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
665             GlobalFree16( hModule );
666             return (HMODULE16)11;  /* invalid exe */
667         }
668     }
669     else pModule->dlls_to_init = 0;
670
671     NE_RegisterModule( pModule );
672     if (fnSNOOP16_RegisterDLL)
673         fnSNOOP16_RegisterDLL(pModule,ofs->szPathName);
674     return hModule;
675 }
676
677
678 /***********************************************************************
679  *           NE_LoadDLLs
680  *
681  * Load all DLLs implicitly linked to a module.
682  */
683 static BOOL32 NE_LoadDLLs( NE_MODULE *pModule )
684 {
685     int i;
686     WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
687     WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
688
689     for (i = 0; i < pModule->modref_count; i++, pModRef++)
690     {
691         char buffer[260];
692         BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
693         memcpy( buffer, pstr + 1, *pstr );
694         strcpy( buffer + *pstr, ".dll" );
695         TRACE(module, "Loading '%s'\n", buffer );
696         if (!(*pModRef = GetModuleHandle16( buffer )))
697         {
698             /* If the DLL is not loaded yet, load it and store */
699             /* its handle in the list of DLLs to initialize.   */
700             HMODULE16 hDLL;
701
702             if ((hDLL = NE_LoadModule( buffer, NULL, TRUE, TRUE )) == 2)
703             {
704                 /* file not found */
705                 char *p;
706
707                 /* Try with prepending the path of the current module */
708                 GetModuleFileName16( pModule->self, buffer, sizeof(buffer) );
709                 if (!(p = strrchr( buffer, '\\' ))) p = buffer;
710                 memcpy( p + 1, pstr + 1, *pstr );
711                 strcpy( p + 1 + *pstr, ".dll" );
712                 hDLL = NE_LoadModule( buffer, NULL, TRUE, TRUE );
713             }
714             if (hDLL < 32)
715             {
716                 /* FIXME: cleanup what was done */
717
718                 MSG( "Could not load '%s' required by '%.*s', error=%d\n",
719                      buffer, *((BYTE*)pModule + pModule->name_table),
720                      (char *)pModule + pModule->name_table + 1, hDLL );
721                 return FALSE;
722             }
723             *pModRef = GetExePtr( hDLL );
724             *pDLLs++ = *pModRef;
725         }
726         else  /* Increment the reference count of the DLL */
727         {
728             NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
729             if (pOldDLL) pOldDLL->count++;
730         }
731     }
732     return TRUE;
733 }
734
735
736 /**********************************************************************
737  *          NE_LoadModule
738  *
739  * Implementation of LoadModule16().
740  */
741 HINSTANCE16 NE_LoadModule( LPCSTR name, HINSTANCE16 *hPrevInstance,
742                            BOOL32 implicit, BOOL32 lib_only )
743 {
744     HMODULE16 hModule;
745     HINSTANCE16 hInstance;
746     NE_MODULE *pModule;
747     HFILE16 hFile;
748     OFSTRUCT ofs;
749
750     /* Check if the module is already loaded */
751
752     if ((hModule = GetModuleHandle16( name )) != 0)
753     {
754         HINSTANCE16 prev;
755         pModule = NE_GetPtr( hModule );
756         if ( pModule->module32 ) return (HINSTANCE16)21;
757
758         hInstance = NE_CreateInstance( pModule, &prev, lib_only );
759         if (hInstance != prev)  /* not a library */
760             NE_LoadSegment( pModule, pModule->dgroup );
761         pModule->count++;
762         if (hPrevInstance) *hPrevInstance = prev;
763         return hInstance;
764     }
765     if (hPrevInstance) *hPrevInstance = 0;
766
767     /* Try to load the built-in first if not disabled */
768
769     if ((hModule = fnBUILTIN_LoadModule( name, FALSE ))) return hModule;
770
771     if ((hFile = OpenFile16( name, &ofs, OF_READ )) == HFILE_ERROR16)
772     {
773         /* Now try the built-in even if disabled */
774         if ((hModule = fnBUILTIN_LoadModule( name, TRUE )))
775         {
776             MSG( "Could not load Windows DLL '%s', using built-in module.\n",
777                  name );
778             return hModule;
779         }
780         return 2;  /* File not found */
781     }
782
783     /* Create the module structure */
784
785     hModule = NE_LoadExeHeader( hFile, &ofs );
786     _lclose16( hFile );
787     if (hModule < 32) return hModule;
788     pModule = NE_GetPtr( hModule );
789
790     /* Allocate the segments for this module */
791
792     if (!NE_CreateSegments( pModule ) ||
793         !(hInstance = NE_CreateInstance( pModule, NULL, lib_only )))
794     {
795         GlobalFreeAll( hModule );
796         return 8;  /* Insufficient memory */
797     }
798
799     /* Load the referenced DLLs */
800
801     if (!NE_LoadDLLs( pModule ))
802         return 2;  /* File not found (FIXME: free everything) */
803
804     /* Load the segments */
805
806     NE_LoadAllSegments( pModule );
807
808     /* Fixup the functions prologs */
809
810     NE_FixupPrologs( pModule );
811
812     /* Make sure the usage count is 1 on the first loading of  */
813     /* the module, even if it contains circular DLL references */
814
815     pModule->count = 1;
816
817     /* Call initialization rountines for all loaded DLLs. Note that
818      * when we load implicitly linked DLLs this will be done by InitTask().
819      */
820
821     if (!implicit && (pModule->flags & NE_FFLAGS_LIBMODULE))
822         NE_InitializeDLLs( hModule );
823
824     return hInstance;
825 }
826
827
828 /***********************************************************************
829  *           LoadLibrary   (KERNEL.95)
830  */
831 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
832 {
833     HINSTANCE16 handle;
834     LPCSTR p;
835     char *new_name;
836
837     TRACE(module, "(%08x) %s\n", (int)libname, libname);
838
839     /* Check for an extension */
840
841     if ((p = strrchr( libname, '.')) && !strchr( p, '/' ) && !strchr( p, '\\'))
842     {
843         /* An extension is present -> use the name as is */
844         return NE_LoadModule( libname, NULL, FALSE, TRUE );
845     }
846
847     /* Now append .dll before loading */
848
849     if (!(new_name = HeapAlloc( GetProcessHeap(), 0, strlen(libname) + 4 )))
850         return 0;
851     strcpy( new_name, libname );
852     strcat( new_name, ".dll" );
853     handle = NE_LoadModule( new_name, NULL, FALSE, TRUE );
854     HeapFree( GetProcessHeap(), 0, new_name );
855     return handle;
856 }
857
858
859 /**********************************************************************
860  *          MODULE_CallWEP
861  *
862  * Call a DLL's WEP, allowing it to shut down.
863  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
864  */
865 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
866 {
867     FARPROC16 WEP = (FARPROC16)0;
868     WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
869
870     if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
871     if (!WEP)
872     {
873         WARN(module, "module %04x doesn't have a WEP\n", hModule );
874         return FALSE;
875     }
876     return Callbacks->CallWindowsExitProc( WEP, WEP_FREE_DLL );
877 }
878
879
880 /**********************************************************************
881  *          NE_FreeModule
882  *
883  * Implementation of FreeModule16().
884  */
885 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL32 call_wep )
886 {
887     HMODULE16 *hPrevModule;
888     NE_MODULE *pModule;
889     HMODULE16 *pModRef;
890     int i;
891
892     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
893     hModule = pModule->self;
894
895     TRACE( module, "%04x count %d\n", hModule, pModule->count );
896
897     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
898     else pModule->count = 0;
899
900     if (pModule->flags & NE_FFLAGS_BUILTIN)
901         return FALSE;  /* Can't free built-in module */
902
903     if (call_wep)
904     {
905         if (pModule->flags & NE_FFLAGS_LIBMODULE)
906         {
907             TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
908             MODULE_CallWEP( hModule );
909
910             /* Free the objects owned by the DLL module */
911
912             if (pTask && pTask->userhandler)
913                 pTask->userhandler( hModule, USIG_DLL_UNLOAD, 0,
914                                     pTask->hInstance, pTask->hQueue );
915         }
916         else
917             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
918     }
919     
920
921     /* Clear magic number just in case */
922
923     pModule->magic = pModule->self = 0;
924
925       /* Remove it from the linked list */
926
927     hPrevModule = &hFirstModule;
928     while (*hPrevModule && (*hPrevModule != hModule))
929     {
930         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
931     }
932     if (*hPrevModule) *hPrevModule = pModule->next;
933
934     /* Free the referenced modules */
935
936     pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
937     for (i = 0; i < pModule->modref_count; i++, pModRef++)
938     {
939         NE_FreeModule( *pModRef, call_wep );
940     }
941
942     /* Free the module storage */
943
944     GlobalFreeAll( hModule );
945
946     /* Remove module from cache */
947
948     if (pCachedModule == pModule) pCachedModule = NULL;
949     return TRUE;
950 }
951
952
953 /**********************************************************************
954  *          FreeModule16    (KERNEL.46)
955  */
956 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
957 {
958     return NE_FreeModule( hModule, TRUE );
959 }
960
961
962 /***********************************************************************
963  *           FreeLibrary16   (KERNEL.96)
964  */
965 void WINAPI FreeLibrary16( HINSTANCE16 handle )
966 {
967     TRACE(module,"%04x\n", handle );
968     FreeModule16( handle );
969 }
970
971
972 /**********************************************************************
973  *          GetModuleName    (KERNEL.27)
974  */
975 BOOL16 WINAPI GetModuleName( HINSTANCE16 hinst, LPSTR buf, INT16 count )
976 {
977     NE_MODULE *pModule;
978     BYTE *p;
979
980     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
981     p = (BYTE *)pModule + pModule->name_table;
982     if (count > *p) count = *p + 1;
983     if (count > 0)
984     {
985         memcpy( buf, p + 1, count - 1 );
986         buf[count-1] = '\0';
987     }
988     return TRUE;
989 }
990
991
992 /**********************************************************************
993  *          GetModuleUsage    (KERNEL.48)
994  */
995 INT16 WINAPI GetModuleUsage( HINSTANCE16 hModule )
996 {
997     NE_MODULE *pModule = NE_GetPtr( hModule );
998     return pModule ? pModule->count : 0;
999 }
1000
1001
1002 /**********************************************************************
1003  *          GetExpWinVer    (KERNEL.167)
1004  */
1005 WORD WINAPI GetExpWinVer( HMODULE16 hModule )
1006 {
1007     NE_MODULE *pModule = NE_GetPtr( hModule );
1008     return pModule ? pModule->expected_version : 0;
1009 }
1010
1011
1012 /**********************************************************************
1013  *          GetModuleFileName16    (KERNEL.49)
1014  */
1015 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1016                                   INT16 nSize )
1017 {
1018     NE_MODULE *pModule;
1019
1020     if (!hModule) hModule = GetCurrentTask();
1021     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1022     lstrcpyn32A( lpFileName, NE_MODULE_NAME(pModule), nSize );
1023     TRACE(module, "%s\n", lpFileName );
1024     return strlen(lpFileName);
1025 }
1026
1027
1028 /**********************************************************************
1029  *          GetModuleHandle16    (KERNEL.47)
1030  *
1031  * Find a module from a path name.
1032  *
1033  * RETURNS
1034  *   LOWORD:
1035  *      the win16 module handle if found
1036  *      0 if not
1037  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1038  *      Always hFirstModule
1039  */
1040 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1041 {
1042     if (HIWORD(name) == 0)
1043         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1044     return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1045 }
1046
1047 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1048 {
1049     HMODULE16 hModule = hFirstModule;
1050     LPCSTR filename, dotptr, modulepath, modulename;
1051     BYTE len, *name_table;
1052
1053     if (!(filename = strrchr( name, '\\' ))) filename = name;
1054     else filename++;
1055     if ((dotptr = strrchr( filename, '.' )) != NULL)
1056         len = (BYTE)(dotptr - filename);
1057     else len = strlen( filename );
1058
1059     while (hModule)
1060     {
1061         NE_MODULE *pModule = NE_GetPtr( hModule );
1062         if (!pModule) break;
1063         modulepath = NE_MODULE_NAME(pModule);
1064         if (!(modulename = strrchr( modulepath, '\\' )))
1065             modulename = modulepath;
1066         else modulename++;
1067         if (!lstrcmpi32A( modulename, filename )) return hModule;
1068
1069         name_table = (BYTE *)pModule + pModule->name_table;
1070         if ((*name_table == len) && !lstrncmpi32A(filename, name_table+1, len))
1071             return hModule;
1072         hModule = pModule->next;
1073     }
1074     return 0;
1075 }
1076
1077
1078 /**********************************************************************
1079  *          ModuleFirst    (TOOLHELP.59)
1080  */
1081 BOOL16 WINAPI ModuleFirst( MODULEENTRY *lpme )
1082 {
1083     lpme->wNext = hFirstModule;
1084     return ModuleNext( lpme );
1085 }
1086
1087
1088 /**********************************************************************
1089  *          ModuleNext    (TOOLHELP.60)
1090  */
1091 BOOL16 WINAPI ModuleNext( MODULEENTRY *lpme )
1092 {
1093     NE_MODULE *pModule;
1094     char *name;
1095
1096     if (!lpme->wNext) return FALSE;
1097     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1098     name = (char *)pModule + pModule->name_table;
1099     memcpy( lpme->szModule, name + 1, *name );
1100     lpme->szModule[(BYTE)*name] = '\0';
1101     lpme->hModule = lpme->wNext;
1102     lpme->wcUsage = pModule->count;
1103     strncpy( lpme->szExePath, NE_MODULE_NAME(pModule), MAX_PATH );
1104     lpme->szExePath[MAX_PATH] = '\0';
1105     lpme->wNext = pModule->next;
1106     return TRUE;
1107 }
1108
1109
1110 /**********************************************************************
1111  *          ModuleFindName    (TOOLHELP.61)
1112  */
1113 BOOL16 WINAPI ModuleFindName( MODULEENTRY *lpme, LPCSTR name )
1114 {
1115     lpme->wNext = GetModuleHandle16( name );
1116     return ModuleNext( lpme );
1117 }
1118
1119
1120 /**********************************************************************
1121  *          ModuleFindHandle    (TOOLHELP.62)
1122  */
1123 BOOL16 WINAPI ModuleFindHandle( MODULEENTRY *lpme, HMODULE16 hModule )
1124 {
1125     hModule = GetExePtr( hModule );
1126     lpme->wNext = hModule;
1127     return ModuleNext( lpme );
1128 }
1129
1130 /***************************************************************************
1131  *              MapHModuleLS                    (KERNEL32.520)
1132  */
1133 HMODULE16 WINAPI MapHModuleLS(HMODULE32 hmod) {
1134         NE_MODULE       *pModule;
1135
1136         if (!hmod)
1137                 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1138         if (!HIWORD(hmod))
1139                 return hmod; /* we already have a 16 bit module handle */
1140         pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1141         while (pModule)  {
1142                 if (pModule->module32 == hmod)
1143                         return pModule->self;
1144                 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1145         }
1146         return 0;
1147 }
1148
1149 /***************************************************************************
1150  *              MapHModuleSL                    (KERNEL32.521)
1151  */
1152 HMODULE32 WINAPI MapHModuleSL(HMODULE16 hmod) {
1153         NE_MODULE       *pModule;
1154
1155         if (!hmod) {
1156                 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1157
1158                 hmod = pTask->hInstance;
1159         }
1160         pModule = (NE_MODULE*)GlobalLock16(hmod);
1161         if (    (pModule->magic!=IMAGE_OS2_SIGNATURE)   ||
1162                 !(pModule->flags & NE_FFLAGS_WIN32)
1163         )
1164                 return 0;
1165         return pModule->module32;
1166 }
1167
1168 /***************************************************************************
1169  *              MapHInstLS                      (KERNEL32.516)
1170  */
1171 REGS_ENTRYPOINT(MapHInstLS) {
1172         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1173 }
1174
1175 /***************************************************************************
1176  *              MapHInstSL                      (KERNEL32.518)
1177  */
1178 REGS_ENTRYPOINT(MapHInstSL) {
1179         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1180 }
1181
1182 /***************************************************************************
1183  *              MapHInstLS_PN                   (KERNEL32.517)
1184  */
1185 REGS_ENTRYPOINT(MapHInstLS_PN) {
1186         if (EAX_reg(context))
1187             EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1188 }
1189
1190 /***************************************************************************
1191  *              MapHInstSL_PN                   (KERNEL32.519)
1192  */
1193 REGS_ENTRYPOINT(MapHInstSL_PN) {
1194         if (EAX_reg(context))
1195             EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1196 }
1197
1198 /***************************************************************************
1199  *              WIN16_MapHInstLS                (KERNEL.472)
1200  */
1201 VOID WINAPI WIN16_MapHInstLS( CONTEXT *context ) {
1202         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1203 }
1204
1205 /***************************************************************************
1206  *              WIN16_MapHInstSL                (KERNEL.473)
1207  */
1208 VOID WINAPI WIN16_MapHInstSL( CONTEXT *context ) {
1209         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1210 }