INT21_GetFreeDiskSpace(): The drive parameter is found in the DL
[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
1173         ERR( "loaded .so but dll %s still not found\n", dllname );
1174     }
1175     else
1176     {
1177         if (!file_exists) WARN("cannot open .so lib for 16-bit builtin %s: %s\n", name, error);
1178         else ERR("failed to load .so lib for 16-bit builtin %s: %s\n", name, error );
1179     }
1180     return (HMODULE16)2;
1181 }
1182
1183
1184 /**********************************************************************
1185  *          MODULE_LoadModule16
1186  *
1187  * Load a NE module in the order of the loadorder specification.
1188  * The caller is responsible that the module is not loaded already.
1189  *
1190  */
1191 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1192 {
1193     HINSTANCE16 hinst = 2;
1194     enum loadorder_type loadorder[LOADORDER_NTYPES];
1195     int i;
1196     const char *filetype = "";
1197     const char *ptr, *basename;
1198
1199     /* strip path information */
1200
1201     basename = libname;
1202     if (basename[0] && basename[1] == ':') basename += 2;  /* strip drive specification */
1203     if ((ptr = strrchr( basename, '\\' ))) basename = ptr + 1;
1204     if ((ptr = strrchr( basename, '/' ))) basename = ptr + 1;
1205
1206     if (is_builtin_present(basename))
1207     {
1208         TRACE( "forcing loadorder to builtin for %s\n", debugstr_a(basename) );
1209         /* force builtin loadorder since the dll is already in memory */
1210         loadorder[0] = LOADORDER_BI;
1211         loadorder[1] = LOADORDER_INVALID;
1212     }
1213     else
1214     {
1215         UNICODE_STRING pathW;
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         RtlCreateUnicodeStringFromAsciiz( &pathW, basename );
1225         MODULE_GetLoadOrderW( loadorder, p, pathW.Buffer );
1226         RtlFreeUnicodeString( &pathW );
1227     }
1228
1229     for(i = 0; i < LOADORDER_NTYPES; i++)
1230     {
1231         if (loadorder[i] == LOADORDER_INVALID) break;
1232
1233         switch(loadorder[i])
1234         {
1235         case LOADORDER_DLL:
1236             TRACE("Trying native dll '%s'\n", libname);
1237             hinst = NE_LoadModule(libname, lib_only);
1238             filetype = "native";
1239             break;
1240
1241         case LOADORDER_BI:
1242             TRACE("Trying built-in '%s'\n", libname);
1243             hinst = NE_LoadBuiltinModule(libname);
1244             filetype = "builtin";
1245             break;
1246
1247         default:
1248             hinst = 2;
1249             break;
1250         }
1251
1252         if(hinst >= 32)
1253         {
1254             TRACE_(loaddll)("Loaded module '%s' : %s\n", libname, filetype);
1255             if(!implicit)
1256             {
1257                 HMODULE16 hModule;
1258                 NE_MODULE *pModule;
1259
1260                 hModule = GetModuleHandle16(libname);
1261                 if(!hModule)
1262                 {
1263                     ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1264                         libname, hinst);
1265                     return 6;   /* ERROR_INVALID_HANDLE seems most appropriate */
1266                 }
1267
1268                 pModule = NE_GetPtr(hModule);
1269                 if(!pModule)
1270                 {
1271                     ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1272                         libname, hinst);
1273                     return 6;   /* ERROR_INVALID_HANDLE seems most appropriate */
1274                 }
1275
1276                 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1277
1278                 /*
1279                  * Call initialization routines for all loaded DLLs. Note that
1280                  * when we load implicitly linked DLLs this will be done by InitTask().
1281                  */
1282                 if(pModule->flags & NE_FFLAGS_LIBMODULE)
1283                 {
1284                     NE_InitializeDLLs(hModule);
1285                     NE_DllProcessAttach(hModule);
1286                 }
1287             }
1288             return hinst;
1289         }
1290
1291         if(hinst != 2)
1292         {
1293             /* We quit searching when we get another error than 'File not found' */
1294             break;
1295         }
1296     }
1297     return hinst;       /* The last error that occurred */
1298 }
1299
1300
1301 /**********************************************************************
1302  *          NE_CreateThread
1303  *
1304  * Create the thread for a 16-bit module.
1305  */
1306 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1307 {
1308     HANDLE hThread;
1309     TDB *pTask;
1310     HTASK16 hTask;
1311     HINSTANCE16 instance = 0;
1312
1313     if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1314         return 0;
1315
1316     /* Post event to start the task */
1317     PostEvent16( hTask );
1318
1319     /* Wait until we get the instance handle */
1320     do
1321     {
1322         DirectedYield16( hTask );
1323         if (!IsTask16( hTask ))  /* thread has died */
1324         {
1325             DWORD exit_code;
1326             WaitForSingleObject( hThread, INFINITE );
1327             GetExitCodeThread( hThread, &exit_code );
1328             CloseHandle( hThread );
1329             return exit_code;
1330         }
1331         if (!(pTask = GlobalLock16( hTask ))) break;
1332         instance = pTask->hInstance;
1333         GlobalUnlock16( hTask );
1334     } while (!instance);
1335
1336     CloseHandle( hThread );
1337     return instance;
1338 }
1339
1340
1341 /**********************************************************************
1342  *          LoadModule      (KERNEL.45)
1343  */
1344 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1345 {
1346     BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1347     LOADPARAMS16 *params;
1348     HMODULE16 hModule;
1349     NE_MODULE *pModule;
1350     LPSTR cmdline;
1351     WORD cmdShow;
1352
1353     /* Load module */
1354
1355     if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1356     {
1357         /* Special case: second instance of an already loaded NE module */
1358
1359         if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1360         if ( pModule->module32 ) return (HINSTANCE16)21;
1361
1362         /* Increment refcount */
1363
1364         pModule->count++;
1365     }
1366     else
1367     {
1368         /* Main case: load first instance of NE module */
1369
1370         if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1371             return hModule;
1372
1373         if ( !(pModule = NE_GetPtr( hModule )) )
1374             return (HINSTANCE16)11;
1375     }
1376
1377     /* If library module, we just retrieve the instance handle */
1378
1379     if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1380         return NE_GetInstance( pModule );
1381
1382     /*
1383      *  At this point, we need to create a new process.
1384      *
1385      *  pModule points either to an already loaded module, whose refcount
1386      *  has already been incremented (to avoid having the module vanish
1387      *  in the meantime), or else to a stub module which contains only header
1388      *  information.
1389      */
1390     params = (LOADPARAMS16 *)paramBlock;
1391     cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1392     cmdline = MapSL( params->cmdLine );
1393     return NE_CreateThread( pModule, cmdShow, cmdline );
1394 }
1395
1396
1397 /**********************************************************************
1398  *          NE_StartTask
1399  *
1400  * Startup code for a new 16-bit task.
1401  */
1402 DWORD NE_StartTask(void)
1403 {
1404     TDB *pTask = TASK_GetCurrent();
1405     NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1406     HINSTANCE16 hInstance, hPrevInstance;
1407     SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1408     WORD sp;
1409
1410     if ( pModule->count > 0 )
1411     {
1412         /* Second instance of an already loaded NE module */
1413         /* Note that the refcount was already incremented by the parent */
1414
1415         hPrevInstance = NE_GetInstance( pModule );
1416
1417         if ( pModule->dgroup )
1418             if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1419                 NE_LoadSegment( pModule, pModule->dgroup );
1420
1421         hInstance = NE_GetInstance( pModule );
1422         TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1423
1424     }
1425     else
1426     {
1427         /* Load first instance of NE module */
1428
1429         pModule->flags |= NE_FFLAGS_GUI;  /* FIXME: is this necessary? */
1430
1431         hInstance = NE_DoLoadModule( pModule );
1432         hPrevInstance = 0;
1433     }
1434
1435     if ( hInstance >= 32 )
1436     {
1437         CONTEXT86 context;
1438
1439         /* Enter instance handles into task struct */
1440
1441         pTask->hInstance = hInstance;
1442         pTask->hPrevInstance = hPrevInstance;
1443
1444         /* Use DGROUP for 16-bit stack */
1445
1446         if (!(sp = pModule->sp))
1447             sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1448         sp &= ~1;
1449         sp -= sizeof(STACK16FRAME);
1450         NtCurrentTeb()->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1451
1452         /* Registers at initialization must be:
1453          * ax   zero
1454          * bx   stack size in bytes
1455          * cx   heap size in bytes
1456          * si   previous app instance
1457          * di   current app instance
1458          * bp   zero
1459          * es   selector to the PSP
1460          * ds   dgroup of the application
1461          * ss   stack selector
1462          * sp   top of the stack
1463          */
1464         memset( &context, 0, sizeof(context) );
1465         context.SegCs  = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1466         context.SegDs  = GlobalHandleToSel16(pTask->hInstance);
1467         context.SegEs  = pTask->hPDB;
1468         context.SegFs  = wine_get_fs();
1469         context.SegGs  = wine_get_gs();
1470         context.Eip    = pModule->ip;
1471         context.Ebx    = pModule->stack_size;
1472         context.Ecx    = pModule->heap_size;
1473         context.Edi    = pTask->hInstance;
1474         context.Esi    = pTask->hPrevInstance;
1475
1476         /* Now call 16-bit entry point */
1477
1478         TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1479               context.SegCs, context.Eip, context.SegDs,
1480               SELECTOROF(NtCurrentTeb()->cur_stack),
1481               OFFSETOF(NtCurrentTeb()->cur_stack) );
1482
1483         WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1484         ExitThread( LOWORD(context.Eax) );
1485     }
1486     return hInstance;  /* error code */
1487 }
1488
1489 /***********************************************************************
1490  *           LoadLibrary     (KERNEL.95)
1491  *           LoadLibrary16   (KERNEL32.35)
1492  */
1493 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1494 {
1495     return LoadModule16(libname, (LPVOID)-1 );
1496 }
1497
1498
1499 /**********************************************************************
1500  *          MODULE_CallWEP
1501  *
1502  * Call a DLL's WEP, allowing it to shut down.
1503  * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1504  */
1505 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1506 {
1507     BOOL16 ret;
1508     FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1509     if (!WEP) return FALSE;
1510
1511     __TRY
1512     {
1513         WORD args[1];
1514         DWORD dwRet;
1515
1516         args[0] = WEP_FREE_DLL;
1517         WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1518         ret = LOWORD(dwRet);
1519     }
1520     __EXCEPT(page_fault)
1521     {
1522         WARN("Page fault\n");
1523         ret = 0;
1524     }
1525     __ENDTRY
1526
1527     return ret;
1528 }
1529
1530
1531 /**********************************************************************
1532  *          NE_FreeModule
1533  *
1534  * Implementation of FreeModule16().
1535  */
1536 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1537 {
1538     HMODULE16 *hPrevModule;
1539     NE_MODULE *pModule;
1540     HMODULE16 *pModRef;
1541     int i;
1542
1543     if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1544     hModule = pModule->self;
1545
1546     TRACE("%04x count %d\n", hModule, pModule->count );
1547
1548     if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1549     else pModule->count = 0;
1550
1551     if (pModule->flags & NE_FFLAGS_BUILTIN)
1552         return FALSE;  /* Can't free built-in module */
1553
1554     if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1555     {
1556         /* Free the objects owned by the DLL module */
1557         NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1558
1559         if (pModule->flags & NE_FFLAGS_LIBMODULE)
1560             MODULE_CallWEP( hModule );
1561         else
1562             call_wep = FALSE;  /* We are freeing a task -> no more WEPs */
1563     }
1564
1565
1566     /* Clear magic number just in case */
1567
1568     pModule->magic = pModule->self = 0;
1569     if (pModule->fd) CloseHandle( pModule->fd );
1570
1571       /* Remove it from the linked list */
1572
1573     hPrevModule = &hFirstModule;
1574     while (*hPrevModule && (*hPrevModule != hModule))
1575     {
1576         hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1577     }
1578     if (*hPrevModule) *hPrevModule = pModule->next;
1579
1580     /* Free the referenced modules */
1581
1582     pModRef = (HMODULE16*)((char *)pModule + pModule->modref_table);
1583     for (i = 0; i < pModule->modref_count; i++, pModRef++)
1584     {
1585         NE_FreeModule( *pModRef, call_wep );
1586     }
1587
1588     /* Free the module storage */
1589
1590     GlobalFreeAll16( hModule );
1591     return TRUE;
1592 }
1593
1594
1595 /**********************************************************************
1596  *          FreeModule    (KERNEL.46)
1597  */
1598 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1599 {
1600     return NE_FreeModule( hModule, TRUE );
1601 }
1602
1603
1604 /***********************************************************************
1605  *           FreeLibrary     (KERNEL.96)
1606  *           FreeLibrary16   (KERNEL32.36)
1607  */
1608 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1609 {
1610     TRACE("%04x\n", handle );
1611     FreeModule16( handle );
1612 }
1613
1614
1615 /***********************************************************************
1616  *          GetModuleHandle16 (KERNEL32.@)
1617  */
1618 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1619 {
1620     HMODULE16   hModule = hFirstModule;
1621     LPSTR       s;
1622     BYTE        len, *name_table;
1623     char        tmpstr[MAX_PATH];
1624     NE_MODULE *pModule;
1625
1626     TRACE("(%s)\n", name);
1627
1628     if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1629
1630     len = strlen(name);
1631     if (!len) return 0;
1632
1633     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1634
1635     /* If 'name' matches exactly the module name of a module:
1636      * Return its handle.
1637      */
1638     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1639     {
1640         pModule = NE_GetPtr( hModule );
1641         if (!pModule) break;
1642         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1643
1644         name_table = (BYTE *)pModule + pModule->name_table;
1645         if ((*name_table == len) && !strncmp(name, name_table+1, len))
1646             return hModule;
1647     }
1648
1649     /* If uppercased 'name' matches exactly the module name of a module:
1650      * Return its handle
1651      */
1652     for (s = tmpstr; *s; s++) *s = FILE_toupper(*s);
1653
1654     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1655     {
1656         pModule = NE_GetPtr( hModule );
1657         if (!pModule) break;
1658         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1659
1660         name_table = (BYTE *)pModule + pModule->name_table;
1661         /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1662          * but case sensitive! (Unfortunately Winword 6 and subdlls have
1663          * lowercased module names, but try to load uppercase DLLs, so this
1664          * 'i' compare is just a quickfix until the loader handles that
1665          * correctly. -MM 990705
1666          */
1667         if ((*name_table == len) && !FILE_strncasecmp(tmpstr, name_table+1, len))
1668             return hModule;
1669     }
1670
1671     /* If the base filename of 'name' matches the base filename of the module
1672      * filename of some module (case-insensitive compare):
1673      * Return its handle.
1674      */
1675
1676     /* basename: search backwards in passed name to \ / or : */
1677     s = tmpstr + strlen(tmpstr);
1678     while (s > tmpstr)
1679     {
1680         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1681                 break;
1682         s--;
1683     }
1684
1685     /* search this in loaded filename list */
1686     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1687     {
1688         char            *loadedfn;
1689         OFSTRUCT        *ofs;
1690
1691         pModule = NE_GetPtr( hModule );
1692         if (!pModule) break;
1693         if (!pModule->fileinfo) continue;
1694         if (pModule->flags & NE_FFLAGS_WIN32) continue;
1695
1696         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1697         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1698         /* basename: search backwards in pathname to \ / or : */
1699         while (loadedfn > (char*)ofs->szPathName)
1700         {
1701             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1702                     break;
1703             loadedfn--;
1704         }
1705         /* case insensitive compare ... */
1706         if (!FILE_strcasecmp(loadedfn, s))
1707             return hModule;
1708     }
1709     return 0;
1710 }
1711
1712
1713 /**********************************************************************
1714  *          GetModuleName    (KERNEL.27)
1715  */
1716 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1717 {
1718     NE_MODULE *pModule;
1719     BYTE *p;
1720
1721     if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1722     p = (BYTE *)pModule + pModule->name_table;
1723     if (count > *p) count = *p + 1;
1724     if (count > 0)
1725     {
1726         memcpy( buf, p + 1, count - 1 );
1727         buf[count-1] = '\0';
1728     }
1729     return TRUE;
1730 }
1731
1732
1733 /**********************************************************************
1734  *          GetModuleFileName      (KERNEL.49)
1735  *
1736  * Comment: see GetModuleFileNameA
1737  *
1738  * Even if invoked by second instance of a program,
1739  * it still returns path of first one.
1740  */
1741 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1742                                   INT16 nSize )
1743 {
1744     NE_MODULE *pModule;
1745
1746     /* Win95 does not query hModule if set to 0 !
1747      * Is this wrong or maybe Win3.1 only ? */
1748     if (!hModule) hModule = GetCurrentTask();
1749
1750     if (!(pModule = NE_GetPtr( hModule ))) return 0;
1751     lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1752     if (pModule->expected_version >= 0x400)
1753         GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1754     TRACE("%04x -> '%s'\n", hModule, lpFileName );
1755     return strlen(lpFileName);
1756 }
1757
1758
1759 /**********************************************************************
1760  *          GetModuleUsage    (KERNEL.48)
1761  */
1762 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1763 {
1764     NE_MODULE *pModule = NE_GetPtr( hModule );
1765     return pModule ? pModule->count : 0;
1766 }
1767
1768
1769 /**********************************************************************
1770  *          GetExpWinVer    (KERNEL.167)
1771  */
1772 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1773 {
1774     NE_MODULE *pModule = NE_GetPtr( hModule );
1775     if ( !pModule ) return 0;
1776
1777     /*
1778      * For built-in modules, fake the expected version the module should
1779      * have according to the Windows version emulated by Wine
1780      */
1781     if ( !pModule->expected_version )
1782     {
1783         OSVERSIONINFOA versionInfo;
1784         versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1785
1786         if ( GetVersionExA( &versionInfo ) )
1787             pModule->expected_version =
1788                      (versionInfo.dwMajorVersion & 0xff) << 8
1789                    | (versionInfo.dwMinorVersion & 0xff);
1790     }
1791
1792     return pModule->expected_version;
1793 }
1794
1795
1796 /***********************************************************************
1797  *           WinExec     (KERNEL.166)
1798  */
1799 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1800 {
1801     LPCSTR p, args = NULL;
1802     LPCSTR name_beg, name_end;
1803     LPSTR name, cmdline;
1804     int arglen;
1805     HINSTANCE16 ret;
1806     char buffer[MAX_PATH];
1807
1808     if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1809     {
1810         name_beg = lpCmdLine+1;
1811         p = strchr ( lpCmdLine+1, '"' );
1812         if (p)
1813         {
1814             name_end = p;
1815             args = strchr ( p, ' ' );
1816         }
1817         else /* yes, even valid with trailing '"' missing */
1818             name_end = lpCmdLine+strlen(lpCmdLine);
1819     }
1820     else
1821     {
1822         name_beg = lpCmdLine;
1823         args = strchr( lpCmdLine, ' ' );
1824         name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1825     }
1826
1827     if ((name_beg == lpCmdLine) && (!args))
1828     { /* just use the original cmdline string as file name */
1829         name = (LPSTR)lpCmdLine;
1830     }
1831     else
1832     {
1833         if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1834             return ERROR_NOT_ENOUGH_MEMORY;
1835         memcpy( name, name_beg, name_end - name_beg );
1836         name[name_end - name_beg] = '\0';
1837     }
1838
1839     if (args)
1840     {
1841         args++;
1842         arglen = strlen(args);
1843         cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1844         cmdline[0] = (BYTE)arglen;
1845         strcpy( cmdline + 1, args );
1846     }
1847     else
1848     {
1849         cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1850         cmdline[0] = cmdline[1] = 0;
1851     }
1852
1853     TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1854
1855     if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1856     {
1857         LOADPARAMS16 params;
1858         WORD showCmd[2];
1859         showCmd[0] = 2;
1860         showCmd[1] = nCmdShow;
1861
1862         params.hEnvironment = 0;
1863         params.cmdLine = MapLS( cmdline );
1864         params.showCmd = MapLS( showCmd );
1865         params.reserved = 0;
1866
1867         ret = LoadModule16( buffer, &params );
1868         UnMapLS( params.cmdLine );
1869         UnMapLS( params.showCmd );
1870     }
1871     else ret = GetLastError();
1872
1873     HeapFree( GetProcessHeap(), 0, cmdline );
1874     if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1875
1876     if (ret == 21)  /* 32-bit module */
1877     {
1878         DWORD count;
1879         ReleaseThunkLock( &count );
1880         ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1881         RestoreThunkLock( count );
1882     }
1883     return ret;
1884 }
1885
1886 /***********************************************************************
1887  *           GetProcAddress   (KERNEL.50)
1888  */
1889 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1890 {
1891     WORD ordinal;
1892     FARPROC16 ret;
1893
1894     if (!hModule) hModule = GetCurrentTask();
1895     hModule = GetExePtr( hModule );
1896
1897     if (HIWORD(name) != 0)
1898     {
1899         ordinal = NE_GetOrdinal( hModule, name );
1900         TRACE("%04x '%s'\n", hModule, name );
1901     }
1902     else
1903     {
1904         ordinal = LOWORD(name);
1905         TRACE("%04x %04x\n", hModule, ordinal );
1906     }
1907     if (!ordinal) return (FARPROC16)0;
1908
1909     ret = NE_GetEntryPoint( hModule, ordinal );
1910
1911     TRACE("returning %08x\n", (UINT)ret );
1912     return ret;
1913 }
1914
1915
1916 /***************************************************************************
1917  *              HasGPHandler                    (KERNEL.338)
1918  */
1919 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1920 {
1921     HMODULE16 hModule;
1922     int gpOrdinal;
1923     SEGPTR gpPtr;
1924     GPHANDLERDEF *gpHandler;
1925
1926     if (    (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1927          && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1928          && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1929          && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1930          && (gpHandler = MapSL( gpPtr )) != NULL )
1931     {
1932         while (gpHandler->selector)
1933         {
1934             if (    SELECTOROF(address) == gpHandler->selector
1935                  && OFFSETOF(address)   >= gpHandler->rangeStart
1936                  && OFFSETOF(address)   <  gpHandler->rangeEnd  )
1937                 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1938             gpHandler++;
1939         }
1940     }
1941
1942     return 0;
1943 }
1944
1945
1946 /**********************************************************************
1947  *          GetModuleHandle    (KERNEL.47)
1948  *
1949  * Find a module from a module name.
1950  *
1951  * NOTE: The current implementation works the same way the Windows 95 one
1952  *       does. Do not try to 'fix' it, fix the callers.
1953  *       + It does not do ANY extension handling (except that strange .EXE bit)!
1954  *       + It does not care about paths, just about basenames. (same as Windows)
1955  *
1956  * RETURNS
1957  *   LOWORD:
1958  *      the win16 module handle if found
1959  *      0 if not
1960  *   HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1961  *      Always hFirstModule
1962  */
1963 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1964 {
1965     if (HIWORD(name) == 0)
1966         return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1967     return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1968 }
1969
1970 /**********************************************************************
1971  *          NE_GetModuleByFilename
1972  */
1973 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1974 {
1975     HMODULE16   hModule;
1976     LPSTR       s, p;
1977     BYTE        len, *name_table;
1978     char        tmpstr[MAX_PATH];
1979     NE_MODULE *pModule;
1980
1981     lstrcpynA(tmpstr, name, sizeof(tmpstr));
1982
1983     /* If the base filename of 'name' matches the base filename of the module
1984      * filename of some module (case-insensitive compare):
1985      * Return its handle.
1986      */
1987
1988     /* basename: search backwards in passed name to \ / or : */
1989     s = tmpstr + strlen(tmpstr);
1990     while (s > tmpstr)
1991     {
1992         if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1993                 break;
1994         s--;
1995     }
1996
1997     /* search this in loaded filename list */
1998     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1999     {
2000         char            *loadedfn;
2001         OFSTRUCT        *ofs;
2002
2003         pModule = NE_GetPtr( hModule );
2004         if (!pModule) break;
2005         if (!pModule->fileinfo) continue;
2006         if (pModule->flags & NE_FFLAGS_WIN32) continue;
2007
2008         ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
2009         loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
2010         /* basename: search backwards in pathname to \ / or : */
2011         while (loadedfn > (char*)ofs->szPathName)
2012         {
2013             if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
2014                     break;
2015             loadedfn--;
2016         }
2017         /* case insensitive compare ... */
2018         if (!FILE_strcasecmp(loadedfn, s))
2019             return hModule;
2020     }
2021     /* If basename (without ext) matches the module name of a module:
2022      * Return its handle.
2023      */
2024
2025     if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
2026     len = strlen(s);
2027
2028     for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2029     {
2030         pModule = NE_GetPtr( hModule );
2031         if (!pModule) break;
2032         if (pModule->flags & NE_FFLAGS_WIN32) continue;
2033
2034         name_table = (BYTE *)pModule + pModule->name_table;
2035         if ((*name_table == len) && !FILE_strncasecmp(s, name_table+1, len))
2036             return hModule;
2037     }
2038
2039     return 0;
2040 }
2041
2042 /***********************************************************************
2043  *           GetProcAddress16   (KERNEL32.37)
2044  * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
2045  */
2046 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
2047 {
2048     if (!hModule) return 0;
2049     if (HIWORD(hModule))
2050     {
2051         WARN("hModule is Win32 handle (%p)\n", hModule );
2052         return 0;
2053     }
2054     return GetProcAddress16( LOWORD(hModule), name );
2055 }
2056
2057 /**********************************************************************
2058  *          ModuleFirst    (TOOLHELP.59)
2059  */
2060 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
2061 {
2062     lpme->wNext = hFirstModule;
2063     return ModuleNext16( lpme );
2064 }
2065
2066
2067 /**********************************************************************
2068  *          ModuleNext    (TOOLHELP.60)
2069  */
2070 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
2071 {
2072     NE_MODULE *pModule;
2073     char *name;
2074
2075     if (!lpme->wNext) return FALSE;
2076     if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
2077     name = (char *)pModule + pModule->name_table;
2078     memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
2079     lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
2080     lpme->hModule = lpme->wNext;
2081     lpme->wcUsage = pModule->count;
2082     lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
2083     lpme->wNext = pModule->next;
2084     return TRUE;
2085 }
2086
2087
2088 /**********************************************************************
2089  *          ModuleFindName    (TOOLHELP.61)
2090  */
2091 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
2092 {
2093     lpme->wNext = GetModuleHandle16( name );
2094     return ModuleNext16( lpme );
2095 }
2096
2097
2098 /**********************************************************************
2099  *          ModuleFindHandle    (TOOLHELP.62)
2100  */
2101 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
2102 {
2103     hModule = GetExePtr( hModule );
2104     lpme->wNext = hModule;
2105     return ModuleNext16( lpme );
2106 }
2107
2108
2109 /***************************************************************************
2110  *          IsRomModule    (KERNEL.323)
2111  */
2112 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
2113 {
2114     return FALSE;
2115 }
2116
2117 /***************************************************************************
2118  *          IsRomFile    (KERNEL.326)
2119  */
2120 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
2121 {
2122     return FALSE;
2123 }
2124
2125 /***********************************************************************
2126  *           create_dummy_module
2127  *
2128  * Create a dummy NE module for Win32 or Winelib.
2129  */
2130 static HMODULE16 create_dummy_module( HMODULE module32 )
2131 {
2132     HMODULE16 hModule;
2133     NE_MODULE *pModule;
2134     SEGTABLEENTRY *pSegment;
2135     char *pStr,*s;
2136     unsigned int len;
2137     const char* basename;
2138     OFSTRUCT *ofs;
2139     int of_size, size;
2140     char filename[MAX_PATH];
2141     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
2142
2143     if (!nt) return (HMODULE16)11;  /* invalid exe */
2144
2145     /* Extract base filename */
2146     GetModuleFileNameA( module32, filename, sizeof(filename) );
2147     basename = strrchr(filename, '\\');
2148     if (!basename) basename = filename;
2149     else basename++;
2150     len = strlen(basename);
2151     if ((s = strchr(basename, '.'))) len = s - basename;
2152
2153     /* Allocate module */
2154     of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2155                     + strlen(filename) + 1;
2156     size = sizeof(NE_MODULE) +
2157                  /* loaded file info */
2158                  ((of_size + 3) & ~3) +
2159                  /* segment table: DS,CS */
2160                  2 * sizeof(SEGTABLEENTRY) +
2161                  /* name table */
2162                  len + 2 +
2163                  /* several empty tables */
2164                  8;
2165
2166     hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2167     if (!hModule) return (HMODULE16)11;  /* invalid exe */
2168
2169     FarSetOwner16( hModule, hModule );
2170     pModule = (NE_MODULE *)GlobalLock16( hModule );
2171
2172     /* Set all used entries */
2173     pModule->magic            = IMAGE_OS2_SIGNATURE;
2174     pModule->count            = 1;
2175     pModule->next             = 0;
2176     pModule->flags            = NE_FFLAGS_WIN32;
2177     pModule->dgroup           = 0;
2178     pModule->ss               = 1;
2179     pModule->cs               = 2;
2180     pModule->heap_size        = 0;
2181     pModule->stack_size       = 0;
2182     pModule->seg_count        = 2;
2183     pModule->modref_count     = 0;
2184     pModule->nrname_size      = 0;
2185     pModule->fileinfo         = sizeof(NE_MODULE);
2186     pModule->os_flags         = NE_OSFLAGS_WINDOWS;
2187     pModule->self             = hModule;
2188     pModule->module32         = module32;
2189
2190     /* Set version and flags */
2191     pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2192                                 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2193     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2194         pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2195
2196     /* Set loaded file information */
2197     ofs = (OFSTRUCT *)(pModule + 1);
2198     memset( ofs, 0, of_size );
2199     ofs->cBytes = of_size < 256 ? of_size : 255;   /* FIXME */
2200     strcpy( ofs->szPathName, filename );
2201
2202     pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2203     pModule->seg_table = (int)pSegment - (int)pModule;
2204     /* Data segment */
2205     pSegment->size    = 0;
2206     pSegment->flags   = NE_SEGFLAGS_DATA;
2207     pSegment->minsize = 0x1000;
2208     pSegment++;
2209     /* Code segment */
2210     pSegment->flags   = 0;
2211     pSegment++;
2212
2213     /* Module name */
2214     pStr = (char *)pSegment;
2215     pModule->name_table = (int)pStr - (int)pModule;
2216     assert(len<256);
2217     *pStr = len;
2218     lstrcpynA( pStr+1, basename, len+1 );
2219     pStr += len+2;
2220
2221     /* All tables zero terminated */
2222     pModule->res_table = pModule->import_table = pModule->entry_table = (int)pStr - (int)pModule;
2223
2224     NE_RegisterModule( pModule );
2225     LoadLibraryA( filename );  /* increment the ref count of the 32-bit module */
2226     return hModule;
2227 }
2228
2229 /***********************************************************************
2230  *           PrivateLoadLibrary       (KERNEL32.@)
2231  *
2232  * FIXME: rough guesswork, don't know what "Private" means
2233  */
2234 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2235 {
2236     return LoadLibrary16(libname);
2237 }
2238
2239 /***********************************************************************
2240  *           PrivateFreeLibrary       (KERNEL32.@)
2241  *
2242  * FIXME: rough guesswork, don't know what "Private" means
2243  */
2244 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2245 {
2246     FreeLibrary16(handle);
2247 }
2248
2249 /***********************************************************************
2250  *           LoadLibrary32        (KERNEL.452)
2251  *           LoadSystemLibrary32  (KERNEL.482)
2252  */
2253 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2254 {
2255     HMODULE hModule;
2256     DWORD count;
2257
2258     ReleaseThunkLock( &count );
2259     hModule = LoadLibraryA( libname );
2260     RestoreThunkLock( count );
2261     return hModule;
2262 }
2263
2264 /***************************************************************************
2265  *              MapHModuleLS                    (KERNEL32.@)
2266  */
2267 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2268 {
2269     HMODULE16 ret;
2270     NE_MODULE *pModule;
2271
2272     if (!hmod)
2273         return TASK_GetCurrent()->hInstance;
2274     if (!HIWORD(hmod))
2275         return LOWORD(hmod); /* we already have a 16 bit module handle */
2276     pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2277     while (pModule)  {
2278         if (pModule->module32 == hmod)
2279             return pModule->self;
2280         pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2281     }
2282     if ((ret = create_dummy_module( hmod )) < 32)
2283     {
2284         SetLastError(ret);
2285         ret = 0;
2286     }
2287     return ret;
2288 }
2289
2290 /***************************************************************************
2291  *              MapHModuleSL                    (KERNEL32.@)
2292  */
2293 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2294 {
2295     NE_MODULE *pModule;
2296
2297     if (!hmod) {
2298         TDB *pTask = TASK_GetCurrent();
2299         hmod = pTask->hModule;
2300     }
2301     pModule = (NE_MODULE*)GlobalLock16(hmod);
2302     if ((pModule->magic!=IMAGE_OS2_SIGNATURE) || !(pModule->flags & NE_FFLAGS_WIN32))
2303         return 0;
2304     return pModule->module32;
2305 }
2306
2307 /***************************************************************************
2308  *              MapHInstLS                      (KERNEL32.@)
2309  *              MapHInstLS                      (KERNEL.472)
2310  */
2311 void WINAPI MapHInstLS( CONTEXT86 *context )
2312 {
2313     context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2314 }
2315
2316 /***************************************************************************
2317  *              MapHInstSL                      (KERNEL32.@)
2318  *              MapHInstSL                      (KERNEL.473)
2319  */
2320 void WINAPI MapHInstSL( CONTEXT86 *context )
2321 {
2322     context->Eax = (DWORD)MapHModuleSL( context->Eax );
2323 }
2324
2325 /***************************************************************************
2326  *              MapHInstLS_PN                   (KERNEL32.@)
2327  */
2328 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
2329 {
2330     if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2331 }
2332
2333 /***************************************************************************
2334  *              MapHInstSL_PN                   (KERNEL32.@)
2335  */
2336 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
2337 {
2338     if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );
2339 }