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