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