Store print dlg structure in a property instead of DWL_USER.
[wine/multimedia.git] / loader / pe_image.c
blob35a1ab115745f69ec27c4bc8fd8d72a08a0584b8
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 TRACE("*******EXPORT DATA*******\n");
101 TRACE("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 TRACE(" Ord RVA Addr Name\n" );
109 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
111 if (!*function) continue; /* No such function */
112 if (TRACE_ON(win32))
114 DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
115 /* Check if we have a name for it */
116 for (j = 0; j < pe_exports->NumberOfNames; j++)
117 if (ordinal[j] == i)
119 DPRINTF( " %s", (char*)RVA(name[j]) );
120 break;
122 if ((*function >= rva_start) && (*function <= rva_end))
123 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
124 DPRINTF("\n");
129 /* Look up the specified function or ordinal in the export list:
130 * If it is a string:
131 * - look up the name in the name list.
132 * - look up the ordinal with that index.
133 * - use the ordinal as offset into the functionlist
134 * If it is an ordinal:
135 * - use ordinal-pe_export->Base as offset into the function list
137 static FARPROC PE_FindExportedFunction(
138 WINE_MODREF *wm, /* [in] WINE modreference */
139 LPCSTR funcName, /* [in] function name */
140 BOOL snoop )
142 WORD * ordinals;
143 DWORD * function;
144 BYTE ** name, *ename = NULL;
145 int i, ordinal;
146 unsigned int load_addr = wm->module;
147 DWORD rva_start, rva_end, addr;
148 char * forward;
149 IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
151 if (HIWORD(funcName))
152 TRACE("(%s)\n",funcName);
153 else
154 TRACE("(%d)\n",(int)funcName);
155 if (!exports) {
156 /* Not a fatal problem, some apps do
157 * GetProcAddress(0,"RegisterPenApp") which triggers this
158 * case.
160 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
161 return NULL;
163 ordinals= RVA(exports->AddressOfNameOrdinals);
164 function= RVA(exports->AddressOfFunctions);
165 name = RVA(exports->AddressOfNames);
166 forward = NULL;
167 rva_start = PE_HEADER(wm->module)->OptionalHeader
168 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
169 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
170 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
172 if (HIWORD(funcName))
174 /* first try a binary search */
175 int min = 0, max = exports->NumberOfNames - 1;
176 while (min <= max)
178 int res, pos = (min + max) / 2;
179 ename = RVA(name[pos]);
180 if (!(res = strcmp( ename, funcName )))
182 ordinal = ordinals[pos];
183 goto found;
185 if (res > 0) max = pos - 1;
186 else min = pos + 1;
188 /* now try a linear search in case the names aren't sorted properly */
189 for (i = 0; i < exports->NumberOfNames; i++)
191 ename = RVA(name[i]);
192 if (!strcmp( ename, funcName ))
194 ERR( "%s.%s required a linear search\n", wm->modname, funcName );
195 ordinal = ordinals[i];
196 goto found;
199 return NULL;
201 else /* find by ordinal */
203 ordinal = LOWORD(funcName) - exports->Base;
204 if (snoop && name) /* need to find a name for it */
206 for (i = 0; i < exports->NumberOfNames; i++)
207 if (ordinals[i] == ordinal)
209 ename = RVA(name[i]);
210 break;
215 found:
216 if (ordinal >= exports->NumberOfFunctions)
218 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
219 return NULL;
221 addr = function[ordinal];
222 if (!addr) return NULL;
223 if ((addr < rva_start) || (addr >= rva_end))
225 FARPROC proc = RVA(addr);
226 if (snoop)
228 if (!ename) ename = "@";
229 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
231 return proc;
233 else /* forward entry point */
235 WINE_MODREF *wm_fw;
236 FARPROC proc;
237 char *forward = RVA(addr);
238 char module[256];
239 char *end = strchr(forward, '.');
241 if (!end) return NULL;
242 if (end - forward >= sizeof(module)) return NULL;
243 memcpy( module, forward, end - forward );
244 module[end-forward] = 0;
245 if (!(wm_fw = MODULE_FindModule( module )))
247 ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
248 return NULL;
250 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, snoop )))
251 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 );
252 return proc;
256 /****************************************************************
257 * PE_fixup_imports
259 DWORD PE_fixup_imports( WINE_MODREF *wm )
261 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
262 unsigned int load_addr = wm->module;
263 int i,characteristics_detection=1;
264 IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
266 /* first, count the number of imported non-internal modules */
267 pe_imp = imports;
268 if (!pe_imp) return 0;
270 /* OK, now dump the import list */
271 TRACE("Dumping imports list\n");
273 /* We assume that we have at least one import with !0 characteristics and
274 * detect broken imports with all characteristics 0 (notably Borland) and
275 * switch the detection off for them.
277 for (i = 0; pe_imp->Name ; pe_imp++) {
278 if (!i && !pe_imp->u.Characteristics)
279 characteristics_detection = 0;
280 if (characteristics_detection && !pe_imp->u.Characteristics)
281 break;
282 i++;
284 if (!i) return 0; /* no imports */
286 /* Allocate module dependency list */
287 wm->nDeps = i;
288 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
290 /* load the imported modules. They are automatically
291 * added to the modref list of the process.
294 for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
295 WINE_MODREF *wmImp;
296 IMAGE_IMPORT_BY_NAME *pe_name;
297 PIMAGE_THUNK_DATA import_list,thunk_list;
298 char *name = (char *) RVA(pe_imp->Name);
300 if (characteristics_detection && !pe_imp->u.Characteristics)
301 break;
303 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
304 if (!wmImp) {
305 ERR_(module)("Module (file) %s (which is needed by %s) not found\n", name, wm->filename);
306 return 1;
308 wm->deps[i++] = wmImp;
310 /* FIXME: forwarder entries ... */
312 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
313 TRACE("Microsoft style imports used\n");
314 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
315 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
317 while (import_list->u1.Ordinal) {
318 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
319 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
321 TRACE("--- Ordinal %s,%d\n", name, ordinal);
322 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
323 wmImp->module, (LPCSTR)ordinal, TRUE
325 if (!thunk_list->u1.Function) {
326 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
327 name, ordinal, wm->filename );
328 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
330 } else { /* import by name */
331 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
332 TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
333 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
334 wmImp->module, pe_name->Name, TRUE
336 if (!thunk_list->u1.Function) {
337 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
338 name,pe_name->Hint,pe_name->Name,wm->filename);
339 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
342 import_list++;
343 thunk_list++;
345 } else { /* Borland style */
346 TRACE("Borland style imports used\n");
347 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
348 while (thunk_list->u1.Ordinal) {
349 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
350 /* not sure about this branch, but it seems to work */
351 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
353 TRACE("--- Ordinal %s.%d\n",name,ordinal);
354 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
355 wmImp->module, (LPCSTR) ordinal, TRUE
357 if (!thunk_list->u1.Function) {
358 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
359 name,ordinal, wm->filename);
360 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
362 } else {
363 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
364 TRACE("--- %s %s.%d\n",
365 pe_name->Name,name,pe_name->Hint);
366 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
367 wmImp->module, pe_name->Name, TRUE
369 if (!thunk_list->u1.Function) {
370 ERR("No implementation for %s.%d(%s) imported from %s, setting to 0xdeadbeef\n",
371 name, pe_name->Hint, pe_name->Name, wm->filename);
372 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
375 thunk_list++;
379 return 0;
382 /***********************************************************************
383 * do_relocations
385 * Apply the relocations to a mapped PE image
387 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
389 const IMAGE_DATA_DIRECTORY *dir;
390 const IMAGE_BASE_RELOCATION *rel;
391 int delta = base - (char *)nt->OptionalHeader.ImageBase;
393 dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
394 rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
396 WARN("Info: base relocations needed for %s\n", filename);
397 if (!dir->VirtualAddress || !dir->Size)
399 if (nt->OptionalHeader.ImageBase == 0x400000)
400 ERR("Standard load address for a Win32 program (0x00400000) not available - security-patched kernel ?\n");
401 ERR( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
402 filename,
403 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
404 "stripped during link" : "unknown reason" );
405 return 0;
408 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
409 * really make sure that the *new* base address is also > 2GB.
410 * Some DLLs really check the MSB of the module handle :-/
412 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
413 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
415 for ( ; ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->SizeOfBlock;
416 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock))
418 char *page = base + rel->VirtualAddress;
419 WORD *TypeOffset = (WORD *)(rel + 1);
420 int i, count = (rel->SizeOfBlock - sizeof(*rel)) / sizeof(*TypeOffset);
422 if (!count) continue;
424 /* sanity checks */
425 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
426 page > base + nt->OptionalHeader.SizeOfImage)
428 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
429 rel, rel->VirtualAddress, rel->SizeOfBlock,
430 base, dir->VirtualAddress, dir->Size );
431 return 0;
434 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
436 /* patching in reverse order */
437 for (i = 0 ; i < count; i++)
439 int offset = TypeOffset[i] & 0xFFF;
440 int type = TypeOffset[i] >> 12;
441 switch(type)
443 case IMAGE_REL_BASED_ABSOLUTE:
444 break;
445 case IMAGE_REL_BASED_HIGH:
446 *(short*)(page+offset) += HIWORD(delta);
447 break;
448 case IMAGE_REL_BASED_LOW:
449 *(short*)(page+offset) += LOWORD(delta);
450 break;
451 case IMAGE_REL_BASED_HIGHLOW:
452 *(int*)(page+offset) += delta;
453 /* FIXME: if this is an exported address, fire up enhanced logic */
454 break;
455 default:
456 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
457 break;
461 return 1;
465 /**********************************************************************
466 * PE_LoadImage
467 * Load one PE format DLL/EXE into memory
469 * Unluckily we can't just mmap the sections where we want them, for
470 * (at least) Linux does only support offsets which are page-aligned.
472 * BUT we have to map the whole image anyway, for Win32 programs sometimes
473 * want to access them. (HMODULE points to the start of it)
475 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
477 IMAGE_NT_HEADERS *nt;
478 HMODULE hModule;
479 HANDLE mapping;
480 void *base;
482 TRACE_(module)( "loading %s\n", filename );
484 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
485 if (!mapping) return 0;
486 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
487 CloseHandle( mapping );
488 if (!base) return 0;
490 hModule = (HMODULE)base;
492 /* perform base relocation, if necessary */
494 nt = PE_HEADER( hModule );
495 if (hModule != nt->OptionalHeader.ImageBase)
497 if (!do_relocations( base, nt, filename ))
499 UnmapViewOfFile( base );
500 SetLastError( ERROR_BAD_EXE_FORMAT );
501 return 0;
505 /* virus check */
507 if (nt->OptionalHeader.AddressOfEntryPoint)
509 int i;
510 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
511 nt->FileHeader.SizeOfOptionalHeader);
512 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
514 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
515 continue;
516 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
517 break;
519 if (i == nt->FileHeader.NumberOfSections)
520 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
521 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
522 nt->OptionalHeader.AddressOfEntryPoint );
525 return hModule;
528 /**********************************************************************
529 * PE_CreateModule
531 * Create WINE_MODREF structure for loaded HMODULE, link it into
532 * process modref_list, and fixup all imports.
534 * Note: hModule must point to a correctly allocated PE image,
535 * with base relocations applied; the 16-bit dummy module
536 * associated to hModule must already exist.
538 * Note: This routine must always be called in the context of the
539 * process that is to own the module to be created.
541 * Note: Assumes that the process critical section is held
543 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
544 HANDLE hFile, BOOL builtin )
546 DWORD load_addr = (DWORD)hModule; /* for RVA */
547 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
548 IMAGE_DATA_DIRECTORY *dir;
549 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
550 WINE_MODREF *wm;
551 HMODULE16 hModule16;
553 /* Retrieve DataDirectory entries */
555 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
556 if (dir->Size)
557 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
559 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
560 if (dir->Size) FIXME("Exception directory ignored\n" );
562 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
563 if (dir->Size) FIXME("Security directory ignored\n" );
565 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
566 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
568 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
569 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
571 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
573 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
574 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
576 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
577 if (dir->Size) TRACE("Bound Import directory ignored\n" );
579 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
580 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
582 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
583 if (dir->Size)
585 TRACE("Delayed import, stub calls LoadLibrary\n" );
587 * Nothing to do here.
590 #ifdef ImgDelayDescr
592 * This code is useful to observe what the heck is going on.
595 ImgDelayDescr *pe_delay = NULL;
596 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
597 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
598 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
599 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
600 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
601 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
602 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
603 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
604 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
606 #endif /* ImgDelayDescr */
609 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
610 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
612 dir = nt->OptionalHeader.DataDirectory+15;
613 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
615 /* Create 16-bit dummy module */
617 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
619 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
620 return NULL;
623 /* Allocate and fill WINE_MODREF */
625 if (!(wm = MODULE_AllocModRef( hModule, filename )))
627 FreeLibrary16( hModule16 );
628 return NULL;
630 wm->hDummyMod = hModule16;
632 if ( builtin )
634 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
635 pModule->flags |= NE_FFLAGS_BUILTIN;
636 wm->flags |= WINE_MODREF_INTERNAL;
638 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
639 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
641 wm->find_export = PE_FindExportedFunction;
643 /* Dump Exports */
645 if ( pe_export )
646 dump_exports( hModule );
648 /* Fixup Imports */
650 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
651 PE_fixup_imports( wm ))
653 /* remove entry from modref chain */
655 if ( !wm->prev )
656 MODULE_modref_list = wm->next;
657 else
658 wm->prev->next = wm->next;
660 if ( wm->next ) wm->next->prev = wm->prev;
661 wm->next = wm->prev = NULL;
663 /* FIXME: there are several more dangling references
664 * left. Including dlls loaded by this dll before the
665 * failed one. Unrolling is rather difficult with the
666 * current structure and we can leave them lying
667 * around with no problems, so we don't care.
668 * As these might reference our wm, we don't free it.
670 return NULL;
673 if (!builtin && pe_export)
674 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
676 /* Send DLL load event */
677 /* we don't need to send a dll event for the main exe */
679 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
681 if (hFile)
683 UINT drive_type = GetDriveTypeA( wm->short_filename );
684 /* don't keep the file handle open on removable media */
685 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
687 SERVER_START_REQ( load_dll )
689 req->handle = hFile;
690 req->base = (void *)hModule;
691 req->size = nt->OptionalHeader.SizeOfImage;
692 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
693 req->dbg_size = nt->FileHeader.NumberOfSymbols;
694 req->name = &wm->filename;
695 wine_server_add_data( req, wm->filename, strlen(wm->filename) );
696 wine_server_call( req );
698 SERVER_END_REQ;
701 return wm;
704 /******************************************************************************
705 * The PE Library Loader frontend.
706 * FIXME: handle the flags.
708 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
710 HMODULE hModule32;
711 WINE_MODREF *wm;
712 HANDLE hFile;
714 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
715 NULL, OPEN_EXISTING, 0, 0 );
716 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
718 /* Load PE module */
719 hModule32 = PE_LoadImage( hFile, name, flags );
720 if (!hModule32)
722 CloseHandle( hFile );
723 return NULL;
726 /* Create 32-bit MODREF */
727 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
729 ERR( "can't load %s\n", name );
730 CloseHandle( hFile );
731 SetLastError( ERROR_OUTOFMEMORY );
732 return NULL;
735 CloseHandle( hFile );
736 return wm;
740 /* Called if the library is loaded or freed.
741 * NOTE: if a thread attaches a DLL, the current thread will only do
742 * DLL_PROCESS_ATTACH. Only newly created threads do DLL_THREAD_ATTACH
743 * (SDK)
745 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
747 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
749 BOOL retv = TRUE;
750 IMAGE_NT_HEADERS *nt = PE_HEADER(module);
752 /* Is this a library? And has it got an entrypoint? */
753 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
754 (nt->OptionalHeader.AddressOfEntryPoint))
756 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
757 if (TRACE_ON(relay))
758 DPRINTF("%08lx:Call PE DLL (proc=%p,module=%08x,type=%ld,res=%p)\n",
759 GetCurrentThreadId(), entry, module, type, lpReserved );
760 retv = entry( module, type, lpReserved );
761 if (TRACE_ON(relay))
762 DPRINTF("%08lx:Ret PE DLL (proc=%p,module=%08x,type=%ld,res=%p) retval=%x\n",
763 GetCurrentThreadId(), entry, module, type, lpReserved, retv );
766 return retv;
769 /************************************************************************
770 * PE_InitTls (internal)
772 * If included, initialises the thread local storages of modules.
773 * Pointers in those structs are not RVAs but real pointers which have been
774 * relocated by do_relocations() already.
776 static LPVOID
777 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
778 if ( ((DWORD)addr>opt->ImageBase) &&
779 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
781 /* the address has not been relocated! */
782 return (LPVOID)(((DWORD)addr)+delta);
783 else
784 /* the address has been relocated already */
785 return addr;
787 void PE_InitTls( void )
789 WINE_MODREF *wm;
790 IMAGE_NT_HEADERS *peh;
791 DWORD size,datasize;
792 LPVOID mem;
793 PIMAGE_TLS_DIRECTORY pdir;
794 int delta;
796 for (wm = MODULE_modref_list;wm;wm=wm->next) {
797 peh = PE_HEADER(wm->module);
798 delta = wm->module - peh->OptionalHeader.ImageBase;
799 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
800 continue;
801 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
802 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
805 if ( wm->tlsindex == -1 ) {
806 LPDWORD xaddr;
807 wm->tlsindex = TlsAlloc();
808 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
809 pdir->AddressOfIndex
811 *xaddr=wm->tlsindex;
813 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
814 size = datasize + pdir->SizeOfZeroFill;
815 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
816 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
817 if (pdir->AddressOfCallBacks) {
818 PIMAGE_TLS_CALLBACK *cbs;
820 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
821 if (*cbs)
822 FIXME("TLS Callbacks aren't going to be called\n");
825 TlsSetValue( wm->tlsindex, mem );