kernel32: Remove the DOS/Win16/OS2 binary distinction.
[wine.git] / dlls / kernel32 / module.c
blobf03b498847920618ae3bb95b951395e51c79448b
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/list.h"
44 #include "wine/debug.h"
45 #include "wine/unicode.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 #define NE_FFLAGS_LIBMODULE 0x8000
51 struct dll_dir_entry
53 struct list entry;
54 WCHAR dir[1];
57 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from AddDllDirectory */
58 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
59 static DWORD default_search_flags; /* default flags set by SetDefaultDllDirectories */
61 /* to keep track of LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE file handles */
62 struct exclusive_datafile
64 struct list entry;
65 HMODULE module;
66 HANDLE file;
68 static struct list exclusive_datafile_list = LIST_INIT( exclusive_datafile_list );
70 static CRITICAL_SECTION dlldir_section;
71 static CRITICAL_SECTION_DEBUG critsect_debug =
73 0, 0, &dlldir_section,
74 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
75 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
77 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
79 /****************************************************************************
80 * GetDllDirectoryA (KERNEL32.@)
82 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
84 DWORD len;
86 RtlEnterCriticalSection( &dlldir_section );
87 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
88 if (buffer && buf_len > len)
90 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
91 else *buffer = 0;
93 else
95 len++; /* for terminating null */
96 if (buffer) *buffer = 0;
98 RtlLeaveCriticalSection( &dlldir_section );
99 return len;
103 /****************************************************************************
104 * GetDllDirectoryW (KERNEL32.@)
106 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
108 DWORD len;
110 RtlEnterCriticalSection( &dlldir_section );
111 len = dll_directory ? strlenW( dll_directory ) : 0;
112 if (buffer && buf_len > len)
114 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
115 else *buffer = 0;
117 else
119 len++; /* for terminating null */
120 if (buffer) *buffer = 0;
122 RtlLeaveCriticalSection( &dlldir_section );
123 return len;
127 /****************************************************************************
128 * SetDllDirectoryA (KERNEL32.@)
130 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
132 WCHAR *dirW;
133 BOOL ret;
135 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
136 ret = SetDllDirectoryW( dirW );
137 HeapFree( GetProcessHeap(), 0, dirW );
138 return ret;
142 /****************************************************************************
143 * SetDllDirectoryW (KERNEL32.@)
145 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
147 WCHAR *newdir = NULL;
149 if (dir)
151 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
152 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
154 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
155 return FALSE;
157 memcpy( newdir, dir, len );
160 RtlEnterCriticalSection( &dlldir_section );
161 HeapFree( GetProcessHeap(), 0, dll_directory );
162 dll_directory = newdir;
163 RtlLeaveCriticalSection( &dlldir_section );
164 return TRUE;
168 /****************************************************************************
169 * AddDllDirectory (KERNEL32.@)
171 DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory( const WCHAR *dir )
173 WCHAR path[MAX_PATH];
174 DWORD len;
175 struct dll_dir_entry *ptr;
176 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir );
178 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
180 SetLastError( ERROR_INVALID_PARAMETER );
181 return NULL;
183 if (!(len = GetFullPathNameW( dir, MAX_PATH, path, NULL ))) return NULL;
184 if (GetFileAttributesW( path ) == INVALID_FILE_ATTRIBUTES) return NULL;
186 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] )))) return NULL;
187 memcpy( ptr->dir, path, len * sizeof(WCHAR) );
188 TRACE( "%s\n", debugstr_w( ptr->dir ));
190 RtlEnterCriticalSection( &dlldir_section );
191 list_add_head( &dll_dir_list, &ptr->entry );
192 RtlLeaveCriticalSection( &dlldir_section );
193 return ptr;
197 /****************************************************************************
198 * RemoveDllDirectory (KERNEL32.@)
200 BOOL WINAPI RemoveDllDirectory( DLL_DIRECTORY_COOKIE cookie )
202 struct dll_dir_entry *ptr = cookie;
204 TRACE( "%s\n", debugstr_w( ptr->dir ));
206 RtlEnterCriticalSection( &dlldir_section );
207 list_remove( &ptr->entry );
208 HeapFree( GetProcessHeap(), 0, ptr );
209 RtlLeaveCriticalSection( &dlldir_section );
210 return TRUE;
214 /*************************************************************************
215 * SetDefaultDllDirectories (KERNEL32.@)
217 BOOL WINAPI SetDefaultDllDirectories( DWORD flags )
219 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
220 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
221 LOAD_LIBRARY_SEARCH_USER_DIRS |
222 LOAD_LIBRARY_SEARCH_SYSTEM32 |
223 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
225 if (!flags || (flags & ~load_library_search_flags))
227 SetLastError( ERROR_INVALID_PARAMETER );
228 return FALSE;
230 default_search_flags = flags;
231 return TRUE;
235 /****************************************************************************
236 * DisableThreadLibraryCalls (KERNEL32.@)
238 * Inform the module loader that thread notifications are not required for a dll.
240 * PARAMS
241 * hModule [I] Module handle to skip calls for
243 * RETURNS
244 * Success: TRUE. Thread attach and detach notifications will not be sent
245 * to hModule.
246 * Failure: FALSE. Use GetLastError() to determine the cause.
248 * NOTES
249 * This is typically called from the dll entry point of a dll during process
250 * attachment, for dlls that do not need to process thread notifications.
252 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
254 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
255 if (nts == STATUS_SUCCESS) return TRUE;
257 SetLastError( RtlNtStatusToDosError( nts ) );
258 return FALSE;
262 /***********************************************************************
263 * MODULE_GetBinaryType
265 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
267 union
269 struct
271 unsigned char magic[4];
272 unsigned char class;
273 unsigned char data;
274 unsigned char ignored1[10];
275 unsigned short type;
276 unsigned short machine;
277 unsigned char ignored2[8];
278 unsigned int phoff;
279 unsigned char ignored3[12];
280 unsigned short phnum;
281 } elf;
282 struct
284 unsigned char magic[4];
285 unsigned char class;
286 unsigned char data;
287 unsigned char ignored1[10];
288 unsigned short type;
289 unsigned short machine;
290 unsigned char ignored2[12];
291 unsigned __int64 phoff;
292 unsigned char ignored3[16];
293 unsigned short phnum;
294 } elf64;
295 struct
297 unsigned int magic;
298 unsigned int cputype;
299 unsigned int cpusubtype;
300 unsigned int filetype;
301 } macho;
302 IMAGE_DOS_HEADER mz;
303 } header;
305 DWORD len;
307 memset( info, 0, sizeof(*info) );
309 /* Seek to the start of the file and read the header information. */
310 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
311 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
313 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
315 #ifdef WORDS_BIGENDIAN
316 BOOL byteswap = (header.elf.data == 1);
317 #else
318 BOOL byteswap = (header.elf.data == 2);
319 #endif
320 if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
321 if (byteswap)
323 header.elf.type = RtlUshortByteSwap( header.elf.type );
324 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
326 switch(header.elf.type)
328 case 2:
329 info->type = BINARY_UNIX_EXE;
330 break;
331 case 3:
333 LARGE_INTEGER phoff;
334 unsigned short phnum;
335 unsigned int type;
336 if (header.elf.class == 2)
338 phoff.QuadPart = byteswap ? RtlUlonglongByteSwap( header.elf64.phoff ) : header.elf64.phoff;
339 phnum = byteswap ? RtlUshortByteSwap( header.elf64.phnum ) : header.elf64.phnum;
341 else
343 phoff.QuadPart = byteswap ? RtlUlongByteSwap( header.elf.phoff ) : header.elf.phoff;
344 phnum = byteswap ? RtlUshortByteSwap( header.elf.phnum ) : header.elf.phnum;
346 while (phnum--)
348 if (SetFilePointerEx( hfile, phoff, NULL, FILE_BEGIN ) == -1) return;
349 if (!ReadFile( hfile, &type, sizeof(type), &len, NULL ) || len < sizeof(type)) return;
350 if (byteswap) type = RtlUlongByteSwap( type );
351 if (type == 3)
353 info->type = BINARY_UNIX_EXE;
354 break;
356 phoff.QuadPart += (header.elf.class == 2) ? 56 : 32;
358 if (!info->type) info->type = BINARY_UNIX_LIB;
359 break;
361 default:
362 return;
364 switch(header.elf.machine)
366 case 3: info->arch = IMAGE_FILE_MACHINE_I386; break;
367 case 20: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
368 case 40: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
369 case 50: info->arch = IMAGE_FILE_MACHINE_IA64; break;
370 case 62: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
371 case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
374 /* Mach-o File with Endian set to Big Endian or Little Endian */
375 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
376 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
378 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
379 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
381 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
382 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
384 switch(header.macho.filetype)
386 case 2: info->type = BINARY_UNIX_EXE; break;
387 case 8: info->type = BINARY_UNIX_LIB; break;
389 switch(header.macho.cputype)
391 case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
392 case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
393 case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
394 case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
395 case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
398 /* Not ELF, try DOS */
399 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
401 union
403 IMAGE_OS2_HEADER os2;
404 IMAGE_NT_HEADERS32 nt;
405 IMAGE_NT_HEADERS64 nt64;
406 } ext_header;
408 /* We do have a DOS image so we will now try to seek into
409 * the file by the amount indicated by the field
410 * "Offset to extended header" and read in the
411 * "magic" field information at that location.
412 * This will tell us if there is more header information
413 * to read or not.
415 info->type = BINARY_WIN16;
416 info->arch = IMAGE_FILE_MACHINE_I386;
417 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
418 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
420 /* Reading the magic field succeeded so
421 * we will try to determine what type it is.
423 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
425 if (len >= sizeof(ext_header.nt.FileHeader))
427 static const char fakedll_signature[] = "Wine placeholder DLL";
428 char buffer[sizeof(fakedll_signature)];
430 info->type = BINARY_PE;
431 info->arch = ext_header.nt.FileHeader.Machine;
432 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
433 info->flags |= BINARY_FLAG_DLL;
434 if (len < sizeof(ext_header)) /* clear remaining part of header if missing */
435 memset( (char *)&ext_header + len, 0, sizeof(ext_header) - len );
436 switch (ext_header.nt.OptionalHeader.Magic)
438 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
439 info->res_start = ext_header.nt.OptionalHeader.ImageBase;
440 info->res_end = info->res_start + ext_header.nt.OptionalHeader.SizeOfImage;
441 break;
442 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
443 info->res_start = ext_header.nt64.OptionalHeader.ImageBase;
444 info->res_end = info->res_start + ext_header.nt64.OptionalHeader.SizeOfImage;
445 info->flags |= BINARY_FLAG_64BIT;
446 break;
449 if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
450 SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
451 ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
452 len == sizeof(fakedll_signature) &&
453 !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
455 info->flags |= BINARY_FLAG_FAKEDLL;
462 /***********************************************************************
463 * GetBinaryTypeW [KERNEL32.@]
465 * Determine whether a file is executable, and if so, what kind.
467 * PARAMS
468 * lpApplicationName [I] Path of the file to check
469 * lpBinaryType [O] Destination for the binary type
471 * RETURNS
472 * TRUE, if the file is an executable, in which case lpBinaryType is set.
473 * FALSE, if the file is not an executable or if the function fails.
475 * NOTES
476 * The type of executable is a property that determines which subsystem an
477 * executable file runs under. lpBinaryType can be set to one of the following
478 * values:
479 * SCS_32BIT_BINARY: A Win32 based application
480 * SCS_64BIT_BINARY: A Win64 based application
481 * SCS_DOS_BINARY: An MS-Dos based application
482 * SCS_WOW_BINARY: A Win16 based application
483 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
484 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
485 * SCS_OS216_BINARY: A 16bit OS/2 based application
487 * To find the binary type, this function reads in the files header information.
488 * If extended header information is not present it will assume that the file
489 * is a DOS executable. If extended header information is present it will
490 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
491 * flags in the header.
493 * ".com" and ".pif" files are only recognized by their file name extension,
494 * as per native Windows.
496 BOOL WINAPI GetBinaryTypeW( LPCWSTR name, LPDWORD type )
498 static const WCHAR comW[] = { '.','c','o','m',0 };
499 static const WCHAR pifW[] = { '.','p','i','f',0 };
500 HANDLE hfile, mapping;
501 NTSTATUS status;
502 const WCHAR *ptr;
504 TRACE("%s\n", debugstr_w(name) );
506 if (type == NULL) return FALSE;
508 hfile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
509 if ( hfile == INVALID_HANDLE_VALUE )
510 return FALSE;
512 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY,
513 NULL, NULL, PAGE_READONLY, SEC_IMAGE, hfile );
514 CloseHandle( hfile );
516 switch (status)
518 case STATUS_SUCCESS:
520 SECTION_IMAGE_INFORMATION info;
522 status = NtQuerySection( mapping, SectionImageInformation, &info, sizeof(info), NULL );
523 CloseHandle( mapping );
524 if (status) return FALSE;
525 switch (info.Machine)
527 case IMAGE_FILE_MACHINE_I386:
528 case IMAGE_FILE_MACHINE_ARM:
529 case IMAGE_FILE_MACHINE_THUMB:
530 case IMAGE_FILE_MACHINE_ARMNT:
531 case IMAGE_FILE_MACHINE_POWERPC:
532 *type = SCS_32BIT_BINARY;
533 return TRUE;
534 case IMAGE_FILE_MACHINE_AMD64:
535 case IMAGE_FILE_MACHINE_ARM64:
536 *type = SCS_64BIT_BINARY;
537 return TRUE;
539 return FALSE;
541 case STATUS_INVALID_IMAGE_WIN_16:
542 *type = SCS_WOW_BINARY;
543 return TRUE;
544 case STATUS_INVALID_IMAGE_WIN_32:
545 *type = SCS_32BIT_BINARY;
546 return TRUE;
547 case STATUS_INVALID_IMAGE_WIN_64:
548 *type = SCS_64BIT_BINARY;
549 return TRUE;
550 case STATUS_INVALID_IMAGE_NE_FORMAT:
551 *type = SCS_OS216_BINARY;
552 return TRUE;
553 case STATUS_INVALID_IMAGE_PROTECT:
554 *type = SCS_DOS_BINARY;
555 return TRUE;
556 case STATUS_INVALID_IMAGE_NOT_MZ:
557 if ((ptr = strrchrW( name, '.' )))
559 if (!strcmpiW( ptr, comW ))
561 *type = SCS_DOS_BINARY;
562 return TRUE;
564 if (!strcmpiW( ptr, pifW ))
566 *type = SCS_PIF_BINARY;
567 return TRUE;
570 return FALSE;
571 default:
572 return FALSE;
576 /***********************************************************************
577 * GetBinaryTypeA [KERNEL32.@]
578 * GetBinaryType [KERNEL32.@]
580 * See GetBinaryTypeW.
582 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
584 ANSI_STRING app_nameA;
585 NTSTATUS status;
587 TRACE("%s\n", debugstr_a(lpApplicationName));
589 /* Sanity check.
591 if ( lpApplicationName == NULL || lpBinaryType == NULL )
592 return FALSE;
594 RtlInitAnsiString(&app_nameA, lpApplicationName);
595 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
596 &app_nameA, FALSE);
597 if (!status)
598 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
600 SetLastError(RtlNtStatusToDosError(status));
601 return FALSE;
604 /***********************************************************************
605 * GetModuleHandleExA (KERNEL32.@)
607 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
609 WCHAR *nameW;
611 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
612 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
614 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
615 return GetModuleHandleExW( flags, nameW, module );
618 /***********************************************************************
619 * GetModuleHandleExW (KERNEL32.@)
621 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
623 NTSTATUS status = STATUS_SUCCESS;
624 HMODULE ret;
625 ULONG_PTR magic;
626 BOOL lock;
628 if (!module)
630 SetLastError( ERROR_INVALID_PARAMETER );
631 return FALSE;
634 /* if we are messing with the refcount, grab the loader lock */
635 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
636 if (lock)
637 LdrLockLoaderLock( 0, NULL, &magic );
639 if (!name)
641 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
643 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
645 void *dummy;
646 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
648 else
650 UNICODE_STRING wstr;
651 RtlInitUnicodeString( &wstr, name );
652 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
655 if (status == STATUS_SUCCESS)
657 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
658 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
659 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
660 LdrAddRefDll( 0, ret );
662 else SetLastError( RtlNtStatusToDosError( status ) );
664 if (lock)
665 LdrUnlockLoaderLock( 0, magic );
667 if (status == STATUS_SUCCESS) *module = ret;
668 else *module = NULL;
670 return (status == STATUS_SUCCESS);
673 /***********************************************************************
674 * GetModuleHandleA (KERNEL32.@)
676 * Get the handle of a dll loaded into the process address space.
678 * PARAMS
679 * module [I] Name of the dll
681 * RETURNS
682 * Success: A handle to the loaded dll.
683 * Failure: A NULL handle. Use GetLastError() to determine the cause.
685 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
687 HMODULE ret;
689 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
690 return ret;
693 /***********************************************************************
694 * GetModuleHandleW (KERNEL32.@)
696 * Unicode version of GetModuleHandleA.
698 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
700 HMODULE ret;
702 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
703 return ret;
707 /***********************************************************************
708 * GetModuleFileNameA (KERNEL32.@)
710 * Get the file name of a loaded module from its handle.
712 * RETURNS
713 * Success: The length of the file name, excluding the terminating NUL.
714 * Failure: 0. Use GetLastError() to determine the cause.
716 * NOTES
717 * This function always returns the long path of hModule
718 * The function doesn't write a terminating '\0' if the buffer is too
719 * small.
721 DWORD WINAPI GetModuleFileNameA(
722 HMODULE hModule, /* [in] Module handle (32 bit) */
723 LPSTR lpFileName, /* [out] Destination for file name */
724 DWORD size ) /* [in] Size of lpFileName in characters */
726 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
727 DWORD len;
729 if (!filenameW)
731 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
732 return 0;
734 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
736 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
737 if (len < size)
738 lpFileName[len] = '\0';
739 else
740 SetLastError( ERROR_INSUFFICIENT_BUFFER );
742 HeapFree( GetProcessHeap(), 0, filenameW );
743 return len;
746 /***********************************************************************
747 * GetModuleFileNameW (KERNEL32.@)
749 * Unicode version of GetModuleFileNameA.
751 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
753 ULONG len = 0;
754 ULONG_PTR magic;
755 LDR_MODULE *pldr;
756 NTSTATUS nts;
757 WIN16_SUBSYSTEM_TIB *win16_tib;
759 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
761 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
762 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
763 if (len < size) lpFileName[len] = '\0';
764 goto done;
767 LdrLockLoaderLock( 0, NULL, &magic );
769 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
770 nts = LdrFindEntryForAddress( hModule, &pldr );
771 if (nts == STATUS_SUCCESS)
773 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
774 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
775 if (len < size)
777 lpFileName[len] = '\0';
778 SetLastError( 0 );
780 else
781 SetLastError( ERROR_INSUFFICIENT_BUFFER );
783 else SetLastError( RtlNtStatusToDosError( nts ) );
785 LdrUnlockLoaderLock( 0, magic );
786 done:
787 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
788 return len;
792 /***********************************************************************
793 * get_dll_system_path
795 static const WCHAR *get_dll_system_path(void)
797 static WCHAR *cached_path;
799 if (!cached_path)
801 WCHAR *p, *path;
802 int len = 1;
804 len += 2 * GetSystemDirectoryW( NULL, 0 );
805 len += GetWindowsDirectoryW( NULL, 0 );
806 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
807 GetSystemDirectoryW( p, path + len - p);
808 p += strlenW(p);
809 /* if system directory ends in "32" add 16-bit version too */
810 if (p[-2] == '3' && p[-1] == '2')
812 *p++ = ';';
813 GetSystemDirectoryW( p, path + len - p);
814 p += strlenW(p) - 2;
816 *p++ = ';';
817 GetWindowsDirectoryW( p, path + len - p);
818 cached_path = path;
820 return cached_path;
823 /***********************************************************************
824 * get_dll_safe_mode
826 static BOOL get_dll_safe_mode(void)
828 static const WCHAR keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
829 'M','a','c','h','i','n','e','\\',
830 'S','y','s','t','e','m','\\',
831 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
832 'C','o','n','t','r','o','l','\\',
833 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
834 static const WCHAR valueW[] = {'S','a','f','e','D','l','l','S','e','a','r','c','h','M','o','d','e',0};
836 static int safe_mode = -1;
838 if (safe_mode == -1)
840 char buffer[offsetof(KEY_VALUE_PARTIAL_INFORMATION, Data[sizeof(DWORD)])];
841 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
842 OBJECT_ATTRIBUTES attr;
843 UNICODE_STRING nameW;
844 HANDLE hkey;
845 DWORD size = sizeof(buffer);
847 attr.Length = sizeof(attr);
848 attr.RootDirectory = 0;
849 attr.ObjectName = &nameW;
850 attr.Attributes = 0;
851 attr.SecurityDescriptor = NULL;
852 attr.SecurityQualityOfService = NULL;
854 safe_mode = 1;
855 RtlInitUnicodeString( &nameW, keyW );
856 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
858 RtlInitUnicodeString( &nameW, valueW );
859 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ) &&
860 info->Type == REG_DWORD && info->DataLength == sizeof(DWORD))
861 safe_mode = !!*(DWORD *)info->Data;
862 NtClose( hkey );
864 if (!safe_mode) TRACE( "SafeDllSearchMode disabled through the registry\n" );
866 return safe_mode;
869 /******************************************************************
870 * get_module_path_end
872 * Returns the end of the directory component of the module path.
874 static inline const WCHAR *get_module_path_end(const WCHAR *module)
876 const WCHAR *p;
877 const WCHAR *mod_end = module;
878 if (!module) return mod_end;
880 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
881 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
882 if (mod_end == module + 2 && module[1] == ':') mod_end++;
883 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
885 return mod_end;
889 /******************************************************************
890 * append_path_len
892 * Append a counted string to the load path. Helper for MODULE_get_dll_load_path.
894 static inline WCHAR *append_path_len( WCHAR *p, const WCHAR *str, DWORD len )
896 if (!len) return p;
897 memcpy( p, str, len * sizeof(WCHAR) );
898 p[len] = ';';
899 return p + len + 1;
903 /******************************************************************
904 * append_path
906 * Append a string to the load path. Helper for MODULE_get_dll_load_path.
908 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str )
910 return append_path_len( p, str, strlenW(str) );
914 /******************************************************************
915 * MODULE_get_dll_load_path
917 * Compute the load path to use for a given dll.
918 * Returned pointer must be freed by caller.
920 WCHAR *MODULE_get_dll_load_path( LPCWSTR module, int safe_mode )
922 static const WCHAR pathW[] = {'P','A','T','H',0};
923 static const WCHAR dotW[] = {'.',0};
925 const WCHAR *system_path = get_dll_system_path();
926 const WCHAR *mod_end = NULL;
927 UNICODE_STRING name, value;
928 WCHAR *p, *ret;
929 int len = 0, path_len = 0;
931 /* adjust length for module name */
933 if (module)
934 mod_end = get_module_path_end( module );
935 /* if module is NULL or doesn't contain a path, fall back to directory
936 * process was loaded from */
937 if (module == mod_end)
939 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
940 mod_end = get_module_path_end( module );
942 len += (mod_end - module) + 1;
944 len += strlenW( system_path ) + 2;
946 /* get the PATH variable */
948 RtlInitUnicodeString( &name, pathW );
949 value.Length = 0;
950 value.MaximumLength = 0;
951 value.Buffer = NULL;
952 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
953 path_len = value.Length;
955 RtlEnterCriticalSection( &dlldir_section );
956 if (safe_mode == -1) safe_mode = get_dll_safe_mode();
957 if (dll_directory) len += strlenW(dll_directory) + 1;
958 else len += 2; /* current directory */
959 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
961 if (module) p = append_path_len( p, module, mod_end - module );
963 if (dll_directory) p = append_path( p, dll_directory );
964 else if (!safe_mode) p = append_path( p, dotW );
966 p = append_path( p, system_path );
968 if (!dll_directory && safe_mode) p = append_path( p, dotW );
970 RtlLeaveCriticalSection( &dlldir_section );
971 if (!ret) return NULL;
973 value.Buffer = p;
974 value.MaximumLength = path_len;
976 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
978 WCHAR *new_ptr;
980 /* grow the buffer and retry */
981 path_len = value.Length;
982 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
984 HeapFree( GetProcessHeap(), 0, ret );
985 return NULL;
987 value.Buffer = new_ptr + (value.Buffer - ret);
988 value.MaximumLength = path_len;
989 ret = new_ptr;
991 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
992 return ret;
996 /******************************************************************
997 * get_dll_load_path_search_flags
999 static WCHAR *get_dll_load_path_search_flags( LPCWSTR module, DWORD flags )
1001 const WCHAR *image = NULL, *mod_end, *image_end;
1002 struct dll_dir_entry *dir;
1003 WCHAR *p, *ret;
1004 int len = 1;
1006 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
1007 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1008 LOAD_LIBRARY_SEARCH_USER_DIRS |
1009 LOAD_LIBRARY_SEARCH_SYSTEM32);
1011 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
1013 DWORD type = RtlDetermineDosPathNameType_U( module );
1014 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH)
1016 SetLastError( ERROR_INVALID_PARAMETER );
1017 return NULL;
1019 mod_end = get_module_path_end( module );
1020 len += (mod_end - module) + 1;
1022 else module = NULL;
1024 RtlEnterCriticalSection( &dlldir_section );
1026 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
1028 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
1029 image_end = get_module_path_end( image );
1030 len += (image_end - image) + 1;
1033 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1035 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1036 len += strlenW( dir->dir ) + 1;
1037 if (dll_directory) len += strlenW(dll_directory) + 1;
1040 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += GetSystemDirectoryW( NULL, 0 );
1042 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1044 if (module) p = append_path_len( p, module, mod_end - module );
1045 if (image) p = append_path_len( p, image, image_end - image );
1046 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1048 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1049 p = append_path( p, dir->dir );
1050 if (dll_directory) p = append_path( p, dll_directory );
1052 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) GetSystemDirectoryW( p, ret + len - p );
1053 else
1055 if (p > ret) p--;
1056 *p = 0;
1060 RtlLeaveCriticalSection( &dlldir_section );
1061 return ret;
1065 /******************************************************************
1066 * load_library_as_datafile
1068 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
1070 static const WCHAR dotDLL[] = {'.','d','l','l',0};
1072 WCHAR filenameW[MAX_PATH];
1073 HANDLE hFile = INVALID_HANDLE_VALUE;
1074 HANDLE mapping;
1075 HMODULE module = 0;
1076 DWORD protect = PAGE_READONLY;
1077 DWORD sharing = FILE_SHARE_READ | FILE_SHARE_DELETE;
1079 *hmod = 0;
1081 if (flags & LOAD_LIBRARY_AS_IMAGE_RESOURCE) protect |= SEC_IMAGE;
1083 if (SearchPathW( NULL, name, dotDLL, ARRAY_SIZE( filenameW ), filenameW, NULL ))
1085 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
1087 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1089 mapping = CreateFileMappingW( hFile, NULL, protect, 0, 0, NULL );
1090 if (!mapping) goto failed;
1092 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1093 CloseHandle( mapping );
1094 if (!module) goto failed;
1096 if (!(flags & LOAD_LIBRARY_AS_IMAGE_RESOURCE))
1098 /* make sure it's a valid PE file */
1099 if (!RtlImageNtHeader( module )) goto failed;
1100 *hmod = (HMODULE)((char *)module + 1); /* set bit 0 for data file module */
1102 if (flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)
1104 struct exclusive_datafile *file = HeapAlloc( GetProcessHeap(), 0, sizeof(*file) );
1105 if (!file) goto failed;
1106 file->module = *hmod;
1107 file->file = hFile;
1108 list_add_head( &exclusive_datafile_list, &file->entry );
1109 TRACE( "delaying close %p for module %p\n", file->file, file->module );
1110 return TRUE;
1113 else *hmod = (HMODULE)((char *)module + 2); /* set bit 1 for image resource module */
1115 CloseHandle( hFile );
1116 return TRUE;
1118 failed:
1119 if (module) UnmapViewOfFile( module );
1120 CloseHandle( hFile );
1121 return FALSE;
1125 /******************************************************************
1126 * load_library
1128 * Helper for LoadLibraryExA/W.
1130 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
1132 NTSTATUS nts;
1133 HMODULE hModule;
1134 WCHAR *load_path;
1135 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
1136 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1137 LOAD_LIBRARY_SEARCH_USER_DIRS |
1138 LOAD_LIBRARY_SEARCH_SYSTEM32 |
1139 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
1140 const DWORD unsupported_flags = (LOAD_IGNORE_CODE_AUTHZ_LEVEL |
1141 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
1143 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
1145 if( flags & unsupported_flags)
1146 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
1148 if (flags & load_library_search_flags)
1149 load_path = get_dll_load_path_search_flags( libname->Buffer, flags );
1150 else
1151 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL, -1 );
1152 if (!load_path) return 0;
1154 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))
1156 ULONG_PTR magic;
1158 LdrLockLoaderLock( 0, NULL, &magic );
1159 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
1161 LdrAddRefDll( 0, hModule );
1162 LdrUnlockLoaderLock( 0, magic );
1163 goto done;
1165 if (load_library_as_datafile( libname->Buffer, &hModule, flags ))
1167 LdrUnlockLoaderLock( 0, magic );
1168 goto done;
1170 LdrUnlockLoaderLock( 0, magic );
1171 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1172 /* Fallback to normal behaviour */
1175 nts = LdrLoadDll( load_path, flags, libname, &hModule );
1176 if (nts != STATUS_SUCCESS)
1178 hModule = 0;
1179 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
1180 SetLastError( ERROR_DLL_NOT_FOUND );
1181 else
1182 SetLastError( RtlNtStatusToDosError( nts ) );
1184 done:
1185 HeapFree( GetProcessHeap(), 0, load_path );
1186 return hModule;
1190 /******************************************************************
1191 * LoadLibraryExA (KERNEL32.@)
1193 * Load a dll file into the process address space.
1195 * PARAMS
1196 * libname [I] Name of the file to load
1197 * hfile [I] Reserved, must be 0.
1198 * flags [I] Flags for loading the dll
1200 * RETURNS
1201 * Success: A handle to the loaded dll.
1202 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1204 * NOTES
1205 * The HFILE parameter is not used and marked reserved in the SDK. I can
1206 * only guess that it should force a file to be mapped, but I rather
1207 * ignore the parameter because it would be extremely difficult to
1208 * integrate this with different types of module representations.
1210 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1212 WCHAR *libnameW;
1214 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1215 return LoadLibraryExW( libnameW, hfile, flags );
1218 /***********************************************************************
1219 * LoadLibraryExW (KERNEL32.@)
1221 * Unicode version of LoadLibraryExA.
1223 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1225 UNICODE_STRING wstr;
1226 HMODULE res;
1228 if (!libnameW)
1230 SetLastError(ERROR_INVALID_PARAMETER);
1231 return 0;
1233 RtlInitUnicodeString( &wstr, libnameW );
1234 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1235 return load_library( &wstr, flags );
1237 /* Library name has trailing spaces */
1238 RtlCreateUnicodeString( &wstr, libnameW );
1239 while (wstr.Length > sizeof(WCHAR) &&
1240 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1242 wstr.Length -= sizeof(WCHAR);
1244 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1245 res = load_library( &wstr, flags );
1246 RtlFreeUnicodeString( &wstr );
1247 return res;
1250 /***********************************************************************
1251 * LoadLibraryA (KERNEL32.@)
1253 * Load a dll file into the process address space.
1255 * PARAMS
1256 * libname [I] Name of the file to load
1258 * RETURNS
1259 * Success: A handle to the loaded dll.
1260 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1262 * NOTES
1263 * See LoadLibraryExA().
1265 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1267 return LoadLibraryExA(libname, 0, 0);
1270 /***********************************************************************
1271 * LoadLibraryW (KERNEL32.@)
1273 * Unicode version of LoadLibraryA.
1275 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1277 return LoadLibraryExW(libnameW, 0, 0);
1280 /***********************************************************************
1281 * FreeLibrary (KERNEL32.@)
1283 * Free a dll loaded into the process address space.
1285 * PARAMS
1286 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1288 * RETURNS
1289 * Success: TRUE. The dll is removed if it is not still in use.
1290 * Failure: FALSE. Use GetLastError() to determine the cause.
1292 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1294 BOOL retv = FALSE;
1295 NTSTATUS nts;
1297 if (!hLibModule)
1299 SetLastError( ERROR_INVALID_HANDLE );
1300 return FALSE;
1303 if ((ULONG_PTR)hLibModule & 3) /* this is a datafile module */
1305 if ((ULONG_PTR)hLibModule & 1)
1307 struct exclusive_datafile *file;
1308 ULONG_PTR magic;
1310 LdrLockLoaderLock( 0, NULL, &magic );
1311 LIST_FOR_EACH_ENTRY( file, &exclusive_datafile_list, struct exclusive_datafile, entry )
1313 if (file->module != hLibModule) continue;
1314 TRACE( "closing %p for module %p\n", file->file, file->module );
1315 CloseHandle( file->file );
1316 list_remove( &file->entry );
1317 HeapFree( GetProcessHeap(), 0, file );
1318 break;
1320 LdrUnlockLoaderLock( 0, magic );
1322 return UnmapViewOfFile( (void *)((ULONG_PTR)hLibModule & ~3) );
1325 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1326 else SetLastError( RtlNtStatusToDosError( nts ) );
1328 return retv;
1331 /***********************************************************************
1332 * GetProcAddress (KERNEL32.@)
1334 * Find the address of an exported symbol in a loaded dll.
1336 * PARAMS
1337 * hModule [I] Handle to the dll returned by LoadLibraryA().
1338 * function [I] Name of the symbol, or an integer ordinal number < 16384
1340 * RETURNS
1341 * Success: A pointer to the symbol in the process address space.
1342 * Failure: NULL. Use GetLastError() to determine the cause.
1344 FARPROC get_proc_address( HMODULE hModule, LPCSTR function )
1346 NTSTATUS nts;
1347 FARPROC fp;
1349 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1351 if ((ULONG_PTR)function >> 16)
1353 ANSI_STRING str;
1355 RtlInitAnsiString( &str, function );
1356 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1358 else
1359 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1360 if (nts != STATUS_SUCCESS)
1362 SetLastError( RtlNtStatusToDosError( nts ) );
1363 fp = NULL;
1365 return fp;
1368 #ifdef __x86_64__
1370 * Work around a Delphi bug on x86_64. When delay loading a symbol,
1371 * Delphi saves rcx, rdx, r8 and r9 to the stack. It then calls
1372 * GetProcAddress(), pops the saved registers and calls the function.
1373 * This works fine if all of the parameters are ints. However, since
1374 * it does not save xmm0 - 3, it relies on GetProcAddress() preserving
1375 * these registers if the function takes floating point parameters.
1376 * This wrapper saves xmm0 - 3 to the stack.
1378 extern FARPROC get_proc_address_wrapper( HMODULE module, LPCSTR function );
1380 __ASM_GLOBAL_FUNC( get_proc_address_wrapper,
1381 "pushq %rbp\n\t"
1382 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
1383 __ASM_CFI(".cfi_rel_offset %rbp,0\n\t")
1384 "movq %rsp,%rbp\n\t"
1385 __ASM_CFI(".cfi_def_cfa_register %rbp\n\t")
1386 "subq $0x40,%rsp\n\t"
1387 "movaps %xmm0,-0x10(%rbp)\n\t"
1388 "movaps %xmm1,-0x20(%rbp)\n\t"
1389 "movaps %xmm2,-0x30(%rbp)\n\t"
1390 "movaps %xmm3,-0x40(%rbp)\n\t"
1391 "call " __ASM_NAME("get_proc_address") "\n\t"
1392 "movaps -0x40(%rbp), %xmm3\n\t"
1393 "movaps -0x30(%rbp), %xmm2\n\t"
1394 "movaps -0x20(%rbp), %xmm1\n\t"
1395 "movaps -0x10(%rbp), %xmm0\n\t"
1396 "movq %rbp,%rsp\n\t"
1397 __ASM_CFI(".cfi_def_cfa_register %rsp\n\t")
1398 "popq %rbp\n\t"
1399 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
1400 __ASM_CFI(".cfi_same_value %rbp\n\t")
1401 "ret" )
1402 #else /* __x86_64__ */
1404 static inline FARPROC get_proc_address_wrapper( HMODULE module, LPCSTR function )
1406 return get_proc_address( module, function );
1409 #endif /* __x86_64__ */
1411 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1413 return get_proc_address_wrapper( hModule, function );
1416 /***********************************************************************
1417 * DelayLoadFailureHook (KERNEL32.@)
1419 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1421 ULONG_PTR args[2];
1423 if ((ULONG_PTR)function >> 16)
1424 ERR( "failed to delay load %s.%s\n", name, function );
1425 else
1426 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1427 args[0] = (ULONG_PTR)name;
1428 args[1] = (ULONG_PTR)function;
1429 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1430 return NULL;
1433 typedef struct _PEB32
1435 BOOLEAN InheritedAddressSpace;
1436 BOOLEAN ReadImageFileExecOptions;
1437 BOOLEAN BeingDebugged;
1438 BOOLEAN SpareBool;
1439 DWORD Mutant;
1440 DWORD ImageBaseAddress;
1441 DWORD LdrData;
1442 } PEB32;
1444 typedef struct _LIST_ENTRY32
1446 DWORD Flink;
1447 DWORD Blink;
1448 } LIST_ENTRY32;
1450 typedef struct _PEB_LDR_DATA32
1452 ULONG Length;
1453 BOOLEAN Initialized;
1454 DWORD SsHandle;
1455 LIST_ENTRY32 InLoadOrderModuleList;
1456 } PEB_LDR_DATA32;
1458 typedef struct _UNICODE_STRING32
1460 USHORT Length;
1461 USHORT MaximumLength;
1462 DWORD Buffer;
1463 } UNICODE_STRING32;
1465 typedef struct _LDR_MODULE32
1467 LIST_ENTRY32 InLoadOrderModuleList;
1468 LIST_ENTRY32 InMemoryOrderModuleList;
1469 LIST_ENTRY32 InInitializationOrderModuleList;
1470 DWORD BaseAddress;
1471 DWORD EntryPoint;
1472 ULONG SizeOfImage;
1473 UNICODE_STRING32 FullDllName;
1474 UNICODE_STRING32 BaseDllName;
1475 } LDR_MODULE32;
1477 typedef struct {
1478 HANDLE process;
1479 PLIST_ENTRY head, current;
1480 LDR_MODULE ldr_module;
1481 BOOL wow64;
1482 LDR_MODULE32 ldr_module32;
1483 } MODULE_ITERATOR;
1485 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1487 PROCESS_BASIC_INFORMATION pbi;
1488 PPEB_LDR_DATA ldr_data;
1489 NTSTATUS status;
1491 if (!IsWow64Process(process, &iter->wow64))
1492 return FALSE;
1494 /* Get address of PEB */
1495 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1496 &pbi, sizeof(pbi), NULL);
1497 if (status != STATUS_SUCCESS)
1499 SetLastError(RtlNtStatusToDosError(status));
1500 return FALSE;
1503 if (sizeof(void *) == 8 && iter->wow64)
1505 PEB_LDR_DATA32 *ldr_data32_ptr;
1506 DWORD ldr_data32, first_module;
1507 PEB32 *peb32;
1509 peb32 = (PEB32 *)(DWORD_PTR)pbi.PebBaseAddress;
1511 if (!ReadProcessMemory(process, &peb32->LdrData, &ldr_data32,
1512 sizeof(ldr_data32), NULL))
1513 return FALSE;
1514 ldr_data32_ptr = (PEB_LDR_DATA32 *)(DWORD_PTR) ldr_data32;
1516 if (!ReadProcessMemory(process,
1517 &ldr_data32_ptr->InLoadOrderModuleList.Flink,
1518 &first_module, sizeof(first_module), NULL))
1519 return FALSE;
1520 iter->head = (LIST_ENTRY *)&ldr_data32_ptr->InLoadOrderModuleList;
1521 iter->current = (LIST_ENTRY *)(DWORD_PTR) first_module;
1522 iter->process = process;
1524 return TRUE;
1527 /* Read address of LdrData from PEB */
1528 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1529 &ldr_data, sizeof(ldr_data), NULL))
1530 return FALSE;
1532 /* Read address of first module from LdrData */
1533 if (!ReadProcessMemory(process,
1534 &ldr_data->InLoadOrderModuleList.Flink,
1535 &iter->current, sizeof(iter->current), NULL))
1536 return FALSE;
1538 iter->head = &ldr_data->InLoadOrderModuleList;
1539 iter->process = process;
1541 return TRUE;
1544 static int module_iterator_next(MODULE_ITERATOR *iter)
1546 if (iter->current == iter->head)
1547 return 0;
1549 if (sizeof(void *) == 8 && iter->wow64)
1551 LIST_ENTRY32 *entry32 = (LIST_ENTRY32 *)iter->current;
1553 if (!ReadProcessMemory(iter->process,
1554 CONTAINING_RECORD(entry32, LDR_MODULE32, InLoadOrderModuleList),
1555 &iter->ldr_module32, sizeof(iter->ldr_module32), NULL))
1556 return -1;
1558 iter->current = (LIST_ENTRY *)(DWORD_PTR) iter->ldr_module32.InLoadOrderModuleList.Flink;
1559 return 1;
1562 if (!ReadProcessMemory(iter->process,
1563 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1564 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1565 return -1;
1567 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1568 return 1;
1571 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1573 MODULE_ITERATOR iter;
1574 INT ret;
1576 if (!init_module_iterator(&iter, process))
1577 return FALSE;
1579 while ((ret = module_iterator_next(&iter)) > 0)
1580 /* When hModule is NULL we return the process image - which will be
1581 * the first module since our iterator uses InLoadOrderModuleList */
1582 if (!module || module == iter.ldr_module.BaseAddress)
1584 *ldr_module = iter.ldr_module;
1585 return TRUE;
1588 if (ret == 0)
1589 SetLastError(ERROR_INVALID_HANDLE);
1591 return FALSE;
1594 static BOOL get_ldr_module32(HANDLE process, HMODULE module, LDR_MODULE32 *ldr_module)
1596 MODULE_ITERATOR iter;
1597 INT ret;
1599 if (!init_module_iterator(&iter, process))
1600 return FALSE;
1602 while ((ret = module_iterator_next(&iter)) > 0)
1603 /* When hModule is NULL we return the process image - which will be
1604 * the first module since our iterator uses InLoadOrderModuleList */
1605 if (!module || (DWORD)(DWORD_PTR) module == iter.ldr_module32.BaseAddress)
1607 *ldr_module = iter.ldr_module32;
1608 return TRUE;
1611 if (ret == 0)
1612 SetLastError(ERROR_INVALID_HANDLE);
1614 return FALSE;
1617 /***********************************************************************
1618 * K32EnumProcessModules (KERNEL32.@)
1620 * NOTES
1621 * Returned list is in load order.
1623 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1624 DWORD cb, DWORD *needed)
1626 MODULE_ITERATOR iter;
1627 DWORD size = 0;
1628 INT ret;
1630 if (!init_module_iterator(&iter, process))
1631 return FALSE;
1633 if (cb && !lphModule)
1635 SetLastError(ERROR_NOACCESS);
1636 return FALSE;
1639 while ((ret = module_iterator_next(&iter)) > 0)
1641 if (cb >= sizeof(HMODULE))
1643 if (sizeof(void *) == 8 && iter.wow64)
1644 *lphModule++ = (HMODULE) (DWORD_PTR)iter.ldr_module32.BaseAddress;
1645 else
1646 *lphModule++ = iter.ldr_module.BaseAddress;
1647 cb -= sizeof(HMODULE);
1649 size += sizeof(HMODULE);
1652 if (!needed)
1654 SetLastError(ERROR_NOACCESS);
1655 return FALSE;
1657 *needed = size;
1659 return ret == 0;
1662 /***********************************************************************
1663 * K32EnumProcessModulesEx (KERNEL32.@)
1665 * NOTES
1666 * Returned list is in load order.
1668 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1669 DWORD cb, DWORD *needed, DWORD filter)
1671 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1672 process, lphModule, cb, needed, filter);
1673 return K32EnumProcessModules(process, lphModule, cb, needed);
1676 /***********************************************************************
1677 * K32GetModuleBaseNameW (KERNEL32.@)
1679 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1680 LPWSTR base_name, DWORD size)
1682 LDR_MODULE ldr_module;
1683 BOOL wow64;
1685 if (!IsWow64Process(process, &wow64))
1686 return 0;
1688 if (sizeof(void *) == 8 && wow64)
1690 LDR_MODULE32 ldr_module32;
1692 if (!get_ldr_module32(process, module, &ldr_module32))
1693 return 0;
1695 size = min(ldr_module32.BaseDllName.Length / sizeof(WCHAR), size);
1696 if (!ReadProcessMemory(process, (void *)(DWORD_PTR)ldr_module32.BaseDllName.Buffer,
1697 base_name, size * sizeof(WCHAR), NULL))
1698 return 0;
1700 else
1702 if (!get_ldr_module(process, module, &ldr_module))
1703 return 0;
1705 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1706 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1707 base_name, size * sizeof(WCHAR), NULL))
1708 return 0;
1711 base_name[size] = 0;
1712 return size;
1715 /***********************************************************************
1716 * K32GetModuleBaseNameA (KERNEL32.@)
1718 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1719 LPSTR base_name, DWORD size)
1721 WCHAR *base_name_w;
1722 DWORD len, ret = 0;
1724 if(!base_name || !size) {
1725 SetLastError(ERROR_INVALID_PARAMETER);
1726 return 0;
1729 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1730 if(!base_name_w)
1731 return 0;
1733 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1734 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1735 if (len)
1737 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1738 base_name, size, NULL, NULL);
1739 if (ret < size) base_name[ret] = 0;
1741 HeapFree(GetProcessHeap(), 0, base_name_w);
1742 return ret;
1745 /***********************************************************************
1746 * K32GetModuleFileNameExW (KERNEL32.@)
1748 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1749 LPWSTR file_name, DWORD size)
1751 LDR_MODULE ldr_module;
1752 BOOL wow64;
1753 DWORD len;
1755 if (!size) return 0;
1757 if (!IsWow64Process(process, &wow64))
1758 return 0;
1760 if (sizeof(void *) == 8 && wow64)
1762 LDR_MODULE32 ldr_module32;
1764 if (!get_ldr_module32(process, module, &ldr_module32))
1765 return 0;
1767 len = ldr_module32.FullDllName.Length / sizeof(WCHAR);
1768 if (!ReadProcessMemory(process, (void *)(DWORD_PTR)ldr_module32.FullDllName.Buffer,
1769 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1770 return 0;
1772 else
1774 if (!get_ldr_module(process, module, &ldr_module))
1775 return 0;
1777 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1778 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1779 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1780 return 0;
1783 if (len < size)
1785 file_name[len] = 0;
1786 return len;
1788 else
1790 file_name[size - 1] = 0;
1791 return size;
1795 /***********************************************************************
1796 * K32GetModuleFileNameExA (KERNEL32.@)
1798 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1799 LPSTR file_name, DWORD size)
1801 WCHAR *ptr;
1802 DWORD len;
1804 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1806 if (!file_name || !size)
1808 SetLastError( ERROR_INVALID_PARAMETER );
1809 return 0;
1812 if ( process == GetCurrentProcess() )
1814 len = GetModuleFileNameA( module, file_name, size );
1815 if (size) file_name[size - 1] = '\0';
1816 return len;
1819 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1821 len = K32GetModuleFileNameExW(process, module, ptr, size);
1822 if (!len)
1824 file_name[0] = '\0';
1826 else
1828 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1830 file_name[size - 1] = 0;
1831 len = size;
1833 else if (len < size) len = strlen( file_name );
1836 HeapFree(GetProcessHeap(), 0, ptr);
1837 return len;
1840 /***********************************************************************
1841 * K32GetModuleInformation (KERNEL32.@)
1843 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1844 MODULEINFO *modinfo, DWORD cb)
1846 LDR_MODULE ldr_module;
1847 BOOL wow64;
1849 if (cb < sizeof(MODULEINFO))
1851 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1852 return FALSE;
1855 if (!IsWow64Process(process, &wow64))
1856 return FALSE;
1858 if (sizeof(void *) == 8 && wow64)
1860 LDR_MODULE32 ldr_module32;
1862 if (!get_ldr_module32(process, module, &ldr_module32))
1863 return FALSE;
1865 modinfo->lpBaseOfDll = (void *)(DWORD_PTR)ldr_module32.BaseAddress;
1866 modinfo->SizeOfImage = ldr_module32.SizeOfImage;
1867 modinfo->EntryPoint = (void *)(DWORD_PTR)ldr_module32.EntryPoint;
1869 else
1871 if (!get_ldr_module(process, module, &ldr_module))
1872 return FALSE;
1874 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1875 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1876 modinfo->EntryPoint = ldr_module.EntryPoint;
1878 return TRUE;
1881 #ifdef __i386__
1883 /***********************************************************************
1884 * __wine_dll_register_16 (KERNEL32.@)
1886 * No longer used.
1888 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1890 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1894 /***********************************************************************
1895 * __wine_dll_unregister_16 (KERNEL32.@)
1897 * No longer used.
1899 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1903 #endif