d3dxof: Enable referencing objects defined in current top-level object.
[wine/multimedia.git] / dlls / krnl386.exe16 / ne_module.c
blob08ed94cc9f7c263e17459ca40627d8b9496fe8ed
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 "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <fcntl.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <ctype.h>
35 #include "windef.h"
36 #include "wine/winbase16.h"
37 #include "wownt32.h"
38 #include "winternl.h"
39 #include "kernel16_private.h"
40 #include "wine/exception.h"
41 #include "wine/debug.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(module);
44 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
45 WINE_DECLARE_DEBUG_CHANNEL(relay);
47 #include "pshpack1.h"
48 typedef struct _GPHANDLERDEF
50 WORD selector;
51 WORD rangeStart;
52 WORD rangeEnd;
53 WORD handler;
54 } GPHANDLERDEF;
55 #include "poppack.h"
58 * Segment table entry
60 struct ne_segment_table_entry_s
62 WORD seg_data_offset; /* Sector offset of segment data */
63 WORD seg_data_length; /* Length of segment data */
64 WORD seg_flags; /* Flags associated with this segment */
65 WORD min_alloc; /* Minimum allocation size for this */
68 #define hFirstModule (pThhook->hExeHead)
70 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
71 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
73 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
75 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
78 /* patch all the flat cs references of the code segment if necessary */
79 static inline void patch_code_segment( NE_MODULE *pModule )
81 int i;
82 CALLFROM16 *call;
83 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule );
85 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
86 if (!(pSeg->flags & NE_SEGFLAGS_DATA)) break; /* found the code segment */
88 call = GlobalLock16( pSeg->hSeg );
90 /* patch glue code address and code selector */
91 for (i = 0; call[i].pushl == 0x68; i++)
93 if (call[i].ret[0] == 0xca66 || call[i].ret[0] == 0xcb66) /* register entry point? */
94 call[i].glue = __wine_call_from_16_regs;
95 else
96 call[i].glue = __wine_call_from_16;
97 call[i].flatcs = wine_get_cs();
100 if (TRACE_ON(relay)) /* patch relay functions to all point to relay_call_from_16 */
101 for (i = 0; call[i].pushl == 0x68; i++) call[i].relay = relay_call_from_16;
105 /***********************************************************************
106 * contains_path
108 static inline int contains_path( LPCSTR name )
110 return ((*name && (name[1] == ':')) || strchr(name, '/') || strchr(name, '\\'));
114 /***********************************************************************
115 * NE_strcasecmp
117 * locale-independent case conversion for module lookups
119 static int NE_strcasecmp( const char *str1, const char *str2 )
121 int ret = 0;
122 for ( ; ; str1++, str2++)
123 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
124 return ret;
128 /***********************************************************************
129 * NE_strncasecmp
131 * locale-independent case conversion for module lookups
133 static int NE_strncasecmp( const char *str1, const char *str2, int len )
135 int ret = 0;
136 for ( ; len > 0; len--, str1++, str2++)
137 if ((ret = RtlUpperChar(*str1) - RtlUpperChar(*str2)) || !*str1) break;
138 return ret;
142 /***********************************************************************
143 * NE_GetPtr
145 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
147 return GlobalLock16( GetExePtr(hModule) );
151 /**********************************************************************
152 * NE_RegisterModule
154 static void NE_RegisterModule( NE_MODULE *pModule )
156 pModule->next = hFirstModule;
157 hFirstModule = pModule->self;
161 /***********************************************************************
162 * NE_DumpModule
164 void NE_DumpModule( HMODULE16 hModule )
166 int i, ordinal;
167 SEGTABLEENTRY *pSeg;
168 BYTE *pstr;
169 WORD *pword;
170 NE_MODULE *pModule;
171 ET_BUNDLE *bundle;
172 ET_ENTRY *entry;
174 if (!(pModule = NE_GetPtr( hModule )))
176 ERR( "**** %04x is not a module handle\n", hModule );
177 return;
180 /* Dump the module info */
181 TRACE( "---\n" );
182 TRACE( "Module %04x:\n", hModule );
183 TRACE( "count=%d flags=%04x heap=%d stack=%d\n",
184 pModule->count, pModule->ne_flags,
185 pModule->ne_heap, pModule->ne_stack );
186 TRACE( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
187 SELECTOROF(pModule->ne_csip), OFFSETOF(pModule->ne_csip),
188 SELECTOROF(pModule->ne_sssp), OFFSETOF(pModule->ne_sssp),
189 pModule->ne_autodata, pModule->ne_cseg, pModule->ne_cmod );
190 TRACE( "os_flags=%d swap_area=%d version=%04x\n",
191 pModule->ne_exetyp, pModule->ne_swaparea, pModule->ne_expver );
192 if (pModule->ne_flags & NE_FFLAGS_WIN32)
193 TRACE( "PE module=%p\n", pModule->module32 );
195 /* Dump the file info */
196 TRACE( "---\n" );
197 TRACE( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
199 /* Dump the segment table */
200 TRACE( "---\n" );
201 TRACE( "Segment table:\n" );
202 pSeg = NE_SEG_TABLE( pModule );
203 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
204 TRACE( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
205 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
206 pSeg->minsize, pSeg->hSeg );
208 /* Dump the resource table */
209 TRACE( "---\n" );
210 TRACE( "Resource table:\n" );
211 if (pModule->ne_rsrctab)
213 pword = (WORD *)((BYTE *)pModule + pModule->ne_rsrctab);
214 TRACE( "Alignment: %d\n", *pword++ );
215 while (*pword)
217 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
218 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
219 TRACE( "id=%04x count=%d\n", ptr->type_id, ptr->count );
220 for (i = 0; i < ptr->count; i++, pname++)
221 TRACE( "offset=%d len=%d id=%04x\n",
222 pname->offset, pname->length, pname->id );
223 pword = (WORD *)pname;
226 else TRACE( "None\n" );
228 /* Dump the resident name table */
229 TRACE( "---\n" );
230 TRACE( "Resident-name table:\n" );
231 pstr = (BYTE*) pModule + pModule->ne_restab;
232 while (*pstr)
234 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
235 *(WORD *)(pstr + *pstr + 1) );
236 pstr += *pstr + 1 + sizeof(WORD);
239 /* Dump the module reference table */
240 TRACE( "---\n" );
241 TRACE( "Module ref table:\n" );
242 if (pModule->ne_modtab)
244 pword = (WORD *)((BYTE *)pModule + pModule->ne_modtab);
245 for (i = 0; i < pModule->ne_cmod; i++, pword++)
247 char name[10];
248 GetModuleName16( *pword, name, sizeof(name) );
249 TRACE( "%d: %04x -> '%s'\n", i, *pword, name );
252 else TRACE( "None\n" );
254 /* Dump the entry table */
255 TRACE( "---\n" );
256 TRACE( "Entry table:\n" );
257 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->ne_enttab);
258 do {
259 entry = (ET_ENTRY *)((BYTE *)bundle+6);
260 TRACE( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
261 ordinal = bundle->first;
262 while (ordinal < bundle->last)
264 if (entry->type == 0xff)
265 TRACE("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
266 else
267 TRACE("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
268 entry++;
270 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
272 /* Dump the non-resident names table */
273 TRACE( "---\n" );
274 TRACE( "Non-resident names table:\n" );
275 if (pModule->nrname_handle)
277 pstr = GlobalLock16( pModule->nrname_handle );
278 while (*pstr)
280 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
281 *(WORD *)(pstr + *pstr + 1) );
282 pstr += *pstr + 1 + sizeof(WORD);
285 TRACE( "\n" );
289 /***********************************************************************
290 * NE_WalkModules
292 * Walk the module list and print the modules.
294 void NE_WalkModules(void)
296 HMODULE16 hModule = hFirstModule;
297 MESSAGE( "Module Flags Name\n" );
298 while (hModule)
300 NE_MODULE *pModule = NE_GetPtr( hModule );
301 if (!pModule)
303 MESSAGE( "Bad module %04x in list\n", hModule );
304 return;
306 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->ne_flags,
307 *((char *)pModule + pModule->ne_restab),
308 (char *)pModule + pModule->ne_restab + 1 );
309 hModule = pModule->next;
314 /***********************************************************************
315 * NE_InitResourceHandler
317 * Fill in 'resloader' fields in the resource table.
319 static void NE_InitResourceHandler( HMODULE16 hModule )
321 static FARPROC16 proc;
323 NE_TYPEINFO *pTypeInfo;
324 NE_MODULE *pModule;
326 if (!(pModule = NE_GetPtr( hModule )) || !pModule->ne_rsrctab) return;
328 TRACE("InitResourceHandler[%04x]\n", hModule );
330 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
332 pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->ne_rsrctab + 2);
333 while(pTypeInfo->type_id)
335 memcpy_unaligned( &pTypeInfo->resloader, &proc, sizeof(FARPROC16) );
336 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
341 /***********************************************************************
342 * NE_GetOrdinal
344 * Lookup the ordinal for a given name.
346 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
348 char buffer[256], *p;
349 BYTE *cpnt;
350 BYTE len;
351 NE_MODULE *pModule;
353 if (!(pModule = NE_GetPtr( hModule ))) return 0;
354 if (pModule->ne_flags & NE_FFLAGS_WIN32) return 0;
356 TRACE("(%04x,'%s')\n", hModule, name );
358 /* First handle names of the form '#xxxx' */
360 if (name[0] == '#') return atoi( name + 1 );
362 /* Now copy and uppercase the string */
364 strcpy( buffer, name );
365 for (p = buffer; *p; p++) *p = RtlUpperChar(*p);
366 len = p - buffer;
368 /* First search the resident names */
370 cpnt = (BYTE *)pModule + pModule->ne_restab;
372 /* Skip the first entry (module name) */
373 cpnt += *cpnt + 1 + sizeof(WORD);
374 while (*cpnt)
376 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
378 WORD ordinal;
379 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
380 TRACE(" Found: ordinal=%d\n", ordinal );
381 return ordinal;
383 cpnt += *cpnt + 1 + sizeof(WORD);
386 /* Now search the non-resident names table */
388 if (!pModule->nrname_handle) return 0; /* No non-resident table */
389 cpnt = GlobalLock16( pModule->nrname_handle );
391 /* Skip the first entry (module description string) */
392 cpnt += *cpnt + 1 + sizeof(WORD);
393 while (*cpnt)
395 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
397 WORD ordinal;
398 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
399 TRACE(" Found: ordinal=%d\n", ordinal );
400 return ordinal;
402 cpnt += *cpnt + 1 + sizeof(WORD);
404 return 0;
408 /***********************************************************************
409 * NE_GetEntryPoint
411 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
413 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
416 /***********************************************************************
417 * NE_GetEntryPointEx
419 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
421 NE_MODULE *pModule;
422 WORD sel, offset, i;
424 ET_ENTRY *entry;
425 ET_BUNDLE *bundle;
427 if (!(pModule = NE_GetPtr( hModule ))) return 0;
428 assert( !(pModule->ne_flags & NE_FFLAGS_WIN32) );
430 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
431 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
433 if (!(bundle->next))
434 return 0;
435 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
438 entry = (ET_ENTRY *)((BYTE *)bundle+6);
439 for (i=0; i < (ordinal - bundle->first - 1); i++)
440 entry++;
442 sel = entry->segnum;
443 memcpy( &offset, &entry->offs, sizeof(WORD) );
445 if (sel == 0xfe) sel = 0xffff; /* constant entry */
446 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
447 if (sel==0xffff)
448 return (FARPROC16)MAKESEGPTR( sel, offset );
449 if (!snoop)
450 return (FARPROC16)MAKESEGPTR( sel, offset );
451 else
452 return SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
456 /***********************************************************************
457 * EntryAddrProc (KERNEL.667) Wine-specific export
459 * Return the entry point for a given ordinal.
461 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
463 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
464 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
465 return ret;
468 /***********************************************************************
469 * NE_SetEntryPoint
471 * Change the value of an entry point. Use with caution!
472 * It can only change the offset value, not the selector.
474 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
476 NE_MODULE *pModule;
477 ET_ENTRY *entry;
478 ET_BUNDLE *bundle;
479 int i;
481 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
482 assert( !(pModule->ne_flags & NE_FFLAGS_WIN32) );
484 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
485 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
487 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
488 if (!(bundle->next)) return 0;
491 entry = (ET_ENTRY *)((BYTE *)bundle+6);
492 for (i=0; i < (ordinal - bundle->first - 1); i++)
493 entry++;
495 memcpy( &entry->offs, &offset, sizeof(WORD) );
496 return TRUE;
500 /***********************************************************************
501 * build_bundle_data
503 * Build the entry table bundle data from the on-disk format. Helper for build_module.
505 static void *build_bundle_data( NE_MODULE *pModule, void *dest, const BYTE *table )
507 ET_BUNDLE *oldbundle, *bundle = dest;
508 ET_ENTRY *entry;
509 BYTE nr_entries, type;
511 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
512 entry = (ET_ENTRY *)((BYTE *)bundle+6);
514 while ((nr_entries = *table++))
516 if ((type = *table++))
518 bundle->last += nr_entries;
519 if (type == 0xff)
521 while (nr_entries--)
523 entry->type = type;
524 entry->flags = *table++;
525 table += sizeof(WORD);
526 entry->segnum = *table++;
527 entry->offs = *(const WORD *)table;
528 table += sizeof(WORD);
529 entry++;
532 else
534 while (nr_entries--)
536 entry->type = type;
537 entry->flags = *table++;
538 entry->segnum = type;
539 entry->offs = *(const WORD *)table;
540 table += sizeof(WORD);
541 entry++;
545 else
547 if (bundle->first == bundle->last)
549 bundle->first += nr_entries;
550 bundle->last += nr_entries;
552 else
554 oldbundle = bundle;
555 oldbundle->next = (char *)entry - (char *)pModule;
556 bundle = (ET_BUNDLE *)entry;
557 bundle->first = bundle->last = oldbundle->last + nr_entries;
558 bundle->next = 0;
559 entry = (ET_ENTRY*)(((BYTE*)entry)+sizeof(ET_BUNDLE));
563 return entry;
567 /***********************************************************************
568 * build_module
570 * Build the in-memory module from the on-disk data.
572 static HMODULE16 build_module( const void *mapping, SIZE_T mapping_size, LPCSTR path )
574 const IMAGE_DOS_HEADER *mz_header = mapping;
575 const IMAGE_OS2_HEADER *ne_header;
576 const struct ne_segment_table_entry_s *pSeg;
577 const void *ptr;
578 int i;
579 size_t size;
580 HMODULE16 hModule;
581 NE_MODULE *pModule;
582 BYTE *buffer, *pData, *end;
583 OFSTRUCT *ofs;
585 if (mapping_size < sizeof(*mz_header)) return ERROR_BAD_FORMAT;
586 if (mz_header->e_magic != IMAGE_DOS_SIGNATURE) return ERROR_BAD_FORMAT;
587 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mapping + mz_header->e_lfanew);
588 if (mz_header->e_lfanew + sizeof(*ne_header) > mapping_size) return ERROR_BAD_FORMAT;
589 if (ne_header->ne_magic == IMAGE_NT_SIGNATURE) return 21; /* win32 exe */
590 if (ne_header->ne_magic == IMAGE_OS2_SIGNATURE_LX)
592 MESSAGE("Sorry, %s is an OS/2 linear executable (LX) file!\n", path);
593 return 12;
595 if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE) return ERROR_BAD_FORMAT;
597 /* We now have a valid NE header */
599 /* check to be able to fall back to loading OS/2 programs as DOS
600 * FIXME: should this check be reversed in order to be less strict?
601 * (only fail for OS/2 ne_exetyp 0x01 here?) */
602 if ((ne_header->ne_exetyp != 0x02 /* Windows */)
603 && (ne_header->ne_exetyp != 0x04) /* Windows 386 */)
604 return ERROR_BAD_FORMAT;
606 size = sizeof(NE_MODULE) +
607 /* segment table */
608 ne_header->ne_cseg * sizeof(SEGTABLEENTRY) +
609 /* resource table */
610 ne_header->ne_restab - ne_header->ne_rsrctab +
611 /* resident names table */
612 ne_header->ne_modtab - ne_header->ne_restab +
613 /* module ref table */
614 ne_header->ne_cmod * sizeof(WORD) +
615 /* imported names table */
616 ne_header->ne_enttab - ne_header->ne_imptab +
617 /* entry table length */
618 ne_header->ne_cbenttab +
619 /* entry table extra conversion space */
620 sizeof(ET_BUNDLE) +
621 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6) +
622 /* loaded file info */
623 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
625 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
626 if (!hModule) return ERROR_BAD_FORMAT;
628 FarSetOwner16( hModule, hModule );
629 pModule = GlobalLock16( hModule );
630 memcpy( pModule, ne_header, sizeof(*ne_header) );
631 pModule->count = 0;
632 /* check programs for default minimal stack size */
633 if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE) && (pModule->ne_stack < 0x1400))
634 pModule->ne_stack = 0x1400;
636 pModule->self = hModule;
637 pModule->mapping = mapping;
638 pModule->mapping_size = mapping_size;
640 pData = (BYTE *)(pModule + 1);
642 /* Clear internal Wine flags in case they are set in the EXE file */
644 pModule->ne_flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
646 /* Get the segment table */
648 pModule->ne_segtab = pData - (BYTE *)pModule;
649 if (!(pSeg = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_segtab,
650 ne_header->ne_cseg * sizeof(struct ne_segment_table_entry_s) )))
651 goto failed;
652 for (i = ne_header->ne_cseg; i > 0; i--, pSeg++)
654 memcpy( pData, pSeg, sizeof(*pSeg) );
655 pData += sizeof(SEGTABLEENTRY);
658 /* Get the resource table */
660 if (ne_header->ne_rsrctab < ne_header->ne_restab)
662 pModule->ne_rsrctab = pData - (BYTE *)pModule;
663 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_rsrctab,
664 ne_header->ne_restab - ne_header->ne_rsrctab )) goto failed;
665 pData += ne_header->ne_restab - ne_header->ne_rsrctab;
667 else pModule->ne_rsrctab = 0; /* No resource table */
669 /* Get the resident names table */
671 pModule->ne_restab = pData - (BYTE *)pModule;
672 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_restab,
673 ne_header->ne_modtab - ne_header->ne_restab )) goto failed;
674 pData += ne_header->ne_modtab - ne_header->ne_restab;
676 /* Get the module references table */
678 if (ne_header->ne_cmod > 0)
680 pModule->ne_modtab = pData - (BYTE *)pModule;
681 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_modtab,
682 ne_header->ne_cmod * sizeof(WORD) )) goto failed;
683 pData += ne_header->ne_cmod * sizeof(WORD);
685 else pModule->ne_modtab = 0; /* No module references */
687 /* Get the imported names table */
689 pModule->ne_imptab = pData - (BYTE *)pModule;
690 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_imptab,
691 ne_header->ne_enttab - ne_header->ne_imptab )) goto failed;
692 pData += ne_header->ne_enttab - ne_header->ne_imptab;
694 /* Load entry table, convert it to the optimized version used by Windows */
696 pModule->ne_enttab = pData - (BYTE *)pModule;
697 if (!(ptr = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_enttab,
698 ne_header->ne_cbenttab ))) goto failed;
699 end = build_bundle_data( pModule, pData, ptr );
701 pData += ne_header->ne_cbenttab + sizeof(ET_BUNDLE) +
702 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6);
704 if (end > pData)
706 FIXME( "not enough space for entry table for %s\n", debugstr_a(path) );
707 goto failed;
710 /* Store the filename information */
712 pModule->fileinfo = pData - (BYTE *)pModule;
713 ofs = (OFSTRUCT *)pData;
714 ofs->cBytes = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path);
715 ofs->fFixedDisk = 1;
716 strcpy( ofs->szPathName, path );
717 pData += ofs->cBytes + 1;
718 assert( (BYTE *)pModule + size <= pData );
720 /* Get the non-resident names table */
722 if (ne_header->ne_cbnrestab)
724 pModule->nrname_handle = GlobalAlloc16( 0, ne_header->ne_cbnrestab );
725 if (!pModule->nrname_handle) goto failed;
726 FarSetOwner16( pModule->nrname_handle, hModule );
727 buffer = GlobalLock16( pModule->nrname_handle );
728 if (!NE_READ_DATA( pModule, buffer, ne_header->ne_nrestab, ne_header->ne_cbnrestab ))
730 GlobalFree16( pModule->nrname_handle );
731 goto failed;
734 else pModule->nrname_handle = 0;
736 /* Allocate a segment for the implicitly-loaded DLLs */
738 if (pModule->ne_cmod)
740 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
741 (pModule->ne_cmod+1)*sizeof(HMODULE16) );
742 if (!pModule->dlls_to_init)
744 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
745 goto failed;
747 FarSetOwner16( pModule->dlls_to_init, hModule );
749 else pModule->dlls_to_init = 0;
751 NE_RegisterModule( pModule );
752 return hModule;
754 failed:
755 GlobalFree16( hModule );
756 return ERROR_BAD_FORMAT;
760 /***********************************************************************
761 * NE_LoadDLLs
763 * Load all DLLs implicitly linked to a module.
765 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
767 int i;
768 WORD *pModRef = (WORD *)((char *)pModule + pModule->ne_modtab);
769 WORD *pDLLs = GlobalLock16( pModule->dlls_to_init );
771 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
773 char buffer[260], *p;
774 BYTE *pstr = (BYTE *)pModule + pModule->ne_imptab + *pModRef;
775 memcpy( buffer, pstr + 1, *pstr );
776 *(buffer + *pstr) = 0; /* terminate it */
778 TRACE("Loading '%s'\n", buffer );
779 if (!(*pModRef = GetModuleHandle16( buffer )))
781 /* If the DLL is not loaded yet, load it and store */
782 /* its handle in the list of DLLs to initialize. */
783 HMODULE16 hDLL;
785 /* Append .DLL to name if no extension present */
786 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
787 strcat( buffer, ".DLL" );
789 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
791 /* FIXME: cleanup what was done */
793 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
794 buffer, *((BYTE*)pModule + pModule->ne_restab),
795 (char *)pModule + pModule->ne_restab + 1, hDLL );
796 return FALSE;
798 *pModRef = GetExePtr( hDLL );
799 *pDLLs++ = *pModRef;
801 else /* Increment the reference count of the DLL */
803 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
804 if (pOldDLL) pOldDLL->count++;
807 return TRUE;
811 /**********************************************************************
812 * NE_DoLoadModule
814 * Load first instance of NE module from file.
816 * pModule must point to a module structure prepared by build_module.
817 * This routine must never be called twice on a module.
819 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
821 /* Allocate the segments for this module */
823 if (!NE_CreateAllSegments( pModule ))
824 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
826 /* Load the referenced DLLs */
828 if (!NE_LoadDLLs( pModule ))
829 return ERROR_FILE_NOT_FOUND; /* 2 */
831 /* Load the segments */
833 NE_LoadAllSegments( pModule );
835 /* Make sure the usage count is 1 on the first loading of */
836 /* the module, even if it contains circular DLL references */
838 pModule->count = 1;
840 return NE_GetInstance( pModule );
843 /**********************************************************************
844 * NE_LoadModule
846 * Load first instance of NE module. (Note: caller is responsible for
847 * ensuring the module isn't already loaded!)
849 * If the module turns out to be an executable module, only a
850 * handle to a module stub is returned; this needs to be initialized
851 * by calling NE_DoLoadModule later, in the context of the newly
852 * created process.
854 * If lib_only is TRUE, however, the module is perforce treated
855 * like a DLL module, even if it is an executable module.
858 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
860 NE_MODULE *pModule;
861 HMODULE16 hModule;
862 HINSTANCE16 hInstance;
863 HFILE16 hFile;
864 OFSTRUCT ofs;
865 HANDLE mapping;
866 void *ptr;
867 MEMORY_BASIC_INFORMATION info;
869 /* Open file */
870 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
871 return ERROR_FILE_NOT_FOUND;
873 mapping = CreateFileMappingW( DosFileHandleToWin32Handle(hFile), NULL, PAGE_WRITECOPY, 0, 0, NULL );
874 _lclose16( hFile );
875 if (!mapping) return ERROR_BAD_FORMAT;
877 ptr = MapViewOfFile( mapping, FILE_MAP_COPY, 0, 0, 0 );
878 CloseHandle( mapping );
879 if (!ptr) return ERROR_BAD_FORMAT;
881 VirtualQuery( ptr, &info, sizeof(info) );
882 hModule = build_module( ptr, info.RegionSize, ofs.szPathName );
884 if (hModule < 32)
886 UnmapViewOfFile( ptr );
887 return hModule;
890 SNOOP16_RegisterDLL( hModule, ofs.szPathName );
891 NE_InitResourceHandler( hModule );
893 pModule = NE_GetPtr( hModule );
895 if ( !lib_only && !( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) )
896 return hModule;
898 hInstance = NE_DoLoadModule( pModule );
899 if ( hInstance < 32 )
901 /* cleanup ... */
902 NE_FreeModule( hModule, 0 );
905 return hInstance;
909 /***********************************************************************
910 * NE_DoLoadBuiltinModule
912 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
914 static HMODULE16 NE_DoLoadBuiltinModule( const IMAGE_DOS_HEADER *mz_header, const char *file_name,
915 HMODULE owner32 )
917 NE_MODULE *pModule;
918 HMODULE16 hModule;
919 HINSTANCE16 hInstance;
920 OSVERSIONINFOW versionInfo;
921 SIZE_T mapping_size = ~0UL; /* assume builtins don't contain invalid offsets... */
923 hModule = build_module( mz_header, mapping_size, file_name );
924 if (hModule < 32) return hModule;
925 pModule = GlobalLock16( hModule );
926 pModule->ne_flags |= NE_FFLAGS_BUILTIN;
927 pModule->owner32 = owner32;
929 /* fake the expected version the module should have according to the current Windows version */
930 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
931 if (GetVersionExW( &versionInfo ))
932 pModule->ne_expver = MAKEWORD( versionInfo.dwMinorVersion, versionInfo.dwMajorVersion );
934 hInstance = NE_DoLoadModule( pModule );
935 if (hInstance < 32) NE_FreeModule( hModule, 0 );
937 NE_InitResourceHandler( hModule );
939 if (pModule->ne_heap)
941 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1;
942 unsigned int size = pSeg->minsize + pModule->ne_heap;
943 if (size > 0xfffe) size = 0xfffe;
944 LocalInit16( GlobalHandleToSel16(pSeg->hSeg), pSeg->minsize, size );
947 patch_code_segment( pModule );
949 return hInstance;
953 /**********************************************************************
954 * MODULE_LoadModule16
956 * Load a NE module in the order of the loadorder specification.
957 * The caller is responsible that the module is not loaded already.
960 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
962 HINSTANCE16 hinst = 2;
963 HMODULE16 hModule;
964 HMODULE mod32 = 0;
965 NE_MODULE *pModule;
966 const IMAGE_DOS_HEADER *descr = NULL;
967 const char *file_name = NULL;
968 char dllname[32], *p;
969 const char *basename, *main_module;
970 int owner_exists = FALSE;
972 /* strip path information */
974 basename = libname;
975 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
976 if ((p = strrchr( basename, '\\' ))) basename = p + 1;
977 if ((p = strrchr( basename, '/' ))) basename = p + 1;
979 if (strlen(basename) < sizeof(dllname)-6)
981 strcpy( dllname, basename );
982 p = strrchr( dllname, '.' );
983 if (!p) strcat( dllname, ".dll" );
984 for (p = dllname; *p; p++) if (*p >= 'A' && *p <= 'Z') *p += 32;
986 strcpy( p, "16" );
987 if ((mod32 = LoadLibraryA( dllname )))
989 if (!(descr = (void *)GetProcAddress( mod32, "__wine_spec_dos_header" )))
991 WARN( "loaded %s but does not contain a 16-bit module\n", debugstr_a(dllname) );
992 FreeLibrary( mod32 );
994 else
996 TRACE( "found %s with embedded 16-bit module\n", debugstr_a(dllname) );
997 file_name = basename;
999 /* if module has a 32-bit owner, match the load order of the owner */
1000 if ((main_module = (void *)GetProcAddress( mod32, "__wine_spec_main_module" )))
1002 LDR_MODULE *ldr;
1003 HMODULE main_owner = LoadLibraryA( main_module );
1005 if (!main_owner)
1007 WARN( "couldn't load owner %s for 16-bit dll %s\n", main_module, dllname );
1008 FreeLibrary( mod32 );
1009 return ERROR_FILE_NOT_FOUND;
1011 /* check if module was loaded native */
1012 if (LdrFindEntryForAddress( main_owner, &ldr ) || !(ldr->Flags & LDR_WINE_INTERNAL))
1014 FreeLibrary( mod32 );
1015 descr = NULL;
1017 FreeLibrary( main_owner );
1022 /* loading the 32-bit library can have the side effect of loading the module */
1023 /* if so, simply incr the ref count and return the module */
1024 if (descr && (hModule = GetModuleHandle16( libname )))
1026 TRACE( "module %s already loaded by owner\n", libname );
1027 pModule = NE_GetPtr( hModule );
1028 if (pModule) pModule->count++;
1029 FreeLibrary( mod32 );
1030 return hModule;
1034 if (descr)
1036 TRACE("Trying built-in '%s'\n", libname);
1037 hinst = NE_DoLoadBuiltinModule( descr, file_name, mod32 );
1038 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : builtin\n", debugstr_a(file_name));
1040 else
1042 TRACE("Trying native dll '%s'\n", libname);
1043 hinst = NE_LoadModule(libname, lib_only);
1044 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : native\n", debugstr_a(libname));
1045 if (hinst == ERROR_FILE_NOT_FOUND && owner_exists) hinst = 21; /* win32 module */
1048 if (hinst > 32 && !implicit)
1050 hModule = GetModuleHandle16(libname);
1051 if(!hModule)
1053 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1054 libname, hinst);
1055 return ERROR_INVALID_HANDLE;
1058 pModule = NE_GetPtr(hModule);
1059 if(!pModule)
1061 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1062 libname, hinst);
1063 return ERROR_INVALID_HANDLE;
1066 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1069 * Call initialization routines for all loaded DLLs. Note that
1070 * when we load implicitly linked DLLs this will be done by InitTask().
1072 if(pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1074 NE_InitializeDLLs(hModule);
1075 NE_DllProcessAttach(hModule);
1078 return hinst; /* The last error that occurred */
1082 /**********************************************************************
1083 * NE_CreateThread
1085 * Create the thread for a 16-bit module.
1087 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1089 HANDLE hThread;
1090 TDB *pTask;
1091 HTASK16 hTask;
1092 HINSTANCE16 instance = 0;
1094 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1095 return 0;
1097 /* Post event to start the task */
1098 PostEvent16( hTask );
1100 /* Wait until we get the instance handle */
1103 DirectedYield16( hTask );
1104 if (!IsTask16( hTask )) /* thread has died */
1106 DWORD exit_code;
1107 WaitForSingleObject( hThread, INFINITE );
1108 GetExitCodeThread( hThread, &exit_code );
1109 CloseHandle( hThread );
1110 return exit_code;
1112 if (!(pTask = GlobalLock16( hTask ))) break;
1113 instance = pTask->hInstance;
1114 GlobalUnlock16( hTask );
1115 } while (!instance);
1117 CloseHandle( hThread );
1118 return instance;
1122 /**********************************************************************
1123 * LoadModule (KERNEL.45)
1125 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1127 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1128 LOADPARAMS16 *params;
1129 HMODULE16 hModule;
1130 NE_MODULE *pModule;
1131 LPSTR cmdline;
1132 WORD cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
1134 if (name == NULL) return 0;
1136 TRACE("name %s, paramBlock %p\n", name, paramBlock);
1138 /* Load module */
1140 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1142 /* Special case: second instance of an already loaded NE module */
1144 if ( !( pModule = NE_GetPtr( hModule ) ) ) return ERROR_BAD_FORMAT;
1145 if ( pModule->module32 ) return (HINSTANCE16)21;
1147 /* Increment refcount */
1149 pModule->count++;
1151 else
1153 /* Main case: load first instance of NE module */
1155 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1156 return hModule;
1158 if ( !(pModule = NE_GetPtr( hModule )) )
1159 return ERROR_BAD_FORMAT;
1162 /* If library module, we just retrieve the instance handle */
1164 if ( ( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1165 return NE_GetInstance( pModule );
1168 * At this point, we need to create a new process.
1170 * pModule points either to an already loaded module, whose refcount
1171 * has already been incremented (to avoid having the module vanish
1172 * in the meantime), or else to a stub module which contains only header
1173 * information.
1175 params = paramBlock;
1176 if (params->showCmd)
1177 cmdShow = ((WORD *)MapSL( params->showCmd ))[1];
1178 cmdline = MapSL( params->cmdLine );
1179 return NE_CreateThread( pModule, cmdShow, cmdline );
1183 /**********************************************************************
1184 * NE_StartTask
1186 * Startup code for a new 16-bit task.
1188 DWORD NE_StartTask(void)
1190 TDB *pTask = TASK_GetCurrent();
1191 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1192 HINSTANCE16 hInstance, hPrevInstance;
1193 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1194 WORD sp;
1196 if ( pModule->count > 0 )
1198 /* Second instance of an already loaded NE module */
1199 /* Note that the refcount was already incremented by the parent */
1201 hPrevInstance = NE_GetInstance( pModule );
1203 if ( pModule->ne_autodata )
1204 if ( NE_CreateSegment( pModule, pModule->ne_autodata ) )
1205 NE_LoadSegment( pModule, pModule->ne_autodata );
1207 hInstance = NE_GetInstance( pModule );
1208 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->ne_autodata, hPrevInstance);
1211 else
1213 /* Load first instance of NE module */
1215 pModule->ne_flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1217 hInstance = NE_DoLoadModule( pModule );
1218 hPrevInstance = 0;
1221 if ( hInstance >= 32 )
1223 CONTEXT86 context;
1225 /* Enter instance handles into task struct */
1227 pTask->hInstance = hInstance;
1228 pTask->hPrevInstance = hPrevInstance;
1230 /* Use DGROUP for 16-bit stack */
1232 if (!(sp = OFFSETOF(pModule->ne_sssp)))
1233 sp = pSegTable[SELECTOROF(pModule->ne_sssp)-1].minsize + pModule->ne_stack;
1234 sp &= ~1;
1235 sp -= sizeof(STACK16FRAME);
1236 NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR( GlobalHandleToSel16(hInstance), sp );
1238 /* Registers at initialization must be:
1239 * ax zero
1240 * bx stack size in bytes
1241 * cx heap size in bytes
1242 * si previous app instance
1243 * di current app instance
1244 * bp zero
1245 * es selector to the PSP
1246 * ds dgroup of the application
1247 * ss stack selector
1248 * sp top of the stack
1250 memset( &context, 0, sizeof(context) );
1251 context.SegCs = GlobalHandleToSel16(pSegTable[SELECTOROF(pModule->ne_csip) - 1].hSeg);
1252 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1253 context.SegEs = pTask->hPDB;
1254 context.SegFs = wine_get_fs();
1255 context.SegGs = wine_get_gs();
1256 context.Eip = OFFSETOF(pModule->ne_csip);
1257 context.Ebx = pModule->ne_stack;
1258 context.Ecx = pModule->ne_heap;
1259 context.Edi = pTask->hInstance;
1260 context.Esi = pTask->hPrevInstance;
1262 /* Now call 16-bit entry point */
1264 TRACE("Starting main program: cs:ip=%04x:%04x ds=%04x ss:sp=%04x:%04x\n",
1265 context.SegCs, context.Eip, context.SegDs,
1266 SELECTOROF(NtCurrentTeb()->WOW32Reserved),
1267 OFFSETOF(NtCurrentTeb()->WOW32Reserved) );
1269 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1270 ExitThread( LOWORD(context.Eax) );
1272 return hInstance; /* error code */
1275 /***********************************************************************
1276 * LoadLibrary (KERNEL.95)
1277 * LoadLibrary16 (KERNEL32.35)
1279 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1281 return LoadModule16(libname, (LPVOID)-1 );
1285 /**********************************************************************
1286 * MODULE_CallWEP
1288 * Call a DLL's WEP, allowing it to shut down.
1289 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1291 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1293 BOOL16 ret;
1294 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1295 if (!WEP) return FALSE;
1297 __TRY
1299 WORD args[1];
1300 DWORD dwRet;
1302 args[0] = WEP_FREE_DLL;
1303 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1304 ret = LOWORD(dwRet);
1306 __EXCEPT_PAGE_FAULT
1308 WARN("Page fault\n");
1309 ret = 0;
1311 __ENDTRY
1313 return ret;
1317 /**********************************************************************
1318 * NE_FreeModule
1320 * Implementation of FreeModule16().
1322 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1324 HMODULE16 *hPrevModule;
1325 NE_MODULE *pModule;
1326 HMODULE16 *pModRef;
1327 int i;
1329 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1330 hModule = pModule->self;
1332 TRACE("%04x count %d\n", hModule, pModule->count );
1334 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1335 else pModule->count = 0;
1337 if (call_wep && !(pModule->ne_flags & NE_FFLAGS_WIN32))
1339 /* Free the objects owned by the DLL module */
1340 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1342 if (pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1343 MODULE_CallWEP( hModule );
1344 else
1345 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1348 TRACE_(loaddll)("Unloaded module %s : %s\n", debugstr_a(NE_MODULE_NAME(pModule)),
1349 (pModule->ne_flags & NE_FFLAGS_BUILTIN) ? "builtin" : "native");
1351 /* Clear magic number just in case */
1353 pModule->ne_magic = pModule->self = 0;
1354 if (pModule->owner32) FreeLibrary( pModule->owner32 );
1355 else if (pModule->mapping) UnmapViewOfFile( pModule->mapping );
1357 /* Remove it from the linked list */
1359 hPrevModule = &hFirstModule;
1360 while (*hPrevModule && (*hPrevModule != hModule))
1362 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1364 if (*hPrevModule) *hPrevModule = pModule->next;
1366 /* Free the referenced modules */
1368 pModRef = (HMODULE16*)((char *)pModule + pModule->ne_modtab);
1369 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
1371 NE_FreeModule( *pModRef, call_wep );
1374 /* Free the module storage */
1376 GlobalFreeAll16( hModule );
1377 return TRUE;
1381 /**********************************************************************
1382 * FreeModule (KERNEL.46)
1384 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1386 return NE_FreeModule( hModule, TRUE );
1390 /***********************************************************************
1391 * FreeLibrary (KERNEL.96)
1392 * FreeLibrary16 (KERNEL32.36)
1394 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1396 TRACE("%04x\n", handle );
1397 FreeModule16( handle );
1401 /***********************************************************************
1402 * GetModuleHandle16 (KERNEL32.@)
1404 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1406 HMODULE16 hModule = hFirstModule;
1407 LPSTR s;
1408 BYTE len, *name_table;
1409 char tmpstr[MAX_PATH];
1410 NE_MODULE *pModule;
1412 TRACE("(%s)\n", name);
1414 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1416 len = strlen(name);
1417 if (!len) return 0;
1419 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1421 /* If 'name' matches exactly the module name of a module:
1422 * Return its handle.
1424 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1426 pModule = NE_GetPtr( hModule );
1427 if (!pModule) break;
1428 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1430 name_table = (BYTE *)pModule + pModule->ne_restab;
1431 if ((*name_table == len) && !strncmp(name, (char*) name_table+1, len))
1432 return hModule;
1435 /* If uppercased 'name' matches exactly the module name of a module:
1436 * Return its handle
1438 for (s = tmpstr; *s; s++) *s = RtlUpperChar(*s);
1440 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1442 pModule = NE_GetPtr( hModule );
1443 if (!pModule) break;
1444 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1446 name_table = (BYTE *)pModule + pModule->ne_restab;
1447 /* FIXME: the strncasecmp is WRONG. It should not be case insensitive,
1448 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1449 * lowercased module names, but try to load uppercase DLLs, so this
1450 * 'i' compare is just a quickfix until the loader handles that
1451 * correctly. -MM 990705
1453 if ((*name_table == len) && !NE_strncasecmp(tmpstr, (const char*)name_table+1, len))
1454 return hModule;
1457 /* If the base filename of 'name' matches the base filename of the module
1458 * filename of some module (case-insensitive compare):
1459 * Return its handle.
1462 /* basename: search backwards in passed name to \ / or : */
1463 s = tmpstr + strlen(tmpstr);
1464 while (s > tmpstr)
1466 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1467 break;
1468 s--;
1471 /* search this in loaded filename list */
1472 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1474 char *loadedfn;
1475 OFSTRUCT *ofs;
1477 pModule = NE_GetPtr( hModule );
1478 if (!pModule) break;
1479 if (!pModule->fileinfo) continue;
1480 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1482 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1483 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1484 /* basename: search backwards in pathname to \ / or : */
1485 while (loadedfn > (char*)ofs->szPathName)
1487 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1488 break;
1489 loadedfn--;
1491 /* case insensitive compare ... */
1492 if (!NE_strcasecmp(loadedfn, s))
1493 return hModule;
1495 return 0;
1499 /**********************************************************************
1500 * GetModuleName (KERNEL.27)
1502 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1504 NE_MODULE *pModule;
1505 BYTE *p;
1507 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1508 p = (BYTE *)pModule + pModule->ne_restab;
1509 if (count > *p) count = *p + 1;
1510 if (count > 0)
1512 memcpy( buf, p + 1, count - 1 );
1513 buf[count-1] = '\0';
1515 return TRUE;
1519 /**********************************************************************
1520 * GetModuleFileName (KERNEL.49)
1522 * Comment: see GetModuleFileNameA
1524 * Even if invoked by second instance of a program,
1525 * it still returns path of first one.
1527 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1528 INT16 nSize )
1530 NE_MODULE *pModule;
1532 /* Win95 does not query hModule if set to 0 !
1533 * Is this wrong or maybe Win3.1 only ? */
1534 if (!hModule) hModule = GetCurrentTask();
1536 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1537 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1538 if (pModule->ne_expver < 0x400)
1539 GetShortPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1540 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1541 return strlen(lpFileName);
1545 /**********************************************************************
1546 * GetModuleUsage (KERNEL.48)
1548 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1550 NE_MODULE *pModule = NE_GetPtr( hModule );
1551 return pModule ? pModule->count : 0;
1555 /**********************************************************************
1556 * GetExpWinVer (KERNEL.167)
1558 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1560 NE_MODULE *pModule = NE_GetPtr( hModule );
1561 if ( !pModule ) return 0;
1562 return pModule->ne_expver;
1566 /***********************************************************************
1567 * WinExec (KERNEL.166)
1569 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1571 LPCSTR p, args = NULL;
1572 LPCSTR name_beg, name_end;
1573 LPSTR name, cmdline;
1574 int arglen;
1575 HINSTANCE16 ret;
1576 char buffer[MAX_PATH];
1577 LOADPARAMS16 params;
1578 WORD showCmd[2];
1580 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1582 name_beg = lpCmdLine+1;
1583 p = strchr ( lpCmdLine+1, '"' );
1584 if (p)
1586 name_end = p;
1587 args = strchr ( p, ' ' );
1589 else /* yes, even valid with trailing '"' missing */
1590 name_end = lpCmdLine+strlen(lpCmdLine);
1592 else
1594 name_beg = lpCmdLine;
1595 args = strchr( lpCmdLine, ' ' );
1596 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1599 if ((name_beg == lpCmdLine) && (!args))
1600 { /* just use the original cmdline string as file name */
1601 name = (LPSTR)lpCmdLine;
1603 else
1605 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1606 return ERROR_NOT_ENOUGH_MEMORY;
1607 memcpy( name, name_beg, name_end - name_beg );
1608 name[name_end - name_beg] = '\0';
1611 if (args)
1613 args++;
1614 arglen = strlen(args);
1615 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1616 cmdline[0] = (BYTE)arglen;
1617 strcpy( cmdline + 1, args );
1619 else
1621 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1622 cmdline[0] = cmdline[1] = 0;
1625 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1627 showCmd[0] = 2;
1628 showCmd[1] = nCmdShow;
1630 params.hEnvironment = 0;
1631 params.cmdLine = MapLS( cmdline );
1632 params.showCmd = MapLS( showCmd );
1633 params.reserved = 0;
1635 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1637 ret = LoadModule16( buffer, &params );
1639 else if (!contains_path( name )) /* try 16-bit builtin */
1641 lstrcpynA( buffer, name, sizeof(buffer) );
1642 if (strlen( buffer ) < sizeof(buffer) - 4 && !strchr( buffer, '.' )) strcat( buffer, ".exe" );
1643 ret = LoadModule16( buffer, &params );
1644 if (ret == ERROR_FILE_NOT_FOUND) ret = 21; /* it might be a 32-bit builtin too */
1646 else ret = ERROR_FILE_NOT_FOUND;
1648 UnMapLS( params.cmdLine );
1649 UnMapLS( params.showCmd );
1651 HeapFree( GetProcessHeap(), 0, cmdline );
1652 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1654 if (ret == 21 || ret == ERROR_BAD_FORMAT) /* 32-bit module or unknown executable*/
1656 LOADPARAMS16 params;
1657 WORD showCmd[2];
1658 showCmd[0] = 2;
1659 showCmd[1] = nCmdShow;
1661 arglen = strlen( lpCmdLine );
1662 cmdline = HeapAlloc( GetProcessHeap(), 0, arglen + 1 );
1663 cmdline[0] = (BYTE)arglen;
1664 memcpy( cmdline + 1, lpCmdLine, arglen );
1666 params.hEnvironment = 0;
1667 params.cmdLine = MapLS( cmdline );
1668 params.showCmd = MapLS( showCmd );
1669 params.reserved = 0;
1671 ret = LoadModule16( "winoldap.mod", &params );
1672 UnMapLS( params.cmdLine );
1673 UnMapLS( params.showCmd );
1675 return ret;
1678 /***********************************************************************
1679 * GetProcAddress (KERNEL.50)
1681 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1683 WORD ordinal;
1684 FARPROC16 ret;
1686 if (!hModule) hModule = GetCurrentTask();
1687 hModule = GetExePtr( hModule );
1689 if (HIWORD(name) != 0)
1691 ordinal = NE_GetOrdinal( hModule, name );
1692 TRACE("%04x '%s'\n", hModule, name );
1694 else
1696 ordinal = LOWORD(name);
1697 TRACE("%04x %04x\n", hModule, ordinal );
1699 if (!ordinal) return NULL;
1701 ret = NE_GetEntryPoint( hModule, ordinal );
1703 TRACE("returning %p\n", ret );
1704 return ret;
1708 /***************************************************************************
1709 * HasGPHandler (KERNEL.338)
1711 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1713 HMODULE16 hModule;
1714 int gpOrdinal;
1715 SEGPTR gpPtr;
1716 GPHANDLERDEF *gpHandler;
1718 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1719 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1720 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1721 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1722 && (gpHandler = MapSL( gpPtr )) != NULL )
1724 while (gpHandler->selector)
1726 if ( SELECTOROF(address) == gpHandler->selector
1727 && OFFSETOF(address) >= gpHandler->rangeStart
1728 && OFFSETOF(address) < gpHandler->rangeEnd )
1729 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1730 gpHandler++;
1734 return 0;
1738 /**********************************************************************
1739 * GetModuleHandle (KERNEL.47)
1741 * Find a module from a module name.
1743 * NOTE: The current implementation works the same way the Windows 95 one
1744 * does. Do not try to 'fix' it, fix the callers.
1745 * + It does not do ANY extension handling (except that strange .EXE bit)!
1746 * + It does not care about paths, just about basenames. (same as Windows)
1748 * RETURNS
1749 * LOWORD:
1750 * the win16 module handle if found
1751 * 0 if not
1752 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1753 * Always hFirstModule
1755 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1757 if (HIWORD(name) == 0)
1758 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1759 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1762 /**********************************************************************
1763 * NE_GetModuleByFilename
1765 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1767 HMODULE16 hModule;
1768 LPSTR s, p;
1769 BYTE len, *name_table;
1770 char tmpstr[MAX_PATH];
1771 NE_MODULE *pModule;
1773 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1775 /* If the base filename of 'name' matches the base filename of the module
1776 * filename of some module (case-insensitive compare):
1777 * Return its handle.
1780 /* basename: search backwards in passed name to \ / or : */
1781 s = tmpstr + strlen(tmpstr);
1782 while (s > tmpstr)
1784 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1785 break;
1786 s--;
1789 /* search this in loaded filename list */
1790 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1792 char *loadedfn;
1793 OFSTRUCT *ofs;
1795 pModule = NE_GetPtr( hModule );
1796 if (!pModule) break;
1797 if (!pModule->fileinfo) continue;
1798 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1800 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1801 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1802 /* basename: search backwards in pathname to \ / or : */
1803 while (loadedfn > (char*)ofs->szPathName)
1805 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1806 break;
1807 loadedfn--;
1809 /* case insensitive compare ... */
1810 if (!NE_strcasecmp(loadedfn, s))
1811 return hModule;
1813 /* If basename (without ext) matches the module name of a module:
1814 * Return its handle.
1817 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1818 len = strlen(s);
1820 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1822 pModule = NE_GetPtr( hModule );
1823 if (!pModule) break;
1824 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1826 name_table = (BYTE *)pModule + pModule->ne_restab;
1827 if ((*name_table == len) && !NE_strncasecmp(s, (const char*)name_table+1, len))
1828 return hModule;
1831 return 0;
1834 /***********************************************************************
1835 * GetProcAddress16 (KERNEL32.37)
1836 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1838 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1840 if (!hModule) return 0;
1841 if (HIWORD(hModule))
1843 WARN("hModule is Win32 handle (%p)\n", hModule );
1844 return 0;
1846 return GetProcAddress16( LOWORD(hModule), name );
1849 /***************************************************************************
1850 * IsRomModule (KERNEL.323)
1852 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1854 return FALSE;
1857 /***************************************************************************
1858 * IsRomFile (KERNEL.326)
1860 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1862 return FALSE;
1865 /***********************************************************************
1866 * create_dummy_module
1868 * Create a dummy NE module for Win32 or Winelib.
1870 static HMODULE16 create_dummy_module( HMODULE module32 )
1872 HMODULE16 hModule;
1873 NE_MODULE *pModule;
1874 SEGTABLEENTRY *pSegment;
1875 char *pStr,*s;
1876 unsigned int len;
1877 const char* basename;
1878 OFSTRUCT *ofs;
1879 int of_size, size;
1880 char filename[MAX_PATH];
1881 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
1883 if (!nt) return ERROR_BAD_FORMAT;
1885 /* Extract base filename */
1886 len = GetModuleFileNameA( module32, filename, sizeof(filename) );
1887 if (!len || len >= sizeof(filename)) return ERROR_BAD_FORMAT;
1888 basename = strrchr(filename, '\\');
1889 if (!basename) basename = filename;
1890 else basename++;
1891 len = strlen(basename);
1892 if ((s = strchr(basename, '.'))) len = s - basename;
1894 /* Allocate module */
1895 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
1896 + strlen(filename) + 1;
1897 size = sizeof(NE_MODULE) +
1898 /* loaded file info */
1899 ((of_size + 3) & ~3) +
1900 /* segment table: DS,CS */
1901 2 * sizeof(SEGTABLEENTRY) +
1902 /* name table */
1903 len + 2 +
1904 /* several empty tables */
1907 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
1908 if (!hModule) return ERROR_BAD_FORMAT;
1910 FarSetOwner16( hModule, hModule );
1911 pModule = GlobalLock16( hModule );
1913 /* Set all used entries */
1914 pModule->ne_magic = IMAGE_OS2_SIGNATURE;
1915 pModule->count = 1;
1916 pModule->next = 0;
1917 pModule->ne_flags = NE_FFLAGS_WIN32;
1918 pModule->ne_autodata = 0;
1919 pModule->ne_sssp = MAKESEGPTR( 0, 1 );
1920 pModule->ne_csip = MAKESEGPTR( 0, 2 );
1921 pModule->ne_heap = 0;
1922 pModule->ne_stack = 0;
1923 pModule->ne_cseg = 2;
1924 pModule->ne_cmod = 0;
1925 pModule->ne_cbnrestab = 0;
1926 pModule->fileinfo = sizeof(NE_MODULE);
1927 pModule->ne_exetyp = NE_OSFLAGS_WINDOWS;
1928 pModule->self = hModule;
1929 pModule->module32 = module32;
1931 /* Set version and flags */
1932 pModule->ne_expver = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
1933 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
1934 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1935 pModule->ne_flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
1937 /* Set loaded file information */
1938 ofs = (OFSTRUCT *)(pModule + 1);
1939 memset( ofs, 0, of_size );
1940 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
1941 strcpy( ofs->szPathName, filename );
1943 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
1944 pModule->ne_segtab = (char *)pSegment - (char *)pModule;
1945 /* Data segment */
1946 pSegment->size = 0;
1947 pSegment->flags = NE_SEGFLAGS_DATA;
1948 pSegment->minsize = 0x1000;
1949 pSegment++;
1950 /* Code segment */
1951 pSegment->flags = 0;
1952 pSegment++;
1954 /* Module name */
1955 pStr = (char *)pSegment;
1956 pModule->ne_restab = pStr - (char *)pModule;
1957 assert(len<256);
1958 *pStr = len;
1959 lstrcpynA( pStr+1, basename, len+1 );
1960 pStr += len+2;
1962 /* All tables zero terminated */
1963 pModule->ne_rsrctab = pModule->ne_imptab = pModule->ne_enttab = pStr - (char *)pModule;
1965 NE_RegisterModule( pModule );
1966 pModule->owner32 = LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
1967 return hModule;
1970 /***********************************************************************
1971 * PrivateLoadLibrary (KERNEL32.@)
1973 * FIXME: rough guesswork, don't know what "Private" means
1975 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1977 return LoadLibrary16(libname);
1980 /***********************************************************************
1981 * PrivateFreeLibrary (KERNEL32.@)
1983 * FIXME: rough guesswork, don't know what "Private" means
1985 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1987 FreeLibrary16(handle);
1990 /***********************************************************************
1991 * LoadLibrary32 (KERNEL.452)
1992 * LoadSystemLibrary32 (KERNEL.482)
1994 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1996 HMODULE hModule;
1997 DWORD count;
1999 ReleaseThunkLock( &count );
2000 hModule = LoadLibraryA( libname );
2001 RestoreThunkLock( count );
2002 return hModule;
2005 /***************************************************************************
2006 * MapHModuleLS (KERNEL32.@)
2008 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
2010 HMODULE16 ret;
2011 NE_MODULE *pModule;
2013 if (!hmod)
2014 return TASK_GetCurrent()->hInstance;
2015 if (!HIWORD(hmod))
2016 return LOWORD(hmod); /* we already have a 16 bit module handle */
2017 pModule = GlobalLock16(hFirstModule);
2018 while (pModule) {
2019 if (pModule->module32 == hmod)
2020 return pModule->self;
2021 pModule = GlobalLock16(pModule->next);
2023 if ((ret = create_dummy_module( hmod )) < 32)
2025 SetLastError(ret);
2026 ret = 0;
2028 return ret;
2031 /***************************************************************************
2032 * MapHModuleSL (KERNEL32.@)
2034 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2036 NE_MODULE *pModule;
2038 if (!hmod) {
2039 TDB *pTask = TASK_GetCurrent();
2040 hmod = pTask->hModule;
2042 pModule = GlobalLock16(hmod);
2043 if ((pModule->ne_magic != IMAGE_OS2_SIGNATURE) || !(pModule->ne_flags & NE_FFLAGS_WIN32))
2044 return 0;
2045 return pModule->module32;
2048 /***************************************************************************
2049 * MapHInstLS (KERNEL.472)
2051 void WINAPI MapHInstLS16( CONTEXT86 *context )
2053 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2056 /***************************************************************************
2057 * MapHInstSL (KERNEL.473)
2059 void WINAPI MapHInstSL16( CONTEXT86 *context )
2061 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2064 /***************************************************************************
2065 * MapHInstLS (KERNEL32.@)
2067 __ASM_STDCALL_FUNC( MapHInstLS, 0,
2068 "pushl %eax\n\t"
2069 "call " __ASM_NAME("MapHModuleLS") __ASM_STDCALL(4) "\n\t"
2070 "ret" )
2072 /***************************************************************************
2073 * MapHInstSL (KERNEL32.@)
2075 __ASM_STDCALL_FUNC( MapHInstSL, 0,
2076 "pushl %eax\n\t"
2077 "call " __ASM_NAME("MapHModuleSL") __ASM_STDCALL(4) "\n\t"
2078 "ret" )
2080 /***************************************************************************
2081 * MapHInstLS_PN (KERNEL32.@)
2083 __ASM_STDCALL_FUNC( MapHInstLS_PN, 0,
2084 "testl %eax,%eax\n\t"
2085 "jz 1f\n\t"
2086 "pushl %eax\n\t"
2087 "call " __ASM_NAME("MapHModuleLS") __ASM_STDCALL(4) "\n"
2088 "1:\tret" )
2090 /***************************************************************************
2091 * MapHInstSL_PN (KERNEL32.@)
2093 __ASM_STDCALL_FUNC( MapHInstSL_PN, 0,
2094 "andl $0xffff,%eax\n\t"
2095 "jz 1f\n\t"
2096 "pushl %eax\n\t"
2097 "call " __ASM_NAME("MapHModuleSL") __ASM_STDCALL(4) "\n"
2098 "1:\tret" )