Sample rate sanity check.
[wine.git] / dlls / kernel / ne_module.c
blobad94116c7b9d8f4e06fe426bfe3d2c4590f81ca7
1 /*
2 * NE modules
4 * Copyright 1995 Alexandre Julliard
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.
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.
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
21 #include "config.h"
22 #include "wine/port.h"
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>
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 "module.h"
42 #include "toolhelp.h"
43 #include "builtin16.h"
44 #include "stackframe.h"
45 #include "excpt.h"
46 #include "kernel_private.h"
47 #include "wine/unicode.h"
48 #include "wine/exception.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(module);
52 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
54 #include "pshpack1.h"
55 typedef struct _GPHANDLERDEF
57 WORD selector;
58 WORD rangeStart;
59 WORD rangeEnd;
60 WORD handler;
61 } GPHANDLERDEF;
62 #include "poppack.h"
65 * Segment table entry
67 struct ne_segment_table_entry_s
69 WORD seg_data_offset; /* Sector offset of segment data */
70 WORD seg_data_length; /* Length of segment data */
71 WORD seg_flags; /* Flags associated with this segment */
72 WORD min_alloc; /* Minimum allocation size for this */
75 #define hFirstModule (pThhook->hExeHead)
77 typedef struct
79 void *module_start; /* 32-bit address of the module data */
80 int module_size; /* Size of the module data */
81 void *code_start; /* 32-bit address of DLL code */
82 void *data_start; /* 32-bit address of DLL data */
83 const char *owner; /* 32-bit dll that contains this dll */
84 const void *rsrc; /* resources data */
85 } BUILTIN16_DESCRIPTOR;
87 /* Table of all built-in DLLs */
89 #define MAX_DLLS 50
91 static const BUILTIN16_DESCRIPTOR *builtin_dlls[MAX_DLLS];
93 extern void SNOOP16_RegisterDLL(NE_MODULE*,LPCSTR);
94 extern FARPROC16 SNOOP16_GetProcAddress16(HMODULE16,DWORD,FARPROC16);
96 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
97 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
99 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
101 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
104 static WINE_EXCEPTION_FILTER(page_fault)
106 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
107 GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
108 return EXCEPTION_EXECUTE_HANDLER;
109 return EXCEPTION_CONTINUE_SEARCH;
113 /* patch all the flat cs references of the code segment if necessary */
114 inline static void patch_code_segment( void *code_segment )
116 #ifdef __i386__
117 CALLFROM16 *call = code_segment;
118 if (call->flatcs == wine_get_cs()) return; /* nothing to patch */
119 while (call->pushl == 0x68)
121 call->flatcs = wine_get_cs();
122 call++;
124 #endif
128 /***********************************************************************
129 * NE_strcasecmp
131 * locale-independent case conversion for module lookups
133 static int NE_strcasecmp( const char *str1, const char *str2 )
135 int ret = 0;
136 for ( ; ; str1++, str2++)
137 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
138 return ret;
142 /***********************************************************************
143 * NE_strncasecmp
145 * locale-independent case conversion for module lookups
147 static int NE_strncasecmp( const char *str1, const char *str2, int len )
149 int ret = 0;
150 for ( ; len > 0; len--, str1++, str2++)
151 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
152 return ret;
156 /***********************************************************************
157 * find_dll_descr
159 * Find a descriptor in the list
161 static const BUILTIN16_DESCRIPTOR *find_dll_descr( const char *dllname )
163 int i;
164 for (i = 0; i < MAX_DLLS; i++)
166 const BUILTIN16_DESCRIPTOR *descr = builtin_dlls[i];
167 if (descr)
169 NE_MODULE *pModule = (NE_MODULE *)descr->module_start;
170 OFSTRUCT *pOfs = (OFSTRUCT *)((LPBYTE)pModule + pModule->fileinfo);
171 BYTE *name_table = (BYTE *)pModule + pModule->name_table;
173 /* check the dll file name */
174 if (!NE_strcasecmp( pOfs->szPathName, dllname )) return descr;
175 /* check the dll module name (without extension) */
176 if (!NE_strncasecmp( dllname, name_table+1, *name_table ) &&
177 !strcmp( dllname + *name_table, ".dll" ))
178 return descr;
181 return NULL;
185 /***********************************************************************
186 * __wine_register_dll_16 (KERNEL32.@)
188 * Register a built-in DLL descriptor.
190 void __wine_register_dll_16( const BUILTIN16_DESCRIPTOR *descr )
192 int i;
194 for (i = 0; i < MAX_DLLS; i++)
196 if (builtin_dlls[i]) continue;
197 builtin_dlls[i] = descr;
198 break;
200 assert( i < MAX_DLLS );
204 /***********************************************************************
205 * __wine_unregister_dll_16 (KERNEL32.@)
207 * Unregister a built-in DLL descriptor.
209 void __wine_unregister_dll_16( const BUILTIN16_DESCRIPTOR *descr )
211 int i;
213 for (i = 0; i < MAX_DLLS; i++)
215 if (builtin_dlls[i] != descr) continue;
216 builtin_dlls[i] = NULL;
217 break;
222 /***********************************************************************
223 * NE_GetPtr
225 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
227 return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
231 /**********************************************************************
232 * NE_RegisterModule
234 static void NE_RegisterModule( NE_MODULE *pModule )
236 pModule->next = hFirstModule;
237 hFirstModule = pModule->self;
241 /***********************************************************************
242 * NE_DumpModule
244 void NE_DumpModule( HMODULE16 hModule )
246 int i, ordinal;
247 SEGTABLEENTRY *pSeg;
248 BYTE *pstr;
249 WORD *pword;
250 NE_MODULE *pModule;
251 ET_BUNDLE *bundle;
252 ET_ENTRY *entry;
254 if (!(pModule = NE_GetPtr( hModule )))
256 MESSAGE( "**** %04x is not a module handle\n", hModule );
257 return;
260 /* Dump the module info */
261 DPRINTF( "---\n" );
262 DPRINTF( "Module %04x:\n", hModule );
263 DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
264 pModule->count, pModule->flags,
265 pModule->heap_size, pModule->stack_size );
266 DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
267 pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
268 pModule->seg_count, pModule->modref_count );
269 DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
270 pModule->os_flags, pModule->min_swap_area,
271 pModule->expected_version );
272 if (pModule->flags & NE_FFLAGS_WIN32)
273 DPRINTF( "PE module=%p\n", pModule->module32 );
275 /* Dump the file info */
276 DPRINTF( "---\n" );
277 DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
279 /* Dump the segment table */
280 DPRINTF( "---\n" );
281 DPRINTF( "Segment table:\n" );
282 pSeg = NE_SEG_TABLE( pModule );
283 for (i = 0; i < pModule->seg_count; i++, pSeg++)
284 DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
285 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
286 pSeg->minsize, pSeg->hSeg );
288 /* Dump the resource table */
289 DPRINTF( "---\n" );
290 DPRINTF( "Resource table:\n" );
291 if (pModule->res_table)
293 pword = (WORD *)((BYTE *)pModule + pModule->res_table);
294 DPRINTF( "Alignment: %d\n", *pword++ );
295 while (*pword)
297 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
298 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
299 DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
300 for (i = 0; i < ptr->count; i++, pname++)
301 DPRINTF( "offset=%d len=%d id=%04x\n",
302 pname->offset, pname->length, pname->id );
303 pword = (WORD *)pname;
306 else DPRINTF( "None\n" );
308 /* Dump the resident name table */
309 DPRINTF( "---\n" );
310 DPRINTF( "Resident-name table:\n" );
311 pstr = (char *)pModule + pModule->name_table;
312 while (*pstr)
314 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
315 *(WORD *)(pstr + *pstr + 1) );
316 pstr += *pstr + 1 + sizeof(WORD);
319 /* Dump the module reference table */
320 DPRINTF( "---\n" );
321 DPRINTF( "Module ref table:\n" );
322 if (pModule->modref_table)
324 pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
325 for (i = 0; i < pModule->modref_count; i++, pword++)
327 char name[10];
328 GetModuleName16( *pword, name, sizeof(name) );
329 DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
332 else DPRINTF( "None\n" );
334 /* Dump the entry table */
335 DPRINTF( "---\n" );
336 DPRINTF( "Entry table:\n" );
337 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);
338 do {
339 entry = (ET_ENTRY *)((BYTE *)bundle+6);
340 DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
341 ordinal = bundle->first;
342 while (ordinal < bundle->last)
344 if (entry->type == 0xff)
345 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
346 else
347 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
348 entry++;
350 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
352 /* Dump the non-resident names table */
353 DPRINTF( "---\n" );
354 DPRINTF( "Non-resident names table:\n" );
355 if (pModule->nrname_handle)
357 pstr = (char *)GlobalLock16( pModule->nrname_handle );
358 while (*pstr)
360 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
361 *(WORD *)(pstr + *pstr + 1) );
362 pstr += *pstr + 1 + sizeof(WORD);
365 DPRINTF( "\n" );
369 /***********************************************************************
370 * NE_WalkModules
372 * Walk the module list and print the modules.
374 void NE_WalkModules(void)
376 HMODULE16 hModule = hFirstModule;
377 MESSAGE( "Module Flags Name\n" );
378 while (hModule)
380 NE_MODULE *pModule = NE_GetPtr( hModule );
381 if (!pModule)
383 MESSAGE( "Bad module %04x in list\n", hModule );
384 return;
386 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->flags,
387 *((char *)pModule + pModule->name_table),
388 (char *)pModule + pModule->name_table + 1 );
389 hModule = pModule->next;
394 /***********************************************************************
395 * NE_InitResourceHandler
397 * Fill in 'resloader' fields in the resource table.
399 static void NE_InitResourceHandler( NE_MODULE *pModule )
401 static FARPROC16 proc;
403 NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
405 TRACE("InitResourceHandler[%04x]\n", pModule->self );
407 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
409 while(pTypeInfo->type_id)
411 memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
412 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
417 /***********************************************************************
418 * NE_GetOrdinal
420 * Lookup the ordinal for a given name.
422 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
424 unsigned char buffer[256], *cpnt;
425 BYTE len;
426 NE_MODULE *pModule;
428 if (!(pModule = NE_GetPtr( hModule ))) return 0;
429 if (pModule->flags & NE_FFLAGS_WIN32) return 0;
431 TRACE("(%04x,'%s')\n", hModule, name );
433 /* First handle names of the form '#xxxx' */
435 if (name[0] == '#') return atoi( name + 1 );
437 /* Now copy and uppercase the string */
439 strcpy( buffer, name );
440 for (cpnt = buffer; *cpnt; cpnt++) *cpnt = RtlUpperChar(*cpnt);
441 len = cpnt - buffer;
443 /* First search the resident names */
445 cpnt = (char *)pModule + pModule->name_table;
447 /* Skip the first entry (module name) */
448 cpnt += *cpnt + 1 + sizeof(WORD);
449 while (*cpnt)
451 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
453 WORD ordinal;
454 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
455 TRACE(" Found: ordinal=%d\n", ordinal );
456 return ordinal;
458 cpnt += *cpnt + 1 + sizeof(WORD);
461 /* Now search the non-resident names table */
463 if (!pModule->nrname_handle) return 0; /* No non-resident table */
464 cpnt = (char *)GlobalLock16( pModule->nrname_handle );
466 /* Skip the first entry (module description string) */
467 cpnt += *cpnt + 1 + sizeof(WORD);
468 while (*cpnt)
470 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
472 WORD ordinal;
473 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
474 TRACE(" Found: ordinal=%d\n", ordinal );
475 return ordinal;
477 cpnt += *cpnt + 1 + sizeof(WORD);
479 return 0;
483 /***********************************************************************
484 * NE_GetEntryPoint
486 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
488 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
491 /***********************************************************************
492 * NE_GetEntryPointEx
494 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
496 NE_MODULE *pModule;
497 WORD sel, offset, i;
499 ET_ENTRY *entry;
500 ET_BUNDLE *bundle;
502 if (!(pModule = NE_GetPtr( hModule ))) return 0;
503 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
505 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
506 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
508 if (!(bundle->next))
509 return 0;
510 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
513 entry = (ET_ENTRY *)((BYTE *)bundle+6);
514 for (i=0; i < (ordinal - bundle->first - 1); i++)
515 entry++;
517 sel = entry->segnum;
518 memcpy( &offset, &entry->offs, sizeof(WORD) );
520 if (sel == 0xfe) sel = 0xffff; /* constant entry */
521 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
522 if (sel==0xffff)
523 return (FARPROC16)MAKESEGPTR( sel, offset );
524 if (!snoop)
525 return (FARPROC16)MAKESEGPTR( sel, offset );
526 else
527 return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
531 /***********************************************************************
532 * EntryAddrProc (KERNEL.667) Wine-specific export
534 * Return the entry point for a given ordinal.
536 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
538 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
539 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
540 return ret;
543 /***********************************************************************
544 * NE_SetEntryPoint
546 * Change the value of an entry point. Use with caution!
547 * It can only change the offset value, not the selector.
549 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
551 NE_MODULE *pModule;
552 ET_ENTRY *entry;
553 ET_BUNDLE *bundle;
554 int i;
556 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
557 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
559 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
560 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
562 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
563 if (!(bundle->next)) return 0;
566 entry = (ET_ENTRY *)((BYTE *)bundle+6);
567 for (i=0; i < (ordinal - bundle->first - 1); i++)
568 entry++;
570 memcpy( &entry->offs, &offset, sizeof(WORD) );
571 return TRUE;
575 /***********************************************************************
576 * NE_OpenFile
578 HANDLE NE_OpenFile( NE_MODULE *pModule )
580 HANDLE handle;
581 char *name = NE_MODULE_NAME( pModule );
583 TRACE("(%p)\n", pModule );
585 if (pModule->fd)
587 if (!DuplicateHandle( GetCurrentProcess(), pModule->fd,
588 GetCurrentProcess(), &handle, 0, FALSE,
589 DUPLICATE_SAME_ACCESS )) handle = INVALID_HANDLE_VALUE;
591 else
593 handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
594 NULL, OPEN_EXISTING, 0, 0 );
596 if (handle == INVALID_HANDLE_VALUE)
597 ERR( "Can't open file '%s' for module %04x\n", name, pModule->self );
599 TRACE("opened '%s' -> %p\n", name, handle);
600 return handle;
604 /* wrapper for SetFilePointer and ReadFile */
605 static BOOL read_data( HANDLE handle, LONG offset, void *buffer, DWORD size )
607 DWORD result;
609 if (SetFilePointer( handle, offset, NULL, SEEK_SET ) == INVALID_SET_FILE_POINTER) return FALSE;
610 if (!ReadFile( handle, buffer, size, &result, NULL )) return FALSE;
611 return (result == size);
614 /***********************************************************************
615 * NE_LoadExeHeader
617 static HMODULE16 NE_LoadExeHeader( HANDLE handle, LPCSTR path )
619 IMAGE_DOS_HEADER mz_header;
620 IMAGE_OS2_HEADER ne_header;
621 int size;
622 HMODULE16 hModule;
623 NE_MODULE *pModule;
624 BYTE *pData, *pTempEntryTable;
625 char *buffer, *fastload = NULL;
626 int fastload_offset = 0, fastload_length = 0;
627 ET_ENTRY *entry;
628 ET_BUNDLE *bundle, *oldbundle;
629 OFSTRUCT *ofs;
631 /* Read a block from either the file or the fast-load area. */
632 #define READ(offset,size,buffer) \
633 ((fastload && ((offset) >= fastload_offset) && \
634 ((offset)+(size) <= fastload_offset+fastload_length)) ? \
635 (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
636 read_data( handle, (offset), (buffer), (size)))
638 if (!read_data( handle, 0, &mz_header, sizeof(mz_header)) ||
639 (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
640 return (HMODULE16)11; /* invalid exe */
642 if (!read_data( handle, mz_header.e_lfanew, &ne_header, sizeof(ne_header) ))
643 return (HMODULE16)11; /* invalid exe */
645 if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21; /* win32 exe */
646 if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
647 MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
648 return (HMODULE16)12;
650 if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11; /* invalid exe */
652 /* We now have a valid NE header */
654 size = sizeof(NE_MODULE) +
655 /* segment table */
656 ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
657 /* resource table */
658 ne_header.ne_restab - ne_header.ne_rsrctab +
659 /* resident names table */
660 ne_header.ne_modtab - ne_header.ne_restab +
661 /* module ref table */
662 ne_header.ne_cmod * sizeof(WORD) +
663 /* imported names table */
664 ne_header.ne_enttab - ne_header.ne_imptab +
665 /* entry table length */
666 ne_header.ne_cbenttab +
667 /* entry table extra conversion space */
668 sizeof(ET_BUNDLE) +
669 2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
670 /* loaded file info */
671 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
673 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
674 if (!hModule) return (HMODULE16)11; /* invalid exe */
676 FarSetOwner16( hModule, hModule );
677 pModule = (NE_MODULE *)GlobalLock16( hModule );
678 memcpy( pModule, &ne_header, sizeof(ne_header) );
679 pModule->count = 0;
680 /* check *programs* for default minimal stack size */
681 if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
682 && (pModule->stack_size < 0x1400) )
683 pModule->stack_size = 0x1400;
684 pModule->module32 = 0;
685 pModule->self = hModule;
686 pModule->self_loading_sel = 0;
687 pData = (BYTE *)(pModule + 1);
689 /* Clear internal Wine flags in case they are set in the EXE file */
691 pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
693 /* Read the fast-load area */
695 if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
697 fastload_offset=ne_header.ne_pretthunks << ne_header.ne_align;
698 fastload_length=ne_header.ne_psegrefbytes << ne_header.ne_align;
699 TRACE("Using fast-load area offset=%x len=%d\n",
700 fastload_offset, fastload_length );
701 if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
703 if (!read_data( handle, fastload_offset, fastload, fastload_length))
705 HeapFree( GetProcessHeap(), 0, fastload );
706 WARN("Error reading fast-load area!\n");
707 fastload = NULL;
712 /* Get the segment table */
714 pModule->seg_table = pData - (BYTE *)pModule;
715 buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
716 sizeof(struct ne_segment_table_entry_s));
717 if (buffer)
719 int i;
720 struct ne_segment_table_entry_s *pSeg;
722 if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
723 ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
724 buffer ))
726 HeapFree( GetProcessHeap(), 0, buffer );
727 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
728 GlobalFree16( hModule );
729 return (HMODULE16)11; /* invalid exe */
731 pSeg = (struct ne_segment_table_entry_s *)buffer;
732 for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
734 memcpy( pData, pSeg, sizeof(*pSeg) );
735 pData += sizeof(SEGTABLEENTRY);
737 HeapFree( GetProcessHeap(), 0, buffer );
739 else
741 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
742 GlobalFree16( hModule );
743 return (HMODULE16)11; /* invalid exe */
746 /* Get the resource table */
748 if (ne_header.ne_rsrctab < ne_header.ne_restab)
750 pModule->res_table = pData - (BYTE *)pModule;
751 if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
752 ne_header.ne_restab - ne_header.ne_rsrctab,
753 pData ))
754 return (HMODULE16)11; /* invalid exe */
755 pData += ne_header.ne_restab - ne_header.ne_rsrctab;
756 NE_InitResourceHandler( pModule );
758 else pModule->res_table = 0; /* No resource table */
760 /* Get the resident names table */
762 pModule->name_table = pData - (BYTE *)pModule;
763 if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
764 ne_header.ne_modtab - ne_header.ne_restab,
765 pData ))
767 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
768 GlobalFree16( hModule );
769 return (HMODULE16)11; /* invalid exe */
771 pData += ne_header.ne_modtab - ne_header.ne_restab;
773 /* Get the module references table */
775 if (ne_header.ne_cmod > 0)
777 pModule->modref_table = pData - (BYTE *)pModule;
778 if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
779 ne_header.ne_cmod * sizeof(WORD),
780 pData ))
782 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
783 GlobalFree16( hModule );
784 return (HMODULE16)11; /* invalid exe */
786 pData += ne_header.ne_cmod * sizeof(WORD);
788 else pModule->modref_table = 0; /* No module references */
790 /* Get the imported names table */
792 pModule->import_table = pData - (BYTE *)pModule;
793 if (!READ( mz_header.e_lfanew + ne_header.ne_imptab,
794 ne_header.ne_enttab - ne_header.ne_imptab,
795 pData ))
797 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
798 GlobalFree16( hModule );
799 return (HMODULE16)11; /* invalid exe */
801 pData += ne_header.ne_enttab - ne_header.ne_imptab;
803 /* Load entry table, convert it to the optimized version used by Windows */
805 if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
807 BYTE nr_entries, type, *s;
809 TRACE("Converting entry table.\n");
810 pModule->entry_table = pData - (BYTE *)pModule;
811 if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
812 ne_header.ne_cbenttab, pTempEntryTable ))
814 HeapFree( GetProcessHeap(), 0, pTempEntryTable );
815 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
816 GlobalFree16( hModule );
817 return (HMODULE16)11; /* invalid exe */
820 s = pTempEntryTable;
821 TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
823 bundle = (ET_BUNDLE *)pData;
824 TRACE("first bundle: %p\n", bundle);
825 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
826 entry = (ET_ENTRY *)((BYTE *)bundle+6);
828 while ((nr_entries = *s++))
830 if ((type = *s++))
832 bundle->last += nr_entries;
833 if (type == 0xff)
834 while (nr_entries--)
836 entry->type = type;
837 entry->flags = *s++;
838 s += 2;
839 entry->segnum = *s++;
840 entry->offs = *(WORD *)s; s += 2;
841 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
842 entry++;
844 else
845 while (nr_entries--)
847 entry->type = type;
848 entry->flags = *s++;
849 entry->segnum = type;
850 entry->offs = *(WORD *)s; s += 2;
851 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
852 entry++;
855 else
857 if (bundle->first == bundle->last)
859 bundle->first += nr_entries;
860 bundle->last += nr_entries;
862 else
864 oldbundle = bundle;
865 oldbundle->next = ((int)entry - (int)pModule);
866 bundle = (ET_BUNDLE *)entry;
867 TRACE("new bundle: %p\n", bundle);
868 bundle->first = bundle->last =
869 oldbundle->last + nr_entries;
870 bundle->next = 0;
871 (BYTE *)entry += sizeof(ET_BUNDLE);
875 HeapFree( GetProcessHeap(), 0, pTempEntryTable );
877 else
879 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
880 GlobalFree16( hModule );
881 return (HMODULE16)11; /* invalid exe */
884 pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
885 2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
887 if ((DWORD)entry > (DWORD)pData)
888 ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
890 /* Store the filename information */
892 pModule->fileinfo = pData - (BYTE *)pModule;
893 size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
894 ofs = (OFSTRUCT *)pData;
895 ofs->cBytes = size - 1;
896 ofs->fFixedDisk = 1;
897 strcpy( ofs->szPathName, path );
898 pData += size;
900 /* Free the fast-load area */
902 #undef READ
903 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
905 /* Get the non-resident names table */
907 if (ne_header.ne_cbnrestab)
909 pModule->nrname_handle = GlobalAlloc16( 0, ne_header.ne_cbnrestab );
910 if (!pModule->nrname_handle)
912 GlobalFree16( hModule );
913 return (HMODULE16)11; /* invalid exe */
915 FarSetOwner16( pModule->nrname_handle, hModule );
916 buffer = GlobalLock16( pModule->nrname_handle );
917 if (!read_data( handle, ne_header.ne_nrestab, buffer, ne_header.ne_cbnrestab ))
919 GlobalFree16( pModule->nrname_handle );
920 GlobalFree16( hModule );
921 return (HMODULE16)11; /* invalid exe */
924 else pModule->nrname_handle = 0;
926 /* Allocate a segment for the implicitly-loaded DLLs */
928 if (pModule->modref_count)
930 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
931 (pModule->modref_count+1)*sizeof(HMODULE16) );
932 if (!pModule->dlls_to_init)
934 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
935 GlobalFree16( hModule );
936 return (HMODULE16)11; /* invalid exe */
938 FarSetOwner16( pModule->dlls_to_init, hModule );
940 else pModule->dlls_to_init = 0;
942 NE_RegisterModule( pModule );
943 SNOOP16_RegisterDLL(pModule,path);
944 return hModule;
948 /***********************************************************************
949 * NE_LoadDLLs
951 * Load all DLLs implicitly linked to a module.
953 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
955 int i;
956 WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
957 WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
959 for (i = 0; i < pModule->modref_count; i++, pModRef++)
961 char buffer[260], *p;
962 BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
963 memcpy( buffer, pstr + 1, *pstr );
964 *(buffer + *pstr) = 0; /* terminate it */
966 TRACE("Loading '%s'\n", buffer );
967 if (!(*pModRef = GetModuleHandle16( buffer )))
969 /* If the DLL is not loaded yet, load it and store */
970 /* its handle in the list of DLLs to initialize. */
971 HMODULE16 hDLL;
973 /* Append .DLL to name if no extension present */
974 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
975 strcat( buffer, ".DLL" );
977 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
979 /* FIXME: cleanup what was done */
981 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
982 buffer, *((BYTE*)pModule + pModule->name_table),
983 (char *)pModule + pModule->name_table + 1, hDLL );
984 return FALSE;
986 *pModRef = GetExePtr( hDLL );
987 *pDLLs++ = *pModRef;
989 else /* Increment the reference count of the DLL */
991 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
992 if (pOldDLL) pOldDLL->count++;
995 return TRUE;
999 /**********************************************************************
1000 * NE_DoLoadModule
1002 * Load first instance of NE module from file.
1004 * pModule must point to a module structure prepared by NE_LoadExeHeader.
1005 * This routine must never be called twice on a module.
1008 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
1010 /* Allocate the segments for this module */
1012 if (!NE_CreateAllSegments( pModule ))
1013 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
1015 /* Load the referenced DLLs */
1017 if (!NE_LoadDLLs( pModule ))
1018 return ERROR_FILE_NOT_FOUND; /* 2 */
1020 /* Load the segments */
1022 NE_LoadAllSegments( pModule );
1024 /* Make sure the usage count is 1 on the first loading of */
1025 /* the module, even if it contains circular DLL references */
1027 pModule->count = 1;
1029 return NE_GetInstance( pModule );
1032 /**********************************************************************
1033 * NE_LoadModule
1035 * Load first instance of NE module. (Note: caller is responsible for
1036 * ensuring the module isn't already loaded!)
1038 * If the module turns out to be an executable module, only a
1039 * handle to a module stub is returned; this needs to be initialized
1040 * by calling NE_DoLoadModule later, in the context of the newly
1041 * created process.
1043 * If lib_only is TRUE, however, the module is perforce treated
1044 * like a DLL module, even if it is an executable module.
1047 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
1049 NE_MODULE *pModule;
1050 HMODULE16 hModule;
1051 HINSTANCE16 hInstance;
1052 HFILE16 hFile;
1053 OFSTRUCT ofs;
1054 UINT drive_type;
1056 /* Open file */
1057 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
1058 return ERROR_FILE_NOT_FOUND;
1060 hModule = NE_LoadExeHeader( DosFileHandleToWin32Handle(hFile), ofs.szPathName );
1061 if (hModule < 32)
1063 _lclose16( hFile );
1064 return hModule;
1066 pModule = NE_GetPtr( hModule );
1068 drive_type = GetDriveTypeA( ofs.szPathName );
1069 if (drive_type != DRIVE_REMOVABLE && drive_type != DRIVE_CDROM)
1071 /* keep the file handle open if not on a removable media */
1072 DuplicateHandle( GetCurrentProcess(), DosFileHandleToWin32Handle(hFile),
1073 GetCurrentProcess(), &pModule->fd, 0, FALSE,
1074 DUPLICATE_SAME_ACCESS );
1076 _lclose16( hFile );
1078 if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
1079 return hModule;
1081 hInstance = NE_DoLoadModule( pModule );
1082 if ( hInstance < 32 )
1084 /* cleanup ... */
1085 NE_FreeModule( hModule, 0 );
1088 return hInstance;
1092 /***********************************************************************
1093 * NE_DoLoadBuiltinModule
1095 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
1097 static HMODULE16 NE_DoLoadBuiltinModule( const BUILTIN16_DESCRIPTOR *descr )
1099 NE_MODULE *pModule;
1100 int minsize;
1101 SEGTABLEENTRY *pSegTable;
1102 HMODULE16 hModule;
1104 hModule = GLOBAL_CreateBlock( GMEM_MOVEABLE, descr->module_start,
1105 descr->module_size, 0, WINE_LDT_FLAGS_DATA );
1106 if (!hModule) return ERROR_NOT_ENOUGH_MEMORY;
1107 FarSetOwner16( hModule, hModule );
1109 pModule = (NE_MODULE *)GlobalLock16( hModule );
1110 pModule->self = hModule;
1111 /* NOTE: (Ab)use the hRsrcMap parameter for resource data pointer */
1112 pModule->hRsrcMap = (void *)descr->rsrc;
1114 /* Allocate the code segment */
1116 pSegTable = NE_SEG_TABLE( pModule );
1117 pSegTable->hSeg = GLOBAL_CreateBlock( GMEM_FIXED, descr->code_start,
1118 pSegTable->minsize, hModule,
1119 WINE_LDT_FLAGS_CODE|WINE_LDT_FLAGS_32BIT );
1120 if (!pSegTable->hSeg) return ERROR_NOT_ENOUGH_MEMORY;
1121 patch_code_segment( descr->code_start );
1122 pSegTable++;
1124 /* Allocate the data segment */
1126 minsize = pSegTable->minsize ? pSegTable->minsize : 0x10000;
1127 minsize += pModule->heap_size;
1128 if (minsize > 0x10000) minsize = 0x10000;
1129 pSegTable->hSeg = GlobalAlloc16( GMEM_FIXED, minsize );
1130 if (!pSegTable->hSeg) return ERROR_NOT_ENOUGH_MEMORY;
1131 FarSetOwner16( pSegTable->hSeg, hModule );
1132 if (pSegTable->minsize) memcpy( GlobalLock16( pSegTable->hSeg ),
1133 descr->data_start, pSegTable->minsize);
1134 if (pModule->heap_size)
1135 LocalInit16( GlobalHandleToSel16(pSegTable->hSeg), pSegTable->minsize, minsize );
1137 if (descr->rsrc) NE_InitResourceHandler(pModule);
1139 NE_RegisterModule( pModule );
1141 return hModule;
1145 /**********************************************************************
1146 * MODULE_LoadModule16
1148 * Load a NE module in the order of the loadorder specification.
1149 * The caller is responsible that the module is not loaded already.
1152 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1154 HINSTANCE16 hinst = 2;
1155 HMODULE16 hModule;
1156 NE_MODULE *pModule;
1157 const BUILTIN16_DESCRIPTOR *descr = NULL;
1158 char dllname[20], owner[20], *p;
1159 const char *basename;
1161 /* strip path information */
1163 basename = libname;
1164 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
1165 if ((p = strrchr( basename, '\\' ))) basename = p + 1;
1166 if ((p = strrchr( basename, '/' ))) basename = p + 1;
1168 if (strlen(basename) < sizeof(dllname)-4)
1170 int file_exists;
1172 strcpy( dllname, basename );
1173 p = strrchr( dllname, '.' );
1174 if (!p) strcat( dllname, ".dll" );
1175 for (p = dllname; *p; p++) if (*p >= 'A' && *p <= 'Z') *p += 32;
1177 if (wine_dll_get_owner( dllname, owner, sizeof(owner), &file_exists ) == -1)
1179 if (file_exists) return 21; /* it may be a Win32 module then */
1181 else /* found 32-bit owner, try to load it */
1183 HMODULE mod32 = LoadLibraryA( owner );
1184 if (mod32)
1186 if (!(descr = find_dll_descr( dllname ))) FreeLibrary( mod32 );
1187 /* loading the 32-bit library can have the side effect of loading the module */
1188 /* if so, simply incr the ref count and return the module */
1189 if ((hModule = GetModuleHandle16( libname )))
1191 TRACE( "module %s already loaded by owner\n", libname );
1192 pModule = NE_GetPtr( hModule );
1193 if (pModule) pModule->count++;
1194 return hModule;
1197 else
1199 /* it's probably disabled by the load order config */
1200 WARN( "couldn't load owner %s for 16-bit dll %s\n", owner, dllname );
1201 return ERROR_FILE_NOT_FOUND;
1206 if (descr)
1208 TRACE("Trying built-in '%s'\n", libname);
1209 hinst = NE_DoLoadBuiltinModule( descr );
1210 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : builtin\n", debugstr_a(libname));
1212 else
1214 TRACE("Trying native dll '%s'\n", libname);
1215 hinst = NE_LoadModule(libname, lib_only);
1216 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : native\n", debugstr_a(libname));
1219 if (hinst > 32 && !implicit)
1221 hModule = GetModuleHandle16(libname);
1222 if(!hModule)
1224 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1225 libname, hinst);
1226 return ERROR_INVALID_HANDLE;
1229 pModule = NE_GetPtr(hModule);
1230 if(!pModule)
1232 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1233 libname, hinst);
1234 return ERROR_INVALID_HANDLE;
1237 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1240 * Call initialization routines for all loaded DLLs. Note that
1241 * when we load implicitly linked DLLs this will be done by InitTask().
1243 if(pModule->flags & NE_FFLAGS_LIBMODULE)
1245 NE_InitializeDLLs(hModule);
1246 NE_DllProcessAttach(hModule);
1249 return hinst; /* The last error that occurred */
1253 /**********************************************************************
1254 * NE_CreateThread
1256 * Create the thread for a 16-bit module.
1258 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1260 HANDLE hThread;
1261 TDB *pTask;
1262 HTASK16 hTask;
1263 HINSTANCE16 instance = 0;
1265 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1266 return 0;
1268 /* Post event to start the task */
1269 PostEvent16( hTask );
1271 /* Wait until we get the instance handle */
1274 DirectedYield16( hTask );
1275 if (!IsTask16( hTask )) /* thread has died */
1277 DWORD exit_code;
1278 WaitForSingleObject( hThread, INFINITE );
1279 GetExitCodeThread( hThread, &exit_code );
1280 CloseHandle( hThread );
1281 return exit_code;
1283 if (!(pTask = GlobalLock16( hTask ))) break;
1284 instance = pTask->hInstance;
1285 GlobalUnlock16( hTask );
1286 } while (!instance);
1288 CloseHandle( hThread );
1289 return instance;
1293 /**********************************************************************
1294 * LoadModule (KERNEL.45)
1296 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1298 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1299 LOADPARAMS16 *params;
1300 HMODULE16 hModule;
1301 NE_MODULE *pModule;
1302 LPSTR cmdline;
1303 WORD cmdShow;
1305 /* Load module */
1307 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1309 /* Special case: second instance of an already loaded NE module */
1311 if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1312 if ( pModule->module32 ) return (HINSTANCE16)21;
1314 /* Increment refcount */
1316 pModule->count++;
1318 else
1320 /* Main case: load first instance of NE module */
1322 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1323 return hModule;
1325 if ( !(pModule = NE_GetPtr( hModule )) )
1326 return (HINSTANCE16)11;
1329 /* If library module, we just retrieve the instance handle */
1331 if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1332 return NE_GetInstance( pModule );
1335 * At this point, we need to create a new process.
1337 * pModule points either to an already loaded module, whose refcount
1338 * has already been incremented (to avoid having the module vanish
1339 * in the meantime), or else to a stub module which contains only header
1340 * information.
1342 params = (LOADPARAMS16 *)paramBlock;
1343 cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1344 cmdline = MapSL( params->cmdLine );
1345 return NE_CreateThread( pModule, cmdShow, cmdline );
1349 /**********************************************************************
1350 * NE_StartTask
1352 * Startup code for a new 16-bit task.
1354 DWORD NE_StartTask(void)
1356 TDB *pTask = TASK_GetCurrent();
1357 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1358 HINSTANCE16 hInstance, hPrevInstance;
1359 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1360 WORD sp;
1362 if ( pModule->count > 0 )
1364 /* Second instance of an already loaded NE module */
1365 /* Note that the refcount was already incremented by the parent */
1367 hPrevInstance = NE_GetInstance( pModule );
1369 if ( pModule->dgroup )
1370 if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1371 NE_LoadSegment( pModule, pModule->dgroup );
1373 hInstance = NE_GetInstance( pModule );
1374 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1377 else
1379 /* Load first instance of NE module */
1381 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1383 hInstance = NE_DoLoadModule( pModule );
1384 hPrevInstance = 0;
1387 if ( hInstance >= 32 )
1389 CONTEXT86 context;
1391 /* Enter instance handles into task struct */
1393 pTask->hInstance = hInstance;
1394 pTask->hPrevInstance = hPrevInstance;
1396 /* Use DGROUP for 16-bit stack */
1398 if (!(sp = pModule->sp))
1399 sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1400 sp &= ~1;
1401 sp -= sizeof(STACK16FRAME);
1402 NtCurrentTeb()->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1404 /* Registers at initialization must be:
1405 * ax zero
1406 * bx stack size in bytes
1407 * cx heap size in bytes
1408 * si previous app instance
1409 * di current app instance
1410 * bp zero
1411 * es selector to the PSP
1412 * ds dgroup of the application
1413 * ss stack selector
1414 * sp top of the stack
1416 memset( &context, 0, sizeof(context) );
1417 context.SegCs = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1418 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1419 context.SegEs = pTask->hPDB;
1420 context.SegFs = wine_get_fs();
1421 context.SegGs = wine_get_gs();
1422 context.Eip = pModule->ip;
1423 context.Ebx = pModule->stack_size;
1424 context.Ecx = pModule->heap_size;
1425 context.Edi = pTask->hInstance;
1426 context.Esi = pTask->hPrevInstance;
1428 /* Now call 16-bit entry point */
1430 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1431 context.SegCs, context.Eip, context.SegDs,
1432 SELECTOROF(NtCurrentTeb()->cur_stack),
1433 OFFSETOF(NtCurrentTeb()->cur_stack) );
1435 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1436 ExitThread( LOWORD(context.Eax) );
1438 return hInstance; /* error code */
1441 /***********************************************************************
1442 * LoadLibrary (KERNEL.95)
1443 * LoadLibrary16 (KERNEL32.35)
1445 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1447 return LoadModule16(libname, (LPVOID)-1 );
1451 /**********************************************************************
1452 * MODULE_CallWEP
1454 * Call a DLL's WEP, allowing it to shut down.
1455 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1457 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1459 BOOL16 ret;
1460 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1461 if (!WEP) return FALSE;
1463 __TRY
1465 WORD args[1];
1466 DWORD dwRet;
1468 args[0] = WEP_FREE_DLL;
1469 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1470 ret = LOWORD(dwRet);
1472 __EXCEPT(page_fault)
1474 WARN("Page fault\n");
1475 ret = 0;
1477 __ENDTRY
1479 return ret;
1483 /**********************************************************************
1484 * NE_FreeModule
1486 * Implementation of FreeModule16().
1488 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1490 HMODULE16 *hPrevModule;
1491 NE_MODULE *pModule;
1492 HMODULE16 *pModRef;
1493 int i;
1495 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1496 hModule = pModule->self;
1498 TRACE("%04x count %d\n", hModule, pModule->count );
1500 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1501 else pModule->count = 0;
1503 if (pModule->flags & NE_FFLAGS_BUILTIN)
1504 return FALSE; /* Can't free built-in module */
1506 if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1508 /* Free the objects owned by the DLL module */
1509 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1511 if (pModule->flags & NE_FFLAGS_LIBMODULE)
1512 MODULE_CallWEP( hModule );
1513 else
1514 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1518 /* Clear magic number just in case */
1520 pModule->magic = pModule->self = 0;
1521 if (pModule->fd) CloseHandle( pModule->fd );
1523 /* Remove it from the linked list */
1525 hPrevModule = &hFirstModule;
1526 while (*hPrevModule && (*hPrevModule != hModule))
1528 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1530 if (*hPrevModule) *hPrevModule = pModule->next;
1532 /* Free the referenced modules */
1534 pModRef = (HMODULE16*)((char *)pModule + pModule->modref_table);
1535 for (i = 0; i < pModule->modref_count; i++, pModRef++)
1537 NE_FreeModule( *pModRef, call_wep );
1540 /* Free the module storage */
1542 GlobalFreeAll16( hModule );
1543 return TRUE;
1547 /**********************************************************************
1548 * FreeModule (KERNEL.46)
1550 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1552 return NE_FreeModule( hModule, TRUE );
1556 /***********************************************************************
1557 * FreeLibrary (KERNEL.96)
1558 * FreeLibrary16 (KERNEL32.36)
1560 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1562 TRACE("%04x\n", handle );
1563 FreeModule16( handle );
1567 /***********************************************************************
1568 * GetModuleHandle16 (KERNEL32.@)
1570 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1572 HMODULE16 hModule = hFirstModule;
1573 LPSTR s;
1574 BYTE len, *name_table;
1575 char tmpstr[MAX_PATH];
1576 NE_MODULE *pModule;
1578 TRACE("(%s)\n", name);
1580 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1582 len = strlen(name);
1583 if (!len) return 0;
1585 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1587 /* If 'name' matches exactly the module name of a module:
1588 * Return its handle.
1590 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1592 pModule = NE_GetPtr( hModule );
1593 if (!pModule) break;
1594 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1596 name_table = (BYTE *)pModule + pModule->name_table;
1597 if ((*name_table == len) && !strncmp(name, name_table+1, len))
1598 return hModule;
1601 /* If uppercased 'name' matches exactly the module name of a module:
1602 * Return its handle
1604 for (s = tmpstr; *s; s++) *s = RtlUpperChar(*s);
1606 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1608 pModule = NE_GetPtr( hModule );
1609 if (!pModule) break;
1610 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1612 name_table = (BYTE *)pModule + pModule->name_table;
1613 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1614 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1615 * lowercased module names, but try to load uppercase DLLs, so this
1616 * 'i' compare is just a quickfix until the loader handles that
1617 * correctly. -MM 990705
1619 if ((*name_table == len) && !NE_strncasecmp(tmpstr, name_table+1, len))
1620 return hModule;
1623 /* If the base filename of 'name' matches the base filename of the module
1624 * filename of some module (case-insensitive compare):
1625 * Return its handle.
1628 /* basename: search backwards in passed name to \ / or : */
1629 s = tmpstr + strlen(tmpstr);
1630 while (s > tmpstr)
1632 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1633 break;
1634 s--;
1637 /* search this in loaded filename list */
1638 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1640 char *loadedfn;
1641 OFSTRUCT *ofs;
1643 pModule = NE_GetPtr( hModule );
1644 if (!pModule) break;
1645 if (!pModule->fileinfo) continue;
1646 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1648 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1649 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1650 /* basename: search backwards in pathname to \ / or : */
1651 while (loadedfn > (char*)ofs->szPathName)
1653 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1654 break;
1655 loadedfn--;
1657 /* case insensitive compare ... */
1658 if (!NE_strcasecmp(loadedfn, s))
1659 return hModule;
1661 return 0;
1665 /**********************************************************************
1666 * GetModuleName (KERNEL.27)
1668 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1670 NE_MODULE *pModule;
1671 BYTE *p;
1673 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1674 p = (BYTE *)pModule + pModule->name_table;
1675 if (count > *p) count = *p + 1;
1676 if (count > 0)
1678 memcpy( buf, p + 1, count - 1 );
1679 buf[count-1] = '\0';
1681 return TRUE;
1685 /**********************************************************************
1686 * GetModuleFileName (KERNEL.49)
1688 * Comment: see GetModuleFileNameA
1690 * Even if invoked by second instance of a program,
1691 * it still returns path of first one.
1693 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1694 INT16 nSize )
1696 NE_MODULE *pModule;
1698 /* Win95 does not query hModule if set to 0 !
1699 * Is this wrong or maybe Win3.1 only ? */
1700 if (!hModule) hModule = GetCurrentTask();
1702 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1703 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1704 if (pModule->expected_version >= 0x400)
1705 GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1706 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1707 return strlen(lpFileName);
1711 /**********************************************************************
1712 * GetModuleUsage (KERNEL.48)
1714 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1716 NE_MODULE *pModule = NE_GetPtr( hModule );
1717 return pModule ? pModule->count : 0;
1721 /**********************************************************************
1722 * GetExpWinVer (KERNEL.167)
1724 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1726 NE_MODULE *pModule = NE_GetPtr( hModule );
1727 if ( !pModule ) return 0;
1730 * For built-in modules, fake the expected version the module should
1731 * have according to the Windows version emulated by Wine
1733 if ( !pModule->expected_version )
1735 OSVERSIONINFOA versionInfo;
1736 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1738 if ( GetVersionExA( &versionInfo ) )
1739 pModule->expected_version =
1740 (versionInfo.dwMajorVersion & 0xff) << 8
1741 | (versionInfo.dwMinorVersion & 0xff);
1744 return pModule->expected_version;
1748 /***********************************************************************
1749 * WinExec (KERNEL.166)
1751 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1753 LPCSTR p, args = NULL;
1754 LPCSTR name_beg, name_end;
1755 LPSTR name, cmdline;
1756 int arglen;
1757 HINSTANCE16 ret;
1758 char buffer[MAX_PATH];
1760 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1762 name_beg = lpCmdLine+1;
1763 p = strchr ( lpCmdLine+1, '"' );
1764 if (p)
1766 name_end = p;
1767 args = strchr ( p, ' ' );
1769 else /* yes, even valid with trailing '"' missing */
1770 name_end = lpCmdLine+strlen(lpCmdLine);
1772 else
1774 name_beg = lpCmdLine;
1775 args = strchr( lpCmdLine, ' ' );
1776 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1779 if ((name_beg == lpCmdLine) && (!args))
1780 { /* just use the original cmdline string as file name */
1781 name = (LPSTR)lpCmdLine;
1783 else
1785 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1786 return ERROR_NOT_ENOUGH_MEMORY;
1787 memcpy( name, name_beg, name_end - name_beg );
1788 name[name_end - name_beg] = '\0';
1791 if (args)
1793 args++;
1794 arglen = strlen(args);
1795 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1796 cmdline[0] = (BYTE)arglen;
1797 strcpy( cmdline + 1, args );
1799 else
1801 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1802 cmdline[0] = cmdline[1] = 0;
1805 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1807 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1809 LOADPARAMS16 params;
1810 WORD showCmd[2];
1811 showCmd[0] = 2;
1812 showCmd[1] = nCmdShow;
1814 params.hEnvironment = 0;
1815 params.cmdLine = MapLS( cmdline );
1816 params.showCmd = MapLS( showCmd );
1817 params.reserved = 0;
1819 ret = LoadModule16( buffer, &params );
1820 UnMapLS( params.cmdLine );
1821 UnMapLS( params.showCmd );
1823 else ret = GetLastError();
1825 HeapFree( GetProcessHeap(), 0, cmdline );
1826 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1828 if (ret == 21) /* 32-bit module */
1830 DWORD count;
1831 ReleaseThunkLock( &count );
1832 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1833 RestoreThunkLock( count );
1835 return ret;
1838 /***********************************************************************
1839 * GetProcAddress (KERNEL.50)
1841 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1843 WORD ordinal;
1844 FARPROC16 ret;
1846 if (!hModule) hModule = GetCurrentTask();
1847 hModule = GetExePtr( hModule );
1849 if (HIWORD(name) != 0)
1851 ordinal = NE_GetOrdinal( hModule, name );
1852 TRACE("%04x '%s'\n", hModule, name );
1854 else
1856 ordinal = LOWORD(name);
1857 TRACE("%04x %04x\n", hModule, ordinal );
1859 if (!ordinal) return (FARPROC16)0;
1861 ret = NE_GetEntryPoint( hModule, ordinal );
1863 TRACE("returning %08x\n", (UINT)ret );
1864 return ret;
1868 /***************************************************************************
1869 * HasGPHandler (KERNEL.338)
1871 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1873 HMODULE16 hModule;
1874 int gpOrdinal;
1875 SEGPTR gpPtr;
1876 GPHANDLERDEF *gpHandler;
1878 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1879 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1880 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1881 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1882 && (gpHandler = MapSL( gpPtr )) != NULL )
1884 while (gpHandler->selector)
1886 if ( SELECTOROF(address) == gpHandler->selector
1887 && OFFSETOF(address) >= gpHandler->rangeStart
1888 && OFFSETOF(address) < gpHandler->rangeEnd )
1889 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1890 gpHandler++;
1894 return 0;
1898 /**********************************************************************
1899 * GetModuleHandle (KERNEL.47)
1901 * Find a module from a module name.
1903 * NOTE: The current implementation works the same way the Windows 95 one
1904 * does. Do not try to 'fix' it, fix the callers.
1905 * + It does not do ANY extension handling (except that strange .EXE bit)!
1906 * + It does not care about paths, just about basenames. (same as Windows)
1908 * RETURNS
1909 * LOWORD:
1910 * the win16 module handle if found
1911 * 0 if not
1912 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1913 * Always hFirstModule
1915 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1917 if (HIWORD(name) == 0)
1918 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1919 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1922 /**********************************************************************
1923 * NE_GetModuleByFilename
1925 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1927 HMODULE16 hModule;
1928 LPSTR s, p;
1929 BYTE len, *name_table;
1930 char tmpstr[MAX_PATH];
1931 NE_MODULE *pModule;
1933 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1935 /* If the base filename of 'name' matches the base filename of the module
1936 * filename of some module (case-insensitive compare):
1937 * Return its handle.
1940 /* basename: search backwards in passed name to \ / or : */
1941 s = tmpstr + strlen(tmpstr);
1942 while (s > tmpstr)
1944 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1945 break;
1946 s--;
1949 /* search this in loaded filename list */
1950 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1952 char *loadedfn;
1953 OFSTRUCT *ofs;
1955 pModule = NE_GetPtr( hModule );
1956 if (!pModule) break;
1957 if (!pModule->fileinfo) continue;
1958 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1960 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1961 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1962 /* basename: search backwards in pathname to \ / or : */
1963 while (loadedfn > (char*)ofs->szPathName)
1965 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1966 break;
1967 loadedfn--;
1969 /* case insensitive compare ... */
1970 if (!NE_strcasecmp(loadedfn, s))
1971 return hModule;
1973 /* If basename (without ext) matches the module name of a module:
1974 * Return its handle.
1977 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1978 len = strlen(s);
1980 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1982 pModule = NE_GetPtr( hModule );
1983 if (!pModule) break;
1984 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1986 name_table = (BYTE *)pModule + pModule->name_table;
1987 if ((*name_table == len) && !NE_strncasecmp(s, name_table+1, len))
1988 return hModule;
1991 return 0;
1994 /***********************************************************************
1995 * GetProcAddress16 (KERNEL32.37)
1996 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1998 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
2000 if (!hModule) return 0;
2001 if (HIWORD(hModule))
2003 WARN("hModule is Win32 handle (%p)\n", hModule );
2004 return 0;
2006 return GetProcAddress16( LOWORD(hModule), name );
2009 /**********************************************************************
2010 * ModuleFirst (TOOLHELP.59)
2012 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
2014 lpme->wNext = hFirstModule;
2015 return ModuleNext16( lpme );
2019 /**********************************************************************
2020 * ModuleNext (TOOLHELP.60)
2022 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
2024 NE_MODULE *pModule;
2025 char *name;
2027 if (!lpme->wNext) return FALSE;
2028 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
2029 name = (char *)pModule + pModule->name_table;
2030 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
2031 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
2032 lpme->hModule = lpme->wNext;
2033 lpme->wcUsage = pModule->count;
2034 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
2035 lpme->wNext = pModule->next;
2036 return TRUE;
2040 /**********************************************************************
2041 * ModuleFindName (TOOLHELP.61)
2043 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
2045 lpme->wNext = GetModuleHandle16( name );
2046 return ModuleNext16( lpme );
2050 /**********************************************************************
2051 * ModuleFindHandle (TOOLHELP.62)
2053 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
2055 hModule = GetExePtr( hModule );
2056 lpme->wNext = hModule;
2057 return ModuleNext16( lpme );
2061 /***************************************************************************
2062 * IsRomModule (KERNEL.323)
2064 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
2066 return FALSE;
2069 /***************************************************************************
2070 * IsRomFile (KERNEL.326)
2072 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
2074 return FALSE;
2077 /***********************************************************************
2078 * create_dummy_module
2080 * Create a dummy NE module for Win32 or Winelib.
2082 static HMODULE16 create_dummy_module( HMODULE module32 )
2084 HMODULE16 hModule;
2085 NE_MODULE *pModule;
2086 SEGTABLEENTRY *pSegment;
2087 char *pStr,*s;
2088 unsigned int len;
2089 const char* basename;
2090 OFSTRUCT *ofs;
2091 int of_size, size;
2092 char filename[MAX_PATH];
2093 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
2095 if (!nt) return (HMODULE16)11; /* invalid exe */
2097 /* Extract base filename */
2098 GetModuleFileNameA( module32, filename, sizeof(filename) );
2099 basename = strrchr(filename, '\\');
2100 if (!basename) basename = filename;
2101 else basename++;
2102 len = strlen(basename);
2103 if ((s = strchr(basename, '.'))) len = s - basename;
2105 /* Allocate module */
2106 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2107 + strlen(filename) + 1;
2108 size = sizeof(NE_MODULE) +
2109 /* loaded file info */
2110 ((of_size + 3) & ~3) +
2111 /* segment table: DS,CS */
2112 2 * sizeof(SEGTABLEENTRY) +
2113 /* name table */
2114 len + 2 +
2115 /* several empty tables */
2118 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2119 if (!hModule) return (HMODULE16)11; /* invalid exe */
2121 FarSetOwner16( hModule, hModule );
2122 pModule = (NE_MODULE *)GlobalLock16( hModule );
2124 /* Set all used entries */
2125 pModule->magic = IMAGE_OS2_SIGNATURE;
2126 pModule->count = 1;
2127 pModule->next = 0;
2128 pModule->flags = NE_FFLAGS_WIN32;
2129 pModule->dgroup = 0;
2130 pModule->ss = 1;
2131 pModule->cs = 2;
2132 pModule->heap_size = 0;
2133 pModule->stack_size = 0;
2134 pModule->seg_count = 2;
2135 pModule->modref_count = 0;
2136 pModule->nrname_size = 0;
2137 pModule->fileinfo = sizeof(NE_MODULE);
2138 pModule->os_flags = NE_OSFLAGS_WINDOWS;
2139 pModule->self = hModule;
2140 pModule->module32 = module32;
2142 /* Set version and flags */
2143 pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2144 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2145 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2146 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2148 /* Set loaded file information */
2149 ofs = (OFSTRUCT *)(pModule + 1);
2150 memset( ofs, 0, of_size );
2151 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
2152 strcpy( ofs->szPathName, filename );
2154 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2155 pModule->seg_table = (int)pSegment - (int)pModule;
2156 /* Data segment */
2157 pSegment->size = 0;
2158 pSegment->flags = NE_SEGFLAGS_DATA;
2159 pSegment->minsize = 0x1000;
2160 pSegment++;
2161 /* Code segment */
2162 pSegment->flags = 0;
2163 pSegment++;
2165 /* Module name */
2166 pStr = (char *)pSegment;
2167 pModule->name_table = (int)pStr - (int)pModule;
2168 assert(len<256);
2169 *pStr = len;
2170 lstrcpynA( pStr+1, basename, len+1 );
2171 pStr += len+2;
2173 /* All tables zero terminated */
2174 pModule->res_table = pModule->import_table = pModule->entry_table = (int)pStr - (int)pModule;
2176 NE_RegisterModule( pModule );
2177 LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
2178 return hModule;
2181 /***********************************************************************
2182 * PrivateLoadLibrary (KERNEL32.@)
2184 * FIXME: rough guesswork, don't know what "Private" means
2186 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2188 return LoadLibrary16(libname);
2191 /***********************************************************************
2192 * PrivateFreeLibrary (KERNEL32.@)
2194 * FIXME: rough guesswork, don't know what "Private" means
2196 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2198 FreeLibrary16(handle);
2201 /***********************************************************************
2202 * LoadLibrary32 (KERNEL.452)
2203 * LoadSystemLibrary32 (KERNEL.482)
2205 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2207 HMODULE hModule;
2208 DWORD count;
2210 ReleaseThunkLock( &count );
2211 hModule = LoadLibraryA( libname );
2212 RestoreThunkLock( count );
2213 return hModule;
2216 /***************************************************************************
2217 * MapHModuleLS (KERNEL32.@)
2219 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2221 HMODULE16 ret;
2222 NE_MODULE *pModule;
2224 if (!hmod)
2225 return TASK_GetCurrent()->hInstance;
2226 if (!HIWORD(hmod))
2227 return LOWORD(hmod); /* we already have a 16 bit module handle */
2228 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2229 while (pModule) {
2230 if (pModule->module32 == hmod)
2231 return pModule->self;
2232 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2234 if ((ret = create_dummy_module( hmod )) < 32)
2236 SetLastError(ret);
2237 ret = 0;
2239 return ret;
2242 /***************************************************************************
2243 * MapHModuleSL (KERNEL32.@)
2245 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2247 NE_MODULE *pModule;
2249 if (!hmod) {
2250 TDB *pTask = TASK_GetCurrent();
2251 hmod = pTask->hModule;
2253 pModule = (NE_MODULE*)GlobalLock16(hmod);
2254 if ((pModule->magic!=IMAGE_OS2_SIGNATURE) || !(pModule->flags & NE_FFLAGS_WIN32))
2255 return 0;
2256 return pModule->module32;
2259 /***************************************************************************
2260 * MapHInstLS (KERNEL32.@)
2261 * MapHInstLS (KERNEL.472)
2263 void WINAPI MapHInstLS( CONTEXT86 *context )
2265 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2268 /***************************************************************************
2269 * MapHInstSL (KERNEL32.@)
2270 * MapHInstSL (KERNEL.473)
2272 void WINAPI MapHInstSL( CONTEXT86 *context )
2274 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2277 /***************************************************************************
2278 * MapHInstLS_PN (KERNEL32.@)
2280 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
2282 if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2285 /***************************************************************************
2286 * MapHInstSL_PN (KERNEL32.@)
2288 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
2290 if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );