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