kernel32/tests/pipe: Enable compilation with long types.
[wine.git] / dlls / krnl386.exe16 / ne_module.c
blob82b976fab6b8a09ac64dce4e0264a5ca9e25e6ba
1 /*
2 * NE modules
4 * Copyright 1995 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <assert.h>
22 #include <fcntl.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
29 #include "windef.h"
30 #include "wine/winbase16.h"
31 #include "wownt32.h"
32 #include "winternl.h"
33 #include "kernel16_private.h"
34 #include "wine/exception.h"
35 #include "wine/debug.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(module);
38 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
39 WINE_DECLARE_DEBUG_CHANNEL(relay);
40 WINE_DECLARE_DEBUG_CHANNEL(winediag);
42 #include "pshpack1.h"
43 typedef struct _GPHANDLERDEF
45 WORD selector;
46 WORD rangeStart;
47 WORD rangeEnd;
48 WORD handler;
49 } GPHANDLERDEF;
50 #include "poppack.h"
53 * Segment table entry
55 struct ne_segment_table_entry_s
57 WORD seg_data_offset; /* Sector offset of segment data */
58 WORD seg_data_length; /* Length of segment data */
59 WORD seg_flags; /* Flags associated with this segment */
60 WORD min_alloc; /* Minimum allocation size for this */
63 #define hFirstModule (pThhook->hExeHead)
65 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only );
66 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep );
68 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only );
70 static HMODULE16 NE_GetModuleByFilename( LPCSTR name );
73 /* patch all the flat cs references of the code segment if necessary */
74 static inline void patch_code_segment( NE_MODULE *pModule )
76 int i;
77 CALLFROM16 *call;
78 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule );
80 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
81 if (!(pSeg->flags & NE_SEGFLAGS_DATA)) break; /* found the code segment */
83 call = GlobalLock16( pSeg->hSeg );
85 /* patch glue code address and code selector */
86 for (i = 0; call[i].pushl == 0x68; i++)
88 if (call[i].ret[0] == 0xca66 || call[i].ret[0] == 0xcb66) /* register entry point? */
89 call[i].glue = __wine_call_from_16_regs;
90 else
91 call[i].glue = __wine_call_from_16;
92 call[i].flatcs = get_cs();
95 if (TRACE_ON(relay)) /* patch relay functions to all point to relay_call_from_16 */
96 for (i = 0; call[i].pushl == 0x68; i++) call[i].relay = relay_call_from_16;
100 /***********************************************************************
101 * contains_path
103 static inline BOOL contains_path( LPCSTR name )
105 return ((*name && (name[1] == ':')) || strchr(name, '/') || strchr(name, '\\'));
109 /***********************************************************************
110 * NE_GetPtr
112 NE_MODULE *NE_GetPtr( HMODULE16 hModule )
114 return GlobalLock16( GetExePtr(hModule) );
118 /**********************************************************************
119 * NE_RegisterModule
121 static void NE_RegisterModule( NE_MODULE *pModule )
123 pModule->next = hFirstModule;
124 hFirstModule = pModule->self;
128 /***********************************************************************
129 * NE_DumpModule
131 void NE_DumpModule( HMODULE16 hModule )
133 int i, ordinal;
134 SEGTABLEENTRY *pSeg;
135 BYTE *pstr;
136 WORD *pword;
137 NE_MODULE *pModule;
138 ET_BUNDLE *bundle;
139 ET_ENTRY *entry;
141 if (!(pModule = NE_GetPtr( hModule )))
143 ERR( "**** %04x is not a module handle\n", hModule );
144 return;
147 /* Dump the module info */
148 TRACE( "---\n" );
149 TRACE( "Module %04x:\n", hModule );
150 TRACE( "count=%d flags=%04x heap=%d stack=%d\n",
151 pModule->count, pModule->ne_flags,
152 pModule->ne_heap, pModule->ne_stack );
153 TRACE( "cs:ip=%04x:%04x ss:sp=%04x:%04x ds=%04x nb seg=%d modrefs=%d\n",
154 SELECTOROF(pModule->ne_csip), OFFSETOF(pModule->ne_csip),
155 SELECTOROF(pModule->ne_sssp), OFFSETOF(pModule->ne_sssp),
156 pModule->ne_autodata, pModule->ne_cseg, pModule->ne_cmod );
157 TRACE( "os_flags=%d swap_area=%d version=%04x\n",
158 pModule->ne_exetyp, pModule->ne_swaparea, pModule->ne_expver );
159 if (pModule->ne_flags & NE_FFLAGS_WIN32)
160 TRACE( "PE module=%p\n", pModule->module32 );
162 /* Dump the file info */
163 TRACE( "---\n" );
164 TRACE( "Filename: '%s'\n", NE_MODULE_NAME(pModule) );
166 /* Dump the segment table */
167 TRACE( "---\n" );
168 TRACE( "Segment table:\n" );
169 pSeg = NE_SEG_TABLE( pModule );
170 for (i = 0; i < pModule->ne_cseg; i++, pSeg++)
171 TRACE( "%02x: pos=%d size=%d flags=%04x minsize=%d hSeg=%04x\n",
172 i + 1, pSeg->filepos, pSeg->size, pSeg->flags,
173 pSeg->minsize, pSeg->hSeg );
175 /* Dump the resource table */
176 TRACE( "---\n" );
177 TRACE( "Resource table:\n" );
178 if (pModule->ne_rsrctab)
180 pword = (WORD *)((BYTE *)pModule + pModule->ne_rsrctab);
181 TRACE( "Alignment: %d\n", *pword++ );
182 while (*pword)
184 NE_TYPEINFO *ptr = (NE_TYPEINFO *)pword;
185 NE_NAMEINFO *pname = (NE_NAMEINFO *)(ptr + 1);
186 TRACE( "id=%04x count=%d\n", ptr->type_id, ptr->count );
187 for (i = 0; i < ptr->count; i++, pname++)
188 TRACE( "offset=%d len=%d id=%04x\n",
189 pname->offset, pname->length, pname->id );
190 pword = (WORD *)pname;
193 else TRACE( "None\n" );
195 /* Dump the resident name table */
196 TRACE( "---\n" );
197 TRACE( "Resident-name table:\n" );
198 pstr = (BYTE*) pModule + pModule->ne_restab;
199 while (*pstr)
201 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
202 *(WORD *)(pstr + *pstr + 1) );
203 pstr += *pstr + 1 + sizeof(WORD);
206 /* Dump the module reference table */
207 TRACE( "---\n" );
208 TRACE( "Module ref table:\n" );
209 if (pModule->ne_modtab)
211 pword = (WORD *)((BYTE *)pModule + pModule->ne_modtab);
212 for (i = 0; i < pModule->ne_cmod; i++, pword++)
214 char name[10];
215 GetModuleName16( *pword, name, sizeof(name) );
216 TRACE( "%d: %04x -> '%s'\n", i, *pword, name );
219 else TRACE( "None\n" );
221 /* Dump the entry table */
222 TRACE( "---\n" );
223 TRACE( "Entry table:\n" );
224 bundle = (ET_BUNDLE *)((BYTE *)pModule+pModule->ne_enttab);
225 do {
226 entry = (ET_ENTRY *)((BYTE *)bundle+6);
227 TRACE( "Bundle %d-%d: %02x\n", bundle->first, bundle->last, entry->type);
228 ordinal = bundle->first;
229 while (ordinal < bundle->last)
231 if (entry->type == 0xff)
232 TRACE("%d: %02x:%04x (moveable)\n", ordinal++, entry->segnum, entry->offs);
233 else
234 TRACE("%d: %02x:%04x (fixed)\n", ordinal++, entry->segnum, entry->offs);
235 entry++;
237 } while ( (bundle->next) && (bundle = ((ET_BUNDLE *)((BYTE *)pModule + bundle->next))) );
239 /* Dump the non-resident names table */
240 TRACE( "---\n" );
241 TRACE( "Non-resident names table:\n" );
242 if (pModule->nrname_handle)
244 pstr = GlobalLock16( pModule->nrname_handle );
245 while (*pstr)
247 TRACE( "%*.*s: %d\n", *pstr, *pstr, pstr + 1,
248 *(WORD *)(pstr + *pstr + 1) );
249 pstr += *pstr + 1 + sizeof(WORD);
252 TRACE( "\n" );
256 /***********************************************************************
257 * NE_WalkModules
259 * Walk the module list and print the modules.
261 void NE_WalkModules(void)
263 HMODULE16 hModule = hFirstModule;
264 MESSAGE( "Module Flags Name\n" );
265 while (hModule)
267 NE_MODULE *pModule = NE_GetPtr( hModule );
268 if (!pModule)
270 MESSAGE( "Bad module %04x in list\n", hModule );
271 return;
273 MESSAGE( " %04x %04x %.*s\n", hModule, pModule->ne_flags,
274 *((char *)pModule + pModule->ne_restab),
275 (char *)pModule + pModule->ne_restab + 1 );
276 hModule = pModule->next;
281 /***********************************************************************
282 * NE_InitResourceHandler
284 * Fill in 'resloader' fields in the resource table.
286 static void NE_InitResourceHandler( HMODULE16 hModule )
288 static FARPROC16 proc;
290 NE_TYPEINFO *pTypeInfo;
291 NE_MODULE *pModule;
293 if (!(pModule = NE_GetPtr( hModule )) || !pModule->ne_rsrctab) return;
295 TRACE("InitResourceHandler[%04x]\n", hModule );
297 if (!proc) proc = GetProcAddress16( GetModuleHandle16("KERNEL"), "DefResourceHandler" );
299 pTypeInfo = (NE_TYPEINFO *)((char *)pModule + pModule->ne_rsrctab + 2);
300 while(pTypeInfo->type_id)
302 pTypeInfo->resloader = proc;
303 pTypeInfo = (NE_TYPEINFO *)((char*)(pTypeInfo + 1) + pTypeInfo->count * sizeof(NE_NAMEINFO));
308 /***********************************************************************
309 * NE_GetOrdinal
311 * Lookup the ordinal for a given name.
313 WORD NE_GetOrdinal( HMODULE16 hModule, const char *name )
315 char buffer[256], *p;
316 BYTE *cpnt;
317 BYTE len;
318 NE_MODULE *pModule;
320 if (!(pModule = NE_GetPtr( hModule ))) return 0;
321 if (pModule->ne_flags & NE_FFLAGS_WIN32) return 0;
323 TRACE("(%04x,'%s')\n", hModule, name );
325 /* First handle names of the form '#xxxx' */
327 if (name[0] == '#') return atoi( name + 1 );
329 /* Now copy and uppercase the string */
331 strcpy( buffer, name );
332 for (p = buffer; *p; p++) *p = RtlUpperChar(*p);
333 len = p - buffer;
335 /* First search the resident names */
337 cpnt = (BYTE *)pModule + pModule->ne_restab;
339 /* Skip the first entry (module name) */
340 cpnt += *cpnt + 1 + sizeof(WORD);
341 while (*cpnt)
343 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
345 WORD ordinal;
346 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
347 TRACE(" Found: ordinal=%d\n", ordinal );
348 return ordinal;
350 cpnt += *cpnt + 1 + sizeof(WORD);
353 /* Now search the non-resident names table */
355 if (!pModule->nrname_handle) return 0; /* No non-resident table */
356 cpnt = GlobalLock16( pModule->nrname_handle );
358 /* Skip the first entry (module description string) */
359 cpnt += *cpnt + 1 + sizeof(WORD);
360 while (*cpnt)
362 if ((*cpnt == len) && !memcmp( cpnt+1, buffer, len ))
364 WORD ordinal;
365 memcpy( &ordinal, cpnt + *cpnt + 1, sizeof(ordinal) );
366 TRACE(" Found: ordinal=%d\n", ordinal );
367 return ordinal;
369 cpnt += *cpnt + 1 + sizeof(WORD);
371 return 0;
375 /***********************************************************************
376 * NE_GetEntryPoint
378 FARPROC16 WINAPI NE_GetEntryPoint( HMODULE16 hModule, WORD ordinal )
380 return NE_GetEntryPointEx( hModule, ordinal, TRUE );
383 /***********************************************************************
384 * NE_GetEntryPointEx
386 FARPROC16 NE_GetEntryPointEx( HMODULE16 hModule, WORD ordinal, BOOL16 snoop )
388 NE_MODULE *pModule;
389 WORD sel, offset, i;
391 ET_ENTRY *entry;
392 ET_BUNDLE *bundle;
394 if (!(pModule = NE_GetPtr( hModule ))) return 0;
396 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
397 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
399 if (!(bundle->next))
400 return 0;
401 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
404 entry = (ET_ENTRY *)((BYTE *)bundle+6);
405 for (i=0; i < (ordinal - bundle->first - 1); i++)
406 entry++;
408 sel = entry->segnum;
409 memcpy( &offset, &entry->offs, sizeof(WORD) );
411 if (sel == 0xfe) sel = 0xffff; /* constant entry */
412 else sel = GlobalHandleToSel16(NE_SEG_TABLE(pModule)[sel-1].hSeg);
413 if (sel==0xffff)
414 return (FARPROC16)MAKESEGPTR( sel, offset );
415 if (!snoop)
416 return (FARPROC16)MAKESEGPTR( sel, offset );
417 else
418 return SNOOP16_GetProcAddress16(hModule,ordinal,(FARPROC16)MAKESEGPTR( sel, offset ));
422 /***********************************************************************
423 * EntryAddrProc (KERNEL.667) Wine-specific export
425 * Return the entry point for a given ordinal.
427 FARPROC16 WINAPI EntryAddrProc16( HMODULE16 hModule, WORD ordinal )
429 FARPROC16 ret = NE_GetEntryPointEx( hModule, ordinal, TRUE );
430 CURRENT_STACK16->ecx = hModule; /* FIXME: might be incorrect value */
431 return ret;
434 /***********************************************************************
435 * NE_SetEntryPoint
437 * Change the value of an entry point. Use with caution!
438 * It can only change the offset value, not the selector.
440 BOOL16 NE_SetEntryPoint( HMODULE16 hModule, WORD ordinal, WORD offset )
442 NE_MODULE *pModule;
443 ET_ENTRY *entry;
444 ET_BUNDLE *bundle;
445 int i;
447 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
449 bundle = (ET_BUNDLE *)((BYTE *)pModule + pModule->ne_enttab);
450 while ((ordinal < bundle->first + 1) || (ordinal > bundle->last))
452 bundle = (ET_BUNDLE *)((BYTE *)pModule + bundle->next);
453 if (!bundle->next) return FALSE;
456 entry = (ET_ENTRY *)((BYTE *)bundle+6);
457 for (i=0; i < (ordinal - bundle->first - 1); i++)
458 entry++;
460 memcpy( &entry->offs, &offset, sizeof(WORD) );
461 return TRUE;
465 /***********************************************************************
466 * build_bundle_data
468 * Build the entry table bundle data from the on-disk format. Helper for build_module.
470 static void *build_bundle_data( NE_MODULE *pModule, void *dest, const BYTE *table )
472 ET_BUNDLE *oldbundle, *bundle = dest;
473 ET_ENTRY *entry;
474 BYTE nr_entries, type;
476 memset(bundle, 0, sizeof(ET_BUNDLE)); /* in case no entry table exists */
477 entry = (ET_ENTRY *)((BYTE *)bundle+6);
479 while ((nr_entries = *table++))
481 if ((type = *table++))
483 bundle->last += nr_entries;
484 if (type == 0xff)
486 while (nr_entries--)
488 entry->type = type;
489 entry->flags = *table++;
490 table += sizeof(WORD);
491 entry->segnum = *table++;
492 entry->offs = *(const WORD *)table;
493 table += sizeof(WORD);
494 entry++;
497 else
499 while (nr_entries--)
501 entry->type = type;
502 entry->flags = *table++;
503 entry->segnum = type;
504 entry->offs = *(const WORD *)table;
505 table += sizeof(WORD);
506 entry++;
510 else
512 if (bundle->first == bundle->last)
514 bundle->first += nr_entries;
515 bundle->last += nr_entries;
517 else
519 oldbundle = bundle;
520 oldbundle->next = (char *)entry - (char *)pModule;
521 bundle = (ET_BUNDLE *)entry;
522 bundle->first = bundle->last = oldbundle->last + nr_entries;
523 bundle->next = 0;
524 entry = (ET_ENTRY*)(((BYTE*)entry)+sizeof(ET_BUNDLE));
528 return entry;
532 /***********************************************************************
533 * build_module
535 * Build the in-memory module from the on-disk data.
537 static HMODULE16 build_module( const void *mapping, SIZE_T mapping_size, LPCSTR path )
539 const IMAGE_DOS_HEADER *mz_header = mapping;
540 const IMAGE_OS2_HEADER *ne_header;
541 const struct ne_segment_table_entry_s *pSeg;
542 const void *ptr;
543 int i;
544 size_t size;
545 HMODULE16 hModule;
546 NE_MODULE *pModule;
547 BYTE *buffer, *pData, *end;
548 OFSTRUCT *ofs;
550 if (mapping_size < sizeof(*mz_header)) return ERROR_BAD_FORMAT;
551 if (mz_header->e_magic != IMAGE_DOS_SIGNATURE) return ERROR_BAD_FORMAT;
552 ne_header = (const IMAGE_OS2_HEADER *)((const char *)mapping + mz_header->e_lfanew);
553 if (mz_header->e_lfanew + sizeof(*ne_header) > mapping_size) return ERROR_BAD_FORMAT;
554 if (ne_header->ne_magic == IMAGE_NT_SIGNATURE) return 21; /* win32 exe */
555 if (ne_header->ne_magic == IMAGE_OS2_SIGNATURE_LX)
557 MESSAGE("Sorry, %s is an OS/2 linear executable (LX) file!\n", path);
558 return 12;
560 if (ne_header->ne_magic != IMAGE_OS2_SIGNATURE) return ERROR_BAD_FORMAT;
562 /* We now have a valid NE header */
564 /* check to be able to fall back to loading OS/2 programs as DOS
565 * FIXME: should this check be reversed in order to be less strict?
566 * (only fail for OS/2 ne_exetyp 0x01 here?) */
567 if ((ne_header->ne_exetyp != 0x02 /* Windows */)
568 && (ne_header->ne_exetyp != 0x04) /* Windows 386 */)
569 return ERROR_BAD_FORMAT;
571 size = sizeof(NE_MODULE) +
572 /* segment table */
573 ne_header->ne_cseg * sizeof(SEGTABLEENTRY) +
574 /* resource table */
575 ne_header->ne_restab - ne_header->ne_rsrctab +
576 /* resident names table */
577 ne_header->ne_modtab - ne_header->ne_restab +
578 /* module ref table */
579 ne_header->ne_cmod * sizeof(WORD) +
580 /* imported names table */
581 ne_header->ne_enttab - ne_header->ne_imptab +
582 /* entry table length */
583 ne_header->ne_cbenttab +
584 /* entry table extra conversion space */
585 sizeof(ET_BUNDLE) +
586 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6) +
587 /* loaded file info */
588 sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path) + 1;
590 hModule = GlobalAlloc16( GMEM_FIXED | GMEM_ZEROINIT, size );
591 if (!hModule)
593 ERR_(winediag)( "Failed to create module for %s, 16-bit LDT support may be missing.\n",
594 debugstr_a(path) );
595 return ERROR_BAD_FORMAT;
598 FarSetOwner16( hModule, hModule );
599 pModule = GlobalLock16( hModule );
600 memcpy( pModule, ne_header, sizeof(*ne_header) );
601 pModule->count = 0;
602 /* check programs for default minimal stack size */
603 if (!(pModule->ne_flags & NE_FFLAGS_LIBMODULE) && (pModule->ne_stack < 0x1400))
604 pModule->ne_stack = 0x1400;
606 pModule->self = hModule;
607 pModule->mapping = mapping;
608 pModule->mapping_size = mapping_size;
610 pData = (BYTE *)(pModule + 1);
612 /* Clear internal Wine flags in case they are set in the EXE file */
614 pModule->ne_flags &= ~(NE_FFLAGS_BUILTIN | NE_FFLAGS_WIN32);
616 /* Get the segment table */
618 pModule->ne_segtab = pData - (BYTE *)pModule;
619 if (!(pSeg = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_segtab,
620 ne_header->ne_cseg * sizeof(struct ne_segment_table_entry_s) )))
621 goto failed;
622 for (i = ne_header->ne_cseg; i > 0; i--, pSeg++)
624 memcpy( pData, pSeg, sizeof(*pSeg) );
625 pData += sizeof(SEGTABLEENTRY);
628 /* Get the resource table */
630 if (ne_header->ne_rsrctab < ne_header->ne_restab)
632 pModule->ne_rsrctab = pData - (BYTE *)pModule;
633 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_rsrctab,
634 ne_header->ne_restab - ne_header->ne_rsrctab )) goto failed;
635 pData += ne_header->ne_restab - ne_header->ne_rsrctab;
637 else pModule->ne_rsrctab = 0; /* No resource table */
639 /* Get the resident names table */
641 pModule->ne_restab = pData - (BYTE *)pModule;
642 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_restab,
643 ne_header->ne_modtab - ne_header->ne_restab )) goto failed;
644 pData += ne_header->ne_modtab - ne_header->ne_restab;
646 /* Get the module references table */
648 if (ne_header->ne_cmod > 0)
650 pModule->ne_modtab = pData - (BYTE *)pModule;
651 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_modtab,
652 ne_header->ne_cmod * sizeof(WORD) )) goto failed;
653 pData += ne_header->ne_cmod * sizeof(WORD);
655 else pModule->ne_modtab = 0; /* No module references */
657 /* Get the imported names table */
659 pModule->ne_imptab = pData - (BYTE *)pModule;
660 if (!NE_READ_DATA( pModule, pData, mz_header->e_lfanew + ne_header->ne_imptab,
661 ne_header->ne_enttab - ne_header->ne_imptab )) goto failed;
662 pData += ne_header->ne_enttab - ne_header->ne_imptab;
664 /* Load entry table, convert it to the optimized version used by Windows */
666 pModule->ne_enttab = pData - (BYTE *)pModule;
667 if (!(ptr = NE_GET_DATA( pModule, mz_header->e_lfanew + ne_header->ne_enttab,
668 ne_header->ne_cbenttab ))) goto failed;
669 end = build_bundle_data( pModule, pData, ptr );
671 pData += ne_header->ne_cbenttab + sizeof(ET_BUNDLE) +
672 2 * (ne_header->ne_cbenttab - ne_header->ne_cmovent*6);
674 if (end > pData)
676 FIXME( "not enough space for entry table for %s\n", debugstr_a(path) );
677 goto failed;
680 /* Store the filename information */
682 pModule->fileinfo = pData - (BYTE *)pModule;
683 ofs = (OFSTRUCT *)pData;
684 ofs->cBytes = sizeof(OFSTRUCT) - sizeof(ofs->szPathName) + strlen(path);
685 ofs->fFixedDisk = 1;
686 strcpy( ofs->szPathName, path );
687 pData += ofs->cBytes + 1;
689 /* Get the non-resident names table */
691 if (ne_header->ne_cbnrestab)
693 pModule->nrname_handle = GlobalAlloc16( 0, ne_header->ne_cbnrestab );
694 if (!pModule->nrname_handle) goto failed;
695 FarSetOwner16( pModule->nrname_handle, hModule );
696 buffer = GlobalLock16( pModule->nrname_handle );
697 if (!NE_READ_DATA( pModule, buffer, ne_header->ne_nrestab, ne_header->ne_cbnrestab ))
699 GlobalFree16( pModule->nrname_handle );
700 pModule->nrname_handle = 0;
703 else pModule->nrname_handle = 0;
705 /* Allocate a segment for the implicitly-loaded DLLs */
707 if (pModule->ne_cmod)
709 pModule->dlls_to_init = GlobalAlloc16( GMEM_ZEROINIT,
710 (pModule->ne_cmod+1)*sizeof(HMODULE16) );
711 if (!pModule->dlls_to_init)
713 if (pModule->nrname_handle) GlobalFree16( pModule->nrname_handle );
714 goto failed;
716 FarSetOwner16( pModule->dlls_to_init, hModule );
718 else pModule->dlls_to_init = 0;
720 NE_RegisterModule( pModule );
721 return hModule;
723 failed:
724 GlobalFree16( hModule );
725 return ERROR_BAD_FORMAT;
729 /***********************************************************************
730 * NE_LoadDLLs
732 * Load all DLLs implicitly linked to a module.
734 static BOOL NE_LoadDLLs( NE_MODULE *pModule )
736 int i;
737 WORD *pModRef = (WORD *)((char *)pModule + pModule->ne_modtab);
738 WORD *pDLLs = GlobalLock16( pModule->dlls_to_init );
740 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
742 char buffer[260], *p;
743 BYTE *pstr = (BYTE *)pModule + pModule->ne_imptab + *pModRef;
744 memcpy( buffer, pstr + 1, *pstr );
745 *(buffer + *pstr) = 0; /* terminate it */
747 TRACE("Loading '%s'\n", buffer );
748 if (!(*pModRef = GetModuleHandle16( buffer )))
750 /* If the DLL is not loaded yet, load it and store */
751 /* its handle in the list of DLLs to initialize. */
752 HMODULE16 hDLL;
754 /* Append .DLL (Windows >= 3.00) or .EXE (Windows < 3.00) to name if no extension present */
755 if (!(p = strrchr( buffer, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
756 strcat( buffer, (GetExeVersion16() >= 0x0300) ? ".DLL" : ".EXE" );
758 if ((hDLL = MODULE_LoadModule16( buffer, TRUE, TRUE )) < 32)
760 /* FIXME: cleanup what was done */
762 MESSAGE( "Could not load '%s' required by '%.*s', error=%d\n",
763 buffer, *((BYTE*)pModule + pModule->ne_restab),
764 (char *)pModule + pModule->ne_restab + 1, hDLL );
765 return FALSE;
767 *pModRef = GetExePtr( hDLL );
768 *pDLLs++ = *pModRef;
770 else /* Increment the reference count of the DLL */
772 NE_MODULE *pOldDLL = NE_GetPtr( *pModRef );
773 if (pOldDLL) pOldDLL->count++;
776 return TRUE;
780 /**********************************************************************
781 * NE_DoLoadModule
783 * Load first instance of NE module from file.
785 * pModule must point to a module structure prepared by build_module.
786 * This routine must never be called twice on a module.
788 static HINSTANCE16 NE_DoLoadModule( NE_MODULE *pModule )
790 /* Allocate the segments for this module */
792 if (!NE_CreateAllSegments( pModule ))
793 return ERROR_NOT_ENOUGH_MEMORY; /* 8 */
795 /* Load the referenced DLLs */
797 if (!NE_LoadDLLs( pModule ))
798 return ERROR_FILE_NOT_FOUND; /* 2 */
800 /* Load the segments */
802 NE_LoadAllSegments( pModule );
804 /* Make sure the usage count is 1 on the first loading of */
805 /* the module, even if it contains circular DLL references */
807 pModule->count = 1;
809 return NE_GetInstance( pModule );
812 /**********************************************************************
813 * NE_LoadModule
815 * Load first instance of NE module. (Note: caller is responsible for
816 * ensuring the module isn't already loaded!)
818 * If the module turns out to be an executable module, only a
819 * handle to a module stub is returned; this needs to be initialized
820 * by calling NE_DoLoadModule later, in the context of the newly
821 * created process.
823 * If lib_only is TRUE, however, the module is perforce treated
824 * like a DLL module, even if it is an executable module.
827 static HINSTANCE16 NE_LoadModule( LPCSTR name, BOOL lib_only )
829 NE_MODULE *pModule;
830 HMODULE16 hModule;
831 HINSTANCE16 hInstance;
832 HFILE16 hFile;
833 OFSTRUCT ofs;
834 HANDLE mapping;
835 void *ptr;
836 MEMORY_BASIC_INFORMATION info;
838 /* Open file */
839 if ((hFile = OpenFile16( name, &ofs, OF_READ|OF_SHARE_DENY_WRITE )) == HFILE_ERROR16)
840 return ERROR_FILE_NOT_FOUND;
842 mapping = CreateFileMappingW( DosFileHandleToWin32Handle(hFile), NULL, PAGE_WRITECOPY, 0, 0, NULL );
843 _lclose16( hFile );
844 if (!mapping) return ERROR_BAD_FORMAT;
846 ptr = MapViewOfFile( mapping, FILE_MAP_COPY, 0, 0, 0 );
847 CloseHandle( mapping );
848 if (!ptr) return ERROR_BAD_FORMAT;
850 VirtualQuery( ptr, &info, sizeof(info) );
851 hModule = build_module( ptr, info.RegionSize, ofs.szPathName );
853 if (hModule < 32)
855 UnmapViewOfFile( ptr );
856 return hModule;
859 SNOOP16_RegisterDLL( hModule, ofs.szPathName );
860 NE_InitResourceHandler( hModule );
862 pModule = NE_GetPtr( hModule );
864 if ( !lib_only && !( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) )
865 return hModule;
867 hInstance = NE_DoLoadModule( pModule );
868 if ( hInstance < 32 )
870 /* cleanup ... */
871 NE_FreeModule( hModule, 0 );
874 return hInstance;
878 /***********************************************************************
879 * NE_DoLoadBuiltinModule
881 * Load a built-in Win16 module. Helper function for NE_LoadBuiltinModule.
883 static HMODULE16 NE_DoLoadBuiltinModule( const IMAGE_DOS_HEADER *mz_header, const char *file_name,
884 HMODULE owner32 )
886 NE_MODULE *pModule;
887 HMODULE16 hModule;
888 HINSTANCE16 hInstance;
889 SIZE_T mapping_size = ~0UL; /* assume builtins don't contain invalid offsets... */
891 hModule = build_module( mz_header, mapping_size, file_name );
892 if (hModule < 32) return hModule;
893 pModule = GlobalLock16( hModule );
894 pModule->ne_flags |= NE_FFLAGS_BUILTIN;
895 pModule->owner32 = owner32;
897 /* fake the expected version the module should have according to the current Windows version */
898 pModule->ne_expver = MAKEWORD( NtCurrentTeb()->Peb->OSMajorVersion,
899 NtCurrentTeb()->Peb->OSMinorVersion );
901 hInstance = NE_DoLoadModule( pModule );
902 if (hInstance < 32) NE_FreeModule( hModule, 0 );
904 NE_InitResourceHandler( hModule );
906 if (pModule->ne_heap)
908 SEGTABLEENTRY *pSeg = NE_SEG_TABLE( pModule ) + pModule->ne_autodata - 1;
909 unsigned int size = pSeg->minsize + pModule->ne_heap;
910 if (size > 0xfffe) size = 0xfffe;
911 LocalInit16( GlobalHandleToSel16(pSeg->hSeg), pSeg->minsize, size );
914 patch_code_segment( pModule );
915 *(const void **)mz_header->e_res2 = ldt_copy->base;
917 return hInstance;
921 /**********************************************************************
922 * MODULE_LoadModule16
924 * Load a NE module in the order of the loadorder specification.
925 * The caller is responsible that the module is not loaded already.
928 static HINSTANCE16 MODULE_LoadModule16( LPCSTR libname, BOOL implicit, BOOL lib_only )
930 HINSTANCE16 hinst = 2;
931 HMODULE16 hModule;
932 HMODULE mod32 = 0;
933 NE_MODULE *pModule;
934 const IMAGE_DOS_HEADER *descr = NULL;
935 const char *file_name = NULL;
936 char dllname[32];
937 const char *basename, *main_module, *p;
939 /* strip path information */
941 basename = libname;
942 if (basename[0] && basename[1] == ':') basename += 2; /* strip drive specification */
943 if ((p = strrchr( basename, '\\' ))) basename = p + 1;
944 if ((p = strrchr( basename, '/' ))) basename = p + 1;
946 if (strlen(basename) < sizeof(dllname)-6)
948 DWORD count;
949 char *q;
951 ReleaseThunkLock( &count );
953 strcpy( dllname, basename );
954 q = strrchr( dllname, '.' );
955 if (!q) strcat( dllname, (GetExeVersion16() >= 0x0300) ? ".dll" : ".exe" );
956 for (q = dllname; *q; q++) if (*q >= 'A' && *q <= 'Z') *q += 32;
958 strcpy( q, "16" );
959 if ((mod32 = LoadLibraryA( dllname )))
961 if (!(descr = (void *)GetProcAddress( mod32, "__wine_spec_dos_header" )))
963 WARN( "loaded %s but does not contain a 16-bit module\n", debugstr_a(dllname) );
964 FreeLibrary( mod32 );
966 else
968 TRACE( "found %s with embedded 16-bit module\n", debugstr_a(dllname) );
969 file_name = basename;
971 /* if module has a 32-bit owner, match the load order of the owner */
972 if ((main_module = (void *)GetProcAddress( mod32, "__wine_spec_main_module" )))
974 LDR_DATA_TABLE_ENTRY *ldr;
975 HMODULE main_owner = LoadLibraryA( main_module );
977 if (!main_owner)
979 WARN( "couldn't load owner %s for 16-bit dll %s\n", main_module, dllname );
980 FreeLibrary( mod32 );
981 RestoreThunkLock( count );
982 return ERROR_FILE_NOT_FOUND;
984 /* check if module was loaded native */
985 if (LdrFindEntryForAddress( main_owner, &ldr ) || !(ldr->Flags & LDR_WINE_INTERNAL))
987 FreeLibrary( mod32 );
988 descr = NULL;
990 FreeLibrary( main_owner );
994 RestoreThunkLock( count );
996 /* loading the 32-bit library can have the side effect of loading the module */
997 /* if so, simply incr the ref count and return the module */
998 if (descr && (hModule = GetModuleHandle16( libname )))
1000 TRACE( "module %s already loaded by owner\n", libname );
1001 pModule = NE_GetPtr( hModule );
1002 if (pModule) pModule->count++;
1003 FreeLibrary( mod32 );
1004 return hModule;
1008 if (descr)
1010 TRACE("Trying built-in '%s'\n", libname);
1011 hinst = NE_DoLoadBuiltinModule( descr, file_name, mod32 );
1012 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : builtin\n", debugstr_a(file_name));
1013 else FreeLibrary( mod32 );
1015 else
1017 TRACE("Trying native dll '%s'\n", libname);
1018 hinst = NE_LoadModule(libname, lib_only);
1019 if (hinst > 32) TRACE_(loaddll)("Loaded module %s : native\n", debugstr_a(libname));
1022 if (hinst > 32 && !implicit)
1024 hModule = GetModuleHandle16(libname);
1025 if(!hModule)
1027 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get module handle. Filename too long ?\n",
1028 libname, hinst);
1029 return ERROR_INVALID_HANDLE;
1032 pModule = NE_GetPtr(hModule);
1033 if(!pModule)
1035 ERR("Serious trouble. Just loaded module '%s' (hinst=0x%04x), but can't get NE_MODULE pointer\n",
1036 libname, hinst);
1037 return ERROR_INVALID_HANDLE;
1040 TRACE("Loaded module '%s' at 0x%04x.\n", libname, hinst);
1043 * Call initialization routines for all loaded DLLs. Note that
1044 * when we load implicitly linked DLLs this will be done by InitTask().
1046 if(pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1048 NE_InitializeDLLs(hModule);
1049 NE_DllProcessAttach(hModule);
1051 else DOSMEM_InitDosMemory(); /* we will be running a 16-bit task, setup DOS memory */
1053 return hinst; /* The last error that occurred */
1057 /**********************************************************************
1058 * NE_CreateThread
1060 * Create the thread for a 16-bit module.
1062 static HINSTANCE16 NE_CreateThread( NE_MODULE *pModule, WORD cmdShow, LPCSTR cmdline )
1064 HANDLE hThread;
1065 TDB *pTask;
1066 HTASK16 hTask;
1067 HINSTANCE16 instance = 0;
1069 if (!(hTask = TASK_SpawnTask( pModule, cmdShow, cmdline + 1, *cmdline, &hThread )))
1070 return 0;
1072 /* Post event to start the task */
1073 PostEvent16( hTask );
1075 /* Wait until we get the instance handle */
1078 DirectedYield16( hTask );
1079 if (!IsTask16( hTask )) /* thread has died */
1081 DWORD exit_code;
1082 WaitForSingleObject( hThread, INFINITE );
1083 GetExitCodeThread( hThread, &exit_code );
1084 CloseHandle( hThread );
1085 return exit_code;
1087 if (!(pTask = GlobalLock16( hTask ))) break;
1088 instance = pTask->hInstance;
1089 GlobalUnlock16( hTask );
1090 } while (!instance);
1092 CloseHandle( hThread );
1093 return instance;
1097 /**********************************************************************
1098 * LoadModule (KERNEL.45)
1100 HINSTANCE16 WINAPI LoadModule16( LPCSTR name, LPVOID paramBlock )
1102 BOOL lib_only = !paramBlock || (paramBlock == (LPVOID)-1);
1103 LOADPARAMS16 *params;
1104 HMODULE16 hModule;
1105 NE_MODULE *pModule;
1106 LPSTR cmdline;
1107 WORD cmdShow = 1; /* SW_SHOWNORMAL but we don't want to include winuser.h here */
1109 if (name == NULL) return 0;
1111 TRACE("name %s, paramBlock %p\n", name, paramBlock);
1113 /* Load module */
1115 if ( (hModule = NE_GetModuleByFilename(name) ) != 0 )
1117 /* Special case: second instance of an already loaded NE module */
1119 if ( !( pModule = NE_GetPtr( hModule ) ) ) return ERROR_BAD_FORMAT;
1120 if ( pModule->module32 ) return (HINSTANCE16)21;
1122 /* Increment refcount */
1124 pModule->count++;
1126 else
1128 /* Main case: load first instance of NE module */
1130 if ( (hModule = MODULE_LoadModule16( name, FALSE, lib_only )) < 32 )
1131 return hModule;
1133 if ( !(pModule = NE_GetPtr( hModule )) )
1134 return ERROR_BAD_FORMAT;
1137 /* If library module, we just retrieve the instance handle */
1139 if ( ( pModule->ne_flags & NE_FFLAGS_LIBMODULE ) || lib_only )
1140 return NE_GetInstance( pModule );
1143 * At this point, we need to create a new process.
1145 * pModule points either to an already loaded module, whose refcount
1146 * has already been incremented (to avoid having the module vanish
1147 * in the meantime), or else to a stub module which contains only header
1148 * information.
1150 params = paramBlock;
1151 if (params->showCmd)
1152 cmdShow = ((WORD *)MapSL( params->showCmd ))[1];
1153 cmdline = MapSL( params->cmdLine );
1154 return NE_CreateThread( pModule, cmdShow, cmdline );
1158 /**********************************************************************
1159 * NE_StartTask
1161 * Startup code for a new 16-bit task.
1163 DWORD NE_StartTask(void)
1165 TDB *pTask = TASK_GetCurrent();
1166 NE_MODULE *pModule = NE_GetPtr( pTask->hModule );
1167 HINSTANCE16 hInstance, hPrevInstance;
1168 SEGTABLEENTRY *pSegTable = NE_SEG_TABLE( pModule );
1169 WORD sp;
1171 if ( pModule->count > 0 )
1173 /* Second instance of an already loaded NE module */
1174 /* Note that the refcount was already incremented by the parent */
1176 hPrevInstance = NE_GetInstance( pModule );
1178 if ( pModule->ne_autodata )
1179 if ( NE_CreateSegment( pModule, pModule->ne_autodata ) )
1180 NE_LoadSegment( pModule, pModule->ne_autodata );
1182 hInstance = NE_GetInstance( pModule );
1183 TRACE("created second instance %04x[%d] of instance %04x.\n", hInstance, pModule->ne_autodata, hPrevInstance);
1186 else
1188 /* Load first instance of NE module */
1190 pModule->ne_flags |= NE_FFLAGS_GUI; /* FIXME: is this necessary? */
1192 hInstance = NE_DoLoadModule( pModule );
1193 hPrevInstance = 0;
1196 if ( hInstance >= 32 )
1198 CONTEXT context;
1200 /* Enter instance handles into task struct */
1202 pTask->hInstance = hInstance;
1203 pTask->hPrevInstance = hPrevInstance;
1205 /* Use DGROUP for 16-bit stack */
1207 if (!(sp = OFFSETOF(pModule->ne_sssp)))
1208 sp = pSegTable[SELECTOROF(pModule->ne_sssp)-1].minsize + pModule->ne_stack;
1209 sp &= ~1;
1210 CURRENT_SS = GlobalHandleToSel16(hInstance);
1211 CURRENT_SP = sp - sizeof(STACK16FRAME);
1213 /* Registers at initialization must be:
1214 * ax zero
1215 * bx stack size in bytes
1216 * cx heap size in bytes
1217 * si previous app instance
1218 * di current app instance
1219 * bp zero
1220 * es selector to the PSP
1221 * ds dgroup of the application
1222 * ss stack selector
1223 * sp top of the stack
1225 memset( &context, 0, sizeof(context) );
1226 context.SegCs = GlobalHandleToSel16(pSegTable[SELECTOROF(pModule->ne_csip) - 1].hSeg);
1227 context.SegDs = GlobalHandleToSel16(pTask->hInstance);
1228 context.SegEs = pTask->hPDB;
1229 context.Eip = OFFSETOF(pModule->ne_csip);
1230 context.Ebx = pModule->ne_stack;
1231 context.Ecx = pModule->ne_heap;
1232 context.Edi = pTask->hInstance;
1233 context.Esi = pTask->hPrevInstance;
1235 /* Now call 16-bit entry point */
1237 TRACE("Starting main program: cs:ip=%04lx:%04lx ds=%04lx ss:sp=%04x:%04x\n",
1238 context.SegCs, context.Eip, context.SegDs, CURRENT_SS, CURRENT_SP);
1240 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&context );
1241 ExitThread( LOWORD(context.Eax) );
1243 return hInstance; /* error code */
1246 /***********************************************************************
1247 * LoadLibrary (KERNEL.95)
1248 * LoadLibrary16 (KERNEL32.35)
1250 HINSTANCE16 WINAPI LoadLibrary16( LPCSTR libname )
1252 return LoadModule16(libname, (LPVOID)-1 );
1256 /**********************************************************************
1257 * MODULE_CallWEP
1259 * Call a DLL's WEP, allowing it to shut down.
1260 * FIXME: we always pass the WEP WEP_FREE_DLL, never WEP_SYSTEM_EXIT
1262 static BOOL16 MODULE_CallWEP( HMODULE16 hModule )
1264 BOOL16 ret;
1265 FARPROC16 WEP = GetProcAddress16( hModule, "WEP" );
1266 if (!WEP) return FALSE;
1268 __TRY
1270 WORD args[1];
1271 DWORD dwRet;
1273 args[0] = WEP_FREE_DLL;
1274 WOWCallback16Ex( (DWORD)WEP, WCB16_PASCAL, sizeof(args), args, &dwRet );
1275 ret = LOWORD(dwRet);
1277 __EXCEPT_PAGE_FAULT
1279 WARN("Page fault\n");
1280 ret = 0;
1282 __ENDTRY
1284 return ret;
1288 /**********************************************************************
1289 * NE_FreeModule
1291 * Implementation of FreeModule16().
1293 static BOOL16 NE_FreeModule( HMODULE16 hModule, BOOL call_wep )
1295 HMODULE16 *hPrevModule;
1296 NE_MODULE *pModule;
1297 HMODULE16 *pModRef;
1298 int i;
1300 if (!(pModule = NE_GetPtr( hModule ))) return FALSE;
1301 hModule = pModule->self;
1303 TRACE("%04x count %d\n", hModule, pModule->count );
1305 if (((INT16)(--pModule->count)) > 0 ) return TRUE;
1306 else pModule->count = 0;
1308 if (call_wep && !(pModule->ne_flags & NE_FFLAGS_WIN32))
1310 /* Free the objects owned by the DLL module */
1311 NE_CallUserSignalProc( hModule, USIG16_DLL_UNLOAD );
1313 if (pModule->ne_flags & NE_FFLAGS_LIBMODULE)
1314 MODULE_CallWEP( hModule );
1315 else
1316 call_wep = FALSE; /* We are freeing a task -> no more WEPs */
1319 TRACE_(loaddll)("Unloaded module %s : %s\n", debugstr_a(NE_MODULE_NAME(pModule)),
1320 (pModule->ne_flags & NE_FFLAGS_BUILTIN) ? "builtin" : "native");
1322 /* Clear magic number just in case */
1324 pModule->ne_magic = pModule->self = 0;
1325 if (pModule->owner32) FreeLibrary( pModule->owner32 );
1326 else if (pModule->mapping) UnmapViewOfFile( pModule->mapping );
1328 /* Remove it from the linked list */
1330 hPrevModule = &hFirstModule;
1331 while (*hPrevModule && (*hPrevModule != hModule))
1333 hPrevModule = &(NE_GetPtr( *hPrevModule ))->next;
1335 if (*hPrevModule) *hPrevModule = pModule->next;
1337 /* Free the referenced modules */
1339 pModRef = (HMODULE16*)((char *)pModule + pModule->ne_modtab);
1340 for (i = 0; i < pModule->ne_cmod; i++, pModRef++)
1342 NE_FreeModule( *pModRef, call_wep );
1345 /* Free the module storage */
1347 GlobalFreeAll16( hModule );
1348 return TRUE;
1352 /**********************************************************************
1353 * FreeModule (KERNEL.46)
1355 BOOL16 WINAPI FreeModule16( HMODULE16 hModule )
1357 return NE_FreeModule( hModule, TRUE );
1361 /***********************************************************************
1362 * FreeLibrary (KERNEL.96)
1363 * FreeLibrary16 (KERNEL32.36)
1365 void WINAPI FreeLibrary16( HINSTANCE16 handle )
1367 TRACE("%04x\n", handle );
1368 FreeModule16( handle );
1372 /***********************************************************************
1373 * GetModuleHandle16 (KERNEL32.@)
1375 HMODULE16 WINAPI GetModuleHandle16( LPCSTR name )
1377 HMODULE16 hModule;
1378 LPSTR s;
1379 BYTE len, *name_table;
1380 char tmpstr[MAX_PATH];
1381 NE_MODULE *pModule;
1383 TRACE("(%s)\n", name);
1385 if (!HIWORD(name)) return GetExePtr(LOWORD(name));
1387 len = strlen(name);
1388 if (!len) return 0;
1390 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1392 /* If 'name' matches exactly the module name of a module:
1393 * Return its handle.
1395 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1397 pModule = NE_GetPtr( hModule );
1398 if (!pModule) break;
1399 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1401 name_table = (BYTE *)pModule + pModule->ne_restab;
1402 if ((*name_table == len) && !strncmp(name, (char*) name_table+1, len))
1403 return hModule;
1406 /* If uppercased 'name' matches exactly the module name of a module:
1407 * Return its handle
1409 for (s = tmpstr; *s; s++) *s = RtlUpperChar(*s);
1411 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1413 pModule = NE_GetPtr( hModule );
1414 if (!pModule) break;
1415 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1417 name_table = (BYTE *)pModule + pModule->ne_restab;
1418 /* FIXME: the _strnicmp is WRONG. It should not be case insensitive,
1419 * but case sensitive! (Unfortunately Winword 6 and subdlls have
1420 * lowercased module names, but try to load uppercase DLLs, so this
1421 * 'i' compare is just a quickfix until the loader handles that
1422 * correctly. -MM 990705
1424 if ((*name_table == len) && !_strnicmp(tmpstr, (const char*)name_table+1, len))
1425 return hModule;
1428 /* If the base filename of 'name' matches the base filename of the module
1429 * filename of some module (case-insensitive compare):
1430 * Return its handle.
1433 /* basename: search backwards in passed name to \ / or : */
1434 s = tmpstr + strlen(tmpstr);
1435 while (s > tmpstr)
1437 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1438 break;
1439 s--;
1442 /* search this in loaded filename list */
1443 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1445 char *loadedfn;
1446 OFSTRUCT *ofs;
1448 pModule = NE_GetPtr( hModule );
1449 if (!pModule) break;
1450 if (!pModule->fileinfo) continue;
1451 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1453 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1454 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1455 /* basename: search backwards in pathname to \ / or : */
1456 while (loadedfn > (char*)ofs->szPathName)
1458 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1459 break;
1460 loadedfn--;
1462 /* case insensitive compare ... */
1463 if (!stricmp(loadedfn, s))
1464 return hModule;
1466 return 0;
1470 /**********************************************************************
1471 * GetModuleName (KERNEL.27)
1473 BOOL16 WINAPI GetModuleName16( HINSTANCE16 hinst, LPSTR buf, INT16 count )
1475 NE_MODULE *pModule;
1476 BYTE *p;
1478 if (!(pModule = NE_GetPtr( hinst ))) return FALSE;
1479 p = (BYTE *)pModule + pModule->ne_restab;
1480 if (count > *p) count = *p + 1;
1481 if (count > 0)
1483 memcpy( buf, p + 1, count - 1 );
1484 buf[count-1] = '\0';
1486 return TRUE;
1490 /**********************************************************************
1491 * GetModuleFileName (KERNEL.49)
1493 * See also: GetModuleFileNameA
1495 * This function returns short paths when the modules version field is < 4.0).
1497 * Even if invoked by second instance of a program,
1498 * it still returns path of first one.
1500 INT16 WINAPI GetModuleFileName16( HINSTANCE16 hModule, LPSTR lpFileName,
1501 INT16 nSize )
1503 NE_MODULE *pModule;
1505 /* Win95 does not query hModule if set to 0 !
1506 * Is this wrong or maybe Win3.1 only ? */
1507 if (!hModule) hModule = GetCurrentTask();
1509 if (!(pModule = NE_GetPtr( hModule ))) return 0;
1510 lstrcpynA( lpFileName, NE_MODULE_NAME(pModule), nSize );
1511 if (pModule->ne_expver < 0x400)
1512 GetShortPathNameA(NE_MODULE_NAME(pModule), lpFileName, nSize);
1513 TRACE("%04x -> '%s'\n", hModule, lpFileName );
1514 return strlen(lpFileName);
1518 /**********************************************************************
1519 * GetModuleUsage (KERNEL.48)
1521 INT16 WINAPI GetModuleUsage16( HINSTANCE16 hModule )
1523 NE_MODULE *pModule = NE_GetPtr( hModule );
1524 return pModule ? pModule->count : 0;
1528 /**********************************************************************
1529 * GetExpWinVer (KERNEL.167)
1531 WORD WINAPI GetExpWinVer16( HMODULE16 hModule )
1533 NE_MODULE *pModule = NE_GetPtr( hModule );
1534 if ( !pModule ) return 0;
1535 return pModule->ne_expver;
1539 /***********************************************************************
1540 * WinExec (KERNEL.166)
1542 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
1544 LPCSTR p, args = NULL;
1545 LPCSTR name_beg, name_end;
1546 LPSTR name, cmdline;
1547 int arglen;
1548 HINSTANCE16 ret;
1549 char buffer[MAX_PATH];
1550 LOADPARAMS16 params;
1551 WORD showCmd[2];
1553 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
1555 name_beg = lpCmdLine+1;
1556 p = strchr ( lpCmdLine+1, '"' );
1557 if (p)
1559 name_end = p;
1560 args = strchr ( p, ' ' );
1562 else /* yes, even valid with trailing '"' missing */
1563 name_end = lpCmdLine+strlen(lpCmdLine);
1565 else
1567 name_beg = lpCmdLine;
1568 args = strchr( lpCmdLine, ' ' );
1569 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
1572 if ((name_beg == lpCmdLine) && (!args))
1573 { /* just use the original cmdline string as file name */
1574 name = (LPSTR)lpCmdLine;
1576 else
1578 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
1579 return ERROR_NOT_ENOUGH_MEMORY;
1580 memcpy( name, name_beg, name_end - name_beg );
1581 name[name_end - name_beg] = '\0';
1584 if (args)
1586 args++;
1587 arglen = strlen(args);
1588 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
1589 cmdline[0] = (BYTE)arglen;
1590 strcpy( cmdline + 1, args );
1592 else
1594 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
1595 cmdline[0] = cmdline[1] = 0;
1598 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
1600 showCmd[0] = 2;
1601 showCmd[1] = nCmdShow;
1603 params.hEnvironment = 0;
1604 params.cmdLine = MapLS( cmdline );
1605 params.showCmd = MapLS( showCmd );
1606 params.reserved = 0;
1608 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
1610 ret = LoadModule16( buffer, &params );
1612 else if (!contains_path( name )) /* try 16-bit builtin */
1614 lstrcpynA( buffer, name, sizeof(buffer) );
1615 if (strlen( buffer ) < sizeof(buffer) - 4 && !strchr( buffer, '.' )) strcat( buffer, ".exe" );
1616 ret = LoadModule16( buffer, &params );
1617 if (ret == ERROR_FILE_NOT_FOUND) ret = 21; /* it might be a 32-bit builtin too */
1619 else ret = ERROR_FILE_NOT_FOUND;
1621 UnMapLS( params.cmdLine );
1622 UnMapLS( params.showCmd );
1624 HeapFree( GetProcessHeap(), 0, cmdline );
1625 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
1627 if (ret == 21 || ret == ERROR_BAD_FORMAT) /* 32-bit module or unknown executable*/
1629 LOADPARAMS16 params;
1630 WORD showCmd[2];
1631 showCmd[0] = 2;
1632 showCmd[1] = nCmdShow;
1634 arglen = strlen( lpCmdLine );
1635 cmdline = HeapAlloc( GetProcessHeap(), 0, arglen + 1 );
1636 cmdline[0] = (BYTE)arglen;
1637 memcpy( cmdline + 1, lpCmdLine, arglen );
1639 params.hEnvironment = 0;
1640 params.cmdLine = MapLS( cmdline );
1641 params.showCmd = MapLS( showCmd );
1642 params.reserved = 0;
1644 ret = LoadModule16( "winoldap.mod", &params );
1645 UnMapLS( params.cmdLine );
1646 UnMapLS( params.showCmd );
1648 return ret;
1651 /***********************************************************************
1652 * GetProcAddress (KERNEL.50)
1654 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1656 WORD ordinal;
1657 FARPROC16 ret;
1659 if (!hModule) hModule = GetCurrentTask();
1660 hModule = GetExePtr( hModule );
1662 if (HIWORD(name) != 0)
1664 ordinal = NE_GetOrdinal( hModule, name );
1665 TRACE("%04x '%s'\n", hModule, name );
1667 else
1669 ordinal = LOWORD(name);
1670 TRACE("%04x %04x\n", hModule, ordinal );
1672 if (!ordinal) return NULL;
1674 ret = NE_GetEntryPoint( hModule, ordinal );
1676 TRACE("returning %p\n", ret );
1677 return ret;
1681 /***************************************************************************
1682 * HasGPHandler (KERNEL.338)
1684 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1686 HMODULE16 hModule;
1687 int gpOrdinal;
1688 SEGPTR gpPtr;
1689 GPHANDLERDEF *gpHandler;
1691 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1692 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1693 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1694 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1695 && (gpHandler = MapSL( gpPtr )) != NULL )
1697 while (gpHandler->selector)
1699 if ( SELECTOROF(address) == gpHandler->selector
1700 && OFFSETOF(address) >= gpHandler->rangeStart
1701 && OFFSETOF(address) < gpHandler->rangeEnd )
1702 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1703 gpHandler++;
1707 return 0;
1711 /**********************************************************************
1712 * GetModuleHandle (KERNEL.47)
1714 * Find a module from a module name.
1716 * NOTE: The current implementation works the same way the Windows 95 one
1717 * does. Do not try to 'fix' it, fix the callers.
1718 * + It does not do ANY extension handling (except that strange .EXE bit)!
1719 * + It does not care about paths, just about basenames. (same as Windows)
1721 * RETURNS
1722 * LOWORD:
1723 * the win16 module handle if found
1724 * 0 if not
1725 * HIWORD (undocumented, see "Undocumented Windows", chapter 5):
1726 * Always hFirstModule
1728 DWORD WINAPI WIN16_GetModuleHandle( SEGPTR name )
1730 if (HIWORD(name) == 0)
1731 return MAKELONG(GetExePtr( (HINSTANCE16)name), hFirstModule );
1732 return MAKELONG(GetModuleHandle16( MapSL(name)), hFirstModule );
1735 /**********************************************************************
1736 * NE_GetModuleByFilename
1738 static HMODULE16 NE_GetModuleByFilename( LPCSTR name )
1740 HMODULE16 hModule;
1741 LPSTR s, p;
1742 BYTE len, *name_table;
1743 char tmpstr[MAX_PATH];
1744 NE_MODULE *pModule;
1746 lstrcpynA(tmpstr, name, sizeof(tmpstr));
1748 /* If the base filename of 'name' matches the base filename of the module
1749 * filename of some module (case-insensitive compare):
1750 * Return its handle.
1753 /* basename: search backwards in passed name to \ / or : */
1754 s = tmpstr + strlen(tmpstr);
1755 while (s > tmpstr)
1757 if (s[-1]=='/' || s[-1]=='\\' || s[-1]==':')
1758 break;
1759 s--;
1762 /* search this in loaded filename list */
1763 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1765 char *loadedfn;
1766 OFSTRUCT *ofs;
1768 pModule = NE_GetPtr( hModule );
1769 if (!pModule) break;
1770 if (!pModule->fileinfo) continue;
1771 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1773 ofs = (OFSTRUCT*)((BYTE *)pModule + pModule->fileinfo);
1774 loadedfn = ((char*)ofs->szPathName) + strlen(ofs->szPathName);
1775 /* basename: search backwards in pathname to \ / or : */
1776 while (loadedfn > (char*)ofs->szPathName)
1778 if (loadedfn[-1]=='/' || loadedfn[-1]=='\\' || loadedfn[-1]==':')
1779 break;
1780 loadedfn--;
1782 /* case insensitive compare ... */
1783 if (!stricmp(loadedfn, s))
1784 return hModule;
1786 /* If basename (without ext) matches the module name of a module:
1787 * Return its handle.
1790 if ( (p = strrchr( s, '.' )) != NULL ) *p = '\0';
1791 len = strlen(s);
1793 for (hModule = hFirstModule; hModule ; hModule = pModule->next)
1795 pModule = NE_GetPtr( hModule );
1796 if (!pModule) break;
1797 if (pModule->ne_flags & NE_FFLAGS_WIN32) continue;
1799 name_table = (BYTE *)pModule + pModule->ne_restab;
1800 if ((*name_table == len) && !_strnicmp(s, (const char*)name_table+1, len))
1801 return hModule;
1804 return 0;
1807 /***********************************************************************
1808 * GetProcAddress16 (KERNEL32.37)
1809 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1811 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1813 if (!hModule) return 0;
1814 if (HIWORD(hModule))
1816 WARN("hModule is Win32 handle (%p)\n", hModule );
1817 return 0;
1819 return GetProcAddress16( LOWORD(hModule), name );
1822 /***************************************************************************
1823 * IsRomModule (KERNEL.323)
1825 BOOL16 WINAPI IsRomModule16( HMODULE16 unused )
1827 return FALSE;
1830 /***************************************************************************
1831 * IsRomFile (KERNEL.326)
1833 BOOL16 WINAPI IsRomFile16( HFILE16 unused )
1835 return FALSE;
1838 /***********************************************************************
1839 * create_dummy_module
1841 * Create a dummy NE module for Win32 or Winelib.
1843 static HMODULE16 create_dummy_module( HMODULE module32 )
1845 HMODULE16 hModule;
1846 NE_MODULE *pModule;
1847 SEGTABLEENTRY *pSegment;
1848 char *pStr;
1849 unsigned int len;
1850 const char *basename, *s;
1851 OFSTRUCT *ofs;
1852 int of_size, size;
1853 char filename[MAX_PATH];
1854 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
1856 if (!nt) return ERROR_BAD_FORMAT;
1858 /* Extract base filename */
1859 len = GetModuleFileNameA( module32, filename, sizeof(filename) );
1860 if (!len || len >= sizeof(filename)) return ERROR_BAD_FORMAT;
1861 basename = strrchr(filename, '\\');
1862 if (!basename) basename = filename;
1863 else basename++;
1864 len = strlen(basename);
1865 if ((s = strchr(basename, '.'))) len = s - basename;
1867 /* Allocate module */
1868 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
1869 + strlen(filename) + 1;
1870 size = sizeof(NE_MODULE) +
1871 /* loaded file info */
1872 ((of_size + 3) & ~3) +
1873 /* segment table: DS,CS */
1874 2 * sizeof(SEGTABLEENTRY) +
1875 /* name table */
1876 len + 2 +
1877 /* several empty tables */
1880 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
1881 if (!hModule) return ERROR_BAD_FORMAT;
1883 FarSetOwner16( hModule, hModule );
1884 pModule = GlobalLock16( hModule );
1886 /* Set all used entries */
1887 pModule->ne_magic = IMAGE_OS2_SIGNATURE;
1888 pModule->count = 1;
1889 pModule->next = 0;
1890 pModule->ne_flags = NE_FFLAGS_WIN32;
1891 pModule->ne_autodata = 0;
1892 pModule->ne_sssp = MAKESEGPTR( 0, 1 );
1893 pModule->ne_csip = MAKESEGPTR( 0, 2 );
1894 pModule->ne_heap = 0;
1895 pModule->ne_stack = 0;
1896 pModule->ne_cseg = 2;
1897 pModule->ne_cmod = 0;
1898 pModule->ne_cbnrestab = 0;
1899 pModule->fileinfo = sizeof(NE_MODULE);
1900 pModule->ne_exetyp = NE_OSFLAGS_WINDOWS;
1901 pModule->self = hModule;
1902 pModule->module32 = module32;
1904 /* Set version and flags */
1905 pModule->ne_expver = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
1906 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
1907 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1908 pModule->ne_flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
1910 /* Set loaded file information */
1911 ofs = (OFSTRUCT *)(pModule + 1);
1912 memset( ofs, 0, of_size );
1913 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
1914 strcpy( ofs->szPathName, filename );
1916 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
1917 pModule->ne_segtab = (char *)pSegment - (char *)pModule;
1918 /* Data segment */
1919 pSegment->size = 0;
1920 pSegment->flags = NE_SEGFLAGS_DATA;
1921 pSegment->minsize = 0x1000;
1922 pSegment++;
1923 /* Code segment */
1924 pSegment->flags = 0;
1925 pSegment++;
1927 /* Module name */
1928 pStr = (char *)pSegment;
1929 pModule->ne_restab = pStr - (char *)pModule;
1930 *pStr = len;
1931 lstrcpynA( pStr+1, basename, len+1 );
1932 pStr += len+2;
1934 /* All tables zero terminated */
1935 pModule->ne_rsrctab = pModule->ne_imptab = pModule->ne_enttab = pStr - (char *)pModule;
1937 NE_RegisterModule( pModule );
1938 pModule->owner32 = LoadLibraryA( filename ); /* increment the ref count of the 32-bit module */
1939 return hModule;
1942 /***********************************************************************
1943 * PrivateLoadLibrary (KERNEL32.@)
1945 * FIXME: rough guesswork, don't know what "Private" means
1947 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1949 return LoadLibrary16(libname);
1952 /***********************************************************************
1953 * PrivateFreeLibrary (KERNEL32.@)
1955 * FIXME: rough guesswork, don't know what "Private" means
1957 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1959 FreeLibrary16(handle);
1962 /***********************************************************************
1963 * LoadLibrary32 (KERNEL.452)
1964 * LoadSystemLibrary32 (KERNEL.482)
1966 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1968 HMODULE hModule;
1969 DWORD count;
1971 ReleaseThunkLock( &count );
1972 hModule = LoadLibraryA( libname );
1973 RestoreThunkLock( count );
1974 return hModule;
1977 /***************************************************************************
1978 * MapHModuleLS (KERNEL32.@)
1980 HMODULE16 WINAPI MapHModuleLS(HMODULE hmod)
1982 HMODULE16 ret;
1983 NE_MODULE *pModule;
1985 if (!hmod)
1986 return TASK_GetCurrent()->hInstance;
1987 if (!HIWORD(hmod))
1988 return LOWORD(hmod); /* we already have a 16 bit module handle */
1989 pModule = GlobalLock16(hFirstModule);
1990 while (pModule) {
1991 if (pModule->module32 == hmod)
1992 return pModule->self;
1993 pModule = GlobalLock16(pModule->next);
1995 if ((ret = create_dummy_module( hmod )) < 32)
1997 SetLastError(ret);
1998 ret = 0;
2000 return ret;
2003 /***************************************************************************
2004 * MapHModuleSL (KERNEL32.@)
2006 HMODULE WINAPI MapHModuleSL(HMODULE16 hmod)
2008 NE_MODULE *pModule;
2010 if (!hmod) {
2011 TDB *pTask = TASK_GetCurrent();
2012 hmod = pTask->hModule;
2014 pModule = GlobalLock16(hmod);
2015 if ((pModule->ne_magic != IMAGE_OS2_SIGNATURE) || !(pModule->ne_flags & NE_FFLAGS_WIN32))
2016 return 0;
2017 return pModule->module32;
2020 /***************************************************************************
2021 * MapHInstLS (KERNEL.472)
2023 void WINAPI MapHInstLS16( CONTEXT *context )
2025 context->Eax = MapHModuleLS( (HMODULE)context->Eax );
2028 /***************************************************************************
2029 * MapHInstSL (KERNEL.473)
2031 void WINAPI MapHInstSL16( CONTEXT *context )
2033 context->Eax = (DWORD)MapHModuleSL( context->Eax );
2036 /***************************************************************************
2037 * MapHInstLS (KERNEL32.@)
2039 __ASM_STDCALL_FUNC( MapHInstLS, 0,
2040 "pushl %eax\n\t"
2041 "call " __ASM_STDCALL("MapHModuleLS",4) "\n\t"
2042 "ret" )
2044 /***************************************************************************
2045 * MapHInstSL (KERNEL32.@)
2047 __ASM_STDCALL_FUNC( MapHInstSL, 0,
2048 "pushl %eax\n\t"
2049 "call " __ASM_STDCALL("MapHModuleSL",4) "\n\t"
2050 "ret" )
2052 /***************************************************************************
2053 * MapHInstLS_PN (KERNEL32.@)
2055 __ASM_STDCALL_FUNC( MapHInstLS_PN, 0,
2056 "testl %eax,%eax\n\t"
2057 "jz 1f\n\t"
2058 "pushl %eax\n\t"
2059 "call " __ASM_STDCALL("MapHModuleLS",4) "\n"
2060 "1:\tret" )
2062 /***************************************************************************
2063 * MapHInstSL_PN (KERNEL32.@)
2065 __ASM_STDCALL_FUNC( MapHInstSL_PN, 0,
2066 "andl $0xffff,%eax\n\t"
2067 "jz 1f\n\t"
2068 "pushl %eax\n\t"
2069 "call " __ASM_STDCALL("MapHModuleSL",4) "\n"
2070 "1:\tret" )