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 );
1173 ERR( "loaded .so but dll %s still not found\n", dllname );
1177 if (!file_exists) WARN("cannot open .so lib for 16-bit builtin %s: %s\n", name, error);
1178 else ERR("failed to load .so lib for 16-bit builtin %s: %s\n", name, error );
1180 return (HMODULE16)2;
1184 /**********************************************************************
1185 * MODULE_LoadModule16
1187 * Load a NE module in the order of the loadorder specification.
1188 * The caller is responsible that the module is not loaded already.
1191 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1193 HINSTANCE16 hinst = 2;
1194 enum loadorder_type loadorder[LOADORDER_NTYPES];
1196 const char *filetype = "";
1197 const char *ptr, *basename;
1199 /* strip path information */
1202 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
1203 if ((ptr = strrchr( basename, '\\' ))) basename = ptr + 1;
1204 if ((ptr = strrchr( basename, '/' ))) basename = ptr + 1;
1206 if (is_builtin_present(basename))
1208 TRACE( "forcing loadorder to builtin for %s\n", debugstr_a(basename) );
1209 /* force builtin loadorder since the dll is already in memory */
1210 loadorder[0] = LOADORDER_BI;
1211 loadorder[1] = LOADORDER_INVALID;
1215 UNICODE_STRING pathW;
1216 WCHAR buffer[MAX_PATH], *p;
1218 if (!GetModuleFileNameW( 0, buffer, MAX_PATH )) p = NULL;
1221 if ((p = strrchrW( buffer, '\\' ))) p++;
1224 RtlCreateUnicodeStringFromAsciiz( &pathW, basename );
1225 MODULE_GetLoadOrderW( loadorder, p, pathW.Buffer );
1226 RtlFreeUnicodeString( &pathW );
1229 for(i = 0; i < LOADORDER_NTYPES; i++)
1231 if (loadorder[i] == LOADORDER_INVALID) break;
1233 switch(loadorder[i])
1236 TRACE("Trying native dll '%s'\n", libname);
1237 hinst = NE_LoadModule(libname, lib_only);
1238 filetype = "native";
1242 TRACE("Trying built-in '%s'\n", libname);
1243 hinst = NE_LoadBuiltinModule(libname);
1244 filetype = "builtin";
1254 TRACE_(loaddll)("Loaded module '%s' : %s\n", libname, filetype);
1260 hModule = GetModuleHandle16(libname);
1263 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1265 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
1268 pModule = NE_GetPtr(hModule);
1271 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1273 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
1276 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1279 * Call initialization routines for all loaded DLLs. Note that
1280 * when we load implicitly linked DLLs this will be done by InitTask().
1282 if(pModule->flags & NE_FFLAGS_LIBMODULE)
1284 NE_InitializeDLLs(hModule);
1285 NE_DllProcessAttach(hModule);
1293 /* We quit searching when we get another error than 'File not found' */
1297 return hinst; /* The last error that occurred */
1301 /**********************************************************************
1304 * Create the thread for a 16-bit module.
1306 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1311 HINSTANCE16 instance = 0;
1313 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1316 /* Post event to start the task */
1317 PostEvent16( hTask );
1319 /* Wait until we get the instance handle */
1322 DirectedYield16( hTask );
1323 if (!IsTask16( hTask )) /* thread has died */
1326 WaitForSingleObject( hThread, INFINITE );
1327 GetExitCodeThread( hThread, &exit_code );
1328 CloseHandle( hThread );
1331 if (!(pTask = GlobalLock16( hTask ))) break;
1332 instance = pTask->hInstance;
1333 GlobalUnlock16( hTask );
1334 } while (!instance);
1336 CloseHandle( hThread );
1341 /**********************************************************************
1342 * LoadModule (KERNEL.45)
1344 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1346 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1347 LOADPARAMS16 *params;
1355 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1357 /* Special case: second instance of an already loaded NE module */
1359 if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1360 if ( pModule->module32 ) return (HINSTANCE16)21;
1362 /* Increment refcount */
1368 /* Main case: load first instance of NE module */
1370 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1373 if ( !(pModule = NE_GetPtr( hModule )) )
1374 return (HINSTANCE16)11;
1377 /* If library module, we just retrieve the instance handle */
1379 if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1380 return NE_GetInstance( pModule );
1383 * At this point, we need to create a new process.
1385 * pModule points either to an already loaded module, whose refcount
1386 * has already been incremented (to avoid having the module vanish
1387 * in the meantime), or else to a stub module which contains only header
1390 params = (LOADPARAMS16 *)paramBlock;
1391 cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1392 cmdline = MapSL( params->cmdLine );
1393 return NE_CreateThread( pModule, cmdShow, cmdline );
1397 /**********************************************************************
1400 * Startup code for a new 16-bit task.
1402 DWORD NE_StartTask(void)
1404 TDB *pTask = TASK_GetCurrent();
1405 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1406 HINSTANCE16 hInstance, hPrevInstance;
1407 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1410 if ( pModule->count > 0 )
1412 /* Second instance of an already loaded NE module */
1413 /* Note that the refcount was already incremented by the parent */
1415 hPrevInstance = NE_GetInstance( pModule );
1417 if ( pModule->dgroup )
1418 if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1419 NE_LoadSegment( pModule, pModule->dgroup );
1421 hInstance = NE_GetInstance( pModule );
1422 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1427 /* Load first instance of NE module */
1429 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1431 hInstance = NE_DoLoadModule( pModule );
1435 if ( hInstance >= 32 )
1439 /* Enter instance handles into task struct */
1441 pTask->hInstance = hInstance;
1442 pTask->hPrevInstance = hPrevInstance;
1444 /* Use DGROUP for 16-bit stack */
1446 if (!(sp = pModule->sp))
1447 sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1449 sp -= sizeof(STACK16FRAME);
1450 NtCurrentTeb()->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1452 /* Registers at initialization must be:
1454 * bx stack size in bytes
1455 * cx heap size in bytes
1456 * si previous app instance
1457 * di current app instance
1459 * es selector to the PSP
1460 * ds dgroup of the application
1462 * sp top of the stack
1464 memset( &context, 0, sizeof(context) );
1465 context.SegCs = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1466 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1467 context.SegEs = pTask->hPDB;
1468 context.SegFs = wine_get_fs();
1469 context.SegGs = wine_get_gs();
1470 context.Eip = pModule->ip;
1471 context.Ebx = pModule->stack_size;
1472 context.Ecx = pModule->heap_size;
1473 context.Edi = pTask->hInstance;
1474 context.Esi = pTask->hPrevInstance;
1476 /* Now call 16-bit entry point */
1478 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1479 context.SegCs, context.Eip, context.SegDs,
1480 SELECTOROF(NtCurrentTeb()->cur_stack),
1481 OFFSETOF(NtCurrentTeb()->cur_stack) );
1483 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1484 ExitThread( LOWORD(context.Eax) );
1486 return hInstance; /* error code */
1489 /***********************************************************************
1490 * LoadLibrary (KERNEL.95)
1491 * LoadLibrary16 (KERNEL32.35)
1493 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1495 return LoadModule16(libname, (LPVOID)-1 );
1499 /**********************************************************************
1502 * Call a DLL's WEP, allowing it to shut down.
1503 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1505 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1508 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1509 if (!WEP) return FALSE;
1516 args[0] = WEP_FREE_DLL;
1517 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1518 ret = LOWORD(dwRet);
1520 __EXCEPT(page_fault)
1522 WARN("Page fault\n");
1531 /**********************************************************************
1534 * Implementation of FreeModule16().
1536 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1538 HMODULE16 *hPrevModule;
1543 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1544 hModule = pModule->self;
1546 TRACE("%04x count %d\n", hModule, pModule->count );
1548 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1549 else pModule->count = 0;
1551 if (pModule->flags & NE_FFLAGS_BUILTIN)
1552 return FALSE; /* Can't free built-in module */
1554 if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1556 /* Free the objects owned by the DLL module */
1557 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1559 if (pModule->flags & NE_FFLAGS_LIBMODULE)
1560 MODULE_CallWEP( hModule );
1562 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1566 /* Clear magic number just in case */
1568 pModule->magic = pModule->self = 0;
1569 if (pModule->fd) CloseHandle( pModule->fd );
1571 /* Remove it from the linked list */
1573 hPrevModule = &hFirstModule;
1574 while (*hPrevModule && (*hPrevModule != hModule))
1576 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1578 if (*hPrevModule) *hPrevModule = pModule->next;
1580 /* Free the referenced modules */
1582 pModRef = (HMODULE16*)((char *)pModule + pModule->modref_table);
1583 for (i = 0; i < pModule->modref_count; i++, pModRef++)
1585 NE_FreeModule( *pModRef, call_wep );
1588 /* Free the module storage */
1590 GlobalFreeAll16( hModule );
1595 /**********************************************************************
1596 * FreeModule (KERNEL.46)
1598 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1600 return NE_FreeModule( hModule, TRUE );
1604 /***********************************************************************
1605 * FreeLibrary (KERNEL.96)
1606 * FreeLibrary16 (KERNEL32.36)
1608 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1610 TRACE("%04x\n", handle );
1611 FreeModule16( handle );
1615 /***********************************************************************
1616 * GetModuleHandle16 (KERNEL32.@)
1618 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1620 HMODULE16 hModule = hFirstModule;
1622 BYTE len, *name_table;
1623 char tmpstr[MAX_PATH];
1626 TRACE("(%s)\n", name);
1628 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1633 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1635 /* If 'name' matches exactly the module name of a module:
1636 * Return its handle.
1638 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1640 pModule = NE_GetPtr( hModule );
1641 if (!pModule) break;
1642 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1644 name_table = (BYTE *)pModule + pModule->name_table;
1645 if ((*name_table == len) && !strncmp(name, name_table+1, len))
1649 /* If uppercased 'name' matches exactly the module name of a module:
1652 for (s = tmpstr; *s; s++) *s = FILE_toupper(*s);
1654 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1656 pModule = NE_GetPtr( hModule );
1657 if (!pModule) break;
1658 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1660 name_table = (BYTE *)pModule + pModule->name_table;
1661 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1662 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1663 * lowercased module names, but try to load uppercase DLLs, so this
1664 * 'i' compare is just a quickfix until the loader handles that
1665 * correctly. -MM 990705
1667 if ((*name_table == len) && !FILE_strncasecmp(tmpstr, name_table+1, len))
1671 /* If the base filename of 'name' matches the base filename of the module
1672 * filename of some module (case-insensitive compare):
1673 * Return its handle.
1676 /* basename: search backwards in passed name to \ / or : */
1677 s = tmpstr + strlen(tmpstr);
1680 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1685 /* search this in loaded filename list */
1686 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1691 pModule = NE_GetPtr( hModule );
1692 if (!pModule) break;
1693 if (!pModule->fileinfo) continue;
1694 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1696 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1697 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1698 /* basename: search backwards in pathname to \ / or : */
1699 while (loadedfn > (char*)ofs->szPathName)
1701 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1705 /* case insensitive compare ... */
1706 if (!FILE_strcasecmp(loadedfn, s))
1713 /**********************************************************************
1714 * GetModuleName (KERNEL.27)
1716 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1721 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1722 p = (BYTE *)pModule + pModule->name_table;
1723 if (count > *p) count = *p + 1;
1726 memcpy( buf, p + 1, count - 1 );
1727 buf[count-1] = '\0';
1733 /**********************************************************************
1734 * GetModuleFileName (KERNEL.49)
1736 * Comment: see GetModuleFileNameA
1738 * Even if invoked by second instance of a program,
1739 * it still returns path of first one.
1741 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1746 /* Win95 does not query hModule if set to 0 !
1747 * Is this wrong or maybe Win3.1 only ? */
1748 if (!hModule) hModule = GetCurrentTask();
1750 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1751 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1752 if (pModule->expected_version >= 0x400)
1753 GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1754 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1755 return strlen(lpFileName);
1759 /**********************************************************************
1760 * GetModuleUsage (KERNEL.48)
1762 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1764 NE_MODULE *pModule = NE_GetPtr( hModule );
1765 return pModule ? pModule->count : 0;
1769 /**********************************************************************
1770 * GetExpWinVer (KERNEL.167)
1772 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1774 NE_MODULE *pModule = NE_GetPtr( hModule );
1775 if ( !pModule ) return 0;
1778 * For built-in modules, fake the expected version the module should
1779 * have according to the Windows version emulated by Wine
1781 if ( !pModule->expected_version )
1783 OSVERSIONINFOA versionInfo;
1784 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1786 if ( GetVersionExA( &versionInfo ) )
1787 pModule->expected_version =
1788 (versionInfo.dwMajorVersion & 0xff) << 8
1789 | (versionInfo.dwMinorVersion & 0xff);
1792 return pModule->expected_version;
1796 /***********************************************************************
1797 * WinExec (KERNEL.166)
1799 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1801 LPCSTR p, args = NULL;
1802 LPCSTR name_beg, name_end;
1803 LPSTR name, cmdline;
1806 char buffer[MAX_PATH];
1808 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1810 name_beg = lpCmdLine+1;
1811 p = strchr ( lpCmdLine+1, '"' );
1815 args = strchr ( p, ' ' );
1817 else /* yes, even valid with trailing '"' missing */
1818 name_end = lpCmdLine+strlen(lpCmdLine);
1822 name_beg = lpCmdLine;
1823 args = strchr( lpCmdLine, ' ' );
1824 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1827 if ((name_beg == lpCmdLine) && (!args))
1828 { /* just use the original cmdline string as file name */
1829 name = (LPSTR)lpCmdLine;
1833 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1834 return ERROR_NOT_ENOUGH_MEMORY;
1835 memcpy( name, name_beg, name_end - name_beg );
1836 name[name_end - name_beg] = '\0';
1842 arglen = strlen(args);
1843 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1844 cmdline[0] = (BYTE)arglen;
1845 strcpy( cmdline + 1, args );
1849 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1850 cmdline[0] = cmdline[1] = 0;
1853 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1855 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1857 LOADPARAMS16 params;
1860 showCmd[1] = nCmdShow;
1862 params.hEnvironment = 0;
1863 params.cmdLine = MapLS( cmdline );
1864 params.showCmd = MapLS( showCmd );
1865 params.reserved = 0;
1867 ret = LoadModule16( buffer, ¶ms );
1868 UnMapLS( params.cmdLine );
1869 UnMapLS( params.showCmd );
1871 else ret = GetLastError();
1873 HeapFree( GetProcessHeap(), 0, cmdline );
1874 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1876 if (ret == 21) /* 32-bit module */
1879 ReleaseThunkLock( &count );
1880 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1881 RestoreThunkLock( count );
1886 /***********************************************************************
1887 * GetProcAddress (KERNEL.50)
1889 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1894 if (!hModule) hModule = GetCurrentTask();
1895 hModule = GetExePtr( hModule );
1897 if (HIWORD(name) != 0)
1899 ordinal = NE_GetOrdinal( hModule, name );
1900 TRACE("%04x '%s'\n", hModule, name );
1904 ordinal = LOWORD(name);
1905 TRACE("%04x %04x\n", hModule, ordinal );
1907 if (!ordinal) return (FARPROC16)0;
1909 ret = NE_GetEntryPoint( hModule, ordinal );
1911 TRACE("returning %08x\n", (UINT)ret );
1916 /***************************************************************************
1917 * HasGPHandler (KERNEL.338)
1919 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1924 GPHANDLERDEF *gpHandler;
1926 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1927 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1928 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1929 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1930 && (gpHandler = MapSL( gpPtr )) != NULL )
1932 while (gpHandler->selector)
1934 if ( SELECTOROF(address) == gpHandler->selector
1935 && OFFSETOF(address) >= gpHandler->rangeStart
1936 && OFFSETOF(address) < gpHandler->rangeEnd )
1937 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1946 /**********************************************************************
1947 * GetModuleHandle (KERNEL.47)
1949 * Find a module from a module name.
1951 * NOTE: The current implementation works the same way the Windows 95 one
1952 * does. Do not try to 'fix' it, fix the callers.
1953 * + It does not do ANY extension handling (except that strange .EXE bit)!
1954 * + It does not care about paths, just about basenames. (same as Windows)
1958 * the win16 module handle if found
1960 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1961 * Always hFirstModule
1963 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1965 if (HIWORD(name) == 0)
1966 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1967 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1970 /**********************************************************************
1971 * NE_GetModuleByFilename
1973 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1977 BYTE len, *name_table;
1978 char tmpstr[MAX_PATH];
1981 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1983 /* If the base filename of 'name' matches the base filename of the module
1984 * filename of some module (case-insensitive compare):
1985 * Return its handle.
1988 /* basename: search backwards in passed name to \ / or : */
1989 s = tmpstr + strlen(tmpstr);
1992 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1997 /* search this in loaded filename list */
1998 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2003 pModule = NE_GetPtr( hModule );
2004 if (!pModule) break;
2005 if (!pModule->fileinfo) continue;
2006 if (pModule->flags & NE_FFLAGS_WIN32) continue;
2008 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
2009 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
2010 /* basename: search backwards in pathname to \ / or : */
2011 while (loadedfn > (char*)ofs->szPathName)
2013 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
2017 /* case insensitive compare ... */
2018 if (!FILE_strcasecmp(loadedfn, s))
2021 /* If basename (without ext) matches the module name of a module:
2022 * Return its handle.
2025 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
2028 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
2030 pModule = NE_GetPtr( hModule );
2031 if (!pModule) break;
2032 if (pModule->flags & NE_FFLAGS_WIN32) continue;
2034 name_table = (BYTE *)pModule + pModule->name_table;
2035 if ((*name_table == len) && !FILE_strncasecmp(s, name_table+1, len))
2042 /***********************************************************************
2043 * GetProcAddress16 (KERNEL32.37)
2044 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
2046 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
2048 if (!hModule) return 0;
2049 if (HIWORD(hModule))
2051 WARN("hModule is Win32 handle (%p)\n", hModule );
2054 return GetProcAddress16( LOWORD(hModule), name );
2057 /**********************************************************************
2058 * ModuleFirst (TOOLHELP.59)
2060 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
2062 lpme->wNext = hFirstModule;
2063 return ModuleNext16( lpme );
2067 /**********************************************************************
2068 * ModuleNext (TOOLHELP.60)
2070 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
2075 if (!lpme->wNext) return FALSE;
2076 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
2077 name = (char *)pModule + pModule->name_table;
2078 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
2079 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
2080 lpme->hModule = lpme->wNext;
2081 lpme->wcUsage = pModule->count;
2082 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
2083 lpme->wNext = pModule->next;
2088 /**********************************************************************
2089 * ModuleFindName (TOOLHELP.61)
2091 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
2093 lpme->wNext = GetModuleHandle16( name );
2094 return ModuleNext16( lpme );
2098 /**********************************************************************
2099 * ModuleFindHandle (TOOLHELP.62)
2101 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
2103 hModule = GetExePtr( hModule );
2104 lpme->wNext = hModule;
2105 return ModuleNext16( lpme );
2109 /***************************************************************************
2110 * IsRomModule (KERNEL.323)
2112 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
2117 /***************************************************************************
2118 * IsRomFile (KERNEL.326)
2120 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
2125 /***********************************************************************
2126 * create_dummy_module
2128 * Create a dummy NE module for Win32 or Winelib.
2130 static HMODULE16 create_dummy_module( HMODULE module32 )
2134 SEGTABLEENTRY *pSegment;
2137 const char* basename;
2140 char filename[MAX_PATH];
2141 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
2143 if (!nt) return (HMODULE16)11; /* invalid exe */
2145 /* Extract base filename */
2146 GetModuleFileNameA( module32, filename, sizeof(filename) );
2147 basename = strrchr(filename, '\\');
2148 if (!basename) basename = filename;
2150 len = strlen(basename);
2151 if ((s = strchr(basename, '.'))) len = s - basename;
2153 /* Allocate module */
2154 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2155 + strlen(filename) + 1;
2156 size = sizeof(NE_MODULE) +
2157 /* loaded file info */
2158 ((of_size + 3) & ~3) +
2159 /* segment table: DS,CS */
2160 2 * sizeof(SEGTABLEENTRY) +
2163 /* several empty tables */
2166 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2167 if (!hModule) return (HMODULE16)11; /* invalid exe */
2169 FarSetOwner16( hModule, hModule );
2170 pModule = (NE_MODULE *)GlobalLock16( hModule );
2172 /* Set all used entries */
2173 pModule->magic = IMAGE_OS2_SIGNATURE;
2176 pModule->flags = NE_FFLAGS_WIN32;
2177 pModule->dgroup = 0;
2180 pModule->heap_size = 0;
2181 pModule->stack_size = 0;
2182 pModule->seg_count = 2;
2183 pModule->modref_count = 0;
2184 pModule->nrname_size = 0;
2185 pModule->fileinfo = sizeof(NE_MODULE);
2186 pModule->os_flags = NE_OSFLAGS_WINDOWS;
2187 pModule->self = hModule;
2188 pModule->module32 = module32;
2190 /* Set version and flags */
2191 pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2192 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2193 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2194 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2196 /* Set loaded file information */
2197 ofs = (OFSTRUCT *)(pModule + 1);
2198 memset( ofs, 0, of_size );
2199 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
2200 strcpy( ofs->szPathName, filename );
2202 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2203 pModule->seg_table = (int)pSegment - (int)pModule;
2206 pSegment->flags = NE_SEGFLAGS_DATA;
2207 pSegment->minsize = 0x1000;
2210 pSegment->flags = 0;
2214 pStr = (char *)pSegment;
2215 pModule->name_table = (int)pStr - (int)pModule;
2218 lstrcpynA( pStr+1, basename, len+1 );
2221 /* All tables zero terminated */
2222 pModule->res_table = pModule->import_table = pModule->entry_table = (int)pStr - (int)pModule;
2224 NE_RegisterModule( pModule );
2225 LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
2229 /***********************************************************************
2230 * PrivateLoadLibrary (KERNEL32.@)
2232 * FIXME: rough guesswork, don't know what "Private" means
2234 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2236 return LoadLibrary16(libname);
2239 /***********************************************************************
2240 * PrivateFreeLibrary (KERNEL32.@)
2242 * FIXME: rough guesswork, don't know what "Private" means
2244 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2246 FreeLibrary16(handle);
2249 /***********************************************************************
2250 * LoadLibrary32 (KERNEL.452)
2251 * LoadSystemLibrary32 (KERNEL.482)
2253 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2258 ReleaseThunkLock( &count );
2259 hModule = LoadLibraryA( libname );
2260 RestoreThunkLock( count );
2264 /***************************************************************************
2265 * MapHModuleLS (KERNEL32.@)
2267 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2273 return TASK_GetCurrent()->hInstance;
2275 return LOWORD(hmod); /* we already have a 16 bit module handle */
2276 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2278 if (pModule->module32 == hmod)
2279 return pModule->self;
2280 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2282 if ((ret = create_dummy_module( hmod )) < 32)
2290 /***************************************************************************
2291 * MapHModuleSL (KERNEL32.@)
2293 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2298 TDB *pTask = TASK_GetCurrent();
2299 hmod = pTask->hModule;
2301 pModule = (NE_MODULE*)GlobalLock16(hmod);
2302 if ((pModule->magic!=IMAGE_OS2_SIGNATURE) || !(pModule->flags & NE_FFLAGS_WIN32))
2304 return pModule->module32;
2307 /***************************************************************************
2308 * MapHInstLS (KERNEL32.@)
2309 * MapHInstLS (KERNEL.472)
2311 void WINAPI MapHInstLS( CONTEXT86 *context )
2313 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2316 /***************************************************************************
2317 * MapHInstSL (KERNEL32.@)
2318 * MapHInstSL (KERNEL.473)
2320 void WINAPI MapHInstSL( CONTEXT86 *context )
2322 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2325 /***************************************************************************
2326 * MapHInstLS_PN (KERNEL32.@)
2328 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
2330 if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2333 /***************************************************************************
2334 * MapHInstSL_PN (KERNEL32.@)
2336 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
2338 if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );