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