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