Added support for ordinal hint in PE_FindExportedFunction.
[wine/multimedia.git] / loader / pe_image.c
blob1974ac58ed735eb2fb762709f3071a36e11ea39c
1 /*
2 * Copyright 1994 Eric Youndale & Erik Bos
3 * Copyright 1995 Martin von Löwis
4 * Copyright 1996-98 Marcus Meissner
6 * based on Eric Youndale's pe-test and:
7 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 /* Notes:
24 * Before you start changing something in this file be aware of the following:
26 * - There are several functions called recursively. In a very subtle and
27 * obscure way. DLLs can reference each other recursively etc.
28 * - If you want to enhance, speed up or clean up something in here, think
29 * twice WHY it is implemented in that strange way. There is usually a reason.
30 * Though sometimes it might just be lazyness ;)
31 * - In PE_MapImage, right before PE_fixup_imports() all external and internal
32 * state MUST be correct since this function can be called with the SAME image
33 * AGAIN. (Thats recursion for you.) That means MODREF.module and
34 * NE_MODULE.module32.
37 #include "config.h"
39 #include <sys/types.h>
40 #ifdef HAVE_SYS_MMAN_H
41 #include <sys/mman.h>
42 #endif
43 #include <string.h>
44 #include "wine/winbase16.h"
45 #include "winerror.h"
46 #include "snoop.h"
47 #include "wine/server.h"
48 #include "wine/debug.h"
50 WINE_DEFAULT_DEBUG_CHANNEL(win32);
51 WINE_DECLARE_DEBUG_CHANNEL(delayhlp);
52 WINE_DECLARE_DEBUG_CHANNEL(fixup);
53 WINE_DECLARE_DEBUG_CHANNEL(module);
54 WINE_DECLARE_DEBUG_CHANNEL(relay);
55 WINE_DECLARE_DEBUG_CHANNEL(segment);
58 static IMAGE_EXPORT_DIRECTORY *get_exports( HMODULE hmod )
60 IMAGE_EXPORT_DIRECTORY *ret = NULL;
61 IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
62 + IMAGE_DIRECTORY_ENTRY_EXPORT;
63 if (dir->Size && dir->VirtualAddress)
64 ret = (IMAGE_EXPORT_DIRECTORY *)((char *)hmod + dir->VirtualAddress);
65 return ret;
68 static IMAGE_IMPORT_DESCRIPTOR *get_imports( HMODULE hmod )
70 IMAGE_IMPORT_DESCRIPTOR *ret = NULL;
71 IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
72 + IMAGE_DIRECTORY_ENTRY_IMPORT;
73 if (dir->Size && dir->VirtualAddress)
74 ret = (IMAGE_IMPORT_DESCRIPTOR *)((char *)hmod + dir->VirtualAddress);
75 return ret;
79 /* convert PE image VirtualAddress to Real Address */
80 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
82 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
84 void dump_exports( HMODULE hModule )
86 char *Module;
87 int i, j;
88 WORD *ordinal;
89 DWORD *function,*functions;
90 BYTE **name;
91 unsigned int load_addr = hModule;
93 DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
94 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
95 DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
96 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
97 IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
99 Module = (char*)RVA(pe_exports->Name);
100 DPRINTF("*******EXPORT DATA*******\n");
101 DPRINTF("Module name is %s, %ld functions, %ld names\n",
102 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
104 ordinal = RVA(pe_exports->AddressOfNameOrdinals);
105 functions = function = RVA(pe_exports->AddressOfFunctions);
106 name = RVA(pe_exports->AddressOfNames);
108 DPRINTF(" Ord RVA Addr Name\n" );
109 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
111 if (!*function) continue; /* No such function */
112 DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
113 /* Check if we have a name for it */
114 for (j = 0; j < pe_exports->NumberOfNames; j++)
115 if (ordinal[j] == i)
117 DPRINTF( " %s", (char*)RVA(name[j]) );
118 break;
120 if ((*function >= rva_start) && (*function <= rva_end))
121 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
122 DPRINTF("\n");
126 /* Look up the specified function or ordinal in the export list:
127 * If it is a string:
128 * - look up the name in the name list.
129 * - look up the ordinal with that index.
130 * - use the ordinal as offset into the functionlist
131 * If it is an ordinal:
132 * - use ordinal-pe_export->Base as offset into the function list
134 static FARPROC PE_FindExportedFunction(
135 WINE_MODREF *wm, /* [in] WINE modreference */
136 LPCSTR funcName, /* [in] function name */
137 int hint,
138 BOOL snoop )
140 WORD * ordinals;
141 DWORD * function;
142 BYTE ** name, *ename = NULL;
143 int i, ordinal;
144 unsigned int load_addr = wm->module;
145 DWORD rva_start, rva_end, addr;
146 char * forward;
147 IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
149 if (HIWORD(funcName))
150 TRACE("(%s)\n",funcName);
151 else
152 TRACE("(%d)\n",(int)funcName);
153 if (!exports) {
154 /* Not a fatal problem, some apps do
155 * GetProcAddress(0,"RegisterPenApp") which triggers this
156 * case.
158 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
159 return NULL;
161 ordinals= RVA(exports->AddressOfNameOrdinals);
162 function= RVA(exports->AddressOfFunctions);
163 name = RVA(exports->AddressOfNames);
164 forward = NULL;
165 rva_start = PE_HEADER(wm->module)->OptionalHeader
166 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
167 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
168 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
170 if (HIWORD(funcName))
172 int min = 0, max = exports->NumberOfNames - 1;
174 /* first check the hint */
175 if (hint >= 0 && hint <= max)
177 ename = RVA(name[hint]);
178 if (!strcmp( ename, funcName ))
180 ordinal = ordinals[hint];
181 goto found;
185 /* then do a binary search */
186 while (min <= max)
188 int res, pos = (min + max) / 2;
189 ename = RVA(name[pos]);
190 if (!(res = strcmp( ename, funcName )))
192 ordinal = ordinals[pos];
193 goto found;
195 if (res > 0) max = pos - 1;
196 else min = pos + 1;
198 return NULL;
200 else /* find by ordinal */
202 ordinal = LOWORD(funcName) - exports->Base;
203 if (snoop && name) /* need to find a name for it */
205 for (i = 0; i < exports->NumberOfNames; i++)
206 if (ordinals[i] == ordinal)
208 ename = RVA(name[i]);
209 break;
214 found:
215 if (ordinal >= exports->NumberOfFunctions)
217 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
218 return NULL;
220 addr = function[ordinal];
221 if (!addr) return NULL;
222 if ((addr < rva_start) || (addr >= rva_end))
224 FARPROC proc = RVA(addr);
225 if (snoop)
227 if (!ename) ename = "@";
228 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
230 return proc;
232 else /* forward entry point */
234 WINE_MODREF *wm_fw;
235 FARPROC proc;
236 char *forward = RVA(addr);
237 char module[256];
238 char *end = strchr(forward, '.');
240 if (!end) return NULL;
241 if (end - forward >= sizeof(module)) return NULL;
242 memcpy( module, forward, end - forward );
243 module[end-forward] = 0;
244 if (!(wm_fw = MODULE_FindModule( module )))
246 ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
247 return NULL;
249 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, -1, snoop )))
250 ERR("function not found for forward '%s' used by '%s'. If you are using builtin '%s', try using the native one instead.\n", forward, wm->modname, wm->modname );
251 return proc;
255 /****************************************************************
256 * PE_fixup_imports
258 DWORD PE_fixup_imports( WINE_MODREF *wm )
260 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
261 unsigned int load_addr = wm->module;
262 int i,characteristics_detection=1;
263 IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
265 /* first, count the number of imported non-internal modules */
266 pe_imp = imports;
267 if (!pe_imp) return 0;
269 /* OK, now dump the import list */
270 TRACE("Dumping imports list\n");
272 /* We assume that we have at least one import with !0 characteristics and
273 * detect broken imports with all characteristics 0 (notably Borland) and
274 * switch the detection off for them.
276 for (i = 0; pe_imp->Name ; pe_imp++) {
277 if (!i && !pe_imp->u.Characteristics)
278 characteristics_detection = 0;
279 if (characteristics_detection && !pe_imp->u.Characteristics)
280 break;
281 i++;
283 if (!i) return 0; /* no imports */
285 /* Allocate module dependency list */
286 wm->nDeps = i;
287 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
289 /* load the imported modules. They are automatically
290 * added to the modref list of the process.
293 for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
294 WINE_MODREF *wmImp;
295 IMAGE_IMPORT_BY_NAME *pe_name;
296 PIMAGE_THUNK_DATA import_list,thunk_list;
297 char *name = (char *) RVA(pe_imp->Name);
299 if (characteristics_detection && !pe_imp->u.Characteristics)
300 break;
302 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
303 if (!wmImp) {
304 ERR_(module)("Module (file) %s (which is needed by %s) not found\n", name, wm->filename);
305 return 1;
307 wm->deps[i++] = wmImp;
309 /* FIXME: forwarder entries ... */
311 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
312 TRACE("Microsoft style imports used\n");
313 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
314 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
316 while (import_list->u1.Ordinal) {
317 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
318 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
320 TRACE("--- Ordinal %s,%d\n", name, ordinal);
321 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
322 wmImp->module, (LPCSTR)ordinal, -1, TRUE
324 if (!thunk_list->u1.Function) {
325 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
326 name, ordinal, wm->filename );
327 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
329 } else { /* import by name */
330 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
331 TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
332 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
333 wmImp->module, pe_name->Name, pe_name->Hint, TRUE
335 if (!thunk_list->u1.Function) {
336 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
337 name,pe_name->Hint,pe_name->Name,wm->filename);
338 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
341 import_list++;
342 thunk_list++;
344 } else { /* Borland style */
345 TRACE("Borland style imports used\n");
346 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
347 while (thunk_list->u1.Ordinal) {
348 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
349 /* not sure about this branch, but it seems to work */
350 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
352 TRACE("--- Ordinal %s.%d\n",name,ordinal);
353 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
354 wmImp->module, (LPCSTR) ordinal, -1, TRUE
356 if (!thunk_list->u1.Function) {
357 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
358 name,ordinal, wm->filename);
359 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
361 } else {
362 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
363 TRACE("--- %s %s.%d\n",
364 pe_name->Name,name,pe_name->Hint);
365 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
366 wmImp->module, pe_name->Name, pe_name->Hint, TRUE
368 if (!thunk_list->u1.Function) {
369 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
370 name, pe_name->Hint, pe_name->Name, wm->filename);
371 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
374 thunk_list++;
378 return 0;
381 /***********************************************************************
382 * do_relocations
384 * Apply the relocations to a mapped PE image
386 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
388 const IMAGE_DATA_DIRECTORY *dir;
389 const IMAGE_BASE_RELOCATION *rel;
390 int delta = base - (char *)nt->OptionalHeader.ImageBase;
392 dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
393 rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
395 WARN("Info: base relocations needed for %s\n", filename);
396 if (!dir->VirtualAddress || !dir->Size)
398 if (nt->OptionalHeader.ImageBase == 0x400000)
399 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
400 else
401 ERR( "FATAL: Need to relocate %s from addr %lx, but %s\n",
402 filename, nt->OptionalHeader.ImageBase,
403 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
404 "relocation records are stripped" : "no relocation records present" );
405 return 0;
408 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
409 * really make sure that the *new* base address is also > 2GB.
410 * Some DLLs really check the MSB of the module handle :-/
412 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
413 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
415 for ( ; ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
416 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock))
418 char *page = base + rel->VirtualAddress;
419 WORD *TypeOffset = (WORD *)(rel + 1);
420 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
422 if (!count) continue;
424 /* sanity checks */
425 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
426 page > base + nt->OptionalHeader.SizeOfImage)
428 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
429 rel, rel->VirtualAddress, rel->SizeOfBlock,
430 base, dir->VirtualAddress, dir->Size );
431 return 0;
434 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
436 /* patching in reverse order */
437 for (i = 0 ; i < count; i++)
439 int offset = TypeOffset[i] & 0xFFF;
440 int type = TypeOffset[i] >> 12;
441 switch(type)
443 case IMAGE_REL_BASED_ABSOLUTE:
444 break;
445 case IMAGE_REL_BASED_HIGH:
446 *(short*)(page+offset) += HIWORD(delta);
447 break;
448 case IMAGE_REL_BASED_LOW:
449 *(short*)(page+offset) += LOWORD(delta);
450 break;
451 case IMAGE_REL_BASED_HIGHLOW:
452 *(int*)(page+offset) += delta;
453 /* FIXME: if this is an exported address, fire up enhanced logic */
454 break;
455 default:
456 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
457 break;
461 return 1;
465 /**********************************************************************
466 * PE_LoadImage
467 * Load one PE format DLL/EXE into memory
469 * Unluckily we can't just mmap the sections where we want them, for
470 * (at least) Linux does only support offsets which are page-aligned.
472 * BUT we have to map the whole image anyway, for Win32 programs sometimes
473 * want to access them. (HMODULE points to the start of it)
475 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
477 IMAGE_NT_HEADERS *nt;
478 HMODULE hModule;
479 HANDLE mapping;
480 void *base;
482 TRACE_(module)( "loading %s\n", filename );
484 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
485 if (!mapping) return 0;
486 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
487 CloseHandle( mapping );
488 if (!base) return 0;
490 hModule = (HMODULE)base;
492 /* perform base relocation, if necessary */
494 nt = PE_HEADER( hModule );
495 if (hModule != nt->OptionalHeader.ImageBase)
497 if (!do_relocations( base, nt, filename ))
499 UnmapViewOfFile( base );
500 SetLastError( ERROR_BAD_EXE_FORMAT );
501 return 0;
505 /* virus check */
507 if (nt->OptionalHeader.AddressOfEntryPoint)
509 int i;
510 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
511 nt->FileHeader.SizeOfOptionalHeader);
512 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
514 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
515 continue;
516 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
517 break;
519 if (i == nt->FileHeader.NumberOfSections)
520 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
521 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
522 nt->OptionalHeader.AddressOfEntryPoint );
525 return hModule;
528 /**********************************************************************
529 * PE_CreateModule
531 * Create WINE_MODREF structure for loaded HMODULE, link it into
532 * process modref_list, and fixup all imports.
534 * Note: hModule must point to a correctly allocated PE image,
535 * with base relocations applied; the 16-bit dummy module
536 * associated to hModule must already exist.
538 * Note: This routine must always be called in the context of the
539 * process that is to own the module to be created.
541 * Note: Assumes that the process critical section is held
543 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
544 HANDLE hFile, BOOL builtin )
546 DWORD load_addr = (DWORD)hModule; /* for RVA */
547 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
548 IMAGE_DATA_DIRECTORY *dir;
549 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
550 WINE_MODREF *wm;
551 HMODULE16 hModule16;
553 /* Retrieve DataDirectory entries */
555 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
556 if (dir->Size)
557 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
559 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
560 if (dir->Size) FIXME("Exception directory ignored\n" );
562 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
563 if (dir->Size) FIXME("Security directory ignored\n" );
565 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
566 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
568 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
569 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
571 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
573 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
574 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
576 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
577 if (dir->Size) TRACE("Bound Import directory ignored\n" );
579 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
580 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
582 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
583 if (dir->Size)
585 TRACE("Delayed import, stub calls LoadLibrary\n" );
587 * Nothing to do here.
590 #ifdef ImgDelayDescr
592 * This code is useful to observe what the heck is going on.
595 ImgDelayDescr *pe_delay = NULL;
596 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
597 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
598 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
599 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
600 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
601 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
602 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
603 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
604 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
606 #endif /* ImgDelayDescr */
609 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
610 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
612 dir = nt->OptionalHeader.DataDirectory+15;
613 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
615 /* Create 16-bit dummy module */
617 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
619 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
620 return NULL;
623 /* Allocate and fill WINE_MODREF */
625 if (!(wm = MODULE_AllocModRef( hModule, filename )))
627 FreeLibrary16( hModule16 );
628 return NULL;
630 wm->hDummyMod = hModule16;
632 if ( builtin )
634 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
635 pModule->flags |= NE_FFLAGS_BUILTIN;
636 wm->flags |= WINE_MODREF_INTERNAL;
638 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
639 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
641 wm->find_export = PE_FindExportedFunction;
643 /* Dump Exports */
645 if (pe_export && TRACE_ON(win32))
646 dump_exports( hModule );
648 /* Fixup Imports */
650 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
651 PE_fixup_imports( wm ))
653 /* remove entry from modref chain */
655 if ( !wm->prev )
656 MODULE_modref_list = wm->next;
657 else
658 wm->prev->next = wm->next;
660 if ( wm->next ) wm->next->prev = wm->prev;
661 wm->next = wm->prev = NULL;
663 /* FIXME: there are several more dangling references
664 * left. Including dlls loaded by this dll before the
665 * failed one. Unrolling is rather difficult with the
666 * current structure and we can leave them lying
667 * around with no problems, so we don't care.
668 * As these might reference our wm, we don't free it.
670 return NULL;
673 if (!builtin && pe_export)
674 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
676 /* Send DLL load event */
677 /* we don't need to send a dll event for the main exe */
679 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
681 if (hFile)
683 UINT drive_type = GetDriveTypeA( wm->short_filename );
684 /* don't keep the file handle open on removable media */
685 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
687 SERVER_START_REQ( load_dll )
689 req->handle = hFile;
690 req->base = (void *)hModule;
691 req->size = nt->OptionalHeader.SizeOfImage;
692 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
693 req->dbg_size = nt->FileHeader.NumberOfSymbols;
694 req->name = &wm->filename;
695 wine_server_add_data( req, wm->filename, strlen(wm->filename) );
696 wine_server_call( req );
698 SERVER_END_REQ;
701 return wm;
704 /******************************************************************************
705 * The PE Library Loader frontend.
706 * FIXME: handle the flags.
708 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
710 HMODULE hModule32;
711 WINE_MODREF *wm;
712 HANDLE hFile;
714 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
715 NULL, OPEN_EXISTING, 0, 0 );
716 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
718 /* Load PE module */
719 hModule32 = PE_LoadImage( hFile, name, flags );
720 if (!hModule32)
722 CloseHandle( hFile );
723 return NULL;
726 /* Create 32-bit MODREF */
727 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
729 ERR( "can't load %s\n", name );
730 CloseHandle( hFile );
731 SetLastError( ERROR_OUTOFMEMORY );
732 return NULL;
735 CloseHandle( hFile );
736 return wm;
740 /* Called if the library is loaded or freed.
741 * NOTE: if a thread attaches a DLL, the current thread will only do
742 * DLL_PROCESS_ATTACH. Only newly created threads do DLL_THREAD_ATTACH
743 * (SDK)
745 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
747 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
749 BOOL retv = TRUE;
750 IMAGE_NT_HEADERS *nt = PE_HEADER(module);
752 /* Is this a library? And has it got an entrypoint? */
753 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
754 (nt->OptionalHeader.AddressOfEntryPoint))
756 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
757 if (TRACE_ON(relay))
758 DPRINTF("%08lx:Call PE DLL (proc=%p,module=%08x,type=%ld,res=%p)\n",
759 GetCurrentThreadId(), entry, module, type, lpReserved );
760 retv = entry( module, type, lpReserved );
761 if (TRACE_ON(relay))
762 DPRINTF("%08lx:Ret PE DLL (proc=%p,module=%08x,type=%ld,res=%p) retval=%x\n",
763 GetCurrentThreadId(), entry, module, type, lpReserved, retv );
766 return retv;
769 /************************************************************************
770 * PE_InitTls (internal)
772 * If included, initialises the thread local storages of modules.
773 * Pointers in those structs are not RVAs but real pointers which have been
774 * relocated by do_relocations() already.
776 static LPVOID
777 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
778 if ( ((DWORD)addr>opt->ImageBase) &&
779 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
781 /* the address has not been relocated! */
782 return (LPVOID)(((DWORD)addr)+delta);
783 else
784 /* the address has been relocated already */
785 return addr;
787 void PE_InitTls( void )
789 WINE_MODREF *wm;
790 IMAGE_NT_HEADERS *peh;
791 DWORD size,datasize;
792 LPVOID mem;
793 PIMAGE_TLS_DIRECTORY pdir;
794 int delta;
796 for (wm = MODULE_modref_list;wm;wm=wm->next) {
797 peh = PE_HEADER(wm->module);
798 delta = wm->module - peh->OptionalHeader.ImageBase;
799 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
800 continue;
801 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
802 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
805 if ( wm->tlsindex == -1 ) {
806 LPDWORD xaddr;
807 wm->tlsindex = TlsAlloc();
808 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
809 pdir->AddressOfIndex
811 *xaddr=wm->tlsindex;
813 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
814 size = datasize + pdir->SizeOfZeroFill;
815 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
816 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
817 if (pdir->AddressOfCallBacks) {
818 PIMAGE_TLS_CALLBACK *cbs;
820 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
821 if (*cbs)
822 FIXME("TLS Callbacks aren't going to be called\n");
825 TlsSetValue( wm->tlsindex, mem );