Convert HKL to a void*.
[wine/wine-kai.git] / loader / pe_image.c
blob029665c512f48e613d37579e96fe1fad5c85e6af
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 /* convert PE image VirtualAddress to Real Address */
59 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
61 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
63 void dump_exports( HMODULE hModule )
65 char *Module;
66 int i, j;
67 WORD *ordinal;
68 DWORD *function,*functions;
69 BYTE **name;
70 unsigned int load_addr = hModule;
71 IMAGE_EXPORT_DIRECTORY *pe_exports;
72 DWORD rva_start, size;
74 pe_exports = RtlImageDirectoryEntryToData( hModule, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
75 rva_start = (char *)pe_exports - (char *)hModule;
77 Module = (char*)RVA(pe_exports->Name);
78 DPRINTF("*******EXPORT DATA*******\n");
79 DPRINTF("Module name is %s, %ld functions, %ld names\n",
80 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
82 ordinal = RVA(pe_exports->AddressOfNameOrdinals);
83 functions = function = RVA(pe_exports->AddressOfFunctions);
84 name = RVA(pe_exports->AddressOfNames);
86 DPRINTF(" Ord RVA Addr Name\n" );
87 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
89 if (!*function) continue; /* No such function */
90 DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
91 /* Check if we have a name for it */
92 for (j = 0; j < pe_exports->NumberOfNames; j++)
93 if (ordinal[j] == i)
95 DPRINTF( " %s", (char*)RVA(name[j]) );
96 break;
98 if ((*function >= rva_start) && (*function <= rva_start + size))
99 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
100 DPRINTF("\n");
104 /* Look up the specified function or ordinal in the export list:
105 * If it is a string:
106 * - look up the name in the name list.
107 * - look up the ordinal with that index.
108 * - use the ordinal as offset into the functionlist
109 * If it is an ordinal:
110 * - use ordinal-pe_export->Base as offset into the function list
112 static FARPROC PE_FindExportedFunction(
113 WINE_MODREF *wm, /* [in] WINE modreference */
114 LPCSTR funcName, /* [in] function name */
115 int hint,
116 BOOL snoop )
118 WORD * ordinals;
119 DWORD * function;
120 BYTE ** name, *ename = NULL;
121 int i, ordinal;
122 unsigned int load_addr = wm->module;
123 DWORD rva_start, addr;
124 char * forward;
125 FARPROC proc;
126 IMAGE_EXPORT_DIRECTORY *exports;
127 DWORD exp_size;
129 if (!(exports = RtlImageDirectoryEntryToData( wm->module, TRUE,
130 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
131 return NULL;
133 if (HIWORD(funcName)) TRACE("(%s)\n",funcName);
134 else TRACE("(%d)\n",LOWORD(funcName));
136 ordinals= RVA(exports->AddressOfNameOrdinals);
137 function= RVA(exports->AddressOfFunctions);
138 name = RVA(exports->AddressOfNames);
139 forward = NULL;
140 rva_start = (char *)exports - (char *)wm->module;
142 if (HIWORD(funcName))
144 int min = 0, max = exports->NumberOfNames - 1;
146 /* first check the hint */
147 if (hint >= 0 && hint <= max)
149 ename = RVA(name[hint]);
150 if (!strcmp( ename, funcName ))
152 ordinal = ordinals[hint];
153 goto found;
157 /* then do a binary search */
158 while (min <= max)
160 int res, pos = (min + max) / 2;
161 ename = RVA(name[pos]);
162 if (!(res = strcmp( ename, funcName )))
164 ordinal = ordinals[pos];
165 goto found;
167 if (res > 0) max = pos - 1;
168 else min = pos + 1;
170 return NULL;
172 else /* find by ordinal */
174 ordinal = LOWORD(funcName) - exports->Base;
175 if (snoop && name) /* need to find a name for it */
177 for (i = 0; i < exports->NumberOfNames; i++)
178 if (ordinals[i] == ordinal)
180 ename = RVA(name[i]);
181 break;
186 found:
187 if (ordinal >= exports->NumberOfFunctions)
189 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
190 return NULL;
192 addr = function[ordinal];
193 if (!addr) return NULL;
195 proc = RVA(addr);
196 if (((char *)proc < (char *)exports) || ((char *)proc >= (char *)exports + exp_size))
198 if (snoop)
200 if (!ename) ename = "@";
201 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
203 return proc;
205 else /* forward entry point */
207 WINE_MODREF *wm_fw;
208 char *forward = (char *)proc;
209 char module[256];
210 char *end = strchr(forward, '.');
212 if (!end) return NULL;
213 if (end - forward >= sizeof(module)) return NULL;
214 memcpy( module, forward, end - forward );
215 module[end-forward] = 0;
216 if (!(wm_fw = MODULE_FindModule( module )))
218 ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
219 return NULL;
221 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, -1, snoop )))
222 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 );
223 return proc;
227 /****************************************************************
228 * PE_fixup_imports
230 DWORD PE_fixup_imports( WINE_MODREF *wm )
232 unsigned int load_addr = wm->module;
233 int i,characteristics_detection=1;
234 IMAGE_IMPORT_DESCRIPTOR *imports, *pe_imp;
235 DWORD size;
237 imports = RtlImageDirectoryEntryToData( wm->module, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &size );
239 /* first, count the number of imported non-internal modules */
240 pe_imp = imports;
241 if (!pe_imp) return 0;
243 /* OK, now dump the import list */
244 TRACE("Dumping imports list\n");
246 /* We assume that we have at least one import with !0 characteristics and
247 * detect broken imports with all characteristics 0 (notably Borland) and
248 * switch the detection off for them.
250 for (i = 0; pe_imp->Name ; pe_imp++) {
251 if (!i && !pe_imp->u.Characteristics)
252 characteristics_detection = 0;
253 if (characteristics_detection && !pe_imp->u.Characteristics)
254 break;
255 i++;
257 if (!i) return 0; /* no imports */
259 /* Allocate module dependency list */
260 wm->nDeps = i;
261 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
263 /* load the imported modules. They are automatically
264 * added to the modref list of the process.
267 for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
268 WINE_MODREF *wmImp;
269 IMAGE_IMPORT_BY_NAME *pe_name;
270 PIMAGE_THUNK_DATA import_list,thunk_list;
271 char *name = (char *) RVA(pe_imp->Name);
273 if (characteristics_detection && !pe_imp->u.Characteristics)
274 break;
276 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
277 if (!wmImp) {
278 ERR_(module)("Module (file) %s (which is needed by %s) not found\n", name, wm->filename);
279 return 1;
281 wm->deps[i++] = wmImp;
283 /* FIXME: forwarder entries ... */
285 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
286 TRACE("Microsoft style imports used\n");
287 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
288 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
290 while (import_list->u1.Ordinal) {
291 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
292 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
294 TRACE("--- Ordinal %s,%d\n", name, ordinal);
295 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
296 wmImp->module, (LPCSTR)ordinal, -1, TRUE
298 if (!thunk_list->u1.Function) {
299 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
300 name, ordinal, wm->filename );
301 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
303 } else { /* import by name */
304 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
305 TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
306 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
307 wmImp->module, pe_name->Name, pe_name->Hint, TRUE
309 if (!thunk_list->u1.Function) {
310 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
311 name,pe_name->Hint,pe_name->Name,wm->filename);
312 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
315 import_list++;
316 thunk_list++;
318 } else { /* Borland style */
319 TRACE("Borland style imports used\n");
320 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
321 while (thunk_list->u1.Ordinal) {
322 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
323 /* not sure about this branch, but it seems to work */
324 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
326 TRACE("--- Ordinal %s.%d\n",name,ordinal);
327 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
328 wmImp->module, (LPCSTR) ordinal, -1, TRUE
330 if (!thunk_list->u1.Function) {
331 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
332 name,ordinal, wm->filename);
333 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
335 } else {
336 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
337 TRACE("--- %s %s.%d\n",
338 pe_name->Name,name,pe_name->Hint);
339 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
340 wmImp->module, pe_name->Name, pe_name->Hint, TRUE
342 if (!thunk_list->u1.Function) {
343 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
344 name, pe_name->Hint, pe_name->Name, wm->filename);
345 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
348 thunk_list++;
352 return 0;
355 /**********************************************************************
356 * PE_LoadImage
357 * Load one PE format DLL/EXE into memory
359 * Unluckily we can't just mmap the sections where we want them, for
360 * (at least) Linux does only support offsets which are page-aligned.
362 * BUT we have to map the whole image anyway, for Win32 programs sometimes
363 * want to access them. (HMODULE points to the start of it)
365 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
367 IMAGE_NT_HEADERS *nt;
368 HMODULE hModule;
369 HANDLE mapping;
370 void *base;
372 TRACE_(module)( "loading %s\n", filename );
374 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
375 if (!mapping) return 0;
376 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
377 CloseHandle( mapping );
378 if (!base) return 0;
380 /* virus check */
382 hModule = (HMODULE)base;
383 nt = RtlImageNtHeader( hModule );
385 if (nt->OptionalHeader.AddressOfEntryPoint)
387 if (!RtlImageRvaToSection( nt, hModule, nt->OptionalHeader.AddressOfEntryPoint ))
388 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
389 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
390 nt->OptionalHeader.AddressOfEntryPoint );
393 return hModule;
396 /**********************************************************************
397 * PE_CreateModule
399 * Create WINE_MODREF structure for loaded HMODULE, link it into
400 * process modref_list, and fixup all imports.
402 * Note: hModule must point to a correctly allocated PE image,
403 * with base relocations applied; the 16-bit dummy module
404 * associated to hModule must already exist.
406 * Note: This routine must always be called in the context of the
407 * process that is to own the module to be created.
409 * Note: Assumes that the process critical section is held
411 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
412 HANDLE hFile, BOOL builtin )
414 DWORD load_addr = (DWORD)hModule; /* for RVA */
415 IMAGE_NT_HEADERS *nt;
416 IMAGE_DATA_DIRECTORY *dir;
417 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
418 WINE_MODREF *wm;
419 HMODULE16 hModule16;
421 /* Retrieve DataDirectory entries */
423 nt = RtlImageNtHeader(hModule);
424 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
425 if (dir->Size)
426 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
428 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
429 if (dir->Size) FIXME("Exception directory ignored\n" );
431 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
432 if (dir->Size) FIXME("Security directory ignored\n" );
434 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
435 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
437 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
438 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
440 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
442 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
443 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
445 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
446 if (dir->Size) TRACE("Bound Import directory ignored\n" );
448 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
449 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
451 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
452 if (dir->Size)
454 TRACE("Delayed import, stub calls LoadLibrary\n" );
456 * Nothing to do here.
459 #ifdef ImgDelayDescr
461 * This code is useful to observe what the heck is going on.
464 ImgDelayDescr *pe_delay = NULL;
465 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
466 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
467 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
468 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
469 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
470 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
471 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
472 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
473 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
475 #endif /* ImgDelayDescr */
478 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
479 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
481 dir = nt->OptionalHeader.DataDirectory+15;
482 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
484 /* Create 16-bit dummy module */
486 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
488 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
489 return NULL;
492 /* Allocate and fill WINE_MODREF */
494 if (!(wm = MODULE_AllocModRef( hModule, filename )))
496 FreeLibrary16( hModule16 );
497 return NULL;
499 wm->hDummyMod = hModule16;
501 if ( builtin )
503 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
504 pModule->flags |= NE_FFLAGS_BUILTIN;
505 wm->flags |= WINE_MODREF_INTERNAL;
507 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
508 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
510 wm->find_export = PE_FindExportedFunction;
512 /* Dump Exports */
514 if (pe_export && TRACE_ON(win32))
515 dump_exports( hModule );
517 /* Fixup Imports */
519 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
520 PE_fixup_imports( wm ))
522 /* remove entry from modref chain */
524 if ( !wm->prev )
525 MODULE_modref_list = wm->next;
526 else
527 wm->prev->next = wm->next;
529 if ( wm->next ) wm->next->prev = wm->prev;
530 wm->next = wm->prev = NULL;
532 /* FIXME: there are several more dangling references
533 * left. Including dlls loaded by this dll before the
534 * failed one. Unrolling is rather difficult with the
535 * current structure and we can leave them lying
536 * around with no problems, so we don't care.
537 * As these might reference our wm, we don't free it.
539 return NULL;
542 if (!builtin && pe_export)
543 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
545 /* Send DLL load event */
546 /* we don't need to send a dll event for the main exe */
548 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
550 if (hFile)
552 UINT drive_type = GetDriveTypeA( wm->short_filename );
553 /* don't keep the file handle open on removable media */
554 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
556 SERVER_START_REQ( load_dll )
558 req->handle = hFile;
559 req->base = (void *)hModule;
560 req->size = nt->OptionalHeader.SizeOfImage;
561 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
562 req->dbg_size = nt->FileHeader.NumberOfSymbols;
563 req->name = &wm->filename;
564 wine_server_add_data( req, wm->filename, strlen(wm->filename) );
565 wine_server_call( req );
567 SERVER_END_REQ;
570 return wm;
573 /******************************************************************************
574 * The PE Library Loader frontend.
575 * FIXME: handle the flags.
577 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
579 HMODULE hModule32;
580 WINE_MODREF *wm;
581 HANDLE hFile;
583 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
584 NULL, OPEN_EXISTING, 0, 0 );
585 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
587 /* Load PE module */
588 hModule32 = PE_LoadImage( hFile, name, flags );
589 if (!hModule32)
591 CloseHandle( hFile );
592 return NULL;
595 /* Create 32-bit MODREF */
596 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
598 ERR( "can't load %s\n", name );
599 CloseHandle( hFile );
600 SetLastError( ERROR_OUTOFMEMORY );
601 return NULL;
604 CloseHandle( hFile );
605 return wm;
609 /* Called if the library is loaded or freed.
610 * NOTE: if a thread attaches a DLL, the current thread will only do
611 * DLL_PROCESS_ATTACH. Only newly created threads do DLL_THREAD_ATTACH
612 * (SDK)
614 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
616 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
618 BOOL retv = TRUE;
619 IMAGE_NT_HEADERS *nt = RtlImageNtHeader(module);
621 /* Is this a library? And has it got an entrypoint? */
622 if (nt && (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
623 (nt->OptionalHeader.AddressOfEntryPoint))
625 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
626 if (TRACE_ON(relay))
627 DPRINTF("%08lx:Call PE DLL (proc=%p,module=%08x,type=%ld,res=%p)\n",
628 GetCurrentThreadId(), entry, module, type, lpReserved );
629 retv = entry( module, type, lpReserved );
630 if (TRACE_ON(relay))
631 DPRINTF("%08lx:Ret PE DLL (proc=%p,module=%08x,type=%ld,res=%p) retval=%x\n",
632 GetCurrentThreadId(), entry, module, type, lpReserved, retv );
635 return retv;
638 /************************************************************************
639 * PE_InitTls (internal)
641 * If included, initialises the thread local storages of modules.
642 * Pointers in those structs are not RVAs but real pointers which have been
643 * relocated by do_relocations() already.
645 static LPVOID
646 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
647 if ( ((DWORD)addr>opt->ImageBase) &&
648 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
650 /* the address has not been relocated! */
651 return (LPVOID)(((DWORD)addr)+delta);
652 else
653 /* the address has been relocated already */
654 return addr;
656 void PE_InitTls( void )
658 WINE_MODREF *wm;
659 IMAGE_NT_HEADERS *peh;
660 DWORD size,datasize,dirsize;
661 LPVOID mem;
662 PIMAGE_TLS_DIRECTORY pdir;
663 int delta;
665 for (wm = MODULE_modref_list;wm;wm=wm->next) {
666 peh = RtlImageNtHeader(wm->module);
667 pdir = RtlImageDirectoryEntryToData( wm->module, TRUE,
668 IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
669 if (!pdir) continue;
670 delta = (char *)wm->module - (char *)peh->OptionalHeader.ImageBase;
672 if ( wm->tlsindex == -1 ) {
673 LPDWORD xaddr;
674 wm->tlsindex = TlsAlloc();
675 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
676 pdir->AddressOfIndex
678 *xaddr=wm->tlsindex;
680 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
681 size = datasize + pdir->SizeOfZeroFill;
682 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
683 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
684 if (pdir->AddressOfCallBacks) {
685 PIMAGE_TLS_CALLBACK *cbs;
687 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
688 if (*cbs)
689 FIXME("TLS Callbacks aren't going to be called\n");
692 TlsSetValue( wm->tlsindex, mem );