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