4 * Copyright 1995 Alexandre Julliard
13 #include "wine/winbase16.h"
28 #include "stackframe.h"
29 #include "debugtools.h"
31 #include "loadorder.h"
35 DEFAULT_DEBUG_CHANNEL(module)
37 FARPROC16 (*fnSNOOP16_GetProcAddress16)(HMODULE16,DWORD,FARPROC16) = NULL;
38 void (*fnSNOOP16_RegisterDLL)(NE_MODULE*,LPCSTR) = NULL;
40 #define hFirstModule (pThhook->hExeHead)
42 static NE_MODULE *pCachedModule = 0; /* Module cached by NE_OpenFile */
44 static HMODULE16 NE_LoadBuiltin(LPCSTR name,BOOL force) { return 0; }
45 HMODULE16 (*fnBUILTIN_LoadModule)(LPCSTR name,BOOL force) = NE_LoadBuiltin;
46 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
48 /***********************************************************************
51 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
53 return (NE_MODULE *)GlobalLock16( GetExePtr(hModule) );
57 /***********************************************************************
60 void NE_DumpModule( HMODULE16 hModule )
70 if (!(pModule = NE_GetPtr( hModule )))
72 MESSAGE( "**** %04x is not a module handle\n", hModule );
76 /* Dump the module info */
78 DPRINTF( "Module %04x:\n", hModule );
79 DPRINTF( "count=%d flags=%04x heap=%d stack=%d\n",
80 pModule->count, pModule->flags,
81 pModule->heap_size, pModule->stack_size );
82 DPRINTF( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
83 pModule->cs, pModule->ip, pModule->ss, pModule->sp, pModule->dgroup,
84 pModule->seg_count, pModule->modref_count );
85 DPRINTF( "os_flags=%d swap_area=%d version=%04x\n",
86 pModule->os_flags, pModule->min_swap_area,
87 pModule->expected_version );
88 if (pModule->flags & NE_FFLAGS_WIN32)
89 DPRINTF( "PE module=%08x\n", pModule->module32 );
91 /* Dump the file info */
93 DPRINTF( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
95 /* Dump the segment table */
97 DPRINTF( "Segment table:\n" );
98 pSeg = NE_SEG_TABLE( pModule );
99 for (i = 0; i < pModule->seg_count; i++, pSeg++)
100 DPRINTF( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
101 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
102 pSeg->minsize, pSeg->hSeg );
104 /* Dump the resource table */
106 DPRINTF( "Resource table:\n" );
107 if (pModule->res_table)
109 pword = (WORD *)((BYTE *)pModule + pModule->res_table);
110 DPRINTF( "Alignment: %d\n", *pword++ );
113 struct resource_typeinfo_s *ptr = (struct resource_typeinfo_s *)pword;
114 struct resource_nameinfo_s *pname = (struct resource_nameinfo_s *)(ptr + 1);
115 DPRINTF( "id=%04x count=%d\n", ptr->type_id, ptr->count );
116 for (i = 0; i < ptr->count; i++, pname++)
117 DPRINTF( "offset=%d len=%d id=%04x\n",
118 pname->offset, pname->length, pname->id );
119 pword = (WORD *)pname;
122 else DPRINTF( "None\n" );
124 /* Dump the resident name table */
126 DPRINTF( "Resident-name table:\n" );
127 pstr = (char *)pModule + pModule->name_table;
130 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
131 *(WORD *)(pstr + *pstr + 1) );
132 pstr += *pstr + 1 + sizeof(WORD);
135 /* Dump the module reference table */
137 DPRINTF( "Module ref table:\n" );
138 if (pModule->modref_table)
140 pword = (WORD *)((BYTE *)pModule + pModule->modref_table);
141 for (i = 0; i < pModule->modref_count; i++, pword++)
144 GetModuleName16( *pword, name, sizeof(name) );
145 DPRINTF( "%d: %04x -> '%s'\n", i, *pword, name );
148 else DPRINTF( "None\n" );
150 /* Dump the entry table */
152 DPRINTF( "Entry table:\n" );
153 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);
155 entry = (ET_ENTRY *)((BYTE *)bundle+6);
156 DPRINTF( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
157 ordinal = bundle->first;
158 while (ordinal < bundle->last)
160 if (entry->type == 0xff)
161 DPRINTF("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
163 DPRINTF("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
166 } while ( (bundle->next)
167 && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
169 /* Dump the non-resident names table */
171 DPRINTF( "Non-resident names table:\n" );
172 if (pModule->nrname_handle)
174 pstr = (char *)GlobalLock16( pModule->nrname_handle );
177 DPRINTF( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
178 *(WORD *)(pstr + *pstr + 1) );
179 pstr += *pstr + 1 + sizeof(WORD);
186 /***********************************************************************
189 * Walk the module list and print the modules.
191 void NE_WalkModules(void)
193 HMODULE16 hModule = hFirstModule;
194 MESSAGE( "Module Flags Name\n" );
197 NE_MODULE *pModule = NE_GetPtr( hModule );
200 MESSAGE( "Bad module %04x in list\n", hModule );
203 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->flags,
204 *((char *)pModule + pModule->name_table),
205 (char *)pModule + pModule->name_table + 1 );
206 hModule = pModule->next;
211 /**********************************************************************
214 void NE_RegisterModule( NE_MODULE *pModule )
216 pModule->next = hFirstModule;
217 hFirstModule = pModule->self;
221 /***********************************************************************
224 * Lookup the ordinal for a given name.
226 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
228 unsigned char buffer[256], *cpnt;
232 if (!(pModule = NE_GetPtr( hModule ))) return 0;
233 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
235 TRACE("(%04x,'%s')\n", hModule, name );
237 /* First handle names of the form '#xxxx' */
239 if (name[0] == '#') return atoi( name + 1 );
241 /* Now copy and uppercase the string */
243 strcpy( buffer, name );
244 CharUpperA( buffer );
245 len = strlen( buffer );
247 /* First search the resident names */
249 cpnt = (char *)pModule + pModule->name_table;
251 /* Skip the first entry (module name) */
252 cpnt += *cpnt + 1 + sizeof(WORD);
255 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
257 TRACE(" Found: ordinal=%d\n",
258 *(WORD *)(cpnt + *cpnt + 1) );
259 return *(WORD *)(cpnt + *cpnt + 1);
261 cpnt += *cpnt + 1 + sizeof(WORD);
264 /* Now search the non-resident names table */
266 if (!pModule->nrname_handle) return 0; /* No non-resident table */
267 cpnt = (char *)GlobalLock16( pModule->nrname_handle );
269 /* Skip the first entry (module description string) */
270 cpnt += *cpnt + 1 + sizeof(WORD);
273 if (((BYTE)*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
275 TRACE(" Found: ordinal=%d\n",
276 *(WORD *)(cpnt + *cpnt + 1) );
277 return *(WORD *)(cpnt + *cpnt + 1);
279 cpnt += *cpnt + 1 + sizeof(WORD);
285 /***********************************************************************
286 * NE_GetEntryPoint (WPROCS.27)
288 * Return the entry point for a given ordinal.
290 FARPROC16 NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
292 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
294 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
302 if (!(pModule = NE_GetPtr( hModule ))) return 0;
303 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
305 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
306 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
310 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
313 entry = (ET_ENTRY *)((BYTE *)bundle+6);
314 for (i=0; i < (ordinal - bundle->first - 1); i++)
318 offset = entry->offs;
320 if (sel == 0xfe) sel = 0xffff; /* constant entry */
321 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
323 return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
324 if (!snoop || !fnSNOOP16_GetProcAddress16)
325 return (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset );
327 return (FARPROC16)fnSNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)PTR_SEG_OFF_TO_SEGPTR( sel, offset ));
331 /***********************************************************************
334 * Change the value of an entry point. Use with caution!
335 * It can only change the offset value, not the selector.
337 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
344 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
345 assert( !(pModule->flags & NE_FFLAGS_WIN32) );
347 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->entry_table);
348 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
350 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
355 entry = (ET_ENTRY *)((BYTE *)bundle+6);
356 for (i=0; i < (ordinal - bundle->first - 1); i++)
359 entry->offs = offset;
364 /***********************************************************************
367 HANDLE NE_OpenFile( NE_MODULE *pModule )
371 static HANDLE cachedfd = -1;
373 TRACE("(%p) cache: mod=%p fd=%d\n",
374 pModule, pCachedModule, cachedfd );
375 if (pCachedModule == pModule) return cachedfd;
376 CloseHandle( cachedfd );
377 pCachedModule = pModule;
378 name = NE_MODULE_NAME( pModule );
379 if ((cachedfd = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
380 NULL, OPEN_EXISTING, 0, -1 )) == -1)
381 MESSAGE( "Can't open file '%s' for module %04x\n", name, pModule->self );
383 /* FIXME: should not be necessary */
384 cachedfd = ConvertToGlobalHandle(cachedfd);
385 TRACE("opened '%s' -> %d\n",
391 /***********************************************************************
394 static HMODULE16 NE_LoadExeHeader( HFILE16 hFile, OFSTRUCT *ofs )
396 IMAGE_DOS_HEADER mz_header;
397 IMAGE_OS2_HEADER ne_header;
401 BYTE *pData, *pTempEntryTable;
402 char *buffer, *fastload = NULL;
403 int fastload_offset = 0, fastload_length = 0;
405 ET_BUNDLE *bundle, *oldbundle;
407 /* Read a block from either the file or the fast-load area. */
408 #define READ(offset,size,buffer) \
409 ((fastload && ((offset) >= fastload_offset) && \
410 ((offset)+(size) <= fastload_offset+fastload_length)) ? \
411 (memcpy( buffer, fastload+(offset)-fastload_offset, (size) ), TRUE) : \
412 (_llseek16( hFile, (offset), SEEK_SET), \
413 _hread16( hFile, (buffer), (size) ) == (size)))
415 _llseek16( hFile, 0, SEEK_SET );
416 if ((_hread16(hFile,&mz_header,sizeof(mz_header)) != sizeof(mz_header)) ||
417 (mz_header.e_magic != IMAGE_DOS_SIGNATURE))
418 return (HMODULE16)11; /* invalid exe */
420 _llseek16( hFile, mz_header.e_lfanew, SEEK_SET );
421 if (_hread16( hFile, &ne_header, sizeof(ne_header) ) != sizeof(ne_header))
422 return (HMODULE16)11; /* invalid exe */
424 if (ne_header.ne_magic == IMAGE_NT_SIGNATURE) return (HMODULE16)21; /* win32 exe */
425 if (ne_header.ne_magic != IMAGE_OS2_SIGNATURE) return (HMODULE16)11; /* invalid exe */
427 if (ne_header.ne_magic == IMAGE_OS2_SIGNATURE_LX) {
428 MESSAGE("Sorry, this is an OS/2 linear executable (LX) file !\n");
429 return (HMODULE16)12;
432 /* We now have a valid NE header */
434 size = sizeof(NE_MODULE) +
436 ne_header.n_segment_tab * sizeof(SEGTABLEENTRY) +
438 ne_header.rname_tab_offset - ne_header.resource_tab_offset +
439 /* resident names table */
440 ne_header.moduleref_tab_offset - ne_header.rname_tab_offset +
441 /* module ref table */
442 ne_header.n_mod_ref_tab * sizeof(WORD) +
443 /* imported names table */
444 ne_header.entry_tab_offset - ne_header.iname_tab_offset +
445 /* entry table length */
446 ne_header.entry_tab_length +
447 /* entry table extra conversion space */
449 2 * (ne_header.entry_tab_length - ne_header.n_mov_entry_points*6) +
450 /* loaded file info */
451 sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1;
453 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
454 if (!hModule) return (HMODULE16)11; /* invalid exe */
455 FarSetOwner16( hModule, hModule );
456 pModule = (NE_MODULE *)GlobalLock16( hModule );
457 memcpy( pModule, &ne_header, sizeof(ne_header) );
459 /* check *programs* for default minimal stack size */
460 if ( (!(pModule->flags & NE_FFLAGS_LIBMODULE))
461 && (pModule->stack_size < 0x1400) )
462 pModule->stack_size = 0x1400;
463 pModule->module32 = 0;
464 pModule->self = hModule;
465 pModule->self_loading_sel = 0;
466 pData = (BYTE *)(pModule + 1);
468 /* Clear internal Wine flags in case they are set in the EXE file */
470 pModule->flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
472 /* Read the fast-load area */
474 if (ne_header.additional_flags & NE_AFLAGS_FASTLOAD)
476 fastload_offset=ne_header.fastload_offset<<ne_header.align_shift_count;
477 fastload_length=ne_header.fastload_length<<ne_header.align_shift_count;
478 TRACE("Using fast-load area offset=%x len=%d\n",
479 fastload_offset, fastload_length );
480 if ((fastload = HeapAlloc( SystemHeap, 0, fastload_length )) != NULL)
482 _llseek16( hFile, fastload_offset, SEEK_SET);
483 if (_hread16(hFile, fastload, fastload_length) != fastload_length)
485 HeapFree( SystemHeap, 0, fastload );
486 WARN("Error reading fast-load area!\n");
492 /* Get the segment table */
494 pModule->seg_table = (int)pData - (int)pModule;
495 buffer = HeapAlloc( SystemHeap, 0, ne_header.n_segment_tab *
496 sizeof(struct ne_segment_table_entry_s));
500 struct ne_segment_table_entry_s *pSeg;
502 if (!READ( mz_header.e_lfanew + ne_header.segment_tab_offset,
503 ne_header.n_segment_tab * sizeof(struct ne_segment_table_entry_s),
506 HeapFree( SystemHeap, 0, buffer );
508 HeapFree( SystemHeap, 0, fastload );
509 GlobalFree16( hModule );
510 return (HMODULE16)11; /* invalid exe */
512 pSeg = (struct ne_segment_table_entry_s *)buffer;
513 for (i = ne_header.n_segment_tab; i > 0; i--, pSeg++)
515 memcpy( pData, pSeg, sizeof(*pSeg) );
516 pData += sizeof(SEGTABLEENTRY);
518 HeapFree( SystemHeap, 0, buffer );
523 HeapFree( SystemHeap, 0, fastload );
524 GlobalFree16( hModule );
525 return (HMODULE16)11; /* invalid exe */
528 /* Get the resource table */
530 if (ne_header.resource_tab_offset < ne_header.rname_tab_offset)
532 pModule->res_table = (int)pData - (int)pModule;
533 if (!READ(mz_header.e_lfanew + ne_header.resource_tab_offset,
534 ne_header.rname_tab_offset - ne_header.resource_tab_offset,
535 pData )) return (HMODULE16)11; /* invalid exe */
536 pData += ne_header.rname_tab_offset - ne_header.resource_tab_offset;
537 NE_InitResourceHandler( hModule );
539 else pModule->res_table = 0; /* No resource table */
541 /* Get the resident names table */
543 pModule->name_table = (int)pData - (int)pModule;
544 if (!READ( mz_header.e_lfanew + ne_header.rname_tab_offset,
545 ne_header.moduleref_tab_offset - ne_header.rname_tab_offset,
549 HeapFree( SystemHeap, 0, fastload );
550 GlobalFree16( hModule );
551 return (HMODULE16)11; /* invalid exe */
553 pData += ne_header.moduleref_tab_offset - ne_header.rname_tab_offset;
555 /* Get the module references table */
557 if (ne_header.n_mod_ref_tab > 0)
559 pModule->modref_table = (int)pData - (int)pModule;
560 if (!READ( mz_header.e_lfanew + ne_header.moduleref_tab_offset,
561 ne_header.n_mod_ref_tab * sizeof(WORD),
565 HeapFree( SystemHeap, 0, fastload );
566 GlobalFree16( hModule );
567 return (HMODULE16)11; /* invalid exe */
569 pData += ne_header.n_mod_ref_tab * sizeof(WORD);
571 else pModule->modref_table = 0; /* No module references */
573 /* Get the imported names table */
575 pModule->import_table = (int)pData - (int)pModule;
576 if (!READ( mz_header.e_lfanew + ne_header.iname_tab_offset,
577 ne_header.entry_tab_offset - ne_header.iname_tab_offset,
581 HeapFree( SystemHeap, 0, fastload );
582 GlobalFree16( hModule );
583 return (HMODULE16)11; /* invalid exe */
585 pData += ne_header.entry_tab_offset - ne_header.iname_tab_offset;
587 /* Load entry table, convert it to the optimized version used by Windows */
589 if ((pTempEntryTable = HeapAlloc( SystemHeap, 0, ne_header.entry_tab_length)) != NULL)
591 BYTE nr_entries, type, *s;
593 TRACE("Converting entry table.\n");
594 pModule->entry_table = (int)pData - (int)pModule;
595 if (!READ( mz_header.e_lfanew + ne_header.entry_tab_offset,
596 ne_header.entry_tab_length, pTempEntryTable ))
598 HeapFree( SystemHeap, 0, pTempEntryTable );
600 HeapFree( SystemHeap, 0, fastload );
601 GlobalFree16( hModule );
602 return (HMODULE16)11; /* invalid exe */
606 TRACE("entry table: offs %04x, len %04x, entries %d\n", ne_header.entry_tab_offset, ne_header.entry_tab_length, *s);
608 bundle = (ET_BUNDLE *)pData;
609 TRACE("first bundle: %p\n", bundle);
610 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
611 entry = (ET_ENTRY *)((BYTE *)bundle+6);
613 while ((nr_entries = *s++))
617 bundle->last += nr_entries;
624 entry->segnum = *s++;
625 entry->offs = *(WORD *)s; s += 2;
626 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
634 entry->segnum = type;
635 entry->offs = *(WORD *)s; s += 2;
636 /*TRACE(module, "entry: %p, type: %d, flags: %d, segnum: %d, offs: %04x\n", entry, entry->type, entry->flags, entry->segnum, entry->offs);*/
642 if (bundle->first == bundle->last)
644 bundle->first += nr_entries;
645 bundle->last += nr_entries;
650 oldbundle->next = ((int)entry - (int)pModule);
651 bundle = (ET_BUNDLE *)entry;
652 TRACE("new bundle: %p\n", bundle);
653 bundle->first = bundle->last =
654 oldbundle->last + nr_entries;
656 (BYTE *)entry += sizeof(ET_BUNDLE);
660 HeapFree( SystemHeap, 0, pTempEntryTable );
665 HeapFree( SystemHeap, 0, fastload );
666 GlobalFree16( hModule );
667 return (HMODULE16)11; /* invalid exe */
670 pData += ne_header.entry_tab_length + sizeof(ET_BUNDLE) +
671 2 * (ne_header.entry_tab_length - ne_header.n_mov_entry_points*6);
673 if ((DWORD)entry > (DWORD)pData)
674 ERR("converted entry table bigger than reserved space !!!\nentry: %p, pData: %p. Please report !\n", entry, pData);
676 /* Store the filename information */
678 pModule->fileinfo = (int)pData - (int)pModule;
679 size = sizeof(OFSTRUCT)-sizeof(ofs->szPathName)+strlen(ofs->szPathName)+1;
680 memcpy( pData, ofs, size );
681 ((OFSTRUCT *)pData)->cBytes = size - 1;
684 /* Free the fast-load area */
688 HeapFree( SystemHeap, 0, fastload );
690 /* Get the non-resident names table */
692 if (ne_header.nrname_tab_length)
694 pModule->nrname_handle = GLOBAL_Alloc( 0, ne_header.nrname_tab_length,
695 hModule, FALSE, FALSE, FALSE );
696 if (!pModule->nrname_handle)
698 GlobalFree16( hModule );
699 return (HMODULE16)11; /* invalid exe */
701 buffer = GlobalLock16( pModule->nrname_handle );
702 _llseek16( hFile, ne_header.nrname_tab_offset, SEEK_SET );
703 if (_hread16( hFile, buffer, ne_header.nrname_tab_length )
704 != ne_header.nrname_tab_length)
706 GlobalFree16( pModule->nrname_handle );
707 GlobalFree16( hModule );
708 return (HMODULE16)11; /* invalid exe */
711 else pModule->nrname_handle = 0;
713 /* Allocate a segment for the implicitly-loaded DLLs */
715 if (pModule->modref_count)
717 pModule->dlls_to_init = GLOBAL_Alloc(GMEM_ZEROINIT,
718 (pModule->modref_count+1)*sizeof(HMODULE16),
719 hModule, FALSE, FALSE, FALSE );
720 if (!pModule->dlls_to_init)
722 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
723 GlobalFree16( hModule );
724 return (HMODULE16)11; /* invalid exe */
727 else pModule->dlls_to_init = 0;
729 NE_RegisterModule( pModule );
730 if (fnSNOOP16_RegisterDLL)
731 fnSNOOP16_RegisterDLL(pModule,ofs->szPathName);
736 /***********************************************************************
739 * Load all DLLs implicitly linked to a module.
741 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
744 WORD *pModRef = (WORD *)((char *)pModule + pModule->modref_table);
745 WORD *pDLLs = (WORD *)GlobalLock16( pModule->dlls_to_init );
747 for (i = 0; i < pModule->modref_count; i++, pModRef++)
750 BYTE *pstr = (BYTE *)pModule + pModule->import_table + *pModRef;
751 memcpy( buffer, pstr + 1, *pstr );
752 *(buffer + *pstr) = 0; /* terminate it */
754 TRACE("Loading '%s'\n", buffer );
755 if (!(*pModRef = GetModuleHandle16( buffer )))
757 /* If the DLL is not loaded yet, load it and store */
758 /* its handle in the list of DLLs to initialize. */
761 if ((hDLL = MODULE_LoadModule16( buffer, 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->name_table),
767 (char *)pModule + pModule->name_table + 1, hDLL );
770 *pModRef = GetExePtr( hDLL );
773 else /* Increment the reference count of the DLL */
777 pOldDLL = NE_GetPtr( *pModRef );
778 if (pOldDLL) pOldDLL->count++;
785 /**********************************************************************
788 * Load first instance of NE module from file.
789 * (Note: caller is responsible for ensuring the module isn't
792 static HINSTANCE16 NE_LoadFileModule( HFILE16 hFile, OFSTRUCT *ofs,
795 HINSTANCE16 hInstance;
799 /* Create the module structure */
801 hModule = NE_LoadExeHeader( hFile, ofs );
802 if (hModule < 32) return hModule;
803 pModule = NE_GetPtr( hModule );
805 /* Allocate the segments for this module */
807 if (!NE_CreateSegments( pModule ) ||
808 !(hInstance = NE_CreateInstance( pModule, NULL, FALSE )))
810 GlobalFreeAll16( hModule );
811 return 8; /* Insufficient memory */
814 /* Load the referenced DLLs */
816 if (!NE_LoadDLLs( pModule ))
818 NE_FreeModule(hModule,0);
822 /* Load the segments */
824 NE_LoadAllSegments( pModule );
826 /* Fixup the functions prologs */
828 NE_FixupPrologs( pModule );
830 /* Make sure the usage count is 1 on the first loading of */
831 /* the module, even if it contains circular DLL references */
838 /**********************************************************************
841 * Load first instance of NE module, deciding whether to use
842 * built-in module or load module from file.
843 * (Note: caller is responsible for ensuring the module isn't
846 HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL implicit )
848 HINSTANCE16 hInstance;
852 if ((hFile = OpenFile16( name, &ofs, OF_READ )) == HFILE_ERROR16)
858 /* 4 == strlen(".dll") */
859 strncpy(buffer, name, sizeof(buffer) - 1 - 4);
860 strcat(buffer, ".dll");
861 if ((hFile = OpenFile16( buffer, &ofs, OF_READ )) == HFILE_ERROR16)
862 return 2; /* File not found */
866 hInstance = NE_LoadFileModule( hFile, &ofs, implicit );
873 /**********************************************************************
874 * MODULE_LoadModule16
876 * Load a NE module in the order of the loadorder specification.
877 * The caller is responsible that the module is not loaded already.
880 HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit )
884 module_loadorder_t *plo;
886 plo = MODULE_GetLoadOrder(libname);
888 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
890 switch(plo->loadorder[i])
892 case MODULE_LOADORDER_DLL:
893 TRACE("Trying native dll '%s'\n", libname);
894 hinst = NE_LoadModule(libname, implicit);
897 case MODULE_LOADORDER_ELFDLL:
898 TRACE("Trying elfdll '%s'\n", libname);
899 hinst = ELFDLL_LoadModule16(libname, implicit);
902 case MODULE_LOADORDER_BI:
903 TRACE("Trying built-in '%s'\n", libname);
904 hinst = fnBUILTIN_LoadModule(libname, TRUE);
908 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
911 case MODULE_LOADORDER_SO: /* This is not supported for NE modules */
912 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
924 hModule = GetModuleHandle16(libname);
927 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle\n",
929 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
932 pModule = NE_GetPtr(hModule);
935 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
937 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
940 TRACE("Loaded module '%s' at 0x%04x, \n", libname, hinst);
943 * Call initialization routines for all loaded DLLs. Note that
944 * when we load implicitly linked DLLs this will be done by InitTask().
946 if(pModule->flags & NE_FFLAGS_LIBMODULE)
947 NE_InitializeDLLs(hModule);
954 /* We quit searching when we get another error than 'File not found' */
958 return hinst; /* The last error that occured */
962 /**********************************************************************
963 * LoadModule16 (KERNEL.45)
965 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
967 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
968 LOADPARAMS16 *params;
969 LPSTR cmd_line, new_cmd_line;
971 STARTUPINFOA startup;
972 PROCESS_INFORMATION info;
973 HINSTANCE16 hInstance, hPrevInstance = 0;
980 if ( (hModule = GetModuleHandle16(name) ) != 0 )
982 /* Special case: second instance of an already loaded NE module */
984 if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
985 if ( pModule->module32 ) return (HINSTANCE16)21;
987 hInstance = NE_CreateInstance( pModule, &hPrevInstance, lib_only );
988 if ( hInstance != hPrevInstance ) /* not a library */
989 NE_LoadSegment( pModule, pModule->dgroup );
995 /* Main case: load first instance of NE module */
997 if ( (hInstance = MODULE_LoadModule16( name, FALSE )) < 32 )
1000 if ( !(pModule = NE_GetPtr( hInstance )) )
1001 return (HINSTANCE16)11;
1004 /* If library module, we're finished */
1006 if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1009 /* Create a task for this instance */
1011 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1013 params = (LOADPARAMS16 *)paramBlock;
1014 cmd_line = (LPSTR)PTR_SEG_TO_LIN( params->cmdLine );
1015 if (!cmd_line) cmd_line = "";
1016 else if (*cmd_line) cmd_line++; /* skip the length byte */
1018 if (!(new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1019 strlen(cmd_line)+strlen(name)+2 )))
1021 strcpy( new_cmd_line, name );
1022 strcat( new_cmd_line, " " );
1023 strcat( new_cmd_line, cmd_line );
1025 if (params->hEnvironment) env = GlobalLock16( params->hEnvironment );
1027 memset( &info, '\0', sizeof(info) );
1028 memset( &startup, '\0', sizeof(startup) );
1029 startup.cb = sizeof(startup);
1030 if (params->showCmd)
1032 startup.dwFlags = STARTF_USESHOWWINDOW;
1033 startup.wShowWindow = ((UINT16 *)PTR_SEG_TO_LIN(params->showCmd))[1];
1036 SYSLEVEL_ReleaseWin16Lock();
1037 pdb = PROCESS_Create( pModule, new_cmd_line, env,
1038 hInstance, hPrevInstance,
1039 NULL, NULL, TRUE, 0, &startup, &info );
1040 SYSLEVEL_RestoreWin16Lock();
1042 CloseHandle( info.hThread );
1043 CloseHandle( info.hProcess );
1045 if (params->hEnvironment) GlobalUnlock16( params->hEnvironment );
1046 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1050 /**********************************************************************
1053 BOOL NE_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmd_line, LPCSTR env,
1054 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1055 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1056 LPPROCESS_INFORMATION info )
1058 HINSTANCE16 hInstance, hPrevInstance = 0;
1063 /* Special case: second instance of an already loaded NE module */
1065 if ( ( hModule = GetModuleHandle16( ofs->szPathName ) ) != 0 )
1067 if ( !( pModule = NE_GetPtr( hModule) )
1068 || ( pModule->flags & NE_FFLAGS_LIBMODULE )
1069 || pModule->module32 )
1071 SetLastError( ERROR_BAD_FORMAT );
1075 hInstance = NE_CreateInstance( pModule, &hPrevInstance, FALSE );
1076 if ( hInstance != hPrevInstance ) /* not a library */
1077 NE_LoadSegment( pModule, pModule->dgroup );
1082 /* Main case: load first instance of NE module */
1085 /* If we didn't get a file handle, return */
1087 if ( hFile == HFILE_ERROR )
1090 /* Allocate temporary HFILE16 for NE_LoadFileModule */
1092 if (!DuplicateHandle( GetCurrentProcess(), hFile,
1093 GetCurrentProcess(), &hFile,
1094 0, FALSE, DUPLICATE_SAME_ACCESS ))
1096 SetLastError( ERROR_INVALID_HANDLE );
1099 hFile16 = FILE_AllocDosHandle( hFile );
1103 hInstance = NE_LoadFileModule( hFile16, ofs, TRUE );
1104 _lclose16( hFile16 );
1106 if ( hInstance < 32 )
1108 SetLastError( hInstance );
1112 if ( !( pModule = NE_GetPtr( hInstance ) )
1113 || ( pModule->flags & NE_FFLAGS_LIBMODULE) )
1115 /* FIXME: cleanup */
1116 SetLastError( ERROR_BAD_FORMAT );
1121 /* Create a task for this instance */
1123 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1125 if ( !PROCESS_Create( pModule, cmd_line, env,
1126 hInstance, hPrevInstance,
1127 psa, tsa, inherit, flags, startup, info ) )
1133 /***********************************************************************
1134 * LoadLibrary16 (KERNEL.95)
1136 * In Win95 LoadLibrary16("c:/junkname/user.foo") returns the HINSTANCE
1137 * to user.exe. As GetModuleHandle as of 990425 explicitly asks _not_
1138 * to change its handling of extensions, we have to try a stripped down
1139 * libname here too (bon 990425)
1141 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1143 char strippedname[256];
1144 char *dirsep1,*dirsep2;
1147 dirsep1=strrchr(libname,'\\');
1148 dirsep2=strrchr(libname,'/');
1149 dirsep1=MAX(dirsep1,dirsep2);
1151 dirsep1 =(LPSTR)libname;
1154 lstrcpynA(strippedname,dirsep1,256);
1155 dirsep1=strchr(strippedname,'.');
1159 TRACE("looking for (%p) %s and %s \n",
1160 libname, libname,strippedname );
1162 /* Load library module */
1163 ret= LoadModule16( strippedname, (LPVOID)-1 );
1164 if (ret > HINSTANCE_ERROR)
1166 return LoadModule16(libname, (LPVOID)-1 );
1170 /**********************************************************************
1173 * Call a DLL's WEP, allowing it to shut down.
1174 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1176 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1178 FARPROC16 WEP = (FARPROC16)0;
1179 WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
1181 if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
1184 WARN("module %04x doesn't have a WEP\n", hModule );
1187 return Callbacks->CallWindowsExitProc( WEP, WEP_FREE_DLL );
1191 /**********************************************************************
1194 * Implementation of FreeModule16().
1196 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1198 HMODULE16 *hPrevModule;
1203 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1204 hModule = pModule->self;
1206 TRACE("%04x count %d\n", hModule, pModule->count );
1208 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1209 else pModule->count = 0;
1211 if (pModule->flags & NE_FFLAGS_BUILTIN)
1212 return FALSE; /* Can't free built-in module */
1216 if (pModule->flags & NE_FFLAGS_LIBMODULE)
1218 TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1219 MODULE_CallWEP( hModule );
1221 /* Free the objects owned by the DLL module */
1223 if (pTask && pTask->userhandler)
1224 pTask->userhandler( hModule, USIG16_DLL_UNLOAD, 0,
1225 pTask->hInstance, pTask->hQueue );
1227 PROCESS_CallUserSignalProc( USIG_DLL_UNLOAD_WIN16, hModule );
1230 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1234 /* Clear magic number just in case */
1236 pModule->magic = pModule->self = 0;
1238 /* Remove it from the linked list */
1240 hPrevModule = &hFirstModule;
1241 while (*hPrevModule && (*hPrevModule != hModule))
1243 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1245 if (*hPrevModule) *hPrevModule = pModule->next;
1247 /* Free the referenced modules */
1249 pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1250 for (i = 0; i < pModule->modref_count; i++, pModRef++)
1252 NE_FreeModule( *pModRef, call_wep );
1255 /* Free the module storage */
1257 GlobalFreeAll16( hModule );
1259 /* Remove module from cache */
1261 if (pCachedModule == pModule) pCachedModule = NULL;
1266 /**********************************************************************
1267 * FreeModule16 (KERNEL.46)
1269 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1271 return NE_FreeModule( hModule, TRUE );
1275 /***********************************************************************
1276 * FreeLibrary16 (KERNEL.96)
1278 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1280 TRACE("%04x\n", handle );
1281 FreeModule16( handle );
1285 /**********************************************************************
1286 * GetModuleName (KERNEL.27)
1288 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1293 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1294 p = (BYTE *)pModule + pModule->name_table;
1295 if (count > *p) count = *p + 1;
1298 memcpy( buf, p + 1, count - 1 );
1299 buf[count-1] = '\0';
1305 /**********************************************************************
1306 * GetModuleUsage (KERNEL.48)
1308 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1310 NE_MODULE *pModule = NE_GetPtr( hModule );
1311 return pModule ? pModule->count : 0;
1315 /**********************************************************************
1316 * GetExpWinVer (KERNEL.167)
1318 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1320 NE_MODULE *pModule = NE_GetPtr( hModule );
1321 return pModule ? pModule->expected_version : 0;
1325 /**********************************************************************
1326 * GetModuleFileName16 (KERNEL.49)
1328 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1333 if (!hModule) hModule = GetCurrentTask();
1334 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1335 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1336 TRACE("%s\n", lpFileName );
1337 return strlen(lpFileName);
1341 /**********************************************************************
1342 * GetModuleHandle16 (KERNEL.47)
1344 * Find a module from a module name.
1346 * NOTE: The current implementation works the same way the Windows 95 one
1347 * does. Do not try to 'fix' it, fix the callers.
1348 * + It does not do ANY extension handling (except that strange .EXE bit)!
1349 * + It does not care about paths, just about basenames. (same as Windows)
1353 * the win16 module handle if found
1355 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1356 * Always hFirstModule
1358 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1360 if (HIWORD(name) == 0)
1361 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1362 return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1365 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1367 HMODULE16 hModule = hFirstModule;
1369 BYTE len, *name_table;
1373 TRACE("(%s)\n", name);
1376 return GetExePtr(LOWORD(name));
1382 strncpy(tmpstr, name, sizeof(tmpstr));
1383 tmpstr[sizeof(tmpstr)-1] = '\0';
1385 /* If 'name' matches exactly the module name of a module:
1386 * Return its handle.
1388 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1390 pModule = NE_GetPtr( hModule );
1391 if (!pModule) break;
1393 name_table = (BYTE *)pModule + pModule->name_table;
1394 if ((*name_table == len) && !strncmp(name, name_table+1, len))
1398 /* If uppercased 'name' matches exactly the module name of a module:
1401 for (s = tmpstr; *s; s++)
1404 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1406 pModule = NE_GetPtr( hModule );
1407 if (!pModule) break;
1409 name_table = (BYTE *)pModule + pModule->name_table;
1410 if ((*name_table == len) && !strncmp(tmpstr, name_table+1, len))
1414 /* If the base filename of 'name' matches the base filename of the module
1415 * filename of some module (case-insensitive compare):
1416 * Return its handle.
1419 /* basename: search backwards in passed name to \ / or : */
1420 s = tmpstr + strlen(tmpstr);
1423 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1428 /* search this in loaded filename list */
1429 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1434 pModule = NE_GetPtr( hModule );
1435 if (!pModule) break;
1436 if (!pModule->fileinfo) continue;
1438 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1439 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1440 /* basename: search backwards in pathname to \ / or : */
1441 while (loadedfn > (char*)ofs->szPathName)
1443 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1447 /* case insensitive compare ... */
1448 if (!lstrcmpiA(loadedfn, s))
1452 /* If the extension of 'name' is '.EXE' and the base filename of 'name'
1453 * matches the base filename of the module filename of some 32-bit module:
1454 * Return the corresponding 16-bit dummy module handle.
1456 if (len >= 4 && !strcasecmp(name+len-4, ".EXE"))
1458 HMODULE hModule = GetModuleHandleA( name );
1460 return MapHModuleLS( hModule );
1463 if (!strcmp(tmpstr,"MSDOS"))
1466 if (!strcmp(tmpstr,"TIMER"))
1468 FIXME("Eh... Should return caller's code segment, expect crash\n");
1476 /**********************************************************************
1477 * ModuleFirst (TOOLHELP.59)
1479 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1481 lpme->wNext = hFirstModule;
1482 return ModuleNext16( lpme );
1486 /**********************************************************************
1487 * ModuleNext (TOOLHELP.60)
1489 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1494 if (!lpme->wNext) return FALSE;
1495 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1496 name = (char *)pModule + pModule->name_table;
1497 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1498 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1499 lpme->hModule = lpme->wNext;
1500 lpme->wcUsage = pModule->count;
1501 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1502 lpme->wNext = pModule->next;
1507 /**********************************************************************
1508 * ModuleFindName (TOOLHELP.61)
1510 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1512 lpme->wNext = GetModuleHandle16( name );
1513 return ModuleNext16( lpme );
1517 /**********************************************************************
1518 * ModuleFindHandle (TOOLHELP.62)
1520 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1522 hModule = GetExePtr( hModule );
1523 lpme->wNext = hModule;
1524 return ModuleNext16( lpme );
1528 /***************************************************************************
1529 * MapHModuleLS (KERNEL32.520)
1531 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod) {
1535 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1537 return hmod; /* we already have a 16 bit module handle */
1538 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1540 if (pModule->module32 == hmod)
1541 return pModule->self;
1542 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1547 /***************************************************************************
1548 * MapHModuleSL (KERNEL32.521)
1550 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod) {
1554 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1556 hmod = pTask->hModule;
1558 pModule = (NE_MODULE*)GlobalLock16(hmod);
1559 if ( (pModule->magic!=IMAGE_OS2_SIGNATURE) ||
1560 !(pModule->flags & NE_FFLAGS_WIN32)
1563 return pModule->module32;
1566 /***************************************************************************
1567 * MapHInstLS (KERNEL32.516)
1569 void WINAPI REGS_FUNC(MapHInstLS)( CONTEXT *context )
1572 EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1576 /***************************************************************************
1577 * MapHInstSL (KERNEL32.518)
1579 void WINAPI REGS_FUNC(MapHInstSL)( CONTEXT *context )
1582 EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1586 /***************************************************************************
1587 * MapHInstLS_PN (KERNEL32.517)
1589 void WINAPI REGS_FUNC(MapHInstLS_PN)( CONTEXT *context )
1592 if (EAX_reg(context))
1593 EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1597 /***************************************************************************
1598 * MapHInstSL_PN (KERNEL32.519)
1600 void WINAPI REGS_FUNC(MapHInstSL_PN)( CONTEXT *context )
1603 if (EAX_reg(context))
1604 EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1608 /***************************************************************************
1609 * WIN16_MapHInstLS (KERNEL.472)
1611 VOID WINAPI WIN16_MapHInstLS( CONTEXT86 *context )
1613 EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1616 /***************************************************************************
1617 * WIN16_MapHInstSL (KERNEL.473)
1619 VOID WINAPI WIN16_MapHInstSL( CONTEXT86 *context )
1621 EAX_reg(context) = MapHModuleSL(EAX_reg(context));