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