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
22 #include "wine/port.h"
29 #include <sys/types.h>
34 #define WIN32_NO_STATUS
39 #include "kernel_private.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
)
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
);
78 len
++; /* for terminating null */
79 if (buffer
) *buffer
= 0;
81 RtlLeaveCriticalSection( &dlldir_section
);
86 /****************************************************************************
87 * GetDllDirectoryW (KERNEL32.@)
89 DWORD WINAPI
GetDllDirectoryW( DWORD buf_len
, LPWSTR buffer
)
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
) );
102 len
++; /* for terminating null */
103 if (buffer
) *buffer
= 0;
105 RtlLeaveCriticalSection( &dlldir_section
);
110 /****************************************************************************
111 * SetDllDirectoryA (KERNEL32.@)
113 BOOL WINAPI
SetDllDirectoryA( LPCSTR dir
)
118 if (!(dirW
= FILE_name_AtoW( dir
, TRUE
))) return FALSE
;
119 ret
= SetDllDirectoryW( dirW
);
120 HeapFree( GetProcessHeap(), 0, dirW
);
125 /****************************************************************************
126 * SetDllDirectoryW (KERNEL32.@)
128 BOOL WINAPI
SetDllDirectoryW( LPCWSTR dir
)
130 WCHAR
*newdir
= NULL
;
134 DWORD len
= (strlenW(dir
) + 1) * sizeof(WCHAR
);
135 if (!(newdir
= HeapAlloc( GetProcessHeap(), 0, len
)))
137 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
140 memcpy( newdir
, dir
, len
);
143 RtlEnterCriticalSection( &dlldir_section
);
144 HeapFree( GetProcessHeap(), 0, dll_directory
);
145 dll_directory
= newdir
;
146 RtlLeaveCriticalSection( &dlldir_section
);
151 /****************************************************************************
152 * DisableThreadLibraryCalls (KERNEL32.@)
154 * Inform the module loader that thread notifications are not required for a dll.
157 * hModule [I] Module handle to skip calls for
160 * Success: TRUE. Thread attach and detach notifications will not be sent
162 * Failure: FALSE. Use GetLastError() to determine the cause.
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
) );
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
;
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
)) )
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
) )
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");
220 ERR("Hmm, an error occurred. Is this binary file broken?\n");
223 HeapFree( GetProcessHeap(), 0, modtab
);
224 HeapFree( GetProcessHeap(), 0, nametab
);
225 SetFilePointer( hfile
, currpos
, NULL
, SEEK_SET
); /* restore filepos */
229 /***********************************************************************
230 * MODULE_GetBinaryType
232 void MODULE_get_binary_info( HANDLE hfile
, struct binary_info
*info
)
238 unsigned char magic
[4];
241 unsigned char version
;
242 unsigned char ignored
[9];
244 unsigned short machine
;
249 unsigned int cputype
;
250 unsigned int cpusubtype
;
251 unsigned int filetype
;
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)
270 if (header
.elf
.data
== 2)
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 ||
293 header
.macho
.magic
== 0xfeedfacf || header
.macho
.magic
== 0xcffaedfe)
295 if ((header
.macho
.cputype
>> 24) == 1) info
->flags
|= BINARY_FLAG_64BIT
;
296 if (header
.macho
.magic
== 0xcefaedfe || header
.macho
.magic
== 0xcffaedfe)
298 header
.macho
.filetype
= RtlUlongByteSwap( header
.macho
.filetype
);
299 header
.macho
.cputype
= RtlUlongByteSwap( header
.macho
.cputype
);
301 switch(header
.macho
.filetype
)
303 case 2: info
->type
= BINARY_UNIX_EXE
; break;
304 case 8: info
->type
= BINARY_UNIX_LIB
; break;
306 switch(header
.macho
.cputype
)
308 case 0x00000007: info
->arch
= IMAGE_FILE_MACHINE_I386
; break;
309 case 0x01000007: info
->arch
= IMAGE_FILE_MACHINE_AMD64
; break;
310 case 0x0000000c: info
->arch
= IMAGE_FILE_MACHINE_ARMNT
; break;
311 case 0x0100000c: info
->arch
= IMAGE_FILE_MACHINE_ARM64
; break;
312 case 0x00000012: info
->arch
= IMAGE_FILE_MACHINE_POWERPC
; break;
315 /* Not ELF, try DOS */
316 else if (header
.mz
.e_magic
== IMAGE_DOS_SIGNATURE
)
320 IMAGE_OS2_HEADER os2
;
321 IMAGE_NT_HEADERS32 nt
;
324 /* We do have a DOS image so we will now try to seek into
325 * the file by the amount indicated by the field
326 * "Offset to extended header" and read in the
327 * "magic" field information at that location.
328 * This will tell us if there is more header information
331 info
->type
= BINARY_DOS
;
332 info
->arch
= IMAGE_FILE_MACHINE_I386
;
333 if (SetFilePointer( hfile
, header
.mz
.e_lfanew
, NULL
, SEEK_SET
) == -1) return;
334 if (!ReadFile( hfile
, &ext_header
, sizeof(ext_header
), &len
, NULL
) || len
< 4) return;
336 /* Reading the magic field succeeded so
337 * we will try to determine what type it is.
339 if (!memcmp( &ext_header
.nt
.Signature
, "PE\0\0", 4 ))
341 if (len
>= sizeof(ext_header
.nt
.FileHeader
))
343 static const char fakedll_signature
[] = "Wine placeholder DLL";
344 char buffer
[sizeof(fakedll_signature
)];
346 info
->type
= BINARY_PE
;
347 info
->arch
= ext_header
.nt
.FileHeader
.Machine
;
348 if (ext_header
.nt
.FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
349 info
->flags
|= BINARY_FLAG_DLL
;
350 if (len
< sizeof(ext_header
.nt
)) /* clear remaining part of header if missing */
351 memset( (char *)&ext_header
.nt
+ len
, 0, sizeof(ext_header
.nt
) - len
);
352 switch (ext_header
.nt
.OptionalHeader
.Magic
)
354 case IMAGE_NT_OPTIONAL_HDR32_MAGIC
:
355 info
->res_start
= (void *)(ULONG_PTR
)ext_header
.nt
.OptionalHeader
.ImageBase
;
356 info
->res_end
= (void *)((ULONG_PTR
)ext_header
.nt
.OptionalHeader
.ImageBase
+
357 ext_header
.nt
.OptionalHeader
.SizeOfImage
);
359 case IMAGE_NT_OPTIONAL_HDR64_MAGIC
:
360 info
->flags
|= BINARY_FLAG_64BIT
;
364 if (header
.mz
.e_lfanew
>= sizeof(header
.mz
) + sizeof(fakedll_signature
) &&
365 SetFilePointer( hfile
, sizeof(header
.mz
), NULL
, SEEK_SET
) == sizeof(header
.mz
) &&
366 ReadFile( hfile
, buffer
, sizeof(fakedll_signature
), &len
, NULL
) &&
367 len
== sizeof(fakedll_signature
) &&
368 !memcmp( buffer
, fakedll_signature
, sizeof(fakedll_signature
) ))
370 info
->flags
|= BINARY_FLAG_FAKEDLL
;
374 else if (!memcmp( &ext_header
.os2
.ne_magic
, "NE", 2 ))
376 /* This is a Windows executable (NE) header. This can
377 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
378 * DOS program (running under a DOS extender). To decide
379 * which, we'll have to read the NE header.
381 if (len
>= sizeof(ext_header
.os2
))
383 if (ext_header
.os2
.ne_flags
& NE_FFLAGS_LIBMODULE
) info
->flags
|= BINARY_FLAG_DLL
;
384 switch ( ext_header
.os2
.ne_exetyp
)
386 case 1: info
->type
= BINARY_OS216
; break; /* OS/2 */
387 case 2: info
->type
= BINARY_WIN16
; break; /* Windows */
388 case 3: info
->type
= BINARY_DOS
; break; /* European MS-DOS 4.x */
389 case 4: info
->type
= BINARY_WIN16
; break; /* Windows 386; FIXME: is this 32bit??? */
390 case 5: info
->type
= BINARY_DOS
; break; /* BOSS, Borland Operating System Services */
391 /* other types, e.g. 0 is: "unknown" */
392 default: info
->type
= MODULE_Decide_OS2_OldWin(hfile
, &header
.mz
, &ext_header
.os2
); break;
399 /***********************************************************************
400 * GetBinaryTypeW [KERNEL32.@]
402 * Determine whether a file is executable, and if so, what kind.
405 * lpApplicationName [I] Path of the file to check
406 * lpBinaryType [O] Destination for the binary type
409 * TRUE, if the file is an executable, in which case lpBinaryType is set.
410 * FALSE, if the file is not an executable or if the function fails.
413 * The type of executable is a property that determines which subsystem an
414 * executable file runs under. lpBinaryType can be set to one of the following
416 * SCS_32BIT_BINARY: A Win32 based application
417 * SCS_64BIT_BINARY: A Win64 based application
418 * SCS_DOS_BINARY: An MS-Dos based application
419 * SCS_WOW_BINARY: A Win16 based application
420 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
421 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
422 * SCS_OS216_BINARY: A 16bit OS/2 based application
424 * To find the binary type, this function reads in the files header information.
425 * If extended header information is not present it will assume that the file
426 * is a DOS executable. If extended header information is present it will
427 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
428 * flags in the header.
430 * ".com" and ".pif" files are only recognized by their file name extension,
431 * as per native Windows.
433 BOOL WINAPI
GetBinaryTypeW( LPCWSTR lpApplicationName
, LPDWORD lpBinaryType
)
437 struct binary_info binary_info
;
439 TRACE("%s\n", debugstr_w(lpApplicationName
) );
443 if ( lpApplicationName
== NULL
|| lpBinaryType
== NULL
)
446 /* Open the file indicated by lpApplicationName for reading.
448 hfile
= CreateFileW( lpApplicationName
, GENERIC_READ
, FILE_SHARE_READ
,
449 NULL
, OPEN_EXISTING
, 0, 0 );
450 if ( hfile
== INVALID_HANDLE_VALUE
)
455 MODULE_get_binary_info( hfile
, &binary_info
);
456 switch (binary_info
.type
)
460 static const WCHAR comW
[] = { '.','C','O','M',0 };
461 static const WCHAR pifW
[] = { '.','P','I','F',0 };
464 /* try to determine from file name */
465 ptr
= strrchrW( lpApplicationName
, '.' );
467 if (!strcmpiW( ptr
, comW
))
469 *lpBinaryType
= SCS_DOS_BINARY
;
472 else if (!strcmpiW( ptr
, pifW
))
474 *lpBinaryType
= SCS_PIF_BINARY
;
480 *lpBinaryType
= (binary_info
.flags
& BINARY_FLAG_64BIT
) ? SCS_64BIT_BINARY
: SCS_32BIT_BINARY
;
484 *lpBinaryType
= SCS_WOW_BINARY
;
488 *lpBinaryType
= SCS_OS216_BINARY
;
492 *lpBinaryType
= SCS_DOS_BINARY
;
495 case BINARY_UNIX_EXE
:
496 case BINARY_UNIX_LIB
:
501 CloseHandle( hfile
);
505 /***********************************************************************
506 * GetBinaryTypeA [KERNEL32.@]
507 * GetBinaryType [KERNEL32.@]
509 * See GetBinaryTypeW.
511 BOOL WINAPI
GetBinaryTypeA( LPCSTR lpApplicationName
, LPDWORD lpBinaryType
)
513 ANSI_STRING app_nameA
;
516 TRACE("%s\n", debugstr_a(lpApplicationName
));
520 if ( lpApplicationName
== NULL
|| lpBinaryType
== NULL
)
523 RtlInitAnsiString(&app_nameA
, lpApplicationName
);
524 status
= RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString
,
527 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString
.Buffer
, lpBinaryType
);
529 SetLastError(RtlNtStatusToDosError(status
));
533 /***********************************************************************
534 * GetModuleHandleExA (KERNEL32.@)
536 BOOL WINAPI
GetModuleHandleExA( DWORD flags
, LPCSTR name
, HMODULE
*module
)
540 if (!name
|| (flags
& GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
))
541 return GetModuleHandleExW( flags
, (LPCWSTR
)name
, module
);
543 if (!(nameW
= FILE_name_AtoW( name
, FALSE
))) return FALSE
;
544 return GetModuleHandleExW( flags
, nameW
, module
);
547 /***********************************************************************
548 * GetModuleHandleExW (KERNEL32.@)
550 BOOL WINAPI
GetModuleHandleExW( DWORD flags
, LPCWSTR name
, HMODULE
*module
)
552 NTSTATUS status
= STATUS_SUCCESS
;
559 SetLastError( ERROR_INVALID_PARAMETER
);
563 /* if we are messing with the refcount, grab the loader lock */
564 lock
= (flags
& GET_MODULE_HANDLE_EX_FLAG_PIN
) || !(flags
& GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
);
566 LdrLockLoaderLock( 0, NULL
, &magic
);
570 ret
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
572 else if (flags
& GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
)
575 if (!(ret
= RtlPcToFileHeader( (void *)name
, &dummy
))) status
= STATUS_DLL_NOT_FOUND
;
580 RtlInitUnicodeString( &wstr
, name
);
581 status
= LdrGetDllHandle( NULL
, 0, &wstr
, &ret
);
584 if (status
== STATUS_SUCCESS
)
586 if (flags
& GET_MODULE_HANDLE_EX_FLAG_PIN
)
587 LdrAddRefDll( LDR_ADDREF_DLL_PIN
, ret
);
588 else if (!(flags
& GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
))
589 LdrAddRefDll( 0, ret
);
591 else SetLastError( RtlNtStatusToDosError( status
) );
594 LdrUnlockLoaderLock( 0, magic
);
596 if (status
== STATUS_SUCCESS
) *module
= ret
;
599 return (status
== STATUS_SUCCESS
);
602 /***********************************************************************
603 * GetModuleHandleA (KERNEL32.@)
605 * Get the handle of a dll loaded into the process address space.
608 * module [I] Name of the dll
611 * Success: A handle to the loaded dll.
612 * Failure: A NULL handle. Use GetLastError() to determine the cause.
614 HMODULE WINAPI DECLSPEC_HOTPATCH
GetModuleHandleA(LPCSTR module
)
618 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
, module
, &ret
);
622 /***********************************************************************
623 * GetModuleHandleW (KERNEL32.@)
625 * Unicode version of GetModuleHandleA.
627 HMODULE WINAPI
GetModuleHandleW(LPCWSTR module
)
631 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
, module
, &ret
);
636 /***********************************************************************
637 * GetModuleFileNameA (KERNEL32.@)
639 * Get the file name of a loaded module from its handle.
642 * Success: The length of the file name, excluding the terminating NUL.
643 * Failure: 0. Use GetLastError() to determine the cause.
646 * This function always returns the long path of hModule
647 * The function doesn't write a terminating '\0' if the buffer is too
650 DWORD WINAPI
GetModuleFileNameA(
651 HMODULE hModule
, /* [in] Module handle (32 bit) */
652 LPSTR lpFileName
, /* [out] Destination for file name */
653 DWORD size
) /* [in] Size of lpFileName in characters */
655 LPWSTR filenameW
= HeapAlloc( GetProcessHeap(), 0, size
* sizeof(WCHAR
) );
660 SetLastError( ERROR_NOT_ENOUGH_MEMORY
);
663 if ((len
= GetModuleFileNameW( hModule
, filenameW
, size
)))
665 len
= FILE_name_WtoA( filenameW
, len
, lpFileName
, size
);
667 lpFileName
[len
] = '\0';
669 SetLastError( ERROR_INSUFFICIENT_BUFFER
);
671 HeapFree( GetProcessHeap(), 0, filenameW
);
675 /***********************************************************************
676 * GetModuleFileNameW (KERNEL32.@)
678 * Unicode version of GetModuleFileNameA.
680 DWORD WINAPI
GetModuleFileNameW( HMODULE hModule
, LPWSTR lpFileName
, DWORD size
)
686 WIN16_SUBSYSTEM_TIB
*win16_tib
;
688 if (!hModule
&& ((win16_tib
= NtCurrentTeb()->Tib
.SubSystemTib
)) && win16_tib
->exe_name
)
690 len
= min(size
, win16_tib
->exe_name
->Length
/ sizeof(WCHAR
));
691 memcpy( lpFileName
, win16_tib
->exe_name
->Buffer
, len
* sizeof(WCHAR
) );
692 if (len
< size
) lpFileName
[len
] = '\0';
696 LdrLockLoaderLock( 0, NULL
, &magic
);
698 if (!hModule
) hModule
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
699 nts
= LdrFindEntryForAddress( hModule
, &pldr
);
700 if (nts
== STATUS_SUCCESS
)
702 len
= min(size
, pldr
->FullDllName
.Length
/ sizeof(WCHAR
));
703 memcpy(lpFileName
, pldr
->FullDllName
.Buffer
, len
* sizeof(WCHAR
));
706 lpFileName
[len
] = '\0';
710 SetLastError( ERROR_INSUFFICIENT_BUFFER
);
712 else SetLastError( RtlNtStatusToDosError( nts
) );
714 LdrUnlockLoaderLock( 0, magic
);
716 TRACE( "%s\n", debugstr_wn(lpFileName
, len
) );
721 /***********************************************************************
722 * get_dll_system_path
724 static const WCHAR
*get_dll_system_path(void)
726 static WCHAR
*cached_path
;
733 len
+= 2 * GetSystemDirectoryW( NULL
, 0 );
734 len
+= GetWindowsDirectoryW( NULL
, 0 );
735 p
= path
= HeapAlloc( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
738 GetSystemDirectoryW( p
, path
+ len
- p
);
740 /* if system directory ends in "32" add 16-bit version too */
741 if (p
[-2] == '3' && p
[-1] == '2')
744 GetSystemDirectoryW( p
, path
+ len
- p
);
748 GetWindowsDirectoryW( p
, path
+ len
- p
);
754 /******************************************************************
755 * get_module_path_end
757 * Returns the end of the directory component of the module path.
759 static inline const WCHAR
*get_module_path_end(const WCHAR
*module
)
762 const WCHAR
*mod_end
= module
;
763 if (!module
) return mod_end
;
765 if ((p
= strrchrW( mod_end
, '\\' ))) mod_end
= p
;
766 if ((p
= strrchrW( mod_end
, '/' ))) mod_end
= p
;
767 if (mod_end
== module
+ 2 && module
[1] == ':') mod_end
++;
768 if (mod_end
== module
&& module
[0] && module
[1] == ':') mod_end
+= 2;
773 /******************************************************************
774 * MODULE_get_dll_load_path
776 * Compute the load path to use for a given dll.
777 * Returned pointer must be freed by caller.
779 WCHAR
*MODULE_get_dll_load_path( LPCWSTR module
)
781 static const WCHAR pathW
[] = {'P','A','T','H',0};
783 const WCHAR
*system_path
= get_dll_system_path();
784 const WCHAR
*mod_end
= NULL
;
785 UNICODE_STRING name
, value
;
787 int len
= 0, path_len
= 0;
789 /* adjust length for module name */
792 mod_end
= get_module_path_end( module
);
793 /* if module is NULL or doesn't contain a path, fall back to directory
794 * process was loaded from */
795 if (module
== mod_end
)
797 module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
798 mod_end
= get_module_path_end( module
);
800 len
+= (mod_end
- module
) + 1;
802 len
+= strlenW( system_path
) + 2;
804 /* get the PATH variable */
806 RtlInitUnicodeString( &name
, pathW
);
808 value
.MaximumLength
= 0;
810 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
811 path_len
= value
.Length
;
813 RtlEnterCriticalSection( &dlldir_section
);
814 if (dll_directory
) len
+= strlenW(dll_directory
) + 1;
815 if ((p
= ret
= HeapAlloc( GetProcessHeap(), 0, path_len
+ len
* sizeof(WCHAR
) )))
819 memcpy( ret
, module
, (mod_end
- module
) * sizeof(WCHAR
) );
820 p
+= (mod_end
- module
);
825 strcpyW( p
, dll_directory
);
830 RtlLeaveCriticalSection( &dlldir_section
);
831 if (!ret
) return NULL
;
833 strcpyW( p
, system_path
);
837 value
.MaximumLength
= path_len
;
839 while (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
843 /* grow the buffer and retry */
844 path_len
= value
.Length
;
845 if (!(new_ptr
= HeapReAlloc( GetProcessHeap(), 0, ret
, path_len
+ len
* sizeof(WCHAR
) )))
847 HeapFree( GetProcessHeap(), 0, ret
);
850 value
.Buffer
= new_ptr
+ (value
.Buffer
- ret
);
851 value
.MaximumLength
= path_len
;
854 value
.Buffer
[value
.Length
/ sizeof(WCHAR
)] = 0;
859 /******************************************************************
860 * load_library_as_datafile
862 static BOOL
load_library_as_datafile( LPCWSTR name
, HMODULE
* hmod
)
864 static const WCHAR dotDLL
[] = {'.','d','l','l',0};
866 WCHAR filenameW
[MAX_PATH
];
867 HANDLE hFile
= INVALID_HANDLE_VALUE
;
873 if (SearchPathW( NULL
, name
, dotDLL
, sizeof(filenameW
) / sizeof(filenameW
[0]),
876 hFile
= CreateFileW( filenameW
, GENERIC_READ
, FILE_SHARE_READ
,
877 NULL
, OPEN_EXISTING
, 0, 0 );
879 if (hFile
== INVALID_HANDLE_VALUE
) return FALSE
;
881 mapping
= CreateFileMappingW( hFile
, NULL
, PAGE_READONLY
, 0, 0, NULL
);
882 CloseHandle( hFile
);
883 if (!mapping
) return FALSE
;
885 module
= MapViewOfFile( mapping
, FILE_MAP_READ
, 0, 0, 0 );
886 CloseHandle( mapping
);
887 if (!module
) return FALSE
;
889 /* make sure it's a valid PE file */
890 if (!RtlImageNtHeader(module
))
892 UnmapViewOfFile( module
);
895 *hmod
= (HMODULE
)((char *)module
+ 1); /* set low bit of handle to indicate datafile module */
900 /******************************************************************
903 * Helper for LoadLibraryExA/W.
905 static HMODULE
load_library( const UNICODE_STRING
*libname
, DWORD flags
)
910 static const DWORD unsupported_flags
=
911 LOAD_IGNORE_CODE_AUTHZ_LEVEL
|
912 LOAD_LIBRARY_AS_IMAGE_RESOURCE
|
913 LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE
|
914 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET
|
915 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
|
916 LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
917 LOAD_LIBRARY_SEARCH_USER_DIRS
|
918 LOAD_LIBRARY_SEARCH_SYSTEM32
|
919 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
;
921 if( flags
& unsupported_flags
)
922 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags
);
924 load_path
= MODULE_get_dll_load_path( flags
& LOAD_WITH_ALTERED_SEARCH_PATH
? libname
->Buffer
: NULL
);
926 if (flags
& LOAD_LIBRARY_AS_DATAFILE
)
930 LdrLockLoaderLock( 0, NULL
, &magic
);
931 if (!LdrGetDllHandle( load_path
, flags
, libname
, &hModule
))
933 LdrAddRefDll( 0, hModule
);
934 LdrUnlockLoaderLock( 0, magic
);
937 LdrUnlockLoaderLock( 0, magic
);
939 /* The method in load_library_as_datafile allows searching for the
940 * 'native' libraries only
942 if (load_library_as_datafile( libname
->Buffer
, &hModule
)) goto done
;
943 flags
|= DONT_RESOLVE_DLL_REFERENCES
; /* Just in case */
944 /* Fallback to normal behaviour */
947 nts
= LdrLoadDll( load_path
, flags
, libname
, &hModule
);
948 if (nts
!= STATUS_SUCCESS
)
951 if (nts
== STATUS_DLL_NOT_FOUND
&& (GetVersion() & 0x80000000))
952 SetLastError( ERROR_DLL_NOT_FOUND
);
954 SetLastError( RtlNtStatusToDosError( nts
) );
957 HeapFree( GetProcessHeap(), 0, load_path
);
962 /******************************************************************
963 * LoadLibraryExA (KERNEL32.@)
965 * Load a dll file into the process address space.
968 * libname [I] Name of the file to load
969 * hfile [I] Reserved, must be 0.
970 * flags [I] Flags for loading the dll
973 * Success: A handle to the loaded dll.
974 * Failure: A NULL handle. Use GetLastError() to determine the cause.
977 * The HFILE parameter is not used and marked reserved in the SDK. I can
978 * only guess that it should force a file to be mapped, but I rather
979 * ignore the parameter because it would be extremely difficult to
980 * integrate this with different types of module representations.
982 HMODULE WINAPI DECLSPEC_HOTPATCH
LoadLibraryExA(LPCSTR libname
, HANDLE hfile
, DWORD flags
)
986 if (!(libnameW
= FILE_name_AtoW( libname
, FALSE
))) return 0;
987 return LoadLibraryExW( libnameW
, hfile
, flags
);
990 /***********************************************************************
991 * LoadLibraryExW (KERNEL32.@)
993 * Unicode version of LoadLibraryExA.
995 HMODULE WINAPI DECLSPEC_HOTPATCH
LoadLibraryExW(LPCWSTR libnameW
, HANDLE hfile
, DWORD flags
)
1002 SetLastError(ERROR_INVALID_PARAMETER
);
1005 RtlInitUnicodeString( &wstr
, libnameW
);
1006 if (wstr
.Buffer
[wstr
.Length
/sizeof(WCHAR
) - 1] != ' ')
1007 return load_library( &wstr
, flags
);
1009 /* Library name has trailing spaces */
1010 RtlCreateUnicodeString( &wstr
, libnameW
);
1011 while (wstr
.Length
> sizeof(WCHAR
) &&
1012 wstr
.Buffer
[wstr
.Length
/sizeof(WCHAR
) - 1] == ' ')
1014 wstr
.Length
-= sizeof(WCHAR
);
1016 wstr
.Buffer
[wstr
.Length
/sizeof(WCHAR
)] = '\0';
1017 res
= load_library( &wstr
, flags
);
1018 RtlFreeUnicodeString( &wstr
);
1022 /***********************************************************************
1023 * LoadLibraryA (KERNEL32.@)
1025 * Load a dll file into the process address space.
1028 * libname [I] Name of the file to load
1031 * Success: A handle to the loaded dll.
1032 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1035 * See LoadLibraryExA().
1037 HMODULE WINAPI DECLSPEC_HOTPATCH
LoadLibraryA(LPCSTR libname
)
1039 return LoadLibraryExA(libname
, 0, 0);
1042 /***********************************************************************
1043 * LoadLibraryW (KERNEL32.@)
1045 * Unicode version of LoadLibraryA.
1047 HMODULE WINAPI DECLSPEC_HOTPATCH
LoadLibraryW(LPCWSTR libnameW
)
1049 return LoadLibraryExW(libnameW
, 0, 0);
1052 /***********************************************************************
1053 * FreeLibrary (KERNEL32.@)
1055 * Free a dll loaded into the process address space.
1058 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1061 * Success: TRUE. The dll is removed if it is not still in use.
1062 * Failure: FALSE. Use GetLastError() to determine the cause.
1064 BOOL WINAPI DECLSPEC_HOTPATCH
FreeLibrary(HINSTANCE hLibModule
)
1071 SetLastError( ERROR_INVALID_HANDLE
);
1075 if ((ULONG_PTR
)hLibModule
& 1)
1077 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1078 char *ptr
= (char *)hLibModule
- 1;
1079 return UnmapViewOfFile( ptr
);
1082 if ((nts
= LdrUnloadDll( hLibModule
)) == STATUS_SUCCESS
) retv
= TRUE
;
1083 else SetLastError( RtlNtStatusToDosError( nts
) );
1088 /***********************************************************************
1089 * GetProcAddress (KERNEL32.@)
1091 * Find the address of an exported symbol in a loaded dll.
1094 * hModule [I] Handle to the dll returned by LoadLibraryA().
1095 * function [I] Name of the symbol, or an integer ordinal number < 16384
1098 * Success: A pointer to the symbol in the process address space.
1099 * Failure: NULL. Use GetLastError() to determine the cause.
1101 FARPROC WINAPI
GetProcAddress( HMODULE hModule
, LPCSTR function
)
1106 if (!hModule
) hModule
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
1108 if ((ULONG_PTR
)function
>> 16)
1112 RtlInitAnsiString( &str
, function
);
1113 nts
= LdrGetProcedureAddress( hModule
, &str
, 0, (void**)&fp
);
1116 nts
= LdrGetProcedureAddress( hModule
, NULL
, LOWORD(function
), (void**)&fp
);
1117 if (nts
!= STATUS_SUCCESS
)
1119 SetLastError( RtlNtStatusToDosError( nts
) );
1125 /***********************************************************************
1126 * DelayLoadFailureHook (KERNEL32.@)
1128 FARPROC WINAPI
DelayLoadFailureHook( LPCSTR name
, LPCSTR function
)
1132 if ((ULONG_PTR
)function
>> 16)
1133 ERR( "failed to delay load %s.%s\n", name
, function
);
1135 ERR( "failed to delay load %s.%u\n", name
, LOWORD(function
) );
1136 args
[0] = (ULONG_PTR
)name
;
1137 args
[1] = (ULONG_PTR
)function
;
1138 RaiseException( EXCEPTION_WINE_STUB
, EH_NONCONTINUABLE
, 2, args
);
1144 PLIST_ENTRY head
, current
;
1145 LDR_MODULE ldr_module
;
1148 static BOOL
init_module_iterator(MODULE_ITERATOR
*iter
, HANDLE process
)
1150 PROCESS_BASIC_INFORMATION pbi
;
1151 PPEB_LDR_DATA ldr_data
;
1154 /* Get address of PEB */
1155 status
= NtQueryInformationProcess(process
, ProcessBasicInformation
,
1156 &pbi
, sizeof(pbi
), NULL
);
1157 if (status
!= STATUS_SUCCESS
)
1159 SetLastError(RtlNtStatusToDosError(status
));
1163 /* Read address of LdrData from PEB */
1164 if (!ReadProcessMemory(process
, &pbi
.PebBaseAddress
->LdrData
,
1165 &ldr_data
, sizeof(ldr_data
), NULL
))
1168 /* Read address of first module from LdrData */
1169 if (!ReadProcessMemory(process
,
1170 &ldr_data
->InLoadOrderModuleList
.Flink
,
1171 &iter
->current
, sizeof(iter
->current
), NULL
))
1174 iter
->head
= &ldr_data
->InLoadOrderModuleList
;
1175 iter
->process
= process
;
1180 static int module_iterator_next(MODULE_ITERATOR
*iter
)
1182 if (iter
->current
== iter
->head
)
1185 if (!ReadProcessMemory(iter
->process
,
1186 CONTAINING_RECORD(iter
->current
, LDR_MODULE
, InLoadOrderModuleList
),
1187 &iter
->ldr_module
, sizeof(iter
->ldr_module
), NULL
))
1190 iter
->current
= iter
->ldr_module
.InLoadOrderModuleList
.Flink
;
1194 static BOOL
get_ldr_module(HANDLE process
, HMODULE module
, LDR_MODULE
*ldr_module
)
1196 MODULE_ITERATOR iter
;
1199 if (!init_module_iterator(&iter
, process
))
1202 while ((ret
= module_iterator_next(&iter
)) > 0)
1203 /* When hModule is NULL we return the process image - which will be
1204 * the first module since our iterator uses InLoadOrderModuleList */
1205 if (!module
|| module
== iter
.ldr_module
.BaseAddress
)
1207 *ldr_module
= iter
.ldr_module
;
1212 SetLastError(ERROR_INVALID_HANDLE
);
1217 /***********************************************************************
1218 * K32EnumProcessModules (KERNEL32.@)
1221 * Returned list is in load order.
1223 BOOL WINAPI
K32EnumProcessModules(HANDLE process
, HMODULE
*lphModule
,
1224 DWORD cb
, DWORD
*needed
)
1226 MODULE_ITERATOR iter
;
1229 if (!init_module_iterator(&iter
, process
))
1232 if ((cb
&& !lphModule
) || !needed
)
1234 SetLastError(ERROR_NOACCESS
);
1240 while ((ret
= module_iterator_next(&iter
)) > 0)
1242 if (cb
>= sizeof(HMODULE
))
1244 *lphModule
++ = iter
.ldr_module
.BaseAddress
;
1245 cb
-= sizeof(HMODULE
);
1247 *needed
+= sizeof(HMODULE
);
1253 /***********************************************************************
1254 * K32EnumProcessModulesEx (KERNEL32.@)
1257 * Returned list is in load order.
1259 BOOL WINAPI
K32EnumProcessModulesEx(HANDLE process
, HMODULE
*lphModule
,
1260 DWORD cb
, DWORD
*needed
, DWORD filter
)
1262 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1263 process
, lphModule
, cb
, needed
, filter
);
1264 return K32EnumProcessModules(process
, lphModule
, cb
, needed
);
1267 /***********************************************************************
1268 * K32GetModuleBaseNameW (KERNEL32.@)
1270 DWORD WINAPI
K32GetModuleBaseNameW(HANDLE process
, HMODULE module
,
1271 LPWSTR base_name
, DWORD size
)
1273 LDR_MODULE ldr_module
;
1275 if (!get_ldr_module(process
, module
, &ldr_module
))
1278 size
= min(ldr_module
.BaseDllName
.Length
/ sizeof(WCHAR
), size
);
1279 if (!ReadProcessMemory(process
, ldr_module
.BaseDllName
.Buffer
,
1280 base_name
, size
* sizeof(WCHAR
), NULL
))
1283 base_name
[size
] = 0;
1287 /***********************************************************************
1288 * K32GetModuleBaseNameA (KERNEL32.@)
1290 DWORD WINAPI
K32GetModuleBaseNameA(HANDLE process
, HMODULE module
,
1291 LPSTR base_name
, DWORD size
)
1296 if(!base_name
|| !size
) {
1297 SetLastError(ERROR_INVALID_PARAMETER
);
1301 base_name_w
= HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR
) * size
);
1305 len
= K32GetModuleBaseNameW(process
, module
, base_name_w
, size
);
1306 TRACE("%d, %s\n", len
, debugstr_w(base_name_w
));
1309 ret
= WideCharToMultiByte(CP_ACP
, 0, base_name_w
, len
,
1310 base_name
, size
, NULL
, NULL
);
1311 if (ret
< size
) base_name
[ret
] = 0;
1313 HeapFree(GetProcessHeap(), 0, base_name_w
);
1317 /***********************************************************************
1318 * K32GetModuleFileNameExW (KERNEL32.@)
1320 DWORD WINAPI
K32GetModuleFileNameExW(HANDLE process
, HMODULE module
,
1321 LPWSTR file_name
, DWORD size
)
1323 LDR_MODULE ldr_module
;
1326 if (!size
) return 0;
1328 if(!get_ldr_module(process
, module
, &ldr_module
))
1331 len
= ldr_module
.FullDllName
.Length
/ sizeof(WCHAR
);
1332 if (!ReadProcessMemory(process
, ldr_module
.FullDllName
.Buffer
,
1333 file_name
, min( len
, size
) * sizeof(WCHAR
), NULL
))
1343 file_name
[size
- 1] = 0;
1348 /***********************************************************************
1349 * K32GetModuleFileNameExA (KERNEL32.@)
1351 DWORD WINAPI
K32GetModuleFileNameExA(HANDLE process
, HMODULE module
,
1352 LPSTR file_name
, DWORD size
)
1357 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process
, module
, file_name
, size
);
1359 if (!file_name
|| !size
)
1361 SetLastError( ERROR_INVALID_PARAMETER
);
1365 if ( process
== GetCurrentProcess() )
1367 len
= GetModuleFileNameA( module
, file_name
, size
);
1368 if (size
) file_name
[size
- 1] = '\0';
1372 if (!(ptr
= HeapAlloc(GetProcessHeap(), 0, size
* sizeof(WCHAR
)))) return 0;
1374 len
= K32GetModuleFileNameExW(process
, module
, ptr
, size
);
1377 file_name
[0] = '\0';
1381 if (!WideCharToMultiByte( CP_ACP
, 0, ptr
, -1, file_name
, size
, NULL
, NULL
))
1383 file_name
[size
- 1] = 0;
1386 else if (len
< size
) len
= strlen( file_name
);
1389 HeapFree(GetProcessHeap(), 0, ptr
);
1393 /***********************************************************************
1394 * K32GetModuleInformation (KERNEL32.@)
1396 BOOL WINAPI
K32GetModuleInformation(HANDLE process
, HMODULE module
,
1397 MODULEINFO
*modinfo
, DWORD cb
)
1399 LDR_MODULE ldr_module
;
1401 if (cb
< sizeof(MODULEINFO
))
1403 SetLastError(ERROR_INSUFFICIENT_BUFFER
);
1407 if (!get_ldr_module(process
, module
, &ldr_module
))
1410 modinfo
->lpBaseOfDll
= ldr_module
.BaseAddress
;
1411 modinfo
->SizeOfImage
= ldr_module
.SizeOfImage
;
1412 modinfo
->EntryPoint
= ldr_module
.EntryPoint
;
1418 /***********************************************************************
1419 * __wine_dll_register_16 (KERNEL32.@)
1423 void __wine_dll_register_16( const IMAGE_DOS_HEADER
*header
, const char *file_name
)
1425 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name
);
1429 /***********************************************************************
1430 * __wine_dll_unregister_16 (KERNEL32.@)
1434 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER
*header
)