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