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