d3d10core: Set the initial blend factors to 1.0f.
[wine/multimedia.git] / dlls / kernel32 / module.c
blobca4cf41ff5e7a34107337ad161915bcaaf9f3e53
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <fcntl.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include "ntstatus.h"
34 #define WIN32_NO_STATUS
35 #include "winerror.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winternl.h"
39 #include "kernel_private.h"
40 #include "psapi.h"
42 #include "wine/exception.h"
43 #include "wine/debug.h"
44 #include "wine/unicode.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 #define NE_FFLAGS_LIBMODULE 0x8000
50 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
52 static CRITICAL_SECTION dlldir_section;
53 static CRITICAL_SECTION_DEBUG critsect_debug =
55 0, 0, &dlldir_section,
56 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
57 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
59 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
62 /****************************************************************************
63 * GetDllDirectoryA (KERNEL32.@)
65 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
67 DWORD len;
69 RtlEnterCriticalSection( &dlldir_section );
70 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
71 if (buffer && buf_len > len)
73 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
74 else *buffer = 0;
76 else
78 len++; /* for terminating null */
79 if (buffer) *buffer = 0;
81 RtlLeaveCriticalSection( &dlldir_section );
82 return len;
86 /****************************************************************************
87 * GetDllDirectoryW (KERNEL32.@)
89 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
91 DWORD len;
93 RtlEnterCriticalSection( &dlldir_section );
94 len = dll_directory ? strlenW( dll_directory ) : 0;
95 if (buffer && buf_len > len)
97 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
98 else *buffer = 0;
100 else
102 len++; /* for terminating null */
103 if (buffer) *buffer = 0;
105 RtlLeaveCriticalSection( &dlldir_section );
106 return len;
110 /****************************************************************************
111 * SetDllDirectoryA (KERNEL32.@)
113 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
115 WCHAR *dirW;
116 BOOL ret;
118 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
119 ret = SetDllDirectoryW( dirW );
120 HeapFree( GetProcessHeap(), 0, dirW );
121 return ret;
125 /****************************************************************************
126 * SetDllDirectoryW (KERNEL32.@)
128 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
130 WCHAR *newdir = NULL;
132 if (dir)
134 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
135 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
137 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
138 return FALSE;
140 memcpy( newdir, dir, len );
143 RtlEnterCriticalSection( &dlldir_section );
144 HeapFree( GetProcessHeap(), 0, dll_directory );
145 dll_directory = newdir;
146 RtlLeaveCriticalSection( &dlldir_section );
147 return TRUE;
151 /****************************************************************************
152 * DisableThreadLibraryCalls (KERNEL32.@)
154 * Inform the module loader that thread notifications are not required for a dll.
156 * PARAMS
157 * hModule [I] Module handle to skip calls for
159 * RETURNS
160 * Success: TRUE. Thread attach and detach notifications will not be sent
161 * to hModule.
162 * Failure: FALSE. Use GetLastError() to determine the cause.
164 * NOTES
165 * This is typically called from the dll entry point of a dll during process
166 * attachment, for dlls that do not need to process thread notifications.
168 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
170 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
171 if (nts == STATUS_SUCCESS) return TRUE;
173 SetLastError( RtlNtStatusToDosError( nts ) );
174 return FALSE;
178 /* Check whether a file is an OS/2 or a very old Windows executable
179 * by testing on import of KERNEL.
181 * FIXME: is reading the module imports the only way of discerning
182 * old Windows binaries from OS/2 ones ? At least it seems so...
184 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
186 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
187 DWORD ret = BINARY_OS216;
188 LPWORD modtab = NULL;
189 LPSTR nametab = NULL;
190 DWORD len;
191 int i;
193 /* read modref table */
194 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
195 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
196 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
197 || (len != ne->ne_cmod*sizeof(WORD)) )
198 goto broken;
200 /* read imported names table */
201 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
202 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
203 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
204 || (len != ne->ne_enttab - ne->ne_imptab) )
205 goto broken;
207 for (i=0; i < ne->ne_cmod; i++)
209 LPSTR module = &nametab[modtab[i]];
210 TRACE("modref: %.*s\n", module[0], &module[1]);
211 if (!(strncmp(&module[1], "KERNEL", module[0])))
212 { /* very old Windows file */
213 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
214 ret = BINARY_WIN16;
215 goto good;
219 broken:
220 ERR("Hmm, an error occurred. Is this binary file broken?\n");
222 good:
223 HeapFree( GetProcessHeap(), 0, modtab);
224 HeapFree( GetProcessHeap(), 0, nametab);
225 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
226 return ret;
229 /***********************************************************************
230 * MODULE_GetBinaryType
232 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
234 union
236 struct
238 unsigned char magic[4];
239 unsigned char class;
240 unsigned char data;
241 unsigned char version;
242 unsigned char ignored[9];
243 unsigned short type;
244 unsigned short machine;
245 } elf;
246 struct
248 unsigned int magic;
249 unsigned int cputype;
250 unsigned int cpusubtype;
251 unsigned int filetype;
252 } macho;
253 IMAGE_DOS_HEADER mz;
254 } header;
256 DWORD len;
258 memset( info, 0, sizeof(*info) );
260 /* Seek to the start of the file and read the header information. */
261 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
262 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
264 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
266 if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
267 #ifdef WORDS_BIGENDIAN
268 if (header.elf.data == 1)
269 #else
270 if (header.elf.data == 2)
271 #endif
273 header.elf.type = RtlUshortByteSwap( header.elf.type );
274 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
276 switch(header.elf.type)
278 case 2: info->type = BINARY_UNIX_EXE; break;
279 case 3: info->type = BINARY_UNIX_LIB; break;
281 switch(header.elf.machine)
283 case 3: info->arch = IMAGE_FILE_MACHINE_I386; break;
284 case 20: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
285 case 40: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
286 case 50: info->arch = IMAGE_FILE_MACHINE_IA64; break;
287 case 62: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
288 case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
291 /* Mach-o File with Endian set to Big Endian or Little Endian */
292 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
294 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
295 if (header.macho.magic == 0xcefaedfe)
297 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
298 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
300 switch(header.macho.filetype)
302 case 2: info->type = BINARY_UNIX_EXE; break;
303 case 8: info->type = BINARY_UNIX_LIB; break;
305 switch(header.macho.cputype)
307 case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
308 case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
309 case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
310 case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
311 case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
314 /* Not ELF, try DOS */
315 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
317 union
319 IMAGE_OS2_HEADER os2;
320 IMAGE_NT_HEADERS32 nt;
321 } ext_header;
323 /* We do have a DOS image so we will now try to seek into
324 * the file by the amount indicated by the field
325 * "Offset to extended header" and read in the
326 * "magic" field information at that location.
327 * This will tell us if there is more header information
328 * to read or not.
330 info->type = BINARY_DOS;
331 info->arch = IMAGE_FILE_MACHINE_I386;
332 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
333 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
335 /* Reading the magic field succeeded so
336 * we will try to determine what type it is.
338 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
340 if (len >= sizeof(ext_header.nt.FileHeader))
342 static const char fakedll_signature[] = "Wine placeholder DLL";
343 char buffer[sizeof(fakedll_signature)];
345 info->type = BINARY_PE;
346 info->arch = ext_header.nt.FileHeader.Machine;
347 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
348 info->flags |= BINARY_FLAG_DLL;
349 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
350 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
351 switch (ext_header.nt.OptionalHeader.Magic)
353 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
354 info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
355 info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
356 ext_header.nt.OptionalHeader.SizeOfImage);
357 break;
358 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
359 info->flags |= BINARY_FLAG_64BIT;
360 break;
363 if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
364 SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
365 ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
366 len == sizeof(fakedll_signature) &&
367 !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
369 info->flags |= BINARY_FLAG_FAKEDLL;
373 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
375 /* This is a Windows executable (NE) header. This can
376 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
377 * DOS program (running under a DOS extender). To decide
378 * which, we'll have to read the NE header.
380 if (len >= sizeof(ext_header.os2))
382 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
383 switch ( ext_header.os2.ne_exetyp )
385 case 1: info->type = BINARY_OS216; break; /* OS/2 */
386 case 2: info->type = BINARY_WIN16; break; /* Windows */
387 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
388 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
389 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
390 /* other types, e.g. 0 is: "unknown" */
391 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
398 /***********************************************************************
399 * GetBinaryTypeW [KERNEL32.@]
401 * Determine whether a file is executable, and if so, what kind.
403 * PARAMS
404 * lpApplicationName [I] Path of the file to check
405 * lpBinaryType [O] Destination for the binary type
407 * RETURNS
408 * TRUE, if the file is an executable, in which case lpBinaryType is set.
409 * FALSE, if the file is not an executable or if the function fails.
411 * NOTES
412 * The type of executable is a property that determines which subsystem an
413 * executable file runs under. lpBinaryType can be set to one of the following
414 * values:
415 * SCS_32BIT_BINARY: A Win32 based application
416 * SCS_64BIT_BINARY: A Win64 based application
417 * SCS_DOS_BINARY: An MS-Dos based application
418 * SCS_WOW_BINARY: A Win16 based application
419 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
420 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
421 * SCS_OS216_BINARY: A 16bit OS/2 based application
423 * To find the binary type, this function reads in the files header information.
424 * If extended header information is not present it will assume that the file
425 * is a DOS executable. If extended header information is present it will
426 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
427 * flags in the header.
429 * ".com" and ".pif" files are only recognized by their file name extension,
430 * as per native Windows.
432 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
434 BOOL ret = FALSE;
435 HANDLE hfile;
436 struct binary_info binary_info;
438 TRACE("%s\n", debugstr_w(lpApplicationName) );
440 /* Sanity check.
442 if ( lpApplicationName == NULL || lpBinaryType == NULL )
443 return FALSE;
445 /* Open the file indicated by lpApplicationName for reading.
447 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
448 NULL, OPEN_EXISTING, 0, 0 );
449 if ( hfile == INVALID_HANDLE_VALUE )
450 return FALSE;
452 /* Check binary type
454 MODULE_get_binary_info( hfile, &binary_info );
455 switch (binary_info.type)
457 case BINARY_UNKNOWN:
459 static const WCHAR comW[] = { '.','C','O','M',0 };
460 static const WCHAR pifW[] = { '.','P','I','F',0 };
461 const WCHAR *ptr;
463 /* try to determine from file name */
464 ptr = strrchrW( lpApplicationName, '.' );
465 if (!ptr) break;
466 if (!strcmpiW( ptr, comW ))
468 *lpBinaryType = SCS_DOS_BINARY;
469 ret = TRUE;
471 else if (!strcmpiW( ptr, pifW ))
473 *lpBinaryType = SCS_PIF_BINARY;
474 ret = TRUE;
476 break;
478 case BINARY_PE:
479 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
480 ret = TRUE;
481 break;
482 case BINARY_WIN16:
483 *lpBinaryType = SCS_WOW_BINARY;
484 ret = TRUE;
485 break;
486 case BINARY_OS216:
487 *lpBinaryType = SCS_OS216_BINARY;
488 ret = TRUE;
489 break;
490 case BINARY_DOS:
491 *lpBinaryType = SCS_DOS_BINARY;
492 ret = TRUE;
493 break;
494 case BINARY_UNIX_EXE:
495 case BINARY_UNIX_LIB:
496 ret = FALSE;
497 break;
500 CloseHandle( hfile );
501 return ret;
504 /***********************************************************************
505 * GetBinaryTypeA [KERNEL32.@]
506 * GetBinaryType [KERNEL32.@]
508 * See GetBinaryTypeW.
510 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
512 ANSI_STRING app_nameA;
513 NTSTATUS status;
515 TRACE("%s\n", debugstr_a(lpApplicationName));
517 /* Sanity check.
519 if ( lpApplicationName == NULL || lpBinaryType == NULL )
520 return FALSE;
522 RtlInitAnsiString(&app_nameA, lpApplicationName);
523 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
524 &app_nameA, FALSE);
525 if (!status)
526 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
528 SetLastError(RtlNtStatusToDosError(status));
529 return FALSE;
532 /***********************************************************************
533 * GetModuleHandleExA (KERNEL32.@)
535 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
537 WCHAR *nameW;
539 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
540 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
542 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
543 return GetModuleHandleExW( flags, nameW, module );
546 /***********************************************************************
547 * GetModuleHandleExW (KERNEL32.@)
549 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
551 NTSTATUS status = STATUS_SUCCESS;
552 HMODULE ret;
553 ULONG_PTR magic;
554 BOOL lock;
556 if (!module)
558 SetLastError( ERROR_INVALID_PARAMETER );
559 return FALSE;
562 /* if we are messing with the refcount, grab the loader lock */
563 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
564 if (lock)
565 LdrLockLoaderLock( 0, NULL, &magic );
567 if (!name)
569 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
571 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
573 void *dummy;
574 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
576 else
578 UNICODE_STRING wstr;
579 RtlInitUnicodeString( &wstr, name );
580 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
583 if (status == STATUS_SUCCESS)
585 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
586 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
587 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
588 LdrAddRefDll( 0, ret );
590 else SetLastError( RtlNtStatusToDosError( status ) );
592 if (lock)
593 LdrUnlockLoaderLock( 0, magic );
595 if (status == STATUS_SUCCESS) *module = ret;
596 else *module = NULL;
598 return (status == STATUS_SUCCESS);
601 /***********************************************************************
602 * GetModuleHandleA (KERNEL32.@)
604 * Get the handle of a dll loaded into the process address space.
606 * PARAMS
607 * module [I] Name of the dll
609 * RETURNS
610 * Success: A handle to the loaded dll.
611 * Failure: A NULL handle. Use GetLastError() to determine the cause.
613 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
615 HMODULE ret;
617 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
618 return ret;
621 /***********************************************************************
622 * GetModuleHandleW (KERNEL32.@)
624 * Unicode version of GetModuleHandleA.
626 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
628 HMODULE ret;
630 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
631 return ret;
635 /***********************************************************************
636 * GetModuleFileNameA (KERNEL32.@)
638 * Get the file name of a loaded module from its handle.
640 * RETURNS
641 * Success: The length of the file name, excluding the terminating NUL.
642 * Failure: 0. Use GetLastError() to determine the cause.
644 * NOTES
645 * This function always returns the long path of hModule
646 * The function doesn't write a terminating '\0' if the buffer is too
647 * small.
649 DWORD WINAPI GetModuleFileNameA(
650 HMODULE hModule, /* [in] Module handle (32 bit) */
651 LPSTR lpFileName, /* [out] Destination for file name */
652 DWORD size ) /* [in] Size of lpFileName in characters */
654 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
655 DWORD len;
657 if (!filenameW)
659 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
660 return 0;
662 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
664 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
665 if (len < size)
666 lpFileName[len] = '\0';
667 else
668 SetLastError( ERROR_INSUFFICIENT_BUFFER );
670 HeapFree( GetProcessHeap(), 0, filenameW );
671 return len;
674 /***********************************************************************
675 * GetModuleFileNameW (KERNEL32.@)
677 * Unicode version of GetModuleFileNameA.
679 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
681 ULONG len = 0;
682 ULONG_PTR magic;
683 LDR_MODULE *pldr;
684 NTSTATUS nts;
685 WIN16_SUBSYSTEM_TIB *win16_tib;
687 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
689 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
690 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
691 if (len < size) lpFileName[len] = '\0';
692 goto done;
695 LdrLockLoaderLock( 0, NULL, &magic );
697 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
698 nts = LdrFindEntryForAddress( hModule, &pldr );
699 if (nts == STATUS_SUCCESS)
701 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
702 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
703 if (len < size)
705 lpFileName[len] = '\0';
706 SetLastError( 0 );
708 else
709 SetLastError( ERROR_INSUFFICIENT_BUFFER );
711 else SetLastError( RtlNtStatusToDosError( nts ) );
713 LdrUnlockLoaderLock( 0, magic );
714 done:
715 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
716 return len;
720 /***********************************************************************
721 * get_dll_system_path
723 static const WCHAR *get_dll_system_path(void)
725 static WCHAR *cached_path;
727 if (!cached_path)
729 WCHAR *p, *path;
730 int len = 3;
732 len += 2 * GetSystemDirectoryW( NULL, 0 );
733 len += GetWindowsDirectoryW( NULL, 0 );
734 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
735 *p++ = '.';
736 *p++ = ';';
737 GetSystemDirectoryW( p, path + len - p);
738 p += strlenW(p);
739 /* if system directory ends in "32" add 16-bit version too */
740 if (p[-2] == '3' && p[-1] == '2')
742 *p++ = ';';
743 GetSystemDirectoryW( p, path + len - p);
744 p += strlenW(p) - 2;
746 *p++ = ';';
747 GetWindowsDirectoryW( p, path + len - p);
748 cached_path = path;
750 return cached_path;
753 /******************************************************************
754 * get_module_path_end
756 * Returns the end of the directory component of the module path.
758 static inline const WCHAR *get_module_path_end(const WCHAR *module)
760 const WCHAR *p;
761 const WCHAR *mod_end = module;
762 if (!module) return mod_end;
764 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
765 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
766 if (mod_end == module + 2 && module[1] == ':') mod_end++;
767 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
769 return mod_end;
772 /******************************************************************
773 * MODULE_get_dll_load_path
775 * Compute the load path to use for a given dll.
776 * Returned pointer must be freed by caller.
778 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
780 static const WCHAR pathW[] = {'P','A','T','H',0};
782 const WCHAR *system_path = get_dll_system_path();
783 const WCHAR *mod_end = NULL;
784 UNICODE_STRING name, value;
785 WCHAR *p, *ret;
786 int len = 0, path_len = 0;
788 /* adjust length for module name */
790 if (module)
791 mod_end = get_module_path_end( module );
792 /* if module is NULL or doesn't contain a path, fall back to directory
793 * process was loaded from */
794 if (module == mod_end)
796 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
797 mod_end = get_module_path_end( module );
799 len += (mod_end - module) + 1;
801 len += strlenW( system_path ) + 2;
803 /* get the PATH variable */
805 RtlInitUnicodeString( &name, pathW );
806 value.Length = 0;
807 value.MaximumLength = 0;
808 value.Buffer = NULL;
809 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
810 path_len = value.Length;
812 RtlEnterCriticalSection( &dlldir_section );
813 if (dll_directory) len += strlenW(dll_directory) + 1;
814 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
816 if (module)
818 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
819 p += (mod_end - module);
820 *p++ = ';';
822 if (dll_directory)
824 strcpyW( p, dll_directory );
825 p += strlenW(p);
826 *p++ = ';';
829 RtlLeaveCriticalSection( &dlldir_section );
830 if (!ret) return NULL;
832 strcpyW( p, system_path );
833 p += strlenW(p);
834 *p++ = ';';
835 value.Buffer = p;
836 value.MaximumLength = path_len;
838 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
840 WCHAR *new_ptr;
842 /* grow the buffer and retry */
843 path_len = value.Length;
844 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
846 HeapFree( GetProcessHeap(), 0, ret );
847 return NULL;
849 value.Buffer = new_ptr + (value.Buffer - ret);
850 value.MaximumLength = path_len;
851 ret = new_ptr;
853 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
854 return ret;
858 /******************************************************************
859 * load_library_as_datafile
861 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
863 static const WCHAR dotDLL[] = {'.','d','l','l',0};
865 WCHAR filenameW[MAX_PATH];
866 HANDLE hFile = INVALID_HANDLE_VALUE;
867 HANDLE mapping;
868 HMODULE module;
870 *hmod = 0;
872 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
873 filenameW, NULL ))
875 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
876 NULL, OPEN_EXISTING, 0, 0 );
878 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
880 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
881 CloseHandle( hFile );
882 if (!mapping) return FALSE;
884 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
885 CloseHandle( mapping );
886 if (!module) return FALSE;
888 /* make sure it's a valid PE file */
889 if (!RtlImageNtHeader(module))
891 UnmapViewOfFile( module );
892 return FALSE;
894 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
895 return TRUE;
899 /******************************************************************
900 * load_library
902 * Helper for LoadLibraryExA/W.
904 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
906 NTSTATUS nts;
907 HMODULE hModule;
908 WCHAR *load_path;
909 static const DWORD unsupported_flags =
910 LOAD_IGNORE_CODE_AUTHZ_LEVEL |
911 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
912 LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE |
913 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET |
914 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
915 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
916 LOAD_LIBRARY_SEARCH_USER_DIRS |
917 LOAD_LIBRARY_SEARCH_SYSTEM32 |
918 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS;
920 if( flags & unsupported_flags)
921 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
923 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
925 if (flags & LOAD_LIBRARY_AS_DATAFILE)
927 ULONG_PTR magic;
929 LdrLockLoaderLock( 0, NULL, &magic );
930 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
932 LdrAddRefDll( 0, hModule );
933 LdrUnlockLoaderLock( 0, magic );
934 goto done;
936 LdrUnlockLoaderLock( 0, magic );
938 /* The method in load_library_as_datafile allows searching for the
939 * 'native' libraries only
941 if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
942 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
943 /* Fallback to normal behaviour */
946 nts = LdrLoadDll( load_path, flags, libname, &hModule );
947 if (nts != STATUS_SUCCESS)
949 hModule = 0;
950 SetLastError( RtlNtStatusToDosError( nts ) );
952 done:
953 HeapFree( GetProcessHeap(), 0, load_path );
954 return hModule;
958 /******************************************************************
959 * LoadLibraryExA (KERNEL32.@)
961 * Load a dll file into the process address space.
963 * PARAMS
964 * libname [I] Name of the file to load
965 * hfile [I] Reserved, must be 0.
966 * flags [I] Flags for loading the dll
968 * RETURNS
969 * Success: A handle to the loaded dll.
970 * Failure: A NULL handle. Use GetLastError() to determine the cause.
972 * NOTES
973 * The HFILE parameter is not used and marked reserved in the SDK. I can
974 * only guess that it should force a file to be mapped, but I rather
975 * ignore the parameter because it would be extremely difficult to
976 * integrate this with different types of module representations.
978 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
980 WCHAR *libnameW;
982 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
983 return LoadLibraryExW( libnameW, hfile, flags );
986 /***********************************************************************
987 * LoadLibraryExW (KERNEL32.@)
989 * Unicode version of LoadLibraryExA.
991 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
993 UNICODE_STRING wstr;
994 HMODULE res;
996 if (!libnameW)
998 SetLastError(ERROR_INVALID_PARAMETER);
999 return 0;
1001 RtlInitUnicodeString( &wstr, libnameW );
1002 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1003 return load_library( &wstr, flags );
1005 /* Library name has trailing spaces */
1006 RtlCreateUnicodeString( &wstr, libnameW );
1007 while (wstr.Length > sizeof(WCHAR) &&
1008 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1010 wstr.Length -= sizeof(WCHAR);
1012 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1013 res = load_library( &wstr, flags );
1014 RtlFreeUnicodeString( &wstr );
1015 return res;
1018 /***********************************************************************
1019 * LoadLibraryA (KERNEL32.@)
1021 * Load a dll file into the process address space.
1023 * PARAMS
1024 * libname [I] Name of the file to load
1026 * RETURNS
1027 * Success: A handle to the loaded dll.
1028 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1030 * NOTES
1031 * See LoadLibraryExA().
1033 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1035 return LoadLibraryExA(libname, 0, 0);
1038 /***********************************************************************
1039 * LoadLibraryW (KERNEL32.@)
1041 * Unicode version of LoadLibraryA.
1043 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1045 return LoadLibraryExW(libnameW, 0, 0);
1048 /***********************************************************************
1049 * FreeLibrary (KERNEL32.@)
1051 * Free a dll loaded into the process address space.
1053 * PARAMS
1054 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1056 * RETURNS
1057 * Success: TRUE. The dll is removed if it is not still in use.
1058 * Failure: FALSE. Use GetLastError() to determine the cause.
1060 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1062 BOOL retv = FALSE;
1063 NTSTATUS nts;
1065 if (!hLibModule)
1067 SetLastError( ERROR_INVALID_HANDLE );
1068 return FALSE;
1071 if ((ULONG_PTR)hLibModule & 1)
1073 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1074 char *ptr = (char *)hLibModule - 1;
1075 return UnmapViewOfFile( ptr );
1078 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1079 else SetLastError( RtlNtStatusToDosError( nts ) );
1081 return retv;
1084 /***********************************************************************
1085 * GetProcAddress (KERNEL32.@)
1087 * Find the address of an exported symbol in a loaded dll.
1089 * PARAMS
1090 * hModule [I] Handle to the dll returned by LoadLibraryA().
1091 * function [I] Name of the symbol, or an integer ordinal number < 16384
1093 * RETURNS
1094 * Success: A pointer to the symbol in the process address space.
1095 * Failure: NULL. Use GetLastError() to determine the cause.
1097 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1099 NTSTATUS nts;
1100 FARPROC fp;
1102 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1104 if ((ULONG_PTR)function >> 16)
1106 ANSI_STRING str;
1108 RtlInitAnsiString( &str, function );
1109 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1111 else
1112 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1113 if (nts != STATUS_SUCCESS)
1115 SetLastError( RtlNtStatusToDosError( nts ) );
1116 fp = NULL;
1118 return fp;
1121 /***********************************************************************
1122 * DelayLoadFailureHook (KERNEL32.@)
1124 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1126 ULONG_PTR args[2];
1128 if ((ULONG_PTR)function >> 16)
1129 ERR( "failed to delay load %s.%s\n", name, function );
1130 else
1131 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1132 args[0] = (ULONG_PTR)name;
1133 args[1] = (ULONG_PTR)function;
1134 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1135 return NULL;
1138 typedef struct {
1139 HANDLE process;
1140 PLIST_ENTRY head, current;
1141 LDR_MODULE ldr_module;
1142 } MODULE_ITERATOR;
1144 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1146 PROCESS_BASIC_INFORMATION pbi;
1147 PPEB_LDR_DATA ldr_data;
1148 NTSTATUS status;
1150 /* Get address of PEB */
1151 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1152 &pbi, sizeof(pbi), NULL);
1153 if (status != STATUS_SUCCESS)
1155 SetLastError(RtlNtStatusToDosError(status));
1156 return FALSE;
1159 /* Read address of LdrData from PEB */
1160 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1161 &ldr_data, sizeof(ldr_data), NULL))
1162 return FALSE;
1164 /* Read address of first module from LdrData */
1165 if (!ReadProcessMemory(process,
1166 &ldr_data->InLoadOrderModuleList.Flink,
1167 &iter->current, sizeof(iter->current), NULL))
1168 return FALSE;
1170 iter->head = &ldr_data->InLoadOrderModuleList;
1171 iter->process = process;
1173 return TRUE;
1176 static int module_iterator_next(MODULE_ITERATOR *iter)
1178 if (iter->current == iter->head)
1179 return 0;
1181 if (!ReadProcessMemory(iter->process,
1182 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1183 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1184 return -1;
1186 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1187 return 1;
1190 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1192 MODULE_ITERATOR iter;
1193 INT ret;
1195 if (!init_module_iterator(&iter, process))
1196 return FALSE;
1198 while ((ret = module_iterator_next(&iter)) > 0)
1199 /* When hModule is NULL we return the process image - which will be
1200 * the first module since our iterator uses InLoadOrderModuleList */
1201 if (!module || module == iter.ldr_module.BaseAddress)
1203 *ldr_module = iter.ldr_module;
1204 return TRUE;
1207 if (ret == 0)
1208 SetLastError(ERROR_INVALID_HANDLE);
1210 return FALSE;
1213 /***********************************************************************
1214 * K32EnumProcessModules (KERNEL32.@)
1216 * NOTES
1217 * Returned list is in load order.
1219 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1220 DWORD cb, DWORD *needed)
1222 MODULE_ITERATOR iter;
1223 INT ret;
1225 if (!init_module_iterator(&iter, process))
1226 return FALSE;
1228 if (!needed)
1230 SetLastError(ERROR_NOACCESS);
1231 return FALSE;
1234 *needed = 0;
1236 while ((ret = module_iterator_next(&iter)) > 0)
1238 if (cb >= sizeof(HMODULE))
1240 *lphModule++ = iter.ldr_module.BaseAddress;
1241 cb -= sizeof(HMODULE);
1243 *needed += sizeof(HMODULE);
1246 return ret == 0;
1249 /***********************************************************************
1250 * K32GetModuleBaseNameW (KERNEL32.@)
1252 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1253 LPWSTR base_name, DWORD size)
1255 LDR_MODULE ldr_module;
1257 if (!get_ldr_module(process, module, &ldr_module))
1258 return 0;
1260 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1261 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1262 base_name, size * sizeof(WCHAR), NULL))
1263 return 0;
1265 base_name[size] = 0;
1266 return size;
1269 /***********************************************************************
1270 * K32GetModuleBaseNameA (KERNEL32.@)
1272 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1273 LPSTR base_name, DWORD size)
1275 WCHAR *base_name_w;
1276 DWORD len, ret = 0;
1278 if(!base_name || !size) {
1279 SetLastError(ERROR_INVALID_PARAMETER);
1280 return 0;
1283 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1284 if(!base_name_w)
1285 return 0;
1287 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1288 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1289 if (len)
1291 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1292 base_name, size, NULL, NULL);
1293 if (ret < size) base_name[ret] = 0;
1295 HeapFree(GetProcessHeap(), 0, base_name_w);
1296 return ret;
1299 /***********************************************************************
1300 * K32GetModuleFileNameExW (KERNEL32.@)
1302 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1303 LPWSTR file_name, DWORD size)
1305 LDR_MODULE ldr_module;
1306 DWORD len;
1308 if (!size) return 0;
1310 if(!get_ldr_module(process, module, &ldr_module))
1311 return 0;
1313 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1314 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1315 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1316 return 0;
1318 if (len < size)
1320 file_name[len] = 0;
1321 return len;
1323 else
1325 file_name[size - 1] = 0;
1326 return size;
1330 /***********************************************************************
1331 * K32GetModuleFileNameExA (KERNEL32.@)
1333 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1334 LPSTR file_name, DWORD size)
1336 WCHAR *ptr;
1337 DWORD len;
1339 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1341 if (!file_name || !size)
1343 SetLastError( ERROR_INVALID_PARAMETER );
1344 return 0;
1347 if ( process == GetCurrentProcess() )
1349 len = GetModuleFileNameA( module, file_name, size );
1350 if (size) file_name[size - 1] = '\0';
1351 return len;
1354 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1356 len = K32GetModuleFileNameExW(process, module, ptr, size);
1357 if (!len)
1359 file_name[0] = '\0';
1361 else
1363 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1365 file_name[size - 1] = 0;
1366 len = size;
1368 else if (len < size) len = strlen( file_name );
1371 HeapFree(GetProcessHeap(), 0, ptr);
1372 return len;
1375 /***********************************************************************
1376 * K32GetModuleInformation (KERNEL32.@)
1378 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1379 MODULEINFO *modinfo, DWORD cb)
1381 LDR_MODULE ldr_module;
1383 if (cb < sizeof(MODULEINFO))
1385 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1386 return FALSE;
1389 if (!get_ldr_module(process, module, &ldr_module))
1390 return FALSE;
1392 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1393 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1394 modinfo->EntryPoint = ldr_module.EntryPoint;
1395 return TRUE;
1398 #ifdef __i386__
1400 /***********************************************************************
1401 * __wine_dll_register_16 (KERNEL32.@)
1403 * No longer used.
1405 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1407 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1411 /***********************************************************************
1412 * __wine_dll_unregister_16 (KERNEL32.@)
1414 * No longer used.
1416 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1420 #endif