Some more RPC definitions.
[wine.git] / loader / pe_image.c
blob84a999c214ebe1224d952e159fb0c20a821a6a5d
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 * PE_LoadImage
383 * Load one PE format DLL/EXE into memory
385 * Unluckily we can't just mmap the sections where we want them, for
386 * (at least) Linux does only support offsets which are page-aligned.
388 * BUT we have to map the whole image anyway, for Win32 programs sometimes
389 * want to access them. (HMODULE points to the start of it)
391 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
393 IMAGE_NT_HEADERS *nt;
394 HMODULE hModule;
395 HANDLE mapping;
396 void *base;
398 TRACE_(module)( "loading %s\n", filename );
400 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
401 if (!mapping) return 0;
402 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
403 CloseHandle( mapping );
404 if (!base) return 0;
406 /* virus check */
408 hModule = (HMODULE)base;
409 nt = PE_HEADER( hModule );
411 if (nt->OptionalHeader.AddressOfEntryPoint)
413 int i;
414 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
415 nt->FileHeader.SizeOfOptionalHeader);
416 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
418 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
419 continue;
420 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
421 break;
423 if (i == nt->FileHeader.NumberOfSections)
424 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
425 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
426 nt->OptionalHeader.AddressOfEntryPoint );
429 return hModule;
432 /**********************************************************************
433 * PE_CreateModule
435 * Create WINE_MODREF structure for loaded HMODULE, link it into
436 * process modref_list, and fixup all imports.
438 * Note: hModule must point to a correctly allocated PE image,
439 * with base relocations applied; the 16-bit dummy module
440 * associated to hModule must already exist.
442 * Note: This routine must always be called in the context of the
443 * process that is to own the module to be created.
445 * Note: Assumes that the process critical section is held
447 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
448 HANDLE hFile, BOOL builtin )
450 DWORD load_addr = (DWORD)hModule; /* for RVA */
451 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
452 IMAGE_DATA_DIRECTORY *dir;
453 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
454 WINE_MODREF *wm;
455 HMODULE16 hModule16;
457 /* Retrieve DataDirectory entries */
459 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
460 if (dir->Size)
461 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
463 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
464 if (dir->Size) FIXME("Exception directory ignored\n" );
466 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
467 if (dir->Size) FIXME("Security directory ignored\n" );
469 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
470 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
472 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
473 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
475 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
477 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
478 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
480 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
481 if (dir->Size) TRACE("Bound Import directory ignored\n" );
483 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
484 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
486 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
487 if (dir->Size)
489 TRACE("Delayed import, stub calls LoadLibrary\n" );
491 * Nothing to do here.
494 #ifdef ImgDelayDescr
496 * This code is useful to observe what the heck is going on.
499 ImgDelayDescr *pe_delay = NULL;
500 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
501 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
502 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
503 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
504 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
505 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
506 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
507 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
508 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
510 #endif /* ImgDelayDescr */
513 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
514 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
516 dir = nt->OptionalHeader.DataDirectory+15;
517 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
519 /* Create 16-bit dummy module */
521 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
523 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
524 return NULL;
527 /* Allocate and fill WINE_MODREF */
529 if (!(wm = MODULE_AllocModRef( hModule, filename )))
531 FreeLibrary16( hModule16 );
532 return NULL;
534 wm->hDummyMod = hModule16;
536 if ( builtin )
538 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
539 pModule->flags |= NE_FFLAGS_BUILTIN;
540 wm->flags |= WINE_MODREF_INTERNAL;
542 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
543 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
545 wm->find_export = PE_FindExportedFunction;
547 /* Dump Exports */
549 if (pe_export && TRACE_ON(win32))
550 dump_exports( hModule );
552 /* Fixup Imports */
554 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
555 PE_fixup_imports( wm ))
557 /* remove entry from modref chain */
559 if ( !wm->prev )
560 MODULE_modref_list = wm->next;
561 else
562 wm->prev->next = wm->next;
564 if ( wm->next ) wm->next->prev = wm->prev;
565 wm->next = wm->prev = NULL;
567 /* FIXME: there are several more dangling references
568 * left. Including dlls loaded by this dll before the
569 * failed one. Unrolling is rather difficult with the
570 * current structure and we can leave them lying
571 * around with no problems, so we don't care.
572 * As these might reference our wm, we don't free it.
574 return NULL;
577 if (!builtin && pe_export)
578 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
580 /* Send DLL load event */
581 /* we don't need to send a dll event for the main exe */
583 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
585 if (hFile)
587 UINT drive_type = GetDriveTypeA( wm->short_filename );
588 /* don't keep the file handle open on removable media */
589 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
591 SERVER_START_REQ( load_dll )
593 req->handle = hFile;
594 req->base = (void *)hModule;
595 req->size = nt->OptionalHeader.SizeOfImage;
596 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
597 req->dbg_size = nt->FileHeader.NumberOfSymbols;
598 req->name = &wm->filename;
599 wine_server_add_data( req, wm->filename, strlen(wm->filename) );
600 wine_server_call( req );
602 SERVER_END_REQ;
605 return wm;
608 /******************************************************************************
609 * The PE Library Loader frontend.
610 * FIXME: handle the flags.
612 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
614 HMODULE hModule32;
615 WINE_MODREF *wm;
616 HANDLE hFile;
618 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
619 NULL, OPEN_EXISTING, 0, 0 );
620 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
622 /* Load PE module */
623 hModule32 = PE_LoadImage( hFile, name, flags );
624 if (!hModule32)
626 CloseHandle( hFile );
627 return NULL;
630 /* Create 32-bit MODREF */
631 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
633 ERR( "can't load %s\n", name );
634 CloseHandle( hFile );
635 SetLastError( ERROR_OUTOFMEMORY );
636 return NULL;
639 CloseHandle( hFile );
640 return wm;
644 /* Called if the library is loaded or freed.
645 * NOTE: if a thread attaches a DLL, the current thread will only do
646 * DLL_PROCESS_ATTACH. Only newly created threads do DLL_THREAD_ATTACH
647 * (SDK)
649 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
651 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
653 BOOL retv = TRUE;
654 IMAGE_NT_HEADERS *nt = PE_HEADER(module);
656 /* Is this a library? And has it got an entrypoint? */
657 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
658 (nt->OptionalHeader.AddressOfEntryPoint))
660 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
661 if (TRACE_ON(relay))
662 DPRINTF("%08lx:Call PE DLL (proc=%p,module=%08x,type=%ld,res=%p)\n",
663 GetCurrentThreadId(), entry, module, type, lpReserved );
664 retv = entry( module, type, lpReserved );
665 if (TRACE_ON(relay))
666 DPRINTF("%08lx:Ret PE DLL (proc=%p,module=%08x,type=%ld,res=%p) retval=%x\n",
667 GetCurrentThreadId(), entry, module, type, lpReserved, retv );
670 return retv;
673 /************************************************************************
674 * PE_InitTls (internal)
676 * If included, initialises the thread local storages of modules.
677 * Pointers in those structs are not RVAs but real pointers which have been
678 * relocated by do_relocations() already.
680 static LPVOID
681 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
682 if ( ((DWORD)addr>opt->ImageBase) &&
683 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
685 /* the address has not been relocated! */
686 return (LPVOID)(((DWORD)addr)+delta);
687 else
688 /* the address has been relocated already */
689 return addr;
691 void PE_InitTls( void )
693 WINE_MODREF *wm;
694 IMAGE_NT_HEADERS *peh;
695 DWORD size,datasize;
696 LPVOID mem;
697 PIMAGE_TLS_DIRECTORY pdir;
698 int delta;
700 for (wm = MODULE_modref_list;wm;wm=wm->next) {
701 peh = PE_HEADER(wm->module);
702 delta = wm->module - peh->OptionalHeader.ImageBase;
703 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
704 continue;
705 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
706 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
709 if ( wm->tlsindex == -1 ) {
710 LPDWORD xaddr;
711 wm->tlsindex = TlsAlloc();
712 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
713 pdir->AddressOfIndex
715 *xaddr=wm->tlsindex;
717 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
718 size = datasize + pdir->SizeOfZeroFill;
719 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
720 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
721 if (pdir->AddressOfCallBacks) {
722 PIMAGE_TLS_CALLBACK *cbs;
724 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
725 if (*cbs)
726 FIXME("TLS Callbacks aren't going to be called\n");
729 TlsSetValue( wm->tlsindex, mem );