Renamed CallTo16* functions to wine_call_to_16* and export them from
[wine] / loader / ne / module.c
1 /*
2  * NE modules
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <unistd.h>
12 #include <ctype.h>
13 #include "wine/winbase16.h"
14 #include "winerror.h"
15 #include "module.h"
16 #include "neexe.h"
17 #include "toolhelp.h"
18 #include "file.h"
19 #include "ldt.h"
20 #include "heap.h"
21 #include "task.h"
22 #include "global.h"
23 #include "process.h"
24 #include "snoop.h"
25 #include "builtin16.h"
26 #include "stackframe.h"
27 #include "debugtools.h"
28 #include "loadorder.h"
29 #include "elfdll.h"
30 #include "server.h"
31
32 DEFAULT_DEBUG_CHANNEL(module);
33
34 #define hFirstModule (pThhook->hExeHead)
35
36 static NE_MODULE *pCachedModule = 0;  /* Module cached by NE_OpenFile */
37
38 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
39 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
40 static void NE_InitProcess(void) WINE_NORETURN;
41
42 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
43
44 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
45
46 /* ### start build ### */
47 extern WORD CALLBACK NE_CallTo16_word_w(FARPROC16,WORD);
48 /* ### stop build ### */
49
50 /***********************************************************************
51  *           NE_GetPtr
52  */
53 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
54 {
55     return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
56 }
57
58
59 /***********************************************************************
60  *           NE_DumpModule
61  */
62 void NE_DumpModule( HMODULE16 hModule )
63 {
64     int i, ordinal;
65     SEGTABLEENTRY *pSeg;
66     BYTE *pstr;
67     WORD *pword;
68     NE_MODULE *pModule;
69     ET_BUNDLE *bundle;
70     ET_ENTRY *entry;
71
72     if (!(pModule = NE_GetPtr( hModule )))
73     {
74         MESSAGE( "**** %04x is not a module handle\n", hModule );
75         return;
76     }
77
78       /* Dump the module info */
79     DPRINTF( "---\n" );
80     DPRINTF( "Module %04x:\n", hModule );
81     DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
82           pModule->count, pModule->flags,
83           pModule->heap_size, pModule->stack_size );
84     DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
85           pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
86           pModule->seg_count, pModule->modref_count );
87     DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
88           pModule->os_flags, pModule->min_swap_area,
89           pModule->expected_version );
90     if (pModule->flags & NE_FFLAGS_WIN32)
91         DPRINTF( "PE module=%08x\n", pModule->module32 );
92
93       /* Dump the file info */
94     DPRINTF( "---\n" );
95     DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
96
97       /* Dump the segment table */
98     DPRINTF( "---\n" );
99     DPRINTF( "Segment table:\n" );
100     pSeg = NE_SEG_TABLE( pModule );
101     for (i = 0; i < pModule->seg_count; i++, pSeg++)
102         DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
103               i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
104               pSeg->minsize, pSeg->hSeg );
105
106       /* Dump the resource table */
107     DPRINTF( "---\n" );
108     DPRINTF( "Resource table:\n" );
109     if (pModule->res_table)
110     {
111         pword = (WORD *)((BYTE *)pModule + pModule->res_table);
112         DPRINTF( "Alignment: %d\n", *pword++ );
113         while (*pword)
114         {
115             struct resource_typeinfo_s *ptr = (struct resource_typeinfo_s *)pword;
116             struct resource_nameinfo_s *pname = (struct resource_nameinfo_s *)(ptr + 1);
117             DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
118             for (i = 0; i < ptr->count; i++, pname++)
119                 DPRINTF( "offset=%d len=%d id=%04x\n",
120                       pname->offset, pname->length, pname->id );
121             pword = (WORD *)pname;
122         }
123     }
124     else DPRINTF( "None\n" );
125
126       /* Dump the resident name table */
127     DPRINTF( "---\n" );
128     DPRINTF( "Resident-name table:\n" );
129     pstr = (char *)pModule + pModule->name_table;
130     while (*pstr)
131     {
132         DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
133               *(WORD *)(pstr + *pstr + 1) );
134         pstr += *pstr + 1 + sizeof(WORD);
135     }
136
137       /* Dump the module reference table */
138     DPRINTF( "---\n" );
139     DPRINTF( "Module ref table:\n" );
140     if (pModule->modref_table)
141     {
142         pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
143         for (i = 0; i < pModule->modref_count; i++, pword++)
144         {
145             char name[10];
146             GetModuleName16( *pword, name, sizeof(name) );
147             DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
148         }
149     }
150     else DPRINTF( "None\n" );
151
152       /* Dump the entry table */
153     DPRINTF( "---\n" );
154     DPRINTF( "Entry table:\n" );
155     bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);    
156     do {
157         entry = (ET_ENTRY *)((BYTE *)bundle+6);
158         DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
159         ordinal = bundle->first;
160         while (ordinal < bundle->last)
161         {
162             if (entry->type == 0xff)
163                 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
164             else
165                 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
166             entry++;
167     }
168     } while ( (bundle->next)
169            && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
170
171     /* Dump the non-resident names table */
172     DPRINTF( "---\n" );
173     DPRINTF( "Non-resident names table:\n" );
174     if (pModule->nrname_handle)
175     {
176         pstr = (char *)GlobalLock16( pModule->nrname_handle );
177         while (*pstr)
178         {
179             DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
180                    *(WORD *)(pstr + *pstr + 1) );
181             pstr += *pstr + 1 + sizeof(WORD);
182         }
183     }
184     DPRINTF( "\n" );
185 }
186
187
188 /***********************************************************************
189  *           NE_WalkModules
190  *
191  * Walk the module list and print the modules.
192  */
193 void NE_WalkModules(void)
194 {
195     HMODULE16 hModule = hFirstModule;
196     MESSAGE( "Module Flags Name\n" );
197     while (hModule)
198     {
199         NE_MODULE *pModule = NE_GetPtr( hModule );
200         if (!pModule)
201         {
202             MESSAGE( "Bad module %04x in list\n", hModule );
203             return;
204         }
205         MESSAGE( " %04x  %04x  %.*s\n", hModule, pModule->flags,
206                  *((char *)pModule + pModule->name_table),
207                  (char *)pModule + pModule->name_table + 1 );
208         hModule = pModule->next;
209     }
210 }
211
212
213 /**********************************************************************
214  *           NE_RegisterModule
215  */
216 void NE_RegisterModule( NE_MODULE *pModule )
217 {
218     pModule->next = hFirstModule;
219     hFirstModule = pModule->self;
220 }
221
222
223 /***********************************************************************
224  *           NE_GetOrdinal
225  *
226  * Lookup the ordinal for a given name.
227  */
228 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
229 {
230     unsigned char buffer[256], *cpnt;
231     BYTE len;
232     NE_MODULE *pModule;
233
234     if (!(pModule = NE_GetPtr( hModule ))) return 0;
235     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
236
237     TRACE("(%04x,'%s')\n", hModule, name );
238
239       /* First handle names of the form '#xxxx' */
240
241     if (name[0] == '#') return atoi( name + 1 );
242
243       /* Now copy and uppercase the string */
244
245     strcpy( buffer, name );
246     _strupr( buffer );
247     len = strlen( buffer );
248
249       /* First search the resident names */
250
251     cpnt = (char *)pModule + pModule->name_table;
252
253       /* Skip the first entry (module name) */
254     cpnt += *cpnt + 1 + sizeof(WORD);
255     while (*cpnt)
256     {
257         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
258         {
259             TRACE("  Found: ordinal=%d\n",
260                             *(WORD *)(cpnt + *cpnt + 1) );
261             return *(WORD *)(cpnt + *cpnt + 1);
262         }
263         cpnt += *cpnt + 1 + sizeof(WORD);
264     }
265
266       /* Now search the non-resident names table */
267
268     if (!pModule->nrname_handle) return 0;  /* No non-resident table */
269     cpnt = (char *)GlobalLock16( pModule->nrname_handle );
270
271       /* Skip the first entry (module description string) */
272     cpnt += *cpnt + 1 + sizeof(WORD);
273     while (*cpnt)
274     {
275         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
276         {
277             TRACE("  Found: ordinal=%d\n",
278                             *(WORD *)(cpnt + *cpnt + 1) );
279             return *(WORD *)(cpnt + *cpnt + 1);
280         }
281         cpnt += *cpnt + 1 + sizeof(WORD);
282     }
283     return 0;
284 }
285
286
287 /***********************************************************************
288  *           NE_GetEntryPoint   (WPROCS.27)
289  *
290  * Return the entry point for a given ordinal.
291  */
292 FARPROC16 WINAPI WIN16_NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
293 {
294     FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
295     CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
296     return ret;
297 }
298 FARPROC16 WINAPI 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 sel, offset, i;
306
307     ET_ENTRY *entry;
308     ET_BUNDLE *bundle;
309
310     if (!(pModule = NE_GetPtr( hModule ))) return 0;
311     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
312
313     bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
314     while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
315     {
316         if (!(bundle->next))
317             return 0;
318         bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
319     }
320
321     entry = (ET_ENTRY *)((BYTE *)bundle+6);
322     for (i=0; i < (ordinal - bundle->first - 1); i++)
323         entry++;
324
325     sel = entry->segnum;
326     offset = entry->offs;
327
328     if (sel == 0xfe) sel = 0xffff;  /* constant entry */
329     else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
330     if (sel==0xffff)
331         return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
332     if (!snoop)
333         return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
334     else
335         return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset ));
336 }
337
338
339 /***********************************************************************
340  *           NE_SetEntryPoint
341  *
342  * Change the value of an entry point. Use with caution!
343  * It can only change the offset value, not the selector.
344  */
345 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
346 {
347     NE_MODULE *pModule;
348     ET_ENTRY *entry;
349     ET_BUNDLE *bundle;
350     int i;
351
352     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
353     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
354
355     bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
356     while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
357         {
358         bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
359         if (!(bundle->next))
360             return 0;
361     }
362
363     entry = (ET_ENTRY *)((BYTE *)bundle+6);
364     for (i=0; i < (ordinal - bundle->first - 1); i++)
365         entry++;
366
367     entry->offs = offset;
368     return TRUE;
369 }
370
371
372 /***********************************************************************
373  *           NE_OpenFile
374  */
375 HANDLE NE_OpenFile( NE_MODULE *pModule )
376 {
377     char *name;
378
379     static HANDLE cachedfd = -1;
380
381     TRACE("(%p) cache: mod=%p fd=%d\n",
382            pModule, pCachedModule, cachedfd );
383     if (pCachedModule == pModule) return cachedfd;
384     CloseHandle( cachedfd );
385     pCachedModule = pModule;
386     name = NE_MODULE_NAME( pModule );
387     if ((cachedfd = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
388                                    NULL, OPEN_EXISTING, 0, -1 )) == -1)
389         MESSAGE( "Can't open file '%s' for module %04x\n", name, pModule->self );
390     TRACE("opened '%s' -> %d\n",
391                     name, cachedfd );
392     return cachedfd;
393 }
394
395
396 /***********************************************************************
397  *           NE_LoadExeHeader
398  *
399  * We always have to close hFile upon exit.
400  * Otherwise we get file sharing trouble !
401  */
402 static HMODULE16 NE_LoadExeHeader( LPCSTR filename )
403 {
404     IMAGE_DOS_HEADER mz_header;
405     IMAGE_OS2_HEADER ne_header;
406     int size;
407     HMODULE16 hModule;
408     NE_MODULE *pModule;
409     BYTE *pData, *pTempEntryTable;
410     char *buffer, *fastload = NULL;
411     int fastload_offset = 0, fastload_length = 0;
412     ET_ENTRY *entry;
413     ET_BUNDLE *bundle, *oldbundle;
414     HFILE16 hFile;
415     OFSTRUCT ofs;
416
417     /* Open file */
418     if ((hFile = OpenFile16( filename, &ofs, OF_READ )) == HFILE_ERROR16)
419         return (HMODULE16)2;  /* File not found */
420
421   /* Read a block from either the file or the fast-load area. */
422 #define READ(offset,size,buffer) \
423        ((fastload && ((offset) >= fastload_offset) && \
424          ((offset)+(size) <= fastload_offset+fastload_length)) ? \
425         (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
426         (_llseek16( hFile, (offset), SEEK_SET), \
427          _hread16( hFile, (buffer), (size) ) == (size)))
428
429     _llseek16( hFile, 0, SEEK_SET );
430     if ((_hread16(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
431         (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
432     {
433         _lclose16( hFile );
434         return (HMODULE16)11;  /* invalid exe */
435     }
436
437     _llseek16( hFile, mz_header.e_lfanew, SEEK_SET );
438     if (_hread16( hFile, &ne_header, sizeof(ne_header) ) != sizeof(ne_header))
439     {
440         _lclose16( hFile );
441         return (HMODULE16)11;  /* invalid exe */
442     }
443
444     if (ne_header.ne_magic == IMAGE_NT_SIGNATURE)
445     {
446         _lclose16( hFile );
447         return (HMODULE16)21;  /* win32 exe */
448     }
449     if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
450         MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
451         _lclose16( hFile );
452         return (HMODULE16)12;
453     }
454     if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE)
455     {
456         _lclose16( hFile );
457         return (HMODULE16)11;  /* invalid exe */
458     }
459
460     /* We now have a valid NE header */
461
462     size = sizeof(NE_MODULE) +
463              /* segment table */
464            ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
465              /* resource table */
466            ne_header.ne_restab - ne_header.ne_rsrctab +
467              /* resident names table */
468            ne_header.ne_modtab - ne_header.ne_restab +
469              /* module ref table */
470            ne_header.ne_cmod * sizeof(WORD) + 
471              /* imported names table */
472            ne_header.ne_enttab - ne_header.ne_imptab +
473              /* entry table length */
474            ne_header.ne_cbenttab +
475              /* entry table extra conversion space */
476            sizeof(ET_BUNDLE) +
477            2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
478              /* loaded file info */
479            sizeof(OFSTRUCT)-sizeof(ofs.szPathName)+strlen(ofs.szPathName)+1;
480
481     hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
482     if (!hModule) 
483     {
484         _lclose16( hFile );
485         return (HMODULE16)11;  /* invalid exe */
486     }
487
488     FarSetOwner16( hModule, hModule );
489     pModule = (NE_MODULE *)GlobalLock16( hModule );
490     memcpy( pModule, &ne_header, sizeof(ne_header) );
491     pModule->count = 0;
492     /* check *programs* for default minimal stack size */
493     if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
494                 && (pModule->stack_size < 0x1400) )
495                 pModule->stack_size = 0x1400;
496     pModule->module32 = 0;
497     pModule->self = hModule;
498     pModule->self_loading_sel = 0;
499     pData = (BYTE *)(pModule + 1);
500
501     /* Clear internal Wine flags in case they are set in the EXE file */
502
503     pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
504
505     /* Read the fast-load area */
506
507     if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
508     {
509         fastload_offset=ne_header.fastload_offset << ne_header.ne_align;
510         fastload_length=ne_header.fastload_length << ne_header.ne_align;
511         TRACE("Using fast-load area offset=%x len=%d\n",
512                         fastload_offset, fastload_length );
513         if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
514         {
515             _llseek16( hFile, fastload_offset, SEEK_SET);
516             if (_hread16(hFile, fastload, fastload_length) != fastload_length)
517             {
518                 HeapFree( GetProcessHeap(), 0, fastload );
519                 WARN("Error reading fast-load area!\n");
520                 fastload = NULL;
521             }
522         }
523     }
524
525     /* Get the segment table */
526
527     pModule->seg_table = (int)pData - (int)pModule;
528     buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
529                                       sizeof(struct ne_segment_table_entry_s));
530     if (buffer)
531     {
532         int i;
533         struct ne_segment_table_entry_s *pSeg;
534
535         if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
536              ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
537              buffer ))
538         {
539             HeapFree( GetProcessHeap(), 0, buffer );
540             if (fastload)
541                 HeapFree( GetProcessHeap(), 0, fastload );
542             GlobalFree16( hModule );
543             _lclose16( hFile );
544             return (HMODULE16)11;  /* invalid exe */
545         }
546         pSeg = (struct ne_segment_table_entry_s *)buffer;
547         for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
548         {
549             memcpy( pData, pSeg, sizeof(*pSeg) );
550             pData += sizeof(SEGTABLEENTRY);
551         }
552         HeapFree( GetProcessHeap(), 0, buffer );
553     }
554     else
555     {
556         if (fastload)
557             HeapFree( GetProcessHeap(), 0, fastload );
558         GlobalFree16( hModule );
559         _lclose16( hFile );
560         return (HMODULE16)11;  /* invalid exe */
561     }
562
563     /* Get the resource table */
564
565     if (ne_header.ne_rsrctab < ne_header.ne_restab)
566     {
567         pModule->res_table = (int)pData - (int)pModule;
568         if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
569                   ne_header.ne_restab - ne_header.ne_rsrctab,
570                   pData )) 
571         {
572             _lclose16( hFile );
573             return (HMODULE16)11;  /* invalid exe */
574         }
575         pData += ne_header.ne_restab - ne_header.ne_rsrctab;
576         NE_InitResourceHandler( hModule );
577     }
578     else pModule->res_table = 0;  /* No resource table */
579
580     /* Get the resident names table */
581
582     pModule->name_table = (int)pData - (int)pModule;
583     if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
584                ne_header.ne_modtab - ne_header.ne_restab,
585                pData ))
586     {
587         if (fastload)
588             HeapFree( GetProcessHeap(), 0, fastload );
589         GlobalFree16( hModule );
590         _lclose16( hFile );
591         return (HMODULE16)11;  /* invalid exe */
592     }
593     pData += ne_header.ne_modtab - ne_header.ne_restab;
594
595     /* Get the module references table */
596
597     if (ne_header.ne_cmod > 0)
598     {
599         pModule->modref_table = (int)pData - (int)pModule;
600         if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
601                   ne_header.ne_cmod * sizeof(WORD),
602                   pData ))
603         {
604             if (fastload)
605                 HeapFree( GetProcessHeap(), 0, fastload );
606             GlobalFree16( hModule );
607             _lclose16( hFile );
608             return (HMODULE16)11;  /* invalid exe */
609         }
610         pData += ne_header.ne_cmod * sizeof(WORD);
611     }
612     else pModule->modref_table = 0;  /* No module references */
613
614     /* Get the imported names table */
615
616     pModule->import_table = (int)pData - (int)pModule;
617     if (!READ( mz_header.e_lfanew + ne_header.ne_imptab, 
618                ne_header.ne_enttab - ne_header.ne_imptab,
619                pData ))
620     {
621         if (fastload)
622             HeapFree( GetProcessHeap(), 0, fastload );
623         GlobalFree16( hModule );
624         _lclose16( hFile );
625         return (HMODULE16)11;  /* invalid exe */
626     }
627     pData += ne_header.ne_enttab - ne_header.ne_imptab;
628
629     /* Load entry table, convert it to the optimized version used by Windows */
630
631     if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
632     {
633         BYTE nr_entries, type, *s;
634
635         TRACE("Converting entry table.\n");
636     pModule->entry_table = (int)pData - (int)pModule;
637     if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
638                 ne_header.ne_cbenttab, pTempEntryTable ))
639     {
640             HeapFree( GetProcessHeap(), 0, pTempEntryTable );
641             if (fastload)
642                 HeapFree( GetProcessHeap(), 0, fastload );
643         GlobalFree16( hModule );
644         _lclose16( hFile );
645         return (HMODULE16)11;  /* invalid exe */
646     }
647
648         s = pTempEntryTable;
649         TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
650
651         bundle = (ET_BUNDLE *)pData;
652         TRACE("first bundle: %p\n", bundle);
653         memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
654         entry = (ET_ENTRY *)((BYTE *)bundle+6);
655
656         while ((nr_entries = *s++))
657         {
658             if ((type = *s++))
659             {
660                 bundle->last += nr_entries;
661                 if (type == 0xff)
662                 while (nr_entries--)
663                 {
664                     entry->type   = type;
665                     entry->flags  = *s++;
666                     s += 2;
667                     entry->segnum = *s++;
668                     entry->offs   = *(WORD *)s; s += 2;
669                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
670                     entry++;
671                 }
672                 else
673                 while (nr_entries--)
674                 {
675                     entry->type   = type;
676                     entry->flags  = *s++;
677                     entry->segnum = type;
678                     entry->offs   = *(WORD *)s; s += 2;
679                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
680                     entry++;
681                 }
682             }
683             else
684             {
685                 if (bundle->first == bundle->last)
686                 {
687                     bundle->first += nr_entries;
688                     bundle->last += nr_entries;
689                 }
690                 else
691                 {
692                     oldbundle = bundle;
693                     oldbundle->next = ((int)entry - (int)pModule);
694                     bundle = (ET_BUNDLE *)entry;
695                     TRACE("new bundle: %p\n", bundle);
696                     bundle->first = bundle->last =
697                         oldbundle->last + nr_entries;
698                     bundle->next = 0;
699                     (BYTE *)entry += sizeof(ET_BUNDLE);
700                 }
701             }
702         }
703         HeapFree( GetProcessHeap(), 0, pTempEntryTable );
704     }
705     else
706     {
707         if (fastload)
708             HeapFree( GetProcessHeap(), 0, fastload );
709         GlobalFree16( hModule );
710         _lclose16( hFile );
711         return (HMODULE16)11;  /* invalid exe */
712     }
713
714     pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
715              2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
716
717     if ((DWORD)entry > (DWORD)pData)
718        ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
719
720     /* Store the filename information */
721
722     pModule->fileinfo = (int)pData - (int)pModule;
723     size = sizeof(OFSTRUCT)-sizeof(ofs.szPathName)+strlen(ofs.szPathName)+1;
724     ofs.cBytes = size - 1;
725     memcpy( pData, &ofs, size );
726     pData += size;
727
728     /* Free the fast-load area */
729
730 #undef READ
731     if (fastload)
732         HeapFree( GetProcessHeap(), 0, fastload );
733
734     /* Get the non-resident names table */
735
736     if (ne_header.ne_cbnrestab)
737     {
738         pModule->nrname_handle = GLOBAL_Alloc( 0, ne_header.ne_cbnrestab,
739                                                hModule, WINE_LDT_FLAGS_DATA );
740         if (!pModule->nrname_handle)
741         {
742             GlobalFree16( hModule );
743             _lclose16( hFile );
744             return (HMODULE16)11;  /* invalid exe */
745         }
746         buffer = GlobalLock16( pModule->nrname_handle );
747         _llseek16( hFile, ne_header.ne_nrestab, SEEK_SET );
748         if (_hread16( hFile, buffer, ne_header.ne_cbnrestab )
749               != ne_header.ne_cbnrestab)
750         {
751             GlobalFree16( pModule->nrname_handle );
752             GlobalFree16( hModule );
753             _lclose16( hFile );
754             return (HMODULE16)11;  /* invalid exe */
755         }
756     }
757     else pModule->nrname_handle = 0;
758
759     /* Allocate a segment for the implicitly-loaded DLLs */
760
761     if (pModule->modref_count)
762     {
763         pModule->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,
764                                     (pModule->modref_count+1)*sizeof(HMODULE16),
765                                     hModule, WINE_LDT_FLAGS_DATA );
766         if (!pModule->dlls_to_init)
767         {
768             if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
769             GlobalFree16( hModule );
770             _lclose16( hFile );
771             return (HMODULE16)11;  /* invalid exe */
772         }
773     }
774     else pModule->dlls_to_init = 0;
775
776     NE_RegisterModule( pModule );
777     SNOOP16_RegisterDLL(pModule,ofs.szPathName);
778
779     _lclose16( hFile );
780     return hModule;
781 }
782
783
784 /***********************************************************************
785  *           NE_LoadDLLs
786  *
787  * Load all DLLs implicitly linked to a module.
788  */
789 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
790 {
791     int i;
792     WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
793     WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
794
795     for (i = 0; i < pModule->modref_count; i++, pModRef++)
796     {
797         char buffer[260], *p;
798         BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
799         memcpy( buffer, pstr + 1, *pstr );
800         *(buffer + *pstr) = 0; /* terminate it */
801
802         TRACE("Loading '%s'\n", buffer );
803         if (!(*pModRef = GetModuleHandle16( buffer )))
804         {
805             /* If the DLL is not loaded yet, load it and store */
806             /* its handle in the list of DLLs to initialize.   */
807             HMODULE16 hDLL;
808
809             /* Append .DLL to name if no extension present */
810             if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
811                     strcat( buffer, ".DLL" );
812
813             if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
814             {
815                 /* FIXME: cleanup what was done */
816
817                 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
818                      buffer, *((BYTE*)pModule + pModule->name_table),
819                      (char *)pModule + pModule->name_table + 1, hDLL );
820                 return FALSE;
821             }
822             *pModRef = GetExePtr( hDLL );
823             *pDLLs++ = *pModRef;
824         }
825         else  /* Increment the reference count of the DLL */
826         {
827             NE_MODULE *pOldDLL;
828
829             pOldDLL = NE_GetPtr( *pModRef );
830             if (pOldDLL) pOldDLL->count++;
831         }
832     }
833     return TRUE;
834 }
835
836
837 /**********************************************************************
838  *          NE_DoLoadModule
839  *
840  * Load first instance of NE module from file.
841  *
842  * pModule must point to a module structure prepared by NE_LoadExeHeader.
843  * This routine must never be called twice on a module.
844  *
845  */
846 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
847 {
848     /* Allocate the segments for this module */
849
850     if (!NE_CreateAllSegments( pModule ))
851         return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
852
853     /* Load the referenced DLLs */
854
855     if (!NE_LoadDLLs( pModule ))
856         return ERROR_FILE_NOT_FOUND; /* 2 */
857
858     /* Load the segments */
859
860     NE_LoadAllSegments( pModule );
861
862     /* Make sure the usage count is 1 on the first loading of  */
863     /* the module, even if it contains circular DLL references */
864
865     pModule->count = 1;
866
867     return NE_GetInstance( pModule );
868 }
869
870 /**********************************************************************
871  *          NE_LoadModule
872  *
873  * Load first instance of NE module. (Note: caller is responsible for 
874  * ensuring the module isn't already loaded!)
875  *
876  * If the module turns out to be an executable module, only a 
877  * handle to a module stub is returned; this needs to be initialized
878  * by calling NE_DoLoadModule later, in the context of the newly
879  * created process.
880  *
881  * If lib_only is TRUE, however, the module is perforce treated
882  * like a DLL module, even if it is an executable module.
883  * 
884  */
885 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
886 {
887     NE_MODULE *pModule;
888     HMODULE16 hModule;
889     HINSTANCE16 hInstance;
890
891     hModule = NE_LoadExeHeader( name );
892     if (hModule < 32) return hModule;
893
894     pModule = NE_GetPtr( hModule );
895     if ( !pModule ) return hModule;
896
897     if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
898         return hModule;
899
900     hInstance = NE_DoLoadModule( pModule );
901     if ( hInstance < 32 )
902     {
903         /* cleanup ... */
904         NE_FreeModule( hModule, 0 );
905     }
906
907     return hInstance;
908 }
909
910
911 /**********************************************************************
912  *          MODULE_LoadModule16
913  *
914  * Load a NE module in the order of the loadorder specification.
915  * The caller is responsible that the module is not loaded already.
916  *
917  */
918 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
919 {
920         HINSTANCE16 hinst;
921         int i;
922         module_loadorder_t *plo;
923
924         plo = MODULE_GetLoadOrder(libname, FALSE);
925
926         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
927         {
928                 switch(plo->loadorder[i])
929                 {
930                 case MODULE_LOADORDER_DLL:
931                         TRACE("Trying native dll '%s'\n", libname);
932                         hinst = NE_LoadModule(libname, lib_only);
933                         break;
934
935                 case MODULE_LOADORDER_BI:
936                         TRACE("Trying built-in '%s'\n", libname);
937                         hinst = BUILTIN_LoadModule(libname);
938                         break;
939
940                 default:
941                         ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
942                 /* Fall through */
943
944                 case MODULE_LOADORDER_SO:       /* This is not supported for NE modules */
945                 case MODULE_LOADORDER_ELFDLL:   /* This is not supported for NE modules */
946                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
947                         hinst = 2;
948                         break;
949                 }
950
951                 if(hinst >= 32)
952                 {
953                         if(!implicit)
954                         {
955                                 HMODULE16 hModule;
956                                 NE_MODULE *pModule;
957
958                                 hModule = GetModuleHandle16(libname);
959                                 if(!hModule)
960                                 {
961                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
962                                                 libname, hinst);
963                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
964                                 }
965
966                                 pModule = NE_GetPtr(hModule);
967                                 if(!pModule)
968                                 {
969                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
970                                                 libname, hinst);
971                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
972                                 }
973
974                                 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
975
976                                 /*
977                                  * Call initialization routines for all loaded DLLs. Note that
978                                  * when we load implicitly linked DLLs this will be done by InitTask().
979                                  */
980                                 if(pModule->flags & NE_FFLAGS_LIBMODULE)
981                                 {
982                                         NE_InitializeDLLs(hModule);
983                                         NE_DllProcessAttach(hModule);
984                                 }
985                         }
986                         return hinst;
987                 }
988
989                 if(hinst != 2)
990                 {
991                         /* We quit searching when we get another error than 'File not found' */
992                         break;
993                 }
994         }
995         return hinst;   /* The last error that occured */
996 }
997
998
999 /**********************************************************************
1000  *          LoadModule16    (KERNEL.45)
1001  */
1002 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1003 {
1004     TEB *teb = NULL;
1005     BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1006     LOADPARAMS16 *params;
1007     HINSTANCE16 instance = 0;
1008     HMODULE16 hModule;
1009     NE_MODULE *pModule;
1010     HTASK hTask;
1011     TDB *pTask;
1012     LPSTR cmdline;
1013     WORD cmdShow;
1014     HANDLE hThread = -1;
1015     int socket;
1016
1017     /* Load module */
1018
1019     if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1020     {
1021         /* Special case: second instance of an already loaded NE module */
1022
1023         if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1024         if ( pModule->module32 ) return (HINSTANCE16)21;
1025
1026         /* Increment refcount */
1027
1028         pModule->count++;
1029     }
1030     else
1031     {
1032         /* Main case: load first instance of NE module */
1033
1034         if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1035             return hModule;
1036
1037         if ( !(pModule = NE_GetPtr( hModule )) )
1038             return (HINSTANCE16)11;
1039     }
1040
1041     /* If library module, we just retrieve the instance handle */
1042
1043     if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1044         return NE_GetInstance( pModule );
1045
1046     /*
1047      *  At this point, we need to create a new process.
1048      *
1049      *  pModule points either to an already loaded module, whose refcount
1050      *  has already been incremented (to avoid having the module vanish 
1051      *  in the meantime), or else to a stub module which contains only header 
1052      *  information.
1053      */
1054
1055     /* Create the main thread */
1056
1057     SERVER_START_REQ
1058     {
1059         struct new_thread_request *req = server_alloc_req( sizeof(*req), 0 );
1060         req->suspend = 0;
1061         req->inherit = 0;
1062         if (!server_call_fd( REQ_NEW_THREAD, -1, &socket )) hThread = req->handle;
1063     }
1064     SERVER_END_REQ;
1065     if (hThread == -1) return 0;
1066
1067     if (!(teb = THREAD_Create( socket, 0, FALSE ))) goto error;
1068     teb->startup = NE_InitProcess;
1069
1070     /* Create a task for this process */
1071
1072     params = (LOADPARAMS16 *)paramBlock;
1073     cmdShow = ((WORD *)PTR_SEG_TO_LIN(params->showCmd))[1];
1074     cmdline = PTR_SEG_TO_LIN( params->cmdLine );
1075     if (!TASK_Create( pModule, cmdShow, teb, cmdline + 1, *cmdline )) goto error;
1076
1077     hTask = teb->htask16;
1078
1079     if (SYSDEPS_SpawnThread( teb ) == -1) goto error;
1080
1081     /* Post event to start the task */
1082     PostEvent16( hTask );
1083
1084     /* Wait until we get the instance handle */
1085     do
1086     {
1087         DirectedYield16( hTask );
1088         if (!IsTask16( hTask ))  /* thread has died */
1089         {
1090             DWORD exit_code;
1091             WaitForSingleObject( hThread, INFINITE );
1092             GetExitCodeThread( hThread, &exit_code );
1093             CloseHandle( hThread );
1094             return exit_code;
1095         }
1096         if (!(pTask = (TDB *)GlobalLock16( hTask ))) break;
1097         instance = pTask->hInstance;
1098         GlobalUnlock16( hTask );
1099     } while (!instance);
1100
1101     return instance;
1102
1103  error:
1104     /* FIXME: free TEB and task */
1105     close( socket );
1106     CloseHandle( hThread );
1107     return 0;  /* FIXME */
1108 }
1109
1110
1111 /**********************************************************************
1112  *          NE_InitProcess
1113  */
1114 static void NE_InitProcess(void)
1115 {
1116     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1117     NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1118     HINSTANCE16 hInstance, hPrevInstance;
1119     SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1120     WORD sp;
1121
1122     _EnterWin16Lock();
1123
1124     if ( pModule->count > 0 )
1125     {
1126         /* Second instance of an already loaded NE module */
1127         /* Note that the refcount was already incremented by the parent */
1128
1129         hPrevInstance = NE_GetInstance( pModule );
1130
1131         if ( pModule->dgroup )
1132             if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1133                 NE_LoadSegment( pModule, pModule->dgroup );
1134
1135         hInstance = NE_GetInstance( pModule );
1136         TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1137
1138     }
1139     else
1140     {
1141         /* Load first instance of NE module */
1142
1143         pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1144
1145         hInstance = NE_DoLoadModule( pModule );
1146         hPrevInstance = 0;
1147     }
1148
1149     if ( hInstance >= 32 )
1150     {
1151         CONTEXT86 context;
1152
1153         /* Enter instance handles into task struct */
1154
1155         pTask->hInstance = hInstance;
1156         pTask->hPrevInstance = hPrevInstance;
1157
1158         /* Use DGROUP for 16-bit stack */
1159  
1160         if (!(sp = pModule->sp))
1161             sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1162         sp &= ~1;
1163         sp -= sizeof(STACK16FRAME);
1164         pTask->teb->cur_stack = PTR_SEG_OFF_TO_SEGPTR( GlobalHandleToSel16(hInstance), sp );
1165
1166         /* Registers at initialization must be:
1167          * ax   zero
1168          * bx   stack size in bytes
1169          * cx   heap size in bytes
1170          * si   previous app instance
1171          * di   current app instance
1172          * bp   zero
1173          * es   selector to the PSP
1174          * ds   dgroup of the application
1175          * ss   stack selector
1176          * sp   top of the stack
1177          */
1178         memset( &context, 0, sizeof(context) );
1179         context.SegCs  = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1180         context.SegDs  = GlobalHandleToSel16(pTask->hInstance);
1181         context.SegEs  = pTask->hPDB;
1182         context.Eip    = pModule->ip;
1183         context.Ebx    = pModule->stack_size;
1184         context.Ecx    = pModule->heap_size;
1185         context.Edi    = pTask->hInstance;
1186         context.Esi    = pTask->hPrevInstance;
1187
1188         /* Now call 16-bit entry point */
1189
1190         TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1191               context.SegCs, context.Eip, context.SegDs,
1192               SELECTOROF(pTask->teb->cur_stack),
1193               OFFSETOF(pTask->teb->cur_stack) );
1194
1195         wine_call_to_16_regs_short( &context, 0 );
1196         ExitThread( LOWORD(context.Eax) );
1197     }
1198
1199     _LeaveWin16Lock();
1200     ExitThread( hInstance );
1201 }
1202
1203 /***********************************************************************
1204  *           LoadLibrary16   (KERNEL.95)
1205  */
1206 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1207 {
1208     return LoadModule16(libname, (LPVOID)-1 );
1209 }
1210
1211
1212 /**********************************************************************
1213  *          MODULE_CallWEP
1214  *
1215  * Call a DLL's WEP, allowing it to shut down.
1216  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1217  */
1218 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1219 {
1220     FARPROC16 WEP = (FARPROC16)0;
1221     WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
1222
1223     if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
1224     if (!WEP)
1225     {
1226         WARN("module %04x doesn't have a WEP\n", hModule );
1227         return FALSE;
1228     }
1229     return NE_CallTo16_word_w( WEP, WEP_FREE_DLL );
1230 }
1231
1232
1233 /**********************************************************************
1234  *          NE_FreeModule
1235  *
1236  * Implementation of FreeModule16().
1237  */
1238 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1239 {
1240     HMODULE16 *hPrevModule;
1241     NE_MODULE *pModule;
1242     HMODULE16 *pModRef;
1243     int i;
1244
1245     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1246     hModule = pModule->self;
1247
1248     TRACE("%04x count %d\n", hModule, pModule->count );
1249
1250     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1251     else pModule->count = 0;
1252
1253     if (pModule->flags & NE_FFLAGS_BUILTIN)
1254         return FALSE;  /* Can't free built-in module */
1255
1256     if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1257     {
1258         if (pModule->flags & NE_FFLAGS_LIBMODULE)
1259         {
1260             MODULE_CallWEP( hModule );
1261
1262             /* Free the objects owned by the DLL module */
1263             TASK_CallTaskSignalProc( USIG16_DLL_UNLOAD, hModule );
1264             PROCESS_CallUserSignalProc( USIG_DLL_UNLOAD_WIN16, hModule );
1265         }
1266         else
1267             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
1268     }
1269     
1270
1271     /* Clear magic number just in case */
1272
1273     pModule->magic = pModule->self = 0;
1274
1275       /* Remove it from the linked list */
1276
1277     hPrevModule = &hFirstModule;
1278     while (*hPrevModule && (*hPrevModule != hModule))
1279     {
1280         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1281     }
1282     if (*hPrevModule) *hPrevModule = pModule->next;
1283
1284     /* Free the referenced modules */
1285
1286     pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1287     for (i = 0; i < pModule->modref_count; i++, pModRef++)
1288     {
1289         NE_FreeModule( *pModRef, call_wep );
1290     }
1291
1292     /* Free the module storage */
1293
1294     GlobalFreeAll16( hModule );
1295
1296     /* Remove module from cache */
1297
1298     if (pCachedModule == pModule) pCachedModule = NULL;
1299     return TRUE;
1300 }
1301
1302
1303 /**********************************************************************
1304  *          FreeModule16    (KERNEL.46)
1305  */
1306 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1307 {
1308     return NE_FreeModule( hModule, TRUE );
1309 }
1310
1311
1312 /***********************************************************************
1313  *           FreeLibrary16   (KERNEL.96)
1314  */
1315 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1316 {
1317     TRACE("%04x\n", handle );
1318     FreeModule16( handle );
1319 }
1320
1321
1322 /**********************************************************************
1323  *          GetModuleName    (KERNEL.27)
1324  */
1325 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1326 {
1327     NE_MODULE *pModule;
1328     BYTE *p;
1329
1330     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1331     p = (BYTE *)pModule + pModule->name_table;
1332     if (count > *p) count = *p + 1;
1333     if (count > 0)
1334     {
1335         memcpy( buf, p + 1, count - 1 );
1336         buf[count-1] = '\0';
1337     }
1338     return TRUE;
1339 }
1340
1341
1342 /**********************************************************************
1343  *          GetModuleUsage    (KERNEL.48)
1344  */
1345 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1346 {
1347     NE_MODULE *pModule = NE_GetPtr( hModule );
1348     return pModule ? pModule->count : 0;
1349 }
1350
1351
1352 /**********************************************************************
1353  *          GetExpWinVer    (KERNEL.167)
1354  */
1355 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1356 {
1357     NE_MODULE *pModule = NE_GetPtr( hModule );
1358     if ( !pModule ) return 0;
1359
1360     /* 
1361      * For built-in modules, fake the expected version the module should
1362      * have according to the Windows version emulated by Wine
1363      */
1364     if ( !pModule->expected_version )
1365     {
1366         OSVERSIONINFOA versionInfo;
1367         versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1368
1369         if ( GetVersionExA( &versionInfo ) )
1370             pModule->expected_version =   
1371                      (versionInfo.dwMajorVersion & 0xff) << 8
1372                    | (versionInfo.dwMinorVersion & 0xff);
1373     }
1374
1375     return pModule->expected_version;
1376 }
1377
1378
1379 /**********************************************************************
1380  *          GetModuleFileName16    (KERNEL.49)
1381  *
1382  * Comment: see GetModuleFileNameA
1383  *
1384  * Even if invoked by second instance of a program,
1385  * it still returns path of first one.
1386  */
1387 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1388                                   INT16 nSize )
1389 {
1390     NE_MODULE *pModule;
1391
1392     /* Win95 does not query hModule if set to 0 !
1393      * Is this wrong or maybe Win3.1 only ? */
1394     if (!hModule) hModule = GetCurrentTask();
1395
1396     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1397     lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1398     if (pModule->expected_version >= 0x400)
1399         GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1400     TRACE("%04x -> '%s'\n", hModule, lpFileName );
1401     return strlen(lpFileName);
1402 }
1403
1404
1405 /**********************************************************************
1406  *          GetModuleHandle    (KERNEL.47)
1407  *
1408  * Find a module from a module name.
1409  *
1410  * NOTE: The current implementation works the same way the Windows 95 one
1411  *       does. Do not try to 'fix' it, fix the callers.
1412  *       + It does not do ANY extension handling (except that strange .EXE bit)!
1413  *       + It does not care about paths, just about basenames. (same as Windows)
1414  *
1415  * RETURNS
1416  *   LOWORD:
1417  *      the win16 module handle if found
1418  *      0 if not
1419  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1420  *      Always hFirstModule
1421  */
1422 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1423 {
1424     if (HIWORD(name) == 0)
1425         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1426     return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1427 }
1428
1429 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1430 {
1431     HMODULE16   hModule = hFirstModule;
1432     LPSTR       s;
1433     BYTE        len, *name_table;
1434     char        tmpstr[MAX_PATH];
1435     NE_MODULE *pModule;
1436
1437     TRACE("(%s)\n", name);
1438
1439     if (!HIWORD(name))
1440         return GetExePtr(LOWORD(name));
1441
1442     len = strlen(name);
1443     if (!len)
1444         return 0;
1445
1446     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1447
1448     /* If 'name' matches exactly the module name of a module:
1449      * Return its handle.
1450      */
1451     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1452     {
1453         pModule = NE_GetPtr( hModule );
1454         if (!pModule) break;
1455         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1456
1457         name_table = (BYTE *)pModule + pModule->name_table;
1458         if ((*name_table == len) && !strncmp(name, name_table+1, len))
1459             return hModule;
1460     }
1461
1462     /* If uppercased 'name' matches exactly the module name of a module:
1463      * Return its handle
1464      */
1465     for (s = tmpstr; *s; s++)
1466         *s = toupper(*s);
1467
1468     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1469     {
1470         pModule = NE_GetPtr( hModule );
1471         if (!pModule) break;
1472         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1473
1474         name_table = (BYTE *)pModule + pModule->name_table;
1475         /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1476          * but case sensitive! (Unfortunately Winword 6 and subdlls have
1477          * lowercased module names, but try to load uppercase DLLs, so this
1478          * 'i' compare is just a quickfix until the loader handles that
1479          * correctly. -MM 990705
1480          */
1481         if ((*name_table == len) && !strncasecmp(tmpstr, name_table+1, len))
1482             return hModule;
1483     }
1484
1485     /* If the base filename of 'name' matches the base filename of the module
1486      * filename of some module (case-insensitive compare):
1487      * Return its handle.
1488      */
1489
1490     /* basename: search backwards in passed name to \ / or : */
1491     s = tmpstr + strlen(tmpstr);
1492     while (s > tmpstr)
1493     {
1494         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1495                 break;
1496         s--;
1497     }
1498
1499     /* search this in loaded filename list */
1500     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1501     {
1502         char            *loadedfn;
1503         OFSTRUCT        *ofs;
1504
1505         pModule = NE_GetPtr( hModule );
1506         if (!pModule) break;
1507         if (!pModule->fileinfo) continue;
1508         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1509
1510         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1511         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1512         /* basename: search backwards in pathname to \ / or : */
1513         while (loadedfn > (char*)ofs->szPathName)
1514         {
1515             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1516                     break;
1517             loadedfn--;
1518         }
1519         /* case insensitive compare ... */
1520         if (!strcasecmp(loadedfn, s))
1521             return hModule;
1522     }
1523
1524     /* If the extension of 'name' is '.EXE' and the base filename of 'name'
1525      * matches the base filename of the module filename of some 32-bit module:
1526      * Return the corresponding 16-bit dummy module handle. 
1527      */
1528     if (len >= 4 && !strcasecmp(name+len-4, ".EXE"))
1529     {
1530         HMODULE hModule = GetModuleHandleA( name );
1531         if ( hModule )
1532             return MapHModuleLS( hModule );
1533     }
1534
1535     if (!strcmp(tmpstr,"MSDOS"))
1536         return 1;
1537
1538     if (!strcmp(tmpstr,"TIMER"))
1539     {
1540         FIXME("Eh... Should return caller's code segment, expect crash\n");
1541         return 0;
1542     }
1543
1544     return 0;
1545 }
1546
1547 /**********************************************************************
1548  *          NE_GetModuleByFilename
1549  */
1550 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1551 {
1552     HMODULE16   hModule;
1553     LPSTR       s, p;
1554     BYTE        len, *name_table;
1555     char        tmpstr[MAX_PATH];
1556     NE_MODULE *pModule;
1557
1558     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1559
1560     /* If the base filename of 'name' matches the base filename of the module
1561      * filename of some module (case-insensitive compare):
1562      * Return its handle.
1563      */
1564
1565     /* basename: search backwards in passed name to \ / or : */
1566     s = tmpstr + strlen(tmpstr);
1567     while (s > tmpstr)
1568     {
1569         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1570                 break;
1571         s--;
1572     }
1573
1574     /* search this in loaded filename list */
1575     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1576     {
1577         char            *loadedfn;
1578         OFSTRUCT        *ofs;
1579
1580         pModule = NE_GetPtr( hModule );
1581         if (!pModule) break;
1582         if (!pModule->fileinfo) continue;
1583         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1584
1585         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1586         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1587         /* basename: search backwards in pathname to \ / or : */
1588         while (loadedfn > (char*)ofs->szPathName)
1589         {
1590             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1591                     break;
1592             loadedfn--;
1593         }
1594         /* case insensitive compare ... */
1595         if (!strcasecmp(loadedfn, s))
1596             return hModule;
1597     }
1598
1599     /* If basename (without ext) matches the module name of a module:
1600      * Return its handle.
1601      */
1602
1603     if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1604     len = strlen(s);
1605
1606     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1607     {
1608         pModule = NE_GetPtr( hModule );
1609         if (!pModule) break;
1610         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1611
1612         name_table = (BYTE *)pModule + pModule->name_table;
1613         if ((*name_table == len) && !strncasecmp(s, name_table+1, len))
1614             return hModule;
1615     }
1616
1617     return 0;
1618 }
1619
1620 /**********************************************************************
1621  *          ModuleFirst    (TOOLHELP.59)
1622  */
1623 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1624 {
1625     lpme->wNext = hFirstModule;
1626     return ModuleNext16( lpme );
1627 }
1628
1629
1630 /**********************************************************************
1631  *          ModuleNext    (TOOLHELP.60)
1632  */
1633 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1634 {
1635     NE_MODULE *pModule;
1636     char *name;
1637
1638     if (!lpme->wNext) return FALSE;
1639     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1640     name = (char *)pModule + pModule->name_table;
1641     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1642     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1643     lpme->hModule = lpme->wNext;
1644     lpme->wcUsage = pModule->count;
1645     lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1646     lpme->wNext = pModule->next;
1647     return TRUE;
1648 }
1649
1650
1651 /**********************************************************************
1652  *          ModuleFindName    (TOOLHELP.61)
1653  */
1654 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1655 {
1656     lpme->wNext = GetModuleHandle16( name );
1657     return ModuleNext16( lpme );
1658 }
1659
1660
1661 /**********************************************************************
1662  *          ModuleFindHandle    (TOOLHELP.62)
1663  */
1664 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1665 {
1666     hModule = GetExePtr( hModule );
1667     lpme->wNext = hModule;
1668     return ModuleNext16( lpme );
1669 }
1670
1671
1672 /***************************************************************************
1673  *          IsRomModule16    (KERNEL.323)
1674  */
1675 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1676 {
1677     return FALSE;
1678 }
1679
1680 /***************************************************************************
1681  *          IsRomFile16    (KERNEL.326)
1682  */
1683 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1684 {
1685     return FALSE;
1686 }
1687
1688 /***************************************************************************
1689  *              MapHModuleLS                    (KERNEL32.520)
1690  */
1691 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod) {
1692         NE_MODULE       *pModule;
1693
1694         if (!hmod)
1695                 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1696         if (!HIWORD(hmod))
1697                 return hmod; /* we already have a 16 bit module handle */
1698         pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1699         while (pModule)  {
1700                 if (pModule->module32 == hmod)
1701                         return pModule->self;
1702                 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1703         }
1704         return 0;
1705 }
1706
1707 /***************************************************************************
1708  *              MapHModuleSL                    (KERNEL32.521)
1709  */
1710 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod) {
1711         NE_MODULE       *pModule;
1712
1713         if (!hmod) {
1714                 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1715
1716                 hmod = pTask->hModule;
1717         }
1718         pModule = (NE_MODULE*)GlobalLock16(hmod);
1719         if (    (pModule->magic!=IMAGE_OS2_SIGNATURE)   ||
1720                 !(pModule->flags & NE_FFLAGS_WIN32)
1721         )
1722                 return 0;
1723         return pModule->module32;
1724 }
1725
1726 /***************************************************************************
1727  *              MapHInstLS                      (KERNEL32.516)(KERNEL.472)
1728  */
1729 void WINAPI MapHInstLS( CONTEXT86 *context )
1730 {
1731     context->Eax = MapHModuleLS(context->Eax);
1732 }
1733
1734 /***************************************************************************
1735  *              MapHInstSL                      (KERNEL32.518)(KERNEL.473)
1736  */
1737 void WINAPI MapHInstSL( CONTEXT86 *context )
1738 {
1739     context->Eax = MapHModuleSL(context->Eax);
1740 }
1741
1742 /***************************************************************************
1743  *              MapHInstLS_PN                   (KERNEL32.517)
1744  */
1745 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
1746 {
1747     if (context->Eax) context->Eax = MapHModuleLS(context->Eax);
1748 }
1749
1750 /***************************************************************************
1751  *              MapHInstSL_PN                   (KERNEL32.519)
1752  */
1753 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
1754 {
1755     if (context->Eax) context->Eax = MapHModuleSL(context->Eax);
1756 }
1757