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