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