4 * Copyright 1995 Alexandre Julliard
13 #include "wine/winbase16.h"
28 #include "stackframe.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;
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 MSG( "**** %04x is not a module handle\n", hModule );
76 /* Dump the module info */
78 DUMP( "Module %04x:\n", hModule );
79 DUMP( "count=%d flags=%04x heap=%d stack=%d\n",
80 pModule->count, pModule->flags,
81 pModule->heap_size, pModule->stack_size );
82 DUMP( "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 DUMP( "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 DUMP( "PE module=%08x\n", pModule->module32 );
91 /* Dump the file info */
93 DUMP( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
95 /* Dump the segment table */
97 DUMP( "Segment table:\n" );
98 pSeg = NE_SEG_TABLE( pModule );
99 for (i = 0; i < pModule->seg_count; i++, pSeg++)
100 DUMP( "%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 DUMP( "Resource table:\n" );
107 if (pModule->res_table)
109 pword = (WORD *)((BYTE *)pModule + pModule->res_table);
110 DUMP( "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 DUMP( "id=%04x count=%d\n", ptr->type_id, ptr->count );
116 for (i = 0; i < ptr->count; i++, pname++)
117 DUMP( "offset=%d len=%d id=%04x\n",
118 pname->offset, pname->length, pname->id );
119 pword = (WORD *)pname;
122 else DUMP( "None\n" );
124 /* Dump the resident name table */
126 DUMP( "Resident-name table:\n" );
127 pstr = (char *)pModule + pModule->name_table;
130 DUMP( "%*.*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 DUMP( "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 DUMP( "%d: %04x -> '%s'\n", i, *pword, name );
148 else DUMP( "None\n" );
150 /* Dump the entry table */
152 DUMP( "Entry table:\n" );
153 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->entry_table);
155 entry = (ET_ENTRY *)((BYTE *)bundle+6);
156 DUMP( "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 DUMP("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
163 DUMP("%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 DUMP( "Non-resident names table:\n" );
172 if (pModule->nrname_handle)
174 pstr = (char *)GlobalLock16( pModule->nrname_handle );
177 DUMP( "%*.*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 MSG( "Module Flags Name\n" );
197 NE_MODULE *pModule = NE_GetPtr( hModule );
200 MSG( "Bad module %04x in list\n", hModule );
203 MSG( " %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( module, "(%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(module, " 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(module, " 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( module, "(%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 MSG( "Can't open file '%s' for module %04x\n", name, pModule->self );
383 /* FIXME: should not be necessary */
384 cachedfd = ConvertToGlobalHandle(cachedfd);
385 TRACE(module, "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 MSG("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(module, "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( module, "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(module, "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(module, "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(module, "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(module, "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(module, "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(module, "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 MSG( "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 ))
817 return 2; /* File not found (FIXME: free everything) */
819 /* Load the segments */
821 NE_LoadAllSegments( pModule );
823 /* Fixup the functions prologs */
825 NE_FixupPrologs( pModule );
827 /* Make sure the usage count is 1 on the first loading of */
828 /* the module, even if it contains circular DLL references */
835 /**********************************************************************
838 * Load first instance of NE module, deciding whether to use
839 * built-in module or load module from file.
840 * (Note: caller is responsible for ensuring the module isn't
843 HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL implicit )
845 HINSTANCE16 hInstance;
849 if ((hFile = OpenFile16( name, &ofs, OF_READ )) == HFILE_ERROR16)
855 /* 4 == strlen(".dll") */
856 strncpy(buffer, name, sizeof(buffer) - 1 - 4);
857 strcat(buffer, ".dll");
858 if ((hFile = OpenFile16( buffer, &ofs, OF_READ )) == HFILE_ERROR16)
859 return 2; /* File not found */
863 hInstance = NE_LoadFileModule( hFile, &ofs, implicit );
870 /**********************************************************************
871 * MODULE_LoadModule16
873 * Load a NE module in the order of the loadorder specification.
874 * The caller is responsible that the module is not loaded already.
877 HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit )
881 module_loadorder_t *plo;
883 plo = MODULE_GetLoadOrder(libname);
885 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
887 switch(plo->loadorder[i])
889 case MODULE_LOADORDER_DLL:
890 TRACE(module, "Trying native dll '%s'\n", libname);
891 hinst = NE_LoadModule(libname, implicit);
894 case MODULE_LOADORDER_ELFDLL:
895 TRACE(module, "Trying elfdll '%s'\n", libname);
896 hinst = ELFDLL_LoadModule16(libname, implicit);
899 case MODULE_LOADORDER_BI:
900 TRACE(module, "Trying built-in '%s'\n", libname);
901 hinst = fnBUILTIN_LoadModule(libname, TRUE);
905 ERR(module, "Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
908 case MODULE_LOADORDER_SO: /* This is not supported for NE modules */
909 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
921 hModule = GetModuleHandle16(libname);
924 ERR(module, "Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle\n",
926 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
929 pModule = NE_GetPtr(hModule);
932 ERR(module, "Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
934 return 6; /* ERROR_INVALID_HANDLE seems most appropriate */
937 TRACE(module, "Loaded module '%s' at 0x%04x, \n", libname, hinst);
940 * Call initialization routines for all loaded DLLs. Note that
941 * when we load implicitly linked DLLs this will be done by InitTask().
943 if(pModule->flags & NE_FFLAGS_LIBMODULE)
944 NE_InitializeDLLs(hModule);
951 /* We quit searching when we get another error than 'File not found' */
955 return hinst; /* The last error that occured */
959 /**********************************************************************
960 * LoadModule16 (KERNEL.45)
962 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
964 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
965 LOADPARAMS16 *params;
966 LPSTR cmd_line, new_cmd_line;
968 STARTUPINFOA startup;
969 PROCESS_INFORMATION info;
970 HINSTANCE16 hInstance, hPrevInstance = 0;
977 if ( (hModule = GetModuleHandle16(name) ) != 0 )
979 /* Special case: second instance of an already loaded NE module */
981 if ( !( pModule = NE_GetPtr( hModule ) ) ) return (HINSTANCE16)11;
982 if ( pModule->module32 ) return (HINSTANCE16)21;
984 hInstance = NE_CreateInstance( pModule, &hPrevInstance, lib_only );
985 if ( hInstance != hPrevInstance ) /* not a library */
986 NE_LoadSegment( pModule, pModule->dgroup );
992 /* Main case: load first instance of NE module */
994 if ( (hInstance = MODULE_LoadModule16( name, FALSE )) < 32 )
997 if ( !(pModule = NE_GetPtr( hInstance )) )
998 return (HINSTANCE16)11;
1001 /* If library module, we're finished */
1003 if ( ( pModule->flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1006 /* Create a task for this instance */
1008 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1010 params = (LOADPARAMS16 *)paramBlock;
1011 cmd_line = (LPSTR)PTR_SEG_TO_LIN( params->cmdLine );
1012 if (!cmd_line) cmd_line = "";
1013 else if (*cmd_line) cmd_line++; /* skip the length byte */
1015 if (!(new_cmd_line = HeapAlloc( GetProcessHeap(), 0,
1016 strlen(cmd_line)+strlen(name)+2 )))
1018 strcpy( new_cmd_line, name );
1019 strcat( new_cmd_line, " " );
1020 strcat( new_cmd_line, cmd_line );
1022 if (params->hEnvironment) env = GlobalLock16( params->hEnvironment );
1024 memset( &info, '\0', sizeof(info) );
1025 memset( &startup, '\0', sizeof(startup) );
1026 startup.cb = sizeof(startup);
1027 if (params->showCmd)
1029 startup.dwFlags = STARTF_USESHOWWINDOW;
1030 startup.wShowWindow = ((UINT16 *)PTR_SEG_TO_LIN(params->showCmd))[1];
1033 SYSLEVEL_ReleaseWin16Lock();
1034 pdb = PROCESS_Create( pModule, new_cmd_line, env,
1035 hInstance, hPrevInstance,
1036 NULL, NULL, TRUE, 0, &startup, &info );
1037 SYSLEVEL_RestoreWin16Lock();
1039 CloseHandle( info.hThread );
1040 CloseHandle( info.hProcess );
1042 if (params->hEnvironment) GlobalUnlock16( params->hEnvironment );
1043 HeapFree( GetProcessHeap(), 0, new_cmd_line );
1047 /**********************************************************************
1050 BOOL NE_CreateProcess( HFILE hFile, OFSTRUCT *ofs, LPCSTR cmd_line, LPCSTR env,
1051 LPSECURITY_ATTRIBUTES psa, LPSECURITY_ATTRIBUTES tsa,
1052 BOOL inherit, DWORD flags, LPSTARTUPINFOA startup,
1053 LPPROCESS_INFORMATION info )
1055 HINSTANCE16 hInstance, hPrevInstance = 0;
1060 /* Special case: second instance of an already loaded NE module */
1062 if ( ( hModule = GetModuleHandle16( ofs->szPathName ) ) != 0 )
1064 if ( !( pModule = NE_GetPtr( hModule) )
1065 || ( pModule->flags & NE_FFLAGS_LIBMODULE )
1066 || pModule->module32 )
1068 SetLastError( ERROR_BAD_FORMAT );
1072 hInstance = NE_CreateInstance( pModule, &hPrevInstance, FALSE );
1073 if ( hInstance != hPrevInstance ) /* not a library */
1074 NE_LoadSegment( pModule, pModule->dgroup );
1079 /* Main case: load first instance of NE module */
1082 /* If we didn't get a file handle, return */
1084 if ( hFile == HFILE_ERROR )
1087 /* Allocate temporary HFILE16 for NE_LoadFileModule */
1089 if (!DuplicateHandle( GetCurrentProcess(), hFile,
1090 GetCurrentProcess(), &hFile,
1091 0, FALSE, DUPLICATE_SAME_ACCESS ))
1093 SetLastError( ERROR_INVALID_HANDLE );
1096 hFile16 = FILE_AllocDosHandle( hFile );
1100 hInstance = NE_LoadFileModule( hFile16, ofs, TRUE );
1101 _lclose16( hFile16 );
1103 if ( hInstance < 32 )
1105 SetLastError( hInstance );
1109 if ( !( pModule = NE_GetPtr( hInstance ) )
1110 || ( pModule->flags & NE_FFLAGS_LIBMODULE) )
1112 /* FIXME: cleanup */
1113 SetLastError( ERROR_BAD_FORMAT );
1118 /* Create a task for this instance */
1120 pModule->flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1122 if ( !PROCESS_Create( pModule, cmd_line, env,
1123 hInstance, hPrevInstance,
1124 psa, tsa, inherit, flags, startup, info ) )
1130 /***********************************************************************
1131 * LoadLibrary16 (KERNEL.95)
1133 * In Win95 LoadLibrary16("c:/junkname/user.foo") returns the HINSTANCE
1134 * to user.exe. As GetModuleHandle as of 990425 explicitly asks _not_
1135 * to change its handling of extensions, we have to try a stripped down
1136 * libname here too (bon 990425)
1138 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1140 char strippedname[256];
1141 char *dirsep1,*dirsep2;
1144 dirsep1=strrchr(libname,'\\');
1145 dirsep2=strrchr(libname,'/');
1146 dirsep1=MAX(dirsep1,dirsep2);
1148 dirsep1 =(LPSTR)libname;
1151 lstrcpynA(strippedname,dirsep1,256);
1152 dirsep1=strchr(strippedname,'.');
1156 TRACE( module, "looking for (%p) %s and %s \n",
1157 libname, libname,strippedname );
1159 /* Load library module */
1160 ret= LoadModule16( strippedname, (LPVOID)-1 );
1161 if (ret > HINSTANCE_ERROR)
1163 return LoadModule16(libname, (LPVOID)-1 );
1167 /**********************************************************************
1170 * Call a DLL's WEP, allowing it to shut down.
1171 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1173 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1175 FARPROC16 WEP = (FARPROC16)0;
1176 WORD ordinal = NE_GetOrdinal( hModule, "WEP" );
1178 if (ordinal) WEP = NE_GetEntryPoint( hModule, ordinal );
1181 WARN(module, "module %04x doesn't have a WEP\n", hModule );
1184 return Callbacks->CallWindowsExitProc( WEP, WEP_FREE_DLL );
1188 /**********************************************************************
1191 * Implementation of FreeModule16().
1193 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1195 HMODULE16 *hPrevModule;
1200 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1201 hModule = pModule->self;
1203 TRACE( module, "%04x count %d\n", hModule, pModule->count );
1205 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1206 else pModule->count = 0;
1208 if (pModule->flags & NE_FFLAGS_BUILTIN)
1209 return FALSE; /* Can't free built-in module */
1213 if (pModule->flags & NE_FFLAGS_LIBMODULE)
1215 TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
1216 MODULE_CallWEP( hModule );
1218 /* Free the objects owned by the DLL module */
1220 if (pTask && pTask->userhandler)
1221 pTask->userhandler( hModule, USIG16_DLL_UNLOAD, 0,
1222 pTask->hInstance, pTask->hQueue );
1224 PROCESS_CallUserSignalProc( USIG_DLL_UNLOAD_WIN16, hModule );
1227 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1231 /* Clear magic number just in case */
1233 pModule->magic = pModule->self = 0;
1235 /* Remove it from the linked list */
1237 hPrevModule = &hFirstModule;
1238 while (*hPrevModule && (*hPrevModule != hModule))
1240 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1242 if (*hPrevModule) *hPrevModule = pModule->next;
1244 /* Free the referenced modules */
1246 pModRef = (HMODULE16*)NE_MODULE_TABLE( pModule );
1247 for (i = 0; i < pModule->modref_count; i++, pModRef++)
1249 NE_FreeModule( *pModRef, call_wep );
1252 /* Free the module storage */
1254 GlobalFreeAll16( hModule );
1256 /* Remove module from cache */
1258 if (pCachedModule == pModule) pCachedModule = NULL;
1263 /**********************************************************************
1264 * FreeModule16 (KERNEL.46)
1266 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1268 return NE_FreeModule( hModule, TRUE );
1272 /***********************************************************************
1273 * FreeLibrary16 (KERNEL.96)
1275 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1277 TRACE(module,"%04x\n", handle );
1278 FreeModule16( handle );
1282 /**********************************************************************
1283 * GetModuleName (KERNEL.27)
1285 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1290 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1291 p = (BYTE *)pModule + pModule->name_table;
1292 if (count > *p) count = *p + 1;
1295 memcpy( buf, p + 1, count - 1 );
1296 buf[count-1] = '\0';
1302 /**********************************************************************
1303 * GetModuleUsage (KERNEL.48)
1305 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1307 NE_MODULE *pModule = NE_GetPtr( hModule );
1308 return pModule ? pModule->count : 0;
1312 /**********************************************************************
1313 * GetExpWinVer (KERNEL.167)
1315 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1317 NE_MODULE *pModule = NE_GetPtr( hModule );
1318 return pModule ? pModule->expected_version : 0;
1322 /**********************************************************************
1323 * GetModuleFileName16 (KERNEL.49)
1325 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1330 if (!hModule) hModule = GetCurrentTask();
1331 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1332 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1333 TRACE(module, "%s\n", lpFileName );
1334 return strlen(lpFileName);
1338 /**********************************************************************
1339 * GetModuleHandle16 (KERNEL.47)
1341 * Find a module from a module name.
1343 * NOTE: The current implementation works the same way the Windows 95 one
1344 * does. Do not try to 'fix' it, fix the callers.
1345 * + It does not do ANY extension handling (except that strange .EXE bit)!
1346 * + It does not care about paths, just about basenames. (same as Windows)
1350 * the win16 module handle if found
1352 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1353 * Always hFirstModule
1355 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1357 if (HIWORD(name) == 0)
1358 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1359 return MAKELONG(GetModuleHandle16( PTR_SEG_TO_LIN(name)), hFirstModule );
1362 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1364 HMODULE16 hModule = hFirstModule;
1366 BYTE len, *name_table;
1370 TRACE(module, "(%s)\n", name);
1373 return GetExePtr(LOWORD(name));
1379 strncpy(tmpstr, name, sizeof(tmpstr));
1380 tmpstr[sizeof(tmpstr)-1] = '\0';
1382 /* If 'name' matches exactly the module name of a module:
1383 * Return its handle.
1385 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1387 pModule = NE_GetPtr( hModule );
1388 if (!pModule) break;
1390 name_table = (BYTE *)pModule + pModule->name_table;
1391 if ((*name_table == len) && !strncmp(name, name_table+1, len))
1395 /* If uppercased 'name' matches exactly the module name of a module:
1398 for (s = tmpstr; *s; s++)
1401 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1403 pModule = NE_GetPtr( hModule );
1404 if (!pModule) break;
1406 name_table = (BYTE *)pModule + pModule->name_table;
1407 if ((*name_table == len) && !strncmp(tmpstr, name_table+1, len))
1411 /* If the base filename of 'name' matches the base filename of the module
1412 * filename of some module (case-insensitive compare):
1413 * Return its handle.
1416 /* basename: search backwards in passed name to \ / or : */
1417 s = tmpstr + strlen(tmpstr);
1420 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1425 /* search this in loaded filename list */
1426 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1431 pModule = NE_GetPtr( hModule );
1432 if (!pModule) break;
1433 if (!pModule->fileinfo) continue;
1435 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1436 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1437 /* basename: search backwards in pathname to \ / or : */
1438 while (loadedfn > (char*)ofs->szPathName)
1440 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1444 /* case insensitive compare ... */
1445 if (!lstrcmpiA(loadedfn, s))
1449 /* If the extension of 'name' is '.EXE' and the base filename of 'name'
1450 * matches the base filename of the module filename of some 32-bit module:
1451 * Return the corresponding 16-bit dummy module handle.
1453 if (len >= 4 && !strcasecmp(name+len-4, ".EXE"))
1455 HMODULE hModule = GetModuleHandleA( name );
1457 return MapHModuleLS( hModule );
1460 if (!strcmp(tmpstr,"MSDOS"))
1463 if (!strcmp(tmpstr,"TIMER"))
1465 FIXME(module, "Eh... Should return caller's code segment, expect crash\n");
1473 /**********************************************************************
1474 * ModuleFirst (TOOLHELP.59)
1476 BOOL16 WINAPI ModuleFirst16( MODULEENTRY *lpme )
1478 lpme->wNext = hFirstModule;
1479 return ModuleNext16( lpme );
1483 /**********************************************************************
1484 * ModuleNext (TOOLHELP.60)
1486 BOOL16 WINAPI ModuleNext16( MODULEENTRY *lpme )
1491 if (!lpme->wNext) return FALSE;
1492 if (!(pModule = NE_GetPtr( lpme->wNext ))) return FALSE;
1493 name = (char *)pModule + pModule->name_table;
1494 memcpy( lpme->szModule, name + 1, min(*name, MAX_MODULE_NAME) );
1495 lpme->szModule[min(*name, MAX_MODULE_NAME)] = '\0';
1496 lpme->hModule = lpme->wNext;
1497 lpme->wcUsage = pModule->count;
1498 lstrcpynA( lpme->szExePath, NE_MODULE_NAME(pModule), sizeof(lpme->szExePath) );
1499 lpme->wNext = pModule->next;
1504 /**********************************************************************
1505 * ModuleFindName (TOOLHELP.61)
1507 BOOL16 WINAPI ModuleFindName16( MODULEENTRY *lpme, LPCSTR name )
1509 lpme->wNext = GetModuleHandle16( name );
1510 return ModuleNext16( lpme );
1514 /**********************************************************************
1515 * ModuleFindHandle (TOOLHELP.62)
1517 BOOL16 WINAPI ModuleFindHandle16( MODULEENTRY *lpme, HMODULE16 hModule )
1519 hModule = GetExePtr( hModule );
1520 lpme->wNext = hModule;
1521 return ModuleNext16( lpme );
1525 /***************************************************************************
1526 * MapHModuleLS (KERNEL32.520)
1528 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod) {
1532 return ((TDB*)GlobalLock16(GetCurrentTask()))->hInstance;
1534 return hmod; /* we already have a 16 bit module handle */
1535 pModule = (NE_MODULE*)GlobalLock16(hFirstModule);
1537 if (pModule->module32 == hmod)
1538 return pModule->self;
1539 pModule = (NE_MODULE*)GlobalLock16(pModule->next);
1544 /***************************************************************************
1545 * MapHModuleSL (KERNEL32.521)
1547 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod) {
1551 TDB *pTask = (TDB*)GlobalLock16(GetCurrentTask());
1553 hmod = pTask->hModule;
1555 pModule = (NE_MODULE*)GlobalLock16(hmod);
1556 if ( (pModule->magic!=IMAGE_OS2_SIGNATURE) ||
1557 !(pModule->flags & NE_FFLAGS_WIN32)
1560 return pModule->module32;
1563 /***************************************************************************
1564 * MapHInstLS (KERNEL32.516)
1566 void WINAPI REGS_FUNC(MapHInstLS)( CONTEXT *context )
1568 EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1571 /***************************************************************************
1572 * MapHInstSL (KERNEL32.518)
1574 void WINAPI REGS_FUNC(MapHInstSL)( CONTEXT *context )
1576 EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1579 /***************************************************************************
1580 * MapHInstLS_PN (KERNEL32.517)
1582 void WINAPI REGS_FUNC(MapHInstLS_PN)( CONTEXT *context )
1584 if (EAX_reg(context))
1585 EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1588 /***************************************************************************
1589 * MapHInstSL_PN (KERNEL32.519)
1591 void WINAPI REGS_FUNC(MapHInstSL_PN)( CONTEXT *context )
1593 if (EAX_reg(context))
1594 EAX_reg(context) = MapHModuleSL(EAX_reg(context));
1597 /***************************************************************************
1598 * WIN16_MapHInstLS (KERNEL.472)
1600 VOID WINAPI WIN16_MapHInstLS( CONTEXT *context ) {
1601 EAX_reg(context) = MapHModuleLS(EAX_reg(context));
1604 /***************************************************************************
1605 * WIN16_MapHInstSL (KERNEL.473)
1607 VOID WINAPI WIN16_MapHInstSL( CONTEXT *context ) {
1608 EAX_reg(context) = MapHModuleSL(EAX_reg(context));