include: Add STORAGE_HOTPLUG_INFO structure.
[wine.git] / dlls / krnl386.exe16 / ne_module.c
blob2f2431884b928e2581f642c013cc1606cec49fb4
1 /*
2 * NE modules
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
21 #include <assert.h>
22 #include <fcntl.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "wine/winbase16.h"
33 #include "wownt32.h"
34 #include "winternl.h"
35 #include "ddk/ntddk.h"
36 #include "kernel16_private.h"
37 #include "wine/exception.h"
38 #include "wine/debug.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(module);
41 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
42 WINE_DECLARE_DEBUG_CHANNEL(relay);
43 WINE_DECLARE_DEBUG_CHANNEL(winediag);
45 #include "pshpack1.h"
46 typedef struct _GPHANDLERDEF
48 WORD selector;
49 WORD rangeStart;
50 WORD rangeEnd;
51 WORD handler;
52 } GPHANDLERDEF;
53 #include "poppack.h"
56 * Segment table entry
58 struct ne_segment_table_entry_s
60 WORD seg_data_offset; /* Sector offset of segment data */
61 WORD seg_data_length; /* Length of segment data */
62 WORD seg_flags; /* Flags associated with this segment */
63 WORD min_alloc; /* Minimum allocation size for this */
66 #define hFirstModule (pThhook->hExeHead)
68 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
69 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
71 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
73 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
76 /* patch all the flat cs references of the code segment if necessary */
77 static inline void patch_code_segment( NE_MODULE *pModule )
79 int i;
80 CALLFROM16 *call;
81 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule );
83 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
84 if (!(pSeg->flags & NE_SEGFLAGS_DATA)) break; /* found the code segment */
86 call = GlobalLock16( pSeg->hSeg );
88 /* patch glue code address and code selector */
89 for (i = 0; call[i].pushl == 0x68; i++)
91 if (call[i].ret[0] == 0xca66 || call[i].ret[0] == 0xcb66) /* register entry point? */
92 call[i].glue = __wine_call_from_16_regs;
93 else
94 call[i].glue = __wine_call_from_16;
95 call[i].flatcs = get_cs();
98 if (TRACE_ON(relay)) /* patch relay functions to all point to relay_call_from_16 */
99 for (i = 0; call[i].pushl == 0x68; i++) call[i].relay = relay_call_from_16;
103 /***********************************************************************
104 * contains_path
106 static inline BOOL contains_path( LPCSTR name )
108 return ((*name && (name[1] == ':')) || strchr(name, '/') || strchr(name, '\\'));
112 /***********************************************************************
113 * NE_GetPtr
115 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
117 return GlobalLock16( GetExePtr(hModule) );
121 /**********************************************************************
122 * NE_RegisterModule
124 static void NE_RegisterModule( NE_MODULE *pModule )
126 pModule->next = hFirstModule;
127 hFirstModule = pModule->self;
131 /***********************************************************************
132 * NE_DumpModule
134 void NE_DumpModule( HMODULE16 hModule )
136 int i, ordinal;
137 SEGTABLEENTRY *pSeg;
138 BYTE *pstr;
139 WORD *pword;
140 NE_MODULE *pModule;
141 ET_BUNDLE *bundle;
142 ET_ENTRY *entry;
144 if (!(pModule = NE_GetPtr( hModule )))
146 ERR( "**** %04x is not a module handle\n", hModule );
147 return;
150 /* Dump the module info */
151 TRACE( "---\n" );
152 TRACE( "Module %04x:\n", hModule );
153 TRACE( "count=%d flags=%04x heap=%d stack=%d\n",
154 pModule->count, pModule->ne_flags,
155 pModule->ne_heap, pModule->ne_stack );
156 TRACE( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
157 SELECTOROF(pModule->ne_csip), OFFSETOF(pModule->ne_csip),
158 SELECTOROF(pModule->ne_sssp), OFFSETOF(pModule->ne_sssp),
159 pModule->ne_autodata, pModule->ne_cseg, pModule->ne_cmod );
160 TRACE( "os_flags=%d swap_area=%d version=%04x\n",
161 pModule->ne_exetyp, pModule->ne_swaparea, pModule->ne_expver );
162 if (pModule->ne_flags & NE_FFLAGS_WIN32)
163 TRACE( "PE module=%p\n", pModule->module32 );
165 /* Dump the file info */
166 TRACE( "---\n" );
167 TRACE( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
169 /* Dump the segment table */
170 TRACE( "---\n" );
171 TRACE( "Segment table:\n" );
172 pSeg = NE_SEG_TABLE( pModule );
173 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
174 TRACE( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
175 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
176 pSeg->minsize, pSeg->hSeg );
178 /* Dump the resource table */
179 TRACE( "---\n" );
180 TRACE( "Resource table:\n" );
181 if (pModule->ne_rsrctab)
183 pword = (WORD *)((BYTE *)pModule + pModule->ne_rsrctab);
184 TRACE( "Alignment: %d\n", *pword++ );
185 while (*pword)
187 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
188 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
189 TRACE( "id=%04x count=%d\n", ptr->type_id, ptr->count );
190 for (i = 0; i < ptr->count; i++, pname++)
191 TRACE( "offset=%d len=%d id=%04x\n",
192 pname->offset, pname->length, pname->id );
193 pword = (WORD *)pname;
196 else TRACE( "None\n" );
198 /* Dump the resident name table */
199 TRACE( "---\n" );
200 TRACE( "Resident-name table:\n" );
201 pstr = (BYTE*) pModule + pModule->ne_restab;
202 while (*pstr)
204 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
205 *(WORD *)(pstr + *pstr + 1) );
206 pstr += *pstr + 1 + sizeof(WORD);
209 /* Dump the module reference table */
210 TRACE( "---\n" );
211 TRACE( "Module ref table:\n" );
212 if (pModule->ne_modtab)
214 pword = (WORD *)((BYTE *)pModule + pModule->ne_modtab);
215 for (i = 0; i < pModule->ne_cmod; i++, pword++)
217 char name[10];
218 GetModuleName16( *pword, name, sizeof(name) );
219 TRACE( "%d: %04x -> '%s'\n", i, *pword, name );
222 else TRACE( "None\n" );
224 /* Dump the entry table */
225 TRACE( "---\n" );
226 TRACE( "Entry table:\n" );
227 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->ne_enttab);
228 do {
229 entry = (ET_ENTRY *)((BYTE *)bundle+6);
230 TRACE( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
231 ordinal = bundle->first;
232 while (ordinal < bundle->last)
234 if (entry->type == 0xff)
235 TRACE("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
236 else
237 TRACE("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
238 entry++;
240 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
242 /* Dump the non-resident names table */
243 TRACE( "---\n" );
244 TRACE( "Non-resident names table:\n" );
245 if (pModule->nrname_handle)
247 pstr = GlobalLock16( pModule->nrname_handle );
248 while (*pstr)
250 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
251 *(WORD *)(pstr + *pstr + 1) );
252 pstr += *pstr + 1 + sizeof(WORD);
255 TRACE( "\n" );
259 /***********************************************************************
260 * NE_WalkModules
262 * Walk the module list and print the modules.
264 void NE_WalkModules(void)
266 HMODULE16 hModule = hFirstModule;
267 MESSAGE( "Module Flags Name\n" );
268 while (hModule)
270 NE_MODULE *pModule = NE_GetPtr( hModule );
271 if (!pModule)
273 MESSAGE( "Bad module %04x in list\n", hModule );
274 return;
276 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->ne_flags,
277 *((char *)pModule + pModule->ne_restab),
278 (char *)pModule + pModule->ne_restab + 1 );
279 hModule = pModule->next;
284 /***********************************************************************
285 * NE_InitResourceHandler
287 * Fill in 'resloader' fields in the resource table.
289 static void NE_InitResourceHandler( HMODULE16 hModule )
291 static FARPROC16 proc;
293 NE_TYPEINFO *pTypeInfo;
294 NE_MODULE *pModule;
296 if (!(pModule = NE_GetPtr( hModule )) || !pModule->ne_rsrctab) return;
298 TRACE("InitResourceHandler[%04x]\n", hModule );
300 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
302 pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->ne_rsrctab + 2);
303 while(pTypeInfo->type_id)
305 pTypeInfo->resloader = proc;
306 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
311 /***********************************************************************
312 * NE_GetOrdinal
314 * Lookup the ordinal for a given name.
316 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
318 char buffer[256], *p;
319 BYTE *cpnt;
320 BYTE len;
321 NE_MODULE *pModule;
323 if (!(pModule = NE_GetPtr( hModule ))) return 0;
324 if (pModule->ne_flags & NE_FFLAGS_WIN32) return 0;
326 TRACE("(%04x,'%s')\n", hModule, name );
328 /* First handle names of the form '#xxxx' */
330 if (name[0] == '#') return atoi( name + 1 );
332 /* Now copy and uppercase the string */
334 strcpy( buffer, name );
335 for (p = buffer; *p; p++) *p = RtlUpperChar(*p);
336 len = p - buffer;
338 /* First search the resident names */
340 cpnt = (BYTE *)pModule + pModule->ne_restab;
342 /* Skip the first entry (module name) */
343 cpnt += *cpnt + 1 + sizeof(WORD);
344 while (*cpnt)
346 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
348 WORD ordinal;
349 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
350 TRACE(" Found: ordinal=%d\n", ordinal );
351 return ordinal;
353 cpnt += *cpnt + 1 + sizeof(WORD);
356 /* Now search the non-resident names table */
358 if (!pModule->nrname_handle) return 0; /* No non-resident table */
359 cpnt = GlobalLock16( pModule->nrname_handle );
361 /* Skip the first entry (module description string) */
362 cpnt += *cpnt + 1 + sizeof(WORD);
363 while (*cpnt)
365 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
367 WORD ordinal;
368 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
369 TRACE(" Found: ordinal=%d\n", ordinal );
370 return ordinal;
372 cpnt += *cpnt + 1 + sizeof(WORD);
374 return 0;
378 /***********************************************************************
379 * NE_GetEntryPoint
381 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
383 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
386 /***********************************************************************
387 * NE_GetEntryPointEx
389 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
391 NE_MODULE *pModule;
392 WORD sel, offset, i;
394 ET_ENTRY *entry;
395 ET_BUNDLE *bundle;
397 if (!(pModule = NE_GetPtr( hModule ))) return 0;
399 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
400 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
402 if (!(bundle->next))
403 return 0;
404 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
407 entry = (ET_ENTRY *)((BYTE *)bundle+6);
408 for (i=0; i < (ordinal - bundle->first - 1); i++)
409 entry++;
411 sel = entry->segnum;
412 memcpy( &offset, &entry->offs, sizeof(WORD) );
414 if (sel == 0xfe) sel = 0xffff; /* constant entry */
415 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
416 if (sel==0xffff)
417 return (FARPROC16)MAKESEGPTR( sel, offset );
418 if (!snoop)
419 return (FARPROC16)MAKESEGPTR( sel, offset );
420 else
421 return SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
425 /***********************************************************************
426 * EntryAddrProc (KERNEL.667) Wine-specific export
428 * Return the entry point for a given ordinal.
430 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
432 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
433 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
434 return ret;
437 /***********************************************************************
438 * NE_SetEntryPoint
440 * Change the value of an entry point. Use with caution!
441 * It can only change the offset value, not the selector.
443 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
445 NE_MODULE *pModule;
446 ET_ENTRY *entry;
447 ET_BUNDLE *bundle;
448 int i;
450 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
452 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
453 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
455 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
456 if (!bundle->next) return FALSE;
459 entry = (ET_ENTRY *)((BYTE *)bundle+6);
460 for (i=0; i < (ordinal - bundle->first - 1); i++)
461 entry++;
463 memcpy( &entry->offs, &offset, sizeof(WORD) );
464 return TRUE;
468 /***********************************************************************
469 * build_bundle_data
471 * Build the entry table bundle data from the on-disk format. Helper for build_module.
473 static void *build_bundle_data( NE_MODULE *pModule, void *dest, const BYTE *table )
475 ET_BUNDLE *oldbundle, *bundle = dest;
476 ET_ENTRY *entry;
477 BYTE nr_entries, type;
479 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
480 entry = (ET_ENTRY *)((BYTE *)bundle+6);
482 while ((nr_entries = *table++))
484 if ((type = *table++))
486 bundle->last += nr_entries;
487 if (type == 0xff)
489 while (nr_entries--)
491 entry->type = type;
492 entry->flags = *table++;
493 table += sizeof(WORD);
494 entry->segnum = *table++;
495 entry->offs = *(const WORD *)table;
496 table += sizeof(WORD);
497 entry++;
500 else
502 while (nr_entries--)
504 entry->type = type;
505 entry->flags = *table++;
506 entry->segnum = type;
507 entry->offs = *(const WORD *)table;
508 table += sizeof(WORD);
509 entry++;
513 else
515 if (bundle->first == bundle->last)
517 bundle->first += nr_entries;
518 bundle->last += nr_entries;
520 else
522 oldbundle = bundle;
523 oldbundle->next = (char *)entry - (char *)pModule;
524 bundle = (ET_BUNDLE *)entry;
525 bundle->first = bundle->last = oldbundle->last + nr_entries;
526 bundle->next = 0;
527 entry = (ET_ENTRY*)(((BYTE*)entry)+sizeof(ET_BUNDLE));
531 return entry;
535 /***********************************************************************
536 * build_module
538 * Build the in-memory module from the on-disk data.
540 static HMODULE16 build_module( const void *mapping, SIZE_T mapping_size, LPCSTR path )
542 const IMAGE_DOS_HEADER *mz_header = mapping;
543 const IMAGE_OS2_HEADER *ne_header;
544 const struct ne_segment_table_entry_s *pSeg;
545 const void *ptr;
546 int i;
547 size_t size;
548 HMODULE16 hModule;
549 NE_MODULE *pModule;
550 BYTE *buffer, *pData, *end;
551 OFSTRUCT *ofs;
553 if (mapping_size < sizeof(*mz_header)) return ERROR_BAD_FORMAT;
554 if (mz_header->e_magic != IMAGE_DOS_SIGNATURE) return ERROR_BAD_FORMAT;
555 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mapping + mz_header->e_lfanew);
556 if (mz_header->e_lfanew + sizeof(*ne_header) > mapping_size) return ERROR_BAD_FORMAT;
557 if (ne_header->ne_magic == IMAGE_NT_SIGNATURE) return 21; /* win32 exe */
558 if (ne_header->ne_magic == IMAGE_OS2_SIGNATURE_LX)
560 MESSAGE("Sorry, %s is an OS/2 linear executable (LX) file!\n", path);
561 return 12;
563 if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE) return ERROR_BAD_FORMAT;
565 /* We now have a valid NE header */
567 /* check to be able to fall back to loading OS/2 programs as DOS
568 * FIXME: should this check be reversed in order to be less strict?
569 * (only fail for OS/2 ne_exetyp 0x01 here?) */
570 if ((ne_header->ne_exetyp != 0x02 /* Windows */)
571 && (ne_header->ne_exetyp != 0x04) /* Windows 386 */)
572 return ERROR_BAD_FORMAT;
574 size = sizeof(NE_MODULE) +
575 /* segment table */
576 ne_header->ne_cseg * sizeof(SEGTABLEENTRY) +
577 /* resource table */
578 ne_header->ne_restab - ne_header->ne_rsrctab +
579 /* resident names table */
580 ne_header->ne_modtab - ne_header->ne_restab +
581 /* module ref table */
582 ne_header->ne_cmod * sizeof(WORD) +
583 /* imported names table */
584 ne_header->ne_enttab - ne_header->ne_imptab +
585 /* entry table length */
586 ne_header->ne_cbenttab +
587 /* entry table extra conversion space */
588 sizeof(ET_BUNDLE) +
589 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6) +
590 /* loaded file info */
591 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
593 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
594 if (!hModule)
596 ERR_(winediag)( "Failed to create module for %s, 16-bit LDT support may be missing.\n",
597 debugstr_a(path) );
598 return ERROR_BAD_FORMAT;
601 FarSetOwner16( hModule, hModule );
602 pModule = GlobalLock16( hModule );
603 memcpy( pModule, ne_header, sizeof(*ne_header) );
604 pModule->count = 0;
605 /* check programs for default minimal stack size */
606 if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE) && (pModule->ne_stack < 0x1400))
607 pModule->ne_stack = 0x1400;
609 pModule->self = hModule;
610 pModule->mapping = mapping;
611 pModule->mapping_size = mapping_size;
613 pData = (BYTE *)(pModule + 1);
615 /* Clear internal Wine flags in case they are set in the EXE file */
617 pModule->ne_flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
619 /* Get the segment table */
621 pModule->ne_segtab = pData - (BYTE *)pModule;
622 if (!(pSeg = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_segtab,
623 ne_header->ne_cseg * sizeof(struct ne_segment_table_entry_s) )))
624 goto failed;
625 for (i = ne_header->ne_cseg; i > 0; i--, pSeg++)
627 memcpy( pData, pSeg, sizeof(*pSeg) );
628 pData += sizeof(SEGTABLEENTRY);
631 /* Get the resource table */
633 if (ne_header->ne_rsrctab < ne_header->ne_restab)
635 pModule->ne_rsrctab = pData - (BYTE *)pModule;
636 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_rsrctab,
637 ne_header->ne_restab - ne_header->ne_rsrctab )) goto failed;
638 pData += ne_header->ne_restab - ne_header->ne_rsrctab;
640 else pModule->ne_rsrctab = 0; /* No resource table */
642 /* Get the resident names table */
644 pModule->ne_restab = pData - (BYTE *)pModule;
645 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_restab,
646 ne_header->ne_modtab - ne_header->ne_restab )) goto failed;
647 pData += ne_header->ne_modtab - ne_header->ne_restab;
649 /* Get the module references table */
651 if (ne_header->ne_cmod > 0)
653 pModule->ne_modtab = pData - (BYTE *)pModule;
654 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_modtab,
655 ne_header->ne_cmod * sizeof(WORD) )) goto failed;
656 pData += ne_header->ne_cmod * sizeof(WORD);
658 else pModule->ne_modtab = 0; /* No module references */
660 /* Get the imported names table */
662 pModule->ne_imptab = pData - (BYTE *)pModule;
663 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_imptab,
664 ne_header->ne_enttab - ne_header->ne_imptab )) goto failed;
665 pData += ne_header->ne_enttab - ne_header->ne_imptab;
667 /* Load entry table, convert it to the optimized version used by Windows */
669 pModule->ne_enttab = pData - (BYTE *)pModule;
670 if (!(ptr = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_enttab,
671 ne_header->ne_cbenttab ))) goto failed;
672 end = build_bundle_data( pModule, pData, ptr );
674 pData += ne_header->ne_cbenttab + sizeof(ET_BUNDLE) +
675 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6);
677 if (end > pData)
679 FIXME( "not enough space for entry table for %s\n", debugstr_a(path) );
680 goto failed;
683 /* Store the filename information */
685 pModule->fileinfo = pData - (BYTE *)pModule;
686 ofs = (OFSTRUCT *)pData;
687 ofs->cBytes = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path);
688 ofs->fFixedDisk = 1;
689 strcpy( ofs->szPathName, path );
690 pData += ofs->cBytes + 1;
692 /* Get the non-resident names table */
694 if (ne_header->ne_cbnrestab)
696 pModule->nrname_handle = GlobalAlloc16( 0, ne_header->ne_cbnrestab );
697 if (!pModule->nrname_handle) goto failed;
698 FarSetOwner16( pModule->nrname_handle, hModule );
699 buffer = GlobalLock16( pModule->nrname_handle );
700 if (!NE_READ_DATA( pModule, buffer, ne_header->ne_nrestab, ne_header->ne_cbnrestab ))
702 GlobalFree16( pModule->nrname_handle );
703 pModule->nrname_handle = 0;
706 else pModule->nrname_handle = 0;
708 /* Allocate a segment for the implicitly-loaded DLLs */
710 if (pModule->ne_cmod)
712 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
713 (pModule->ne_cmod+1)*sizeof(HMODULE16) );
714 if (!pModule->dlls_to_init)
716 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
717 goto failed;
719 FarSetOwner16( pModule->dlls_to_init, hModule );
721 else pModule->dlls_to_init = 0;
723 NE_RegisterModule( pModule );
724 return hModule;
726 failed:
727 GlobalFree16( hModule );
728 return ERROR_BAD_FORMAT;
732 /***********************************************************************
733 * NE_LoadDLLs
735 * Load all DLLs implicitly linked to a module.
737 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
739 int i;
740 WORD *pModRef = (WORD *)((char *)pModule + pModule->ne_modtab);
741 WORD *pDLLs = GlobalLock16( pModule->dlls_to_init );
743 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
745 char buffer[260], *p;
746 BYTE *pstr = (BYTE *)pModule + pModule->ne_imptab + *pModRef;
747 memcpy( buffer, pstr + 1, *pstr );
748 *(buffer + *pstr) = 0; /* terminate it */
750 TRACE("Loading '%s'\n", buffer );
751 if (!(*pModRef = GetModuleHandle16( buffer )))
753 /* If the DLL is not loaded yet, load it and store */
754 /* its handle in the list of DLLs to initialize. */
755 HMODULE16 hDLL;
757 /* Append .DLL (Windows >= 3.00) or .EXE (Windows < 3.00) to name if no extension present */
758 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
759 strcat( buffer, (GetExeVersion16() >= 0x0300) ? ".DLL" : ".EXE" );
761 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
763 /* FIXME: cleanup what was done */
765 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
766 buffer, *((BYTE*)pModule + pModule->ne_restab),
767 (char *)pModule + pModule->ne_restab + 1, hDLL );
768 return FALSE;
770 *pModRef = GetExePtr( hDLL );
771 *pDLLs++ = *pModRef;
773 else /* Increment the reference count of the DLL */
775 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
776 if (pOldDLL) pOldDLL->count++;
779 return TRUE;
783 /**********************************************************************
784 * NE_DoLoadModule
786 * Load first instance of NE module from file.
788 * pModule must point to a module structure prepared by build_module.
789 * This routine must never be called twice on a module.
791 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
793 /* Allocate the segments for this module */
795 if (!NE_CreateAllSegments( pModule ))
796 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
798 /* Load the referenced DLLs */
800 if (!NE_LoadDLLs( pModule ))
801 return ERROR_FILE_NOT_FOUND; /* 2 */
803 /* Load the segments */
805 NE_LoadAllSegments( pModule );
807 /* Make sure the usage count is 1 on the first loading of */
808 /* the module, even if it contains circular DLL references */
810 pModule->count = 1;
812 return NE_GetInstance( pModule );
815 /**********************************************************************
816 * NE_LoadModule
818 * Load first instance of NE module. (Note: caller is responsible for
819 * ensuring the module isn't already loaded!)
821 * If the module turns out to be an executable module, only a
822 * handle to a module stub is returned; this needs to be initialized
823 * by calling NE_DoLoadModule later, in the context of the newly
824 * created process.
826 * If lib_only is TRUE, however, the module is perforce treated
827 * like a DLL module, even if it is an executable module.
830 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
832 NE_MODULE *pModule;
833 HMODULE16 hModule;
834 HINSTANCE16 hInstance;
835 HFILE16 hFile;
836 OFSTRUCT ofs;
837 HANDLE mapping;
838 void *ptr;
839 MEMORY_BASIC_INFORMATION info;
841 /* Open file */
842 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
843 return ERROR_FILE_NOT_FOUND;
845 mapping = CreateFileMappingW( DosFileHandleToWin32Handle(hFile), NULL, PAGE_WRITECOPY, 0, 0, NULL );
846 _lclose16( hFile );
847 if (!mapping) return ERROR_BAD_FORMAT;
849 ptr = MapViewOfFile( mapping, FILE_MAP_COPY, 0, 0, 0 );
850 CloseHandle( mapping );
851 if (!ptr) return ERROR_BAD_FORMAT;
853 VirtualQuery( ptr, &info, sizeof(info) );
854 hModule = build_module( ptr, info.RegionSize, ofs.szPathName );
856 if (hModule < 32)
858 UnmapViewOfFile( ptr );
859 return hModule;
862 SNOOP16_RegisterDLL( hModule, ofs.szPathName );
863 NE_InitResourceHandler( hModule );
865 pModule = NE_GetPtr( hModule );
867 if ( !lib_only && !( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) )
868 return hModule;
870 hInstance = NE_DoLoadModule( pModule );
871 if ( hInstance < 32 )
873 /* cleanup ... */
874 NE_FreeModule( hModule, 0 );
877 return hInstance;
881 /***********************************************************************
882 * NE_DoLoadBuiltinModule
884 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
886 static HMODULE16 NE_DoLoadBuiltinModule( const IMAGE_DOS_HEADER *mz_header, const char *file_name,
887 HMODULE owner32 )
889 NE_MODULE *pModule;
890 HMODULE16 hModule;
891 HINSTANCE16 hInstance;
892 SIZE_T mapping_size = ~0UL; /* assume builtins don't contain invalid offsets... */
894 hModule = build_module( mz_header, mapping_size, file_name );
895 if (hModule < 32) return hModule;
896 pModule = GlobalLock16( hModule );
897 pModule->ne_flags |= NE_FFLAGS_BUILTIN;
898 pModule->owner32 = owner32;
900 /* fake the expected version the module should have according to the current Windows version */
901 pModule->ne_expver = MAKEWORD( NtCurrentTeb()->Peb->OSMajorVersion,
902 NtCurrentTeb()->Peb->OSMinorVersion );
904 hInstance = NE_DoLoadModule( pModule );
905 if (hInstance < 32) NE_FreeModule( hModule, 0 );
907 NE_InitResourceHandler( hModule );
909 if (pModule->ne_heap)
911 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1;
912 unsigned int size = pSeg->minsize + pModule->ne_heap;
913 if (size > 0xfffe) size = 0xfffe;
914 LocalInit16( GlobalHandleToSel16(pSeg->hSeg), pSeg->minsize, size );
917 patch_code_segment( pModule );
918 *(const void **)mz_header->e_res2 = ldt_copy->base;
920 return hInstance;
924 /**********************************************************************
925 * MODULE_LoadModule16
927 * Load a NE module in the order of the loadorder specification.
928 * The caller is responsible that the module is not loaded already.
931 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
933 HINSTANCE16 hinst = 2;
934 HMODULE16 hModule;
935 HMODULE mod32 = 0;
936 NE_MODULE *pModule;
937 const IMAGE_DOS_HEADER *descr = NULL;
938 const char *file_name = NULL;
939 char dllname[32];
940 const char *basename, *main_module, *p;
942 /* strip path information */
944 basename = libname;
945 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
946 if ((p = strrchr( basename, '\\' ))) basename = p + 1;
947 if ((p = strrchr( basename, '/' ))) basename = p + 1;
949 if (strlen(basename) < sizeof(dllname)-6)
951 DWORD count;
952 char *q;
954 ReleaseThunkLock( &count );
956 strcpy( dllname, basename );
957 q = strrchr( dllname, '.' );
958 if (!q) strcat( dllname, (GetExeVersion16() >= 0x0300) ? ".dll" : ".exe" );
959 for (q = dllname; *q; q++) if (*q >= 'A' && *q <= 'Z') *q += 32;
961 strcpy( q, "16" );
962 if ((mod32 = LoadLibraryA( dllname )))
964 if (!(descr = (void *)GetProcAddress( mod32, "__wine_spec_dos_header" )))
966 WARN( "loaded %s but does not contain a 16-bit module\n", debugstr_a(dllname) );
967 FreeLibrary( mod32 );
969 else
971 TRACE( "found %s with embedded 16-bit module\n", debugstr_a(dllname) );
972 file_name = basename;
974 /* if module has a 32-bit owner, match the load order of the owner */
975 if ((main_module = (void *)GetProcAddress( mod32, "__wine_spec_main_module" )))
977 LDR_DATA_TABLE_ENTRY *ldr;
978 HMODULE main_owner = LoadLibraryA( main_module );
980 if (!main_owner)
982 WARN( "couldn't load owner %s for 16-bit dll %s\n", main_module, dllname );
983 FreeLibrary( mod32 );
984 RestoreThunkLock( count );
985 return ERROR_FILE_NOT_FOUND;
987 /* check if module was loaded native */
988 if (LdrFindEntryForAddress( main_owner, &ldr ) || !(ldr->Flags & LDR_WINE_INTERNAL))
990 FreeLibrary( mod32 );
991 descr = NULL;
993 FreeLibrary( main_owner );
997 RestoreThunkLock( count );
999 /* loading the 32-bit library can have the side effect of loading the module */
1000 /* if so, simply incr the ref count and return the module */
1001 if (descr && (hModule = GetModuleHandle16( libname )))
1003 TRACE( "module %s already loaded by owner\n", libname );
1004 pModule = NE_GetPtr( hModule );
1005 if (pModule) pModule->count++;
1006 FreeLibrary( mod32 );
1007 return hModule;
1011 if (descr)
1013 TRACE("Trying built-in '%s'\n", libname);
1014 hinst = NE_DoLoadBuiltinModule( descr, file_name, mod32 );
1015 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : builtin\n", debugstr_a(file_name));
1016 else FreeLibrary( mod32 );
1018 else
1020 TRACE("Trying native dll '%s'\n", libname);
1021 hinst = NE_LoadModule(libname, lib_only);
1022 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : native\n", debugstr_a(libname));
1025 if (hinst > 32 && !implicit)
1027 hModule = GetModuleHandle16(libname);
1028 if(!hModule)
1030 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1031 libname, hinst);
1032 return ERROR_INVALID_HANDLE;
1035 pModule = NE_GetPtr(hModule);
1036 if(!pModule)
1038 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1039 libname, hinst);
1040 return ERROR_INVALID_HANDLE;
1043 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1046 * Call initialization routines for all loaded DLLs. Note that
1047 * when we load implicitly linked DLLs this will be done by InitTask().
1049 if(pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1051 NE_InitializeDLLs(hModule);
1052 NE_DllProcessAttach(hModule);
1054 else DOSMEM_InitDosMemory(); /* we will be running a 16-bit task, setup DOS memory */
1056 return hinst; /* The last error that occurred */
1060 /**********************************************************************
1061 * NE_CreateThread
1063 * Create the thread for a 16-bit module.
1065 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1067 HANDLE hThread;
1068 TDB *pTask;
1069 HTASK16 hTask;
1070 HINSTANCE16 instance = 0;
1072 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1073 return 0;
1075 /* Post event to start the task */
1076 PostEvent16( hTask );
1078 /* Wait until we get the instance handle */
1081 DirectedYield16( hTask );
1082 if (!IsTask16( hTask )) /* thread has died */
1084 DWORD exit_code;
1085 WaitForSingleObject( hThread, INFINITE );
1086 GetExitCodeThread( hThread, &exit_code );
1087 CloseHandle( hThread );
1088 return exit_code;
1090 if (!(pTask = GlobalLock16( hTask ))) break;
1091 instance = pTask->hInstance;
1092 GlobalUnlock16( hTask );
1093 } while (!instance);
1095 CloseHandle( hThread );
1096 return instance;
1100 /**********************************************************************
1101 * LoadModule (KERNEL.45)
1103 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1105 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1106 LOADPARAMS16 *params;
1107 HMODULE16 hModule;
1108 NE_MODULE *pModule;
1109 LPSTR cmdline;
1110 WORD cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
1112 if (name == NULL) return 0;
1114 TRACE("name %s, paramBlock %p\n", name, paramBlock);
1116 /* Load module */
1118 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1120 /* Special case: second instance of an already loaded NE module */
1122 if ( !( pModule = NE_GetPtr( hModule ) ) ) return ERROR_BAD_FORMAT;
1123 if ( pModule->module32 ) return (HINSTANCE16)21;
1125 /* Increment refcount */
1127 pModule->count++;
1129 else
1131 /* Main case: load first instance of NE module */
1133 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1134 return hModule;
1136 if ( !(pModule = NE_GetPtr( hModule )) )
1137 return ERROR_BAD_FORMAT;
1140 /* If library module, we just retrieve the instance handle */
1142 if ( ( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1143 return NE_GetInstance( pModule );
1146 * At this point, we need to create a new process.
1148 * pModule points either to an already loaded module, whose refcount
1149 * has already been incremented (to avoid having the module vanish
1150 * in the meantime), or else to a stub module which contains only header
1151 * information.
1153 params = paramBlock;
1154 if (params->showCmd)
1155 cmdShow = ((WORD *)MapSL( params->showCmd ))[1];
1156 cmdline = MapSL( params->cmdLine );
1157 return NE_CreateThread( pModule, cmdShow, cmdline );
1161 /**********************************************************************
1162 * NE_StartTask
1164 * Startup code for a new 16-bit task.
1166 DWORD NE_StartTask(void)
1168 TDB *pTask = TASK_GetCurrent();
1169 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1170 HINSTANCE16 hInstance, hPrevInstance;
1171 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1172 WORD sp;
1174 if ( pModule->count > 0 )
1176 /* Second instance of an already loaded NE module */
1177 /* Note that the refcount was already incremented by the parent */
1179 hPrevInstance = NE_GetInstance( pModule );
1181 if ( pModule->ne_autodata )
1182 if ( NE_CreateSegment( pModule, pModule->ne_autodata ) )
1183 NE_LoadSegment( pModule, pModule->ne_autodata );
1185 hInstance = NE_GetInstance( pModule );
1186 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->ne_autodata, hPrevInstance);
1189 else
1191 /* Load first instance of NE module */
1193 pModule->ne_flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1195 hInstance = NE_DoLoadModule( pModule );
1196 hPrevInstance = 0;
1199 if ( hInstance >= 32 )
1201 CONTEXT context;
1203 /* Enter instance handles into task struct */
1205 pTask->hInstance = hInstance;
1206 pTask->hPrevInstance = hPrevInstance;
1208 /* Use DGROUP for 16-bit stack */
1210 if (!(sp = OFFSETOF(pModule->ne_sssp)))
1211 sp = pSegTable[SELECTOROF(pModule->ne_sssp)-1].minsize + pModule->ne_stack;
1212 sp &= ~1;
1213 CURRENT_SS = GlobalHandleToSel16(hInstance);
1214 CURRENT_SP = sp - sizeof(STACK16FRAME);
1216 /* Registers at initialization must be:
1217 * ax zero
1218 * bx stack size in bytes
1219 * cx heap size in bytes
1220 * si previous app instance
1221 * di current app instance
1222 * bp zero
1223 * es selector to the PSP
1224 * ds dgroup of the application
1225 * ss stack selector
1226 * sp top of the stack
1228 memset( &context, 0, sizeof(context) );
1229 context.SegCs = GlobalHandleToSel16(pSegTable[SELECTOROF(pModule->ne_csip) - 1].hSeg);
1230 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1231 context.SegEs = pTask->hPDB;
1232 context.Eip = OFFSETOF(pModule->ne_csip);
1233 context.Ebx = pModule->ne_stack;
1234 context.Ecx = pModule->ne_heap;
1235 context.Edi = pTask->hInstance;
1236 context.Esi = pTask->hPrevInstance;
1238 /* Now call 16-bit entry point */
1240 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1241 context.SegCs, context.Eip, context.SegDs, CURRENT_SS, CURRENT_SP);
1243 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1244 ExitThread( LOWORD(context.Eax) );
1246 return hInstance; /* error code */
1249 /***********************************************************************
1250 * LoadLibrary (KERNEL.95)
1251 * LoadLibrary16 (KERNEL32.35)
1253 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1255 return LoadModule16(libname, (LPVOID)-1 );
1259 /**********************************************************************
1260 * MODULE_CallWEP
1262 * Call a DLL's WEP, allowing it to shut down.
1263 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1265 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1267 BOOL16 ret;
1268 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1269 if (!WEP) return FALSE;
1271 __TRY
1273 WORD args[1];
1274 DWORD dwRet;
1276 args[0] = WEP_FREE_DLL;
1277 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1278 ret = LOWORD(dwRet);
1280 __EXCEPT_PAGE_FAULT
1282 WARN("Page fault\n");
1283 ret = 0;
1285 __ENDTRY
1287 return ret;
1291 /**********************************************************************
1292 * NE_FreeModule
1294 * Implementation of FreeModule16().
1296 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1298 HMODULE16 *hPrevModule;
1299 NE_MODULE *pModule;
1300 HMODULE16 *pModRef;
1301 int i;
1303 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1304 hModule = pModule->self;
1306 TRACE("%04x count %d\n", hModule, pModule->count );
1308 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1309 else pModule->count = 0;
1311 if (call_wep && !(pModule->ne_flags & NE_FFLAGS_WIN32))
1313 /* Free the objects owned by the DLL module */
1314 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1316 if (pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1317 MODULE_CallWEP( hModule );
1318 else
1319 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1322 TRACE_(loaddll)("Unloaded module %s : %s\n", debugstr_a(NE_MODULE_NAME(pModule)),
1323 (pModule->ne_flags & NE_FFLAGS_BUILTIN) ? "builtin" : "native");
1325 /* Clear magic number just in case */
1327 pModule->ne_magic = pModule->self = 0;
1328 if (pModule->owner32) FreeLibrary( pModule->owner32 );
1329 else if (pModule->mapping) UnmapViewOfFile( pModule->mapping );
1331 /* Remove it from the linked list */
1333 hPrevModule = &hFirstModule;
1334 while (*hPrevModule && (*hPrevModule != hModule))
1336 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1338 if (*hPrevModule) *hPrevModule = pModule->next;
1340 /* Free the referenced modules */
1342 pModRef = (HMODULE16*)((char *)pModule + pModule->ne_modtab);
1343 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
1345 NE_FreeModule( *pModRef, call_wep );
1348 /* Free the module storage */
1350 GlobalFreeAll16( hModule );
1351 return TRUE;
1355 /**********************************************************************
1356 * FreeModule (KERNEL.46)
1358 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1360 return NE_FreeModule( hModule, TRUE );
1364 /***********************************************************************
1365 * FreeLibrary (KERNEL.96)
1366 * FreeLibrary16 (KERNEL32.36)
1368 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1370 TRACE("%04x\n", handle );
1371 FreeModule16( handle );
1375 /***********************************************************************
1376 * GetModuleHandle16 (KERNEL32.@)
1378 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1380 HMODULE16 hModule;
1381 LPSTR s;
1382 BYTE len, *name_table;
1383 char tmpstr[MAX_PATH];
1384 NE_MODULE *pModule;
1386 TRACE("(%s)\n", name);
1388 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1390 len = strlen(name);
1391 if (!len) return 0;
1393 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1395 /* If 'name' matches exactly the module name of a module:
1396 * Return its handle.
1398 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1400 pModule = NE_GetPtr( hModule );
1401 if (!pModule) break;
1402 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1404 name_table = (BYTE *)pModule + pModule->ne_restab;
1405 if ((*name_table == len) && !strncmp(name, (char*) name_table+1, len))
1406 return hModule;
1409 /* If uppercased 'name' matches exactly the module name of a module:
1410 * Return its handle
1412 for (s = tmpstr; *s; s++) *s = RtlUpperChar(*s);
1414 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1416 pModule = NE_GetPtr( hModule );
1417 if (!pModule) break;
1418 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1420 name_table = (BYTE *)pModule + pModule->ne_restab;
1421 /* FIXME: the _strnicmp is WRONG. It should not be case insensitive,
1422 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1423 * lowercased module names, but try to load uppercase DLLs, so this
1424 * 'i' compare is just a quickfix until the loader handles that
1425 * correctly. -MM 990705
1427 if ((*name_table == len) && !_strnicmp(tmpstr, (const char*)name_table+1, len))
1428 return hModule;
1431 /* If the base filename of 'name' matches the base filename of the module
1432 * filename of some module (case-insensitive compare):
1433 * Return its handle.
1436 /* basename: search backwards in passed name to \ / or : */
1437 s = tmpstr + strlen(tmpstr);
1438 while (s > tmpstr)
1440 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1441 break;
1442 s--;
1445 /* search this in loaded filename list */
1446 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1448 char *loadedfn;
1449 OFSTRUCT *ofs;
1451 pModule = NE_GetPtr( hModule );
1452 if (!pModule) break;
1453 if (!pModule->fileinfo) continue;
1454 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1456 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1457 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1458 /* basename: search backwards in pathname to \ / or : */
1459 while (loadedfn > (char*)ofs->szPathName)
1461 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1462 break;
1463 loadedfn--;
1465 /* case insensitive compare ... */
1466 if (!stricmp(loadedfn, s))
1467 return hModule;
1469 return 0;
1473 /**********************************************************************
1474 * GetModuleName (KERNEL.27)
1476 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1478 NE_MODULE *pModule;
1479 BYTE *p;
1481 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1482 p = (BYTE *)pModule + pModule->ne_restab;
1483 if (count > *p) count = *p + 1;
1484 if (count > 0)
1486 memcpy( buf, p + 1, count - 1 );
1487 buf[count-1] = '\0';
1489 return TRUE;
1493 /**********************************************************************
1494 * GetModuleFileName (KERNEL.49)
1496 * See also: GetModuleFileNameA
1498 * This function returns short paths when the modules version field is < 4.0).
1500 * Even if invoked by second instance of a program,
1501 * it still returns path of first one.
1503 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1504 INT16 nSize )
1506 NE_MODULE *pModule;
1508 /* Win95 does not query hModule if set to 0 !
1509 * Is this wrong or maybe Win3.1 only ? */
1510 if (!hModule) hModule = GetCurrentTask();
1512 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1513 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1514 if (pModule->ne_expver < 0x400)
1515 GetShortPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1516 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1517 return strlen(lpFileName);
1521 /**********************************************************************
1522 * GetModuleUsage (KERNEL.48)
1524 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1526 NE_MODULE *pModule = NE_GetPtr( hModule );
1527 return pModule ? pModule->count : 0;
1531 /**********************************************************************
1532 * GetExpWinVer (KERNEL.167)
1534 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1536 NE_MODULE *pModule = NE_GetPtr( hModule );
1537 if ( !pModule ) return 0;
1538 return pModule->ne_expver;
1542 /***********************************************************************
1543 * WinExec (KERNEL.166)
1545 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1547 LPCSTR p, args = NULL;
1548 LPCSTR name_beg, name_end;
1549 LPSTR name, cmdline;
1550 int arglen;
1551 HINSTANCE16 ret;
1552 char buffer[MAX_PATH];
1553 LOADPARAMS16 params;
1554 WORD showCmd[2];
1556 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1558 name_beg = lpCmdLine+1;
1559 p = strchr ( lpCmdLine+1, '"' );
1560 if (p)
1562 name_end = p;
1563 args = strchr ( p, ' ' );
1565 else /* yes, even valid with trailing '"' missing */
1566 name_end = lpCmdLine+strlen(lpCmdLine);
1568 else
1570 name_beg = lpCmdLine;
1571 args = strchr( lpCmdLine, ' ' );
1572 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1575 if ((name_beg == lpCmdLine) && (!args))
1576 { /* just use the original cmdline string as file name */
1577 name = (LPSTR)lpCmdLine;
1579 else
1581 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1582 return ERROR_NOT_ENOUGH_MEMORY;
1583 memcpy( name, name_beg, name_end - name_beg );
1584 name[name_end - name_beg] = '\0';
1587 if (args)
1589 args++;
1590 arglen = strlen(args);
1591 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1592 cmdline[0] = (BYTE)arglen;
1593 strcpy( cmdline + 1, args );
1595 else
1597 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1598 cmdline[0] = cmdline[1] = 0;
1601 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1603 showCmd[0] = 2;
1604 showCmd[1] = nCmdShow;
1606 params.hEnvironment = 0;
1607 params.cmdLine = MapLS( cmdline );
1608 params.showCmd = MapLS( showCmd );
1609 params.reserved = 0;
1611 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1613 ret = LoadModule16( buffer, &params );
1615 else if (!contains_path( name )) /* try 16-bit builtin */
1617 lstrcpynA( buffer, name, sizeof(buffer) );
1618 if (strlen( buffer ) < sizeof(buffer) - 4 && !strchr( buffer, '.' )) strcat( buffer, ".exe" );
1619 ret = LoadModule16( buffer, &params );
1620 if (ret == ERROR_FILE_NOT_FOUND) ret = 21; /* it might be a 32-bit builtin too */
1622 else ret = ERROR_FILE_NOT_FOUND;
1624 UnMapLS( params.cmdLine );
1625 UnMapLS( params.showCmd );
1627 HeapFree( GetProcessHeap(), 0, cmdline );
1628 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1630 if (ret == 21 || ret == ERROR_BAD_FORMAT) /* 32-bit module or unknown executable*/
1632 LOADPARAMS16 params;
1633 WORD showCmd[2];
1634 showCmd[0] = 2;
1635 showCmd[1] = nCmdShow;
1637 arglen = strlen( lpCmdLine );
1638 cmdline = HeapAlloc( GetProcessHeap(), 0, arglen + 1 );
1639 cmdline[0] = (BYTE)arglen;
1640 memcpy( cmdline + 1, lpCmdLine, arglen );
1642 params.hEnvironment = 0;
1643 params.cmdLine = MapLS( cmdline );
1644 params.showCmd = MapLS( showCmd );
1645 params.reserved = 0;
1647 ret = LoadModule16( "winoldap.mod", &params );
1648 UnMapLS( params.cmdLine );
1649 UnMapLS( params.showCmd );
1651 return ret;
1654 /***********************************************************************
1655 * GetProcAddress (KERNEL.50)
1657 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1659 WORD ordinal;
1660 FARPROC16 ret;
1662 if (!hModule) hModule = GetCurrentTask();
1663 hModule = GetExePtr( hModule );
1665 if (HIWORD(name) != 0)
1667 ordinal = NE_GetOrdinal( hModule, name );
1668 TRACE("%04x '%s'\n", hModule, name );
1670 else
1672 ordinal = LOWORD(name);
1673 TRACE("%04x %04x\n", hModule, ordinal );
1675 if (!ordinal) return NULL;
1677 ret = NE_GetEntryPoint( hModule, ordinal );
1679 TRACE("returning %p\n", ret );
1680 return ret;
1684 /***************************************************************************
1685 * HasGPHandler (KERNEL.338)
1687 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1689 HMODULE16 hModule;
1690 int gpOrdinal;
1691 SEGPTR gpPtr;
1692 GPHANDLERDEF *gpHandler;
1694 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1695 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1696 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1697 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1698 && (gpHandler = MapSL( gpPtr )) != NULL )
1700 while (gpHandler->selector)
1702 if ( SELECTOROF(address) == gpHandler->selector
1703 && OFFSETOF(address) >= gpHandler->rangeStart
1704 && OFFSETOF(address) < gpHandler->rangeEnd )
1705 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1706 gpHandler++;
1710 return 0;
1714 /**********************************************************************
1715 * GetModuleHandle (KERNEL.47)
1717 * Find a module from a module name.
1719 * NOTE: The current implementation works the same way the Windows 95 one
1720 * does. Do not try to 'fix' it, fix the callers.
1721 * + It does not do ANY extension handling (except that strange .EXE bit)!
1722 * + It does not care about paths, just about basenames. (same as Windows)
1724 * RETURNS
1725 * LOWORD:
1726 * the win16 module handle if found
1727 * 0 if not
1728 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1729 * Always hFirstModule
1731 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1733 if (HIWORD(name) == 0)
1734 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1735 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1738 /**********************************************************************
1739 * NE_GetModuleByFilename
1741 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1743 HMODULE16 hModule;
1744 LPSTR s, p;
1745 BYTE len, *name_table;
1746 char tmpstr[MAX_PATH];
1747 NE_MODULE *pModule;
1749 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1751 /* If the base filename of 'name' matches the base filename of the module
1752 * filename of some module (case-insensitive compare):
1753 * Return its handle.
1756 /* basename: search backwards in passed name to \ / or : */
1757 s = tmpstr + strlen(tmpstr);
1758 while (s > tmpstr)
1760 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1761 break;
1762 s--;
1765 /* search this in loaded filename list */
1766 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1768 char *loadedfn;
1769 OFSTRUCT *ofs;
1771 pModule = NE_GetPtr( hModule );
1772 if (!pModule) break;
1773 if (!pModule->fileinfo) continue;
1774 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1776 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1777 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1778 /* basename: search backwards in pathname to \ / or : */
1779 while (loadedfn > (char*)ofs->szPathName)
1781 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1782 break;
1783 loadedfn--;
1785 /* case insensitive compare ... */
1786 if (!stricmp(loadedfn, s))
1787 return hModule;
1789 /* If basename (without ext) matches the module name of a module:
1790 * Return its handle.
1793 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1794 len = strlen(s);
1796 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1798 pModule = NE_GetPtr( hModule );
1799 if (!pModule) break;
1800 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1802 name_table = (BYTE *)pModule + pModule->ne_restab;
1803 if ((*name_table == len) && !_strnicmp(s, (const char*)name_table+1, len))
1804 return hModule;
1807 return 0;
1810 /***********************************************************************
1811 * GetProcAddress16 (KERNEL32.37)
1812 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1814 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1816 if (!hModule) return 0;
1817 if (HIWORD(hModule))
1819 WARN("hModule is Win32 handle (%p)\n", hModule );
1820 return 0;
1822 return GetProcAddress16( LOWORD(hModule), name );
1825 /***************************************************************************
1826 * IsRomModule (KERNEL.323)
1828 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1830 return FALSE;
1833 /***************************************************************************
1834 * IsRomFile (KERNEL.326)
1836 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1838 return FALSE;
1841 /***********************************************************************
1842 * create_dummy_module
1844 * Create a dummy NE module for Win32 or Winelib.
1846 static HMODULE16 create_dummy_module( HMODULE module32 )
1848 HMODULE16 hModule;
1849 NE_MODULE *pModule;
1850 SEGTABLEENTRY *pSegment;
1851 char *pStr;
1852 unsigned int len;
1853 const char *basename, *s;
1854 OFSTRUCT *ofs;
1855 int of_size, size;
1856 char filename[MAX_PATH];
1857 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
1859 if (!nt) return ERROR_BAD_FORMAT;
1861 /* Extract base filename */
1862 len = GetModuleFileNameA( module32, filename, sizeof(filename) );
1863 if (!len || len >= sizeof(filename)) return ERROR_BAD_FORMAT;
1864 basename = strrchr(filename, '\\');
1865 if (!basename) basename = filename;
1866 else basename++;
1867 len = strlen(basename);
1868 if ((s = strchr(basename, '.'))) len = s - basename;
1870 /* Allocate module */
1871 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
1872 + strlen(filename) + 1;
1873 size = sizeof(NE_MODULE) +
1874 /* loaded file info */
1875 ((of_size + 3) & ~3) +
1876 /* segment table: DS,CS */
1877 2 * sizeof(SEGTABLEENTRY) +
1878 /* name table */
1879 len + 2 +
1880 /* several empty tables */
1883 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
1884 if (!hModule) return ERROR_BAD_FORMAT;
1886 FarSetOwner16( hModule, hModule );
1887 pModule = GlobalLock16( hModule );
1889 /* Set all used entries */
1890 pModule->ne_magic = IMAGE_OS2_SIGNATURE;
1891 pModule->count = 1;
1892 pModule->next = 0;
1893 pModule->ne_flags = NE_FFLAGS_WIN32;
1894 pModule->ne_autodata = 0;
1895 pModule->ne_sssp = MAKESEGPTR( 0, 1 );
1896 pModule->ne_csip = MAKESEGPTR( 0, 2 );
1897 pModule->ne_heap = 0;
1898 pModule->ne_stack = 0;
1899 pModule->ne_cseg = 2;
1900 pModule->ne_cmod = 0;
1901 pModule->ne_cbnrestab = 0;
1902 pModule->fileinfo = sizeof(NE_MODULE);
1903 pModule->ne_exetyp = NE_OSFLAGS_WINDOWS;
1904 pModule->self = hModule;
1905 pModule->module32 = module32;
1907 /* Set version and flags */
1908 pModule->ne_expver = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
1909 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
1910 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1911 pModule->ne_flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
1913 /* Set loaded file information */
1914 ofs = (OFSTRUCT *)(pModule + 1);
1915 memset( ofs, 0, of_size );
1916 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
1917 strcpy( ofs->szPathName, filename );
1919 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
1920 pModule->ne_segtab = (char *)pSegment - (char *)pModule;
1921 /* Data segment */
1922 pSegment->size = 0;
1923 pSegment->flags = NE_SEGFLAGS_DATA;
1924 pSegment->minsize = 0x1000;
1925 pSegment++;
1926 /* Code segment */
1927 pSegment->flags = 0;
1928 pSegment++;
1930 /* Module name */
1931 pStr = (char *)pSegment;
1932 pModule->ne_restab = pStr - (char *)pModule;
1933 *pStr = len;
1934 lstrcpynA( pStr+1, basename, len+1 );
1935 pStr += len+2;
1937 /* All tables zero terminated */
1938 pModule->ne_rsrctab = pModule->ne_imptab = pModule->ne_enttab = pStr - (char *)pModule;
1940 NE_RegisterModule( pModule );
1941 pModule->owner32 = LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
1942 return hModule;
1945 /***********************************************************************
1946 * PrivateLoadLibrary (KERNEL32.@)
1948 * FIXME: rough guesswork, don't know what "Private" means
1950 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1952 return LoadLibrary16(libname);
1955 /***********************************************************************
1956 * PrivateFreeLibrary (KERNEL32.@)
1958 * FIXME: rough guesswork, don't know what "Private" means
1960 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1962 FreeLibrary16(handle);
1965 /***********************************************************************
1966 * LoadLibrary32 (KERNEL.452)
1967 * LoadSystemLibrary32 (KERNEL.482)
1969 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1971 HMODULE hModule;
1972 DWORD count;
1974 ReleaseThunkLock( &count );
1975 hModule = LoadLibraryA( libname );
1976 RestoreThunkLock( count );
1977 return hModule;
1980 /***************************************************************************
1981 * MapHModuleLS (KERNEL32.@)
1983 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
1985 HMODULE16 ret;
1986 NE_MODULE *pModule;
1988 if (!hmod)
1989 return TASK_GetCurrent()->hInstance;
1990 if (!HIWORD(hmod))
1991 return LOWORD(hmod); /* we already have a 16 bit module handle */
1992 pModule = GlobalLock16(hFirstModule);
1993 while (pModule) {
1994 if (pModule->module32 == hmod)
1995 return pModule->self;
1996 pModule = GlobalLock16(pModule->next);
1998 if ((ret = create_dummy_module( hmod )) < 32)
2000 SetLastError(ret);
2001 ret = 0;
2003 return ret;
2006 /***************************************************************************
2007 * MapHModuleSL (KERNEL32.@)
2009 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2011 NE_MODULE *pModule;
2013 if (!hmod) {
2014 TDB *pTask = TASK_GetCurrent();
2015 hmod = pTask->hModule;
2017 pModule = GlobalLock16(hmod);
2018 if ((pModule->ne_magic != IMAGE_OS2_SIGNATURE) || !(pModule->ne_flags & NE_FFLAGS_WIN32))
2019 return 0;
2020 return pModule->module32;
2023 /***************************************************************************
2024 * MapHInstLS (KERNEL.472)
2026 void WINAPI MapHInstLS16( CONTEXT *context )
2028 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2031 /***************************************************************************
2032 * MapHInstSL (KERNEL.473)
2034 void WINAPI MapHInstSL16( CONTEXT *context )
2036 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2039 /***************************************************************************
2040 * MapHInstLS (KERNEL32.@)
2042 __ASM_STDCALL_FUNC( MapHInstLS, 0,
2043 "pushl %eax\n\t"
2044 "call " __ASM_STDCALL("MapHModuleLS",4) "\n\t"
2045 "ret" )
2047 /***************************************************************************
2048 * MapHInstSL (KERNEL32.@)
2050 __ASM_STDCALL_FUNC( MapHInstSL, 0,
2051 "pushl %eax\n\t"
2052 "call " __ASM_STDCALL("MapHModuleSL",4) "\n\t"
2053 "ret" )
2055 /***************************************************************************
2056 * MapHInstLS_PN (KERNEL32.@)
2058 __ASM_STDCALL_FUNC( MapHInstLS_PN, 0,
2059 "testl %eax,%eax\n\t"
2060 "jz 1f\n\t"
2061 "pushl %eax\n\t"
2062 "call " __ASM_STDCALL("MapHModuleLS",4) "\n"
2063 "1:\tret" )
2065 /***************************************************************************
2066 * MapHInstSL_PN (KERNEL32.@)
2068 __ASM_STDCALL_FUNC( MapHInstSL_PN, 0,
2069 "andl $0xffff,%eax\n\t"
2070 "jz 1f\n\t"
2071 "pushl %eax\n\t"
2072 "call " __ASM_STDCALL("MapHModuleSL",4) "\n"
2073 "1:\tret" )