- New implementation of SendMessage, ReceiveMessage, ReplyMessage functions
[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,BOOL32 force) { return 0; }
37 HMODULE16 (*fnBUILTIN_LoadModule)(LPCSTR name,BOOL32 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             GetModuleName( *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     CharUpper32A( 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 = GlobalHandleToSel(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 HANDLE32 NE_OpenFile( NE_MODULE *pModule )
403 {
404     char *name;
405
406     static HANDLE32 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 = CreateFile32A( 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     FarSetOwner( 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 BOOL32 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         strcpy( buffer + *pstr, ".dll" );
701         TRACE(module, "Loading '%s'\n", buffer );
702         if (!(*pModRef = GetModuleHandle16( buffer )))
703         {
704             /* If the DLL is not loaded yet, load it and store */
705             /* its handle in the list of DLLs to initialize.   */
706             HMODULE16 hDLL;
707
708             if ((hDLL = NE_LoadModule( buffer, NULL, TRUE, TRUE )) == 2)
709             {
710                 /* file not found */
711                 char *p;
712
713                 /* Try with prepending the path of the current module */
714                 GetModuleFileName16( pModule->self, buffer, sizeof(buffer) );
715                 if (!(p = strrchr( buffer, '\\' ))) p = buffer;
716                 memcpy( p + 1, pstr + 1, *pstr );
717                 strcpy( p + 1 + *pstr, ".dll" );
718                 hDLL = NE_LoadModule( buffer, NULL, TRUE, TRUE );
719             }
720             if (hDLL < 32)
721             {
722                 /* FIXME: cleanup what was done */
723
724                 MSG( "Could not load '%s' required by '%.*s', error=%d\n",
725                      buffer, *((BYTE*)pModule + pModule->name_table),
726                      (char *)pModule + pModule->name_table + 1, hDLL );
727                 return FALSE;
728             }
729             *pModRef = GetExePtr( hDLL );
730             *pDLLs++ = *pModRef;
731         }
732         else  /* Increment the reference count of the DLL */
733         {
734             NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
735             if (pOldDLL) pOldDLL->count++;
736         }
737     }
738     return TRUE;
739 }
740
741
742 /**********************************************************************
743  *          NE_LoadModule
744  *
745  * Implementation of LoadModule16().
746  */
747 HINSTANCE16 NE_LoadModule( LPCSTR name, HINSTANCE16 *hPrevInstance,
748                            BOOL32 implicit, BOOL32 lib_only )
749 {
750     HMODULE16 hModule;
751     HINSTANCE16 hInstance;
752     NE_MODULE *pModule;
753     HFILE16 hFile;
754     OFSTRUCT ofs;
755
756     /* Check if the module is already loaded */
757
758     if ((hModule = GetModuleHandle16( name )) != 0)
759     {
760         HINSTANCE16 prev;
761         pModule = NE_GetPtr( hModule );
762         if ( pModule->module32 ) return (HINSTANCE16)21;
763
764         hInstance = NE_CreateInstance( pModule, &prev, lib_only );
765         if (hInstance != prev)  /* not a library */
766             NE_LoadSegment( pModule, pModule->dgroup );
767         pModule->count++;
768         if (hPrevInstance) *hPrevInstance = prev;
769         return hInstance;
770     }
771     if (hPrevInstance) *hPrevInstance = 0;
772
773     /* Try to load the built-in first if not disabled */
774
775     if ((hModule = fnBUILTIN_LoadModule( name, FALSE ))) return hModule;
776
777     if ((hFile = OpenFile16( name, &ofs, OF_READ )) == HFILE_ERROR16)
778     {
779         /* Now try the built-in even if disabled */
780         if ((hModule = fnBUILTIN_LoadModule( name, TRUE )))
781         {
782             MSG( "Could not load Windows DLL '%s', using built-in module.\n",
783                  name );
784             return hModule;
785         }
786         return 2;  /* File not found */
787     }
788
789     /* Create the module structure */
790
791     hModule = NE_LoadExeHeader( hFile, &ofs );
792     _lclose16( hFile );
793     if (hModule < 32) return hModule;
794     pModule = NE_GetPtr( hModule );
795
796     /* Allocate the segments for this module */
797
798     if (!NE_CreateSegments( pModule ) ||
799         !(hInstance = NE_CreateInstance( pModule, NULL, lib_only )))
800     {
801         GlobalFreeAll( hModule );
802         return 8;  /* Insufficient memory */
803     }
804
805     /* Load the referenced DLLs */
806
807     if (!NE_LoadDLLs( pModule ))
808         return 2;  /* File not found (FIXME: free everything) */
809
810     /* Load the segments */
811
812     NE_LoadAllSegments( pModule );
813
814     /* Fixup the functions prologs */
815
816     NE_FixupPrologs( pModule );
817
818     /* Make sure the usage count is 1 on the first loading of  */
819     /* the module, even if it contains circular DLL references */
820
821     pModule->count = 1;
822
823     /* Call initialization rountines for all loaded DLLs. Note that
824      * when we load implicitly linked DLLs this will be done by InitTask().
825      */
826
827     if (!implicit && (pModule->flags & NE_FFLAGS_LIBMODULE))
828         NE_InitializeDLLs( hModule );
829
830     return hInstance;
831 }
832
833
834 /***********************************************************************
835  *           LoadLibrary   (KERNEL.95)
836  */
837 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
838 {
839     HINSTANCE16 handle;
840     LPCSTR p;
841     char *new_name;
842
843     TRACE(module, "(%08x) %s\n", (int)libname, libname);
844
845     /* Check for an extension */
846
847     if ((p = strrchr( libname, '.')) && !strchr( p, '/' ) && !strchr( p, '\\'))
848     {
849         /* An extension is present -> use the name as is */
850         return NE_LoadModule( libname, NULL, FALSE, TRUE );
851     }
852
853     /* Now append .dll before loading */
854
855     if (!(new_name = HeapAlloc( GetProcessHeap(), 0, strlen(libname) + 4 )))
856         return 0;
857     strcpy( new_name, libname );
858     strcat( new_name, ".dll" );
859     handle = NE_LoadModule( new_name, NULL, FALSE, TRUE );
860     HeapFree( GetProcessHeap(), 0, new_name );
861     return handle;
862 }
863
864
865 /**********************************************************************
866  *          MODULE_CallWEP
867  *
868  * Call a DLL's WEP, allowing it to shut down.
869  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
870  */
871 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
872 {
873     FARPROC16 WEP = (FARPROC16)0;
874     WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
875
876     if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
877     if (!WEP)
878     {
879         WARN(module, "module %04x doesn't have a WEP\n", hModule );
880         return FALSE;
881     }
882     return Callbacks->CallWindowsExitProc( WEP, WEP_FREE_DLL );
883 }
884
885
886 /**********************************************************************
887  *          NE_FreeModule
888  *
889  * Implementation of FreeModule16().
890  */
891 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL32 call_wep )
892 {
893     HMODULE16 *hPrevModule;
894     NE_MODULE *pModule;
895     HMODULE16 *pModRef;
896     int i;
897
898     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
899     hModule = pModule->self;
900
901     TRACE( module, "%04x count %d\n", hModule, pModule->count );
902
903     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
904     else pModule->count = 0;
905
906     if (pModule->flags & NE_FFLAGS_BUILTIN)
907         return FALSE;  /* Can't free built-in module */
908
909     if (call_wep)
910     {
911         if (pModule->flags & NE_FFLAGS_LIBMODULE)
912         {
913             TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
914             MODULE_CallWEP( hModule );
915
916             /* Free the objects owned by the DLL module */
917
918             if (pTask && pTask->userhandler)
919                 pTask->userhandler( hModule, USIG_DLL_UNLOAD, 0,
920                                     pTask->hInstance, pTask->hQueue );
921         }
922         else
923             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
924     }
925     
926
927     /* Clear magic number just in case */
928
929     pModule->magic = pModule->self = 0;
930
931       /* Remove it from the linked list */
932
933     hPrevModule = &hFirstModule;
934     while (*hPrevModule && (*hPrevModule != hModule))
935     {
936         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
937     }
938     if (*hPrevModule) *hPrevModule = pModule->next;
939
940     /* Free the referenced modules */
941
942     pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
943     for (i = 0; i < pModule->modref_count; i++, pModRef++)
944     {
945         NE_FreeModule( *pModRef, call_wep );
946     }
947
948     /* Free the module storage */
949
950     GlobalFreeAll( hModule );
951
952     /* Remove module from cache */
953
954     if (pCachedModule == pModule) pCachedModule = NULL;
955     return TRUE;
956 }
957
958
959 /**********************************************************************
960  *          FreeModule16    (KERNEL.46)
961  */
962 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
963 {
964     return NE_FreeModule( hModule, TRUE );
965 }
966
967
968 /***********************************************************************
969  *           FreeLibrary16   (KERNEL.96)
970  */
971 void WINAPI FreeLibrary16( HINSTANCE16 handle )
972 {
973     TRACE(module,"%04x\n", handle );
974     FreeModule16( handle );
975 }
976
977
978 /**********************************************************************
979  *          GetModuleName    (KERNEL.27)
980  */
981 BOOL16 WINAPI GetModuleName( HINSTANCE16 hinst, LPSTR buf, INT16 count )
982 {
983     NE_MODULE *pModule;
984     BYTE *p;
985
986     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
987     p = (BYTE *)pModule + pModule->name_table;
988     if (count > *p) count = *p + 1;
989     if (count > 0)
990     {
991         memcpy( buf, p + 1, count - 1 );
992         buf[count-1] = '\0';
993     }
994     return TRUE;
995 }
996
997
998 /**********************************************************************
999  *          GetModuleUsage    (KERNEL.48)
1000  */
1001 INT16 WINAPI GetModuleUsage( HINSTANCE16 hModule )
1002 {
1003     NE_MODULE *pModule = NE_GetPtr( hModule );
1004     return pModule ? pModule->count : 0;
1005 }
1006
1007
1008 /**********************************************************************
1009  *          GetExpWinVer    (KERNEL.167)
1010  */
1011 WORD WINAPI GetExpWinVer( HMODULE16 hModule )
1012 {
1013     NE_MODULE *pModule = NE_GetPtr( hModule );
1014     return pModule ? pModule->expected_version : 0;
1015 }
1016
1017
1018 /**********************************************************************
1019  *          GetModuleFileName16    (KERNEL.49)
1020  */
1021 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1022                                   INT16 nSize )
1023 {
1024     NE_MODULE *pModule;
1025
1026     if (!hModule) hModule = GetCurrentTask();
1027     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1028     lstrcpyn32A( lpFileName, NE_MODULE_NAME(pModule), nSize );
1029     TRACE(module, "%s\n", lpFileName );
1030     return strlen(lpFileName);
1031 }
1032
1033
1034 /**********************************************************************
1035  *          GetModuleHandle16    (KERNEL.47)
1036  *
1037  * Find a module from a path name.
1038  *
1039  * RETURNS
1040  *   LOWORD:
1041  *      the win16 module handle if found
1042  *      0 if not
1043  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1044  *      Always hFirstModule
1045  */
1046 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1047 {
1048     if (HIWORD(name) == 0)
1049         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1050     return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1051 }
1052
1053 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1054 {
1055     HMODULE16 hModule = hFirstModule;
1056     LPCSTR filename, dotptr, modulepath, modulename;
1057     BYTE len, *name_table;
1058
1059     if (!(filename = strrchr( name, '\\' ))) filename = name;
1060     else filename++;
1061     if ((dotptr = strrchr( filename, '.' )) != NULL)
1062         len = (BYTE)(dotptr - filename);
1063     else len = strlen( filename );
1064
1065     while (hModule)
1066     {
1067         NE_MODULE *pModule = NE_GetPtr( hModule );
1068         if (!pModule) break;
1069         modulepath = NE_MODULE_NAME(pModule);
1070         if (!(modulename = strrchr( modulepath, '\\' )))
1071             modulename = modulepath;
1072         else modulename++;
1073         if (!lstrcmpi32A( modulename, filename )) return hModule;
1074
1075         name_table = (BYTE *)pModule + pModule->name_table;
1076         if ((*name_table == len) && !lstrncmpi32A(filename, name_table+1, len))
1077             return hModule;
1078         hModule = pModule->next;
1079     }
1080     return 0;
1081 }
1082
1083
1084 /**********************************************************************
1085  *          ModuleFirst    (TOOLHELP.59)
1086  */
1087 BOOL16 WINAPI ModuleFirst( MODULEENTRY *lpme )
1088 {
1089     lpme->wNext = hFirstModule;
1090     return ModuleNext( lpme );
1091 }
1092
1093
1094 /**********************************************************************
1095  *          ModuleNext    (TOOLHELP.60)
1096  */
1097 BOOL16 WINAPI ModuleNext( MODULEENTRY *lpme )
1098 {
1099     NE_MODULE *pModule;
1100     char *name;
1101
1102     if (!lpme->wNext) return FALSE;
1103     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1104     name = (char *)pModule + pModule->name_table;
1105     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1106     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1107     lpme->hModule = lpme->wNext;
1108     lpme->wcUsage = pModule->count;
1109     lstrcpyn32A( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1110     lpme->wNext = pModule->next;
1111     return TRUE;
1112 }
1113
1114
1115 /**********************************************************************
1116  *          ModuleFindName    (TOOLHELP.61)
1117  */
1118 BOOL16 WINAPI ModuleFindName( MODULEENTRY *lpme, LPCSTR name )
1119 {
1120     lpme->wNext = GetModuleHandle16( name );
1121     return ModuleNext( lpme );
1122 }
1123
1124
1125 /**********************************************************************
1126  *          ModuleFindHandle    (TOOLHELP.62)
1127  */
1128 BOOL16 WINAPI ModuleFindHandle( MODULEENTRY *lpme, HMODULE16 hModule )
1129 {
1130     hModule = GetExePtr( hModule );
1131     lpme->wNext = hModule;
1132     return ModuleNext( lpme );
1133 }
1134
1135 /***************************************************************************
1136  *              MapHModuleLS                    (KERNEL32.520)
1137  */
1138 HMODULE16 WINAPI MapHModuleLS(HMODULE32 hmod) {
1139         NE_MODULE       *pModule;
1140
1141         if (!hmod)
1142                 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1143         if (!HIWORD(hmod))
1144                 return hmod; /* we already have a 16 bit module handle */
1145         pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1146         while (pModule)  {
1147                 if (pModule->module32 == hmod)
1148                         return pModule->self;
1149                 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1150         }
1151         return 0;
1152 }
1153
1154 /***************************************************************************
1155  *              MapHModuleSL                    (KERNEL32.521)
1156  */
1157 HMODULE32 WINAPI MapHModuleSL(HMODULE16 hmod) {
1158         NE_MODULE       *pModule;
1159
1160         if (!hmod) {
1161                 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1162
1163                 hmod = pTask->hInstance;
1164         }
1165         pModule = (NE_MODULE*)GlobalLock16(hmod);
1166         if (    (pModule->magic!=IMAGE_OS2_SIGNATURE)   ||
1167                 !(pModule->flags & NE_FFLAGS_WIN32)
1168         )
1169                 return 0;
1170         return pModule->module32;
1171 }
1172
1173 /***************************************************************************
1174  *              MapHInstLS                      (KERNEL32.516)
1175  */
1176 REGS_ENTRYPOINT(MapHInstLS) {
1177         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1178 }
1179
1180 /***************************************************************************
1181  *              MapHInstSL                      (KERNEL32.518)
1182  */
1183 REGS_ENTRYPOINT(MapHInstSL) {
1184         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1185 }
1186
1187 /***************************************************************************
1188  *              MapHInstLS_PN                   (KERNEL32.517)
1189  */
1190 REGS_ENTRYPOINT(MapHInstLS_PN) {
1191         if (EAX_reg(context))
1192             EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1193 }
1194
1195 /***************************************************************************
1196  *              MapHInstSL_PN                   (KERNEL32.519)
1197  */
1198 REGS_ENTRYPOINT(MapHInstSL_PN) {
1199         if (EAX_reg(context))
1200             EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1201 }
1202
1203 /***************************************************************************
1204  *              WIN16_MapHInstLS                (KERNEL.472)
1205  */
1206 VOID WINAPI WIN16_MapHInstLS( CONTEXT *context ) {
1207         EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1208 }
1209
1210 /***************************************************************************
1211  *              WIN16_MapHInstSL                (KERNEL.473)
1212  */
1213 VOID WINAPI WIN16_MapHInstSL( CONTEXT *context ) {
1214         EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1215 }