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