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
22 #include "wine/port.h"
38 #include "wine/winbase16.h"
41 #include "wine/library.h"
46 #include "builtin16.h"
47 #include "stackframe.h"
49 #include "wine/unicode.h"
50 #include "wine/exception.h"
51 #include "wine/debug.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(module);
54 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
57 typedef struct _GPHANDLERDEF
69 struct ne_segment_table_entry_s
71 WORD seg_data_offset; /* Sector offset of segment data */
72 WORD seg_data_length; /* Length of segment data */
73 WORD seg_flags; /* Flags associated with this segment */
74 WORD min_alloc; /* Minimum allocation size for this */
77 #define hFirstModule (pThhook->hExeHead)
81 void *module_start; /* 32-bit address of the module data */
82 int module_size; /* Size of the module data */
83 void *code_start; /* 32-bit address of DLL code */
84 void *data_start; /* 32-bit address of DLL data */
85 const char *owner; /* 32-bit dll that contains this dll */
86 const void *rsrc; /* resources data */
87 } BUILTIN16_DESCRIPTOR;
89 /* Table of all built-in DLLs */
93 static const BUILTIN16_DESCRIPTOR *builtin_dlls[MAX_DLLS];
95 extern void SNOOP16_RegisterDLL(NE_MODULE*,LPCSTR);
96 extern FARPROC16 SNOOP16_GetProcAddress16(HMODULE16,DWORD,FARPROC16);
98 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
99 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
101 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
103 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
106 static WINE_EXCEPTION_FILTER(page_fault)
108 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
109 GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
110 return EXCEPTION_EXECUTE_HANDLER;
111 return EXCEPTION_CONTINUE_SEARCH;
115 /* patch all the flat cs references of the code segment if necessary */
116 inline static void patch_code_segment( void *code_segment )
119 CALLFROM16 *call = code_segment;
120 if (call->flatcs == wine_get_cs()) return; /* nothing to patch */
121 while (call->pushl == 0x68)
123 call->flatcs = wine_get_cs();
130 /***********************************************************************
133 * Find a descriptor in the list
135 static const BUILTIN16_DESCRIPTOR *find_dll_descr( const char *dllname )
138 for (i = 0; i < MAX_DLLS; i++)
140 const BUILTIN16_DESCRIPTOR *descr = builtin_dlls[i];
143 NE_MODULE *pModule = (NE_MODULE *)descr->module_start;
144 OFSTRUCT *pOfs = (OFSTRUCT *)((LPBYTE)pModule + pModule->fileinfo);
145 BYTE *name_table = (BYTE *)pModule + pModule->name_table;
147 /* check the dll file name */
148 if (!FILE_strcasecmp( pOfs->szPathName, dllname )) return descr;
149 /* check the dll module name (without extension) */
150 if (!FILE_strncasecmp( dllname, name_table+1, *name_table ) &&
151 !strcmp( dllname + *name_table, ".dll" ))
159 /***********************************************************************
162 * Check if a builtin dll descriptor is present (because we loaded its 32-bit counterpart).
164 static BOOL is_builtin_present( LPCSTR name )
166 char dllname[20], *p;
168 if (strlen(name) >= sizeof(dllname)-4) return FALSE;
169 strcpy( dllname, name );
170 p = strrchr( dllname, '.' );
171 if (!p) strcat( dllname, ".dll" );
172 for (p = dllname; *p; p++) *p = FILE_tolower(*p);
174 return (find_dll_descr( dllname ) != NULL);
178 /***********************************************************************
179 * __wine_register_dll_16 (KERNEL32.@)
181 * Register a built-in DLL descriptor.
183 void __wine_register_dll_16( const BUILTIN16_DESCRIPTOR *descr )
187 for (i = 0; i < MAX_DLLS; i++)
189 if (builtin_dlls[i]) continue;
190 builtin_dlls[i] = descr;
193 assert( i < MAX_DLLS );
197 /***********************************************************************
198 * __wine_unregister_dll_16 (KERNEL32.@)
200 * Unregister a built-in DLL descriptor.
202 void __wine_unregister_dll_16( const BUILTIN16_DESCRIPTOR *descr )
206 for (i = 0; i < MAX_DLLS; i++)
208 if (builtin_dlls[i] != descr) continue;
209 builtin_dlls[i] = NULL;
215 /***********************************************************************
218 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
220 return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
224 /**********************************************************************
227 static void NE_RegisterModule( NE_MODULE *pModule )
229 pModule->next = hFirstModule;
230 hFirstModule = pModule->self;
234 /***********************************************************************
237 void NE_DumpModule( HMODULE16 hModule )
247 if (!(pModule = NE_GetPtr( hModule )))
249 MESSAGE( "**** %04x is not a module handle\n", hModule );
253 /* Dump the module info */
255 DPRINTF( "Module %04x:\n", hModule );
256 DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
257 pModule->count, pModule->flags,
258 pModule->heap_size, pModule->stack_size );
259 DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
260 pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
261 pModule->seg_count, pModule->modref_count );
262 DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
263 pModule->os_flags, pModule->min_swap_area,
264 pModule->expected_version );
265 if (pModule->flags & NE_FFLAGS_WIN32)
266 DPRINTF( "PE module=%p\n", pModule->module32 );
268 /* Dump the file info */
270 DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
272 /* Dump the segment table */
274 DPRINTF( "Segment table:\n" );
275 pSeg = NE_SEG_TABLE( pModule );
276 for (i = 0; i < pModule->seg_count; i++, pSeg++)
277 DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
278 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
279 pSeg->minsize, pSeg->hSeg );
281 /* Dump the resource table */
283 DPRINTF( "Resource table:\n" );
284 if (pModule->res_table)
286 pword = (WORD *)((BYTE *)pModule + pModule->res_table);
287 DPRINTF( "Alignment: %d\n", *pword++ );
290 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
291 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
292 DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
293 for (i = 0; i < ptr->count; i++, pname++)
294 DPRINTF( "offset=%d len=%d id=%04x\n",
295 pname->offset, pname->length, pname->id );
296 pword = (WORD *)pname;
299 else DPRINTF( "None\n" );
301 /* Dump the resident name table */
303 DPRINTF( "Resident-name table:\n" );
304 pstr = (char *)pModule + pModule->name_table;
307 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
308 *(WORD *)(pstr + *pstr + 1) );
309 pstr += *pstr + 1 + sizeof(WORD);
312 /* Dump the module reference table */
314 DPRINTF( "Module ref table:\n" );
315 if (pModule->modref_table)
317 pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
318 for (i = 0; i < pModule->modref_count; i++, pword++)
321 GetModuleName16( *pword, name, sizeof(name) );
322 DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
325 else DPRINTF( "None\n" );
327 /* Dump the entry table */
329 DPRINTF( "Entry table:\n" );
330 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);
332 entry = (ET_ENTRY *)((BYTE *)bundle+6);
333 DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
334 ordinal = bundle->first;
335 while (ordinal < bundle->last)
337 if (entry->type == 0xff)
338 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
340 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
343 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
345 /* Dump the non-resident names table */
347 DPRINTF( "Non-resident names table:\n" );
348 if (pModule->nrname_handle)
350 pstr = (char *)GlobalLock16( pModule->nrname_handle );
353 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
354 *(WORD *)(pstr + *pstr + 1) );
355 pstr += *pstr + 1 + sizeof(WORD);
362 /***********************************************************************
365 * Walk the module list and print the modules.
367 void NE_WalkModules(void)
369 HMODULE16 hModule = hFirstModule;
370 MESSAGE( "Module Flags Name\n" );
373 NE_MODULE *pModule = NE_GetPtr( hModule );
376 MESSAGE( "Bad module %04x in list\n", hModule );
379 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->flags,
380 *((char *)pModule + pModule->name_table),
381 (char *)pModule + pModule->name_table + 1 );
382 hModule = pModule->next;
387 /***********************************************************************
388 * NE_InitResourceHandler
390 * Fill in 'resloader' fields in the resource table.
392 static void NE_InitResourceHandler( NE_MODULE *pModule )
394 static FARPROC16 proc;
396 NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
398 TRACE("InitResourceHandler[%04x]\n", pModule->self );
400 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
402 while(pTypeInfo->type_id)
404 memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
405 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
410 /***********************************************************************
413 * Lookup the ordinal for a given name.
415 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
417 unsigned char buffer[256], *cpnt;
421 if (!(pModule = NE_GetPtr( hModule ))) return 0;
422 if (pModule->flags & NE_FFLAGS_WIN32) return 0;
424 TRACE("(%04x,'%s')\n", hModule, name );
426 /* First handle names of the form '#xxxx' */
428 if (name[0] == '#') return atoi( name + 1 );
430 /* Now copy and uppercase the string */
432 strcpy( buffer, name );
433 for (cpnt = buffer; *cpnt; cpnt++) *cpnt = FILE_toupper(*cpnt);
436 /* First search the resident names */
438 cpnt = (char *)pModule + pModule->name_table;
440 /* Skip the first entry (module name) */
441 cpnt += *cpnt + 1 + sizeof(WORD);
444 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
447 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
448 TRACE(" Found: ordinal=%d\n", ordinal );
451 cpnt += *cpnt + 1 + sizeof(WORD);
454 /* Now search the non-resident names table */
456 if (!pModule->nrname_handle) return 0; /* No non-resident table */
457 cpnt = (char *)GlobalLock16( pModule->nrname_handle );
459 /* Skip the first entry (module description string) */
460 cpnt += *cpnt + 1 + sizeof(WORD);
463 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
466 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
467 TRACE(" Found: ordinal=%d\n", ordinal );
470 cpnt += *cpnt + 1 + sizeof(WORD);
476 /***********************************************************************
479 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
481 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
484 /***********************************************************************
487 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
495 if (!(pModule = NE_GetPtr( hModule ))) return 0;
496 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
498 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
499 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
503 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
506 entry = (ET_ENTRY *)((BYTE *)bundle+6);
507 for (i=0; i < (ordinal - bundle->first - 1); i++)
511 memcpy( &offset, &entry->offs, sizeof(WORD) );
513 if (sel == 0xfe) sel = 0xffff; /* constant entry */
514 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
516 return (FARPROC16)MAKESEGPTR( sel, offset );
518 return (FARPROC16)MAKESEGPTR( sel, offset );
520 return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
524 /***********************************************************************
525 * EntryAddrProc (KERNEL.667) Wine-specific export
527 * Return the entry point for a given ordinal.
529 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
531 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
532 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
536 /***********************************************************************
539 * Change the value of an entry point. Use with caution!
540 * It can only change the offset value, not the selector.
542 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
549 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
550 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
552 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
553 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
555 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
556 if (!(bundle->next)) return 0;
559 entry = (ET_ENTRY *)((BYTE *)bundle+6);
560 for (i=0; i < (ordinal - bundle->first - 1); i++)
563 memcpy( &entry->offs, &offset, sizeof(WORD) );
568 /***********************************************************************
571 HANDLE NE_OpenFile( NE_MODULE *pModule )
574 char *name = NE_MODULE_NAME( pModule );
576 TRACE("(%p)\n", pModule );
580 if (!DuplicateHandle( GetCurrentProcess(), pModule->fd,
581 GetCurrentProcess(), &handle, 0, FALSE,
582 DUPLICATE_SAME_ACCESS )) handle = INVALID_HANDLE_VALUE;
586 handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
587 NULL, OPEN_EXISTING, 0, 0 );
589 if (handle == INVALID_HANDLE_VALUE)
590 ERR( "Can't open file '%s' for module %04x\n", name, pModule->self );
592 TRACE("opened '%s' -> %p\n", name, handle);
597 /* wrapper for SetFilePointer and ReadFile */
598 static BOOL read_data( HANDLE handle, LONG offset, void *buffer, DWORD size )
602 if (SetFilePointer( handle, offset, NULL, SEEK_SET ) == INVALID_SET_FILE_POINTER) return FALSE;
603 if (!ReadFile( handle, buffer, size, &result, NULL )) return FALSE;
604 return (result == size);
607 /***********************************************************************
610 static HMODULE16 NE_LoadExeHeader( HANDLE handle, LPCSTR path )
612 IMAGE_DOS_HEADER mz_header;
613 IMAGE_OS2_HEADER ne_header;
617 BYTE *pData, *pTempEntryTable;
618 char *buffer, *fastload = NULL;
619 int fastload_offset = 0, fastload_length = 0;
621 ET_BUNDLE *bundle, *oldbundle;
624 /* Read a block from either the file or the fast-load area. */
625 #define READ(offset,size,buffer) \
626 ((fastload && ((offset) >= fastload_offset) && \
627 ((offset)+(size) <= fastload_offset+fastload_length)) ? \
628 (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
629 read_data( handle, (offset), (buffer), (size)))
631 if (!read_data( handle, 0, &mz_header, sizeof(mz_header)) ||
632 (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
633 return (HMODULE16)11; /* invalid exe */
635 if (!read_data( handle, mz_header.e_lfanew, &ne_header, sizeof(ne_header) ))
636 return (HMODULE16)11; /* invalid exe */
638 if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21; /* win32 exe */
639 if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
640 MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
641 return (HMODULE16)12;
643 if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11; /* invalid exe */
645 /* We now have a valid NE header */
647 size = sizeof(NE_MODULE) +
649 ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
651 ne_header.ne_restab - ne_header.ne_rsrctab +
652 /* resident names table */
653 ne_header.ne_modtab - ne_header.ne_restab +
654 /* module ref table */
655 ne_header.ne_cmod * sizeof(WORD) +
656 /* imported names table */
657 ne_header.ne_enttab - ne_header.ne_imptab +
658 /* entry table length */
659 ne_header.ne_cbenttab +
660 /* entry table extra conversion space */
662 2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
663 /* loaded file info */
664 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
666 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
667 if (!hModule) return (HMODULE16)11; /* invalid exe */
669 FarSetOwner16( hModule, hModule );
670 pModule = (NE_MODULE *)GlobalLock16( hModule );
671 memcpy( pModule, &ne_header, sizeof(ne_header) );
673 /* check *programs* for default minimal stack size */
674 if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
675 && (pModule->stack_size < 0x1400) )
676 pModule->stack_size = 0x1400;
677 pModule->module32 = 0;
678 pModule->self = hModule;
679 pModule->self_loading_sel = 0;
680 pData = (BYTE *)(pModule + 1);
682 /* Clear internal Wine flags in case they are set in the EXE file */
684 pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
686 /* Read the fast-load area */
688 if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
690 fastload_offset=ne_header.ne_pretthunks << ne_header.ne_align;
691 fastload_length=ne_header.ne_psegrefbytes << ne_header.ne_align;
692 TRACE("Using fast-load area offset=%x len=%d\n",
693 fastload_offset, fastload_length );
694 if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
696 if (!read_data( handle, fastload_offset, fastload, fastload_length))
698 HeapFree( GetProcessHeap(), 0, fastload );
699 WARN("Error reading fast-load area!\n");
705 /* Get the segment table */
707 pModule->seg_table = pData - (BYTE *)pModule;
708 buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
709 sizeof(struct ne_segment_table_entry_s));
713 struct ne_segment_table_entry_s *pSeg;
715 if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
716 ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
719 HeapFree( GetProcessHeap(), 0, buffer );
720 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
721 GlobalFree16( hModule );
722 return (HMODULE16)11; /* invalid exe */
724 pSeg = (struct ne_segment_table_entry_s *)buffer;
725 for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
727 memcpy( pData, pSeg, sizeof(*pSeg) );
728 pData += sizeof(SEGTABLEENTRY);
730 HeapFree( GetProcessHeap(), 0, buffer );
734 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
735 GlobalFree16( hModule );
736 return (HMODULE16)11; /* invalid exe */
739 /* Get the resource table */
741 if (ne_header.ne_rsrctab < ne_header.ne_restab)
743 pModule->res_table = pData - (BYTE *)pModule;
744 if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
745 ne_header.ne_restab - ne_header.ne_rsrctab,
747 return (HMODULE16)11; /* invalid exe */
748 pData += ne_header.ne_restab - ne_header.ne_rsrctab;
749 NE_InitResourceHandler( pModule );
751 else pModule->res_table = 0; /* No resource table */
753 /* Get the resident names table */
755 pModule->name_table = pData - (BYTE *)pModule;
756 if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
757 ne_header.ne_modtab - ne_header.ne_restab,
760 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
761 GlobalFree16( hModule );
762 return (HMODULE16)11; /* invalid exe */
764 pData += ne_header.ne_modtab - ne_header.ne_restab;
766 /* Get the module references table */
768 if (ne_header.ne_cmod > 0)
770 pModule->modref_table = pData - (BYTE *)pModule;
771 if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
772 ne_header.ne_cmod * sizeof(WORD),
775 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
776 GlobalFree16( hModule );
777 return (HMODULE16)11; /* invalid exe */
779 pData += ne_header.ne_cmod * sizeof(WORD);
781 else pModule->modref_table = 0; /* No module references */
783 /* Get the imported names table */
785 pModule->import_table = pData - (BYTE *)pModule;
786 if (!READ( mz_header.e_lfanew + ne_header.ne_imptab,
787 ne_header.ne_enttab - ne_header.ne_imptab,
790 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
791 GlobalFree16( hModule );
792 return (HMODULE16)11; /* invalid exe */
794 pData += ne_header.ne_enttab - ne_header.ne_imptab;
796 /* Load entry table, convert it to the optimized version used by Windows */
798 if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
800 BYTE nr_entries, type, *s;
802 TRACE("Converting entry table.\n");
803 pModule->entry_table = pData - (BYTE *)pModule;
804 if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
805 ne_header.ne_cbenttab, pTempEntryTable ))
807 HeapFree( GetProcessHeap(), 0, pTempEntryTable );
808 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
809 GlobalFree16( hModule );
810 return (HMODULE16)11; /* invalid exe */
814 TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
816 bundle = (ET_BUNDLE *)pData;
817 TRACE("first bundle: %p\n", bundle);
818 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
819 entry = (ET_ENTRY *)((BYTE *)bundle+6);
821 while ((nr_entries = *s++))
825 bundle->last += nr_entries;
832 entry->segnum = *s++;
833 entry->offs = *(WORD *)s; s += 2;
834 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
842 entry->segnum = type;
843 entry->offs = *(WORD *)s; s += 2;
844 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
850 if (bundle->first == bundle->last)
852 bundle->first += nr_entries;
853 bundle->last += nr_entries;
858 oldbundle->next = ((int)entry - (int)pModule);
859 bundle = (ET_BUNDLE *)entry;
860 TRACE("new bundle: %p\n", bundle);
861 bundle->first = bundle->last =
862 oldbundle->last + nr_entries;
864 (BYTE *)entry += sizeof(ET_BUNDLE);
868 HeapFree( GetProcessHeap(), 0, pTempEntryTable );
872 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
873 GlobalFree16( hModule );
874 return (HMODULE16)11; /* invalid exe */
877 pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
878 2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
880 if ((DWORD)entry > (DWORD)pData)
881 ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
883 /* Store the filename information */
885 pModule->fileinfo = pData - (BYTE *)pModule;
886 size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
887 ofs = (OFSTRUCT *)pData;
888 ofs->cBytes = size - 1;
890 strcpy( ofs->szPathName, path );
893 /* Free the fast-load area */
896 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
898 /* Get the non-resident names table */
900 if (ne_header.ne_cbnrestab)
902 pModule->nrname_handle = GlobalAlloc16( 0, ne_header.ne_cbnrestab );
903 if (!pModule->nrname_handle)
905 GlobalFree16( hModule );
906 return (HMODULE16)11; /* invalid exe */
908 FarSetOwner16( pModule->nrname_handle, hModule );
909 buffer = GlobalLock16( pModule->nrname_handle );
910 if (!read_data( handle, ne_header.ne_nrestab, buffer, ne_header.ne_cbnrestab ))
912 GlobalFree16( pModule->nrname_handle );
913 GlobalFree16( hModule );
914 return (HMODULE16)11; /* invalid exe */
917 else pModule->nrname_handle = 0;
919 /* Allocate a segment for the implicitly-loaded DLLs */
921 if (pModule->modref_count)
923 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
924 (pModule->modref_count+1)*sizeof(HMODULE16) );
925 if (!pModule->dlls_to_init)
927 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
928 GlobalFree16( hModule );
929 return (HMODULE16)11; /* invalid exe */
931 FarSetOwner16( pModule->dlls_to_init, hModule );
933 else pModule->dlls_to_init = 0;
935 NE_RegisterModule( pModule );
936 SNOOP16_RegisterDLL(pModule,path);
941 /***********************************************************************
944 * Load all DLLs implicitly linked to a module.
946 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
949 WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
950 WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
952 for (i = 0; i < pModule->modref_count; i++, pModRef++)
954 char buffer[260], *p;
955 BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
956 memcpy( buffer, pstr + 1, *pstr );
957 *(buffer + *pstr) = 0; /* terminate it */
959 TRACE("Loading '%s'\n", buffer );
960 if (!(*pModRef = GetModuleHandle16( buffer )))
962 /* If the DLL is not loaded yet, load it and store */
963 /* its handle in the list of DLLs to initialize. */
966 /* Append .DLL to name if no extension present */
967 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
968 strcat( buffer, ".DLL" );
970 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
972 /* FIXME: cleanup what was done */
974 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
975 buffer, *((BYTE*)pModule + pModule->name_table),
976 (char *)pModule + pModule->name_table + 1, hDLL );
979 *pModRef = GetExePtr( hDLL );
982 else /* Increment the reference count of the DLL */
984 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
985 if (pOldDLL) pOldDLL->count++;
992 /**********************************************************************
995 * Load first instance of NE module from file.
997 * pModule must point to a module structure prepared by NE_LoadExeHeader.
998 * This routine must never be called twice on a module.
1001 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
1003 /* Allocate the segments for this module */
1005 if (!NE_CreateAllSegments( pModule ))
1006 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
1008 /* Load the referenced DLLs */
1010 if (!NE_LoadDLLs( pModule ))
1011 return ERROR_FILE_NOT_FOUND; /* 2 */
1013 /* Load the segments */
1015 NE_LoadAllSegments( pModule );
1017 /* Make sure the usage count is 1 on the first loading of */
1018 /* the module, even if it contains circular DLL references */
1022 return NE_GetInstance( pModule );
1025 /**********************************************************************
1028 * Load first instance of NE module. (Note: caller is responsible for
1029 * ensuring the module isn't already loaded!)
1031 * If the module turns out to be an executable module, only a
1032 * handle to a module stub is returned; this needs to be initialized
1033 * by calling NE_DoLoadModule later, in the context of the newly
1036 * If lib_only is TRUE, however, the module is perforce treated
1037 * like a DLL module, even if it is an executable module.
1040 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
1044 HINSTANCE16 hInstance;
1050 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
1051 return (HMODULE16)2; /* File not found */
1053 hModule = NE_LoadExeHeader( DosFileHandleToWin32Handle(hFile), ofs.szPathName );
1059 pModule = NE_GetPtr( hModule );
1061 drive_type = GetDriveTypeA( ofs.szPathName );
1062 if (drive_type != DRIVE_REMOVABLE && drive_type != DRIVE_CDROM)
1064 /* keep the file handle open if not on a removable media */
1065 DuplicateHandle( GetCurrentProcess(), DosFileHandleToWin32Handle(hFile),
1066 GetCurrentProcess(), &pModule->fd, 0, FALSE,
1067 DUPLICATE_SAME_ACCESS );
1071 if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
1074 hInstance = NE_DoLoadModule( pModule );
1075 if ( hInstance < 32 )
1078 NE_FreeModule( hModule, 0 );
1085 /***********************************************************************
1086 * NE_DoLoadBuiltinModule
1088 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
1090 static HMODULE16 NE_DoLoadBuiltinModule( const BUILTIN16_DESCRIPTOR *descr )
1094 SEGTABLEENTRY *pSegTable;
1097 hModule = GLOBAL_CreateBlock( GMEM_MOVEABLE, descr->module_start,
1098 descr->module_size, 0, WINE_LDT_FLAGS_DATA );
1099 if (!hModule) return 0;
1100 FarSetOwner16( hModule, hModule );
1102 pModule = (NE_MODULE *)GlobalLock16( hModule );
1103 pModule->self = hModule;
1104 /* NOTE: (Ab)use the hRsrcMap parameter for resource data pointer */
1105 pModule->hRsrcMap = (void *)descr->rsrc;
1107 /* Allocate the code segment */
1109 pSegTable = NE_SEG_TABLE( pModule );
1110 pSegTable->hSeg = GLOBAL_CreateBlock( GMEM_FIXED, descr->code_start,
1111 pSegTable->minsize, hModule,
1112 WINE_LDT_FLAGS_CODE|WINE_LDT_FLAGS_32BIT );
1113 if (!pSegTable->hSeg) return 0;
1114 patch_code_segment( descr->code_start );
1117 /* Allocate the data segment */
1119 minsize = pSegTable->minsize ? pSegTable->minsize : 0x10000;
1120 minsize += pModule->heap_size;
1121 if (minsize > 0x10000) minsize = 0x10000;
1122 pSegTable->hSeg = GlobalAlloc16( GMEM_FIXED, minsize );
1123 if (!pSegTable->hSeg) return 0;
1124 FarSetOwner16( pSegTable->hSeg, hModule );
1125 if (pSegTable->minsize) memcpy( GlobalLock16( pSegTable->hSeg ),
1126 descr->data_start, pSegTable->minsize);
1127 if (pModule->heap_size)
1128 LocalInit16( GlobalHandleToSel16(pSegTable->hSeg), pSegTable->minsize, minsize );
1130 if (descr->rsrc) NE_InitResourceHandler(pModule);
1132 NE_RegisterModule( pModule );
1134 /* make sure the 32-bit library containing this one is loaded too */
1135 LoadLibraryA( descr->owner );
1141 /***********************************************************************
1142 * NE_LoadBuiltinModule
1144 * Load a built-in module.
1146 static HMODULE16 NE_LoadBuiltinModule( LPCSTR name )
1148 const BUILTIN16_DESCRIPTOR *descr;
1149 char error[256], dllname[20], *p;
1153 /* Fix the name in case we have a full path and extension */
1155 if ((p = strrchr( name, '\\' ))) name = p + 1;
1156 if ((p = strrchr( name, '/' ))) name = p + 1;
1158 if (strlen(name) >= sizeof(dllname)-4) return (HMODULE16)2;
1160 strcpy( dllname, name );
1161 p = strrchr( dllname, '.' );
1162 if (!p) strcat( dllname, ".dll" );
1163 for (p = dllname; *p; p++) *p = FILE_tolower(*p);
1165 if ((descr = find_dll_descr( dllname )))
1166 return NE_DoLoadBuiltinModule( descr );
1168 if ((handle = wine_dll_load( dllname, error, sizeof(error), &file_exists )))
1170 if ((descr = find_dll_descr( dllname )))
1171 return NE_DoLoadBuiltinModule( descr );
1172 if (GetModuleHandleA( dllname ))
1173 return 21; /* Win32 module */
1174 ERR( "loaded .so but dll %s still not found\n", dllname );
1178 if (!file_exists) WARN("cannot open .so lib for 16-bit builtin %s: %s\n", name, error);
1179 else ERR("failed to load .so lib for 16-bit builtin %s: %s\n", name, error );
1181 return (HMODULE16)2;
1185 /**********************************************************************
1186 * MODULE_LoadModule16
1188 * Load a NE module in the order of the loadorder specification.
1189 * The caller is responsible that the module is not loaded already.
1192 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1194 HINSTANCE16 hinst = 2;
1195 enum loadorder_type loadorder[LOADORDER_NTYPES];
1197 const char *filetype = "";
1198 const char *ptr, *basename;
1200 /* strip path information */
1203 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
1204 if ((ptr = strrchr( basename, '\\' ))) basename = ptr + 1;
1205 if ((ptr = strrchr( basename, '/' ))) basename = ptr + 1;
1207 if (is_builtin_present(basename))
1209 TRACE( "forcing loadorder to builtin for %s\n", debugstr_a(basename) );
1210 /* force builtin loadorder since the dll is already in memory */
1211 loadorder[0] = LOADORDER_BI;
1212 loadorder[1] = LOADORDER_INVALID;
1216 UNICODE_STRING pathW;
1217 WCHAR buffer[MAX_PATH], *p;
1219 if (!GetModuleFileNameW( 0, buffer, MAX_PATH )) p = NULL;
1222 if ((p = strrchrW( buffer, '\\' ))) p++;
1225 RtlCreateUnicodeStringFromAsciiz( &pathW, basename );
1226 MODULE_GetLoadOrderW( loadorder, p, pathW.Buffer );
1227 RtlFreeUnicodeString( &pathW );
1230 for(i = 0; i < LOADORDER_NTYPES; i++)
1232 if (loadorder[i] == LOADORDER_INVALID) break;
1234 switch(loadorder[i])
1237 TRACE("Trying native dll '%s'\n", libname);
1238 hinst = NE_LoadModule(libname, lib_only);
1239 filetype = "native";
1243 TRACE("Trying built-in '%s'\n", libname);
1244 hinst = NE_LoadBuiltinModule(libname);
1245 filetype = "builtin";
1255 TRACE_(loaddll)("Loaded module '%s' : %s\n", libname, filetype);
1261 hModule = GetModuleHandle16(libname);
1264 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1266 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
1269 pModule = NE_GetPtr(hModule);
1272 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1274 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
1277 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1280 * Call initialization routines for all loaded DLLs. Note that
1281 * when we load implicitly linked DLLs this will be done by InitTask().
1283 if(pModule->flags & NE_FFLAGS_LIBMODULE)
1285 NE_InitializeDLLs(hModule);
1286 NE_DllProcessAttach(hModule);
1294 /* We quit searching when we get another error than 'File not found' */
1298 return hinst; /* The last error that occurred */
1302 /**********************************************************************
1305 * Create the thread for a 16-bit module.
1307 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1312 HINSTANCE16 instance = 0;
1314 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1317 /* Post event to start the task */
1318 PostEvent16( hTask );
1320 /* Wait until we get the instance handle */
1323 DirectedYield16( hTask );
1324 if (!IsTask16( hTask )) /* thread has died */
1327 WaitForSingleObject( hThread, INFINITE );
1328 GetExitCodeThread( hThread, &exit_code );
1329 CloseHandle( hThread );
1332 if (!(pTask = GlobalLock16( hTask ))) break;
1333 instance = pTask->hInstance;
1334 GlobalUnlock16( hTask );
1335 } while (!instance);
1337 CloseHandle( hThread );
1342 /**********************************************************************
1343 * LoadModule (KERNEL.45)
1345 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1347 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1348 LOADPARAMS16 *params;
1356 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1358 /* Special case: second instance of an already loaded NE module */
1360 if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1361 if ( pModule->module32 ) return (HINSTANCE16)21;
1363 /* Increment refcount */
1369 /* Main case: load first instance of NE module */
1371 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1374 if ( !(pModule = NE_GetPtr( hModule )) )
1375 return (HINSTANCE16)11;
1378 /* If library module, we just retrieve the instance handle */
1380 if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1381 return NE_GetInstance( pModule );
1384 * At this point, we need to create a new process.
1386 * pModule points either to an already loaded module, whose refcount
1387 * has already been incremented (to avoid having the module vanish
1388 * in the meantime), or else to a stub module which contains only header
1391 params = (LOADPARAMS16 *)paramBlock;
1392 cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1393 cmdline = MapSL( params->cmdLine );
1394 return NE_CreateThread( pModule, cmdShow, cmdline );
1398 /**********************************************************************
1401 * Startup code for a new 16-bit task.
1403 DWORD NE_StartTask(void)
1405 TDB *pTask = TASK_GetCurrent();
1406 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1407 HINSTANCE16 hInstance, hPrevInstance;
1408 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1411 if ( pModule->count > 0 )
1413 /* Second instance of an already loaded NE module */
1414 /* Note that the refcount was already incremented by the parent */
1416 hPrevInstance = NE_GetInstance( pModule );
1418 if ( pModule->dgroup )
1419 if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1420 NE_LoadSegment( pModule, pModule->dgroup );
1422 hInstance = NE_GetInstance( pModule );
1423 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1428 /* Load first instance of NE module */
1430 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1432 hInstance = NE_DoLoadModule( pModule );
1436 if ( hInstance >= 32 )
1440 /* Enter instance handles into task struct */
1442 pTask->hInstance = hInstance;
1443 pTask->hPrevInstance = hPrevInstance;
1445 /* Use DGROUP for 16-bit stack */
1447 if (!(sp = pModule->sp))
1448 sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1450 sp -= sizeof(STACK16FRAME);
1451 NtCurrentTeb()->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1453 /* Registers at initialization must be:
1455 * bx stack size in bytes
1456 * cx heap size in bytes
1457 * si previous app instance
1458 * di current app instance
1460 * es selector to the PSP
1461 * ds dgroup of the application
1463 * sp top of the stack
1465 memset( &context, 0, sizeof(context) );
1466 context.SegCs = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1467 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1468 context.SegEs = pTask->hPDB;
1469 context.SegFs = wine_get_fs();
1470 context.SegGs = wine_get_gs();
1471 context.Eip = pModule->ip;
1472 context.Ebx = pModule->stack_size;
1473 context.Ecx = pModule->heap_size;
1474 context.Edi = pTask->hInstance;
1475 context.Esi = pTask->hPrevInstance;
1477 /* Now call 16-bit entry point */
1479 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1480 context.SegCs, context.Eip, context.SegDs,
1481 SELECTOROF(NtCurrentTeb()->cur_stack),
1482 OFFSETOF(NtCurrentTeb()->cur_stack) );
1484 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1485 ExitThread( LOWORD(context.Eax) );
1487 return hInstance; /* error code */
1490 /***********************************************************************
1491 * LoadLibrary (KERNEL.95)
1492 * LoadLibrary16 (KERNEL32.35)
1494 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1496 return LoadModule16(libname, (LPVOID)-1 );
1500 /**********************************************************************
1503 * Call a DLL's WEP, allowing it to shut down.
1504 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1506 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1509 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1510 if (!WEP) return FALSE;
1517 args[0] = WEP_FREE_DLL;
1518 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1519 ret = LOWORD(dwRet);
1521 __EXCEPT(page_fault)
1523 WARN("Page fault\n");
1532 /**********************************************************************
1535 * Implementation of FreeModule16().
1537 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1539 HMODULE16 *hPrevModule;
1544 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1545 hModule = pModule->self;
1547 TRACE("%04x count %d\n", hModule, pModule->count );
1549 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1550 else pModule->count = 0;
1552 if (pModule->flags & NE_FFLAGS_BUILTIN)
1553 return FALSE; /* Can't free built-in module */
1555 if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1557 /* Free the objects owned by the DLL module */
1558 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1560 if (pModule->flags & NE_FFLAGS_LIBMODULE)
1561 MODULE_CallWEP( hModule );
1563 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1567 /* Clear magic number just in case */
1569 pModule->magic = pModule->self = 0;
1570 if (pModule->fd) CloseHandle( pModule->fd );
1572 /* Remove it from the linked list */
1574 hPrevModule = &hFirstModule;
1575 while (*hPrevModule && (*hPrevModule != hModule))
1577 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1579 if (*hPrevModule) *hPrevModule = pModule->next;
1581 /* Free the referenced modules */
1583 pModRef = (HMODULE16*)((char *)pModule + pModule->modref_table);
1584 for (i = 0; i < pModule->modref_count; i++, pModRef++)
1586 NE_FreeModule( *pModRef, call_wep );
1589 /* Free the module storage */
1591 GlobalFreeAll16( hModule );
1596 /**********************************************************************
1597 * FreeModule (KERNEL.46)
1599 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1601 return NE_FreeModule( hModule, TRUE );
1605 /***********************************************************************
1606 * FreeLibrary (KERNEL.96)
1607 * FreeLibrary16 (KERNEL32.36)
1609 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1611 TRACE("%04x\n", handle );
1612 FreeModule16( handle );
1616 /***********************************************************************
1617 * GetModuleHandle16 (KERNEL32.@)
1619 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1621 HMODULE16 hModule = hFirstModule;
1623 BYTE len, *name_table;
1624 char tmpstr[MAX_PATH];
1627 TRACE("(%s)\n", name);
1629 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1634 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1636 /* If 'name' matches exactly the module name of a module:
1637 * Return its handle.
1639 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1641 pModule = NE_GetPtr( hModule );
1642 if (!pModule) break;
1643 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1645 name_table = (BYTE *)pModule + pModule->name_table;
1646 if ((*name_table == len) && !strncmp(name, name_table+1, len))
1650 /* If uppercased 'name' matches exactly the module name of a module:
1653 for (s = tmpstr; *s; s++) *s = FILE_toupper(*s);
1655 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1657 pModule = NE_GetPtr( hModule );
1658 if (!pModule) break;
1659 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1661 name_table = (BYTE *)pModule + pModule->name_table;
1662 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1663 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1664 * lowercased module names, but try to load uppercase DLLs, so this
1665 * 'i' compare is just a quickfix until the loader handles that
1666 * correctly. -MM 990705
1668 if ((*name_table == len) && !FILE_strncasecmp(tmpstr, name_table+1, len))
1672 /* If the base filename of 'name' matches the base filename of the module
1673 * filename of some module (case-insensitive compare):
1674 * Return its handle.
1677 /* basename: search backwards in passed name to \ / or : */
1678 s = tmpstr + strlen(tmpstr);
1681 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1686 /* search this in loaded filename list */
1687 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1692 pModule = NE_GetPtr( hModule );
1693 if (!pModule) break;
1694 if (!pModule->fileinfo) continue;
1695 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1697 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1698 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1699 /* basename: search backwards in pathname to \ / or : */
1700 while (loadedfn > (char*)ofs->szPathName)
1702 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1706 /* case insensitive compare ... */
1707 if (!FILE_strcasecmp(loadedfn, s))
1714 /**********************************************************************
1715 * GetModuleName (KERNEL.27)
1717 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1722 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1723 p = (BYTE *)pModule + pModule->name_table;
1724 if (count > *p) count = *p + 1;
1727 memcpy( buf, p + 1, count - 1 );
1728 buf[count-1] = '\0';
1734 /**********************************************************************
1735 * GetModuleFileName (KERNEL.49)
1737 * Comment: see GetModuleFileNameA
1739 * Even if invoked by second instance of a program,
1740 * it still returns path of first one.
1742 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1747 /* Win95 does not query hModule if set to 0 !
1748 * Is this wrong or maybe Win3.1 only ? */
1749 if (!hModule) hModule = GetCurrentTask();
1751 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1752 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1753 if (pModule->expected_version >= 0x400)
1754 GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1755 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1756 return strlen(lpFileName);
1760 /**********************************************************************
1761 * GetModuleUsage (KERNEL.48)
1763 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1765 NE_MODULE *pModule = NE_GetPtr( hModule );
1766 return pModule ? pModule->count : 0;
1770 /**********************************************************************
1771 * GetExpWinVer (KERNEL.167)
1773 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1775 NE_MODULE *pModule = NE_GetPtr( hModule );
1776 if ( !pModule ) return 0;
1779 * For built-in modules, fake the expected version the module should
1780 * have according to the Windows version emulated by Wine
1782 if ( !pModule->expected_version )
1784 OSVERSIONINFOA versionInfo;
1785 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1787 if ( GetVersionExA( &versionInfo ) )
1788 pModule->expected_version =
1789 (versionInfo.dwMajorVersion & 0xff) << 8
1790 | (versionInfo.dwMinorVersion & 0xff);
1793 return pModule->expected_version;
1797 /***********************************************************************
1798 * WinExec (KERNEL.166)
1800 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1802 LPCSTR p, args = NULL;
1803 LPCSTR name_beg, name_end;
1804 LPSTR name, cmdline;
1807 char buffer[MAX_PATH];
1809 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1811 name_beg = lpCmdLine+1;
1812 p = strchr ( lpCmdLine+1, '"' );
1816 args = strchr ( p, ' ' );
1818 else /* yes, even valid with trailing '"' missing */
1819 name_end = lpCmdLine+strlen(lpCmdLine);
1823 name_beg = lpCmdLine;
1824 args = strchr( lpCmdLine, ' ' );
1825 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1828 if ((name_beg == lpCmdLine) && (!args))
1829 { /* just use the original cmdline string as file name */
1830 name = (LPSTR)lpCmdLine;
1834 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1835 return ERROR_NOT_ENOUGH_MEMORY;
1836 memcpy( name, name_beg, name_end - name_beg );
1837 name[name_end - name_beg] = '\0';
1843 arglen = strlen(args);
1844 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1845 cmdline[0] = (BYTE)arglen;
1846 strcpy( cmdline + 1, args );
1850 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1851 cmdline[0] = cmdline[1] = 0;
1854 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1856 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1858 LOADPARAMS16 params;
1861 showCmd[1] = nCmdShow;
1863 params.hEnvironment = 0;
1864 params.cmdLine = MapLS( cmdline );
1865 params.showCmd = MapLS( showCmd );
1866 params.reserved = 0;
1868 ret = LoadModule16( buffer, ¶ms );
1869 UnMapLS( params.cmdLine );
1870 UnMapLS( params.showCmd );
1872 else ret = GetLastError();
1874 HeapFree( GetProcessHeap(), 0, cmdline );
1875 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1877 if (ret == 21) /* 32-bit module */
1880 ReleaseThunkLock( &count );
1881 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1882 RestoreThunkLock( count );
1887 /***********************************************************************
1888 * GetProcAddress (KERNEL.50)
1890 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1895 if (!hModule) hModule = GetCurrentTask();
1896 hModule = GetExePtr( hModule );
1898 if (HIWORD(name) != 0)
1900 ordinal = NE_GetOrdinal( hModule, name );
1901 TRACE("%04x '%s'\n", hModule, name );
1905 ordinal = LOWORD(name);
1906 TRACE("%04x %04x\n", hModule, ordinal );
1908 if (!ordinal) return (FARPROC16)0;
1910 ret = NE_GetEntryPoint( hModule, ordinal );
1912 TRACE("returning %08x\n", (UINT)ret );
1917 /***************************************************************************
1918 * HasGPHandler (KERNEL.338)
1920 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1925 GPHANDLERDEF *gpHandler;
1927 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1928 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1929 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1930 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1931 && (gpHandler = MapSL( gpPtr )) != NULL )
1933 while (gpHandler->selector)
1935 if ( SELECTOROF(address) == gpHandler->selector
1936 && OFFSETOF(address) >= gpHandler->rangeStart
1937 && OFFSETOF(address) < gpHandler->rangeEnd )
1938 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1947 /**********************************************************************
1948 * GetModuleHandle (KERNEL.47)
1950 * Find a module from a module name.
1952 * NOTE: The current implementation works the same way the Windows 95 one
1953 * does. Do not try to 'fix' it, fix the callers.
1954 * + It does not do ANY extension handling (except that strange .EXE bit)!
1955 * + It does not care about paths, just about basenames. (same as Windows)
1959 * the win16 module handle if found
1961 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1962 * Always hFirstModule
1964 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1966 if (HIWORD(name) == 0)
1967 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1968 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1971 /**********************************************************************
1972 * NE_GetModuleByFilename
1974 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1978 BYTE len, *name_table;
1979 char tmpstr[MAX_PATH];
1982 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1984 /* If the base filename of 'name' matches the base filename of the module
1985 * filename of some module (case-insensitive compare):
1986 * Return its handle.
1989 /* basename: search backwards in passed name to \ / or : */
1990 s = tmpstr + strlen(tmpstr);
1993 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1998 /* search this in loaded filename list */
1999 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2004 pModule = NE_GetPtr( hModule );
2005 if (!pModule) break;
2006 if (!pModule->fileinfo) continue;
2007 if (pModule->flags & NE_FFLAGS_WIN32) continue;
2009 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
2010 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
2011 /* basename: search backwards in pathname to \ / or : */
2012 while (loadedfn > (char*)ofs->szPathName)
2014 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
2018 /* case insensitive compare ... */
2019 if (!FILE_strcasecmp(loadedfn, s))
2022 /* If basename (without ext) matches the module name of a module:
2023 * Return its handle.
2026 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
2029 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2031 pModule = NE_GetPtr( hModule );
2032 if (!pModule) break;
2033 if (pModule->flags & NE_FFLAGS_WIN32) continue;
2035 name_table = (BYTE *)pModule + pModule->name_table;
2036 if ((*name_table == len) && !FILE_strncasecmp(s, name_table+1, len))
2043 /***********************************************************************
2044 * GetProcAddress16 (KERNEL32.37)
2045 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
2047 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
2049 if (!hModule) return 0;
2050 if (HIWORD(hModule))
2052 WARN("hModule is Win32 handle (%p)\n", hModule );
2055 return GetProcAddress16( LOWORD(hModule), name );
2058 /**********************************************************************
2059 * ModuleFirst (TOOLHELP.59)
2061 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
2063 lpme->wNext = hFirstModule;
2064 return ModuleNext16( lpme );
2068 /**********************************************************************
2069 * ModuleNext (TOOLHELP.60)
2071 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
2076 if (!lpme->wNext) return FALSE;
2077 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
2078 name = (char *)pModule + pModule->name_table;
2079 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
2080 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
2081 lpme->hModule = lpme->wNext;
2082 lpme->wcUsage = pModule->count;
2083 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
2084 lpme->wNext = pModule->next;
2089 /**********************************************************************
2090 * ModuleFindName (TOOLHELP.61)
2092 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
2094 lpme->wNext = GetModuleHandle16( name );
2095 return ModuleNext16( lpme );
2099 /**********************************************************************
2100 * ModuleFindHandle (TOOLHELP.62)
2102 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
2104 hModule = GetExePtr( hModule );
2105 lpme->wNext = hModule;
2106 return ModuleNext16( lpme );
2110 /***************************************************************************
2111 * IsRomModule (KERNEL.323)
2113 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
2118 /***************************************************************************
2119 * IsRomFile (KERNEL.326)
2121 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
2126 /***********************************************************************
2127 * create_dummy_module
2129 * Create a dummy NE module for Win32 or Winelib.
2131 static HMODULE16 create_dummy_module( HMODULE module32 )
2135 SEGTABLEENTRY *pSegment;
2138 const char* basename;
2141 char filename[MAX_PATH];
2142 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
2144 if (!nt) return (HMODULE16)11; /* invalid exe */
2146 /* Extract base filename */
2147 GetModuleFileNameA( module32, filename, sizeof(filename) );
2148 basename = strrchr(filename, '\\');
2149 if (!basename) basename = filename;
2151 len = strlen(basename);
2152 if ((s = strchr(basename, '.'))) len = s - basename;
2154 /* Allocate module */
2155 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2156 + strlen(filename) + 1;
2157 size = sizeof(NE_MODULE) +
2158 /* loaded file info */
2159 ((of_size + 3) & ~3) +
2160 /* segment table: DS,CS */
2161 2 * sizeof(SEGTABLEENTRY) +
2164 /* several empty tables */
2167 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2168 if (!hModule) return (HMODULE16)11; /* invalid exe */
2170 FarSetOwner16( hModule, hModule );
2171 pModule = (NE_MODULE *)GlobalLock16( hModule );
2173 /* Set all used entries */
2174 pModule->magic = IMAGE_OS2_SIGNATURE;
2177 pModule->flags = NE_FFLAGS_WIN32;
2178 pModule->dgroup = 0;
2181 pModule->heap_size = 0;
2182 pModule->stack_size = 0;
2183 pModule->seg_count = 2;
2184 pModule->modref_count = 0;
2185 pModule->nrname_size = 0;
2186 pModule->fileinfo = sizeof(NE_MODULE);
2187 pModule->os_flags = NE_OSFLAGS_WINDOWS;
2188 pModule->self = hModule;
2189 pModule->module32 = module32;
2191 /* Set version and flags */
2192 pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2193 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2194 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2195 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2197 /* Set loaded file information */
2198 ofs = (OFSTRUCT *)(pModule + 1);
2199 memset( ofs, 0, of_size );
2200 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
2201 strcpy( ofs->szPathName, filename );
2203 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2204 pModule->seg_table = (int)pSegment - (int)pModule;
2207 pSegment->flags = NE_SEGFLAGS_DATA;
2208 pSegment->minsize = 0x1000;
2211 pSegment->flags = 0;
2215 pStr = (char *)pSegment;
2216 pModule->name_table = (int)pStr - (int)pModule;
2219 lstrcpynA( pStr+1, basename, len+1 );
2222 /* All tables zero terminated */
2223 pModule->res_table = pModule->import_table = pModule->entry_table = (int)pStr - (int)pModule;
2225 NE_RegisterModule( pModule );
2226 LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
2230 /***********************************************************************
2231 * PrivateLoadLibrary (KERNEL32.@)
2233 * FIXME: rough guesswork, don't know what "Private" means
2235 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2237 return LoadLibrary16(libname);
2240 /***********************************************************************
2241 * PrivateFreeLibrary (KERNEL32.@)
2243 * FIXME: rough guesswork, don't know what "Private" means
2245 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2247 FreeLibrary16(handle);
2250 /***********************************************************************
2251 * LoadLibrary32 (KERNEL.452)
2252 * LoadSystemLibrary32 (KERNEL.482)
2254 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2259 ReleaseThunkLock( &count );
2260 hModule = LoadLibraryA( libname );
2261 RestoreThunkLock( count );
2265 /***************************************************************************
2266 * MapHModuleLS (KERNEL32.@)
2268 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2274 return TASK_GetCurrent()->hInstance;
2276 return LOWORD(hmod); /* we already have a 16 bit module handle */
2277 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2279 if (pModule->module32 == hmod)
2280 return pModule->self;
2281 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2283 if ((ret = create_dummy_module( hmod )) < 32)
2291 /***************************************************************************
2292 * MapHModuleSL (KERNEL32.@)
2294 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2299 TDB *pTask = TASK_GetCurrent();
2300 hmod = pTask->hModule;
2302 pModule = (NE_MODULE*)GlobalLock16(hmod);
2303 if ((pModule->magic!=IMAGE_OS2_SIGNATURE) || !(pModule->flags & NE_FFLAGS_WIN32))
2305 return pModule->module32;
2308 /***************************************************************************
2309 * MapHInstLS (KERNEL32.@)
2310 * MapHInstLS (KERNEL.472)
2312 void WINAPI MapHInstLS( CONTEXT86 *context )
2314 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2317 /***************************************************************************
2318 * MapHInstSL (KERNEL32.@)
2319 * MapHInstSL (KERNEL.473)
2321 void WINAPI MapHInstSL( CONTEXT86 *context )
2323 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2326 /***************************************************************************
2327 * MapHInstLS_PN (KERNEL32.@)
2329 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
2331 if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2334 /***************************************************************************
2335 * MapHInstSL_PN (KERNEL32.@)
2337 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
2339 if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );