Fixed some incorrect format strings.
[wine/multimedia.git] / loader / pe_image.c
blob7fa54449b347a0eff1416c5de3f0979c23635db9
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:
8 * ftp.microsoft.com:/pub/developer/MSDN/CD8/PEFILE.ZIP
9 * make that:
10 * ftp.microsoft.com:/developr/MSDN/OctCD/PEFILE.ZIP
12 /* Notes:
13 * Before you start changing something in this file be aware of the following:
15 * - There are several functions called recursively. In a very subtle and
16 * obscure way. DLLs can reference each other recursively etc.
17 * - If you want to enhance, speed up or clean up something in here, think
18 * twice WHY it is implemented in that strange way. There is usually a reason.
19 * Though sometimes it might just be lazyness ;)
20 * - In PE_MapImage, right before fixup_imports() all external and internal
21 * state MUST be correct since this function can be called with the SAME image
22 * AGAIN. (Thats recursion for you.) That means MODREF.module and
23 * NE_MODULE.module32.
26 #include "config.h"
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_MMAN_H
30 #include <sys/mman.h>
31 #endif
32 #include "wine/winbase16.h"
33 #include "winerror.h"
34 #include "snoop.h"
35 #include "server.h"
36 #include "debugtools.h"
38 DEFAULT_DEBUG_CHANNEL(win32);
39 DECLARE_DEBUG_CHANNEL(delayhlp);
40 DECLARE_DEBUG_CHANNEL(fixup);
41 DECLARE_DEBUG_CHANNEL(module);
42 DECLARE_DEBUG_CHANNEL(relay);
43 DECLARE_DEBUG_CHANNEL(segment);
46 static IMAGE_EXPORT_DIRECTORY *get_exports( HMODULE hmod )
48 IMAGE_EXPORT_DIRECTORY *ret = NULL;
49 IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
50 + IMAGE_DIRECTORY_ENTRY_EXPORT;
51 if (dir->Size && dir->VirtualAddress)
52 ret = (IMAGE_EXPORT_DIRECTORY *)((char *)hmod + dir->VirtualAddress);
53 return ret;
56 static IMAGE_IMPORT_DESCRIPTOR *get_imports( HMODULE hmod )
58 IMAGE_IMPORT_DESCRIPTOR *ret = NULL;
59 IMAGE_DATA_DIRECTORY *dir = PE_HEADER(hmod)->OptionalHeader.DataDirectory
60 + IMAGE_DIRECTORY_ENTRY_IMPORT;
61 if (dir->Size && dir->VirtualAddress)
62 ret = (IMAGE_IMPORT_DESCRIPTOR *)((char *)hmod + dir->VirtualAddress);
63 return ret;
67 /* convert PE image VirtualAddress to Real Address */
68 #define RVA(x) ((void *)((char *)load_addr+(unsigned int)(x)))
70 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
72 void dump_exports( HMODULE hModule )
74 char *Module;
75 int i, j;
76 WORD *ordinal;
77 DWORD *function,*functions;
78 BYTE **name;
79 unsigned int load_addr = hModule;
81 DWORD rva_start = PE_HEADER(hModule)->OptionalHeader
82 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
83 DWORD rva_end = rva_start + PE_HEADER(hModule)->OptionalHeader
84 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
85 IMAGE_EXPORT_DIRECTORY *pe_exports = (IMAGE_EXPORT_DIRECTORY*)RVA(rva_start);
87 Module = (char*)RVA(pe_exports->Name);
88 TRACE("*******EXPORT DATA*******\n");
89 TRACE("Module name is %s, %ld functions, %ld names\n",
90 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
92 ordinal = RVA(pe_exports->AddressOfNameOrdinals);
93 functions = function = RVA(pe_exports->AddressOfFunctions);
94 name = RVA(pe_exports->AddressOfNames);
96 TRACE(" Ord RVA Addr Name\n" );
97 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
99 if (!*function) continue; /* No such function */
100 if (TRACE_ON(win32))
102 DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, RVA(*function) );
103 /* Check if we have a name for it */
104 for (j = 0; j < pe_exports->NumberOfNames; j++)
105 if (ordinal[j] == i)
107 DPRINTF( " %s", (char*)RVA(name[j]) );
108 break;
110 if ((*function >= rva_start) && (*function <= rva_end))
111 DPRINTF(" (forwarded -> %s)", (char *)RVA(*function));
112 DPRINTF("\n");
117 /* Look up the specified function or ordinal in the exportlist:
118 * If it is a string:
119 * - look up the name in the Name list.
120 * - look up the ordinal with that index.
121 * - use the ordinal as offset into the functionlist
122 * If it is a ordinal:
123 * - use ordinal-pe_export->Base as offset into the functionlist
125 static FARPROC PE_FindExportedFunction(
126 WINE_MODREF *wm, /* [in] WINE modreference */
127 LPCSTR funcName, /* [in] function name */
128 BOOL snoop )
130 WORD * ordinals;
131 DWORD * function;
132 BYTE ** name, *ename = NULL;
133 int i, ordinal;
134 unsigned int load_addr = wm->module;
135 DWORD rva_start, rva_end, addr;
136 char * forward;
137 IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
139 if (HIWORD(funcName))
140 TRACE("(%s)\n",funcName);
141 else
142 TRACE("(%d)\n",(int)funcName);
143 if (!exports) {
144 /* Not a fatal problem, some apps do
145 * GetProcAddress(0,"RegisterPenApp") which triggers this
146 * case.
148 WARN("Module %08x(%s)/MODREF %p doesn't have a exports table.\n",wm->module,wm->modname,wm);
149 return NULL;
151 ordinals= RVA(exports->AddressOfNameOrdinals);
152 function= RVA(exports->AddressOfFunctions);
153 name = RVA(exports->AddressOfNames);
154 forward = NULL;
155 rva_start = PE_HEADER(wm->module)->OptionalHeader
156 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
157 rva_end = rva_start + PE_HEADER(wm->module)->OptionalHeader
158 .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
160 if (HIWORD(funcName))
162 /* first try a binary search */
163 int min = 0, max = exports->NumberOfNames - 1;
164 while (min <= max)
166 int res, pos = (min + max) / 2;
167 ename = RVA(name[pos]);
168 if (!(res = strcmp( ename, funcName )))
170 ordinal = ordinals[pos];
171 goto found;
173 if (res > 0) max = pos - 1;
174 else min = pos + 1;
176 /* now try a linear search in case the names aren't sorted properly */
177 for (i = 0; i < exports->NumberOfNames; i++)
179 ename = RVA(name[i]);
180 if (!strcmp( ename, funcName ))
182 ERR( "%s.%s required a linear search\n", wm->modname, funcName );
183 ordinal = ordinals[i];
184 goto found;
187 return NULL;
189 else /* find by ordinal */
191 ordinal = LOWORD(funcName) - exports->Base;
192 if (snoop && name) /* need to find a name for it */
194 for (i = 0; i < exports->NumberOfNames; i++)
195 if (ordinals[i] == ordinal)
197 ename = RVA(name[i]);
198 break;
203 found:
204 if (ordinal >= exports->NumberOfFunctions)
206 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
207 return NULL;
209 addr = function[ordinal];
210 if (!addr) return NULL;
211 if ((addr < rva_start) || (addr >= rva_end))
213 FARPROC proc = RVA(addr);
214 if (snoop)
216 if (!ename) ename = "@";
217 proc = SNOOP_GetProcAddress(wm->module,ename,ordinal,proc);
219 return proc;
221 else /* forward entry point */
223 WINE_MODREF *wm_fw;
224 FARPROC proc;
225 char *forward = RVA(addr);
226 char module[256];
227 char *end = strchr(forward, '.');
229 if (!end) return NULL;
230 if (end - forward >= sizeof(module)) return NULL;
231 memcpy( module, forward, end - forward );
232 module[end-forward] = 0;
233 if (!(wm_fw = MODULE_FindModule( module )))
235 ERR("module not found for forward '%s' used by '%s'\n", forward, wm->modname );
236 return NULL;
238 if (!(proc = MODULE_GetProcAddress( wm_fw->module, end + 1, snoop )))
239 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 );
240 return proc;
244 DWORD fixup_imports( WINE_MODREF *wm )
246 IMAGE_IMPORT_DESCRIPTOR *pe_imp;
247 unsigned int load_addr = wm->module;
248 int i,characteristics_detection=1;
249 char *modname;
250 IMAGE_EXPORT_DIRECTORY *exports = get_exports(wm->module);
251 IMAGE_IMPORT_DESCRIPTOR *imports = get_imports(wm->module);
253 if (exports)
254 modname = (char*) RVA(exports->Name);
255 else
256 modname = "<unknown>";
258 /* first, count the number of imported non-internal modules */
259 pe_imp = imports;
260 if (!pe_imp) return 0;
262 /* OK, now dump the import list */
263 TRACE("Dumping imports list\n");
265 /* We assume that we have at least one import with !0 characteristics and
266 * detect broken imports with all characteristics 0 (notably Borland) and
267 * switch the detection off for them.
269 for (i = 0; pe_imp->Name ; pe_imp++) {
270 if (!i && !pe_imp->u.Characteristics)
271 characteristics_detection = 0;
272 if (characteristics_detection && !pe_imp->u.Characteristics)
273 break;
274 i++;
276 if (!i) return 0; /* no imports */
278 /* Allocate module dependency list */
279 wm->nDeps = i;
280 wm->deps = HeapAlloc( GetProcessHeap(), 0, i*sizeof(WINE_MODREF *) );
282 /* load the imported modules. They are automatically
283 * added to the modref list of the process.
286 for (i = 0, pe_imp = imports; pe_imp->Name ; pe_imp++) {
287 WINE_MODREF *wmImp;
288 IMAGE_IMPORT_BY_NAME *pe_name;
289 PIMAGE_THUNK_DATA import_list,thunk_list;
290 char *name = (char *) RVA(pe_imp->Name);
292 if (characteristics_detection && !pe_imp->u.Characteristics)
293 break;
295 wmImp = MODULE_LoadLibraryExA( name, 0, 0 );
296 if (!wmImp) {
297 ERR_(module)("Module (file) %s needed by %s not found\n", name, wm->filename);
298 return 1;
300 wm->deps[i++] = wmImp;
302 /* FIXME: forwarder entries ... */
304 if (pe_imp->u.OriginalFirstThunk != 0) { /* original MS style */
305 TRACE("Microsoft style imports used\n");
306 import_list =(PIMAGE_THUNK_DATA) RVA(pe_imp->u.OriginalFirstThunk);
307 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
309 while (import_list->u1.Ordinal) {
310 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal)) {
311 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
313 TRACE("--- Ordinal %s,%d\n", name, ordinal);
314 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
315 wmImp->module, (LPCSTR)ordinal, TRUE
317 if (!thunk_list->u1.Function) {
318 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
319 name, ordinal);
320 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
322 } else { /* import by name */
323 pe_name = (PIMAGE_IMPORT_BY_NAME)RVA(import_list->u1.AddressOfData);
324 TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
325 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
326 wmImp->module, pe_name->Name, TRUE
328 if (!thunk_list->u1.Function) {
329 ERR("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
330 name,pe_name->Hint,pe_name->Name);
331 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
334 import_list++;
335 thunk_list++;
337 } else { /* Borland style */
338 TRACE("Borland style imports used\n");
339 thunk_list = (PIMAGE_THUNK_DATA) RVA(pe_imp->FirstThunk);
340 while (thunk_list->u1.Ordinal) {
341 if (IMAGE_SNAP_BY_ORDINAL(thunk_list->u1.Ordinal)) {
342 /* not sure about this branch, but it seems to work */
343 int ordinal = IMAGE_ORDINAL(thunk_list->u1.Ordinal);
345 TRACE("--- Ordinal %s.%d\n",name,ordinal);
346 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
347 wmImp->module, (LPCSTR) ordinal, TRUE
349 if (!thunk_list->u1.Function) {
350 ERR("No implementation for %s.%d, setting to 0xdeadbeef\n",
351 name,ordinal);
352 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
354 } else {
355 pe_name=(PIMAGE_IMPORT_BY_NAME) RVA(thunk_list->u1.AddressOfData);
356 TRACE("--- %s %s.%d\n",
357 pe_name->Name,name,pe_name->Hint);
358 thunk_list->u1.Function=(PDWORD)MODULE_GetProcAddress(
359 wmImp->module, pe_name->Name, TRUE
361 if (!thunk_list->u1.Function) {
362 ERR("No implementation for %s.%d(%s), setting to 0xdeadbeef\n",
363 name, pe_name->Hint, pe_name->Name);
364 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
367 thunk_list++;
371 return 0;
374 /***********************************************************************
375 * do_relocations
377 * Apply the relocations to a mapped PE image
379 static int do_relocations( char *base, const IMAGE_NT_HEADERS *nt, const char *filename )
381 const IMAGE_DATA_DIRECTORY *dir;
382 const IMAGE_BASE_RELOCATION *rel;
383 int delta = base - (char *)nt->OptionalHeader.ImageBase;
385 dir = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
386 rel = (IMAGE_BASE_RELOCATION *)(base + dir->VirtualAddress);
388 WARN("Info: base relocations needed for %s\n", filename);
389 if (!dir->VirtualAddress || !dir->Size)
391 if (nt->OptionalHeader.ImageBase == 0x400000)
392 ERR("Standard load address for a Win32 program not available - patched kernel ?\n");
393 ERR( "FATAL: Need to relocate %s, but no relocation records present (%s). Try to run that file directly !\n",
394 filename,
395 (nt->FileHeader.Characteristics&IMAGE_FILE_RELOCS_STRIPPED)?
396 "stripped during link" : "unknown reason" );
397 return 0;
400 /* FIXME: If we need to relocate a system DLL (base > 2GB) we should
401 * really make sure that the *new* base address is also > 2GB.
402 * Some DLLs really check the MSB of the module handle :-/
404 if ((nt->OptionalHeader.ImageBase & 0x80000000) && !((DWORD)base & 0x80000000))
405 ERR( "Forced to relocate system DLL (base > 2GB). This is not good.\n" );
407 for ( ; ((char *)rel < base + dir->VirtualAddress + dir->Size) && rel->VirtualAddress;
408 rel = (IMAGE_BASE_RELOCATION*)((char*)rel + rel->SizeOfBlock))
410 char *page = base + rel->VirtualAddress;
411 int i, count = (rel->SizeOfBlock - 8) / sizeof(rel->TypeOffset);
413 if (!count) continue;
415 /* sanity checks */
416 if ((char *)rel + rel->SizeOfBlock > base + dir->VirtualAddress + dir->Size ||
417 page > base + nt->OptionalHeader.SizeOfImage)
419 ERR_(module)("invalid relocation %p,%lx,%ld at %p,%lx,%lx\n",
420 rel, rel->VirtualAddress, rel->SizeOfBlock,
421 base, dir->VirtualAddress, dir->Size );
422 return 0;
425 TRACE_(module)("%ld relocations for page %lx\n", rel->SizeOfBlock, rel->VirtualAddress);
427 /* patching in reverse order */
428 for (i = 0 ; i < count; i++)
430 int offset = rel->TypeOffset[i] & 0xFFF;
431 int type = rel->TypeOffset[i] >> 12;
432 switch(type)
434 case IMAGE_REL_BASED_ABSOLUTE:
435 break;
436 case IMAGE_REL_BASED_HIGH:
437 *(short*)(page+offset) += HIWORD(delta);
438 break;
439 case IMAGE_REL_BASED_LOW:
440 *(short*)(page+offset) += LOWORD(delta);
441 break;
442 case IMAGE_REL_BASED_HIGHLOW:
443 *(int*)(page+offset) += delta;
444 /* FIXME: if this is an exported address, fire up enhanced logic */
445 break;
446 default:
447 FIXME_(module)("Unknown/unsupported fixup type %d.\n", type);
448 break;
452 return 1;
456 /**********************************************************************
457 * PE_LoadImage
458 * Load one PE format DLL/EXE into memory
460 * Unluckily we can't just mmap the sections where we want them, for
461 * (at least) Linux does only support offsets which are page-aligned.
463 * BUT we have to map the whole image anyway, for Win32 programs sometimes
464 * want to access them. (HMODULE32 point to the start of it)
466 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
468 IMAGE_NT_HEADERS *nt;
469 HMODULE hModule;
470 HANDLE mapping;
471 void *base;
473 TRACE_(module)( "loading %s\n", filename );
475 mapping = CreateFileMappingA( hFile, NULL, SEC_IMAGE, 0, 0, NULL );
476 if (!mapping) return 0;
477 base = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
478 CloseHandle( mapping );
479 if (!base) return 0;
481 hModule = (HMODULE)base;
482 if (flags & LOAD_LIBRARY_AS_DATAFILE) return hModule; /* nothing else to do */
484 /* perform base relocation, if necessary */
486 nt = PE_HEADER( hModule );
487 if (hModule != nt->OptionalHeader.ImageBase)
489 if (!do_relocations( base, nt, filename ))
491 UnmapViewOfFile( base );
492 SetLastError( ERROR_BAD_EXE_FORMAT );
493 return 0;
497 /* virus check */
499 if (nt->OptionalHeader.AddressOfEntryPoint)
501 int i;
502 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
503 nt->FileHeader.SizeOfOptionalHeader);
504 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
506 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress)
507 continue;
508 if (nt->OptionalHeader.AddressOfEntryPoint < sec->VirtualAddress+sec->SizeOfRawData)
509 break;
511 if (i == nt->FileHeader.NumberOfSections)
512 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
513 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
514 nt->OptionalHeader.AddressOfEntryPoint );
517 return hModule;
520 /**********************************************************************
521 * PE_CreateModule
523 * Create WINE_MODREF structure for loaded HMODULE32, link it into
524 * process modref_list, and fixup all imports.
526 * Note: hModule must point to a correctly allocated PE image,
527 * with base relocations applied; the 16-bit dummy module
528 * associated to hModule must already exist.
530 * Note: This routine must always be called in the context of the
531 * process that is to own the module to be created.
533 * Note: Assumes that the process critical section is held
535 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
536 HANDLE hFile, BOOL builtin )
538 DWORD load_addr = (DWORD)hModule; /* for RVA */
539 IMAGE_NT_HEADERS *nt = PE_HEADER(hModule);
540 IMAGE_DATA_DIRECTORY *dir;
541 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
542 WINE_MODREF *wm;
543 HMODULE16 hModule16;
545 /* Retrieve DataDirectory entries */
547 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
548 if (dir->Size)
549 pe_export = (PIMAGE_EXPORT_DIRECTORY)RVA(dir->VirtualAddress);
551 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
552 if (dir->Size) FIXME("Exception directory ignored\n" );
554 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
555 if (dir->Size) FIXME("Security directory ignored\n" );
557 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
558 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
560 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
561 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
563 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
565 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
566 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
568 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
569 if (dir->Size) TRACE("Bound Import directory ignored\n" );
571 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
572 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
574 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
575 if (dir->Size)
577 TRACE("Delayed import, stub calls LoadLibrary\n" );
579 * Nothing to do here.
582 #ifdef ImgDelayDescr
584 * This code is useful to observe what the heck is going on.
587 ImgDelayDescr *pe_delay = NULL;
588 pe_delay = (PImgDelayDescr)RVA(dir->VirtualAddress);
589 TRACE_(delayhlp)("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
590 TRACE_(delayhlp)("pe_delay->szName = %s\n", pe_delay->szName);
591 TRACE_(delayhlp)("pe_delay->phmod = %08x\n", pe_delay->phmod);
592 TRACE_(delayhlp)("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
593 TRACE_(delayhlp)("pe_delay->pINT = %08x\n", pe_delay->pINT);
594 TRACE_(delayhlp)("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
595 TRACE_(delayhlp)("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
596 TRACE_(delayhlp)("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
598 #endif /* ImgDelayDescr */
601 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
602 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
604 dir = nt->OptionalHeader.DataDirectory+15;
605 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
607 /* Create 16-bit dummy module */
609 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
611 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
612 return NULL;
615 /* Allocate and fill WINE_MODREF */
617 if (!(wm = MODULE_AllocModRef( hModule, filename )))
619 FreeLibrary16( hModule16 );
620 return NULL;
622 wm->hDummyMod = hModule16;
624 if ( builtin )
626 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
627 pModule->flags |= NE_FFLAGS_BUILTIN;
628 wm->flags |= WINE_MODREF_INTERNAL;
631 if ( flags & DONT_RESOLVE_DLL_REFERENCES )
632 wm->flags |= WINE_MODREF_DONT_RESOLVE_REFS;
634 wm->find_export = PE_FindExportedFunction;
636 /* Dump Exports */
638 if ( pe_export )
639 dump_exports( hModule );
641 /* Fixup Imports */
643 if (!(wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) && fixup_imports( wm ))
645 /* remove entry from modref chain */
647 if ( !wm->prev )
648 MODULE_modref_list = wm->next;
649 else
650 wm->prev->next = wm->next;
652 if ( wm->next ) wm->next->prev = wm->prev;
653 wm->next = wm->prev = NULL;
655 /* FIXME: there are several more dangling references
656 * left. Including dlls loaded by this dll before the
657 * failed one. Unrolling is rather difficult with the
658 * current structure and we can leave it them lying
659 * around with no problems, so we don't care.
660 * As these might reference our wm, we don't free it.
662 return NULL;
665 if (pe_export)
666 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->NumberOfFunctions );
668 /* Send DLL load event */
669 /* we don't need to send a dll event for the main exe */
671 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
673 SERVER_START_REQ
675 struct load_dll_request *req = server_alloc_req( sizeof(*req), 0 );
676 req->handle = hFile;
677 req->base = (void *)hModule;
678 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
679 req->dbg_size = nt->FileHeader.NumberOfSymbols;
680 req->name = &wm->filename;
681 server_call_noerr( REQ_LOAD_DLL );
683 SERVER_END_REQ;
686 return wm;
689 /******************************************************************************
690 * The PE Library Loader frontend.
691 * FIXME: handle the flags.
693 WINE_MODREF *PE_LoadLibraryExA (LPCSTR name, DWORD flags)
695 HMODULE hModule32;
696 WINE_MODREF *wm;
697 HANDLE hFile;
699 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
700 NULL, OPEN_EXISTING, 0, 0 );
701 if ( hFile == INVALID_HANDLE_VALUE ) return NULL;
703 /* Load PE module */
704 hModule32 = PE_LoadImage( hFile, name, flags );
705 if (!hModule32)
707 CloseHandle( hFile );
708 return NULL;
711 /* Create 32-bit MODREF */
712 if ( !(wm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
714 ERR( "can't load %s\n", name );
715 CloseHandle( hFile );
716 SetLastError( ERROR_OUTOFMEMORY );
717 return NULL;
720 CloseHandle( hFile );
721 return wm;
725 /* Called if the library is loaded or freed.
726 * NOTE: if a thread attaches a DLL, the current thread will only do
727 * DLL_PROCESS_ATTACH. Only new created threads do DLL_THREAD_ATTACH
728 * (SDK)
730 typedef DWORD CALLBACK(*DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
732 BOOL PE_InitDLL( HMODULE module, DWORD type, LPVOID lpReserved )
734 BOOL retv = TRUE;
735 IMAGE_NT_HEADERS *nt = PE_HEADER(module);
737 /* Is this a library? And has it got an entrypoint? */
738 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
739 (nt->OptionalHeader.AddressOfEntryPoint))
741 DLLENTRYPROC entry = (void*)((char*)module + nt->OptionalHeader.AddressOfEntryPoint);
742 TRACE_(relay)("CallTo32(entryproc=%p,module=%08x,type=%ld,res=%p)\n",
743 entry, module, type, lpReserved );
745 retv = entry( module, type, lpReserved );
748 return retv;
751 /************************************************************************
752 * PE_InitTls (internal)
754 * If included, initialises the thread local storages of modules.
755 * Pointers in those structs are not RVAs but real pointers which have been
756 * relocated by do_relocations() already.
758 static LPVOID
759 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
760 if ( ((DWORD)addr>opt->ImageBase) &&
761 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
763 /* the address has not been relocated! */
764 return (LPVOID)(((DWORD)addr)+delta);
765 else
766 /* the address has been relocated already */
767 return addr;
769 void PE_InitTls( void )
771 WINE_MODREF *wm;
772 IMAGE_NT_HEADERS *peh;
773 DWORD size,datasize;
774 LPVOID mem;
775 PIMAGE_TLS_DIRECTORY pdir;
776 int delta;
778 for (wm = MODULE_modref_list;wm;wm=wm->next) {
779 peh = PE_HEADER(wm->module);
780 delta = wm->module - peh->OptionalHeader.ImageBase;
781 if (!peh->OptionalHeader.DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress)
782 continue;
783 pdir = (LPVOID)(wm->module + peh->OptionalHeader.
784 DataDirectory[IMAGE_FILE_THREAD_LOCAL_STORAGE].VirtualAddress);
787 if ( wm->tlsindex == -1 ) {
788 LPDWORD xaddr;
789 wm->tlsindex = TlsAlloc();
790 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
791 pdir->AddressOfIndex
793 *xaddr=wm->tlsindex;
795 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
796 size = datasize + pdir->SizeOfZeroFill;
797 mem=VirtualAlloc(0,size,MEM_RESERVE|MEM_COMMIT,PAGE_READWRITE);
798 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
799 if (pdir->AddressOfCallBacks) {
800 PIMAGE_TLS_CALLBACK *cbs;
802 cbs = _fixup_address(&(peh->OptionalHeader),delta,pdir->AddressOfCallBacks);
803 if (*cbs)
804 FIXME("TLS Callbacks aren't going to be called\n");
807 TlsSetValue( wm->tlsindex, mem );