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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
36 #include "wine/winbase16.h"
39 #include "kernel16_private.h"
40 #include "wine/exception.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(module);
44 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
45 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 typedef struct _GPHANDLERDEF
60 struct ne_segment_table_entry_s
62 WORD seg_data_offset; /* Sector offset of segment data */
63 WORD seg_data_length; /* Length of segment data */
64 WORD seg_flags; /* Flags associated with this segment */
65 WORD min_alloc; /* Minimum allocation size for this */
68 #define hFirstModule (pThhook->hExeHead)
72 const IMAGE_DOS_HEADER *header; /* module headers */
73 const char *file_name; /* module file name */
76 /* Table of all built-in DLLs */
80 static struct builtin_dll builtin_dlls[MAX_DLLS];
82 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
83 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
85 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
87 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
90 /* patch all the flat cs references of the code segment if necessary */
91 static inline void patch_code_segment( NE_MODULE *pModule )
95 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule );
97 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
98 if (!(pSeg->flags & NE_SEGFLAGS_DATA)) break; /* found the code segment */
100 call = GlobalLock16( pSeg->hSeg );
102 /* patch glue code address and code selector */
103 for (i = 0; call[i].pushl == 0x68; i++)
105 if (call[i].ret[0] == 0xca66 || call[i].ret[0] == 0xcb66) /* register entry point? */
106 call[i].glue = __wine_call_from_16_regs;
108 call[i].glue = __wine_call_from_16;
109 call[i].flatcs = wine_get_cs();
112 if (TRACE_ON(relay)) /* patch relay functions to all point to relay_call_from_16 */
113 for (i = 0; call[i].pushl == 0x68; i++) call[i].relay = relay_call_from_16;
117 /***********************************************************************
120 static inline int contains_path( LPCSTR name )
122 return ((*name && (name[1] == ':')) || strchr(name, '/') || strchr(name, '\\'));
126 /***********************************************************************
129 * locale-independent case conversion for module lookups
131 static int NE_strcasecmp( const char *str1, const char *str2 )
134 for ( ; ; str1++, str2++)
135 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
140 /***********************************************************************
143 * locale-independent case conversion for module lookups
145 static int NE_strncasecmp( const char *str1, const char *str2, int len )
148 for ( ; len > 0; len--, str1++, str2++)
149 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
154 /***********************************************************************
157 * Find a descriptor in the list
159 static const IMAGE_DOS_HEADER *find_dll_descr( const char *dllname, const char **file_name )
162 const IMAGE_DOS_HEADER *mz_header;
163 const IMAGE_OS2_HEADER *ne_header;
164 const BYTE *name_table;
166 for (i = 0; i < MAX_DLLS; i++)
168 mz_header = builtin_dlls[i].header;
171 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mz_header + mz_header->e_lfanew);
172 name_table = (const BYTE *)ne_header + ne_header->ne_restab;
174 /* check the dll file name */
175 if (!NE_strcasecmp( builtin_dlls[i].file_name, dllname ) ||
176 /* check the dll module name (without extension) */
177 (!NE_strncasecmp( dllname, (const char*)name_table+1, *name_table ) &&
178 !strcmp( dllname + *name_table, ".dll" )))
180 *file_name = builtin_dlls[i].file_name;
181 return builtin_dlls[i].header;
189 /***********************************************************************
190 * __wine_dll_register_16 (KERNEL32.@)
192 * Register a built-in DLL descriptor.
194 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
198 for (i = 0; i < MAX_DLLS; i++)
200 if (builtin_dlls[i].header) continue;
201 builtin_dlls[i].header = header;
202 builtin_dlls[i].file_name = file_name;
205 assert( i < MAX_DLLS );
209 /***********************************************************************
210 * __wine_dll_unregister_16 (KERNEL32.@)
212 * Unregister a built-in DLL descriptor.
214 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
218 for (i = 0; i < MAX_DLLS; i++)
220 if (builtin_dlls[i].header != header) continue;
221 builtin_dlls[i].header = NULL;
227 /***********************************************************************
230 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
232 return GlobalLock16( GetExePtr(hModule) );
236 /**********************************************************************
239 static void NE_RegisterModule( NE_MODULE *pModule )
241 pModule->next = hFirstModule;
242 hFirstModule = pModule->self;
246 /***********************************************************************
249 void NE_DumpModule( HMODULE16 hModule )
259 if (!(pModule = NE_GetPtr( hModule )))
261 ERR( "**** %04x is not a module handle\n", hModule );
265 /* Dump the module info */
267 TRACE( "Module %04x:\n", hModule );
268 TRACE( "count=%d flags=%04x heap=%d stack=%d\n",
269 pModule->count, pModule->ne_flags,
270 pModule->ne_heap, pModule->ne_stack );
271 TRACE( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
272 SELECTOROF(pModule->ne_csip), OFFSETOF(pModule->ne_csip),
273 SELECTOROF(pModule->ne_sssp), OFFSETOF(pModule->ne_sssp),
274 pModule->ne_autodata, pModule->ne_cseg, pModule->ne_cmod );
275 TRACE( "os_flags=%d swap_area=%d version=%04x\n",
276 pModule->ne_exetyp, pModule->ne_swaparea, pModule->ne_expver );
277 if (pModule->ne_flags & NE_FFLAGS_WIN32)
278 TRACE( "PE module=%p\n", pModule->module32 );
280 /* Dump the file info */
282 TRACE( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
284 /* Dump the segment table */
286 TRACE( "Segment table:\n" );
287 pSeg = NE_SEG_TABLE( pModule );
288 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
289 TRACE( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
290 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
291 pSeg->minsize, pSeg->hSeg );
293 /* Dump the resource table */
295 TRACE( "Resource table:\n" );
296 if (pModule->ne_rsrctab)
298 pword = (WORD *)((BYTE *)pModule + pModule->ne_rsrctab);
299 TRACE( "Alignment: %d\n", *pword++ );
302 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
303 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
304 TRACE( "id=%04x count=%d\n", ptr->type_id, ptr->count );
305 for (i = 0; i < ptr->count; i++, pname++)
306 TRACE( "offset=%d len=%d id=%04x\n",
307 pname->offset, pname->length, pname->id );
308 pword = (WORD *)pname;
311 else TRACE( "None\n" );
313 /* Dump the resident name table */
315 TRACE( "Resident-name table:\n" );
316 pstr = (BYTE*) pModule + pModule->ne_restab;
319 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
320 *(WORD *)(pstr + *pstr + 1) );
321 pstr += *pstr + 1 + sizeof(WORD);
324 /* Dump the module reference table */
326 TRACE( "Module ref table:\n" );
327 if (pModule->ne_modtab)
329 pword = (WORD *)((BYTE *)pModule + pModule->ne_modtab);
330 for (i = 0; i < pModule->ne_cmod; i++, pword++)
333 GetModuleName16( *pword, name, sizeof(name) );
334 TRACE( "%d: %04x -> '%s'\n", i, *pword, name );
337 else TRACE( "None\n" );
339 /* Dump the entry table */
341 TRACE( "Entry table:\n" );
342 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->ne_enttab);
344 entry = (ET_ENTRY *)((BYTE *)bundle+6);
345 TRACE( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
346 ordinal = bundle->first;
347 while (ordinal < bundle->last)
349 if (entry->type == 0xff)
350 TRACE("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
352 TRACE("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
355 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
357 /* Dump the non-resident names table */
359 TRACE( "Non-resident names table:\n" );
360 if (pModule->nrname_handle)
362 pstr = GlobalLock16( pModule->nrname_handle );
365 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
366 *(WORD *)(pstr + *pstr + 1) );
367 pstr += *pstr + 1 + sizeof(WORD);
374 /***********************************************************************
377 * Walk the module list and print the modules.
379 void NE_WalkModules(void)
381 HMODULE16 hModule = hFirstModule;
382 MESSAGE( "Module Flags Name\n" );
385 NE_MODULE *pModule = NE_GetPtr( hModule );
388 MESSAGE( "Bad module %04x in list\n", hModule );
391 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->ne_flags,
392 *((char *)pModule + pModule->ne_restab),
393 (char *)pModule + pModule->ne_restab + 1 );
394 hModule = pModule->next;
399 /***********************************************************************
400 * NE_InitResourceHandler
402 * Fill in 'resloader' fields in the resource table.
404 static void NE_InitResourceHandler( HMODULE16 hModule )
406 static FARPROC16 proc;
408 NE_TYPEINFO *pTypeInfo;
411 if (!(pModule = NE_GetPtr( hModule )) || !pModule->ne_rsrctab) return;
413 TRACE("InitResourceHandler[%04x]\n", hModule );
415 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
417 pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->ne_rsrctab + 2);
418 while(pTypeInfo->type_id)
420 memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
421 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
426 /***********************************************************************
429 * Lookup the ordinal for a given name.
431 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
433 char buffer[256], *p;
438 if (!(pModule = NE_GetPtr( hModule ))) return 0;
439 if (pModule->ne_flags & NE_FFLAGS_WIN32) return 0;
441 TRACE("(%04x,'%s')\n", hModule, name );
443 /* First handle names of the form '#xxxx' */
445 if (name[0] == '#') return atoi( name + 1 );
447 /* Now copy and uppercase the string */
449 strcpy( buffer, name );
450 for (p = buffer; *p; p++) *p = RtlUpperChar(*p);
453 /* First search the resident names */
455 cpnt = (BYTE *)pModule + pModule->ne_restab;
457 /* Skip the first entry (module name) */
458 cpnt += *cpnt + 1 + sizeof(WORD);
461 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
464 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
465 TRACE(" Found: ordinal=%d\n", ordinal );
468 cpnt += *cpnt + 1 + sizeof(WORD);
471 /* Now search the non-resident names table */
473 if (!pModule->nrname_handle) return 0; /* No non-resident table */
474 cpnt = GlobalLock16( pModule->nrname_handle );
476 /* Skip the first entry (module description string) */
477 cpnt += *cpnt + 1 + sizeof(WORD);
480 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
483 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
484 TRACE(" Found: ordinal=%d\n", ordinal );
487 cpnt += *cpnt + 1 + sizeof(WORD);
493 /***********************************************************************
496 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
498 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
501 /***********************************************************************
504 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
512 if (!(pModule = NE_GetPtr( hModule ))) return 0;
513 assert( !(pModule->ne_flags & NE_FFLAGS_WIN32) );
515 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
516 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
520 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
523 entry = (ET_ENTRY *)((BYTE *)bundle+6);
524 for (i=0; i < (ordinal - bundle->first - 1); i++)
528 memcpy( &offset, &entry->offs, sizeof(WORD) );
530 if (sel == 0xfe) sel = 0xffff; /* constant entry */
531 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
533 return (FARPROC16)MAKESEGPTR( sel, offset );
535 return (FARPROC16)MAKESEGPTR( sel, offset );
537 return SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
541 /***********************************************************************
542 * EntryAddrProc (KERNEL.667) Wine-specific export
544 * Return the entry point for a given ordinal.
546 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
548 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
549 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
553 /***********************************************************************
556 * Change the value of an entry point. Use with caution!
557 * It can only change the offset value, not the selector.
559 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
566 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
567 assert( !(pModule->ne_flags & NE_FFLAGS_WIN32) );
569 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
570 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
572 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
573 if (!(bundle->next)) return 0;
576 entry = (ET_ENTRY *)((BYTE *)bundle+6);
577 for (i=0; i < (ordinal - bundle->first - 1); i++)
580 memcpy( &entry->offs, &offset, sizeof(WORD) );
585 /***********************************************************************
588 * Build the entry table bundle data from the on-disk format. Helper for build_module.
590 static void *build_bundle_data( NE_MODULE *pModule, void *dest, const BYTE *table )
592 ET_BUNDLE *oldbundle, *bundle = dest;
594 BYTE nr_entries, type;
596 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
597 entry = (ET_ENTRY *)((BYTE *)bundle+6);
599 while ((nr_entries = *table++))
601 if ((type = *table++))
603 bundle->last += nr_entries;
609 entry->flags = *table++;
610 table += sizeof(WORD);
611 entry->segnum = *table++;
612 entry->offs = *(const WORD *)table;
613 table += sizeof(WORD);
622 entry->flags = *table++;
623 entry->segnum = type;
624 entry->offs = *(const WORD *)table;
625 table += sizeof(WORD);
632 if (bundle->first == bundle->last)
634 bundle->first += nr_entries;
635 bundle->last += nr_entries;
640 oldbundle->next = (char *)entry - (char *)pModule;
641 bundle = (ET_BUNDLE *)entry;
642 bundle->first = bundle->last = oldbundle->last + nr_entries;
644 entry = (ET_ENTRY*)(((BYTE*)entry)+sizeof(ET_BUNDLE));
652 /***********************************************************************
655 * Build the in-memory module from the on-disk data.
657 static HMODULE16 build_module( const void *mapping, SIZE_T mapping_size, LPCSTR path )
659 const IMAGE_DOS_HEADER *mz_header = mapping;
660 const IMAGE_OS2_HEADER *ne_header;
661 const struct ne_segment_table_entry_s *pSeg;
667 BYTE *buffer, *pData, *end;
670 if (mapping_size < sizeof(*mz_header)) return ERROR_BAD_FORMAT;
671 if (mz_header->e_magic != IMAGE_DOS_SIGNATURE) return ERROR_BAD_FORMAT;
672 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mapping + mz_header->e_lfanew);
673 if (mz_header->e_lfanew + sizeof(*ne_header) > mapping_size) return ERROR_BAD_FORMAT;
674 if (ne_header->ne_magic == IMAGE_NT_SIGNATURE) return 21; /* win32 exe */
675 if (ne_header->ne_magic == IMAGE_OS2_SIGNATURE_LX)
677 MESSAGE("Sorry, %s is an OS/2 linear executable (LX) file!\n", path);
680 if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE) return ERROR_BAD_FORMAT;
682 /* We now have a valid NE header */
684 /* check to be able to fall back to loading OS/2 programs as DOS
685 * FIXME: should this check be reversed in order to be less strict?
686 * (only fail for OS/2 ne_exetyp 0x01 here?) */
687 if ((ne_header->ne_exetyp != 0x02 /* Windows */)
688 && (ne_header->ne_exetyp != 0x04) /* Windows 386 */)
689 return ERROR_BAD_FORMAT;
691 size = sizeof(NE_MODULE) +
693 ne_header->ne_cseg * sizeof(SEGTABLEENTRY) +
695 ne_header->ne_restab - ne_header->ne_rsrctab +
696 /* resident names table */
697 ne_header->ne_modtab - ne_header->ne_restab +
698 /* module ref table */
699 ne_header->ne_cmod * sizeof(WORD) +
700 /* imported names table */
701 ne_header->ne_enttab - ne_header->ne_imptab +
702 /* entry table length */
703 ne_header->ne_cbenttab +
704 /* entry table extra conversion space */
706 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6) +
707 /* loaded file info */
708 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
710 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
711 if (!hModule) return ERROR_BAD_FORMAT;
713 FarSetOwner16( hModule, hModule );
714 pModule = GlobalLock16( hModule );
715 memcpy( pModule, ne_header, sizeof(*ne_header) );
717 /* check programs for default minimal stack size */
718 if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE) && (pModule->ne_stack < 0x1400))
719 pModule->ne_stack = 0x1400;
721 pModule->self = hModule;
722 pModule->mapping = mapping;
723 pModule->mapping_size = mapping_size;
725 pData = (BYTE *)(pModule + 1);
727 /* Clear internal Wine flags in case they are set in the EXE file */
729 pModule->ne_flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
731 /* Get the segment table */
733 pModule->ne_segtab = pData - (BYTE *)pModule;
734 if (!(pSeg = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_segtab,
735 ne_header->ne_cseg * sizeof(struct ne_segment_table_entry_s) )))
737 for (i = ne_header->ne_cseg; i > 0; i--, pSeg++)
739 memcpy( pData, pSeg, sizeof(*pSeg) );
740 pData += sizeof(SEGTABLEENTRY);
743 /* Get the resource table */
745 if (ne_header->ne_rsrctab < ne_header->ne_restab)
747 pModule->ne_rsrctab = pData - (BYTE *)pModule;
748 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_rsrctab,
749 ne_header->ne_restab - ne_header->ne_rsrctab )) goto failed;
750 pData += ne_header->ne_restab - ne_header->ne_rsrctab;
752 else pModule->ne_rsrctab = 0; /* No resource table */
754 /* Get the resident names table */
756 pModule->ne_restab = pData - (BYTE *)pModule;
757 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_restab,
758 ne_header->ne_modtab - ne_header->ne_restab )) goto failed;
759 pData += ne_header->ne_modtab - ne_header->ne_restab;
761 /* Get the module references table */
763 if (ne_header->ne_cmod > 0)
765 pModule->ne_modtab = pData - (BYTE *)pModule;
766 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_modtab,
767 ne_header->ne_cmod * sizeof(WORD) )) goto failed;
768 pData += ne_header->ne_cmod * sizeof(WORD);
770 else pModule->ne_modtab = 0; /* No module references */
772 /* Get the imported names table */
774 pModule->ne_imptab = pData - (BYTE *)pModule;
775 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_imptab,
776 ne_header->ne_enttab - ne_header->ne_imptab )) goto failed;
777 pData += ne_header->ne_enttab - ne_header->ne_imptab;
779 /* Load entry table, convert it to the optimized version used by Windows */
781 pModule->ne_enttab = pData - (BYTE *)pModule;
782 if (!(ptr = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_enttab,
783 ne_header->ne_cbenttab ))) goto failed;
784 end = build_bundle_data( pModule, pData, ptr );
786 pData += ne_header->ne_cbenttab + sizeof(ET_BUNDLE) +
787 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6);
791 FIXME( "not enough space for entry table for %s\n", debugstr_a(path) );
795 /* Store the filename information */
797 pModule->fileinfo = pData - (BYTE *)pModule;
798 ofs = (OFSTRUCT *)pData;
799 ofs->cBytes = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path);
801 strcpy( ofs->szPathName, path );
802 pData += ofs->cBytes + 1;
803 assert( (BYTE *)pModule + size <= pData );
805 /* Get the non-resident names table */
807 if (ne_header->ne_cbnrestab)
809 pModule->nrname_handle = GlobalAlloc16( 0, ne_header->ne_cbnrestab );
810 if (!pModule->nrname_handle) goto failed;
811 FarSetOwner16( pModule->nrname_handle, hModule );
812 buffer = GlobalLock16( pModule->nrname_handle );
813 if (!NE_READ_DATA( pModule, buffer, ne_header->ne_nrestab, ne_header->ne_cbnrestab ))
815 GlobalFree16( pModule->nrname_handle );
819 else pModule->nrname_handle = 0;
821 /* Allocate a segment for the implicitly-loaded DLLs */
823 if (pModule->ne_cmod)
825 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
826 (pModule->ne_cmod+1)*sizeof(HMODULE16) );
827 if (!pModule->dlls_to_init)
829 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
832 FarSetOwner16( pModule->dlls_to_init, hModule );
834 else pModule->dlls_to_init = 0;
836 NE_RegisterModule( pModule );
840 GlobalFree16( hModule );
841 return ERROR_BAD_FORMAT;
845 /***********************************************************************
848 * Load all DLLs implicitly linked to a module.
850 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
853 WORD *pModRef = (WORD *)((char *)pModule + pModule->ne_modtab);
854 WORD *pDLLs = GlobalLock16( pModule->dlls_to_init );
856 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
858 char buffer[260], *p;
859 BYTE *pstr = (BYTE *)pModule + pModule->ne_imptab + *pModRef;
860 memcpy( buffer, pstr + 1, *pstr );
861 *(buffer + *pstr) = 0; /* terminate it */
863 TRACE("Loading '%s'\n", buffer );
864 if (!(*pModRef = GetModuleHandle16( buffer )))
866 /* If the DLL is not loaded yet, load it and store */
867 /* its handle in the list of DLLs to initialize. */
870 /* Append .DLL to name if no extension present */
871 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
872 strcat( buffer, ".DLL" );
874 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
876 /* FIXME: cleanup what was done */
878 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
879 buffer, *((BYTE*)pModule + pModule->ne_restab),
880 (char *)pModule + pModule->ne_restab + 1, hDLL );
883 *pModRef = GetExePtr( hDLL );
886 else /* Increment the reference count of the DLL */
888 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
889 if (pOldDLL) pOldDLL->count++;
896 /**********************************************************************
899 * Load first instance of NE module from file.
901 * pModule must point to a module structure prepared by build_module.
902 * This routine must never be called twice on a module.
904 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
906 /* Allocate the segments for this module */
908 if (!NE_CreateAllSegments( pModule ))
909 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
911 /* Load the referenced DLLs */
913 if (!NE_LoadDLLs( pModule ))
914 return ERROR_FILE_NOT_FOUND; /* 2 */
916 /* Load the segments */
918 NE_LoadAllSegments( pModule );
920 /* Make sure the usage count is 1 on the first loading of */
921 /* the module, even if it contains circular DLL references */
925 return NE_GetInstance( pModule );
928 /**********************************************************************
931 * Load first instance of NE module. (Note: caller is responsible for
932 * ensuring the module isn't already loaded!)
934 * If the module turns out to be an executable module, only a
935 * handle to a module stub is returned; this needs to be initialized
936 * by calling NE_DoLoadModule later, in the context of the newly
939 * If lib_only is TRUE, however, the module is perforce treated
940 * like a DLL module, even if it is an executable module.
943 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
947 HINSTANCE16 hInstance;
952 MEMORY_BASIC_INFORMATION info;
955 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
956 return ERROR_FILE_NOT_FOUND;
958 mapping = CreateFileMappingW( DosFileHandleToWin32Handle(hFile), NULL, PAGE_WRITECOPY, 0, 0, NULL );
960 if (!mapping) return ERROR_BAD_FORMAT;
962 ptr = MapViewOfFile( mapping, FILE_MAP_COPY, 0, 0, 0 );
963 CloseHandle( mapping );
964 if (!ptr) return ERROR_BAD_FORMAT;
966 VirtualQuery( ptr, &info, sizeof(info) );
967 hModule = build_module( ptr, info.RegionSize, ofs.szPathName );
971 UnmapViewOfFile( ptr );
975 SNOOP16_RegisterDLL( hModule, ofs.szPathName );
976 NE_InitResourceHandler( hModule );
978 pModule = NE_GetPtr( hModule );
980 if ( !lib_only && !( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) )
983 hInstance = NE_DoLoadModule( pModule );
984 if ( hInstance < 32 )
987 NE_FreeModule( hModule, 0 );
994 /***********************************************************************
995 * NE_DoLoadBuiltinModule
997 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
999 static HMODULE16 NE_DoLoadBuiltinModule( const IMAGE_DOS_HEADER *mz_header, const char *file_name,
1004 HINSTANCE16 hInstance;
1005 OSVERSIONINFOW versionInfo;
1006 SIZE_T mapping_size = ~0UL; /* assume builtins don't contain invalid offsets... */
1008 hModule = build_module( mz_header, mapping_size, file_name );
1009 if (hModule < 32) return hModule;
1010 pModule = GlobalLock16( hModule );
1011 pModule->ne_flags |= NE_FFLAGS_BUILTIN;
1012 pModule->owner32 = owner32;
1014 /* fake the expected version the module should have according to the current Windows version */
1015 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1016 if (GetVersionExW( &versionInfo ))
1017 pModule->ne_expver = MAKEWORD( versionInfo.dwMinorVersion, versionInfo.dwMajorVersion );
1019 hInstance = NE_DoLoadModule( pModule );
1020 if (hInstance < 32) NE_FreeModule( hModule, 0 );
1022 NE_InitResourceHandler( hModule );
1024 if (pModule->ne_heap)
1026 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1;
1027 unsigned int size = pSeg->minsize + pModule->ne_heap;
1028 if (size > 0xfffe) size = 0xfffe;
1029 LocalInit16( GlobalHandleToSel16(pSeg->hSeg), pSeg->minsize, size );
1032 patch_code_segment( pModule );
1038 /**********************************************************************
1039 * MODULE_LoadModule16
1041 * Load a NE module in the order of the loadorder specification.
1042 * The caller is responsible that the module is not loaded already.
1045 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1047 HINSTANCE16 hinst = 2;
1051 const IMAGE_DOS_HEADER *descr = NULL;
1052 const char *file_name = NULL;
1053 char dllname[32], owner[20], *p;
1054 const char *basename, *main_module;
1055 int owner_exists = FALSE;
1057 /* strip path information */
1060 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
1061 if ((p = strrchr( basename, '\\' ))) basename = p + 1;
1062 if ((p = strrchr( basename, '/' ))) basename = p + 1;
1064 if (strlen(basename) < sizeof(dllname)-6)
1066 strcpy( dllname, basename );
1067 p = strrchr( dllname, '.' );
1068 if (!p) strcat( dllname, ".dll" );
1069 for (p = dllname; *p; p++) if (*p >= 'A' && *p <= 'Z') *p += 32;
1072 if ((mod32 = LoadLibraryA( dllname )))
1074 if (!(descr = (void *)GetProcAddress( mod32, "__wine_spec_dos_header" )))
1076 WARN( "loaded %s but does not contain a 16-bit module\n", debugstr_a(dllname) );
1077 FreeLibrary( mod32 );
1081 TRACE( "found %s with embedded 16-bit module\n", debugstr_a(dllname) );
1082 file_name = basename;
1084 /* if module has a 32-bit owner, match the load order of the owner */
1085 if ((main_module = (void *)GetProcAddress( mod32, "__wine_spec_main_module" )))
1088 HMODULE main_owner = LoadLibraryA( main_module );
1092 WARN( "couldn't load owner %s for 16-bit dll %s\n", main_module, dllname );
1093 FreeLibrary( mod32 );
1094 return ERROR_FILE_NOT_FOUND;
1096 /* check if module was loaded native */
1097 if (LdrFindEntryForAddress( main_owner, &ldr ) || !(ldr->Flags & LDR_WINE_INTERNAL))
1099 FreeLibrary( mod32 );
1102 FreeLibrary( main_owner );
1108 /* old-style 16-bit placeholders support, to be removed at some point */
1109 if (!mod32 && wine_dll_get_owner( dllname, owner, sizeof(owner), &owner_exists ) != -1)
1111 mod32 = LoadLibraryA( owner );
1114 if (!(descr = find_dll_descr( dllname, &file_name )))
1116 FreeLibrary( mod32 );
1122 /* it's probably disabled by the load order config */
1123 WARN( "couldn't load owner %s for 16-bit dll %s\n", owner, dllname );
1124 return ERROR_FILE_NOT_FOUND;
1127 /* loading the 32-bit library can have the side effect of loading the module */
1128 /* if so, simply incr the ref count and return the module */
1129 if (descr && (hModule = GetModuleHandle16( libname )))
1131 TRACE( "module %s already loaded by owner\n", libname );
1132 pModule = NE_GetPtr( hModule );
1133 if (pModule) pModule->count++;
1134 FreeLibrary( mod32 );
1141 TRACE("Trying built-in '%s'\n", libname);
1142 hinst = NE_DoLoadBuiltinModule( descr, file_name, mod32 );
1143 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : builtin\n", debugstr_a(file_name));
1147 TRACE("Trying native dll '%s'\n", libname);
1148 hinst = NE_LoadModule(libname, lib_only);
1149 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : native\n", debugstr_a(libname));
1150 if (hinst == ERROR_FILE_NOT_FOUND && owner_exists) hinst = 21; /* win32 module */
1153 if (hinst > 32 && !implicit)
1155 hModule = GetModuleHandle16(libname);
1158 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1160 return ERROR_INVALID_HANDLE;
1163 pModule = NE_GetPtr(hModule);
1166 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1168 return ERROR_INVALID_HANDLE;
1171 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1174 * Call initialization routines for all loaded DLLs. Note that
1175 * when we load implicitly linked DLLs this will be done by InitTask().
1177 if(pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1179 NE_InitializeDLLs(hModule);
1180 NE_DllProcessAttach(hModule);
1183 return hinst; /* The last error that occurred */
1187 /**********************************************************************
1190 * Create the thread for a 16-bit module.
1192 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1197 HINSTANCE16 instance = 0;
1199 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1202 /* Post event to start the task */
1203 PostEvent16( hTask );
1205 /* Wait until we get the instance handle */
1208 DirectedYield16( hTask );
1209 if (!IsTask16( hTask )) /* thread has died */
1212 WaitForSingleObject( hThread, INFINITE );
1213 GetExitCodeThread( hThread, &exit_code );
1214 CloseHandle( hThread );
1217 if (!(pTask = GlobalLock16( hTask ))) break;
1218 instance = pTask->hInstance;
1219 GlobalUnlock16( hTask );
1220 } while (!instance);
1222 CloseHandle( hThread );
1227 /**********************************************************************
1228 * LoadModule (KERNEL.45)
1230 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1232 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1233 LOADPARAMS16 *params;
1237 WORD cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
1239 if (name == NULL) return 0;
1241 TRACE("name %s, paramBlock %p\n", name, paramBlock);
1245 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1247 /* Special case: second instance of an already loaded NE module */
1249 if ( !( pModule = NE_GetPtr( hModule ) ) ) return ERROR_BAD_FORMAT;
1250 if ( pModule->module32 ) return (HINSTANCE16)21;
1252 /* Increment refcount */
1258 /* Main case: load first instance of NE module */
1260 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1263 if ( !(pModule = NE_GetPtr( hModule )) )
1264 return ERROR_BAD_FORMAT;
1267 /* If library module, we just retrieve the instance handle */
1269 if ( ( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1270 return NE_GetInstance( pModule );
1273 * At this point, we need to create a new process.
1275 * pModule points either to an already loaded module, whose refcount
1276 * has already been incremented (to avoid having the module vanish
1277 * in the meantime), or else to a stub module which contains only header
1280 params = paramBlock;
1281 if (params->showCmd)
1282 cmdShow = ((WORD *)MapSL( params->showCmd ))[1];
1283 cmdline = MapSL( params->cmdLine );
1284 return NE_CreateThread( pModule, cmdShow, cmdline );
1288 /**********************************************************************
1291 * Startup code for a new 16-bit task.
1293 DWORD NE_StartTask(void)
1295 TDB *pTask = TASK_GetCurrent();
1296 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1297 HINSTANCE16 hInstance, hPrevInstance;
1298 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1301 if ( pModule->count > 0 )
1303 /* Second instance of an already loaded NE module */
1304 /* Note that the refcount was already incremented by the parent */
1306 hPrevInstance = NE_GetInstance( pModule );
1308 if ( pModule->ne_autodata )
1309 if ( NE_CreateSegment( pModule, pModule->ne_autodata ) )
1310 NE_LoadSegment( pModule, pModule->ne_autodata );
1312 hInstance = NE_GetInstance( pModule );
1313 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->ne_autodata, hPrevInstance);
1318 /* Load first instance of NE module */
1320 pModule->ne_flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1322 hInstance = NE_DoLoadModule( pModule );
1326 if ( hInstance >= 32 )
1330 /* Enter instance handles into task struct */
1332 pTask->hInstance = hInstance;
1333 pTask->hPrevInstance = hPrevInstance;
1335 /* Use DGROUP for 16-bit stack */
1337 if (!(sp = OFFSETOF(pModule->ne_sssp)))
1338 sp = pSegTable[SELECTOROF(pModule->ne_sssp)-1].minsize + pModule->ne_stack;
1340 sp -= sizeof(STACK16FRAME);
1341 NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1343 /* Registers at initialization must be:
1345 * bx stack size in bytes
1346 * cx heap size in bytes
1347 * si previous app instance
1348 * di current app instance
1350 * es selector to the PSP
1351 * ds dgroup of the application
1353 * sp top of the stack
1355 memset( &context, 0, sizeof(context) );
1356 context.SegCs = GlobalHandleToSel16(pSegTable[SELECTOROF(pModule->ne_csip) - 1].hSeg);
1357 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1358 context.SegEs = pTask->hPDB;
1359 context.SegFs = wine_get_fs();
1360 context.SegGs = wine_get_gs();
1361 context.Eip = OFFSETOF(pModule->ne_csip);
1362 context.Ebx = pModule->ne_stack;
1363 context.Ecx = pModule->ne_heap;
1364 context.Edi = pTask->hInstance;
1365 context.Esi = pTask->hPrevInstance;
1367 /* Now call 16-bit entry point */
1369 TRACE("Starting main program: cs:ip=%04x:%04x ds=%04x ss:sp=%04x:%04x\n",
1370 context.SegCs, context.Eip, context.SegDs,
1371 SELECTOROF(NtCurrentTeb()->WOW32Reserved),
1372 OFFSETOF(NtCurrentTeb()->WOW32Reserved) );
1374 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1375 ExitThread( LOWORD(context.Eax) );
1377 return hInstance; /* error code */
1380 /***********************************************************************
1381 * LoadLibrary (KERNEL.95)
1382 * LoadLibrary16 (KERNEL32.35)
1384 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1386 return LoadModule16(libname, (LPVOID)-1 );
1390 /**********************************************************************
1393 * Call a DLL's WEP, allowing it to shut down.
1394 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1396 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1399 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1400 if (!WEP) return FALSE;
1407 args[0] = WEP_FREE_DLL;
1408 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1409 ret = LOWORD(dwRet);
1413 WARN("Page fault\n");
1422 /**********************************************************************
1425 * Implementation of FreeModule16().
1427 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1429 HMODULE16 *hPrevModule;
1434 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1435 hModule = pModule->self;
1437 TRACE("%04x count %d\n", hModule, pModule->count );
1439 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1440 else pModule->count = 0;
1442 if (call_wep && !(pModule->ne_flags & NE_FFLAGS_WIN32))
1444 /* Free the objects owned by the DLL module */
1445 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1447 if (pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1448 MODULE_CallWEP( hModule );
1450 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1453 TRACE_(loaddll)("Unloaded module %s : %s\n", debugstr_a(NE_MODULE_NAME(pModule)),
1454 (pModule->ne_flags & NE_FFLAGS_BUILTIN) ? "builtin" : "native");
1456 /* Clear magic number just in case */
1458 pModule->ne_magic = pModule->self = 0;
1459 if (pModule->owner32) FreeLibrary( pModule->owner32 );
1460 else if (pModule->mapping) UnmapViewOfFile( pModule->mapping );
1462 /* Remove it from the linked list */
1464 hPrevModule = &hFirstModule;
1465 while (*hPrevModule && (*hPrevModule != hModule))
1467 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1469 if (*hPrevModule) *hPrevModule = pModule->next;
1471 /* Free the referenced modules */
1473 pModRef = (HMODULE16*)((char *)pModule + pModule->ne_modtab);
1474 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
1476 NE_FreeModule( *pModRef, call_wep );
1479 /* Free the module storage */
1481 GlobalFreeAll16( hModule );
1486 /**********************************************************************
1487 * FreeModule (KERNEL.46)
1489 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1491 return NE_FreeModule( hModule, TRUE );
1495 /***********************************************************************
1496 * FreeLibrary (KERNEL.96)
1497 * FreeLibrary16 (KERNEL32.36)
1499 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1501 TRACE("%04x\n", handle );
1502 FreeModule16( handle );
1506 /***********************************************************************
1507 * GetModuleHandle16 (KERNEL32.@)
1509 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1511 HMODULE16 hModule = hFirstModule;
1513 BYTE len, *name_table;
1514 char tmpstr[MAX_PATH];
1517 TRACE("(%s)\n", name);
1519 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1524 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1526 /* If 'name' matches exactly the module name of a module:
1527 * Return its handle.
1529 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1531 pModule = NE_GetPtr( hModule );
1532 if (!pModule) break;
1533 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1535 name_table = (BYTE *)pModule + pModule->ne_restab;
1536 if ((*name_table == len) && !strncmp(name, (char*) name_table+1, len))
1540 /* If uppercased 'name' matches exactly the module name of a module:
1543 for (s = tmpstr; *s; s++) *s = RtlUpperChar(*s);
1545 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1547 pModule = NE_GetPtr( hModule );
1548 if (!pModule) break;
1549 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1551 name_table = (BYTE *)pModule + pModule->ne_restab;
1552 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1553 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1554 * lowercased module names, but try to load uppercase DLLs, so this
1555 * 'i' compare is just a quickfix until the loader handles that
1556 * correctly. -MM 990705
1558 if ((*name_table == len) && !NE_strncasecmp(tmpstr, (const char*)name_table+1, len))
1562 /* If the base filename of 'name' matches the base filename of the module
1563 * filename of some module (case-insensitive compare):
1564 * Return its handle.
1567 /* basename: search backwards in passed name to \ / or : */
1568 s = tmpstr + strlen(tmpstr);
1571 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1576 /* search this in loaded filename list */
1577 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1582 pModule = NE_GetPtr( hModule );
1583 if (!pModule) break;
1584 if (!pModule->fileinfo) continue;
1585 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1587 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1588 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1589 /* basename: search backwards in pathname to \ / or : */
1590 while (loadedfn > (char*)ofs->szPathName)
1592 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1596 /* case insensitive compare ... */
1597 if (!NE_strcasecmp(loadedfn, s))
1604 /**********************************************************************
1605 * GetModuleName (KERNEL.27)
1607 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1612 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1613 p = (BYTE *)pModule + pModule->ne_restab;
1614 if (count > *p) count = *p + 1;
1617 memcpy( buf, p + 1, count - 1 );
1618 buf[count-1] = '\0';
1624 /**********************************************************************
1625 * GetModuleFileName (KERNEL.49)
1627 * Comment: see GetModuleFileNameA
1629 * Even if invoked by second instance of a program,
1630 * it still returns path of first one.
1632 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1637 /* Win95 does not query hModule if set to 0 !
1638 * Is this wrong or maybe Win3.1 only ? */
1639 if (!hModule) hModule = GetCurrentTask();
1641 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1642 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1643 if (pModule->ne_expver < 0x400)
1644 GetShortPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1645 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1646 return strlen(lpFileName);
1650 /**********************************************************************
1651 * GetModuleUsage (KERNEL.48)
1653 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1655 NE_MODULE *pModule = NE_GetPtr( hModule );
1656 return pModule ? pModule->count : 0;
1660 /**********************************************************************
1661 * GetExpWinVer (KERNEL.167)
1663 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1665 NE_MODULE *pModule = NE_GetPtr( hModule );
1666 if ( !pModule ) return 0;
1667 return pModule->ne_expver;
1671 /***********************************************************************
1672 * WinExec (KERNEL.166)
1674 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1676 LPCSTR p, args = NULL;
1677 LPCSTR name_beg, name_end;
1678 LPSTR name, cmdline;
1681 char buffer[MAX_PATH];
1682 LOADPARAMS16 params;
1685 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1687 name_beg = lpCmdLine+1;
1688 p = strchr ( lpCmdLine+1, '"' );
1692 args = strchr ( p, ' ' );
1694 else /* yes, even valid with trailing '"' missing */
1695 name_end = lpCmdLine+strlen(lpCmdLine);
1699 name_beg = lpCmdLine;
1700 args = strchr( lpCmdLine, ' ' );
1701 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1704 if ((name_beg == lpCmdLine) && (!args))
1705 { /* just use the original cmdline string as file name */
1706 name = (LPSTR)lpCmdLine;
1710 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1711 return ERROR_NOT_ENOUGH_MEMORY;
1712 memcpy( name, name_beg, name_end - name_beg );
1713 name[name_end - name_beg] = '\0';
1719 arglen = strlen(args);
1720 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1721 cmdline[0] = (BYTE)arglen;
1722 strcpy( cmdline + 1, args );
1726 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1727 cmdline[0] = cmdline[1] = 0;
1730 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1733 showCmd[1] = nCmdShow;
1735 params.hEnvironment = 0;
1736 params.cmdLine = MapLS( cmdline );
1737 params.showCmd = MapLS( showCmd );
1738 params.reserved = 0;
1740 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1742 ret = LoadModule16( buffer, ¶ms );
1744 else if (!contains_path( name )) /* try 16-bit builtin */
1746 lstrcpynA( buffer, name, sizeof(buffer) );
1747 if (strlen( buffer ) < sizeof(buffer) - 4 && !strchr( buffer, '.' )) strcat( buffer, ".exe" );
1748 ret = LoadModule16( buffer, ¶ms );
1749 if (ret == ERROR_FILE_NOT_FOUND) ret = 21; /* it might be a 32-bit builtin too */
1751 else ret = ERROR_FILE_NOT_FOUND;
1753 UnMapLS( params.cmdLine );
1754 UnMapLS( params.showCmd );
1756 HeapFree( GetProcessHeap(), 0, cmdline );
1757 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1759 if (ret == 21 || ret == ERROR_BAD_FORMAT) /* 32-bit module or unknown executable*/
1761 LOADPARAMS16 params;
1764 showCmd[1] = nCmdShow;
1766 arglen = strlen( lpCmdLine );
1767 cmdline = HeapAlloc( GetProcessHeap(), 0, arglen + 1 );
1768 cmdline[0] = (BYTE)arglen;
1769 memcpy( cmdline + 1, lpCmdLine, arglen );
1771 params.hEnvironment = 0;
1772 params.cmdLine = MapLS( cmdline );
1773 params.showCmd = MapLS( showCmd );
1774 params.reserved = 0;
1776 ret = LoadModule16( "winoldap.mod", ¶ms );
1777 UnMapLS( params.cmdLine );
1778 UnMapLS( params.showCmd );
1783 /***********************************************************************
1784 * GetProcAddress (KERNEL.50)
1786 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1791 if (!hModule) hModule = GetCurrentTask();
1792 hModule = GetExePtr( hModule );
1794 if (HIWORD(name) != 0)
1796 ordinal = NE_GetOrdinal( hModule, name );
1797 TRACE("%04x '%s'\n", hModule, name );
1801 ordinal = LOWORD(name);
1802 TRACE("%04x %04x\n", hModule, ordinal );
1804 if (!ordinal) return NULL;
1806 ret = NE_GetEntryPoint( hModule, ordinal );
1808 TRACE("returning %p\n", ret );
1813 /***************************************************************************
1814 * HasGPHandler (KERNEL.338)
1816 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1821 GPHANDLERDEF *gpHandler;
1823 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1824 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1825 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1826 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1827 && (gpHandler = MapSL( gpPtr )) != NULL )
1829 while (gpHandler->selector)
1831 if ( SELECTOROF(address) == gpHandler->selector
1832 && OFFSETOF(address) >= gpHandler->rangeStart
1833 && OFFSETOF(address) < gpHandler->rangeEnd )
1834 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1843 /**********************************************************************
1844 * GetModuleHandle (KERNEL.47)
1846 * Find a module from a module name.
1848 * NOTE: The current implementation works the same way the Windows 95 one
1849 * does. Do not try to 'fix' it, fix the callers.
1850 * + It does not do ANY extension handling (except that strange .EXE bit)!
1851 * + It does not care about paths, just about basenames. (same as Windows)
1855 * the win16 module handle if found
1857 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1858 * Always hFirstModule
1860 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1862 if (HIWORD(name) == 0)
1863 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1864 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1867 /**********************************************************************
1868 * NE_GetModuleByFilename
1870 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1874 BYTE len, *name_table;
1875 char tmpstr[MAX_PATH];
1878 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1880 /* If the base filename of 'name' matches the base filename of the module
1881 * filename of some module (case-insensitive compare):
1882 * Return its handle.
1885 /* basename: search backwards in passed name to \ / or : */
1886 s = tmpstr + strlen(tmpstr);
1889 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1894 /* search this in loaded filename list */
1895 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1900 pModule = NE_GetPtr( hModule );
1901 if (!pModule) break;
1902 if (!pModule->fileinfo) continue;
1903 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1905 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1906 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1907 /* basename: search backwards in pathname to \ / or : */
1908 while (loadedfn > (char*)ofs->szPathName)
1910 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1914 /* case insensitive compare ... */
1915 if (!NE_strcasecmp(loadedfn, s))
1918 /* If basename (without ext) matches the module name of a module:
1919 * Return its handle.
1922 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1925 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1927 pModule = NE_GetPtr( hModule );
1928 if (!pModule) break;
1929 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1931 name_table = (BYTE *)pModule + pModule->ne_restab;
1932 if ((*name_table == len) && !NE_strncasecmp(s, (const char*)name_table+1, len))
1939 /***********************************************************************
1940 * GetProcAddress16 (KERNEL32.37)
1941 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1943 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1945 if (!hModule) return 0;
1946 if (HIWORD(hModule))
1948 WARN("hModule is Win32 handle (%p)\n", hModule );
1951 return GetProcAddress16( LOWORD(hModule), name );
1954 /***************************************************************************
1955 * IsRomModule (KERNEL.323)
1957 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1962 /***************************************************************************
1963 * IsRomFile (KERNEL.326)
1965 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1970 /***********************************************************************
1971 * create_dummy_module
1973 * Create a dummy NE module for Win32 or Winelib.
1975 static HMODULE16 create_dummy_module( HMODULE module32 )
1979 SEGTABLEENTRY *pSegment;
1982 const char* basename;
1985 char filename[MAX_PATH];
1986 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
1988 if (!nt) return ERROR_BAD_FORMAT;
1990 /* Extract base filename */
1991 len = GetModuleFileNameA( module32, filename, sizeof(filename) );
1992 if (!len || len >= sizeof(filename)) return ERROR_BAD_FORMAT;
1993 basename = strrchr(filename, '\\');
1994 if (!basename) basename = filename;
1996 len = strlen(basename);
1997 if ((s = strchr(basename, '.'))) len = s - basename;
1999 /* Allocate module */
2000 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
2001 + strlen(filename) + 1;
2002 size = sizeof(NE_MODULE) +
2003 /* loaded file info */
2004 ((of_size + 3) & ~3) +
2005 /* segment table: DS,CS */
2006 2 * sizeof(SEGTABLEENTRY) +
2009 /* several empty tables */
2012 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2013 if (!hModule) return ERROR_BAD_FORMAT;
2015 FarSetOwner16( hModule, hModule );
2016 pModule = GlobalLock16( hModule );
2018 /* Set all used entries */
2019 pModule->ne_magic = IMAGE_OS2_SIGNATURE;
2022 pModule->ne_flags = NE_FFLAGS_WIN32;
2023 pModule->ne_autodata = 0;
2024 pModule->ne_sssp = MAKESEGPTR( 0, 1 );
2025 pModule->ne_csip = MAKESEGPTR( 0, 2 );
2026 pModule->ne_heap = 0;
2027 pModule->ne_stack = 0;
2028 pModule->ne_cseg = 2;
2029 pModule->ne_cmod = 0;
2030 pModule->ne_cbnrestab = 0;
2031 pModule->fileinfo = sizeof(NE_MODULE);
2032 pModule->ne_exetyp = NE_OSFLAGS_WINDOWS;
2033 pModule->self = hModule;
2034 pModule->module32 = module32;
2036 /* Set version and flags */
2037 pModule->ne_expver = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2038 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2039 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2040 pModule->ne_flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2042 /* Set loaded file information */
2043 ofs = (OFSTRUCT *)(pModule + 1);
2044 memset( ofs, 0, of_size );
2045 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
2046 strcpy( ofs->szPathName, filename );
2048 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2049 pModule->ne_segtab = (char *)pSegment - (char *)pModule;
2052 pSegment->flags = NE_SEGFLAGS_DATA;
2053 pSegment->minsize = 0x1000;
2056 pSegment->flags = 0;
2060 pStr = (char *)pSegment;
2061 pModule->ne_restab = pStr - (char *)pModule;
2064 lstrcpynA( pStr+1, basename, len+1 );
2067 /* All tables zero terminated */
2068 pModule->ne_rsrctab = pModule->ne_imptab = pModule->ne_enttab = pStr - (char *)pModule;
2070 NE_RegisterModule( pModule );
2071 pModule->owner32 = LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
2075 /***********************************************************************
2076 * PrivateLoadLibrary (KERNEL32.@)
2078 * FIXME: rough guesswork, don't know what "Private" means
2080 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2082 return LoadLibrary16(libname);
2085 /***********************************************************************
2086 * PrivateFreeLibrary (KERNEL32.@)
2088 * FIXME: rough guesswork, don't know what "Private" means
2090 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2092 FreeLibrary16(handle);
2095 /***********************************************************************
2096 * LoadLibrary32 (KERNEL.452)
2097 * LoadSystemLibrary32 (KERNEL.482)
2099 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2104 ReleaseThunkLock( &count );
2105 hModule = LoadLibraryA( libname );
2106 RestoreThunkLock( count );
2110 /***************************************************************************
2111 * MapHModuleLS (KERNEL32.@)
2113 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2119 return TASK_GetCurrent()->hInstance;
2121 return LOWORD(hmod); /* we already have a 16 bit module handle */
2122 pModule = GlobalLock16(hFirstModule);
2124 if (pModule->module32 == hmod)
2125 return pModule->self;
2126 pModule = GlobalLock16(pModule->next);
2128 if ((ret = create_dummy_module( hmod )) < 32)
2136 /***************************************************************************
2137 * MapHModuleSL (KERNEL32.@)
2139 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2144 TDB *pTask = TASK_GetCurrent();
2145 hmod = pTask->hModule;
2147 pModule = GlobalLock16(hmod);
2148 if ((pModule->ne_magic != IMAGE_OS2_SIGNATURE) || !(pModule->ne_flags & NE_FFLAGS_WIN32))
2150 return pModule->module32;
2153 /***************************************************************************
2154 * MapHInstLS (KERNEL.472)
2156 void WINAPI MapHInstLS16( CONTEXT86 *context )
2158 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2161 /***************************************************************************
2162 * MapHInstSL (KERNEL.473)
2164 void WINAPI MapHInstSL16( CONTEXT86 *context )
2166 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2169 /***************************************************************************
2170 * MapHInstLS (KERNEL32.@)
2172 __ASM_STDCALL_FUNC( MapHInstLS, 0,
2174 "call " __ASM_NAME("MapHModuleLS") __ASM_STDCALL(4) "\n\t"
2177 /***************************************************************************
2178 * MapHInstSL (KERNEL32.@)
2180 __ASM_STDCALL_FUNC( MapHInstSL, 0,
2182 "call " __ASM_NAME("MapHModuleSL") __ASM_STDCALL(4) "\n\t"
2185 /***************************************************************************
2186 * MapHInstLS_PN (KERNEL32.@)
2188 __ASM_STDCALL_FUNC( MapHInstLS_PN, 0,
2189 "testl %eax,%eax\n\t"
2192 "call " __ASM_NAME("MapHModuleLS") __ASM_STDCALL(4) "\n"
2195 /***************************************************************************
2196 * MapHInstSL_PN (KERNEL32.@)
2198 __ASM_STDCALL_FUNC( MapHInstSL_PN, 0,
2199 "andl $0xffff,%eax\n\t"
2202 "call " __ASM_NAME("MapHModuleSL") __ASM_STDCALL(4) "\n"