Correct the test for the ODS_SELECTED bit in the WM_DRAWITEM message
[wine] / dlls / kernel / 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 <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <ctype.h>
34
35 #include "ntstatus.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "wine/winbase16.h"
39 #include "winerror.h"
40 #include "wownt32.h"
41 #include "wine/library.h"
42 #include "module.h"
43 #include "toolhelp.h"
44 #include "global.h"
45 #include "file.h"
46 #include "builtin16.h"
47 #include "stackframe.h"
48 #include "excpt.h"
49 #include "wine/unicode.h"
50 #include "wine/exception.h"
51 #include "wine/debug.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(module);
54 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
55
56 #include "pshpack1.h"
57 typedef struct _GPHANDLERDEF
58 {
59     WORD selector;
60     WORD rangeStart;
61     WORD rangeEnd;
62     WORD handler;
63 } GPHANDLERDEF;
64 #include "poppack.h"
65
66 /*
67  * Segment table entry
68  */
69 struct ne_segment_table_entry_s
70 {
71     WORD seg_data_offset;   /* Sector offset of segment data    */
72     WORD seg_data_length;   /* Length of segment data           */
73     WORD seg_flags;         /* Flags associated with this segment       */
74     WORD min_alloc;         /* Minimum allocation size for this */
75 };
76
77 #define hFirstModule (pThhook->hExeHead)
78
79 typedef struct
80 {
81     void       *module_start;      /* 32-bit address of the module data */
82     int         module_size;       /* Size of the module data */
83     void       *code_start;        /* 32-bit address of DLL code */
84     void       *data_start;        /* 32-bit address of DLL data */
85     const char *owner;             /* 32-bit dll that contains this dll */
86     const void *rsrc;              /* resources data */
87 } BUILTIN16_DESCRIPTOR;
88
89 /* Table of all built-in DLLs */
90
91 #define MAX_DLLS 50
92
93 static const BUILTIN16_DESCRIPTOR *builtin_dlls[MAX_DLLS];
94
95 extern void SNOOP16_RegisterDLL(NE_MODULE*,LPCSTR);
96 extern FARPROC16 SNOOP16_GetProcAddress16(HMODULE16,DWORD,FARPROC16);
97
98 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
99 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
100
101 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
102
103 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
104
105
106 static WINE_EXCEPTION_FILTER(page_fault)
107 {
108     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
109         GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
110         return EXCEPTION_EXECUTE_HANDLER;
111     return EXCEPTION_CONTINUE_SEARCH;
112 }
113
114
115 /* patch all the flat cs references of the code segment if necessary */
116 inline static void patch_code_segment( void *code_segment )
117 {
118 #ifdef __i386__
119     CALLFROM16 *call = code_segment;
120     if (call->flatcs == wine_get_cs()) return;  /* nothing to patch */
121     while (call->pushl == 0x68)
122     {
123         call->flatcs = wine_get_cs();
124         call++;
125     }
126 #endif
127 }
128
129
130 /***********************************************************************
131  *           find_dll_descr
132  *
133  * Find a descriptor in the list
134  */
135 static const BUILTIN16_DESCRIPTOR *find_dll_descr( const char *dllname )
136 {
137     int i;
138     for (i = 0; i < MAX_DLLS; i++)
139     {
140         const BUILTIN16_DESCRIPTOR *descr = builtin_dlls[i];
141         if (descr)
142         {
143             NE_MODULE *pModule = (NE_MODULE *)descr->module_start;
144             OFSTRUCT *pOfs = (OFSTRUCT *)((LPBYTE)pModule + pModule->fileinfo);
145             BYTE *name_table = (BYTE *)pModule + pModule->name_table;
146
147             /* check the dll file name */
148             if (!FILE_strcasecmp( pOfs->szPathName, dllname )) return descr;
149             /* check the dll module name (without extension) */
150             if (!FILE_strncasecmp( dllname, name_table+1, *name_table ) &&
151                 !strcmp( dllname + *name_table, ".dll" ))
152                 return descr;
153         }
154     }
155     return NULL;
156 }
157
158
159 /***********************************************************************
160  *           is_builtin_present
161  *
162  * Check if a builtin dll descriptor is present (because we loaded its 32-bit counterpart).
163  */
164 static BOOL is_builtin_present( LPCSTR name )
165 {
166     char dllname[20], *p;
167
168     if (strlen(name) >= sizeof(dllname)-4) return FALSE;
169     strcpy( dllname, name );
170     p = strrchr( dllname, '.' );
171     if (!p) strcat( dllname, ".dll" );
172     for (p = dllname; *p; p++) *p = FILE_tolower(*p);
173
174     return (find_dll_descr( dllname ) != NULL);
175 }
176
177
178 /***********************************************************************
179  *           __wine_register_dll_16 (KERNEL32.@)
180  *
181  * Register a built-in DLL descriptor.
182  */
183 void __wine_register_dll_16( const BUILTIN16_DESCRIPTOR *descr )
184 {
185     int i;
186
187     for (i = 0; i < MAX_DLLS; i++)
188     {
189         if (builtin_dlls[i]) continue;
190         builtin_dlls[i] = descr;
191         break;
192     }
193     assert( i < MAX_DLLS );
194 }
195
196
197 /***********************************************************************
198  *           __wine_unregister_dll_16 (KERNEL32.@)
199  *
200  * Unregister a built-in DLL descriptor.
201  */
202 void __wine_unregister_dll_16( const BUILTIN16_DESCRIPTOR *descr )
203 {
204     int i;
205
206     for (i = 0; i < MAX_DLLS; i++)
207     {
208         if (builtin_dlls[i] != descr) continue;
209         builtin_dlls[i] = NULL;
210         break;
211     }
212 }
213
214
215 /***********************************************************************
216  *           NE_GetPtr
217  */
218 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
219 {
220     return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
221 }
222
223
224 /**********************************************************************
225  *           NE_RegisterModule
226  */
227 static void NE_RegisterModule( NE_MODULE *pModule )
228 {
229     pModule->next = hFirstModule;
230     hFirstModule = pModule->self;
231 }
232
233
234 /***********************************************************************
235  *           NE_DumpModule
236  */
237 void NE_DumpModule( HMODULE16 hModule )
238 {
239     int i, ordinal;
240     SEGTABLEENTRY *pSeg;
241     BYTE *pstr;
242     WORD *pword;
243     NE_MODULE *pModule;
244     ET_BUNDLE *bundle;
245     ET_ENTRY *entry;
246
247     if (!(pModule = NE_GetPtr( hModule )))
248     {
249         MESSAGE( "**** %04x is not a module handle\n", hModule );
250         return;
251     }
252
253       /* Dump the module info */
254     DPRINTF( "---\n" );
255     DPRINTF( "Module %04x:\n", hModule );
256     DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
257              pModule->count, pModule->flags,
258              pModule->heap_size, pModule->stack_size );
259     DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
260              pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
261              pModule->seg_count, pModule->modref_count );
262     DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
263              pModule->os_flags, pModule->min_swap_area,
264              pModule->expected_version );
265     if (pModule->flags & NE_FFLAGS_WIN32)
266         DPRINTF( "PE module=%p\n", pModule->module32 );
267
268       /* Dump the file info */
269     DPRINTF( "---\n" );
270     DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
271
272       /* Dump the segment table */
273     DPRINTF( "---\n" );
274     DPRINTF( "Segment table:\n" );
275     pSeg = NE_SEG_TABLE( pModule );
276     for (i = 0; i < pModule->seg_count; i++, pSeg++)
277         DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
278                  i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
279                  pSeg->minsize, pSeg->hSeg );
280
281       /* Dump the resource table */
282     DPRINTF( "---\n" );
283     DPRINTF( "Resource table:\n" );
284     if (pModule->res_table)
285     {
286         pword = (WORD *)((BYTE *)pModule + pModule->res_table);
287         DPRINTF( "Alignment: %d\n", *pword++ );
288         while (*pword)
289         {
290             NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
291             NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
292             DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
293             for (i = 0; i < ptr->count; i++, pname++)
294                 DPRINTF( "offset=%d len=%d id=%04x\n",
295                       pname->offset, pname->length, pname->id );
296             pword = (WORD *)pname;
297         }
298     }
299     else DPRINTF( "None\n" );
300
301       /* Dump the resident name table */
302     DPRINTF( "---\n" );
303     DPRINTF( "Resident-name table:\n" );
304     pstr = (char *)pModule + pModule->name_table;
305     while (*pstr)
306     {
307         DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
308                  *(WORD *)(pstr + *pstr + 1) );
309         pstr += *pstr + 1 + sizeof(WORD);
310     }
311
312       /* Dump the module reference table */
313     DPRINTF( "---\n" );
314     DPRINTF( "Module ref table:\n" );
315     if (pModule->modref_table)
316     {
317         pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
318         for (i = 0; i < pModule->modref_count; i++, pword++)
319         {
320             char name[10];
321             GetModuleName16( *pword, name, sizeof(name) );
322             DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
323         }
324     }
325     else DPRINTF( "None\n" );
326
327       /* Dump the entry table */
328     DPRINTF( "---\n" );
329     DPRINTF( "Entry table:\n" );
330     bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);
331     do {
332         entry = (ET_ENTRY *)((BYTE *)bundle+6);
333         DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
334         ordinal = bundle->first;
335         while (ordinal < bundle->last)
336         {
337             if (entry->type == 0xff)
338                 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
339             else
340                 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
341             entry++;
342         }
343     } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
344
345     /* Dump the non-resident names table */
346     DPRINTF( "---\n" );
347     DPRINTF( "Non-resident names table:\n" );
348     if (pModule->nrname_handle)
349     {
350         pstr = (char *)GlobalLock16( pModule->nrname_handle );
351         while (*pstr)
352         {
353             DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
354                    *(WORD *)(pstr + *pstr + 1) );
355             pstr += *pstr + 1 + sizeof(WORD);
356         }
357     }
358     DPRINTF( "\n" );
359 }
360
361
362 /***********************************************************************
363  *           NE_WalkModules
364  *
365  * Walk the module list and print the modules.
366  */
367 void NE_WalkModules(void)
368 {
369     HMODULE16 hModule = hFirstModule;
370     MESSAGE( "Module Flags Name\n" );
371     while (hModule)
372     {
373         NE_MODULE *pModule = NE_GetPtr( hModule );
374         if (!pModule)
375         {
376             MESSAGE( "Bad module %04x in list\n", hModule );
377             return;
378         }
379         MESSAGE( " %04x  %04x  %.*s\n", hModule, pModule->flags,
380                  *((char *)pModule + pModule->name_table),
381                  (char *)pModule + pModule->name_table + 1 );
382         hModule = pModule->next;
383     }
384 }
385
386
387 /***********************************************************************
388  *           NE_InitResourceHandler
389  *
390  * Fill in 'resloader' fields in the resource table.
391  */
392 static void NE_InitResourceHandler( NE_MODULE *pModule )
393 {
394     static FARPROC16 proc;
395
396     NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
397
398     TRACE("InitResourceHandler[%04x]\n", pModule->self );
399
400     if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
401
402     while(pTypeInfo->type_id)
403     {
404         memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
405         pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
406     }
407 }
408
409
410 /***********************************************************************
411  *           NE_GetOrdinal
412  *
413  * Lookup the ordinal for a given name.
414  */
415 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
416 {
417     unsigned char buffer[256], *cpnt;
418     BYTE len;
419     NE_MODULE *pModule;
420
421     if (!(pModule = NE_GetPtr( hModule ))) return 0;
422     if (pModule->flags & NE_FFLAGS_WIN32) return 0;
423
424     TRACE("(%04x,'%s')\n", hModule, name );
425
426       /* First handle names of the form '#xxxx' */
427
428     if (name[0] == '#') return atoi( name + 1 );
429
430       /* Now copy and uppercase the string */
431
432     strcpy( buffer, name );
433     for (cpnt = buffer; *cpnt; cpnt++) *cpnt = FILE_toupper(*cpnt);
434     len = cpnt - buffer;
435
436       /* First search the resident names */
437
438     cpnt = (char *)pModule + pModule->name_table;
439
440       /* Skip the first entry (module name) */
441     cpnt += *cpnt + 1 + sizeof(WORD);
442     while (*cpnt)
443     {
444         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
445         {
446             WORD ordinal;
447             memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
448             TRACE("  Found: ordinal=%d\n", ordinal );
449             return ordinal;
450         }
451         cpnt += *cpnt + 1 + sizeof(WORD);
452     }
453
454       /* Now search the non-resident names table */
455
456     if (!pModule->nrname_handle) return 0;  /* No non-resident table */
457     cpnt = (char *)GlobalLock16( pModule->nrname_handle );
458
459       /* Skip the first entry (module description string) */
460     cpnt += *cpnt + 1 + sizeof(WORD);
461     while (*cpnt)
462     {
463         if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
464         {
465             WORD ordinal;
466             memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
467             TRACE("  Found: ordinal=%d\n", ordinal );
468             return ordinal;
469         }
470         cpnt += *cpnt + 1 + sizeof(WORD);
471     }
472     return 0;
473 }
474
475
476 /***********************************************************************
477  *              NE_GetEntryPoint
478  */
479 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
480 {
481     return NE_GetEntryPointEx( hModule, ordinal, TRUE );
482 }
483
484 /***********************************************************************
485  *              NE_GetEntryPointEx
486  */
487 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
488 {
489     NE_MODULE *pModule;
490     WORD sel, offset, i;
491
492     ET_ENTRY *entry;
493     ET_BUNDLE *bundle;
494
495     if (!(pModule = NE_GetPtr( hModule ))) return 0;
496     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
497
498     bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
499     while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
500     {
501         if (!(bundle->next))
502             return 0;
503         bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
504     }
505
506     entry = (ET_ENTRY *)((BYTE *)bundle+6);
507     for (i=0; i < (ordinal - bundle->first - 1); i++)
508         entry++;
509
510     sel = entry->segnum;
511     memcpy( &offset, &entry->offs, sizeof(WORD) );
512
513     if (sel == 0xfe) sel = 0xffff;  /* constant entry */
514     else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
515     if (sel==0xffff)
516         return (FARPROC16)MAKESEGPTR( sel, offset );
517     if (!snoop)
518         return (FARPROC16)MAKESEGPTR( sel, offset );
519     else
520         return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
521 }
522
523
524 /***********************************************************************
525  *              EntryAddrProc (KERNEL.667) Wine-specific export
526  *
527  * Return the entry point for a given ordinal.
528  */
529 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
530 {
531     FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
532     CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
533     return ret;
534 }
535
536 /***********************************************************************
537  *           NE_SetEntryPoint
538  *
539  * Change the value of an entry point. Use with caution!
540  * It can only change the offset value, not the selector.
541  */
542 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
543 {
544     NE_MODULE *pModule;
545     ET_ENTRY *entry;
546     ET_BUNDLE *bundle;
547     int i;
548
549     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
550     assert( !(pModule->flags & NE_FFLAGS_WIN32) );
551
552     bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
553     while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
554     {
555         bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
556         if (!(bundle->next)) return 0;
557     }
558
559     entry = (ET_ENTRY *)((BYTE *)bundle+6);
560     for (i=0; i < (ordinal - bundle->first - 1); i++)
561         entry++;
562
563     memcpy( &entry->offs, &offset, sizeof(WORD) );
564     return TRUE;
565 }
566
567
568 /***********************************************************************
569  *           NE_OpenFile
570  */
571 HANDLE NE_OpenFile( NE_MODULE *pModule )
572 {
573     HANDLE handle;
574     char *name = NE_MODULE_NAME( pModule );
575
576     TRACE("(%p)\n", pModule );
577
578     if (pModule->fd)
579     {
580         if (!DuplicateHandle( GetCurrentProcess(), pModule->fd,
581                               GetCurrentProcess(), &handle, 0, FALSE,
582                               DUPLICATE_SAME_ACCESS )) handle = INVALID_HANDLE_VALUE;
583     }
584     else
585     {
586         handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
587                               NULL, OPEN_EXISTING, 0, 0 );
588     }
589     if (handle == INVALID_HANDLE_VALUE)
590         ERR( "Can't open file '%s' for module %04x\n", name, pModule->self );
591
592     TRACE("opened '%s' -> %p\n", name, handle);
593     return handle;
594 }
595
596
597 /* wrapper for SetFilePointer and ReadFile */
598 static BOOL read_data( HANDLE handle, LONG offset, void *buffer, DWORD size )
599 {
600     DWORD result;
601
602     if (SetFilePointer( handle, offset, NULL, SEEK_SET ) == INVALID_SET_FILE_POINTER) return FALSE;
603     if (!ReadFile( handle, buffer, size, &result, NULL )) return FALSE;
604     return (result == size);
605 }
606
607 /***********************************************************************
608  *           NE_LoadExeHeader
609  */
610 static HMODULE16 NE_LoadExeHeader( HANDLE handle, LPCSTR path )
611 {
612     IMAGE_DOS_HEADER mz_header;
613     IMAGE_OS2_HEADER ne_header;
614     int size;
615     HMODULE16 hModule;
616     NE_MODULE *pModule;
617     BYTE *pData, *pTempEntryTable;
618     char *buffer, *fastload = NULL;
619     int fastload_offset = 0, fastload_length = 0;
620     ET_ENTRY *entry;
621     ET_BUNDLE *bundle, *oldbundle;
622     OFSTRUCT *ofs;
623
624   /* Read a block from either the file or the fast-load area. */
625 #define READ(offset,size,buffer) \
626        ((fastload && ((offset) >= fastload_offset) && \
627          ((offset)+(size) <= fastload_offset+fastload_length)) ? \
628         (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
629          read_data( handle, (offset), (buffer), (size)))
630
631     if (!read_data( handle, 0, &mz_header, sizeof(mz_header)) ||
632         (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
633         return (HMODULE16)11;  /* invalid exe */
634
635     if (!read_data( handle, mz_header.e_lfanew, &ne_header, sizeof(ne_header) ))
636         return (HMODULE16)11;  /* invalid exe */
637
638     if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21;  /* win32 exe */
639     if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
640         MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
641         return (HMODULE16)12;
642     }
643     if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11;  /* invalid exe */
644
645     /* We now have a valid NE header */
646
647     size = sizeof(NE_MODULE) +
648              /* segment table */
649            ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
650              /* resource table */
651            ne_header.ne_restab - ne_header.ne_rsrctab +
652              /* resident names table */
653            ne_header.ne_modtab - ne_header.ne_restab +
654              /* module ref table */
655            ne_header.ne_cmod * sizeof(WORD) +
656              /* imported names table */
657            ne_header.ne_enttab - ne_header.ne_imptab +
658              /* entry table length */
659            ne_header.ne_cbenttab +
660              /* entry table extra conversion space */
661            sizeof(ET_BUNDLE) +
662            2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
663              /* loaded file info */
664            sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
665
666     hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
667     if (!hModule) return (HMODULE16)11;  /* invalid exe */
668
669     FarSetOwner16( hModule, hModule );
670     pModule = (NE_MODULE *)GlobalLock16( hModule );
671     memcpy( pModule, &ne_header, sizeof(ne_header) );
672     pModule->count = 0;
673     /* check *programs* for default minimal stack size */
674     if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
675          && (pModule->stack_size < 0x1400) )
676         pModule->stack_size = 0x1400;
677     pModule->module32 = 0;
678     pModule->self = hModule;
679     pModule->self_loading_sel = 0;
680     pData = (BYTE *)(pModule + 1);
681
682     /* Clear internal Wine flags in case they are set in the EXE file */
683
684     pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
685
686     /* Read the fast-load area */
687
688     if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
689     {
690         fastload_offset=ne_header.ne_pretthunks << ne_header.ne_align;
691         fastload_length=ne_header.ne_psegrefbytes << ne_header.ne_align;
692         TRACE("Using fast-load area offset=%x len=%d\n",
693                         fastload_offset, fastload_length );
694         if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
695         {
696             if (!read_data( handle, fastload_offset, fastload, fastload_length))
697             {
698                 HeapFree( GetProcessHeap(), 0, fastload );
699                 WARN("Error reading fast-load area!\n");
700                 fastload = NULL;
701             }
702         }
703     }
704
705     /* Get the segment table */
706
707     pModule->seg_table = pData - (BYTE *)pModule;
708     buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
709                                       sizeof(struct ne_segment_table_entry_s));
710     if (buffer)
711     {
712         int i;
713         struct ne_segment_table_entry_s *pSeg;
714
715         if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
716              ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
717              buffer ))
718         {
719             HeapFree( GetProcessHeap(), 0, buffer );
720             if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
721             GlobalFree16( hModule );
722             return (HMODULE16)11;  /* invalid exe */
723         }
724         pSeg = (struct ne_segment_table_entry_s *)buffer;
725         for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
726         {
727             memcpy( pData, pSeg, sizeof(*pSeg) );
728             pData += sizeof(SEGTABLEENTRY);
729         }
730         HeapFree( GetProcessHeap(), 0, buffer );
731     }
732     else
733     {
734         if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
735         GlobalFree16( hModule );
736         return (HMODULE16)11;  /* invalid exe */
737     }
738
739     /* Get the resource table */
740
741     if (ne_header.ne_rsrctab < ne_header.ne_restab)
742     {
743         pModule->res_table = pData - (BYTE *)pModule;
744         if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
745                   ne_header.ne_restab - ne_header.ne_rsrctab,
746                   pData ))
747             return (HMODULE16)11;  /* invalid exe */
748         pData += ne_header.ne_restab - ne_header.ne_rsrctab;
749         NE_InitResourceHandler( pModule );
750     }
751     else pModule->res_table = 0;  /* No resource table */
752
753     /* Get the resident names table */
754
755     pModule->name_table = pData - (BYTE *)pModule;
756     if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
757                ne_header.ne_modtab - ne_header.ne_restab,
758                pData ))
759     {
760         if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
761         GlobalFree16( hModule );
762         return (HMODULE16)11;  /* invalid exe */
763     }
764     pData += ne_header.ne_modtab - ne_header.ne_restab;
765
766     /* Get the module references table */
767
768     if (ne_header.ne_cmod > 0)
769     {
770         pModule->modref_table = pData - (BYTE *)pModule;
771         if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
772                   ne_header.ne_cmod * sizeof(WORD),
773                   pData ))
774         {
775             if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
776             GlobalFree16( hModule );
777             return (HMODULE16)11;  /* invalid exe */
778         }
779         pData += ne_header.ne_cmod * sizeof(WORD);
780     }
781     else pModule->modref_table = 0;  /* No module references */
782
783     /* Get the imported names table */
784
785     pModule->import_table = pData - (BYTE *)pModule;
786     if (!READ( mz_header.e_lfanew + ne_header.ne_imptab,
787                ne_header.ne_enttab - ne_header.ne_imptab,
788                pData ))
789     {
790         if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
791         GlobalFree16( hModule );
792         return (HMODULE16)11;  /* invalid exe */
793     }
794     pData += ne_header.ne_enttab - ne_header.ne_imptab;
795
796     /* Load entry table, convert it to the optimized version used by Windows */
797
798     if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
799     {
800         BYTE nr_entries, type, *s;
801
802         TRACE("Converting entry table.\n");
803         pModule->entry_table = pData - (BYTE *)pModule;
804         if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
805                    ne_header.ne_cbenttab, pTempEntryTable ))
806         {
807             HeapFree( GetProcessHeap(), 0, pTempEntryTable );
808             if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
809             GlobalFree16( hModule );
810             return (HMODULE16)11;  /* invalid exe */
811         }
812
813         s = pTempEntryTable;
814         TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
815
816         bundle = (ET_BUNDLE *)pData;
817         TRACE("first bundle: %p\n", bundle);
818         memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
819         entry = (ET_ENTRY *)((BYTE *)bundle+6);
820
821         while ((nr_entries = *s++))
822         {
823             if ((type = *s++))
824             {
825                 bundle->last += nr_entries;
826                 if (type == 0xff)
827                 while (nr_entries--)
828                 {
829                     entry->type   = type;
830                     entry->flags  = *s++;
831                     s += 2;
832                     entry->segnum = *s++;
833                     entry->offs   = *(WORD *)s; s += 2;
834                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
835                     entry++;
836                 }
837                 else
838                 while (nr_entries--)
839                 {
840                     entry->type   = type;
841                     entry->flags  = *s++;
842                     entry->segnum = type;
843                     entry->offs   = *(WORD *)s; s += 2;
844                     /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
845                     entry++;
846                 }
847             }
848             else
849             {
850                 if (bundle->first == bundle->last)
851                 {
852                     bundle->first += nr_entries;
853                     bundle->last += nr_entries;
854                 }
855                 else
856                 {
857                     oldbundle = bundle;
858                     oldbundle->next = ((int)entry - (int)pModule);
859                     bundle = (ET_BUNDLE *)entry;
860                     TRACE("new bundle: %p\n", bundle);
861                     bundle->first = bundle->last =
862                         oldbundle->last + nr_entries;
863                     bundle->next = 0;
864                     (BYTE *)entry += sizeof(ET_BUNDLE);
865                 }
866             }
867         }
868         HeapFree( GetProcessHeap(), 0, pTempEntryTable );
869     }
870     else
871     {
872         if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
873         GlobalFree16( hModule );
874         return (HMODULE16)11;  /* invalid exe */
875     }
876
877     pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
878         2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
879
880     if ((DWORD)entry > (DWORD)pData)
881        ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
882
883     /* Store the filename information */
884
885     pModule->fileinfo = pData - (BYTE *)pModule;
886     size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
887     ofs = (OFSTRUCT *)pData;
888     ofs->cBytes = size - 1;
889     ofs->fFixedDisk = 1;
890     strcpy( ofs->szPathName, path );
891     pData += size;
892
893     /* Free the fast-load area */
894
895 #undef READ
896     if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
897
898     /* Get the non-resident names table */
899
900     if (ne_header.ne_cbnrestab)
901     {
902         pModule->nrname_handle = GlobalAlloc16( 0, ne_header.ne_cbnrestab );
903         if (!pModule->nrname_handle)
904         {
905             GlobalFree16( hModule );
906             return (HMODULE16)11;  /* invalid exe */
907         }
908         FarSetOwner16( pModule->nrname_handle, hModule );
909         buffer = GlobalLock16( pModule->nrname_handle );
910         if (!read_data( handle, ne_header.ne_nrestab, buffer, ne_header.ne_cbnrestab ))
911         {
912             GlobalFree16( pModule->nrname_handle );
913             GlobalFree16( hModule );
914             return (HMODULE16)11;  /* invalid exe */
915         }
916     }
917     else pModule->nrname_handle = 0;
918
919     /* Allocate a segment for the implicitly-loaded DLLs */
920
921     if (pModule->modref_count)
922     {
923         pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
924                                                (pModule->modref_count+1)*sizeof(HMODULE16) );
925         if (!pModule->dlls_to_init)
926         {
927             if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
928             GlobalFree16( hModule );
929             return (HMODULE16)11;  /* invalid exe */
930         }
931         FarSetOwner16( pModule->dlls_to_init, hModule );
932     }
933     else pModule->dlls_to_init = 0;
934
935     NE_RegisterModule( pModule );
936     SNOOP16_RegisterDLL(pModule,path);
937     return hModule;
938 }
939
940
941 /***********************************************************************
942  *           NE_LoadDLLs
943  *
944  * Load all DLLs implicitly linked to a module.
945  */
946 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
947 {
948     int i;
949     WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
950     WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
951
952     for (i = 0; i < pModule->modref_count; i++, pModRef++)
953     {
954         char buffer[260], *p;
955         BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
956         memcpy( buffer, pstr + 1, *pstr );
957         *(buffer + *pstr) = 0; /* terminate it */
958
959         TRACE("Loading '%s'\n", buffer );
960         if (!(*pModRef = GetModuleHandle16( buffer )))
961         {
962             /* If the DLL is not loaded yet, load it and store */
963             /* its handle in the list of DLLs to initialize.   */
964             HMODULE16 hDLL;
965
966             /* Append .DLL to name if no extension present */
967             if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
968                     strcat( buffer, ".DLL" );
969
970             if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
971             {
972                 /* FIXME: cleanup what was done */
973
974                 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
975                      buffer, *((BYTE*)pModule + pModule->name_table),
976                      (char *)pModule + pModule->name_table + 1, hDLL );
977                 return FALSE;
978             }
979             *pModRef = GetExePtr( hDLL );
980             *pDLLs++ = *pModRef;
981         }
982         else  /* Increment the reference count of the DLL */
983         {
984             NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
985             if (pOldDLL) pOldDLL->count++;
986         }
987     }
988     return TRUE;
989 }
990
991
992 /**********************************************************************
993  *          NE_DoLoadModule
994  *
995  * Load first instance of NE module from file.
996  *
997  * pModule must point to a module structure prepared by NE_LoadExeHeader.
998  * This routine must never be called twice on a module.
999  *
1000  */
1001 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
1002 {
1003     /* Allocate the segments for this module */
1004
1005     if (!NE_CreateAllSegments( pModule ))
1006         return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
1007
1008     /* Load the referenced DLLs */
1009
1010     if (!NE_LoadDLLs( pModule ))
1011         return ERROR_FILE_NOT_FOUND; /* 2 */
1012
1013     /* Load the segments */
1014
1015     NE_LoadAllSegments( pModule );
1016
1017     /* Make sure the usage count is 1 on the first loading of  */
1018     /* the module, even if it contains circular DLL references */
1019
1020     pModule->count = 1;
1021
1022     return NE_GetInstance( pModule );
1023 }
1024
1025 /**********************************************************************
1026  *          NE_LoadModule
1027  *
1028  * Load first instance of NE module. (Note: caller is responsible for
1029  * ensuring the module isn't already loaded!)
1030  *
1031  * If the module turns out to be an executable module, only a
1032  * handle to a module stub is returned; this needs to be initialized
1033  * by calling NE_DoLoadModule later, in the context of the newly
1034  * created process.
1035  *
1036  * If lib_only is TRUE, however, the module is perforce treated
1037  * like a DLL module, even if it is an executable module.
1038  *
1039  */
1040 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
1041 {
1042     NE_MODULE *pModule;
1043     HMODULE16 hModule;
1044     HINSTANCE16 hInstance;
1045     HFILE16 hFile;
1046     OFSTRUCT ofs;
1047     UINT drive_type;
1048
1049     /* Open file */
1050     if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
1051         return (HMODULE16)2;  /* File not found */
1052
1053     hModule = NE_LoadExeHeader( DosFileHandleToWin32Handle(hFile), ofs.szPathName );
1054     if (hModule < 32)
1055     {
1056         _lclose16( hFile );
1057         return hModule;
1058     }
1059     pModule = NE_GetPtr( hModule );
1060
1061     drive_type = GetDriveTypeA( ofs.szPathName );
1062     if (drive_type != DRIVE_REMOVABLE && drive_type != DRIVE_CDROM)
1063     {
1064         /* keep the file handle open if not on a removable media */
1065         DuplicateHandle( GetCurrentProcess(), DosFileHandleToWin32Handle(hFile),
1066                          GetCurrentProcess(), &pModule->fd, 0, FALSE,
1067                          DUPLICATE_SAME_ACCESS );
1068     }
1069     _lclose16( hFile );
1070
1071     if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
1072         return hModule;
1073
1074     hInstance = NE_DoLoadModule( pModule );
1075     if ( hInstance < 32 )
1076     {
1077         /* cleanup ... */
1078         NE_FreeModule( hModule, 0 );
1079     }
1080
1081     return hInstance;
1082 }
1083
1084
1085 /***********************************************************************
1086  *           NE_DoLoadBuiltinModule
1087  *
1088  * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
1089  */
1090 static HMODULE16 NE_DoLoadBuiltinModule( const BUILTIN16_DESCRIPTOR *descr )
1091 {
1092     NE_MODULE *pModule;
1093     int minsize;
1094     SEGTABLEENTRY *pSegTable;
1095     HMODULE16 hModule;
1096
1097     hModule = GLOBAL_CreateBlock( GMEM_MOVEABLE, descr->module_start,
1098                                   descr->module_size, 0, WINE_LDT_FLAGS_DATA );
1099     if (!hModule) return 0;
1100     FarSetOwner16( hModule, hModule );
1101
1102     pModule = (NE_MODULE *)GlobalLock16( hModule );
1103     pModule->self = hModule;
1104     /* NOTE: (Ab)use the hRsrcMap parameter for resource data pointer */
1105     pModule->hRsrcMap = (void *)descr->rsrc;
1106
1107     /* Allocate the code segment */
1108
1109     pSegTable = NE_SEG_TABLE( pModule );
1110     pSegTable->hSeg = GLOBAL_CreateBlock( GMEM_FIXED, descr->code_start,
1111                                           pSegTable->minsize, hModule,
1112                                           WINE_LDT_FLAGS_CODE|WINE_LDT_FLAGS_32BIT );
1113     if (!pSegTable->hSeg) return 0;
1114     patch_code_segment( descr->code_start );
1115     pSegTable++;
1116
1117     /* Allocate the data segment */
1118
1119     minsize = pSegTable->minsize ? pSegTable->minsize : 0x10000;
1120     minsize += pModule->heap_size;
1121     if (minsize > 0x10000) minsize = 0x10000;
1122     pSegTable->hSeg = GlobalAlloc16( GMEM_FIXED, minsize );
1123     if (!pSegTable->hSeg) return 0;
1124     FarSetOwner16( pSegTable->hSeg, hModule );
1125     if (pSegTable->minsize) memcpy( GlobalLock16( pSegTable->hSeg ),
1126                                     descr->data_start, pSegTable->minsize);
1127     if (pModule->heap_size)
1128         LocalInit16( GlobalHandleToSel16(pSegTable->hSeg), pSegTable->minsize, minsize );
1129
1130     if (descr->rsrc) NE_InitResourceHandler(pModule);
1131
1132     NE_RegisterModule( pModule );
1133
1134     /* make sure the 32-bit library containing this one is loaded too */
1135     LoadLibraryA( descr->owner );
1136
1137     return hModule;
1138 }
1139
1140
1141 /***********************************************************************
1142  *           NE_LoadBuiltinModule
1143  *
1144  * Load a built-in module.
1145  */
1146 static HMODULE16 NE_LoadBuiltinModule( LPCSTR name )
1147 {
1148     const BUILTIN16_DESCRIPTOR *descr;
1149     char error[256], dllname[20], *p;
1150     int file_exists;
1151     void *handle;
1152
1153     /* Fix the name in case we have a full path and extension */
1154
1155     if ((p = strrchr( name, '\\' ))) name = p + 1;
1156     if ((p = strrchr( name, '/' ))) name = p + 1;
1157
1158     if (strlen(name) >= sizeof(dllname)-4) return (HMODULE16)2;
1159
1160     strcpy( dllname, name );
1161     p = strrchr( dllname, '.' );
1162     if (!p) strcat( dllname, ".dll" );
1163     for (p = dllname; *p; p++) *p = FILE_tolower(*p);
1164
1165     if ((descr = find_dll_descr( dllname )))
1166         return NE_DoLoadBuiltinModule( descr );
1167
1168     if ((handle = wine_dll_load( dllname, error, sizeof(error), &file_exists )))
1169     {
1170         if ((descr = find_dll_descr( dllname )))
1171             return NE_DoLoadBuiltinModule( descr );
1172         if (GetModuleHandleA( dllname ))
1173             return 21;  /* Win32 module */
1174         ERR( "loaded .so but dll %s still not found\n", dllname );
1175     }
1176     else
1177     {
1178         if (!file_exists) WARN("cannot open .so lib for 16-bit builtin %s: %s\n", name, error);
1179         else ERR("failed to load .so lib for 16-bit builtin %s: %s\n", name, error );
1180     }
1181     return (HMODULE16)2;
1182 }
1183
1184
1185 /**********************************************************************
1186  *          MODULE_LoadModule16
1187  *
1188  * Load a NE module in the order of the loadorder specification.
1189  * The caller is responsible that the module is not loaded already.
1190  *
1191  */
1192 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1193 {
1194     HINSTANCE16 hinst = 2;
1195     enum loadorder_type loadorder[LOADORDER_NTYPES];
1196     int i;
1197     const char *filetype = "";
1198     const char *ptr, *basename;
1199
1200     /* strip path information */
1201
1202     basename = libname;
1203     if (basename[0] && basename[1] == ':') basename += 2;  /* strip drive specification */
1204     if ((ptr = strrchr( basename, '\\' ))) basename = ptr + 1;
1205     if ((ptr = strrchr( basename, '/' ))) basename = ptr + 1;
1206
1207     if (is_builtin_present(basename))
1208     {
1209         TRACE( "forcing loadorder to builtin for %s\n", debugstr_a(basename) );
1210         /* force builtin loadorder since the dll is already in memory */
1211         loadorder[0] = LOADORDER_BI;
1212         loadorder[1] = LOADORDER_INVALID;
1213     }
1214     else
1215     {
1216         UNICODE_STRING pathW;
1217         WCHAR buffer[MAX_PATH], *p;
1218
1219         if (!GetModuleFileNameW( 0, buffer, MAX_PATH )) p = NULL;
1220         else
1221         {
1222             if ((p = strrchrW( buffer, '\\' ))) p++;
1223             else p = buffer;
1224         }
1225         RtlCreateUnicodeStringFromAsciiz( &pathW, basename );
1226         MODULE_GetLoadOrderW( loadorder, p, pathW.Buffer );
1227         RtlFreeUnicodeString( &pathW );
1228     }
1229
1230     for(i = 0; i < LOADORDER_NTYPES; i++)
1231     {
1232         if (loadorder[i] == LOADORDER_INVALID) break;
1233
1234         switch(loadorder[i])
1235         {
1236         case LOADORDER_DLL:
1237             TRACE("Trying native dll '%s'\n", libname);
1238             hinst = NE_LoadModule(libname, lib_only);
1239             filetype = "native";
1240             break;
1241
1242         case LOADORDER_BI:
1243             TRACE("Trying built-in '%s'\n", libname);
1244             hinst = NE_LoadBuiltinModule(libname);
1245             filetype = "builtin";
1246             break;
1247
1248         default:
1249             hinst = 2;
1250             break;
1251         }
1252
1253         if(hinst >= 32)
1254         {
1255             TRACE_(loaddll)("Loaded module '%s' : %s\n", libname, filetype);
1256             if(!implicit)
1257             {
1258                 HMODULE16 hModule;
1259                 NE_MODULE *pModule;
1260
1261                 hModule = GetModuleHandle16(libname);
1262                 if(!hModule)
1263                 {
1264                     ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1265                         libname, hinst);
1266                     return 6;   /* ERROR_INVALID_HANDLE seems most appropriate */
1267                 }
1268
1269                 pModule = NE_GetPtr(hModule);
1270                 if(!pModule)
1271                 {
1272                     ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1273                         libname, hinst);
1274                     return 6;   /* ERROR_INVALID_HANDLE seems most appropriate */
1275                 }
1276
1277                 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1278
1279                 /*
1280                  * Call initialization routines for all loaded DLLs. Note that
1281                  * when we load implicitly linked DLLs this will be done by InitTask().
1282                  */
1283                 if(pModule->flags & NE_FFLAGS_LIBMODULE)
1284                 {
1285                     NE_InitializeDLLs(hModule);
1286                     NE_DllProcessAttach(hModule);
1287                 }
1288             }
1289             return hinst;
1290         }
1291
1292         if(hinst != 2)
1293         {
1294             /* We quit searching when we get another error than 'File not found' */
1295             break;
1296         }
1297     }
1298     return hinst;       /* The last error that occurred */
1299 }
1300
1301
1302 /**********************************************************************
1303  *          NE_CreateThread
1304  *
1305  * Create the thread for a 16-bit module.
1306  */
1307 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1308 {
1309     HANDLE hThread;
1310     TDB *pTask;
1311     HTASK16 hTask;
1312     HINSTANCE16 instance = 0;
1313
1314     if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1315         return 0;
1316
1317     /* Post event to start the task */
1318     PostEvent16( hTask );
1319
1320     /* Wait until we get the instance handle */
1321     do
1322     {
1323         DirectedYield16( hTask );
1324         if (!IsTask16( hTask ))  /* thread has died */
1325         {
1326             DWORD exit_code;
1327             WaitForSingleObject( hThread, INFINITE );
1328             GetExitCodeThread( hThread, &exit_code );
1329             CloseHandle( hThread );
1330             return exit_code;
1331         }
1332         if (!(pTask = GlobalLock16( hTask ))) break;
1333         instance = pTask->hInstance;
1334         GlobalUnlock16( hTask );
1335     } while (!instance);
1336
1337     CloseHandle( hThread );
1338     return instance;
1339 }
1340
1341
1342 /**********************************************************************
1343  *          LoadModule      (KERNEL.45)
1344  */
1345 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1346 {
1347     BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1348     LOADPARAMS16 *params;
1349     HMODULE16 hModule;
1350     NE_MODULE *pModule;
1351     LPSTR cmdline;
1352     WORD cmdShow;
1353
1354     /* Load module */
1355
1356     if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1357     {
1358         /* Special case: second instance of an already loaded NE module */
1359
1360         if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1361         if ( pModule->module32 ) return (HINSTANCE16)21;
1362
1363         /* Increment refcount */
1364
1365         pModule->count++;
1366     }
1367     else
1368     {
1369         /* Main case: load first instance of NE module */
1370
1371         if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1372             return hModule;
1373
1374         if ( !(pModule = NE_GetPtr( hModule )) )
1375             return (HINSTANCE16)11;
1376     }
1377
1378     /* If library module, we just retrieve the instance handle */
1379
1380     if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1381         return NE_GetInstance( pModule );
1382
1383     /*
1384      *  At this point, we need to create a new process.
1385      *
1386      *  pModule points either to an already loaded module, whose refcount
1387      *  has already been incremented (to avoid having the module vanish
1388      *  in the meantime), or else to a stub module which contains only header
1389      *  information.
1390      */
1391     params = (LOADPARAMS16 *)paramBlock;
1392     cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1393     cmdline = MapSL( params->cmdLine );
1394     return NE_CreateThread( pModule, cmdShow, cmdline );
1395 }
1396
1397
1398 /**********************************************************************
1399  *          NE_StartTask
1400  *
1401  * Startup code for a new 16-bit task.
1402  */
1403 DWORD NE_StartTask(void)
1404 {
1405     TDB *pTask = TASK_GetCurrent();
1406     NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1407     HINSTANCE16 hInstance, hPrevInstance;
1408     SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1409     WORD sp;
1410
1411     if ( pModule->count > 0 )
1412     {
1413         /* Second instance of an already loaded NE module */
1414         /* Note that the refcount was already incremented by the parent */
1415
1416         hPrevInstance = NE_GetInstance( pModule );
1417
1418         if ( pModule->dgroup )
1419             if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1420                 NE_LoadSegment( pModule, pModule->dgroup );
1421
1422         hInstance = NE_GetInstance( pModule );
1423         TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1424
1425     }
1426     else
1427     {
1428         /* Load first instance of NE module */
1429
1430         pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1431
1432         hInstance = NE_DoLoadModule( pModule );
1433         hPrevInstance = 0;
1434     }
1435
1436     if ( hInstance >= 32 )
1437     {
1438         CONTEXT86 context;
1439
1440         /* Enter instance handles into task struct */
1441
1442         pTask->hInstance = hInstance;
1443         pTask->hPrevInstance = hPrevInstance;
1444
1445         /* Use DGROUP for 16-bit stack */
1446
1447         if (!(sp = pModule->sp))
1448             sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1449         sp &= ~1;
1450         sp -= sizeof(STACK16FRAME);
1451         NtCurrentTeb()->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1452
1453         /* Registers at initialization must be:
1454          * ax   zero
1455          * bx   stack size in bytes
1456          * cx   heap size in bytes
1457          * si   previous app instance
1458          * di   current app instance
1459          * bp   zero
1460          * es   selector to the PSP
1461          * ds   dgroup of the application
1462          * ss   stack selector
1463          * sp   top of the stack
1464          */
1465         memset( &context, 0, sizeof(context) );
1466         context.SegCs  = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1467         context.SegDs  = GlobalHandleToSel16(pTask->hInstance);
1468         context.SegEs  = pTask->hPDB;
1469         context.SegFs  = wine_get_fs();
1470         context.SegGs  = wine_get_gs();
1471         context.Eip    = pModule->ip;
1472         context.Ebx    = pModule->stack_size;
1473         context.Ecx    = pModule->heap_size;
1474         context.Edi    = pTask->hInstance;
1475         context.Esi    = pTask->hPrevInstance;
1476
1477         /* Now call 16-bit entry point */
1478
1479         TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1480               context.SegCs, context.Eip, context.SegDs,
1481               SELECTOROF(NtCurrentTeb()->cur_stack),
1482               OFFSETOF(NtCurrentTeb()->cur_stack) );
1483
1484         WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1485         ExitThread( LOWORD(context.Eax) );
1486     }
1487     return hInstance;  /* error code */
1488 }
1489
1490 /***********************************************************************
1491  *           LoadLibrary     (KERNEL.95)
1492  *           LoadLibrary16   (KERNEL32.35)
1493  */
1494 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1495 {
1496     return LoadModule16(libname, (LPVOID)-1 );
1497 }
1498
1499
1500 /**********************************************************************
1501  *          MODULE_CallWEP
1502  *
1503  * Call a DLL's WEP, allowing it to shut down.
1504  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1505  */
1506 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1507 {
1508     BOOL16 ret;
1509     FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1510     if (!WEP) return FALSE;
1511
1512     __TRY
1513     {
1514         WORD args[1];
1515         DWORD dwRet;
1516
1517         args[0] = WEP_FREE_DLL;
1518         WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1519         ret = LOWORD(dwRet);
1520     }
1521     __EXCEPT(page_fault)
1522     {
1523         WARN("Page fault\n");
1524         ret = 0;
1525     }
1526     __ENDTRY
1527
1528     return ret;
1529 }
1530
1531
1532 /**********************************************************************
1533  *          NE_FreeModule
1534  *
1535  * Implementation of FreeModule16().
1536  */
1537 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1538 {
1539     HMODULE16 *hPrevModule;
1540     NE_MODULE *pModule;
1541     HMODULE16 *pModRef;
1542     int i;
1543
1544     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1545     hModule = pModule->self;
1546
1547     TRACE("%04x count %d\n", hModule, pModule->count );
1548
1549     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1550     else pModule->count = 0;
1551
1552     if (pModule->flags & NE_FFLAGS_BUILTIN)
1553         return FALSE;  /* Can't free built-in module */
1554
1555     if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1556     {
1557         /* Free the objects owned by the DLL module */
1558         NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1559
1560         if (pModule->flags & NE_FFLAGS_LIBMODULE)
1561             MODULE_CallWEP( hModule );
1562         else
1563             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
1564     }
1565
1566
1567     /* Clear magic number just in case */
1568
1569     pModule->magic = pModule->self = 0;
1570     if (pModule->fd) CloseHandle( pModule->fd );
1571
1572       /* Remove it from the linked list */
1573
1574     hPrevModule = &hFirstModule;
1575     while (*hPrevModule && (*hPrevModule != hModule))
1576     {
1577         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1578     }
1579     if (*hPrevModule) *hPrevModule = pModule->next;
1580
1581     /* Free the referenced modules */
1582
1583     pModRef = (HMODULE16*)((char *)pModule + pModule->modref_table);
1584     for (i = 0; i < pModule->modref_count; i++, pModRef++)
1585     {
1586         NE_FreeModule( *pModRef, call_wep );
1587     }
1588
1589     /* Free the module storage */
1590
1591     GlobalFreeAll16( hModule );
1592     return TRUE;
1593 }
1594
1595
1596 /**********************************************************************
1597  *          FreeModule    (KERNEL.46)
1598  */
1599 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1600 {
1601     return NE_FreeModule( hModule, TRUE );
1602 }
1603
1604
1605 /***********************************************************************
1606  *           FreeLibrary     (KERNEL.96)
1607  *           FreeLibrary16   (KERNEL32.36)
1608  */
1609 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1610 {
1611     TRACE("%04x\n", handle );
1612     FreeModule16( handle );
1613 }
1614
1615
1616 /***********************************************************************
1617  *          GetModuleHandle16 (KERNEL32.@)
1618  */
1619 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1620 {
1621     HMODULE16   hModule = hFirstModule;
1622     LPSTR       s;
1623     BYTE        len, *name_table;
1624     char        tmpstr[MAX_PATH];
1625     NE_MODULE *pModule;
1626
1627     TRACE("(%s)\n", name);
1628
1629     if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1630
1631     len = strlen(name);
1632     if (!len) return 0;
1633
1634     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1635
1636     /* If 'name' matches exactly the module name of a module:
1637      * Return its handle.
1638      */
1639     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1640     {
1641         pModule = NE_GetPtr( hModule );
1642         if (!pModule) break;
1643         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1644
1645         name_table = (BYTE *)pModule + pModule->name_table;
1646         if ((*name_table == len) && !strncmp(name, name_table+1, len))
1647             return hModule;
1648     }
1649
1650     /* If uppercased 'name' matches exactly the module name of a module:
1651      * Return its handle
1652      */
1653     for (s = tmpstr; *s; s++) *s = FILE_toupper(*s);
1654
1655     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1656     {
1657         pModule = NE_GetPtr( hModule );
1658         if (!pModule) break;
1659         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1660
1661         name_table = (BYTE *)pModule + pModule->name_table;
1662         /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1663          * but case sensitive! (Unfortunately Winword 6 and subdlls have
1664          * lowercased module names, but try to load uppercase DLLs, so this
1665          * 'i' compare is just a quickfix until the loader handles that
1666          * correctly. -MM 990705
1667          */
1668         if ((*name_table == len) && !FILE_strncasecmp(tmpstr, name_table+1, len))
1669             return hModule;
1670     }
1671
1672     /* If the base filename of 'name' matches the base filename of the module
1673      * filename of some module (case-insensitive compare):
1674      * Return its handle.
1675      */
1676
1677     /* basename: search backwards in passed name to \ / or : */
1678     s = tmpstr + strlen(tmpstr);
1679     while (s > tmpstr)
1680     {
1681         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1682                 break;
1683         s--;
1684     }
1685
1686     /* search this in loaded filename list */
1687     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1688     {
1689         char            *loadedfn;
1690         OFSTRUCT        *ofs;
1691
1692         pModule = NE_GetPtr( hModule );
1693         if (!pModule) break;
1694         if (!pModule->fileinfo) continue;
1695         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1696
1697         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1698         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1699         /* basename: search backwards in pathname to \ / or : */
1700         while (loadedfn > (char*)ofs->szPathName)
1701         {
1702             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1703                     break;
1704             loadedfn--;
1705         }
1706         /* case insensitive compare ... */
1707         if (!FILE_strcasecmp(loadedfn, s))
1708             return hModule;
1709     }
1710     return 0;
1711 }
1712
1713
1714 /**********************************************************************
1715  *          GetModuleName    (KERNEL.27)
1716  */
1717 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1718 {
1719     NE_MODULE *pModule;
1720     BYTE *p;
1721
1722     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1723     p = (BYTE *)pModule + pModule->name_table;
1724     if (count > *p) count = *p + 1;
1725     if (count > 0)
1726     {
1727         memcpy( buf, p + 1, count - 1 );
1728         buf[count-1] = '\0';
1729     }
1730     return TRUE;
1731 }
1732
1733
1734 /**********************************************************************
1735  *          GetModuleFileName      (KERNEL.49)
1736  *
1737  * Comment: see GetModuleFileNameA
1738  *
1739  * Even if invoked by second instance of a program,
1740  * it still returns path of first one.
1741  */
1742 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1743                                   INT16 nSize )
1744 {
1745     NE_MODULE *pModule;
1746
1747     /* Win95 does not query hModule if set to 0 !
1748      * Is this wrong or maybe Win3.1 only ? */
1749     if (!hModule) hModule = GetCurrentTask();
1750
1751     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1752     lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1753     if (pModule->expected_version >= 0x400)
1754         GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1755     TRACE("%04x -> '%s'\n", hModule, lpFileName );
1756     return strlen(lpFileName);
1757 }
1758
1759
1760 /**********************************************************************
1761  *          GetModuleUsage    (KERNEL.48)
1762  */
1763 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1764 {
1765     NE_MODULE *pModule = NE_GetPtr( hModule );
1766     return pModule ? pModule->count : 0;
1767 }
1768
1769
1770 /**********************************************************************
1771  *          GetExpWinVer    (KERNEL.167)
1772  */
1773 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1774 {
1775     NE_MODULE *pModule = NE_GetPtr( hModule );
1776     if ( !pModule ) return 0;
1777
1778     /*
1779      * For built-in modules, fake the expected version the module should
1780      * have according to the Windows version emulated by Wine
1781      */
1782     if ( !pModule->expected_version )
1783     {
1784         OSVERSIONINFOA versionInfo;
1785         versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1786
1787         if ( GetVersionExA( &versionInfo ) )
1788             pModule->expected_version =
1789                      (versionInfo.dwMajorVersion & 0xff) << 8
1790                    | (versionInfo.dwMinorVersion & 0xff);
1791     }
1792
1793     return pModule->expected_version;
1794 }
1795
1796
1797 /***********************************************************************
1798  *           WinExec     (KERNEL.166)
1799  */
1800 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1801 {
1802     LPCSTR p, args = NULL;
1803     LPCSTR name_beg, name_end;
1804     LPSTR name, cmdline;
1805     int arglen;
1806     HINSTANCE16 ret;
1807     char buffer[MAX_PATH];
1808
1809     if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1810     {
1811         name_beg = lpCmdLine+1;
1812         p = strchr ( lpCmdLine+1, '"' );
1813         if (p)
1814         {
1815             name_end = p;
1816             args = strchr ( p, ' ' );
1817         }
1818         else /* yes, even valid with trailing '"' missing */
1819             name_end = lpCmdLine+strlen(lpCmdLine);
1820     }
1821     else
1822     {
1823         name_beg = lpCmdLine;
1824         args = strchr( lpCmdLine, ' ' );
1825         name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1826     }
1827
1828     if ((name_beg == lpCmdLine) && (!args))
1829     { /* just use the original cmdline string as file name */
1830         name = (LPSTR)lpCmdLine;
1831     }
1832     else
1833     {
1834         if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1835             return ERROR_NOT_ENOUGH_MEMORY;
1836         memcpy( name, name_beg, name_end - name_beg );
1837         name[name_end - name_beg] = '\0';
1838     }
1839
1840     if (args)
1841     {
1842         args++;
1843         arglen = strlen(args);
1844         cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1845         cmdline[0] = (BYTE)arglen;
1846         strcpy( cmdline + 1, args );
1847     }
1848     else
1849     {
1850         cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1851         cmdline[0] = cmdline[1] = 0;
1852     }
1853
1854     TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1855
1856     if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1857     {
1858         LOADPARAMS16 params;
1859         WORD showCmd[2];
1860         showCmd[0] = 2;
1861         showCmd[1] = nCmdShow;
1862
1863         params.hEnvironment = 0;
1864         params.cmdLine = MapLS( cmdline );
1865         params.showCmd = MapLS( showCmd );
1866         params.reserved = 0;
1867
1868         ret = LoadModule16( buffer, &params );
1869         UnMapLS( params.cmdLine );
1870         UnMapLS( params.showCmd );
1871     }
1872     else ret = GetLastError();
1873
1874     HeapFree( GetProcessHeap(), 0, cmdline );
1875     if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1876
1877     if (ret == 21)  /* 32-bit module */
1878     {
1879         DWORD count;
1880         ReleaseThunkLock( &count );
1881         ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1882         RestoreThunkLock( count );
1883     }
1884     return ret;
1885 }
1886
1887 /***********************************************************************
1888  *           GetProcAddress   (KERNEL.50)
1889  */
1890 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1891 {
1892     WORD ordinal;
1893     FARPROC16 ret;
1894
1895     if (!hModule) hModule = GetCurrentTask();
1896     hModule = GetExePtr( hModule );
1897
1898     if (HIWORD(name) != 0)
1899     {
1900         ordinal = NE_GetOrdinal( hModule, name );
1901         TRACE("%04x '%s'\n", hModule, name );
1902     }
1903     else
1904     {
1905         ordinal = LOWORD(name);
1906         TRACE("%04x %04x\n", hModule, ordinal );
1907     }
1908     if (!ordinal) return (FARPROC16)0;
1909
1910     ret = NE_GetEntryPoint( hModule, ordinal );
1911
1912     TRACE("returning %08x\n", (UINT)ret );
1913     return ret;
1914 }
1915
1916
1917 /***************************************************************************
1918  *              HasGPHandler                    (KERNEL.338)
1919  */
1920 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1921 {
1922     HMODULE16 hModule;
1923     int gpOrdinal;
1924     SEGPTR gpPtr;
1925     GPHANDLERDEF *gpHandler;
1926
1927     if (    (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1928          && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1929          && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1930          && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1931          && (gpHandler = MapSL( gpPtr )) != NULL )
1932     {
1933         while (gpHandler->selector)
1934         {
1935             if (    SELECTOROF(address) == gpHandler->selector
1936                  && OFFSETOF(address)   >= gpHandler->rangeStart
1937                  && OFFSETOF(address)   <  gpHandler->rangeEnd  )
1938                 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1939             gpHandler++;
1940         }
1941     }
1942
1943     return 0;
1944 }
1945
1946
1947 /**********************************************************************
1948  *          GetModuleHandle    (KERNEL.47)
1949  *
1950  * Find a module from a module name.
1951  *
1952  * NOTE: The current implementation works the same way the Windows 95 one
1953  *       does. Do not try to 'fix' it, fix the callers.
1954  *       + It does not do ANY extension handling (except that strange .EXE bit)!
1955  *       + It does not care about paths, just about basenames. (same as Windows)
1956  *
1957  * RETURNS
1958  *   LOWORD:
1959  *      the win16 module handle if found
1960  *      0 if not
1961  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1962  *      Always hFirstModule
1963  */
1964 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1965 {
1966     if (HIWORD(name) == 0)
1967         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1968     return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1969 }
1970
1971 /**********************************************************************
1972  *          NE_GetModuleByFilename
1973  */
1974 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1975 {
1976     HMODULE16   hModule;
1977     LPSTR       s, p;
1978     BYTE        len, *name_table;
1979     char        tmpstr[MAX_PATH];
1980     NE_MODULE *pModule;
1981
1982     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1983
1984     /* If the base filename of 'name' matches the base filename of the module
1985      * filename of some module (case-insensitive compare):
1986      * Return its handle.
1987      */
1988
1989     /* basename: search backwards in passed name to \ / or : */
1990     s = tmpstr + strlen(tmpstr);
1991     while (s > tmpstr)
1992     {
1993         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1994                 break;
1995         s--;
1996     }
1997
1998     /* search this in loaded filename list */
1999     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2000     {
2001         char            *loadedfn;
2002         OFSTRUCT        *ofs;
2003
2004         pModule = NE_GetPtr( hModule );
2005         if (!pModule) break;
2006         if (!pModule->fileinfo) continue;
2007         if (pModule->flags & NE_FFLAGS_WIN32) continue;
2008
2009         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
2010         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
2011         /* basename: search backwards in pathname to \ / or : */
2012         while (loadedfn > (char*)ofs->szPathName)
2013         {
2014             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
2015                     break;
2016             loadedfn--;
2017         }
2018         /* case insensitive compare ... */
2019         if (!FILE_strcasecmp(loadedfn, s))
2020             return hModule;
2021     }
2022     /* If basename (without ext) matches the module name of a module:
2023      * Return its handle.
2024      */
2025
2026     if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
2027     len = strlen(s);
2028
2029     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2030     {
2031         pModule = NE_GetPtr( hModule );
2032         if (!pModule) break;
2033         if (pModule->flags & NE_FFLAGS_WIN32) continue;
2034
2035         name_table = (BYTE *)pModule + pModule->name_table;
2036         if ((*name_table == len) && !FILE_strncasecmp(s, name_table+1, len))
2037             return hModule;
2038     }
2039
2040     return 0;
2041 }
2042
2043 /***********************************************************************
2044  *           GetProcAddress16   (KERNEL32.37)
2045  * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
2046  */
2047 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
2048 {
2049     if (!hModule) return 0;
2050     if (HIWORD(hModule))
2051     {
2052         WARN("hModule is Win32 handle (%p)\n", hModule );
2053         return 0;
2054     }
2055     return GetProcAddress16( LOWORD(hModule), name );
2056 }
2057
2058 /**********************************************************************
2059  *          ModuleFirst    (TOOLHELP.59)
2060  */
2061 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
2062 {
2063     lpme->wNext = hFirstModule;
2064     return ModuleNext16( lpme );
2065 }
2066
2067
2068 /**********************************************************************
2069  *          ModuleNext    (TOOLHELP.60)
2070  */
2071 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
2072 {
2073     NE_MODULE *pModule;
2074     char *name;
2075
2076     if (!lpme->wNext) return FALSE;
2077     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
2078     name = (char *)pModule + pModule->name_table;
2079     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
2080     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
2081     lpme->hModule = lpme->wNext;
2082     lpme->wcUsage = pModule->count;
2083     lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
2084     lpme->wNext = pModule->next;
2085     return TRUE;
2086 }
2087
2088
2089 /**********************************************************************
2090  *          ModuleFindName    (TOOLHELP.61)
2091  */
2092 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
2093 {
2094     lpme->wNext = GetModuleHandle16( name );
2095     return ModuleNext16( lpme );
2096 }
2097
2098
2099 /**********************************************************************
2100  *          ModuleFindHandle    (TOOLHELP.62)
2101  */
2102 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
2103 {
2104     hModule = GetExePtr( hModule );
2105     lpme->wNext = hModule;
2106     return ModuleNext16( lpme );
2107 }
2108
2109
2110 /***************************************************************************
2111  *          IsRomModule    (KERNEL.323)
2112  */
2113 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
2114 {
2115     return FALSE;
2116 }
2117
2118 /***************************************************************************
2119  *          IsRomFile    (KERNEL.326)
2120  */
2121 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
2122 {
2123     return FALSE;
2124 }
2125
2126 /***********************************************************************
2127  *           create_dummy_module
2128  *
2129  * Create a dummy NE module for Win32 or Winelib.
2130  */
2131 static HMODULE16 create_dummy_module( HMODULE module32 )
2132 {
2133     HMODULE16 hModule;
2134     NE_MODULE *pModule;
2135     SEGTABLEENTRY *pSegment;
2136     char *pStr,*s;
2137     unsigned int len;
2138     const char* basename;
2139     OFSTRUCT *ofs;
2140     int of_size, size;
2141     char filename[MAX_PATH];
2142     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
2143
2144     if (!nt) return (HMODULE16)11;  /* invalid exe */
2145
2146     /* Extract base filename */
2147     GetModuleFileNameA( module32, filename, sizeof(filename) );
2148     basename = strrchr(filename, '\\');
2149     if (!basename) basename = filename;
2150     else basename++;
2151     len = strlen(basename);
2152     if ((s = strchr(basename, '.'))) len = s - basename;
2153
2154     /* Allocate module */
2155     of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2156                     + strlen(filename) + 1;
2157     size = sizeof(NE_MODULE) +
2158                  /* loaded file info */
2159                  ((of_size + 3) & ~3) +
2160                  /* segment table: DS,CS */
2161                  2 * sizeof(SEGTABLEENTRY) +
2162                  /* name table */
2163                  len + 2 +
2164                  /* several empty tables */
2165                  8;
2166
2167     hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2168     if (!hModule) return (HMODULE16)11;  /* invalid exe */
2169
2170     FarSetOwner16( hModule, hModule );
2171     pModule = (NE_MODULE *)GlobalLock16( hModule );
2172
2173     /* Set all used entries */
2174     pModule->magic            = IMAGE_OS2_SIGNATURE;
2175     pModule->count            = 1;
2176     pModule->next             = 0;
2177     pModule->flags            = NE_FFLAGS_WIN32;
2178     pModule->dgroup           = 0;
2179     pModule->ss               = 1;
2180     pModule->cs               = 2;
2181     pModule->heap_size        = 0;
2182     pModule->stack_size       = 0;
2183     pModule->seg_count        = 2;
2184     pModule->modref_count     = 0;
2185     pModule->nrname_size      = 0;
2186     pModule->fileinfo         = sizeof(NE_MODULE);
2187     pModule->os_flags         = NE_OSFLAGS_WINDOWS;
2188     pModule->self             = hModule;
2189     pModule->module32         = module32;
2190
2191     /* Set version and flags */
2192     pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2193                                 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2194     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2195         pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2196
2197     /* Set loaded file information */
2198     ofs = (OFSTRUCT *)(pModule + 1);
2199     memset( ofs, 0, of_size );
2200     ofs->cBytes = of_size < 256 ? of_size : 255;   /* FIXME */
2201     strcpy( ofs->szPathName, filename );
2202
2203     pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2204     pModule->seg_table = (int)pSegment - (int)pModule;
2205     /* Data segment */
2206     pSegment->size    = 0;
2207     pSegment->flags   = NE_SEGFLAGS_DATA;
2208     pSegment->minsize = 0x1000;
2209     pSegment++;
2210     /* Code segment */
2211     pSegment->flags   = 0;
2212     pSegment++;
2213
2214     /* Module name */
2215     pStr = (char *)pSegment;
2216     pModule->name_table = (int)pStr - (int)pModule;
2217     assert(len<256);
2218     *pStr = len;
2219     lstrcpynA( pStr+1, basename, len+1 );
2220     pStr += len+2;
2221
2222     /* All tables zero terminated */
2223     pModule->res_table = pModule->import_table = pModule->entry_table = (int)pStr - (int)pModule;
2224
2225     NE_RegisterModule( pModule );
2226     LoadLibraryA( filename );  /* increment the ref count of the 32-bit module */
2227     return hModule;
2228 }
2229
2230 /***********************************************************************
2231  *           PrivateLoadLibrary       (KERNEL32.@)
2232  *
2233  * FIXME: rough guesswork, don't know what "Private" means
2234  */
2235 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2236 {
2237     return LoadLibrary16(libname);
2238 }
2239
2240 /***********************************************************************
2241  *           PrivateFreeLibrary       (KERNEL32.@)
2242  *
2243  * FIXME: rough guesswork, don't know what "Private" means
2244  */
2245 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2246 {
2247     FreeLibrary16(handle);
2248 }
2249
2250 /***********************************************************************
2251  *           LoadLibrary32        (KERNEL.452)
2252  *           LoadSystemLibrary32  (KERNEL.482)
2253  */
2254 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2255 {
2256     HMODULE hModule;
2257     DWORD count;
2258
2259     ReleaseThunkLock( &count );
2260     hModule = LoadLibraryA( libname );
2261     RestoreThunkLock( count );
2262     return hModule;
2263 }
2264
2265 /***************************************************************************
2266  *              MapHModuleLS                    (KERNEL32.@)
2267  */
2268 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2269 {
2270     HMODULE16 ret;
2271     NE_MODULE *pModule;
2272
2273     if (!hmod)
2274         return TASK_GetCurrent()->hInstance;
2275     if (!HIWORD(hmod))
2276         return LOWORD(hmod); /* we already have a 16 bit module handle */
2277     pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2278     while (pModule)  {
2279         if (pModule->module32 == hmod)
2280             return pModule->self;
2281         pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2282     }
2283     if ((ret = create_dummy_module( hmod )) < 32)
2284     {
2285         SetLastError(ret);
2286         ret = 0;
2287     }
2288     return ret;
2289 }
2290
2291 /***************************************************************************
2292  *              MapHModuleSL                    (KERNEL32.@)
2293  */
2294 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2295 {
2296     NE_MODULE *pModule;
2297
2298     if (!hmod) {
2299         TDB *pTask = TASK_GetCurrent();
2300         hmod = pTask->hModule;
2301     }
2302     pModule = (NE_MODULE*)GlobalLock16(hmod);
2303     if ((pModule->magic!=IMAGE_OS2_SIGNATURE) || !(pModule->flags & NE_FFLAGS_WIN32))
2304         return 0;
2305     return pModule->module32;
2306 }
2307
2308 /***************************************************************************
2309  *              MapHInstLS                      (KERNEL32.@)
2310  *              MapHInstLS                      (KERNEL.472)
2311  */
2312 void WINAPI MapHInstLS( CONTEXT86 *context )
2313 {
2314     context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2315 }
2316
2317 /***************************************************************************
2318  *              MapHInstSL                      (KERNEL32.@)
2319  *              MapHInstSL                      (KERNEL.473)
2320  */
2321 void WINAPI MapHInstSL( CONTEXT86 *context )
2322 {
2323     context->Eax = (DWORD)MapHModuleSL( context->Eax );
2324 }
2325
2326 /***************************************************************************
2327  *              MapHInstLS_PN                   (KERNEL32.@)
2328  */
2329 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
2330 {
2331     if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2332 }
2333
2334 /***************************************************************************
2335  *              MapHInstSL_PN                   (KERNEL32.@)
2336  */
2337 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
2338 {
2339     if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );
2340 }