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:
8 * ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
10 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
13 * Before you start changing something in this file be aware of the following:
15 * - There are several functions called recursively. In a very subtle and
16 * obscure way. DLLs can reference each other recursively etc.
17 * - If you want to enhance, speed up or clean up something in here, think
18 * twice WHY it is implemented in that strange way. There is usually a reason.
19 * Though sometimes it might just be lazyness ;)
20 * - In PE_MapImage, right before fixup_imports() all external and internal
21 * state MUST be correct since this function can be called with the SAME image
22 * AGAIN. (Thats recursion for you.) That means MODREF.module and
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_MMAN_H
33 #include "wine/winbase16.h"
37 #include "debugtools.h"
39 DEFAULT_DEBUG_CHANNEL(win32);
40 DECLARE_DEBUG_CHANNEL(delayhlp);
41 DECLARE_DEBUG_CHANNEL(fixup);
42 DECLARE_DEBUG_CHANNEL(module);
43 DECLARE_DEBUG_CHANNEL(relay);
44 DECLARE_DEBUG_CHANNEL(segment);
47 static IMAGE_EXPORT_DIRECTORY *get_exports( HMODULE hmod )
49 IMAGE_EXPORT_DIRECTORY *ret = NULL;
50 IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
51 + IMAGE_DIRECTORY_ENTRY_EXPORT;
52 if (dir->Size && dir->VirtualAddress)
53 ret = (IMAGE_EXPORT_DIRECTORY *)((char *)hmod + dir->VirtualAddress);
57 static IMAGE_IMPORT_DESCRIPTOR *get_imports( HMODULE hmod )
59 IMAGE_IMPORT_DESCRIPTOR *ret = NULL;
60 IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
61 + IMAGE_DIRECTORY_ENTRY_IMPORT;
62 if (dir->Size && dir->VirtualAddress)
63 ret = (IMAGE_IMPORT_DESCRIPTOR *)((char *)hmod + dir->VirtualAddress);
68 /* convert PE image VirtualAddress to Real Address */
69 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
71 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
73 void dump_exports( HMODULE hModule )
78 DWORD *function,*functions;
80 unsigned int load_addr = hModule;
82 DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
83 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
84 DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
85 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
86 IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
88 Module = (char*)RVA(pe_exports->Name);
89 TRACE("*******EXPORT DATA*******\n");
90 TRACE("Module name is %s, %ld functions, %ld names\n",
91 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
93 ordinal = RVA(pe_exports->AddressOfNameOrdinals);
94 functions = function = RVA(pe_exports->AddressOfFunctions);
95 name = RVA(pe_exports->AddressOfNames);
97 TRACE(" Ord RVA Addr Name\n" );
98 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
100 if (!*function) continue; /* No such function */
103 DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
104 /* Check if we have a name for it */
105 for (j = 0; j < pe_exports->NumberOfNames; j++)
108 DPRINTF( " %s", (char*)RVA(name[j]) );
111 if ((*function >= rva_start) && (*function <= rva_end))
112 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
118 /* Look up the specified function or ordinal in the export list:
120 * - look up the name in the name list.
121 * - look up the ordinal with that index.
122 * - use the ordinal as offset into the functionlist
123 * If it is an ordinal:
124 * - use ordinal-pe_export->Base as offset into the function list
126 static FARPROC PE_FindExportedFunction(
127 WINE_MODREF *wm, /* [in] WINE modreference */
128 LPCSTR funcName, /* [in] function name */
133 BYTE ** name, *ename = NULL;
135 unsigned int load_addr = wm->module;
136 DWORD rva_start, rva_end, addr;
138 IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
140 if (HIWORD(funcName))
141 TRACE("(%s)\n",funcName);
143 TRACE("(%d)\n",(int)funcName);
145 /* Not a fatal problem, some apps do
146 * GetProcAddress(0,"RegisterPenApp") which triggers this
149 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
152 ordinals= RVA(exports->AddressOfNameOrdinals);
153 function= RVA(exports->AddressOfFunctions);
154 name = RVA(exports->AddressOfNames);
156 rva_start = PE_HEADER(wm->module)->OptionalHeader
157 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
158 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
159 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
161 if (HIWORD(funcName))
163 /* first try a binary search */
164 int min = 0, max = exports->NumberOfNames - 1;
167 int res, pos = (min + max) / 2;
168 ename = RVA(name[pos]);
169 if (!(res = strcmp( ename, funcName )))
171 ordinal = ordinals[pos];
174 if (res > 0) max = pos - 1;
177 /* now try a linear search in case the names aren't sorted properly */
178 for (i = 0; i < exports->NumberOfNames; i++)
180 ename = RVA(name[i]);
181 if (!strcmp( ename, funcName ))
183 ERR( "%s.%s required a linear search\n", wm->modname, funcName );
184 ordinal = ordinals[i];
190 else /* find by ordinal */
192 ordinal = LOWORD(funcName) - exports->Base;
193 if (snoop && name) /* need to find a name for it */
195 for (i = 0; i < exports->NumberOfNames; i++)
196 if (ordinals[i] == ordinal)
198 ename = RVA(name[i]);
205 if (ordinal >= exports->NumberOfFunctions)
207 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
210 addr = function[ordinal];
211 if (!addr) return NULL;
212 if ((addr < rva_start) || (addr >= rva_end))
214 FARPROC proc = RVA(addr);
217 if (!ename) ename = "@";
218 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
222 else /* forward entry point */
226 char *forward = RVA(addr);
228 char *end = strchr(forward, '.');
230 if (!end) return NULL;
231 if (end - forward >= sizeof(module)) return NULL;
232 memcpy( module, forward, end - forward );
233 module[end-forward] = 0;
234 if (!(wm_fw = MODULE_FindModule( module )))
236 ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
239 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, snoop )))
240 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 );
245 DWORD fixup_imports( WINE_MODREF *wm )
247 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
248 unsigned int load_addr = wm->module;
249 int i,characteristics_detection=1;
250 IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
252 /* first, count the number of imported non-internal modules */
254 if (!pe_imp) return 0;
256 /* OK, now dump the import list */
257 TRACE("Dumping imports list\n");
259 /* We assume that we have at least one import with !0 characteristics and
260 * detect broken imports with all characteristics 0 (notably Borland) and
261 * switch the detection off for them.
263 for (i = 0; pe_imp->Name ; pe_imp++) {
264 if (!i && !pe_imp->u.Characteristics)
265 characteristics_detection = 0;
266 if (characteristics_detection && !pe_imp->u.Characteristics)
270 if (!i) return 0; /* no imports */
272 /* Allocate module dependency list */
274 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
276 /* load the imported modules. They are automatically
277 * added to the modref list of the process.
280 for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
282 IMAGE_IMPORT_BY_NAME *pe_name;
283 PIMAGE_THUNK_DATA import_list,thunk_list;
284 char *name = (char *) RVA(pe_imp->Name);
286 if (characteristics_detection && !pe_imp->u.Characteristics)
289 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
291 ERR_(module)("Module (file) %s needed by %s not found\n", name, wm->filename);
294 wm->deps[i++] = wmImp;
296 /* FIXME: forwarder entries ... */
298 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
299 TRACE("Microsoft style imports used\n");
300 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
301 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
303 while (import_list->u1.Ordinal) {
304 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
305 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
307 TRACE("--- Ordinal %s,%d\n", name, ordinal);
308 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
309 wmImp->module, (LPCSTR)ordinal, TRUE
311 if (!thunk_list->u1.Function) {
312 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
313 name, ordinal, wm->filename );
314 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
316 } else { /* import by name */
317 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
318 TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
319 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
320 wmImp->module, pe_name->Name, TRUE
322 if (!thunk_list->u1.Function) {
323 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
324 name,pe_name->Hint,pe_name->Name,wm->filename);
325 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
331 } else { /* Borland style */
332 TRACE("Borland style imports used\n");
333 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
334 while (thunk_list->u1.Ordinal) {
335 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
336 /* not sure about this branch, but it seems to work */
337 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
339 TRACE("--- Ordinal %s.%d\n",name,ordinal);
340 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
341 wmImp->module, (LPCSTR) ordinal, TRUE
343 if (!thunk_list->u1.Function) {
344 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
345 name,ordinal, wm->filename);
346 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
349 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
350 TRACE("--- %s %s.%d\n",
351 pe_name->Name,name,pe_name->Hint);
352 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
353 wmImp->module, pe_name->Name, TRUE
355 if (!thunk_list->u1.Function) {
356 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
357 name, pe_name->Hint, pe_name->Name, wm->filename);
358 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
368 /***********************************************************************
371 * Apply the relocations to a mapped PE image
373 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
375 const IMAGE_DATA_DIRECTORY *dir;
376 const IMAGE_BASE_RELOCATION *rel;
377 int delta = base - (char *)nt->OptionalHeader.ImageBase;
379 dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
380 rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
382 WARN("Info: base relocations needed for %s\n", filename);
383 if (!dir->VirtualAddress || !dir->Size)
385 if (nt->OptionalHeader.ImageBase == 0x400000)
386 ERR("Standard load address for a Win32 program not available - patched kernel ?\n");
387 ERR( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
389 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
390 "stripped during link" : "unknown reason" );
394 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
395 * really make sure that the *new* base address is also > 2GB.
396 * Some DLLs really check the MSB of the module handle :-/
398 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
399 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
401 for ( ; ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->VirtualAddress;
402 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock))
404 char *page = base + rel->VirtualAddress;
405 int i, count = (rel->SizeOfBlock - 8) / sizeof(rel->TypeOffset);
407 if (!count) continue;
410 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
411 page > base + nt->OptionalHeader.SizeOfImage)
413 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
414 rel, rel->VirtualAddress, rel->SizeOfBlock,
415 base, dir->VirtualAddress, dir->Size );
419 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
421 /* patching in reverse order */
422 for (i = 0 ; i < count; i++)
424 int offset = rel->TypeOffset[i] & 0xFFF;
425 int type = rel->TypeOffset[i] >> 12;
428 case IMAGE_REL_BASED_ABSOLUTE:
430 case IMAGE_REL_BASED_HIGH:
431 *(short*)(page+offset) += HIWORD(delta);
433 case IMAGE_REL_BASED_LOW:
434 *(short*)(page+offset) += LOWORD(delta);
436 case IMAGE_REL_BASED_HIGHLOW:
437 *(int*)(page+offset) += delta;
438 /* FIXME: if this is an exported address, fire up enhanced logic */
441 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
450 /**********************************************************************
452 * Load one PE format DLL/EXE into memory
454 * Unluckily we can't just mmap the sections where we want them, for
455 * (at least) Linux does only support offsets which are page-aligned.
457 * BUT we have to map the whole image anyway, for Win32 programs sometimes
458 * want to access them. (HMODULE32 point to the start of it)
460 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
462 IMAGE_NT_HEADERS *nt;
467 TRACE_(module)( "loading %s\n", filename );
469 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
470 if (!mapping) return 0;
471 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
472 CloseHandle( mapping );
475 hModule = (HMODULE)base;
476 if (flags & LOAD_LIBRARY_AS_DATAFILE) return hModule; /* nothing else to do */
478 /* perform base relocation, if necessary */
480 nt = PE_HEADER( hModule );
481 if (hModule != nt->OptionalHeader.ImageBase)
483 if (!do_relocations( base, nt, filename ))
485 UnmapViewOfFile( base );
486 SetLastError( ERROR_BAD_EXE_FORMAT );
493 if (nt->OptionalHeader.AddressOfEntryPoint)
496 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
497 nt->FileHeader.SizeOfOptionalHeader);
498 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
500 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
502 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
505 if (i == nt->FileHeader.NumberOfSections)
506 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
507 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
508 nt->OptionalHeader.AddressOfEntryPoint );
514 /**********************************************************************
517 * Create WINE_MODREF structure for loaded HMODULE32, link it into
518 * process modref_list, and fixup all imports.
520 * Note: hModule must point to a correctly allocated PE image,
521 * with base relocations applied; the 16-bit dummy module
522 * associated to hModule must already exist.
524 * Note: This routine must always be called in the context of the
525 * process that is to own the module to be created.
527 * Note: Assumes that the process critical section is held
529 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
530 HANDLE hFile, BOOL builtin )
532 DWORD load_addr = (DWORD)hModule; /* for RVA */
533 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
534 IMAGE_DATA_DIRECTORY *dir;
535 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
539 /* Retrieve DataDirectory entries */
541 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
543 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
545 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
546 if (dir->Size) FIXME("Exception directory ignored\n" );
548 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
549 if (dir->Size) FIXME("Security directory ignored\n" );
551 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
552 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
554 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
555 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
557 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
559 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
560 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
562 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
563 if (dir->Size) TRACE("Bound Import directory ignored\n" );
565 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
566 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
568 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
571 TRACE("Delayed import, stub calls LoadLibrary\n" );
573 * Nothing to do here.
578 * This code is useful to observe what the heck is going on.
581 ImgDelayDescr *pe_delay = NULL;
582 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
583 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
584 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
585 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
586 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
587 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
588 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
589 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
590 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
592 #endif /* ImgDelayDescr */
595 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
596 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
598 dir = nt->OptionalHeader.DataDirectory+15;
599 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
601 /* Create 16-bit dummy module */
603 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
605 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
609 /* Allocate and fill WINE_MODREF */
611 if (!(wm = MODULE_AllocModRef( hModule, filename )))
613 FreeLibrary16( hModule16 );
616 wm->hDummyMod = hModule16;
620 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
621 pModule->flags |= NE_FFLAGS_BUILTIN;
622 wm->flags |= WINE_MODREF_INTERNAL;
624 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
625 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
627 wm->find_export = PE_FindExportedFunction;
632 dump_exports( hModule );
636 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) && fixup_imports( wm ))
638 /* remove entry from modref chain */
641 MODULE_modref_list = wm->next;
643 wm->prev->next = wm->next;
645 if ( wm->next ) wm->next->prev = wm->prev;
646 wm->next = wm->prev = NULL;
648 /* FIXME: there are several more dangling references
649 * left. Including dlls loaded by this dll before the
650 * failed one. Unrolling is rather difficult with the
651 * current structure and we can leave it them lying
652 * around with no problems, so we don't care.
653 * As these might reference our wm, we don't free it.
659 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
661 /* Send DLL load event */
662 /* we don't need to send a dll event for the main exe */
664 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
666 SERVER_START_REQ( load_dll )
669 req->base = (void *)hModule;
670 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
671 req->dbg_size = nt->FileHeader.NumberOfSymbols;
672 req->name = &wm->filename;
681 /******************************************************************************
682 * The PE Library Loader frontend.
683 * FIXME: handle the flags.
685 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
691 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
692 NULL, OPEN_EXISTING, 0, 0 );
693 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
696 hModule32 = PE_LoadImage( hFile, name, flags );
699 CloseHandle( hFile );
703 /* Create 32-bit MODREF */
704 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
706 ERR( "can't load %s\n", name );
707 CloseHandle( hFile );
708 SetLastError( ERROR_OUTOFMEMORY );
712 CloseHandle( hFile );
717 /* Called if the library is loaded or freed.
718 * NOTE: if a thread attaches a DLL, the current thread will only do
719 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
722 typedef DWORD CALLBACK(*DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
724 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
727 IMAGE_NT_HEADERS *nt = PE_HEADER(module);
729 /* Is this a library? And has it got an entrypoint? */
730 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
731 (nt->OptionalHeader.AddressOfEntryPoint))
733 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
735 DPRINTF("%08lx:Call PE DLL (proc=%p,module=%08x,type=%ld,res=%p)\n",
736 GetCurrentThreadId(), entry, module, type, lpReserved );
737 retv = entry( module, type, lpReserved );
739 DPRINTF("%08lx:Ret PE DLL (proc=%p,module=%08x,type=%ld,res=%p) retval=%x\n",
740 GetCurrentThreadId(), entry, module, type, lpReserved, retv );
746 /************************************************************************
747 * PE_InitTls (internal)
749 * If included, initialises the thread local storages of modules.
750 * Pointers in those structs are not RVAs but real pointers which have been
751 * relocated by do_relocations() already.
754 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
755 if ( ((DWORD)addr>opt->ImageBase) &&
756 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
758 /* the address has not been relocated! */
759 return (LPVOID)(((DWORD)addr)+delta);
761 /* the address has been relocated already */
764 void PE_InitTls( void )
767 IMAGE_NT_HEADERS *peh;
770 PIMAGE_TLS_DIRECTORY pdir;
773 for (wm = MODULE_modref_list;wm;wm=wm->next) {
774 peh = PE_HEADER(wm->module);
775 delta = wm->module - peh->OptionalHeader.ImageBase;
776 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
778 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
779 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
782 if ( wm->tlsindex == -1 ) {
784 wm->tlsindex = TlsAlloc();
785 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
790 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
791 size = datasize + pdir->SizeOfZeroFill;
792 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
793 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
794 if (pdir->AddressOfCallBacks) {
795 PIMAGE_TLS_CALLBACK *cbs;
797 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
799 FIXME("TLS Callbacks aren't going to be called\n");
802 TlsSetValue( wm->tlsindex, mem );