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"
48 #include "builtin16.h"
49 #include "stackframe.h"
51 #include "wine/exception.h"
52 #include "wine/debug.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(module);
55 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
58 typedef struct _GPHANDLERDEF
70 struct ne_segment_table_entry_s
72 WORD seg_data_offset; /* Sector offset of segment data */
73 WORD seg_data_length; /* Length of segment data */
74 WORD seg_flags; /* Flags associated with this segment */
75 WORD min_alloc; /* Minimum allocation size for this */
78 #define hFirstModule (pThhook->hExeHead)
82 void *module_start; /* 32-bit address of the module data */
83 int module_size; /* Size of the module data */
84 void *code_start; /* 32-bit address of DLL code */
85 void *data_start; /* 32-bit address of DLL data */
86 const char *owner; /* 32-bit dll that contains this dll */
87 const void *rsrc; /* resources data */
88 } BUILTIN16_DESCRIPTOR;
90 /* Table of all built-in DLLs */
94 static const BUILTIN16_DESCRIPTOR *builtin_dlls[MAX_DLLS];
97 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
98 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
100 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
102 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
105 static WINE_EXCEPTION_FILTER(page_fault)
107 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
108 GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
109 return EXCEPTION_EXECUTE_HANDLER;
110 return EXCEPTION_CONTINUE_SEARCH;
114 /* patch all the flat cs references of the code segment if necessary */
115 inline static void patch_code_segment( void *code_segment )
118 CALLFROM16 *call = code_segment;
119 if (call->flatcs == wine_get_cs()) return; /* nothing to patch */
120 while (call->pushl == 0x68)
122 call->flatcs = wine_get_cs();
129 /***********************************************************************
132 * Find a descriptor in the list
134 static const BUILTIN16_DESCRIPTOR *find_dll_descr( const char *dllname )
137 for (i = 0; i < MAX_DLLS; i++)
139 const BUILTIN16_DESCRIPTOR *descr = builtin_dlls[i];
142 NE_MODULE *pModule = (NE_MODULE *)descr->module_start;
143 OFSTRUCT *pOfs = (OFSTRUCT *)((LPBYTE)pModule + pModule->fileinfo);
144 BYTE *name_table = (BYTE *)pModule + pModule->name_table;
146 /* check the dll file name */
147 if (!FILE_strcasecmp( pOfs->szPathName, dllname )) return descr;
148 /* check the dll module name (without extension) */
149 if (!FILE_strncasecmp( dllname, name_table+1, *name_table ) &&
150 !strcmp( dllname + *name_table, ".dll" ))
158 /***********************************************************************
161 * Check if a builtin dll descriptor is present (because we loaded its 32-bit counterpart).
163 static BOOL is_builtin_present( LPCSTR name )
165 char dllname[20], *p;
167 if (strlen(name) >= sizeof(dllname)-4) return FALSE;
168 strcpy( dllname, name );
169 p = strrchr( dllname, '.' );
170 if (!p) strcat( dllname, ".dll" );
171 for (p = dllname; *p; p++) *p = FILE_tolower(*p);
173 return (find_dll_descr( dllname ) != NULL);
177 /***********************************************************************
178 * __wine_register_dll_16 (KERNEL32.@)
180 * Register a built-in DLL descriptor.
182 void __wine_register_dll_16( const BUILTIN16_DESCRIPTOR *descr )
186 for (i = 0; i < MAX_DLLS; i++)
188 if (builtin_dlls[i]) continue;
189 builtin_dlls[i] = descr;
192 assert( i < MAX_DLLS );
196 /***********************************************************************
197 * __wine_unregister_dll_16 (KERNEL32.@)
199 * Unregister a built-in DLL descriptor.
201 void __wine_unregister_dll_16( const BUILTIN16_DESCRIPTOR *descr )
205 for (i = 0; i < MAX_DLLS; i++)
207 if (builtin_dlls[i] != descr) continue;
208 builtin_dlls[i] = NULL;
214 /**********************************************************************
217 void NE_RegisterModule( NE_MODULE *pModule )
219 pModule->next = hFirstModule;
220 hFirstModule = pModule->self;
224 /***********************************************************************
227 void NE_DumpModule( HMODULE16 hModule )
237 if (!(pModule = NE_GetPtr( hModule )))
239 MESSAGE( "**** %04x is not a module handle\n", hModule );
243 /* Dump the module info */
245 DPRINTF( "Module %04x:\n", hModule );
246 DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
247 pModule->count, pModule->flags,
248 pModule->heap_size, pModule->stack_size );
249 DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
250 pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
251 pModule->seg_count, pModule->modref_count );
252 DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
253 pModule->os_flags, pModule->min_swap_area,
254 pModule->expected_version );
255 if (pModule->flags & NE_FFLAGS_WIN32)
256 DPRINTF( "PE module=%p\n", pModule->module32 );
258 /* Dump the file info */
260 DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
262 /* Dump the segment table */
264 DPRINTF( "Segment table:\n" );
265 pSeg = NE_SEG_TABLE( pModule );
266 for (i = 0; i < pModule->seg_count; i++, pSeg++)
267 DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
268 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
269 pSeg->minsize, pSeg->hSeg );
271 /* Dump the resource table */
273 DPRINTF( "Resource table:\n" );
274 if (pModule->res_table)
276 pword = (WORD *)((BYTE *)pModule + pModule->res_table);
277 DPRINTF( "Alignment: %d\n", *pword++ );
280 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
281 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
282 DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
283 for (i = 0; i < ptr->count; i++, pname++)
284 DPRINTF( "offset=%d len=%d id=%04x\n",
285 pname->offset, pname->length, pname->id );
286 pword = (WORD *)pname;
289 else DPRINTF( "None\n" );
291 /* Dump the resident name table */
293 DPRINTF( "Resident-name table:\n" );
294 pstr = (char *)pModule + pModule->name_table;
297 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
298 *(WORD *)(pstr + *pstr + 1) );
299 pstr += *pstr + 1 + sizeof(WORD);
302 /* Dump the module reference table */
304 DPRINTF( "Module ref table:\n" );
305 if (pModule->modref_table)
307 pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
308 for (i = 0; i < pModule->modref_count; i++, pword++)
311 GetModuleName16( *pword, name, sizeof(name) );
312 DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
315 else DPRINTF( "None\n" );
317 /* Dump the entry table */
319 DPRINTF( "Entry table:\n" );
320 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);
322 entry = (ET_ENTRY *)((BYTE *)bundle+6);
323 DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
324 ordinal = bundle->first;
325 while (ordinal < bundle->last)
327 if (entry->type == 0xff)
328 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
330 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
333 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
335 /* Dump the non-resident names table */
337 DPRINTF( "Non-resident names table:\n" );
338 if (pModule->nrname_handle)
340 pstr = (char *)GlobalLock16( pModule->nrname_handle );
343 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
344 *(WORD *)(pstr + *pstr + 1) );
345 pstr += *pstr + 1 + sizeof(WORD);
352 /***********************************************************************
355 * Walk the module list and print the modules.
357 void NE_WalkModules(void)
359 HMODULE16 hModule = hFirstModule;
360 MESSAGE( "Module Flags Name\n" );
363 NE_MODULE *pModule = NE_GetPtr( hModule );
366 MESSAGE( "Bad module %04x in list\n", hModule );
369 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->flags,
370 *((char *)pModule + pModule->name_table),
371 (char *)pModule + pModule->name_table + 1 );
372 hModule = pModule->next;
377 /***********************************************************************
378 * NE_InitResourceHandler
380 * Fill in 'resloader' fields in the resource table.
382 void NE_InitResourceHandler( NE_MODULE *pModule )
384 static FARPROC16 proc;
386 NE_TYPEINFO *pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->res_table + 2);
388 TRACE("InitResourceHandler[%04x]\n", pModule->self );
390 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
392 while(pTypeInfo->type_id)
394 memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
395 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
400 /***********************************************************************
403 * Lookup the ordinal for a given name.
405 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
407 unsigned char buffer[256], *cpnt;
411 if (!(pModule = NE_GetPtr( hModule ))) return 0;
412 if (pModule->flags & NE_FFLAGS_WIN32) return 0;
414 TRACE("(%04x,'%s')\n", hModule, name );
416 /* First handle names of the form '#xxxx' */
418 if (name[0] == '#') return atoi( name + 1 );
420 /* Now copy and uppercase the string */
422 strcpy( buffer, name );
423 for (cpnt = buffer; *cpnt; cpnt++) *cpnt = FILE_toupper(*cpnt);
426 /* First search the resident names */
428 cpnt = (char *)pModule + pModule->name_table;
430 /* Skip the first entry (module name) */
431 cpnt += *cpnt + 1 + sizeof(WORD);
434 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
437 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
438 TRACE(" Found: ordinal=%d\n", ordinal );
441 cpnt += *cpnt + 1 + sizeof(WORD);
444 /* Now search the non-resident names table */
446 if (!pModule->nrname_handle) return 0; /* No non-resident table */
447 cpnt = (char *)GlobalLock16( pModule->nrname_handle );
449 /* Skip the first entry (module description string) */
450 cpnt += *cpnt + 1 + sizeof(WORD);
453 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
456 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
457 TRACE(" Found: ordinal=%d\n", ordinal );
460 cpnt += *cpnt + 1 + sizeof(WORD);
466 /***********************************************************************
469 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
471 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
474 /***********************************************************************
477 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
485 if (!(pModule = NE_GetPtr( hModule ))) return 0;
486 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
488 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
489 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
493 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
496 entry = (ET_ENTRY *)((BYTE *)bundle+6);
497 for (i=0; i < (ordinal - bundle->first - 1); i++)
501 memcpy( &offset, &entry->offs, sizeof(WORD) );
503 if (sel == 0xfe) sel = 0xffff; /* constant entry */
504 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
506 return (FARPROC16)MAKESEGPTR( sel, offset );
508 return (FARPROC16)MAKESEGPTR( sel, offset );
510 return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
514 /***********************************************************************
515 * EntryAddrProc (KERNEL.667) Wine-specific export
517 * Return the entry point for a given ordinal.
519 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
521 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
522 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
526 /***********************************************************************
529 * Change the value of an entry point. Use with caution!
530 * It can only change the offset value, not the selector.
532 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
539 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
540 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
542 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
543 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
545 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
546 if (!(bundle->next)) return 0;
549 entry = (ET_ENTRY *)((BYTE *)bundle+6);
550 for (i=0; i < (ordinal - bundle->first - 1); i++)
553 memcpy( &entry->offs, &offset, sizeof(WORD) );
558 /***********************************************************************
561 HANDLE NE_OpenFile( NE_MODULE *pModule )
564 char *name = NE_MODULE_NAME( pModule );
566 TRACE("(%p)\n", pModule );
570 if (!DuplicateHandle( GetCurrentProcess(), pModule->fd,
571 GetCurrentProcess(), &handle, 0, FALSE,
572 DUPLICATE_SAME_ACCESS )) handle = INVALID_HANDLE_VALUE;
576 handle = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
577 NULL, OPEN_EXISTING, 0, 0 );
579 if (handle == INVALID_HANDLE_VALUE)
580 ERR( "Can't open file '%s' for module %04x\n", name, pModule->self );
582 TRACE("opened '%s' -> %p\n", name, handle);
587 /* wrapper for SetFilePointer and ReadFile */
588 static BOOL read_data( HANDLE handle, LONG offset, void *buffer, DWORD size )
592 if (SetFilePointer( handle, offset, NULL, SEEK_SET ) == INVALID_SET_FILE_POINTER) return FALSE;
593 if (!ReadFile( handle, buffer, size, &result, NULL )) return FALSE;
594 return (result == size);
597 /***********************************************************************
600 static HMODULE16 NE_LoadExeHeader( HANDLE handle, LPCSTR path )
602 IMAGE_DOS_HEADER mz_header;
603 IMAGE_OS2_HEADER ne_header;
607 BYTE *pData, *pTempEntryTable;
608 char *buffer, *fastload = NULL;
609 int fastload_offset = 0, fastload_length = 0;
611 ET_BUNDLE *bundle, *oldbundle;
614 /* Read a block from either the file or the fast-load area. */
615 #define READ(offset,size,buffer) \
616 ((fastload && ((offset) >= fastload_offset) && \
617 ((offset)+(size) <= fastload_offset+fastload_length)) ? \
618 (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
619 read_data( handle, (offset), (buffer), (size)))
621 if (!read_data( handle, 0, &mz_header, sizeof(mz_header)) ||
622 (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
623 return (HMODULE16)11; /* invalid exe */
625 if (!read_data( handle, mz_header.e_lfanew, &ne_header, sizeof(ne_header) ))
626 return (HMODULE16)11; /* invalid exe */
628 if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21; /* win32 exe */
629 if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
630 MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
631 return (HMODULE16)12;
633 if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11; /* invalid exe */
635 /* We now have a valid NE header */
637 size = sizeof(NE_MODULE) +
639 ne_header.ne_cseg * sizeof(SEGTABLEENTRY) +
641 ne_header.ne_restab - ne_header.ne_rsrctab +
642 /* resident names table */
643 ne_header.ne_modtab - ne_header.ne_restab +
644 /* module ref table */
645 ne_header.ne_cmod * sizeof(WORD) +
646 /* imported names table */
647 ne_header.ne_enttab - ne_header.ne_imptab +
648 /* entry table length */
649 ne_header.ne_cbenttab +
650 /* entry table extra conversion space */
652 2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6) +
653 /* loaded file info */
654 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
656 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
657 if (!hModule) return (HMODULE16)11; /* invalid exe */
659 FarSetOwner16( hModule, hModule );
660 pModule = (NE_MODULE *)GlobalLock16( hModule );
661 memcpy( pModule, &ne_header, sizeof(ne_header) );
663 /* check *programs* for default minimal stack size */
664 if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
665 && (pModule->stack_size < 0x1400) )
666 pModule->stack_size = 0x1400;
667 pModule->module32 = 0;
668 pModule->self = hModule;
669 pModule->self_loading_sel = 0;
670 pData = (BYTE *)(pModule + 1);
672 /* Clear internal Wine flags in case they are set in the EXE file */
674 pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
676 /* Read the fast-load area */
678 if (ne_header.ne_flagsothers & NE_AFLAGS_FASTLOAD)
680 fastload_offset=ne_header.ne_pretthunks << ne_header.ne_align;
681 fastload_length=ne_header.ne_psegrefbytes << ne_header.ne_align;
682 TRACE("Using fast-load area offset=%x len=%d\n",
683 fastload_offset, fastload_length );
684 if ((fastload = HeapAlloc( GetProcessHeap(), 0, fastload_length )) != NULL)
686 if (!read_data( handle, fastload_offset, fastload, fastload_length))
688 HeapFree( GetProcessHeap(), 0, fastload );
689 WARN("Error reading fast-load area!\n");
695 /* Get the segment table */
697 pModule->seg_table = pData - (BYTE *)pModule;
698 buffer = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cseg *
699 sizeof(struct ne_segment_table_entry_s));
703 struct ne_segment_table_entry_s *pSeg;
705 if (!READ( mz_header.e_lfanew + ne_header.ne_segtab,
706 ne_header.ne_cseg * sizeof(struct ne_segment_table_entry_s),
709 HeapFree( GetProcessHeap(), 0, buffer );
710 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
711 GlobalFree16( hModule );
712 return (HMODULE16)11; /* invalid exe */
714 pSeg = (struct ne_segment_table_entry_s *)buffer;
715 for (i = ne_header.ne_cseg; i > 0; i--, pSeg++)
717 memcpy( pData, pSeg, sizeof(*pSeg) );
718 pData += sizeof(SEGTABLEENTRY);
720 HeapFree( GetProcessHeap(), 0, buffer );
724 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
725 GlobalFree16( hModule );
726 return (HMODULE16)11; /* invalid exe */
729 /* Get the resource table */
731 if (ne_header.ne_rsrctab < ne_header.ne_restab)
733 pModule->res_table = pData - (BYTE *)pModule;
734 if (!READ(mz_header.e_lfanew + ne_header.ne_rsrctab,
735 ne_header.ne_restab - ne_header.ne_rsrctab,
737 return (HMODULE16)11; /* invalid exe */
738 pData += ne_header.ne_restab - ne_header.ne_rsrctab;
739 NE_InitResourceHandler( pModule );
741 else pModule->res_table = 0; /* No resource table */
743 /* Get the resident names table */
745 pModule->name_table = pData - (BYTE *)pModule;
746 if (!READ( mz_header.e_lfanew + ne_header.ne_restab,
747 ne_header.ne_modtab - ne_header.ne_restab,
750 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
751 GlobalFree16( hModule );
752 return (HMODULE16)11; /* invalid exe */
754 pData += ne_header.ne_modtab - ne_header.ne_restab;
756 /* Get the module references table */
758 if (ne_header.ne_cmod > 0)
760 pModule->modref_table = pData - (BYTE *)pModule;
761 if (!READ( mz_header.e_lfanew + ne_header.ne_modtab,
762 ne_header.ne_cmod * sizeof(WORD),
765 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
766 GlobalFree16( hModule );
767 return (HMODULE16)11; /* invalid exe */
769 pData += ne_header.ne_cmod * sizeof(WORD);
771 else pModule->modref_table = 0; /* No module references */
773 /* Get the imported names table */
775 pModule->import_table = pData - (BYTE *)pModule;
776 if (!READ( mz_header.e_lfanew + ne_header.ne_imptab,
777 ne_header.ne_enttab - ne_header.ne_imptab,
780 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
781 GlobalFree16( hModule );
782 return (HMODULE16)11; /* invalid exe */
784 pData += ne_header.ne_enttab - ne_header.ne_imptab;
786 /* Load entry table, convert it to the optimized version used by Windows */
788 if ((pTempEntryTable = HeapAlloc( GetProcessHeap(), 0, ne_header.ne_cbenttab)) != NULL)
790 BYTE nr_entries, type, *s;
792 TRACE("Converting entry table.\n");
793 pModule->entry_table = pData - (BYTE *)pModule;
794 if (!READ( mz_header.e_lfanew + ne_header.ne_enttab,
795 ne_header.ne_cbenttab, pTempEntryTable ))
797 HeapFree( GetProcessHeap(), 0, pTempEntryTable );
798 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
799 GlobalFree16( hModule );
800 return (HMODULE16)11; /* invalid exe */
804 TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.ne_enttab, ne_header.ne_cbenttab, *s);
806 bundle = (ET_BUNDLE *)pData;
807 TRACE("first bundle: %p\n", bundle);
808 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
809 entry = (ET_ENTRY *)((BYTE *)bundle+6);
811 while ((nr_entries = *s++))
815 bundle->last += nr_entries;
822 entry->segnum = *s++;
823 entry->offs = *(WORD *)s; s += 2;
824 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
832 entry->segnum = type;
833 entry->offs = *(WORD *)s; s += 2;
834 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
840 if (bundle->first == bundle->last)
842 bundle->first += nr_entries;
843 bundle->last += nr_entries;
848 oldbundle->next = ((int)entry - (int)pModule);
849 bundle = (ET_BUNDLE *)entry;
850 TRACE("new bundle: %p\n", bundle);
851 bundle->first = bundle->last =
852 oldbundle->last + nr_entries;
854 (BYTE *)entry += sizeof(ET_BUNDLE);
858 HeapFree( GetProcessHeap(), 0, pTempEntryTable );
862 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
863 GlobalFree16( hModule );
864 return (HMODULE16)11; /* invalid exe */
867 pData += ne_header.ne_cbenttab + sizeof(ET_BUNDLE) +
868 2 * (ne_header.ne_cbenttab - ne_header.ne_cmovent*6);
870 if ((DWORD)entry > (DWORD)pData)
871 ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
873 /* Store the filename information */
875 pModule->fileinfo = pData - (BYTE *)pModule;
876 size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
877 ofs = (OFSTRUCT *)pData;
878 ofs->cBytes = size - 1;
880 strcpy( ofs->szPathName, path );
883 /* Free the fast-load area */
886 if (fastload) HeapFree( GetProcessHeap(), 0, fastload );
888 /* Get the non-resident names table */
890 if (ne_header.ne_cbnrestab)
892 pModule->nrname_handle = GlobalAlloc16( 0, ne_header.ne_cbnrestab );
893 if (!pModule->nrname_handle)
895 GlobalFree16( hModule );
896 return (HMODULE16)11; /* invalid exe */
898 FarSetOwner16( pModule->nrname_handle, hModule );
899 buffer = GlobalLock16( pModule->nrname_handle );
900 if (!read_data( handle, ne_header.ne_nrestab, buffer, ne_header.ne_cbnrestab ))
902 GlobalFree16( pModule->nrname_handle );
903 GlobalFree16( hModule );
904 return (HMODULE16)11; /* invalid exe */
907 else pModule->nrname_handle = 0;
909 /* Allocate a segment for the implicitly-loaded DLLs */
911 if (pModule->modref_count)
913 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
914 (pModule->modref_count+1)*sizeof(HMODULE16) );
915 if (!pModule->dlls_to_init)
917 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
918 GlobalFree16( hModule );
919 return (HMODULE16)11; /* invalid exe */
921 FarSetOwner16( pModule->dlls_to_init, hModule );
923 else pModule->dlls_to_init = 0;
925 NE_RegisterModule( pModule );
926 SNOOP16_RegisterDLL(pModule,path);
931 /***********************************************************************
934 * Load all DLLs implicitly linked to a module.
936 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
939 WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
940 WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
942 for (i = 0; i < pModule->modref_count; i++, pModRef++)
944 char buffer[260], *p;
945 BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
946 memcpy( buffer, pstr + 1, *pstr );
947 *(buffer + *pstr) = 0; /* terminate it */
949 TRACE("Loading '%s'\n", buffer );
950 if (!(*pModRef = GetModuleHandle16( buffer )))
952 /* If the DLL is not loaded yet, load it and store */
953 /* its handle in the list of DLLs to initialize. */
956 /* Append .DLL to name if no extension present */
957 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
958 strcat( buffer, ".DLL" );
960 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
962 /* FIXME: cleanup what was done */
964 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
965 buffer, *((BYTE*)pModule + pModule->name_table),
966 (char *)pModule + pModule->name_table + 1, hDLL );
969 *pModRef = GetExePtr( hDLL );
972 else /* Increment the reference count of the DLL */
974 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
975 if (pOldDLL) pOldDLL->count++;
982 /**********************************************************************
985 * Load first instance of NE module from file.
987 * pModule must point to a module structure prepared by NE_LoadExeHeader.
988 * This routine must never be called twice on a module.
991 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
993 /* Allocate the segments for this module */
995 if (!NE_CreateAllSegments( pModule ))
996 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
998 /* Load the referenced DLLs */
1000 if (!NE_LoadDLLs( pModule ))
1001 return ERROR_FILE_NOT_FOUND; /* 2 */
1003 /* Load the segments */
1005 NE_LoadAllSegments( pModule );
1007 /* Make sure the usage count is 1 on the first loading of */
1008 /* the module, even if it contains circular DLL references */
1012 return NE_GetInstance( pModule );
1015 /**********************************************************************
1018 * Load first instance of NE module. (Note: caller is responsible for
1019 * ensuring the module isn't already loaded!)
1021 * If the module turns out to be an executable module, only a
1022 * handle to a module stub is returned; this needs to be initialized
1023 * by calling NE_DoLoadModule later, in the context of the newly
1026 * If lib_only is TRUE, however, the module is perforce treated
1027 * like a DLL module, even if it is an executable module.
1030 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
1034 HINSTANCE16 hInstance;
1040 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
1041 return (HMODULE16)2; /* File not found */
1043 hModule = NE_LoadExeHeader( DosFileHandleToWin32Handle(hFile), ofs.szPathName );
1049 pModule = NE_GetPtr( hModule );
1051 drive_type = GetDriveTypeA( ofs.szPathName );
1052 if (drive_type != DRIVE_REMOVABLE && drive_type != DRIVE_CDROM)
1054 /* keep the file handle open if not on a removable media */
1055 DuplicateHandle( GetCurrentProcess(), DosFileHandleToWin32Handle(hFile),
1056 GetCurrentProcess(), &pModule->fd, 0, FALSE,
1057 DUPLICATE_SAME_ACCESS );
1061 if ( !lib_only && !( pModule->flags & NE_FFLAGS_LIBMODULE ) )
1064 hInstance = NE_DoLoadModule( pModule );
1065 if ( hInstance < 32 )
1068 NE_FreeModule( hModule, 0 );
1075 /***********************************************************************
1076 * NE_DoLoadBuiltinModule
1078 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
1080 static HMODULE16 NE_DoLoadBuiltinModule( const BUILTIN16_DESCRIPTOR *descr )
1084 SEGTABLEENTRY *pSegTable;
1087 hModule = GLOBAL_CreateBlock( GMEM_MOVEABLE, descr->module_start,
1088 descr->module_size, 0, WINE_LDT_FLAGS_DATA );
1089 if (!hModule) return 0;
1090 FarSetOwner16( hModule, hModule );
1092 pModule = (NE_MODULE *)GlobalLock16( hModule );
1093 pModule->self = hModule;
1094 /* NOTE: (Ab)use the hRsrcMap parameter for resource data pointer */
1095 pModule->hRsrcMap = (void *)descr->rsrc;
1097 /* Allocate the code segment */
1099 pSegTable = NE_SEG_TABLE( pModule );
1100 pSegTable->hSeg = GLOBAL_CreateBlock( GMEM_FIXED, descr->code_start,
1101 pSegTable->minsize, hModule,
1102 WINE_LDT_FLAGS_CODE|WINE_LDT_FLAGS_32BIT );
1103 if (!pSegTable->hSeg) return 0;
1104 patch_code_segment( descr->code_start );
1107 /* Allocate the data segment */
1109 minsize = pSegTable->minsize ? pSegTable->minsize : 0x10000;
1110 minsize += pModule->heap_size;
1111 if (minsize > 0x10000) minsize = 0x10000;
1112 pSegTable->hSeg = GlobalAlloc16( GMEM_FIXED, minsize );
1113 if (!pSegTable->hSeg) return 0;
1114 FarSetOwner16( pSegTable->hSeg, hModule );
1115 if (pSegTable->minsize) memcpy( GlobalLock16( pSegTable->hSeg ),
1116 descr->data_start, pSegTable->minsize);
1117 if (pModule->heap_size)
1118 LocalInit16( GlobalHandleToSel16(pSegTable->hSeg), pSegTable->minsize, minsize );
1120 if (descr->rsrc) NE_InitResourceHandler(pModule);
1122 NE_RegisterModule( pModule );
1124 /* make sure the 32-bit library containing this one is loaded too */
1125 LoadLibraryA( descr->owner );
1131 /***********************************************************************
1132 * NE_LoadBuiltinModule
1134 * Load a built-in module.
1136 static HMODULE16 NE_LoadBuiltinModule( LPCSTR name )
1138 const BUILTIN16_DESCRIPTOR *descr;
1139 char error[256], dllname[20], *p;
1143 /* Fix the name in case we have a full path and extension */
1145 if ((p = strrchr( name, '\\' ))) name = p + 1;
1146 if ((p = strrchr( name, '/' ))) name = p + 1;
1148 if (strlen(name) >= sizeof(dllname)-4) return (HMODULE16)2;
1150 strcpy( dllname, name );
1151 p = strrchr( dllname, '.' );
1152 if (!p) strcat( dllname, ".dll" );
1153 for (p = dllname; *p; p++) *p = FILE_tolower(*p);
1155 if ((descr = find_dll_descr( dllname )))
1156 return NE_DoLoadBuiltinModule( descr );
1158 if ((handle = wine_dll_load( dllname, error, sizeof(error), &file_exists )))
1160 if ((descr = find_dll_descr( dllname )))
1161 return NE_DoLoadBuiltinModule( descr );
1163 ERR( "loaded .so but dll %s still not found\n", dllname );
1167 if (!file_exists) WARN("cannot open .so lib for 16-bit builtin %s: %s\n", name, error);
1168 else ERR("failed to load .so lib for 16-bit builtin %s: %s\n", name, error );
1170 return (HMODULE16)2;
1174 /**********************************************************************
1175 * MODULE_LoadModule16
1177 * Load a NE module in the order of the loadorder specification.
1178 * The caller is responsible that the module is not loaded already.
1181 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1183 HINSTANCE16 hinst = 2;
1184 enum loadorder_type loadorder[LOADORDER_NTYPES];
1186 const char *filetype = "";
1187 const char *ptr, *basename;
1189 /* strip path information */
1192 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
1193 if ((ptr = strrchr( basename, '\\' ))) basename = ptr + 1;
1194 if ((ptr = strrchr( basename, '/' ))) basename = ptr + 1;
1196 if (is_builtin_present(basename))
1198 TRACE( "forcing loadorder to builtin for %s\n", debugstr_a(basename) );
1199 /* force builtin loadorder since the dll is already in memory */
1200 loadorder[0] = LOADORDER_BI;
1201 loadorder[1] = LOADORDER_INVALID;
1203 else MODULE_GetLoadOrder(loadorder, basename, FALSE);
1205 for(i = 0; i < LOADORDER_NTYPES; i++)
1207 if (loadorder[i] == LOADORDER_INVALID) break;
1209 switch(loadorder[i])
1212 TRACE("Trying native dll '%s'\n", libname);
1213 hinst = NE_LoadModule(libname, lib_only);
1214 filetype = "native";
1218 TRACE("Trying built-in '%s'\n", libname);
1219 hinst = NE_LoadBuiltinModule(libname);
1220 filetype = "builtin";
1230 TRACE_(loaddll)("Loaded module '%s' : %s\n", libname, filetype);
1236 hModule = GetModuleHandle16(libname);
1239 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1241 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
1244 pModule = NE_GetPtr(hModule);
1247 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1249 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
1252 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1255 * Call initialization routines for all loaded DLLs. Note that
1256 * when we load implicitly linked DLLs this will be done by InitTask().
1258 if(pModule->flags & NE_FFLAGS_LIBMODULE)
1260 NE_InitializeDLLs(hModule);
1261 NE_DllProcessAttach(hModule);
1269 /* We quit searching when we get another error than 'File not found' */
1273 return hinst; /* The last error that occurred */
1277 /**********************************************************************
1280 * Create the thread for a 16-bit module.
1282 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1287 HINSTANCE16 instance = 0;
1289 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1292 /* Post event to start the task */
1293 PostEvent16( hTask );
1295 /* Wait until we get the instance handle */
1298 DirectedYield16( hTask );
1299 if (!IsTask16( hTask )) /* thread has died */
1302 WaitForSingleObject( hThread, INFINITE );
1303 GetExitCodeThread( hThread, &exit_code );
1304 CloseHandle( hThread );
1307 if (!(pTask = GlobalLock16( hTask ))) break;
1308 instance = pTask->hInstance;
1309 GlobalUnlock16( hTask );
1310 } while (!instance);
1312 CloseHandle( hThread );
1317 /**********************************************************************
1318 * LoadModule (KERNEL.45)
1320 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1322 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1323 LOADPARAMS16 *params;
1331 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1333 /* Special case: second instance of an already loaded NE module */
1335 if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
1336 if ( pModule->module32 ) return (HINSTANCE16)21;
1338 /* Increment refcount */
1344 /* Main case: load first instance of NE module */
1346 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1349 if ( !(pModule = NE_GetPtr( hModule )) )
1350 return (HINSTANCE16)11;
1353 /* If library module, we just retrieve the instance handle */
1355 if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1356 return NE_GetInstance( pModule );
1359 * At this point, we need to create a new process.
1361 * pModule points either to an already loaded module, whose refcount
1362 * has already been incremented (to avoid having the module vanish
1363 * in the meantime), or else to a stub module which contains only header
1366 params = (LOADPARAMS16 *)paramBlock;
1367 cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1368 cmdline = MapSL( params->cmdLine );
1369 return NE_CreateThread( pModule, cmdShow, cmdline );
1373 /**********************************************************************
1376 * Startup code for a new 16-bit task.
1378 DWORD NE_StartTask(void)
1380 TDB *pTask = TASK_GetCurrent();
1381 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1382 HINSTANCE16 hInstance, hPrevInstance;
1383 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1386 if ( pModule->count > 0 )
1388 /* Second instance of an already loaded NE module */
1389 /* Note that the refcount was already incremented by the parent */
1391 hPrevInstance = NE_GetInstance( pModule );
1393 if ( pModule->dgroup )
1394 if ( NE_CreateSegment( pModule, pModule->dgroup ) )
1395 NE_LoadSegment( pModule, pModule->dgroup );
1397 hInstance = NE_GetInstance( pModule );
1398 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->dgroup, hPrevInstance);
1403 /* Load first instance of NE module */
1405 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1407 hInstance = NE_DoLoadModule( pModule );
1411 if ( hInstance >= 32 )
1415 /* Enter instance handles into task struct */
1417 pTask->hInstance = hInstance;
1418 pTask->hPrevInstance = hPrevInstance;
1420 /* Use DGROUP for 16-bit stack */
1422 if (!(sp = pModule->sp))
1423 sp = pSegTable[pModule->ss-1].minsize + pModule->stack_size;
1425 sp -= sizeof(STACK16FRAME);
1426 NtCurrentTeb()->cur_stack = MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1428 /* Registers at initialization must be:
1430 * bx stack size in bytes
1431 * cx heap size in bytes
1432 * si previous app instance
1433 * di current app instance
1435 * es selector to the PSP
1436 * ds dgroup of the application
1438 * sp top of the stack
1440 memset( &context, 0, sizeof(context) );
1441 context.SegCs = GlobalHandleToSel16(pSegTable[pModule->cs - 1].hSeg);
1442 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1443 context.SegEs = pTask->hPDB;
1444 context.Eip = pModule->ip;
1445 context.Ebx = pModule->stack_size;
1446 context.Ecx = pModule->heap_size;
1447 context.Edi = pTask->hInstance;
1448 context.Esi = pTask->hPrevInstance;
1450 /* Now call 16-bit entry point */
1452 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1453 context.SegCs, context.Eip, context.SegDs,
1454 SELECTOROF(NtCurrentTeb()->cur_stack),
1455 OFFSETOF(NtCurrentTeb()->cur_stack) );
1457 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1458 ExitThread( LOWORD(context.Eax) );
1460 return hInstance; /* error code */
1463 /***********************************************************************
1464 * LoadLibrary (KERNEL.95)
1465 * LoadLibrary16 (KERNEL32.35)
1467 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1469 return LoadModule16(libname, (LPVOID)-1 );
1473 /**********************************************************************
1476 * Call a DLL's WEP, allowing it to shut down.
1477 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1479 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1482 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1483 if (!WEP) return FALSE;
1490 args[0] = WEP_FREE_DLL;
1491 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1492 ret = LOWORD(dwRet);
1494 __EXCEPT(page_fault)
1496 WARN("Page fault\n");
1505 /**********************************************************************
1508 * Implementation of FreeModule16().
1510 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1512 HMODULE16 *hPrevModule;
1517 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1518 hModule = pModule->self;
1520 TRACE("%04x count %d\n", hModule, pModule->count );
1522 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1523 else pModule->count = 0;
1525 if (pModule->flags & NE_FFLAGS_BUILTIN)
1526 return FALSE; /* Can't free built-in module */
1528 if (call_wep && !(pModule->flags & NE_FFLAGS_WIN32))
1530 /* Free the objects owned by the DLL module */
1531 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1533 if (pModule->flags & NE_FFLAGS_LIBMODULE)
1534 MODULE_CallWEP( hModule );
1536 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1540 /* Clear magic number just in case */
1542 pModule->magic = pModule->self = 0;
1543 if (pModule->fd) CloseHandle( pModule->fd );
1545 /* Remove it from the linked list */
1547 hPrevModule = &hFirstModule;
1548 while (*hPrevModule && (*hPrevModule != hModule))
1550 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1552 if (*hPrevModule) *hPrevModule = pModule->next;
1554 /* Free the referenced modules */
1556 pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1557 for (i = 0; i < pModule->modref_count; i++, pModRef++)
1559 NE_FreeModule( *pModRef, call_wep );
1562 /* Free the module storage */
1564 GlobalFreeAll16( hModule );
1569 /**********************************************************************
1570 * FreeModule (KERNEL.46)
1572 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1574 return NE_FreeModule( hModule, TRUE );
1578 /***********************************************************************
1579 * FreeLibrary (KERNEL.96)
1580 * FreeLibrary16 (KERNEL32.36)
1582 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1584 TRACE("%04x\n", handle );
1585 FreeModule16( handle );
1589 /***********************************************************************
1590 * GetModuleHandle16 (KERNEL32.@)
1592 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1594 HMODULE16 hModule = hFirstModule;
1596 BYTE len, *name_table;
1597 char tmpstr[MAX_PATH];
1600 TRACE("(%s)\n", name);
1602 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1607 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1609 /* If 'name' matches exactly the module name of a module:
1610 * Return its handle.
1612 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1614 pModule = NE_GetPtr( hModule );
1615 if (!pModule) break;
1616 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1618 name_table = (BYTE *)pModule + pModule->name_table;
1619 if ((*name_table == len) && !strncmp(name, name_table+1, len))
1623 /* If uppercased 'name' matches exactly the module name of a module:
1626 for (s = tmpstr; *s; s++) *s = FILE_toupper(*s);
1628 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1630 pModule = NE_GetPtr( hModule );
1631 if (!pModule) break;
1632 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1634 name_table = (BYTE *)pModule + pModule->name_table;
1635 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1636 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1637 * lowercased module names, but try to load uppercase DLLs, so this
1638 * 'i' compare is just a quickfix until the loader handles that
1639 * correctly. -MM 990705
1641 if ((*name_table == len) && !FILE_strncasecmp(tmpstr, name_table+1, len))
1645 /* If the base filename of 'name' matches the base filename of the module
1646 * filename of some module (case-insensitive compare):
1647 * Return its handle.
1650 /* basename: search backwards in passed name to \ / or : */
1651 s = tmpstr + strlen(tmpstr);
1654 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1659 /* search this in loaded filename list */
1660 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1665 pModule = NE_GetPtr( hModule );
1666 if (!pModule) break;
1667 if (!pModule->fileinfo) continue;
1668 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1670 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1671 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1672 /* basename: search backwards in pathname to \ / or : */
1673 while (loadedfn > (char*)ofs->szPathName)
1675 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1679 /* case insensitive compare ... */
1680 if (!FILE_strcasecmp(loadedfn, s))
1687 /**********************************************************************
1688 * GetModuleName (KERNEL.27)
1690 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1695 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1696 p = (BYTE *)pModule + pModule->name_table;
1697 if (count > *p) count = *p + 1;
1700 memcpy( buf, p + 1, count - 1 );
1701 buf[count-1] = '\0';
1707 /**********************************************************************
1708 * GetModuleUsage (KERNEL.48)
1710 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1712 NE_MODULE *pModule = NE_GetPtr( hModule );
1713 return pModule ? pModule->count : 0;
1717 /**********************************************************************
1718 * GetExpWinVer (KERNEL.167)
1720 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1722 NE_MODULE *pModule = NE_GetPtr( hModule );
1723 if ( !pModule ) return 0;
1726 * For built-in modules, fake the expected version the module should
1727 * have according to the Windows version emulated by Wine
1729 if ( !pModule->expected_version )
1731 OSVERSIONINFOA versionInfo;
1732 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1734 if ( GetVersionExA( &versionInfo ) )
1735 pModule->expected_version =
1736 (versionInfo.dwMajorVersion & 0xff) << 8
1737 | (versionInfo.dwMinorVersion & 0xff);
1740 return pModule->expected_version;
1744 /***********************************************************************
1745 * WinExec (KERNEL.166)
1747 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1749 LPCSTR p, args = NULL;
1750 LPCSTR name_beg, name_end;
1751 LPSTR name, cmdline;
1754 char buffer[MAX_PATH];
1756 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1758 name_beg = lpCmdLine+1;
1759 p = strchr ( lpCmdLine+1, '"' );
1763 args = strchr ( p, ' ' );
1765 else /* yes, even valid with trailing '"' missing */
1766 name_end = lpCmdLine+strlen(lpCmdLine);
1770 name_beg = lpCmdLine;
1771 args = strchr( lpCmdLine, ' ' );
1772 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1775 if ((name_beg == lpCmdLine) && (!args))
1776 { /* just use the original cmdline string as file name */
1777 name = (LPSTR)lpCmdLine;
1781 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1782 return ERROR_NOT_ENOUGH_MEMORY;
1783 memcpy( name, name_beg, name_end - name_beg );
1784 name[name_end - name_beg] = '\0';
1790 arglen = strlen(args);
1791 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1792 cmdline[0] = (BYTE)arglen;
1793 strcpy( cmdline + 1, args );
1797 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1798 cmdline[0] = cmdline[1] = 0;
1801 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1803 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1805 LOADPARAMS16 params;
1808 showCmd[1] = nCmdShow;
1810 params.hEnvironment = 0;
1811 params.cmdLine = MapLS( cmdline );
1812 params.showCmd = MapLS( showCmd );
1813 params.reserved = 0;
1815 ret = LoadModule16( buffer, ¶ms );
1816 UnMapLS( params.cmdLine );
1817 UnMapLS( params.showCmd );
1819 else ret = GetLastError();
1821 HeapFree( GetProcessHeap(), 0, cmdline );
1822 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1824 if (ret == 21) /* 32-bit module */
1827 ReleaseThunkLock( &count );
1828 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1829 RestoreThunkLock( count );
1834 /***********************************************************************
1835 * GetProcAddress (KERNEL.50)
1837 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1842 if (!hModule) hModule = GetCurrentTask();
1843 hModule = GetExePtr( hModule );
1845 if (HIWORD(name) != 0)
1847 ordinal = NE_GetOrdinal( hModule, name );
1848 TRACE("%04x '%s'\n", hModule, name );
1852 ordinal = LOWORD(name);
1853 TRACE("%04x %04x\n", hModule, ordinal );
1855 if (!ordinal) return (FARPROC16)0;
1857 ret = NE_GetEntryPoint( hModule, ordinal );
1859 TRACE("returning %08x\n", (UINT)ret );
1864 /***************************************************************************
1865 * HasGPHandler (KERNEL.338)
1867 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1872 GPHANDLERDEF *gpHandler;
1874 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1875 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1876 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1877 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1878 && (gpHandler = MapSL( gpPtr )) != NULL )
1880 while (gpHandler->selector)
1882 if ( SELECTOROF(address) == gpHandler->selector
1883 && OFFSETOF(address) >= gpHandler->rangeStart
1884 && OFFSETOF(address) < gpHandler->rangeEnd )
1885 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1894 /**********************************************************************
1895 * GetModuleHandle (KERNEL.47)
1897 * Find a module from a module name.
1899 * NOTE: The current implementation works the same way the Windows 95 one
1900 * does. Do not try to 'fix' it, fix the callers.
1901 * + It does not do ANY extension handling (except that strange .EXE bit)!
1902 * + It does not care about paths, just about basenames. (same as Windows)
1906 * the win16 module handle if found
1908 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1909 * Always hFirstModule
1911 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1913 if (HIWORD(name) == 0)
1914 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1915 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1918 /**********************************************************************
1919 * NE_GetModuleByFilename
1921 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1925 BYTE len, *name_table;
1926 char tmpstr[MAX_PATH];
1929 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1931 /* If the base filename of 'name' matches the base filename of the module
1932 * filename of some module (case-insensitive compare):
1933 * Return its handle.
1936 /* basename: search backwards in passed name to \ / or : */
1937 s = tmpstr + strlen(tmpstr);
1940 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1945 /* search this in loaded filename list */
1946 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1951 pModule = NE_GetPtr( hModule );
1952 if (!pModule) break;
1953 if (!pModule->fileinfo) continue;
1954 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1956 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1957 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1958 /* basename: search backwards in pathname to \ / or : */
1959 while (loadedfn > (char*)ofs->szPathName)
1961 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1965 /* case insensitive compare ... */
1966 if (!FILE_strcasecmp(loadedfn, s))
1969 /* If basename (without ext) matches the module name of a module:
1970 * Return its handle.
1973 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1976 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1978 pModule = NE_GetPtr( hModule );
1979 if (!pModule) break;
1980 if (pModule->flags & NE_FFLAGS_WIN32) continue;
1982 name_table = (BYTE *)pModule + pModule->name_table;
1983 if ((*name_table == len) && !FILE_strncasecmp(s, name_table+1, len))
1990 /***********************************************************************
1991 * GetProcAddress16 (KERNEL32.37)
1992 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1994 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1996 if (!hModule) return 0;
1997 if (HIWORD(hModule))
1999 WARN("hModule is Win32 handle (%p)\n", hModule );
2002 return GetProcAddress16( LOWORD(hModule), name );
2005 /**********************************************************************
2006 * ModuleFirst (TOOLHELP.59)
2008 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
2010 lpme->wNext = hFirstModule;
2011 return ModuleNext16( lpme );
2015 /**********************************************************************
2016 * ModuleNext (TOOLHELP.60)
2018 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
2023 if (!lpme->wNext) return FALSE;
2024 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
2025 name = (char *)pModule + pModule->name_table;
2026 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
2027 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
2028 lpme->hModule = lpme->wNext;
2029 lpme->wcUsage = pModule->count;
2030 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
2031 lpme->wNext = pModule->next;
2036 /**********************************************************************
2037 * ModuleFindName (TOOLHELP.61)
2039 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
2041 lpme->wNext = GetModuleHandle16( name );
2042 return ModuleNext16( lpme );
2046 /**********************************************************************
2047 * ModuleFindHandle (TOOLHELP.62)
2049 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
2051 hModule = GetExePtr( hModule );
2052 lpme->wNext = hModule;
2053 return ModuleNext16( lpme );
2057 /***************************************************************************
2058 * IsRomModule (KERNEL.323)
2060 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
2065 /***************************************************************************
2066 * IsRomFile (KERNEL.326)
2068 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
2073 /***********************************************************************
2074 * create_dummy_module
2076 * Create a dummy NE module for Win32 or Winelib.
2078 static HMODULE16 create_dummy_module( HMODULE module32 )
2082 SEGTABLEENTRY *pSegment;
2085 const char* basename;
2088 char filename[MAX_PATH];
2089 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
2091 if (!nt) return (HMODULE16)11; /* invalid exe */
2093 /* Extract base filename */
2094 GetModuleFileNameA( module32, filename, sizeof(filename) );
2095 basename = strrchr(filename, '\\');
2096 if (!basename) basename = filename;
2098 len = strlen(basename);
2099 if ((s = strchr(basename, '.'))) len = s - basename;
2101 /* Allocate module */
2102 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2103 + strlen(filename) + 1;
2104 size = sizeof(NE_MODULE) +
2105 /* loaded file info */
2106 ((of_size + 3) & ~3) +
2107 /* segment table: DS,CS */
2108 2 * sizeof(SEGTABLEENTRY) +
2111 /* several empty tables */
2114 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2115 if (!hModule) return (HMODULE16)11; /* invalid exe */
2117 FarSetOwner16( hModule, hModule );
2118 pModule = (NE_MODULE *)GlobalLock16( hModule );
2120 /* Set all used entries */
2121 pModule->magic = IMAGE_OS2_SIGNATURE;
2124 pModule->flags = NE_FFLAGS_WIN32;
2125 pModule->dgroup = 0;
2128 pModule->heap_size = 0;
2129 pModule->stack_size = 0;
2130 pModule->seg_count = 2;
2131 pModule->modref_count = 0;
2132 pModule->nrname_size = 0;
2133 pModule->fileinfo = sizeof(NE_MODULE);
2134 pModule->os_flags = NE_OSFLAGS_WINDOWS;
2135 pModule->self = hModule;
2136 pModule->module32 = module32;
2138 /* Set version and flags */
2139 pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2140 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2141 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2142 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2144 /* Set loaded file information */
2145 ofs = (OFSTRUCT *)(pModule + 1);
2146 memset( ofs, 0, of_size );
2147 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
2148 strcpy( ofs->szPathName, filename );
2150 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2151 pModule->seg_table = (int)pSegment - (int)pModule;
2154 pSegment->flags = NE_SEGFLAGS_DATA;
2155 pSegment->minsize = 0x1000;
2158 pSegment->flags = 0;
2162 pStr = (char *)pSegment;
2163 pModule->name_table = (int)pStr - (int)pModule;
2166 lstrcpynA( pStr+1, basename, len+1 );
2169 /* All tables zero terminated */
2170 pModule->res_table = pModule->import_table = pModule->entry_table = (int)pStr - (int)pModule;
2172 NE_RegisterModule( pModule );
2173 LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
2177 /***********************************************************************
2178 * PrivateLoadLibrary (KERNEL32.@)
2180 * FIXME: rough guesswork, don't know what "Private" means
2182 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2184 return LoadLibrary16(libname);
2187 /***********************************************************************
2188 * PrivateFreeLibrary (KERNEL32.@)
2190 * FIXME: rough guesswork, don't know what "Private" means
2192 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2194 FreeLibrary16(handle);
2197 /***********************************************************************
2198 * LoadLibrary32 (KERNEL.452)
2199 * LoadSystemLibrary32 (KERNEL.482)
2201 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2206 ReleaseThunkLock( &count );
2207 hModule = LoadLibraryA( libname );
2208 RestoreThunkLock( count );
2212 /***************************************************************************
2213 * MapHModuleLS (KERNEL32.@)
2215 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2221 return TASK_GetCurrent()->hInstance;
2223 return LOWORD(hmod); /* we already have a 16 bit module handle */
2224 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2226 if (pModule->module32 == hmod)
2227 return pModule->self;
2228 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2230 if ((ret = create_dummy_module( hmod )) < 32)
2238 /***************************************************************************
2239 * MapHModuleSL (KERNEL32.@)
2241 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2246 TDB *pTask = TASK_GetCurrent();
2247 hmod = pTask->hModule;
2249 pModule = (NE_MODULE*)GlobalLock16(hmod);
2250 if ((pModule->magic!=IMAGE_OS2_SIGNATURE) || !(pModule->flags & NE_FFLAGS_WIN32))
2252 return pModule->module32;
2255 /***************************************************************************
2256 * MapHInstLS (KERNEL32.@)
2257 * MapHInstLS (KERNEL.472)
2259 void WINAPI MapHInstLS( CONTEXT86 *context )
2261 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2264 /***************************************************************************
2265 * MapHInstSL (KERNEL32.@)
2266 * MapHInstSL (KERNEL.473)
2268 void WINAPI MapHInstSL( CONTEXT86 *context )
2270 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2273 /***************************************************************************
2274 * MapHInstLS_PN (KERNEL32.@)
2276 void WINAPI MapHInstLS_PN( CONTEXT86 *context )
2278 if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2281 /***************************************************************************
2282 * MapHInstSL_PN (KERNEL32.@)
2284 void WINAPI MapHInstSL_PN( CONTEXT86 *context )
2286 if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );