Added an implementation of iphlpapi.dll; most Get* functions
[wine.git] / loader / pe_image.c
blobdeffca76253463622d0051af93244a45ab9867d2
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"
49 #include "ntdll_misc.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(win32);
52 WINE_DECLARE_DEBUG_CHANNEL(module);
53 WINE_DECLARE_DEBUG_CHANNEL(relay);
56 /* convert PE image VirtualAddress to Real Address */
57 inline static void *get_rva( HMODULE module, DWORD va )
59 return (void *)((char *)module + va);
62 #define AdjustPtr(ptr,delta) ((char *)(ptr) + (delta))
64 void dump_exports( HMODULE hModule )
66 char *Module;
67 int i, j;
68 WORD *ordinal;
69 DWORD *function,*functions;
70 DWORD *name;
71 IMAGE_EXPORT_DIRECTORY *pe_exports;
72 DWORD rva_start, size;
74 pe_exports = RtlImageDirectoryEntryToData( hModule, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
75 rva_start = (char *)pe_exports - (char *)hModule;
77 Module = get_rva(hModule, pe_exports->Name);
78 DPRINTF("*******EXPORT DATA*******\n");
79 DPRINTF("Module name is %s, %ld functions, %ld names\n",
80 Module, pe_exports->NumberOfFunctions, pe_exports->NumberOfNames);
82 ordinal = get_rva(hModule, pe_exports->AddressOfNameOrdinals);
83 functions = function = get_rva(hModule, pe_exports->AddressOfFunctions);
84 name = get_rva(hModule, pe_exports->AddressOfNames);
86 DPRINTF(" Ord RVA Addr Name\n" );
87 for (i=0;i<pe_exports->NumberOfFunctions;i++, function++)
89 if (!*function) continue; /* No such function */
90 DPRINTF( "%4ld %08lx %p", i + pe_exports->Base, *function, get_rva(hModule, *function) );
91 /* Check if we have a name for it */
92 for (j = 0; j < pe_exports->NumberOfNames; j++)
93 if (ordinal[j] == i)
95 DPRINTF( " %s", (char*)get_rva(hModule, name[j]) );
96 break;
98 if ((*function >= rva_start) && (*function <= rva_start + size))
99 DPRINTF(" (forwarded -> %s)", (char *)get_rva(hModule, *function));
100 DPRINTF("\n");
104 /**********************************************************************
105 * PE_LoadImage
106 * Load one PE format DLL/EXE into memory
108 * Unluckily we can't just mmap the sections where we want them, for
109 * (at least) Linux does only support offsets which are page-aligned.
111 * BUT we have to map the whole image anyway, for Win32 programs sometimes
112 * want to access them. (HMODULE points to the start of it)
114 HMODULE PE_LoadImage( HANDLE hFile, LPCSTR filename, DWORD flags )
116 IMAGE_NT_HEADERS *nt;
117 HMODULE hModule;
118 HANDLE mapping;
119 void *base = NULL;
120 OBJECT_ATTRIBUTES attr;
121 LARGE_INTEGER lg_int;
122 DWORD len = 0;
123 NTSTATUS nts;
125 TRACE_(module)( "loading %s\n", filename );
127 attr.Length = sizeof(attr);
128 attr.RootDirectory = 0;
129 attr.ObjectName = NULL;
130 attr.Attributes = 0;
131 attr.SecurityDescriptor = NULL;
132 attr.SecurityQualityOfService = NULL;
134 lg_int.QuadPart = 0;
136 if (NtCreateSection( &mapping,
137 STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
138 &attr, &lg_int, 0, SEC_IMAGE, hFile ) != STATUS_SUCCESS)
139 return 0;
141 nts = NtMapViewOfSection( mapping, GetCurrentProcess(),
142 &base, 0, 0, &lg_int, &len, ViewShare, 0,
143 PAGE_READONLY );
145 NtClose( mapping );
146 if (nts != STATUS_SUCCESS) return 0;
148 /* virus check */
150 hModule = (HMODULE)base;
151 nt = RtlImageNtHeader( hModule );
153 if (nt->OptionalHeader.AddressOfEntryPoint)
155 if (!RtlImageRvaToSection( nt, hModule, nt->OptionalHeader.AddressOfEntryPoint ))
156 MESSAGE("VIRUS WARNING: PE module has an invalid entrypoint (0x%08lx) "
157 "outside all sections (possibly infected by Tchernobyl/SpaceFiller virus)!\n",
158 nt->OptionalHeader.AddressOfEntryPoint );
161 return hModule;
164 /**********************************************************************
165 * PE_CreateModule
167 * Create WINE_MODREF structure for loaded HMODULE, link it into
168 * process modref_list, and fixup all imports.
170 * Note: hModule must point to a correctly allocated PE image,
171 * with base relocations applied; the 16-bit dummy module
172 * associated to hModule must already exist.
174 * Note: This routine must always be called in the context of the
175 * process that is to own the module to be created.
177 * Note: Assumes that the process critical section is held
179 WINE_MODREF *PE_CreateModule( HMODULE hModule, LPCSTR filename, DWORD flags,
180 HANDLE hFile, BOOL builtin )
182 IMAGE_NT_HEADERS *nt;
183 IMAGE_DATA_DIRECTORY *dir;
184 IMAGE_EXPORT_DIRECTORY *pe_export = NULL;
185 WINE_MODREF *wm;
186 HMODULE16 hModule16;
188 /* Retrieve DataDirectory entries */
190 nt = RtlImageNtHeader(hModule);
191 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXPORT;
192 if (dir->Size) pe_export = get_rva(hModule, dir->VirtualAddress);
194 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_EXCEPTION;
195 if (dir->Size) FIXME("Exception directory ignored\n" );
197 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_SECURITY;
198 if (dir->Size) FIXME("Security directory ignored\n" );
200 /* IMAGE_DIRECTORY_ENTRY_BASERELOC handled in PE_LoadImage */
201 /* IMAGE_DIRECTORY_ENTRY_DEBUG handled by debugger */
203 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_GLOBALPTR;
204 if (dir->Size) FIXME("Global Pointer (MIPS) ignored\n" );
206 /* IMAGE_DIRECTORY_ENTRY_TLS handled in PE_TlsInit */
208 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG;
209 if (dir->Size) FIXME("Load Configuration directory ignored\n" );
211 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT;
212 if (dir->Size) TRACE("Bound Import directory ignored\n" );
214 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_IAT;
215 if (dir->Size) TRACE("Import Address Table directory ignored\n" );
217 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT;
218 if (dir->Size)
220 TRACE("Delayed import, stub calls LoadLibrary\n" );
222 * Nothing to do here.
225 #ifdef ImgDelayDescr
227 * This code is useful to observe what the heck is going on.
230 ImgDelayDescr *pe_delay = NULL;
231 pe_delay = get_rva(hModule, dir->VirtualAddress);
232 TRACE("pe_delay->grAttrs = %08x\n", pe_delay->grAttrs);
233 TRACE("pe_delay->szName = %s\n", pe_delay->szName);
234 TRACE("pe_delay->phmod = %08x\n", pe_delay->phmod);
235 TRACE("pe_delay->pIAT = %08x\n", pe_delay->pIAT);
236 TRACE("pe_delay->pINT = %08x\n", pe_delay->pINT);
237 TRACE("pe_delay->pBoundIAT = %08x\n", pe_delay->pBoundIAT);
238 TRACE("pe_delay->pUnloadIAT = %08x\n", pe_delay->pUnloadIAT);
239 TRACE("pe_delay->dwTimeStamp = %08x\n", pe_delay->dwTimeStamp);
241 #endif /* ImgDelayDescr */
244 dir = nt->OptionalHeader.DataDirectory+IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR;
245 if (dir->Size) FIXME("Unknown directory 14 ignored\n" );
247 dir = nt->OptionalHeader.DataDirectory+15;
248 if (dir->Size) FIXME("Unknown directory 15 ignored\n" );
250 /* Create 16-bit dummy module */
252 if ((hModule16 = MODULE_CreateDummyModule( filename, hModule )) < 32)
254 SetLastError( (DWORD)hModule16 ); /* This should give the correct error */
255 return NULL;
258 /* Allocate and fill WINE_MODREF */
260 if (!(wm = MODULE_AllocModRef( hModule, filename )))
262 FreeLibrary16( hModule16 );
263 return NULL;
265 wm->hDummyMod = hModule16;
267 if ( builtin )
269 NE_MODULE *pModule = (NE_MODULE *)GlobalLock16( hModule16 );
270 pModule->flags |= NE_FFLAGS_BUILTIN;
271 wm->ldr.Flags |= LDR_WINE_INTERNAL;
273 else if ( flags & DONT_RESOLVE_DLL_REFERENCES )
274 wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
276 /* Dump Exports */
278 if (pe_export && TRACE_ON(win32))
279 dump_exports( hModule );
281 /* Fixup Imports */
283 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
284 PE_fixup_imports( wm ))
286 /* remove entry from modref chain */
288 if ( !wm->prev )
289 MODULE_modref_list = wm->next;
290 else
291 wm->prev->next = wm->next;
293 if ( wm->next ) wm->next->prev = wm->prev;
294 wm->next = wm->prev = NULL;
296 /* FIXME: there are several more dangling references
297 * left. Including dlls loaded by this dll before the
298 * failed one. Unrolling is rather difficult with the
299 * current structure and we can leave them lying
300 * around with no problems, so we don't care.
301 * As these might reference our wm, we don't free it.
303 return NULL;
306 if (!builtin && pe_export)
307 SNOOP_RegisterDLL( hModule, wm->modname, pe_export->Base, pe_export->NumberOfFunctions );
309 /* Send DLL load event */
310 /* we don't need to send a dll event for the main exe */
312 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
314 if (hFile)
316 UINT drive_type = GetDriveTypeA( wm->short_filename );
317 /* don't keep the file handle open on removable media */
318 if (drive_type == DRIVE_REMOVABLE || drive_type == DRIVE_CDROM) hFile = 0;
320 SERVER_START_REQ( load_dll )
322 req->handle = hFile;
323 req->base = (void *)hModule;
324 req->size = nt->OptionalHeader.SizeOfImage;
325 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
326 req->dbg_size = nt->FileHeader.NumberOfSymbols;
327 req->name = &wm->filename;
328 wine_server_add_data( req, wm->filename, strlen(wm->filename) );
329 wine_server_call( req );
331 SERVER_END_REQ;
334 return wm;
337 /******************************************************************************
338 * The PE Library Loader frontend.
339 * FIXME: handle the flags.
341 NTSTATUS PE_LoadLibraryExA (LPCSTR name, DWORD flags, WINE_MODREF** pwm)
343 HMODULE hModule32;
344 HANDLE hFile;
346 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
347 NULL, OPEN_EXISTING, 0, 0 );
348 if ( hFile == INVALID_HANDLE_VALUE )
350 /* keep it that way until we transform CreateFile into NtCreateFile */
351 return (GetLastError() == ERROR_FILE_NOT_FOUND) ?
352 STATUS_NO_SUCH_FILE : STATUS_INTERNAL_ERROR;
355 /* Load PE module */
356 hModule32 = PE_LoadImage( hFile, name, flags );
357 if (!hModule32)
359 CloseHandle( hFile );
360 return STATUS_INTERNAL_ERROR;
363 /* Create 32-bit MODREF */
364 if ( !(*pwm = PE_CreateModule( hModule32, name, flags, hFile, FALSE )) )
366 ERR( "can't load %s\n", name );
367 CloseHandle( hFile );
368 return STATUS_NO_MEMORY; /* FIXME */
371 CloseHandle( hFile );
372 return STATUS_SUCCESS;
376 /************************************************************************
377 * PE_InitTls (internal)
379 * If included, initialises the thread local storages of modules.
380 * Pointers in those structs are not RVAs but real pointers which have been
381 * relocated by do_relocations() already.
383 static LPVOID
384 _fixup_address(PIMAGE_OPTIONAL_HEADER opt,int delta,LPVOID addr) {
385 if ( ((DWORD)addr>opt->ImageBase) &&
386 ((DWORD)addr<opt->ImageBase+opt->SizeOfImage)
388 /* the address has not been relocated! */
389 return (LPVOID)(((DWORD)addr)+delta);
390 else
391 /* the address has been relocated already */
392 return addr;
395 void PE_InitTls( void )
397 WINE_MODREF *wm;
398 IMAGE_NT_HEADERS *peh;
399 DWORD size,datasize,dirsize;
400 LPVOID mem;
401 PIMAGE_TLS_DIRECTORY pdir;
402 int delta;
404 for (wm = MODULE_modref_list;wm;wm=wm->next) {
405 peh = RtlImageNtHeader(wm->ldr.BaseAddress);
406 pdir = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
407 IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
408 if (!pdir) continue;
409 delta = (char *)wm->ldr.BaseAddress - (char *)peh->OptionalHeader.ImageBase;
411 if ( wm->ldr.TlsIndex == -1 ) {
412 LPDWORD xaddr;
413 wm->ldr.TlsIndex = TlsAlloc();
414 xaddr = _fixup_address(&(peh->OptionalHeader),delta,
415 pdir->AddressOfIndex
417 *xaddr=wm->ldr.TlsIndex;
419 datasize= pdir->EndAddressOfRawData-pdir->StartAddressOfRawData;
420 size = datasize + pdir->SizeOfZeroFill;
421 NtAllocateVirtualMemory( GetCurrentProcess(), &mem, NULL, &size,
422 MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
423 memcpy(mem,_fixup_address(&(peh->OptionalHeader),delta,(LPVOID)pdir->StartAddressOfRawData),datasize);
424 TlsSetValue( wm->ldr.TlsIndex, mem );