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"
36 #include "wine/winbase16.h"
41 #include "kernel_private.h"
42 #include "kernel16_private.h"
43 #include "wine/exception.h"
44 #include "wine/debug.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
47 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
48 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 typedef struct _GPHANDLERDEF
63 struct ne_segment_table_entry_s
65 WORD seg_data_offset; /* Sector offset of segment data */
66 WORD seg_data_length; /* Length of segment data */
67 WORD seg_flags; /* Flags associated with this segment */
68 WORD min_alloc; /* Minimum allocation size for this */
71 #define hFirstModule (pThhook->hExeHead)
75 const IMAGE_DOS_HEADER *header; /* module headers */
76 const char *file_name; /* module file name */
79 /* Table of all built-in DLLs */
83 static struct builtin_dll builtin_dlls[MAX_DLLS];
85 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
86 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
88 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
90 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
93 static WINE_EXCEPTION_FILTER(page_fault)
95 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
96 GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
97 return EXCEPTION_EXECUTE_HANDLER;
98 return EXCEPTION_CONTINUE_SEARCH;
102 /* patch all the flat cs references of the code segment if necessary */
103 inline static void patch_code_segment( NE_MODULE *pModule )
108 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule );
110 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
111 if (!(pSeg->flags & NE_SEGFLAGS_DATA)) break; /* found the code segment */
113 call = GlobalLock16( pSeg->hSeg );
115 /* patch glue code address and code selector */
116 for (i = 0; call[i].pushl == 0x68; i++)
118 if (call[i].ret[0] == 0xca66 || call[i].ret[0] == 0xcb66) /* register entry point? */
119 call[i].glue = __wine_call_from_16_regs;
121 call[i].glue = __wine_call_from_16;
122 call[i].flatcs = wine_get_cs();
125 if (TRACE_ON(relay)) /* patch relay functions to all point to relay_call_from_16 */
126 for (i = 0; call[i].pushl == 0x68; i++) call[i].relay = relay_call_from_16;
131 /***********************************************************************
134 * locale-independent case conversion for module lookups
136 static int NE_strcasecmp( const char *str1, const char *str2 )
139 for ( ; ; str1++, str2++)
140 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
145 /***********************************************************************
148 * locale-independent case conversion for module lookups
150 static int NE_strncasecmp( const char *str1, const char *str2, int len )
153 for ( ; len > 0; len--, str1++, str2++)
154 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
159 /***********************************************************************
162 * Find a descriptor in the list
164 static const IMAGE_DOS_HEADER *find_dll_descr( const char *dllname, const char **file_name )
167 const IMAGE_DOS_HEADER *mz_header;
168 const IMAGE_OS2_HEADER *ne_header;
171 for (i = 0; i < MAX_DLLS; i++)
173 mz_header = builtin_dlls[i].header;
176 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mz_header + mz_header->e_lfanew);
177 name_table = (BYTE *)ne_header + ne_header->ne_restab;
179 /* check the dll file name */
180 if (!NE_strcasecmp( builtin_dlls[i].file_name, dllname ) ||
181 /* check the dll module name (without extension) */
182 (!NE_strncasecmp( dllname, (const char*)name_table+1, *name_table ) &&
183 !strcmp( dllname + *name_table, ".dll" )))
185 *file_name = builtin_dlls[i].file_name;
186 return builtin_dlls[i].header;
194 /***********************************************************************
195 * __wine_dll_register_16 (KERNEL32.@)
197 * Register a built-in DLL descriptor.
199 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
203 for (i = 0; i < MAX_DLLS; i++)
205 if (builtin_dlls[i].header) continue;
206 builtin_dlls[i].header = header;
207 builtin_dlls[i].file_name = file_name;
210 assert( i < MAX_DLLS );
214 /***********************************************************************
215 * __wine_dll_unregister_16 (KERNEL32.@)
217 * Unregister a built-in DLL descriptor.
219 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
223 for (i = 0; i < MAX_DLLS; i++)
225 if (builtin_dlls[i].header != header) continue;
226 builtin_dlls[i].header = NULL;
232 /***********************************************************************
235 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
237 return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
241 /**********************************************************************
244 static void NE_RegisterModule( NE_MODULE *pModule )
246 pModule->next = hFirstModule;
247 hFirstModule = pModule->self;
251 /***********************************************************************
254 void NE_DumpModule( HMODULE16 hModule )
264 if (!(pModule = NE_GetPtr( hModule )))
266 ERR( "**** %04x is not a module handle\n", hModule );
270 /* Dump the module info */
272 TRACE( "Module %04x:\n", hModule );
273 TRACE( "count=%d flags=%04x heap=%d stack=%d\n",
274 pModule->count, pModule->ne_flags,
275 pModule->ne_heap, pModule->ne_stack );
276 TRACE( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
277 SELECTOROF(pModule->ne_csip), OFFSETOF(pModule->ne_csip),
278 SELECTOROF(pModule->ne_sssp), OFFSETOF(pModule->ne_sssp),
279 pModule->ne_autodata, pModule->ne_cseg, pModule->ne_cmod );
280 TRACE( "os_flags=%d swap_area=%d version=%04x\n",
281 pModule->ne_exetyp, pModule->ne_swaparea, pModule->ne_expver );
282 if (pModule->ne_flags & NE_FFLAGS_WIN32)
283 TRACE( "PE module=%p\n", pModule->module32 );
285 /* Dump the file info */
287 TRACE( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
289 /* Dump the segment table */
291 TRACE( "Segment table:\n" );
292 pSeg = NE_SEG_TABLE( pModule );
293 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
294 TRACE( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
295 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
296 pSeg->minsize, pSeg->hSeg );
298 /* Dump the resource table */
300 TRACE( "Resource table:\n" );
301 if (pModule->ne_rsrctab)
303 pword = (WORD *)((BYTE *)pModule + pModule->ne_rsrctab);
304 TRACE( "Alignment: %d\n", *pword++ );
307 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
308 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
309 TRACE( "id=%04x count=%d\n", ptr->type_id, ptr->count );
310 for (i = 0; i < ptr->count; i++, pname++)
311 TRACE( "offset=%d len=%d id=%04x\n",
312 pname->offset, pname->length, pname->id );
313 pword = (WORD *)pname;
316 else TRACE( "None\n" );
318 /* Dump the resident name table */
320 TRACE( "Resident-name table:\n" );
321 pstr = (BYTE*) pModule + pModule->ne_restab;
324 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
325 *(WORD *)(pstr + *pstr + 1) );
326 pstr += *pstr + 1 + sizeof(WORD);
329 /* Dump the module reference table */
331 TRACE( "Module ref table:\n" );
332 if (pModule->ne_modtab)
334 pword = (WORD *)((BYTE *)pModule + pModule->ne_modtab);
335 for (i = 0; i < pModule->ne_cmod; i++, pword++)
338 GetModuleName16( *pword, name, sizeof(name) );
339 TRACE( "%d: %04x -> '%s'\n", i, *pword, name );
342 else TRACE( "None\n" );
344 /* Dump the entry table */
346 TRACE( "Entry table:\n" );
347 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->ne_enttab);
349 entry = (ET_ENTRY *)((BYTE *)bundle+6);
350 TRACE( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
351 ordinal = bundle->first;
352 while (ordinal < bundle->last)
354 if (entry->type == 0xff)
355 TRACE("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
357 TRACE("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
360 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
362 /* Dump the non-resident names table */
364 TRACE( "Non-resident names table:\n" );
365 if (pModule->nrname_handle)
367 pstr = GlobalLock16( pModule->nrname_handle );
370 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
371 *(WORD *)(pstr + *pstr + 1) );
372 pstr += *pstr + 1 + sizeof(WORD);
379 /***********************************************************************
382 * Walk the module list and print the modules.
384 void NE_WalkModules(void)
386 HMODULE16 hModule = hFirstModule;
387 MESSAGE( "Module Flags Name\n" );
390 NE_MODULE *pModule = NE_GetPtr( hModule );
393 MESSAGE( "Bad module %04x in list\n", hModule );
396 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->ne_flags,
397 *((char *)pModule + pModule->ne_restab),
398 (char *)pModule + pModule->ne_restab + 1 );
399 hModule = pModule->next;
404 /***********************************************************************
405 * NE_InitResourceHandler
407 * Fill in 'resloader' fields in the resource table.
409 static void NE_InitResourceHandler( HMODULE16 hModule )
411 static FARPROC16 proc;
413 NE_TYPEINFO *pTypeInfo;
416 if (!(pModule = NE_GetPtr( hModule )) || !pModule->ne_rsrctab) return;
418 TRACE("InitResourceHandler[%04x]\n", hModule );
420 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
422 pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->ne_rsrctab + 2);
423 while(pTypeInfo->type_id)
425 memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
426 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
431 /***********************************************************************
434 * Lookup the ordinal for a given name.
436 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
438 char buffer[256], *p;
443 if (!(pModule = NE_GetPtr( hModule ))) return 0;
444 if (pModule->ne_flags & NE_FFLAGS_WIN32) return 0;
446 TRACE("(%04x,'%s')\n", hModule, name );
448 /* First handle names of the form '#xxxx' */
450 if (name[0] == '#') return atoi( name + 1 );
452 /* Now copy and uppercase the string */
454 strcpy( buffer, name );
455 for (p = buffer; *p; p++) *p = RtlUpperChar(*p);
458 /* First search the resident names */
460 cpnt = (BYTE *)pModule + pModule->ne_restab;
462 /* Skip the first entry (module name) */
463 cpnt += *cpnt + 1 + sizeof(WORD);
466 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
469 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
470 TRACE(" Found: ordinal=%d\n", ordinal );
473 cpnt += *cpnt + 1 + sizeof(WORD);
476 /* Now search the non-resident names table */
478 if (!pModule->nrname_handle) return 0; /* No non-resident table */
479 cpnt = GlobalLock16( pModule->nrname_handle );
481 /* Skip the first entry (module description string) */
482 cpnt += *cpnt + 1 + sizeof(WORD);
485 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
488 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
489 TRACE(" Found: ordinal=%d\n", ordinal );
492 cpnt += *cpnt + 1 + sizeof(WORD);
498 /***********************************************************************
501 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
503 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
506 /***********************************************************************
509 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
517 if (!(pModule = NE_GetPtr( hModule ))) return 0;
518 assert( !(pModule->ne_flags & NE_FFLAGS_WIN32) );
520 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
521 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
525 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
528 entry = (ET_ENTRY *)((BYTE *)bundle+6);
529 for (i=0; i < (ordinal - bundle->first - 1); i++)
533 memcpy( &offset, &entry->offs, sizeof(WORD) );
535 if (sel == 0xfe) sel = 0xffff; /* constant entry */
536 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
538 return (FARPROC16)MAKESEGPTR( sel, offset );
540 return (FARPROC16)MAKESEGPTR( sel, offset );
542 return (FARPROC16)SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
546 /***********************************************************************
547 * EntryAddrProc (KERNEL.667) Wine-specific export
549 * Return the entry point for a given ordinal.
551 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
553 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
554 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
558 /***********************************************************************
561 * Change the value of an entry point. Use with caution!
562 * It can only change the offset value, not the selector.
564 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
571 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
572 assert( !(pModule->ne_flags & NE_FFLAGS_WIN32) );
574 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
575 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
577 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
578 if (!(bundle->next)) return 0;
581 entry = (ET_ENTRY *)((BYTE *)bundle+6);
582 for (i=0; i < (ordinal - bundle->first - 1); i++)
585 memcpy( &entry->offs, &offset, sizeof(WORD) );
590 /***********************************************************************
593 * Build the entry table bundle data from the on-disk format. Helper for build_module.
595 static void *build_bundle_data( NE_MODULE *pModule, void *dest, const BYTE *table )
597 ET_BUNDLE *oldbundle, *bundle = dest;
599 BYTE nr_entries, type;
601 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
602 entry = (ET_ENTRY *)((BYTE *)bundle+6);
604 while ((nr_entries = *table++))
606 if ((type = *table++))
608 bundle->last += nr_entries;
614 entry->flags = *table++;
615 table += sizeof(WORD);
616 entry->segnum = *table++;
617 entry->offs = *(WORD *)table;
618 table += sizeof(WORD);
627 entry->flags = *table++;
628 entry->segnum = type;
629 entry->offs = *(WORD *)table;
630 table += sizeof(WORD);
637 if (bundle->first == bundle->last)
639 bundle->first += nr_entries;
640 bundle->last += nr_entries;
645 oldbundle->next = (char *)entry - (char *)pModule;
646 bundle = (ET_BUNDLE *)entry;
647 bundle->first = bundle->last = oldbundle->last + nr_entries;
649 entry = (ET_ENTRY*)(((BYTE*)entry)+sizeof(ET_BUNDLE));
657 /***********************************************************************
660 * Build the in-memory module from the on-disk data.
662 static HMODULE16 build_module( const void *mapping, SIZE_T mapping_size, LPCSTR path )
664 const IMAGE_DOS_HEADER *mz_header = mapping;
665 const IMAGE_OS2_HEADER *ne_header;
666 const struct ne_segment_table_entry_s *pSeg;
672 BYTE *buffer, *pData, *end;
675 if (mapping_size < sizeof(*mz_header)) return ERROR_BAD_FORMAT;
676 if (mz_header->e_magic != IMAGE_DOS_SIGNATURE) return ERROR_BAD_FORMAT;
677 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mapping + mz_header->e_lfanew);
678 if (mz_header->e_lfanew + sizeof(*ne_header) > mapping_size) return ERROR_BAD_FORMAT;
679 if (ne_header->ne_magic == IMAGE_NT_SIGNATURE) return 21; /* win32 exe */
680 if (ne_header->ne_magic == IMAGE_OS2_SIGNATURE_LX)
682 MESSAGE("Sorry, %s is an OS/2 linear executable (LX) file!\n", path);
685 if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE) return ERROR_BAD_FORMAT;
687 /* We now have a valid NE header */
689 /* check to be able to fall back to loading OS/2 programs as DOS
690 * FIXME: should this check be reversed in order to be less strict?
691 * (only fail for OS/2 ne_exetyp 0x01 here?) */
692 if ((ne_header->ne_exetyp != 0x02 /* Windows */)
693 && (ne_header->ne_exetyp != 0x04) /* Windows 386 */)
694 return ERROR_BAD_FORMAT;
696 size = sizeof(NE_MODULE) +
698 ne_header->ne_cseg * sizeof(SEGTABLEENTRY) +
700 ne_header->ne_restab - ne_header->ne_rsrctab +
701 /* resident names table */
702 ne_header->ne_modtab - ne_header->ne_restab +
703 /* module ref table */
704 ne_header->ne_cmod * sizeof(WORD) +
705 /* imported names table */
706 ne_header->ne_enttab - ne_header->ne_imptab +
707 /* entry table length */
708 ne_header->ne_cbenttab +
709 /* entry table extra conversion space */
711 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6) +
712 /* loaded file info */
713 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
715 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
716 if (!hModule) return ERROR_BAD_FORMAT;
718 FarSetOwner16( hModule, hModule );
719 pModule = (NE_MODULE *)GlobalLock16( hModule );
720 memcpy( pModule, ne_header, sizeof(*ne_header) );
722 /* check programs for default minimal stack size */
723 if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE) && (pModule->ne_stack < 0x1400))
724 pModule->ne_stack = 0x1400;
726 pModule->self = hModule;
727 pModule->mapping = mapping;
728 pModule->mapping_size = mapping_size;
730 pData = (BYTE *)(pModule + 1);
732 /* Clear internal Wine flags in case they are set in the EXE file */
734 pModule->ne_flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
736 /* Get the segment table */
738 pModule->ne_segtab = pData - (BYTE *)pModule;
739 if (!(pSeg = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_segtab,
740 ne_header->ne_cseg * sizeof(struct ne_segment_table_entry_s) )))
742 for (i = ne_header->ne_cseg; i > 0; i--, pSeg++)
744 memcpy( pData, pSeg, sizeof(*pSeg) );
745 pData += sizeof(SEGTABLEENTRY);
748 /* Get the resource table */
750 if (ne_header->ne_rsrctab < ne_header->ne_restab)
752 pModule->ne_rsrctab = pData - (BYTE *)pModule;
753 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_rsrctab,
754 ne_header->ne_restab - ne_header->ne_rsrctab )) goto failed;
755 pData += ne_header->ne_restab - ne_header->ne_rsrctab;
757 else pModule->ne_rsrctab = 0; /* No resource table */
759 /* Get the resident names table */
761 pModule->ne_restab = pData - (BYTE *)pModule;
762 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_restab,
763 ne_header->ne_modtab - ne_header->ne_restab )) goto failed;
764 pData += ne_header->ne_modtab - ne_header->ne_restab;
766 /* Get the module references table */
768 if (ne_header->ne_cmod > 0)
770 pModule->ne_modtab = pData - (BYTE *)pModule;
771 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_modtab,
772 ne_header->ne_cmod * sizeof(WORD) )) goto failed;
773 pData += ne_header->ne_cmod * sizeof(WORD);
775 else pModule->ne_modtab = 0; /* No module references */
777 /* Get the imported names table */
779 pModule->ne_imptab = pData - (BYTE *)pModule;
780 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_imptab,
781 ne_header->ne_enttab - ne_header->ne_imptab )) goto failed;
782 pData += ne_header->ne_enttab - ne_header->ne_imptab;
784 /* Load entry table, convert it to the optimized version used by Windows */
786 pModule->ne_enttab = pData - (BYTE *)pModule;
787 if (!(ptr = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_enttab,
788 ne_header->ne_cbenttab ))) goto failed;
789 end = build_bundle_data( pModule, pData, ptr );
791 pData += ne_header->ne_cbenttab + sizeof(ET_BUNDLE) +
792 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6);
796 FIXME( "not enough space for entry table for %s\n", debugstr_a(path) );
800 /* Store the filename information */
802 pModule->fileinfo = pData - (BYTE *)pModule;
803 ofs = (OFSTRUCT *)pData;
804 ofs->cBytes = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path);
806 strcpy( ofs->szPathName, path );
807 pData += ofs->cBytes + 1;
808 assert( (BYTE *)pModule + size <= pData );
810 /* Get the non-resident names table */
812 if (ne_header->ne_cbnrestab)
814 pModule->nrname_handle = GlobalAlloc16( 0, ne_header->ne_cbnrestab );
815 if (!pModule->nrname_handle) goto failed;
816 FarSetOwner16( pModule->nrname_handle, hModule );
817 buffer = GlobalLock16( pModule->nrname_handle );
818 if (!NE_READ_DATA( pModule, buffer, ne_header->ne_nrestab, ne_header->ne_cbnrestab ))
820 GlobalFree16( pModule->nrname_handle );
824 else pModule->nrname_handle = 0;
826 /* Allocate a segment for the implicitly-loaded DLLs */
828 if (pModule->ne_cmod)
830 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
831 (pModule->ne_cmod+1)*sizeof(HMODULE16) );
832 if (!pModule->dlls_to_init)
834 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
837 FarSetOwner16( pModule->dlls_to_init, hModule );
839 else pModule->dlls_to_init = 0;
841 NE_RegisterModule( pModule );
845 GlobalFree16( hModule );
846 return ERROR_BAD_FORMAT;
850 /***********************************************************************
853 * Load all DLLs implicitly linked to a module.
855 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
858 WORD *pModRef = (WORD *)((char *)pModule + pModule->ne_modtab);
859 WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
861 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
863 char buffer[260], *p;
864 BYTE *pstr = (BYTE *)pModule + pModule->ne_imptab + *pModRef;
865 memcpy( buffer, pstr + 1, *pstr );
866 *(buffer + *pstr) = 0; /* terminate it */
868 TRACE("Loading '%s'\n", buffer );
869 if (!(*pModRef = GetModuleHandle16( buffer )))
871 /* If the DLL is not loaded yet, load it and store */
872 /* its handle in the list of DLLs to initialize. */
875 /* Append .DLL to name if no extension present */
876 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
877 strcat( buffer, ".DLL" );
879 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
881 /* FIXME: cleanup what was done */
883 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
884 buffer, *((BYTE*)pModule + pModule->ne_restab),
885 (char *)pModule + pModule->ne_restab + 1, hDLL );
888 *pModRef = GetExePtr( hDLL );
891 else /* Increment the reference count of the DLL */
893 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
894 if (pOldDLL) pOldDLL->count++;
901 /**********************************************************************
904 * Load first instance of NE module from file.
906 * pModule must point to a module structure prepared by build_module.
907 * This routine must never be called twice on a module.
909 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
911 /* Allocate the segments for this module */
913 if (!NE_CreateAllSegments( pModule ))
914 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
916 /* Load the referenced DLLs */
918 if (!NE_LoadDLLs( pModule ))
919 return ERROR_FILE_NOT_FOUND; /* 2 */
921 /* Load the segments */
923 NE_LoadAllSegments( pModule );
925 /* Make sure the usage count is 1 on the first loading of */
926 /* the module, even if it contains circular DLL references */
930 return NE_GetInstance( pModule );
933 /**********************************************************************
936 * Load first instance of NE module. (Note: caller is responsible for
937 * ensuring the module isn't already loaded!)
939 * If the module turns out to be an executable module, only a
940 * handle to a module stub is returned; this needs to be initialized
941 * by calling NE_DoLoadModule later, in the context of the newly
944 * If lib_only is TRUE, however, the module is perforce treated
945 * like a DLL module, even if it is an executable module.
948 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
952 HINSTANCE16 hInstance;
957 MEMORY_BASIC_INFORMATION info;
960 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
961 return ERROR_FILE_NOT_FOUND;
963 mapping = CreateFileMappingW( DosFileHandleToWin32Handle(hFile), NULL, PAGE_WRITECOPY, 0, 0, NULL );
965 if (!mapping) return ERROR_BAD_FORMAT;
967 ptr = MapViewOfFile( mapping, FILE_MAP_COPY, 0, 0, 0 );
968 CloseHandle( mapping );
969 if (!ptr) return ERROR_BAD_FORMAT;
971 VirtualQuery( ptr, &info, sizeof(info) );
972 hModule = build_module( ptr, info.RegionSize, ofs.szPathName );
976 UnmapViewOfFile( ptr );
980 SNOOP16_RegisterDLL( hModule, ofs.szPathName );
981 NE_InitResourceHandler( hModule );
983 pModule = NE_GetPtr( hModule );
985 if ( !lib_only && !( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) )
988 hInstance = NE_DoLoadModule( pModule );
989 if ( hInstance < 32 )
992 NE_FreeModule( hModule, 0 );
999 /***********************************************************************
1000 * NE_DoLoadBuiltinModule
1002 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
1004 static HMODULE16 NE_DoLoadBuiltinModule( const IMAGE_DOS_HEADER *mz_header, const char *file_name,
1009 HINSTANCE16 hInstance;
1010 OSVERSIONINFOW versionInfo;
1011 const IMAGE_OS2_HEADER *ne_header;
1012 SIZE_T mapping_size = ~0UL; /* assume builtins don't contain invalid offsets... */
1014 ne_header = (const IMAGE_OS2_HEADER *)((const BYTE *)mz_header + mz_header->e_lfanew);
1015 hModule = build_module( mz_header, mapping_size, file_name );
1016 if (hModule < 32) return hModule;
1017 pModule = GlobalLock16( hModule );
1018 pModule->ne_flags |= NE_FFLAGS_BUILTIN;
1019 pModule->owner32 = owner32;
1021 /* fake the expected version the module should have according to the current Windows version */
1022 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
1023 if (GetVersionExW( &versionInfo ))
1024 pModule->ne_expver = MAKEWORD( versionInfo.dwMinorVersion, versionInfo.dwMajorVersion );
1026 hInstance = NE_DoLoadModule( pModule );
1027 if (hInstance < 32) NE_FreeModule( hModule, 0 );
1029 NE_InitResourceHandler( hModule );
1031 if (pModule->ne_heap)
1033 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1;
1034 unsigned int size = pSeg->minsize + pModule->ne_heap;
1035 if (size > 0xfffe) size = 0xfffe;
1036 LocalInit16( GlobalHandleToSel16(pSeg->hSeg), pSeg->minsize, size );
1039 patch_code_segment( pModule );
1045 /**********************************************************************
1046 * MODULE_LoadModule16
1048 * Load a NE module in the order of the loadorder specification.
1049 * The caller is responsible that the module is not loaded already.
1052 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
1054 HINSTANCE16 hinst = 2;
1058 const IMAGE_DOS_HEADER *descr = NULL;
1059 const char *file_name = NULL;
1060 char dllname[20], owner[20], *p;
1061 const char *basename;
1064 /* strip path information */
1067 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
1068 if ((p = strrchr( basename, '\\' ))) basename = p + 1;
1069 if ((p = strrchr( basename, '/' ))) basename = p + 1;
1071 if (strlen(basename) < sizeof(dllname)-4)
1073 strcpy( dllname, basename );
1074 p = strrchr( dllname, '.' );
1075 if (!p) strcat( dllname, ".dll" );
1076 for (p = dllname; *p; p++) if (*p >= 'A' && *p <= 'Z') *p += 32;
1078 if (wine_dll_get_owner( dllname, owner, sizeof(owner), &owner_exists ) != -1)
1080 mod32 = LoadLibraryA( owner );
1083 if (!(descr = find_dll_descr( dllname, &file_name )))
1085 FreeLibrary( mod32 );
1088 /* loading the 32-bit library can have the side effect of loading the module */
1089 /* if so, simply incr the ref count and return the module */
1090 if ((hModule = GetModuleHandle16( libname )))
1092 TRACE( "module %s already loaded by owner\n", libname );
1093 pModule = NE_GetPtr( hModule );
1094 if (pModule) pModule->count++;
1095 FreeLibrary( mod32 );
1101 /* it's probably disabled by the load order config */
1102 WARN( "couldn't load owner %s for 16-bit dll %s\n", owner, dllname );
1103 return ERROR_FILE_NOT_FOUND;
1110 TRACE("Trying built-in '%s'\n", libname);
1111 hinst = NE_DoLoadBuiltinModule( descr, file_name, mod32 );
1112 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : builtin\n", debugstr_a(file_name));
1116 TRACE("Trying native dll '%s'\n", libname);
1117 hinst = NE_LoadModule(libname, lib_only);
1118 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : native\n", debugstr_a(libname));
1119 if (hinst == ERROR_FILE_NOT_FOUND && owner_exists) hinst = 21; /* win32 module */
1122 if (hinst > 32 && !implicit)
1124 hModule = GetModuleHandle16(libname);
1127 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1129 return ERROR_INVALID_HANDLE;
1132 pModule = NE_GetPtr(hModule);
1135 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1137 return ERROR_INVALID_HANDLE;
1140 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1143 * Call initialization routines for all loaded DLLs. Note that
1144 * when we load implicitly linked DLLs this will be done by InitTask().
1146 if(pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1148 NE_InitializeDLLs(hModule);
1149 NE_DllProcessAttach(hModule);
1152 return hinst; /* The last error that occurred */
1156 /**********************************************************************
1159 * Create the thread for a 16-bit module.
1161 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1166 HINSTANCE16 instance = 0;
1168 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1171 /* Post event to start the task */
1172 PostEvent16( hTask );
1174 /* Wait until we get the instance handle */
1177 DirectedYield16( hTask );
1178 if (!IsTask16( hTask )) /* thread has died */
1181 WaitForSingleObject( hThread, INFINITE );
1182 GetExitCodeThread( hThread, &exit_code );
1183 CloseHandle( hThread );
1186 if (!(pTask = GlobalLock16( hTask ))) break;
1187 instance = pTask->hInstance;
1188 GlobalUnlock16( hTask );
1189 } while (!instance);
1191 CloseHandle( hThread );
1196 /**********************************************************************
1197 * LoadModule (KERNEL.45)
1199 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1201 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1202 LOADPARAMS16 *params;
1208 if (name == NULL) return 0;
1212 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1214 /* Special case: second instance of an already loaded NE module */
1216 if ( !( pModule = NE_GetPtr( hModule ) ) ) return ERROR_BAD_FORMAT;
1217 if ( pModule->module32 ) return (HINSTANCE16)21;
1219 /* Increment refcount */
1225 /* Main case: load first instance of NE module */
1227 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1230 if ( !(pModule = NE_GetPtr( hModule )) )
1231 return ERROR_BAD_FORMAT;
1234 /* If library module, we just retrieve the instance handle */
1236 if ( ( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1237 return NE_GetInstance( pModule );
1240 * At this point, we need to create a new process.
1242 * pModule points either to an already loaded module, whose refcount
1243 * has already been incremented (to avoid having the module vanish
1244 * in the meantime), or else to a stub module which contains only header
1247 params = (LOADPARAMS16 *)paramBlock;
1248 cmdShow = ((WORD *)MapSL(params->showCmd))[1];
1249 cmdline = MapSL( params->cmdLine );
1250 return NE_CreateThread( pModule, cmdShow, cmdline );
1254 /**********************************************************************
1257 * Startup code for a new 16-bit task.
1259 DWORD NE_StartTask(void)
1261 TDB *pTask = TASK_GetCurrent();
1262 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1263 HINSTANCE16 hInstance, hPrevInstance;
1264 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1267 if ( pModule->count > 0 )
1269 /* Second instance of an already loaded NE module */
1270 /* Note that the refcount was already incremented by the parent */
1272 hPrevInstance = NE_GetInstance( pModule );
1274 if ( pModule->ne_autodata )
1275 if ( NE_CreateSegment( pModule, pModule->ne_autodata ) )
1276 NE_LoadSegment( pModule, pModule->ne_autodata );
1278 hInstance = NE_GetInstance( pModule );
1279 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->ne_autodata, hPrevInstance);
1284 /* Load first instance of NE module */
1286 pModule->ne_flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1288 hInstance = NE_DoLoadModule( pModule );
1292 if ( hInstance >= 32 )
1296 /* Enter instance handles into task struct */
1298 pTask->hInstance = hInstance;
1299 pTask->hPrevInstance = hPrevInstance;
1301 /* Use DGROUP for 16-bit stack */
1303 if (!(sp = OFFSETOF(pModule->ne_sssp)))
1304 sp = pSegTable[SELECTOROF(pModule->ne_sssp)-1].minsize + pModule->ne_stack;
1306 sp -= sizeof(STACK16FRAME);
1307 NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1309 /* Registers at initialization must be:
1311 * bx stack size in bytes
1312 * cx heap size in bytes
1313 * si previous app instance
1314 * di current app instance
1316 * es selector to the PSP
1317 * ds dgroup of the application
1319 * sp top of the stack
1321 memset( &context, 0, sizeof(context) );
1322 context.SegCs = GlobalHandleToSel16(pSegTable[SELECTOROF(pModule->ne_csip) - 1].hSeg);
1323 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1324 context.SegEs = pTask->hPDB;
1325 context.SegFs = wine_get_fs();
1326 context.SegGs = wine_get_gs();
1327 context.Eip = OFFSETOF(pModule->ne_csip);
1328 context.Ebx = pModule->ne_stack;
1329 context.Ecx = pModule->ne_heap;
1330 context.Edi = pTask->hInstance;
1331 context.Esi = pTask->hPrevInstance;
1333 /* Now call 16-bit entry point */
1335 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1336 context.SegCs, context.Eip, context.SegDs,
1337 SELECTOROF(NtCurrentTeb()->WOW32Reserved),
1338 OFFSETOF(NtCurrentTeb()->WOW32Reserved) );
1340 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1341 ExitThread( LOWORD(context.Eax) );
1343 return hInstance; /* error code */
1346 /***********************************************************************
1347 * LoadLibrary (KERNEL.95)
1348 * LoadLibrary16 (KERNEL32.35)
1350 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1352 return LoadModule16(libname, (LPVOID)-1 );
1356 /**********************************************************************
1359 * Call a DLL's WEP, allowing it to shut down.
1360 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1362 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1365 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1366 if (!WEP) return FALSE;
1373 args[0] = WEP_FREE_DLL;
1374 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1375 ret = LOWORD(dwRet);
1377 __EXCEPT(page_fault)
1379 WARN("Page fault\n");
1388 /**********************************************************************
1391 * Implementation of FreeModule16().
1393 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1395 HMODULE16 *hPrevModule;
1400 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1401 hModule = pModule->self;
1403 TRACE("%04x count %d\n", hModule, pModule->count );
1405 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1406 else pModule->count = 0;
1408 if (call_wep && !(pModule->ne_flags & NE_FFLAGS_WIN32))
1410 /* Free the objects owned by the DLL module */
1411 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1413 if (pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1414 MODULE_CallWEP( hModule );
1416 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1419 TRACE_(loaddll)("Unloaded module %s : %s\n", debugstr_a(NE_MODULE_NAME(pModule)),
1420 (pModule->ne_flags & NE_FFLAGS_BUILTIN) ? "builtin" : "native");
1422 /* Clear magic number just in case */
1424 pModule->ne_magic = pModule->self = 0;
1425 if (pModule->owner32) FreeLibrary( pModule->owner32 );
1426 else if (pModule->mapping) UnmapViewOfFile( (void *)pModule->mapping );
1428 /* Remove it from the linked list */
1430 hPrevModule = &hFirstModule;
1431 while (*hPrevModule && (*hPrevModule != hModule))
1433 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1435 if (*hPrevModule) *hPrevModule = pModule->next;
1437 /* Free the referenced modules */
1439 pModRef = (HMODULE16*)((char *)pModule + pModule->ne_modtab);
1440 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
1442 NE_FreeModule( *pModRef, call_wep );
1445 /* Free the module storage */
1447 GlobalFreeAll16( hModule );
1452 /**********************************************************************
1453 * FreeModule (KERNEL.46)
1455 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1457 return NE_FreeModule( hModule, TRUE );
1461 /***********************************************************************
1462 * FreeLibrary (KERNEL.96)
1463 * FreeLibrary16 (KERNEL32.36)
1465 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1467 TRACE("%04x\n", handle );
1468 FreeModule16( handle );
1472 /***********************************************************************
1473 * GetModuleHandle16 (KERNEL32.@)
1475 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1477 HMODULE16 hModule = hFirstModule;
1479 BYTE len, *name_table;
1480 char tmpstr[MAX_PATH];
1483 TRACE("(%s)\n", name);
1485 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1490 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1492 /* If 'name' matches exactly the module name of a module:
1493 * Return its handle.
1495 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1497 pModule = NE_GetPtr( hModule );
1498 if (!pModule) break;
1499 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1501 name_table = (BYTE *)pModule + pModule->ne_restab;
1502 if ((*name_table == len) && !strncmp(name, (char*) name_table+1, len))
1506 /* If uppercased 'name' matches exactly the module name of a module:
1509 for (s = tmpstr; *s; s++) *s = RtlUpperChar(*s);
1511 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1513 pModule = NE_GetPtr( hModule );
1514 if (!pModule) break;
1515 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1517 name_table = (BYTE *)pModule + pModule->ne_restab;
1518 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1519 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1520 * lowercased module names, but try to load uppercase DLLs, so this
1521 * 'i' compare is just a quickfix until the loader handles that
1522 * correctly. -MM 990705
1524 if ((*name_table == len) && !NE_strncasecmp(tmpstr, (const char*)name_table+1, len))
1528 /* If the base filename of 'name' matches the base filename of the module
1529 * filename of some module (case-insensitive compare):
1530 * Return its handle.
1533 /* basename: search backwards in passed name to \ / or : */
1534 s = tmpstr + strlen(tmpstr);
1537 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1542 /* search this in loaded filename list */
1543 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1548 pModule = NE_GetPtr( hModule );
1549 if (!pModule) break;
1550 if (!pModule->fileinfo) continue;
1551 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1553 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1554 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1555 /* basename: search backwards in pathname to \ / or : */
1556 while (loadedfn > (char*)ofs->szPathName)
1558 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1562 /* case insensitive compare ... */
1563 if (!NE_strcasecmp(loadedfn, s))
1570 /**********************************************************************
1571 * GetModuleName (KERNEL.27)
1573 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1578 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1579 p = (BYTE *)pModule + pModule->ne_restab;
1580 if (count > *p) count = *p + 1;
1583 memcpy( buf, p + 1, count - 1 );
1584 buf[count-1] = '\0';
1590 /**********************************************************************
1591 * GetModuleFileName (KERNEL.49)
1593 * Comment: see GetModuleFileNameA
1595 * Even if invoked by second instance of a program,
1596 * it still returns path of first one.
1598 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1603 /* Win95 does not query hModule if set to 0 !
1604 * Is this wrong or maybe Win3.1 only ? */
1605 if (!hModule) hModule = GetCurrentTask();
1607 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1608 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1609 if (pModule->ne_expver < 0x400)
1610 GetShortPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1611 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1612 return strlen(lpFileName);
1616 /**********************************************************************
1617 * GetModuleUsage (KERNEL.48)
1619 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1621 NE_MODULE *pModule = NE_GetPtr( hModule );
1622 return pModule ? pModule->count : 0;
1626 /**********************************************************************
1627 * GetExpWinVer (KERNEL.167)
1629 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1631 NE_MODULE *pModule = NE_GetPtr( hModule );
1632 if ( !pModule ) return 0;
1633 return pModule->ne_expver;
1637 /***********************************************************************
1638 * WinExec (KERNEL.166)
1640 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1642 LPCSTR p, args = NULL;
1643 LPCSTR name_beg, name_end;
1644 LPSTR name, cmdline;
1647 char buffer[MAX_PATH];
1649 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1651 name_beg = lpCmdLine+1;
1652 p = strchr ( lpCmdLine+1, '"' );
1656 args = strchr ( p, ' ' );
1658 else /* yes, even valid with trailing '"' missing */
1659 name_end = lpCmdLine+strlen(lpCmdLine);
1663 name_beg = lpCmdLine;
1664 args = strchr( lpCmdLine, ' ' );
1665 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1668 if ((name_beg == lpCmdLine) && (!args))
1669 { /* just use the original cmdline string as file name */
1670 name = (LPSTR)lpCmdLine;
1674 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1675 return ERROR_NOT_ENOUGH_MEMORY;
1676 memcpy( name, name_beg, name_end - name_beg );
1677 name[name_end - name_beg] = '\0';
1683 arglen = strlen(args);
1684 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1685 cmdline[0] = (BYTE)arglen;
1686 strcpy( cmdline + 1, args );
1690 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1691 cmdline[0] = cmdline[1] = 0;
1694 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1696 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1698 LOADPARAMS16 params;
1701 showCmd[1] = nCmdShow;
1703 params.hEnvironment = 0;
1704 params.cmdLine = MapLS( cmdline );
1705 params.showCmd = MapLS( showCmd );
1706 params.reserved = 0;
1708 ret = LoadModule16( buffer, ¶ms );
1709 UnMapLS( params.cmdLine );
1710 UnMapLS( params.showCmd );
1712 else ret = GetLastError();
1714 HeapFree( GetProcessHeap(), 0, cmdline );
1715 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1717 if (ret == 21 || ret == ERROR_BAD_FORMAT) /* 32-bit module or unknown executable*/
1720 ReleaseThunkLock( &count );
1721 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
1722 RestoreThunkLock( count );
1727 /***********************************************************************
1728 * GetProcAddress (KERNEL.50)
1730 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1735 if (!hModule) hModule = GetCurrentTask();
1736 hModule = GetExePtr( hModule );
1738 if (HIWORD(name) != 0)
1740 ordinal = NE_GetOrdinal( hModule, name );
1741 TRACE("%04x '%s'\n", hModule, name );
1745 ordinal = LOWORD(name);
1746 TRACE("%04x %04x\n", hModule, ordinal );
1748 if (!ordinal) return (FARPROC16)0;
1750 ret = NE_GetEntryPoint( hModule, ordinal );
1752 TRACE("returning %p\n", ret );
1757 /***************************************************************************
1758 * HasGPHandler (KERNEL.338)
1760 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1765 GPHANDLERDEF *gpHandler;
1767 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1768 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1769 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1770 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1771 && (gpHandler = MapSL( gpPtr )) != NULL )
1773 while (gpHandler->selector)
1775 if ( SELECTOROF(address) == gpHandler->selector
1776 && OFFSETOF(address) >= gpHandler->rangeStart
1777 && OFFSETOF(address) < gpHandler->rangeEnd )
1778 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1787 /**********************************************************************
1788 * GetModuleHandle (KERNEL.47)
1790 * Find a module from a module name.
1792 * NOTE: The current implementation works the same way the Windows 95 one
1793 * does. Do not try to 'fix' it, fix the callers.
1794 * + It does not do ANY extension handling (except that strange .EXE bit)!
1795 * + It does not care about paths, just about basenames. (same as Windows)
1799 * the win16 module handle if found
1801 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1802 * Always hFirstModule
1804 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1806 if (HIWORD(name) == 0)
1807 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1808 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1811 /**********************************************************************
1812 * NE_GetModuleByFilename
1814 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1818 BYTE len, *name_table;
1819 char tmpstr[MAX_PATH];
1822 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1824 /* If the base filename of 'name' matches the base filename of the module
1825 * filename of some module (case-insensitive compare):
1826 * Return its handle.
1829 /* basename: search backwards in passed name to \ / or : */
1830 s = tmpstr + strlen(tmpstr);
1833 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1838 /* search this in loaded filename list */
1839 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1844 pModule = NE_GetPtr( hModule );
1845 if (!pModule) break;
1846 if (!pModule->fileinfo) continue;
1847 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1849 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1850 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1851 /* basename: search backwards in pathname to \ / or : */
1852 while (loadedfn > (char*)ofs->szPathName)
1854 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1858 /* case insensitive compare ... */
1859 if (!NE_strcasecmp(loadedfn, s))
1862 /* If basename (without ext) matches the module name of a module:
1863 * Return its handle.
1866 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1869 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1871 pModule = NE_GetPtr( hModule );
1872 if (!pModule) break;
1873 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1875 name_table = (BYTE *)pModule + pModule->ne_restab;
1876 if ((*name_table == len) && !NE_strncasecmp(s, (const char*)name_table+1, len))
1883 /***********************************************************************
1884 * GetProcAddress16 (KERNEL32.37)
1885 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1887 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1889 if (!hModule) return 0;
1890 if (HIWORD(hModule))
1892 WARN("hModule is Win32 handle (%p)\n", hModule );
1895 return GetProcAddress16( LOWORD(hModule), name );
1898 /**********************************************************************
1899 * ModuleFirst (TOOLHELP.59)
1901 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1903 lpme->wNext = hFirstModule;
1904 return ModuleNext16( lpme );
1908 /**********************************************************************
1909 * ModuleNext (TOOLHELP.60)
1911 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1916 if (!lpme->wNext) return FALSE;
1917 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1918 name = (char *)pModule + pModule->ne_restab;
1919 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1920 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1921 lpme->hModule = lpme->wNext;
1922 lpme->wcUsage = pModule->count;
1923 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1924 lpme->wNext = pModule->next;
1929 /**********************************************************************
1930 * ModuleFindName (TOOLHELP.61)
1932 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1934 lpme->wNext = GetModuleHandle16( name );
1935 return ModuleNext16( lpme );
1939 /**********************************************************************
1940 * ModuleFindHandle (TOOLHELP.62)
1942 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1944 hModule = GetExePtr( hModule );
1945 lpme->wNext = hModule;
1946 return ModuleNext16( lpme );
1950 /***************************************************************************
1951 * IsRomModule (KERNEL.323)
1953 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1958 /***************************************************************************
1959 * IsRomFile (KERNEL.326)
1961 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1966 /***********************************************************************
1967 * create_dummy_module
1969 * Create a dummy NE module for Win32 or Winelib.
1971 static HMODULE16 create_dummy_module( HMODULE module32 )
1975 SEGTABLEENTRY *pSegment;
1978 const char* basename;
1981 char filename[MAX_PATH];
1982 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
1984 if (!nt) return ERROR_BAD_FORMAT;
1986 /* Extract base filename */
1987 len = GetModuleFileNameA( module32, filename, sizeof(filename) );
1988 if (!len || len >= sizeof(filename)) return ERROR_BAD_FORMAT;
1989 basename = strrchr(filename, '\\');
1990 if (!basename) basename = filename;
1992 len = strlen(basename);
1993 if ((s = strchr(basename, '.'))) len = s - basename;
1995 /* Allocate module */
1996 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
1997 + strlen(filename) + 1;
1998 size = sizeof(NE_MODULE) +
1999 /* loaded file info */
2000 ((of_size + 3) & ~3) +
2001 /* segment table: DS,CS */
2002 2 * sizeof(SEGTABLEENTRY) +
2005 /* several empty tables */
2008 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
2009 if (!hModule) return ERROR_BAD_FORMAT;
2011 FarSetOwner16( hModule, hModule );
2012 pModule = (NE_MODULE *)GlobalLock16( hModule );
2014 /* Set all used entries */
2015 pModule->ne_magic = IMAGE_OS2_SIGNATURE;
2018 pModule->ne_flags = NE_FFLAGS_WIN32;
2019 pModule->ne_autodata = 0;
2020 pModule->ne_sssp = MAKESEGPTR( 0, 1 );
2021 pModule->ne_csip = MAKESEGPTR( 0, 2 );
2022 pModule->ne_heap = 0;
2023 pModule->ne_stack = 0;
2024 pModule->ne_cseg = 2;
2025 pModule->ne_cmod = 0;
2026 pModule->ne_cbnrestab = 0;
2027 pModule->fileinfo = sizeof(NE_MODULE);
2028 pModule->ne_exetyp = NE_OSFLAGS_WINDOWS;
2029 pModule->self = hModule;
2030 pModule->module32 = module32;
2032 /* Set version and flags */
2033 pModule->ne_expver = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
2034 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
2035 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
2036 pModule->ne_flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
2038 /* Set loaded file information */
2039 ofs = (OFSTRUCT *)(pModule + 1);
2040 memset( ofs, 0, of_size );
2041 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
2042 strcpy( ofs->szPathName, filename );
2044 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
2045 pModule->ne_segtab = (char *)pSegment - (char *)pModule;
2048 pSegment->flags = NE_SEGFLAGS_DATA;
2049 pSegment->minsize = 0x1000;
2052 pSegment->flags = 0;
2056 pStr = (char *)pSegment;
2057 pModule->ne_restab = pStr - (char *)pModule;
2060 lstrcpynA( pStr+1, basename, len+1 );
2063 /* All tables zero terminated */
2064 pModule->ne_rsrctab = pModule->ne_imptab = pModule->ne_enttab = (char *)pStr - (char *)pModule;
2066 NE_RegisterModule( pModule );
2067 pModule->owner32 = LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
2071 /***********************************************************************
2072 * PrivateLoadLibrary (KERNEL32.@)
2074 * FIXME: rough guesswork, don't know what "Private" means
2076 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
2078 return LoadLibrary16(libname);
2081 /***********************************************************************
2082 * PrivateFreeLibrary (KERNEL32.@)
2084 * FIXME: rough guesswork, don't know what "Private" means
2086 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
2088 FreeLibrary16(handle);
2091 /***********************************************************************
2092 * LoadLibrary32 (KERNEL.452)
2093 * LoadSystemLibrary32 (KERNEL.482)
2095 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
2100 ReleaseThunkLock( &count );
2101 hModule = LoadLibraryA( libname );
2102 RestoreThunkLock( count );
2106 /***************************************************************************
2107 * MapHModuleLS (KERNEL32.@)
2109 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2115 return TASK_GetCurrent()->hInstance;
2117 return LOWORD(hmod); /* we already have a 16 bit module handle */
2118 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
2120 if (pModule->module32 == hmod)
2121 return pModule->self;
2122 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
2124 if ((ret = create_dummy_module( hmod )) < 32)
2132 /***************************************************************************
2133 * MapHModuleSL (KERNEL32.@)
2135 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2140 TDB *pTask = TASK_GetCurrent();
2141 hmod = pTask->hModule;
2143 pModule = (NE_MODULE*)GlobalLock16(hmod);
2144 if ((pModule->ne_magic != IMAGE_OS2_SIGNATURE) || !(pModule->ne_flags & NE_FFLAGS_WIN32))
2146 return pModule->module32;
2149 /***************************************************************************
2150 * MapHInstLS (KERNEL32.@)
2151 * MapHInstLS (KERNEL.472)
2153 void WINAPI __regs_MapHInstLS( CONTEXT86 *context )
2155 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2157 #ifdef DEFINE_REGS_ENTRYPOINT
2158 DEFINE_REGS_ENTRYPOINT( MapHInstLS, 0, 0 );
2161 /***************************************************************************
2162 * MapHInstSL (KERNEL32.@)
2163 * MapHInstSL (KERNEL.473)
2165 void WINAPI __regs_MapHInstSL( CONTEXT86 *context )
2167 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2169 #ifdef DEFINE_REGS_ENTRYPOINT
2170 DEFINE_REGS_ENTRYPOINT( MapHInstSL, 0, 0 );
2173 /***************************************************************************
2174 * MapHInstLS_PN (KERNEL32.@)
2176 void WINAPI __regs_MapHInstLS_PN( CONTEXT86 *context )
2178 if (context->Eax) context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2180 #ifdef DEFINE_REGS_ENTRYPOINT
2181 DEFINE_REGS_ENTRYPOINT( MapHInstLS_PN, 0, 0 );
2184 /***************************************************************************
2185 * MapHInstSL_PN (KERNEL32.@)
2187 void WINAPI __regs_MapHInstSL_PN( CONTEXT86 *context )
2189 if (context->Eax) context->Eax = (DWORD)MapHModuleSL( context->Eax );
2191 #ifdef DEFINE_REGS_ENTRYPOINT
2192 DEFINE_REGS_ENTRYPOINT( MapHInstSL_PN, 0, 0 );