ok() does not support '%S'. Store the Ansi version, convert to Unicode
[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 "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=%p\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' -> %p\n", name, handle);
436     return handle;
437 }
438
439
440 /* wrapper for SetFilePointer and ReadFile */
441 static BOOL read_data( HANDLE handle, LONG offset, void *buffer, DWORD size )
442 {
443     DWORD result;
444
445     if (SetFilePointer( handle, offset, NULL, SEEK_SET ) == INVALID_SET_FILE_POINTER) return FALSE;
446     if (!ReadFile( handle, buffer, size, &result, NULL )) return FALSE;
447     return (result == size);
448 }
449
450 /***********************************************************************
451  *           NE_LoadExeHeader
452  */
453 static HMODULE16 NE_LoadExeHeader( HANDLE handle, LPCSTR path )
454 {
455     IMAGE_DOS_HEADER mz_header;
456     IMAGE_OS2_HEADER ne_header;
457     int size;
458     HMODULE16 hModule;
459     NE_MODULE *pModule;
460     BYTE *pData, *pTempEntryTable;
461     char *buffer, *fastload = NULL;
462     int fastload_offset = 0, fastload_length = 0;
463     ET_ENTRY *entry;
464     ET_BUNDLE *bundle, *oldbundle;
465     OFSTRUCT *ofs;
466
467   /* Read a block from either the file or the fast-load area. */
468 #define READ(offset,size,buffer) \
469        ((fastload && ((offset) >= fastload_offset) && \
470          ((offset)+(size) <= fastload_offset+fastload_length)) ? \
471         (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
472          read_data( handle, (offset), (buffer), (size)))
473
474     if (!read_data( handle, 0, &mz_header, sizeof(mz_header)) ||
475         (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
476         return (HMODULE16)11;  /* invalid exe */
477
478     if (!read_data( handle, mz_header.e_lfanew, &ne_header, sizeof(ne_header) ))
479         return (HMODULE16)11;  /* invalid exe */
480
481     if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21;  /* win32 exe */
482     if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
483         MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
484         return (HMODULE16)12;
485     }
486     if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11;  /* invalid exe */
487
488     /* We now have a valid NE header */
489
490     size = sizeof(NE_MODULE) +
491              /* segment table */
492            ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
493              /* resource table */
494            ne_header.ne_restab - ne_header.ne_rsrctab +
495              /* resident names table */
496            ne_header.ne_modtab - ne_header.ne_restab +
497              /* module ref table */
498            ne_header.ne_cmod * sizeof(WORD) +
499              /* imported names table */
500            ne_header.ne_enttab - ne_header.ne_imptab +
501              /* entry table length */
502            ne_header.ne_cbenttab +
503              /* entry table extra conversion space */
504            sizeof(ET_BUNDLE) +
505            2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
506              /* loaded file info */
507            sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
508
509     hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
510     if (!hModule) return (HMODULE16)11;  /* invalid exe */
511
512     FarSetOwner16( hModule, hModule );
513     pModule = (NE_MODULE *)GlobalLock16( hModule );
514     memcpy( pModule, &ne_header, sizeof(ne_header) );
515     pModule->count = 0;
516     /* check *programs* for default minimal stack size */
517     if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
518                 && (pModule->stack_size < 0x1400) )
519                 pModule->stack_size = 0x1400;
520     pModule->module32 = 0;
521     pModule->self = hModule;
522     pModule->self_loading_sel = 0;
523     pData = (BYTE *)(pModule + 1);
524
525     /* Clear internal Wine flags in case they are set in the EXE file */
526
527     pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
528
529     /* Read the fast-load area */
530
531     if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
532     {
533         fastload_offset=ne_header.ne_pretthunks << ne_header.ne_align;
534         fastload_length=ne_header.ne_psegrefbytes << ne_header.ne_align;
535         TRACE("Using fast-load area offset=%x len=%d\n",
536                         fastload_offset, fastload_length );
537         if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
538         {
539             if (!read_data( handle, fastload_offset, fastload, fastload_length))
540             {
541                 HeapFree( GetProcessHeap(), 0, fastload );
542                 WARN("Error reading fast-load area!\n");
543                 fastload = NULL;
544             }
545         }
546     }
547
548     /* Get the segment table */
549
550     pModule->seg_table = pData - (BYTE *)pModule;
551     buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
552                                       sizeof(struct ne_segment_table_entry_s));
553     if (buffer)
554     {
555         int i;
556         struct ne_segment_table_entry_s *pSeg;
557
558         if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
559              ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
560              buffer ))
561         {
562             HeapFree( GetProcessHeap(), 0, buffer );
563             if (fastload)
564                 HeapFree( GetProcessHeap(), 0, fastload );
565             GlobalFree16( hModule );
566             return (HMODULE16)11;  /* invalid exe */
567         }
568         pSeg = (struct ne_segment_table_entry_s *)buffer;
569         for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
570         {
571             memcpy( pData, pSeg, sizeof(*pSeg) );
572             pData += sizeof(SEGTABLEENTRY);
573         }
574         HeapFree( GetProcessHeap(), 0, buffer );
575     }
576     else
577     {
578         if (fastload)
579             HeapFree( GetProcessHeap(), 0, fastload );
580         GlobalFree16( hModule );
581         return (HMODULE16)11;  /* invalid exe */
582     }
583
584     /* Get the resource table */
585
586     if (ne_header.ne_rsrctab < ne_header.ne_restab)
587     {
588         pModule->res_table = pData - (BYTE *)pModule;
589         if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
590                   ne_header.ne_restab - ne_header.ne_rsrctab,
591                   pData ))
592             return (HMODULE16)11;  /* invalid exe */
593         pData += ne_header.ne_restab - ne_header.ne_rsrctab;
594         NE_InitResourceHandler( hModule );
595     }
596     else pModule->res_table = 0;  /* No resource table */
597
598     /* Get the resident names table */
599
600     pModule->name_table = pData - (BYTE *)pModule;
601     if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
602                ne_header.ne_modtab - ne_header.ne_restab,
603                pData ))
604     {
605         if (fastload)
606             HeapFree( GetProcessHeap(), 0, fastload );
607         GlobalFree16( hModule );
608         return (HMODULE16)11;  /* invalid exe */
609     }
610     pData += ne_header.ne_modtab - ne_header.ne_restab;
611
612     /* Get the module references table */
613
614     if (ne_header.ne_cmod > 0)
615     {
616         pModule->modref_table = pData - (BYTE *)pModule;
617         if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
618                   ne_header.ne_cmod * sizeof(WORD),
619                   pData ))
620         {
621             if (fastload)
622                 HeapFree( GetProcessHeap(), 0, fastload );
623             GlobalFree16( hModule );
624             return (HMODULE16)11;  /* invalid exe */
625         }
626         pData += ne_header.ne_cmod * sizeof(WORD);
627     }
628     else pModule->modref_table = 0;  /* No module references */
629
630     /* Get the imported names table */
631
632     pModule->import_table = pData - (BYTE *)pModule;
633     if (!READ( mz_header.e_lfanew + ne_header.ne_imptab,
634                ne_header.ne_enttab - ne_header.ne_imptab,
635                pData ))
636     {
637         if (fastload)
638             HeapFree( GetProcessHeap(), 0, fastload );
639         GlobalFree16( hModule );
640         return (HMODULE16)11;  /* invalid exe */
641     }
642     pData += ne_header.ne_enttab - ne_header.ne_imptab;
643
644     /* Load entry table, convert it to the optimized version used by Windows */
645
646     if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
647     {
648         BYTE nr_entries, type, *s;
649
650         TRACE("Converting entry table.\n");
651     pModule->entry_table = pData - (BYTE *)pModule;
652     if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
653                 ne_header.ne_cbenttab, pTempEntryTable ))
654     {
655             HeapFree( GetProcessHeap(), 0, pTempEntryTable );
656             if (fastload)
657                 HeapFree( GetProcessHeap(), 0, fastload );
658         GlobalFree16( hModule );
659         return (HMODULE16)11;  /* invalid exe */
660     }
661
662         s = pTempEntryTable;
663         TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
664
665         bundle = (ET_BUNDLE *)pData;
666         TRACE("first bundle: %p\n", bundle);
667         memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
668         entry = (ET_ENTRY *)((BYTE *)bundle+6);
669
670         while ((nr_entries = *s++))
671         {
672             if ((type = *s++))
673             {
674                 bundle->last += nr_entries;
675                 if (type == 0xff)
676                 while (nr_entries--)
677                 {
678                     entry->type   = type;
679                     entry->flags  = *s++;
680                     s += 2;
681                     entry->segnum = *s++;
682                     entry->offs   = *(WORD *)s; s += 2;
683                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
684                     entry++;
685                 }
686                 else
687                 while (nr_entries--)
688                 {
689                     entry->type   = type;
690                     entry->flags  = *s++;
691                     entry->segnum = type;
692                     entry->offs   = *(WORD *)s; s += 2;
693                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
694                     entry++;
695                 }
696             }
697             else
698             {
699                 if (bundle->first == bundle->last)
700                 {
701                     bundle->first += nr_entries;
702                     bundle->last += nr_entries;
703                 }
704                 else
705                 {
706                     oldbundle = bundle;
707                     oldbundle->next = ((int)entry - (int)pModule);
708                     bundle = (ET_BUNDLE *)entry;
709                     TRACE("new bundle: %p\n", bundle);
710                     bundle->first = bundle->last =
711                         oldbundle->last + nr_entries;
712                     bundle->next = 0;
713                     (BYTE *)entry += sizeof(ET_BUNDLE);
714                 }
715             }
716         }
717         HeapFree( GetProcessHeap(), 0, pTempEntryTable );
718     }
719     else
720     {
721         if (fastload)
722             HeapFree( GetProcessHeap(), 0, fastload );
723         GlobalFree16( hModule );
724         return (HMODULE16)11;  /* invalid exe */
725     }
726
727     pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
728              2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
729
730     if ((DWORD)entry > (DWORD)pData)
731        ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
732
733     /* Store the filename information */
734
735     pModule->fileinfo = pData - (BYTE *)pModule;
736     size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
737     ofs = (OFSTRUCT *)pData;
738     ofs->cBytes = size - 1;
739     ofs->fFixedDisk = 1;
740     strcpy( ofs->szPathName, path );
741     pData += size;
742
743     /* Free the fast-load area */
744
745 #undef READ
746     if (fastload)
747         HeapFree( GetProcessHeap(), 0, fastload );
748
749     /* Get the non-resident names table */
750
751     if (ne_header.ne_cbnrestab)
752     {
753         pModule->nrname_handle = GlobalAlloc16( 0, ne_header.ne_cbnrestab );
754         if (!pModule->nrname_handle)
755         {
756             GlobalFree16( hModule );
757             return (HMODULE16)11;  /* invalid exe */
758         }
759         FarSetOwner16( pModule->nrname_handle, hModule );
760         buffer = GlobalLock16( pModule->nrname_handle );
761         if (!read_data( handle, ne_header.ne_nrestab, buffer, ne_header.ne_cbnrestab ))
762         {
763             GlobalFree16( pModule->nrname_handle );
764             GlobalFree16( hModule );
765             return (HMODULE16)11;  /* invalid exe */
766         }
767     }
768     else pModule->nrname_handle = 0;
769
770     /* Allocate a segment for the implicitly-loaded DLLs */
771
772     if (pModule->modref_count)
773     {
774         pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
775                                                (pModule->modref_count+1)*sizeof(HMODULE16) );
776         if (!pModule->dlls_to_init)
777         {
778             if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
779             GlobalFree16( hModule );
780             return (HMODULE16)11;  /* invalid exe */
781         }
782         FarSetOwner16( pModule->dlls_to_init, hModule );
783     }
784     else pModule->dlls_to_init = 0;
785
786     NE_RegisterModule( pModule );
787     SNOOP16_RegisterDLL(pModule,path);
788     return hModule;
789 }
790
791
792 /***********************************************************************
793  *           NE_LoadDLLs
794  *
795  * Load all DLLs implicitly linked to a module.
796  */
797 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
798 {
799     int i;
800     WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
801     WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
802
803     for (i = 0; i < pModule->modref_count; i++, pModRef++)
804     {
805         char buffer[260], *p;
806         BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
807         memcpy( buffer, pstr + 1, *pstr );
808         *(buffer + *pstr) = 0; /* terminate it */
809
810         TRACE("Loading '%s'\n", buffer );
811         if (!(*pModRef = GetModuleHandle16( buffer )))
812         {
813             /* If the DLL is not loaded yet, load it and store */
814             /* its handle in the list of DLLs to initialize.   */
815             HMODULE16 hDLL;
816
817             /* Append .DLL to name if no extension present */
818             if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
819                     strcat( buffer, ".DLL" );
820
821             if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
822             {
823                 /* FIXME: cleanup what was done */
824
825                 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
826                      buffer, *((BYTE*)pModule + pModule->name_table),
827                      (char *)pModule + pModule->name_table + 1, hDLL );
828                 return FALSE;
829             }
830             *pModRef = GetExePtr( hDLL );
831             *pDLLs++ = *pModRef;
832         }
833         else  /* Increment the reference count of the DLL */
834         {
835             NE_MODULE *pOldDLL;
836
837             pOldDLL = NE_GetPtr( *pModRef );
838             if (pOldDLL) pOldDLL->count++;
839         }
840     }
841     return TRUE;
842 }
843
844
845 /**********************************************************************
846  *          NE_DoLoadModule
847  *
848  * Load first instance of NE module from file.
849  *
850  * pModule must point to a module structure prepared by NE_LoadExeHeader.
851  * This routine must never be called twice on a module.
852  *
853  */
854 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
855 {
856     /* Allocate the segments for this module */
857
858     if (!NE_CreateAllSegments( pModule ))
859         return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
860
861     /* Load the referenced DLLs */
862
863     if (!NE_LoadDLLs( pModule ))
864         return ERROR_FILE_NOT_FOUND; /* 2 */
865
866     /* Load the segments */
867
868     NE_LoadAllSegments( pModule );
869
870     /* Make sure the usage count is 1 on the first loading of  */
871     /* the module, even if it contains circular DLL references */
872
873     pModule->count = 1;
874
875     return NE_GetInstance( pModule );
876 }
877
878 /**********************************************************************
879  *          NE_LoadModule
880  *
881  * Load first instance of NE module. (Note: caller is responsible for
882  * ensuring the module isn't already loaded!)
883  *
884  * If the module turns out to be an executable module, only a
885  * handle to a module stub is returned; this needs to be initialized
886  * by calling NE_DoLoadModule later, in the context of the newly
887  * created process.
888  *
889  * If lib_only is TRUE, however, the module is perforce treated
890  * like a DLL module, even if it is an executable module.
891  *
892  */
893 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
894 {
895     NE_MODULE *pModule;
896     HMODULE16 hModule;
897     HINSTANCE16 hInstance;
898     HFILE16 hFile;
899     OFSTRUCT ofs;
900
901     /* Open file */
902     if ((hFile = OpenFile16( name, &ofs, OF_READ )) == HFILE_ERROR16)
903         return (HMODULE16)2;  /* File not found */
904
905     hModule = NE_LoadExeHeader( DosFileHandleToWin32Handle(hFile), ofs.szPathName );
906     _lclose16( hFile );
907     if (hModule < 32) return hModule;
908
909     pModule = NE_GetPtr( hModule );
910     if ( !pModule ) return hModule;
911
912     if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
913         return hModule;
914
915     hInstance = NE_DoLoadModule( pModule );
916     if ( hInstance < 32 )
917     {
918         /* cleanup ... */
919         NE_FreeModule( hModule, 0 );
920     }
921
922     return hInstance;
923 }
924
925
926 /**********************************************************************
927  *          MODULE_LoadModule16
928  *
929  * Load a NE module in the order of the loadorder specification.
930  * The caller is responsible that the module is not loaded already.
931  *
932  */
933 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
934 {
935         HINSTANCE16 hinst = 2;
936         enum loadorder_type loadorder[LOADORDER_NTYPES];
937         int i;
938         const char *filetype = "";
939
940         MODULE_GetLoadOrder(loadorder, libname, FALSE);
941
942         for(i = 0; i < LOADORDER_NTYPES; i++)
943         {
944             if (loadorder[i] == LOADORDER_INVALID) break;
945
946                 switch(loadorder[i])
947                 {
948                 case LOADORDER_DLL:
949                         TRACE("Trying native dll '%s'\n", libname);
950                         hinst = NE_LoadModule(libname, lib_only);
951                         filetype = "native";
952                         break;
953
954                 case LOADORDER_BI:
955                         TRACE("Trying built-in '%s'\n", libname);
956                         hinst = BUILTIN_LoadModule(libname);
957                         filetype = "builtin";
958                         break;
959
960                 case LOADORDER_SO: /* This is not supported for NE modules */
961                 default:
962                         hinst = 2;
963                         break;
964                 }
965
966                 if(hinst >= 32)
967                 {
968                         TRACE_(loaddll)("Loaded module '%s' : %s\n", libname, filetype);
969                         if(!implicit)
970                         {
971                                 HMODULE16 hModule;
972                                 NE_MODULE *pModule;
973
974                                 hModule = GetModuleHandle16(libname);
975                                 if(!hModule)
976                                 {
977                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
978                                                 libname, hinst);
979                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
980                                 }
981
982                                 pModule = NE_GetPtr(hModule);
983                                 if(!pModule)
984                                 {
985                                         ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
986                                                 libname, hinst);
987                                         return 6;       /* ERROR_INVALID_HANDLE seems most appropriate */
988                                 }
989
990                                 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
991
992                                 /*
993                                  * Call initialization routines for all loaded DLLs. Note that
994                                  * when we load implicitly linked DLLs this will be done by InitTask().
995                                  */
996                                 if(pModule->flags & NE_FFLAGS_LIBMODULE)
997                                 {
998                                         NE_InitializeDLLs(hModule);
999                                         NE_DllProcessAttach(hModule);
1000                                 }
1001                         }
1002                         return hinst;
1003                 }
1004
1005                 if(hinst != 2)
1006                 {
1007                         /* We quit searching when we get another error than 'File not found' */
1008                         break;
1009                 }
1010         }
1011         return hinst;   /* The last error that occured */
1012 }
1013
1014
1015 /**********************************************************************
1016  *          NE_CreateThread
1017  *
1018  * Create the thread for a 16-bit module.
1019  */
1020 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1021 {
1022     HANDLE hThread;
1023     TDB *pTask;
1024     HTASK16 hTask;
1025     HINSTANCE16 instance = 0;
1026
1027     if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1028         return 0;
1029
1030     /* Post event to start the task */
1031     PostEvent16( hTask );
1032
1033     /* Wait until we get the instance handle */
1034     do
1035     {
1036         DirectedYield16( hTask );
1037         if (!IsTask16( hTask ))  /* thread has died */
1038         {
1039             DWORD exit_code;
1040             WaitForSingleObject( hThread, INFINITE );
1041             GetExitCodeThread( hThread, &exit_code );
1042             CloseHandle( hThread );
1043             return exit_code;
1044         }
1045         if (!(pTask = TASK_GetPtr( hTask ))) break;
1046         instance = pTask->hInstance;
1047         GlobalUnlock16( hTask );
1048     } while (!instance);
1049
1050     CloseHandle( hThread );
1051     return instance;
1052 }
1053
1054
1055 /**********************************************************************
1056  *          LoadModule      (KERNEL.45)
1057  */
1058 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1059 {
1060     BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1061     LOADPARAMS16 *params;
1062     HMODULE16 hModule;
1063     NE_MODULE *pModule;
1064     LPSTR cmdline;
1065     WORD cmdShow;
1066
1067     /* Load module */
1068
1069     if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1070     {
1071         /* Special case: second instance of an already loaded NE module */
1072
1073         if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1074         if ( pModule->module32 ) return (HINSTANCE16)21;
1075
1076         /* Increment refcount */
1077
1078         pModule->count++;
1079     }
1080     else
1081     {
1082         /* Main case: load first instance of NE module */
1083
1084         if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1085             return hModule;
1086
1087         if ( !(pModule = NE_GetPtr( hModule )) )
1088             return (HINSTANCE16)11;
1089     }
1090
1091     /* If library module, we just retrieve the instance handle */
1092
1093     if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1094         return NE_GetInstance( pModule );
1095
1096     /*
1097      *  At this point, we need to create a new process.
1098      *
1099      *  pModule points either to an already loaded module, whose refcount
1100      *  has already been incremented (to avoid having the module vanish
1101      *  in the meantime), or else to a stub module which contains only header
1102      *  information.
1103      */
1104     params = (LOADPARAMS16 *)paramBlock;
1105     cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1106     cmdline = MapSL( params->cmdLine );
1107     return NE_CreateThread( pModule, cmdShow, cmdline );
1108 }
1109
1110
1111 /**********************************************************************
1112  *          NE_StartMain
1113  *
1114  * Start the main NE task.
1115  */
1116 HINSTANCE16 NE_StartMain( LPCSTR name, HANDLE file )
1117 {
1118     STARTUPINFOA info;
1119     HMODULE16 hModule;
1120     NE_MODULE *pModule;
1121     INT len;
1122     LPSTR pCmdLine, cmdline = GetCommandLineA();
1123
1124     if ((hModule = NE_LoadExeHeader( file, name )) < 32) return hModule;
1125
1126     if (!(pModule = NE_GetPtr( hModule ))) return (HINSTANCE16)11;
1127     if (pModule->flags & NE_FFLAGS_LIBMODULE)
1128     {
1129         MESSAGE( "%s is not a valid Win16 executable\n", name );
1130         ExitProcess( ERROR_BAD_EXE_FORMAT );
1131     }
1132
1133     while (*cmdline && *cmdline != ' ') cmdline++;
1134     if (*cmdline) cmdline++;
1135     len = strlen(cmdline);
1136     pCmdLine = HeapAlloc(GetProcessHeap(), 0, len+2);
1137     if (pCmdLine)
1138     {
1139         strcpy(pCmdLine+1, cmdline);
1140         *pCmdLine = len;
1141     }
1142     GetStartupInfoA( &info );
1143     if (!(info.dwFlags & STARTF_USESHOWWINDOW)) info.wShowWindow = 1;
1144
1145     return NE_CreateThread( pModule, info.wShowWindow, pCmdLine );
1146 }
1147
1148
1149 /**********************************************************************
1150  *          NE_StartTask
1151  *
1152  * Startup code for a new 16-bit task.
1153  */
1154 DWORD NE_StartTask(void)
1155 {
1156     TDB *pTask = TASK_GetCurrent();
1157     NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1158     HINSTANCE16 hInstance, hPrevInstance;
1159     SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1160     WORD sp;
1161
1162     if ( pModule->count > 0 )
1163     {
1164         /* Second instance of an already loaded NE module */
1165         /* Note that the refcount was already incremented by the parent */
1166
1167         hPrevInstance = NE_GetInstance( pModule );
1168
1169         if ( pModule->dgroup )
1170             if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1171                 NE_LoadSegment( pModule, pModule->dgroup );
1172
1173         hInstance = NE_GetInstance( pModule );
1174         TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1175
1176     }
1177     else
1178     {
1179         /* Load first instance of NE module */
1180
1181         pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1182
1183         hInstance = NE_DoLoadModule( pModule );
1184         hPrevInstance = 0;
1185     }
1186
1187     if ( hInstance >= 32 )
1188     {
1189         CONTEXT86 context;
1190
1191         /* Enter instance handles into task struct */
1192
1193         pTask->hInstance = hInstance;
1194         pTask->hPrevInstance = hPrevInstance;
1195
1196         /* Use DGROUP for 16-bit stack */
1197
1198         if (!(sp = pModule->sp))
1199             sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1200         sp &= ~1;
1201         sp -= sizeof(STACK16FRAME);
1202         pTask->teb->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1203
1204         /* Registers at initialization must be:
1205          * ax   zero
1206          * bx   stack size in bytes
1207          * cx   heap size in bytes
1208          * si   previous app instance
1209          * di   current app instance
1210          * bp   zero
1211          * es   selector to the PSP
1212          * ds   dgroup of the application
1213          * ss   stack selector
1214          * sp   top of the stack
1215          */
1216         memset( &context, 0, sizeof(context) );
1217         context.SegCs  = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1218         context.SegDs  = GlobalHandleToSel16(pTask->hInstance);
1219         context.SegEs  = pTask->hPDB;
1220         context.Eip    = pModule->ip;
1221         context.Ebx    = pModule->stack_size;
1222         context.Ecx    = pModule->heap_size;
1223         context.Edi    = pTask->hInstance;
1224         context.Esi    = pTask->hPrevInstance;
1225
1226         /* Now call 16-bit entry point */
1227
1228         TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1229               context.SegCs, context.Eip, context.SegDs,
1230               SELECTOROF(pTask->teb->cur_stack),
1231               OFFSETOF(pTask->teb->cur_stack) );
1232
1233         wine_call_to_16_regs_short( &context, 0 );
1234         ExitThread( LOWORD(context.Eax) );
1235     }
1236     return hInstance;  /* error code */
1237 }
1238
1239 /***********************************************************************
1240  *           LoadLibrary     (KERNEL.95)
1241  *           LoadLibrary16   (KERNEL32.35)
1242  */
1243 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1244 {
1245     return LoadModule16(libname, (LPVOID)-1 );
1246 }
1247
1248
1249 /**********************************************************************
1250  *          MODULE_CallWEP
1251  *
1252  * Call a DLL's WEP, allowing it to shut down.
1253  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1254  */
1255 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1256 {
1257     BOOL16 ret;
1258     FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1259     if (!WEP) return FALSE;
1260
1261     __TRY
1262     {
1263         ret = NE_CallTo16_word_w( WEP, WEP_FREE_DLL );
1264     }
1265     __EXCEPT(page_fault)
1266     {
1267         WARN("Page fault\n");
1268         ret = 0;
1269     }
1270     __ENDTRY
1271
1272     return ret;
1273 }
1274
1275
1276 /**********************************************************************
1277  *          NE_FreeModule
1278  *
1279  * Implementation of FreeModule16().
1280  */
1281 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1282 {
1283     HMODULE16 *hPrevModule;
1284     NE_MODULE *pModule;
1285     HMODULE16 *pModRef;
1286     int i;
1287
1288     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1289     hModule = pModule->self;
1290
1291     TRACE("%04x count %d\n", hModule, pModule->count );
1292
1293     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1294     else pModule->count = 0;
1295
1296     if (pModule->flags & NE_FFLAGS_BUILTIN)
1297         return FALSE;  /* Can't free built-in module */
1298
1299     if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1300     {
1301         if (pModule->flags & NE_FFLAGS_LIBMODULE)
1302         {
1303             MODULE_CallWEP( hModule );
1304
1305             /* Free the objects owned by the DLL module */
1306             TASK_CallTaskSignalProc( USIG16_DLL_UNLOAD, hModule );
1307             PROCESS_CallUserSignalProc( USIG_DLL_UNLOAD_WIN16, hModule );
1308         }
1309         else
1310             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
1311     }
1312
1313
1314     /* Clear magic number just in case */
1315
1316     pModule->magic = pModule->self = 0;
1317
1318       /* Remove it from the linked list */
1319
1320     hPrevModule = &hFirstModule;
1321     while (*hPrevModule && (*hPrevModule != hModule))
1322     {
1323         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1324     }
1325     if (*hPrevModule) *hPrevModule = pModule->next;
1326
1327     /* Free the referenced modules */
1328
1329     pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1330     for (i = 0; i < pModule->modref_count; i++, pModRef++)
1331     {
1332         NE_FreeModule( *pModRef, call_wep );
1333     }
1334
1335     /* Free the module storage */
1336
1337     GlobalFreeAll16( hModule );
1338
1339     /* Remove module from cache */
1340
1341     if (pCachedModule == pModule) pCachedModule = NULL;
1342     return TRUE;
1343 }
1344
1345
1346 /**********************************************************************
1347  *          FreeModule    (KERNEL.46)
1348  */
1349 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1350 {
1351     return NE_FreeModule( hModule, TRUE );
1352 }
1353
1354
1355 /***********************************************************************
1356  *           FreeLibrary     (KERNEL.96)
1357  *           FreeLibrary16   (KERNEL32.36)
1358  */
1359 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1360 {
1361     TRACE("%04x\n", handle );
1362     FreeModule16( handle );
1363 }
1364
1365
1366 /**********************************************************************
1367  *          GetModuleName    (KERNEL.27)
1368  */
1369 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1370 {
1371     NE_MODULE *pModule;
1372     BYTE *p;
1373
1374     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1375     p = (BYTE *)pModule + pModule->name_table;
1376     if (count > *p) count = *p + 1;
1377     if (count > 0)
1378     {
1379         memcpy( buf, p + 1, count - 1 );
1380         buf[count-1] = '\0';
1381     }
1382     return TRUE;
1383 }
1384
1385
1386 /**********************************************************************
1387  *          GetModuleUsage    (KERNEL.48)
1388  */
1389 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1390 {
1391     NE_MODULE *pModule = NE_GetPtr( hModule );
1392     return pModule ? pModule->count : 0;
1393 }
1394
1395
1396 /**********************************************************************
1397  *          GetExpWinVer    (KERNEL.167)
1398  */
1399 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1400 {
1401     NE_MODULE *pModule = NE_GetPtr( hModule );
1402     if ( !pModule ) return 0;
1403
1404     /*
1405      * For built-in modules, fake the expected version the module should
1406      * have according to the Windows version emulated by Wine
1407      */
1408     if ( !pModule->expected_version )
1409     {
1410         OSVERSIONINFOA versionInfo;
1411         versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1412
1413         if ( GetVersionExA( &versionInfo ) )
1414             pModule->expected_version =
1415                      (versionInfo.dwMajorVersion & 0xff) << 8
1416                    | (versionInfo.dwMinorVersion & 0xff);
1417     }
1418
1419     return pModule->expected_version;
1420 }
1421
1422
1423 /**********************************************************************
1424  *          GetModuleFileName      (KERNEL.49)
1425  *
1426  * Comment: see GetModuleFileNameA
1427  *
1428  * Even if invoked by second instance of a program,
1429  * it still returns path of first one.
1430  */
1431 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1432                                   INT16 nSize )
1433 {
1434     NE_MODULE *pModule;
1435
1436     /* Win95 does not query hModule if set to 0 !
1437      * Is this wrong or maybe Win3.1 only ? */
1438     if (!hModule) hModule = GetCurrentTask();
1439
1440     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1441     lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1442     if (pModule->expected_version >= 0x400)
1443         GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1444     TRACE("%04x -> '%s'\n", hModule, lpFileName );
1445     return strlen(lpFileName);
1446 }
1447
1448
1449 /**********************************************************************
1450  *          GetModuleHandle    (KERNEL.47)
1451  *
1452  * Find a module from a module name.
1453  *
1454  * NOTE: The current implementation works the same way the Windows 95 one
1455  *       does. Do not try to 'fix' it, fix the callers.
1456  *       + It does not do ANY extension handling (except that strange .EXE bit)!
1457  *       + It does not care about paths, just about basenames. (same as Windows)
1458  *
1459  * RETURNS
1460  *   LOWORD:
1461  *      the win16 module handle if found
1462  *      0 if not
1463  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1464  *      Always hFirstModule
1465  */
1466 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1467 {
1468     if (HIWORD(name) == 0)
1469         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1470     return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1471 }
1472
1473 /***********************************************************************
1474  *          GetModuleHandle16 (KERNEL32.@)
1475  */
1476 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1477 {
1478     HMODULE16   hModule = hFirstModule;
1479     LPSTR       s;
1480     BYTE        len, *name_table;
1481     char        tmpstr[MAX_PATH];
1482     NE_MODULE *pModule;
1483
1484     TRACE("(%s)\n", name);
1485
1486     if (!HIWORD(name))
1487         return GetExePtr(LOWORD(name));
1488
1489     len = strlen(name);
1490     if (!len)
1491         return 0;
1492
1493     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1494
1495     /* If 'name' matches exactly the module name of a module:
1496      * Return its handle.
1497      */
1498     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1499     {
1500         pModule = NE_GetPtr( hModule );
1501         if (!pModule) break;
1502         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1503
1504         name_table = (BYTE *)pModule + pModule->name_table;
1505         if ((*name_table == len) && !strncmp(name, name_table+1, len))
1506             return hModule;
1507     }
1508
1509     /* If uppercased 'name' matches exactly the module name of a module:
1510      * Return its handle
1511      */
1512     for (s = tmpstr; *s; s++) *s = FILE_toupper(*s);
1513
1514     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1515     {
1516         pModule = NE_GetPtr( hModule );
1517         if (!pModule) break;
1518         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1519
1520         name_table = (BYTE *)pModule + pModule->name_table;
1521         /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1522          * but case sensitive! (Unfortunately Winword 6 and subdlls have
1523          * lowercased module names, but try to load uppercase DLLs, so this
1524          * 'i' compare is just a quickfix until the loader handles that
1525          * correctly. -MM 990705
1526          */
1527         if ((*name_table == len) && !FILE_strncasecmp(tmpstr, name_table+1, len))
1528             return hModule;
1529     }
1530
1531     /* If the base filename of 'name' matches the base filename of the module
1532      * filename of some module (case-insensitive compare):
1533      * Return its handle.
1534      */
1535
1536     /* basename: search backwards in passed name to \ / or : */
1537     s = tmpstr + strlen(tmpstr);
1538     while (s > tmpstr)
1539     {
1540         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1541                 break;
1542         s--;
1543     }
1544
1545     /* search this in loaded filename list */
1546     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1547     {
1548         char            *loadedfn;
1549         OFSTRUCT        *ofs;
1550
1551         pModule = NE_GetPtr( hModule );
1552         if (!pModule) break;
1553         if (!pModule->fileinfo) continue;
1554         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1555
1556         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1557         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1558         /* basename: search backwards in pathname to \ / or : */
1559         while (loadedfn > (char*)ofs->szPathName)
1560         {
1561             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1562                     break;
1563             loadedfn--;
1564         }
1565         /* case insensitive compare ... */
1566         if (!FILE_strcasecmp(loadedfn, s))
1567             return hModule;
1568     }
1569
1570     /* If the extension of 'name' is '.EXE' and the base filename of 'name'
1571      * matches the base filename of the module filename of some 32-bit module:
1572      * Return the corresponding 16-bit dummy module handle.
1573      */
1574     if (len >= 4 && !FILE_strcasecmp(name+len-4, ".EXE"))
1575     {
1576         HMODULE hModule = GetModuleHandleA( name );
1577         if ( hModule )
1578             return MapHModuleLS( hModule );
1579     }
1580
1581     if (!strcmp(tmpstr,"MSDOS"))
1582         return 1;
1583
1584     if (!strcmp(tmpstr,"TIMER"))
1585     {
1586         FIXME("Eh... Should return caller's code segment, expect crash\n");
1587         return 0;
1588     }
1589
1590     return 0;
1591 }
1592
1593 /**********************************************************************
1594  *          NE_GetModuleByFilename
1595  */
1596 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1597 {
1598     HMODULE16   hModule;
1599     LPSTR       s, p;
1600     BYTE        len, *name_table;
1601     char        tmpstr[MAX_PATH];
1602     NE_MODULE *pModule;
1603
1604     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1605
1606     /* If the base filename of 'name' matches the base filename of the module
1607      * filename of some module (case-insensitive compare):
1608      * Return its handle.
1609      */
1610
1611     /* basename: search backwards in passed name to \ / or : */
1612     s = tmpstr + strlen(tmpstr);
1613     while (s > tmpstr)
1614     {
1615         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1616                 break;
1617         s--;
1618     }
1619
1620     /* search this in loaded filename list */
1621     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1622     {
1623         char            *loadedfn;
1624         OFSTRUCT        *ofs;
1625
1626         pModule = NE_GetPtr( hModule );
1627         if (!pModule) break;
1628         if (!pModule->fileinfo) continue;
1629         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1630
1631         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1632         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1633         /* basename: search backwards in pathname to \ / or : */
1634         while (loadedfn > (char*)ofs->szPathName)
1635         {
1636             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1637                     break;
1638             loadedfn--;
1639         }
1640         /* case insensitive compare ... */
1641         if (!FILE_strcasecmp(loadedfn, s))
1642             return hModule;
1643     }
1644     /* If basename (without ext) matches the module name of a module:
1645      * Return its handle.
1646      */
1647
1648     if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1649     len = strlen(s);
1650
1651     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1652     {
1653         pModule = NE_GetPtr( hModule );
1654         if (!pModule) break;
1655         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1656
1657         name_table = (BYTE *)pModule + pModule->name_table;
1658         if ((*name_table == len) && !FILE_strncasecmp(s, name_table+1, len))
1659             return hModule;
1660     }
1661
1662     return 0;
1663 }
1664
1665 /**********************************************************************
1666  *          ModuleFirst    (TOOLHELP.59)
1667  */
1668 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1669 {
1670     lpme->wNext = hFirstModule;
1671     return ModuleNext16( lpme );
1672 }
1673
1674
1675 /**********************************************************************
1676  *          ModuleNext    (TOOLHELP.60)
1677  */
1678 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1679 {
1680     NE_MODULE *pModule;
1681     char *name;
1682
1683     if (!lpme->wNext) return FALSE;
1684     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1685     name = (char *)pModule + pModule->name_table;
1686     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1687     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1688     lpme->hModule = lpme->wNext;
1689     lpme->wcUsage = pModule->count;
1690     lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1691     lpme->wNext = pModule->next;
1692     return TRUE;
1693 }
1694
1695
1696 /**********************************************************************
1697  *          ModuleFindName    (TOOLHELP.61)
1698  */
1699 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1700 {
1701     lpme->wNext = GetModuleHandle16( name );
1702     return ModuleNext16( lpme );
1703 }
1704
1705
1706 /**********************************************************************
1707  *          ModuleFindHandle    (TOOLHELP.62)
1708  */
1709 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1710 {
1711     hModule = GetExePtr( hModule );
1712     lpme->wNext = hModule;
1713     return ModuleNext16( lpme );
1714 }
1715
1716
1717 /***************************************************************************
1718  *          IsRomModule    (KERNEL.323)
1719  */
1720 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1721 {
1722     return FALSE;
1723 }
1724
1725 /***************************************************************************
1726  *          IsRomFile    (KERNEL.326)
1727  */
1728 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1729 {
1730     return FALSE;
1731 }
1732
1733 /***************************************************************************
1734  *              MapHModuleLS                    (KERNEL32.@)
1735  */
1736 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod) {
1737         NE_MODULE       *pModule;
1738
1739         if (!hmod)
1740                 return TASK_GetCurrent()->hInstance;
1741         if (!HIWORD(hmod))
1742                 return LOWORD(hmod); /* we already have a 16 bit module handle */
1743         pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1744         while (pModule)  {
1745                 if (pModule->module32 == hmod)
1746                         return pModule->self;
1747                 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1748         }
1749         return 0;
1750 }
1751
1752 /***************************************************************************
1753  *              MapHModuleSL                    (KERNEL32.@)
1754  */
1755 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod) {
1756         NE_MODULE       *pModule;
1757
1758         if (!hmod) {
1759                 TDB *pTask = TASK_GetCurrent();
1760                 hmod = pTask->hModule;
1761         }
1762         pModule = (NE_MODULE*)GlobalLock16(hmod);
1763         if (    (pModule->magic!=IMAGE_OS2_SIGNATURE)   ||
1764                 !(pModule->flags & NE_FFLAGS_WIN32)
1765         )
1766                 return 0;
1767         return pModule->module32;
1768 }
1769
1770 /***************************************************************************
1771  *              MapHInstLS                      (KERNEL32.@)
1772  *              MapHInstLS                      (KERNEL.472)
1773  */
1774 void WINAPI MapHInstLS( CONTEXT86 *context )
1775 {
1776     context->Eax = MapHModuleLS( (HMODULE)context->Eax );
1777 }
1778
1779 /***************************************************************************
1780  *              MapHInstSL                      (KERNEL32.@)
1781  *              MapHInstSL                      (KERNEL.473)
1782  */
1783 void WINAPI MapHInstSL( CONTEXT86 *context )
1784 {
1785     context->Eax = (DWORD)MapHModuleSL( context->Eax );
1786 }
1787
1788 /***************************************************************************
1789  *              MapHInstLS_PN                   (KERNEL32.@)
1790  */
1791 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
1792 {
1793     if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
1794 }
1795
1796 /***************************************************************************
1797  *              MapHInstSL_PN                   (KERNEL32.@)
1798  */
1799 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
1800 {
1801     if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );
1802 }