ExtTextOutW: if GetFontLanguageInfo says that the font may require
[wine/wine64.git] / loader / pe_image.c
blob974c6a11387b99ba601d0abaa890c7effd938505
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 BOOL snoop )
139 WORD * ordinals;
140 DWORD * function;
141 BYTE ** name, *ename = NULL;
142 int i, ordinal;
143 unsigned int load_addr = wm->module;
144 DWORD rva_start, rva_end, addr;
145 char * forward;
146 IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
148 if (HIWORD(funcName))
149 TRACE("(%s)\n",funcName);
150 else
151 TRACE("(%d)\n",(int)funcName);
152 if (!exports) {
153 /* Not a fatal problem, some apps do
154 * GetProcAddress(0,"RegisterPenApp") which triggers this
155 * case.
157 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
158 return NULL;
160 ordinals= RVA(exports->AddressOfNameOrdinals);
161 function= RVA(exports->AddressOfFunctions);
162 name = RVA(exports->AddressOfNames);
163 forward = NULL;
164 rva_start = PE_HEADER(wm->module)->OptionalHeader
165 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
166 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
167 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
169 if (HIWORD(funcName))
171 /* first try a binary search */
172 int min = 0, max = exports->NumberOfNames - 1;
173 while (min <= max)
175 int res, pos = (min + max) / 2;
176 ename = RVA(name[pos]);
177 if (!(res = strcmp( ename, funcName )))
179 ordinal = ordinals[pos];
180 goto found;
182 if (res > 0) max = pos - 1;
183 else min = pos + 1;
185 /* now try a linear search in case the names aren't sorted properly */
186 for (i = 0; i < exports->NumberOfNames; i++)
188 ename = RVA(name[i]);
189 if (!strcmp( ename, funcName ))
191 ERR( "%s.%s required a linear search\n", wm->modname, funcName );
192 ordinal = ordinals[i];
193 goto found;
196 return NULL;
198 else /* find by ordinal */
200 ordinal = LOWORD(funcName) - exports->Base;
201 if (snoop && name) /* need to find a name for it */
203 for (i = 0; i < exports->NumberOfNames; i++)
204 if (ordinals[i] == ordinal)
206 ename = RVA(name[i]);
207 break;
212 found:
213 if (ordinal >= exports->NumberOfFunctions)
215 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
216 return NULL;
218 addr = function[ordinal];
219 if (!addr) return NULL;
220 if ((addr < rva_start) || (addr >= rva_end))
222 FARPROC proc = RVA(addr);
223 if (snoop)
225 if (!ename) ename = "@";
226 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
228 return proc;
230 else /* forward entry point */
232 WINE_MODREF *wm_fw;
233 FARPROC proc;
234 char *forward = RVA(addr);
235 char module[256];
236 char *end = strchr(forward, '.');
238 if (!end) return NULL;
239 if (end - forward >= sizeof(module)) return NULL;
240 memcpy( module, forward, end - forward );
241 module[end-forward] = 0;
242 if (!(wm_fw = MODULE_FindModule( module )))
244 ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
245 return NULL;
247 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, snoop )))
248 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 );
249 return proc;
253 /****************************************************************
254 * PE_fixup_imports
256 DWORD PE_fixup_imports( WINE_MODREF *wm )
258 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
259 unsigned int load_addr = wm->module;
260 int i,characteristics_detection=1;
261 IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
263 /* first, count the number of imported non-internal modules */
264 pe_imp = imports;
265 if (!pe_imp) return 0;
267 /* OK, now dump the import list */
268 TRACE("Dumping imports list\n");
270 /* We assume that we have at least one import with !0 characteristics and
271 * detect broken imports with all characteristics 0 (notably Borland) and
272 * switch the detection off for them.
274 for (i = 0; pe_imp->Name ; pe_imp++) {
275 if (!i && !pe_imp->u.Characteristics)
276 characteristics_detection = 0;
277 if (characteristics_detection && !pe_imp->u.Characteristics)
278 break;
279 i++;
281 if (!i) return 0; /* no imports */
283 /* Allocate module dependency list */
284 wm->nDeps = i;
285 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
287 /* load the imported modules. They are automatically
288 * added to the modref list of the process.
291 for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
292 WINE_MODREF *wmImp;
293 IMAGE_IMPORT_BY_NAME *pe_name;
294 PIMAGE_THUNK_DATA import_list,thunk_list;
295 char *name = (char *) RVA(pe_imp->Name);
297 if (characteristics_detection && !pe_imp->u.Characteristics)
298 break;
300 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
301 if (!wmImp) {
302 ERR_(module)("Module (file) %s (which is needed by %s) not found\n", name, wm->filename);
303 return 1;
305 wm->deps[i++] = wmImp;
307 /* FIXME: forwarder entries ... */
309 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
310 TRACE("Microsoft style imports used\n");
311 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
312 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
314 while (import_list->u1.Ordinal) {
315 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
316 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
318 TRACE("--- Ordinal %s,%d\n", name, ordinal);
319 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
320 wmImp->module, (LPCSTR)ordinal, TRUE
322 if (!thunk_list->u1.Function) {
323 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
324 name, ordinal, wm->filename );
325 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
327 } else { /* import by name */
328 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
329 TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
330 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
331 wmImp->module, pe_name->Name, TRUE
333 if (!thunk_list->u1.Function) {
334 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
335 name,pe_name->Hint,pe_name->Name,wm->filename);
336 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
339 import_list++;
340 thunk_list++;
342 } else { /* Borland style */
343 TRACE("Borland style imports used\n");
344 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
345 while (thunk_list->u1.Ordinal) {
346 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
347 /* not sure about this branch, but it seems to work */
348 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
350 TRACE("--- Ordinal %s.%d\n",name,ordinal);
351 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
352 wmImp->module, (LPCSTR) ordinal, TRUE
354 if (!thunk_list->u1.Function) {
355 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
356 name,ordinal, wm->filename);
357 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
359 } else {
360 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
361 TRACE("--- %s %s.%d\n",
362 pe_name->Name,name,pe_name->Hint);
363 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
364 wmImp->module, pe_name->Name, TRUE
366 if (!thunk_list->u1.Function) {
367 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
368 name, pe_name->Hint, pe_name->Name, wm->filename);
369 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
372 thunk_list++;
376 return 0;
379 /***********************************************************************
380 * do_relocations
382 * Apply the relocations to a mapped PE image
384 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
386 const IMAGE_DATA_DIRECTORY *dir;
387 const IMAGE_BASE_RELOCATION *rel;
388 int delta = base - (char *)nt->OptionalHeader.ImageBase;
390 dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
391 rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
393 WARN("Info: base relocations needed for %s\n", filename);
394 if (!dir->VirtualAddress || !dir->Size)
396 if (nt->OptionalHeader.ImageBase == 0x400000)
397 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
398 ERR( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
399 filename,
400 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
401 "stripped during link" : "unknown reason" );
402 return 0;
405 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
406 * really make sure that the *new* base address is also > 2GB.
407 * Some DLLs really check the MSB of the module handle :-/
409 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
410 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
412 for ( ; ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
413 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock))
415 char *page = base + rel->VirtualAddress;
416 WORD *TypeOffset = (WORD *)(rel + 1);
417 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
419 if (!count) continue;
421 /* sanity checks */
422 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
423 page > base + nt->OptionalHeader.SizeOfImage)
425 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
426 rel, rel->VirtualAddress, rel->SizeOfBlock,
427 base, dir->VirtualAddress, dir->Size );
428 return 0;
431 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
433 /* patching in reverse order */
434 for (i = 0 ; i < count; i++)
436 int offset = TypeOffset[i] & 0xFFF;
437 int type = TypeOffset[i] >> 12;
438 switch(type)
440 case IMAGE_REL_BASED_ABSOLUTE:
441 break;
442 case IMAGE_REL_BASED_HIGH:
443 *(short*)(page+offset) += HIWORD(delta);
444 break;
445 case IMAGE_REL_BASED_LOW:
446 *(short*)(page+offset) += LOWORD(delta);
447 break;
448 case IMAGE_REL_BASED_HIGHLOW:
449 *(int*)(page+offset) += delta;
450 /* FIXME: if this is an exported address, fire up enhanced logic */
451 break;
452 default:
453 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
454 break;
458 return 1;
462 /**********************************************************************
463 * PE_LoadImage
464 * Load one PE format DLL/EXE into memory
466 * Unluckily we can't just mmap the sections where we want them, for
467 * (at least) Linux does only support offsets which are page-aligned.
469 * BUT we have to map the whole image anyway, for Win32 programs sometimes
470 * want to access them. (HMODULE points to the start of it)
472 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
474 IMAGE_NT_HEADERS *nt;
475 HMODULE hModule;
476 HANDLE mapping;
477 void *base;
479 TRACE_(module)( "loading %s\n", filename );
481 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
482 if (!mapping) return 0;
483 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
484 CloseHandle( mapping );
485 if (!base) return 0;
487 hModule = (HMODULE)base;
489 /* perform base relocation, if necessary */
491 nt = PE_HEADER( hModule );
492 if (hModule != nt->OptionalHeader.ImageBase)
494 if (!do_relocations( base, nt, filename ))
496 UnmapViewOfFile( base );
497 SetLastError( ERROR_BAD_EXE_FORMAT );
498 return 0;
502 /* virus check */
504 if (nt->OptionalHeader.AddressOfEntryPoint)
506 int i;
507 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
508 nt->FileHeader.SizeOfOptionalHeader);
509 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
511 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
512 continue;
513 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
514 break;
516 if (i == nt->FileHeader.NumberOfSections)
517 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
518 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
519 nt->OptionalHeader.AddressOfEntryPoint );
522 return hModule;
525 /**********************************************************************
526 * PE_CreateModule
528 * Create WINE_MODREF structure for loaded HMODULE, link it into
529 * process modref_list, and fixup all imports.
531 * Note: hModule must point to a correctly allocated PE image,
532 * with base relocations applied; the 16-bit dummy module
533 * associated to hModule must already exist.
535 * Note: This routine must always be called in the context of the
536 * process that is to own the module to be created.
538 * Note: Assumes that the process critical section is held
540 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
541 HANDLE hFile, BOOL builtin )
543 DWORD load_addr = (DWORD)hModule; /* for RVA */
544 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
545 IMAGE_DATA_DIRECTORY *dir;
546 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
547 WINE_MODREF *wm;
548 HMODULE16 hModule16;
550 /* Retrieve DataDirectory entries */
552 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
553 if (dir->Size)
554 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
556 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
557 if (dir->Size) FIXME("Exception directory ignored\n" );
559 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
560 if (dir->Size) FIXME("Security directory ignored\n" );
562 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
563 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
565 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
566 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
568 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
570 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
571 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
573 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
574 if (dir->Size) TRACE("Bound Import directory ignored\n" );
576 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
577 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
579 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
580 if (dir->Size)
582 TRACE("Delayed import, stub calls LoadLibrary\n" );
584 * Nothing to do here.
587 #ifdef ImgDelayDescr
589 * This code is useful to observe what the heck is going on.
592 ImgDelayDescr *pe_delay = NULL;
593 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
594 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
595 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
596 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
597 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
598 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
599 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
600 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
601 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
603 #endif /* ImgDelayDescr */
606 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
607 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
609 dir = nt->OptionalHeader.DataDirectory+15;
610 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
612 /* Create 16-bit dummy module */
614 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
616 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
617 return NULL;
620 /* Allocate and fill WINE_MODREF */
622 if (!(wm = MODULE_AllocModRef( hModule, filename )))
624 FreeLibrary16( hModule16 );
625 return NULL;
627 wm->hDummyMod = hModule16;
629 if ( builtin )
631 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
632 pModule->flags |= NE_FFLAGS_BUILTIN;
633 wm->flags |= WINE_MODREF_INTERNAL;
635 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
636 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
638 wm->find_export = PE_FindExportedFunction;
640 /* Dump Exports */
642 if (pe_export && TRACE_ON(win32))
643 dump_exports( hModule );
645 /* Fixup Imports */
647 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
648 PE_fixup_imports( wm ))
650 /* remove entry from modref chain */
652 if ( !wm->prev )
653 MODULE_modref_list = wm->next;
654 else
655 wm->prev->next = wm->next;
657 if ( wm->next ) wm->next->prev = wm->prev;
658 wm->next = wm->prev = NULL;
660 /* FIXME: there are several more dangling references
661 * left. Including dlls loaded by this dll before the
662 * failed one. Unrolling is rather difficult with the
663 * current structure and we can leave them lying
664 * around with no problems, so we don't care.
665 * As these might reference our wm, we don't free it.
667 return NULL;
670 if (!builtin && pe_export)
671 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
673 /* Send DLL load event */
674 /* we don't need to send a dll event for the main exe */
676 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
678 if (hFile)
680 UINT drive_type = GetDriveTypeA( wm->short_filename );
681 /* don't keep the file handle open on removable media */
682 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
684 SERVER_START_REQ( load_dll )
686 req->handle = hFile;
687 req->base = (void *)hModule;
688 req->size = nt->OptionalHeader.SizeOfImage;
689 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
690 req->dbg_size = nt->FileHeader.NumberOfSymbols;
691 req->name = &wm->filename;
692 wine_server_add_data( req, wm->filename, strlen(wm->filename) );
693 wine_server_call( req );
695 SERVER_END_REQ;
698 return wm;
701 /******************************************************************************
702 * The PE Library Loader frontend.
703 * FIXME: handle the flags.
705 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
707 HMODULE hModule32;
708 WINE_MODREF *wm;
709 HANDLE hFile;
711 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
712 NULL, OPEN_EXISTING, 0, 0 );
713 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
715 /* Load PE module */
716 hModule32 = PE_LoadImage( hFile, name, flags );
717 if (!hModule32)
719 CloseHandle( hFile );
720 return NULL;
723 /* Create 32-bit MODREF */
724 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
726 ERR( "can't load %s\n", name );
727 CloseHandle( hFile );
728 SetLastError( ERROR_OUTOFMEMORY );
729 return NULL;
732 CloseHandle( hFile );
733 return wm;
737 /* Called if the library is loaded or freed.
738 * NOTE: if a thread attaches a DLL, the current thread will only do
739 * DLL_PROCESS_ATTACH. Only newly created threads do DLL_THREAD_ATTACH
740 * (SDK)
742 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
744 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
746 BOOL retv = TRUE;
747 IMAGE_NT_HEADERS *nt = PE_HEADER(module);
749 /* Is this a library? And has it got an entrypoint? */
750 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
751 (nt->OptionalHeader.AddressOfEntryPoint))
753 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
754 if (TRACE_ON(relay))
755 DPRINTF("%08lx:Call PE DLL (proc=%p,module=%08x,type=%ld,res=%p)\n",
756 GetCurrentThreadId(), entry, module, type, lpReserved );
757 retv = entry( module, type, lpReserved );
758 if (TRACE_ON(relay))
759 DPRINTF("%08lx:Ret PE DLL (proc=%p,module=%08x,type=%ld,res=%p) retval=%x\n",
760 GetCurrentThreadId(), entry, module, type, lpReserved, retv );
763 return retv;
766 /************************************************************************
767 * PE_InitTls (internal)
769 * If included, initialises the thread local storages of modules.
770 * Pointers in those structs are not RVAs but real pointers which have been
771 * relocated by do_relocations() already.
773 static LPVOID
774 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
775 if ( ((DWORD)addr>opt->ImageBase) &&
776 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
778 /* the address has not been relocated! */
779 return (LPVOID)(((DWORD)addr)+delta);
780 else
781 /* the address has been relocated already */
782 return addr;
784 void PE_InitTls( void )
786 WINE_MODREF *wm;
787 IMAGE_NT_HEADERS *peh;
788 DWORD size,datasize;
789 LPVOID mem;
790 PIMAGE_TLS_DIRECTORY pdir;
791 int delta;
793 for (wm = MODULE_modref_list;wm;wm=wm->next) {
794 peh = PE_HEADER(wm->module);
795 delta = wm->module - peh->OptionalHeader.ImageBase;
796 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
797 continue;
798 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
799 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
802 if ( wm->tlsindex == -1 ) {
803 LPDWORD xaddr;
804 wm->tlsindex = TlsAlloc();
805 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
806 pdir->AddressOfIndex
808 *xaddr=wm->tlsindex;
810 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
811 size = datasize + pdir->SizeOfZeroFill;
812 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
813 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
814 if (pdir->AddressOfCallBacks) {
815 PIMAGE_TLS_CALLBACK *cbs;
817 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
818 if (*cbs)
819 FIXME("TLS Callbacks aren't going to be called\n");
822 TlsSetValue( wm->tlsindex, mem );