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