ntdll: Add stub for RtlGetUnloadEventTraceEx.
[wine.git] / dlls / kernel32 / module.c
blob1199eff4e8f50c31f3489243127aca99b7872cc0
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 * GetBinaryTypeW [KERNEL32.@]
265 * Determine whether a file is executable, and if so, what kind.
267 * PARAMS
268 * lpApplicationName [I] Path of the file to check
269 * lpBinaryType [O] Destination for the binary type
271 * RETURNS
272 * TRUE, if the file is an executable, in which case lpBinaryType is set.
273 * FALSE, if the file is not an executable or if the function fails.
275 * NOTES
276 * The type of executable is a property that determines which subsystem an
277 * executable file runs under. lpBinaryType can be set to one of the following
278 * values:
279 * SCS_32BIT_BINARY: A Win32 based application
280 * SCS_64BIT_BINARY: A Win64 based application
281 * SCS_DOS_BINARY: An MS-Dos based application
282 * SCS_WOW_BINARY: A Win16 based application
283 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
284 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
285 * SCS_OS216_BINARY: A 16bit OS/2 based application
287 * To find the binary type, this function reads in the files header information.
288 * If extended header information is not present it will assume that the file
289 * is a DOS executable. If extended header information is present it will
290 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
291 * flags in the header.
293 * ".com" and ".pif" files are only recognized by their file name extension,
294 * as per native Windows.
296 BOOL WINAPI GetBinaryTypeW( LPCWSTR name, LPDWORD type )
298 static const WCHAR comW[] = { '.','c','o','m',0 };
299 static const WCHAR pifW[] = { '.','p','i','f',0 };
300 HANDLE hfile, mapping;
301 NTSTATUS status;
302 const WCHAR *ptr;
304 TRACE("%s\n", debugstr_w(name) );
306 if (type == NULL) return FALSE;
308 hfile = CreateFileW( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
309 if ( hfile == INVALID_HANDLE_VALUE )
310 return FALSE;
312 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY,
313 NULL, NULL, PAGE_READONLY, SEC_IMAGE, hfile );
314 CloseHandle( hfile );
316 switch (status)
318 case STATUS_SUCCESS:
320 SECTION_IMAGE_INFORMATION info;
322 status = NtQuerySection( mapping, SectionImageInformation, &info, sizeof(info), NULL );
323 CloseHandle( mapping );
324 if (status) return FALSE;
325 switch (info.Machine)
327 case IMAGE_FILE_MACHINE_I386:
328 case IMAGE_FILE_MACHINE_ARM:
329 case IMAGE_FILE_MACHINE_THUMB:
330 case IMAGE_FILE_MACHINE_ARMNT:
331 case IMAGE_FILE_MACHINE_POWERPC:
332 *type = SCS_32BIT_BINARY;
333 return TRUE;
334 case IMAGE_FILE_MACHINE_AMD64:
335 case IMAGE_FILE_MACHINE_ARM64:
336 *type = SCS_64BIT_BINARY;
337 return TRUE;
339 return FALSE;
341 case STATUS_INVALID_IMAGE_WIN_16:
342 *type = SCS_WOW_BINARY;
343 return TRUE;
344 case STATUS_INVALID_IMAGE_WIN_32:
345 *type = SCS_32BIT_BINARY;
346 return TRUE;
347 case STATUS_INVALID_IMAGE_WIN_64:
348 *type = SCS_64BIT_BINARY;
349 return TRUE;
350 case STATUS_INVALID_IMAGE_NE_FORMAT:
351 *type = SCS_OS216_BINARY;
352 return TRUE;
353 case STATUS_INVALID_IMAGE_PROTECT:
354 *type = SCS_DOS_BINARY;
355 return TRUE;
356 case STATUS_INVALID_IMAGE_NOT_MZ:
357 if ((ptr = strrchrW( name, '.' )))
359 if (!strcmpiW( ptr, comW ))
361 *type = SCS_DOS_BINARY;
362 return TRUE;
364 if (!strcmpiW( ptr, pifW ))
366 *type = SCS_PIF_BINARY;
367 return TRUE;
370 return FALSE;
371 default:
372 return FALSE;
376 /***********************************************************************
377 * GetBinaryTypeA [KERNEL32.@]
378 * GetBinaryType [KERNEL32.@]
380 * See GetBinaryTypeW.
382 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
384 ANSI_STRING app_nameA;
385 NTSTATUS status;
387 TRACE("%s\n", debugstr_a(lpApplicationName));
389 /* Sanity check.
391 if ( lpApplicationName == NULL || lpBinaryType == NULL )
392 return FALSE;
394 RtlInitAnsiString(&app_nameA, lpApplicationName);
395 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
396 &app_nameA, FALSE);
397 if (!status)
398 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
400 SetLastError(RtlNtStatusToDosError(status));
401 return FALSE;
404 /***********************************************************************
405 * GetModuleHandleExA (KERNEL32.@)
407 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
409 WCHAR *nameW;
411 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
412 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
414 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
415 return GetModuleHandleExW( flags, nameW, module );
418 /***********************************************************************
419 * GetModuleHandleExW (KERNEL32.@)
421 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
423 NTSTATUS status = STATUS_SUCCESS;
424 HMODULE ret;
425 ULONG_PTR magic;
426 BOOL lock;
428 if (!module)
430 SetLastError( ERROR_INVALID_PARAMETER );
431 return FALSE;
434 /* if we are messing with the refcount, grab the loader lock */
435 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
436 if (lock)
437 LdrLockLoaderLock( 0, NULL, &magic );
439 if (!name)
441 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
443 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
445 void *dummy;
446 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
448 else
450 UNICODE_STRING wstr;
451 RtlInitUnicodeString( &wstr, name );
452 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
455 if (status == STATUS_SUCCESS)
457 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
458 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
459 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
460 LdrAddRefDll( 0, ret );
462 else SetLastError( RtlNtStatusToDosError( status ) );
464 if (lock)
465 LdrUnlockLoaderLock( 0, magic );
467 if (status == STATUS_SUCCESS) *module = ret;
468 else *module = NULL;
470 return (status == STATUS_SUCCESS);
473 /***********************************************************************
474 * GetModuleHandleA (KERNEL32.@)
476 * Get the handle of a dll loaded into the process address space.
478 * PARAMS
479 * module [I] Name of the dll
481 * RETURNS
482 * Success: A handle to the loaded dll.
483 * Failure: A NULL handle. Use GetLastError() to determine the cause.
485 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
487 HMODULE ret;
489 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
490 return ret;
493 /***********************************************************************
494 * GetModuleHandleW (KERNEL32.@)
496 * Unicode version of GetModuleHandleA.
498 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
500 HMODULE ret;
502 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
503 return ret;
507 /***********************************************************************
508 * GetModuleFileNameA (KERNEL32.@)
510 * Get the file name of a loaded module from its handle.
512 * RETURNS
513 * Success: The length of the file name, excluding the terminating NUL.
514 * Failure: 0. Use GetLastError() to determine the cause.
516 * NOTES
517 * This function always returns the long path of hModule
518 * The function doesn't write a terminating '\0' if the buffer is too
519 * small.
521 DWORD WINAPI GetModuleFileNameA(
522 HMODULE hModule, /* [in] Module handle (32 bit) */
523 LPSTR lpFileName, /* [out] Destination for file name */
524 DWORD size ) /* [in] Size of lpFileName in characters */
526 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
527 DWORD len;
529 if (!filenameW)
531 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
532 return 0;
534 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
536 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
537 if (len < size)
538 lpFileName[len] = '\0';
539 else
540 SetLastError( ERROR_INSUFFICIENT_BUFFER );
542 HeapFree( GetProcessHeap(), 0, filenameW );
543 return len;
546 /***********************************************************************
547 * GetModuleFileNameW (KERNEL32.@)
549 * Unicode version of GetModuleFileNameA.
551 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
553 ULONG len = 0;
554 ULONG_PTR magic;
555 LDR_MODULE *pldr;
556 NTSTATUS nts;
557 WIN16_SUBSYSTEM_TIB *win16_tib;
559 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
561 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
562 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
563 if (len < size) lpFileName[len] = '\0';
564 goto done;
567 LdrLockLoaderLock( 0, NULL, &magic );
569 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
570 nts = LdrFindEntryForAddress( hModule, &pldr );
571 if (nts == STATUS_SUCCESS)
573 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
574 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
575 if (len < size)
577 lpFileName[len] = '\0';
578 SetLastError( 0 );
580 else
581 SetLastError( ERROR_INSUFFICIENT_BUFFER );
583 else SetLastError( RtlNtStatusToDosError( nts ) );
585 LdrUnlockLoaderLock( 0, magic );
586 done:
587 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
588 return len;
592 /***********************************************************************
593 * get_dll_system_path
595 static const WCHAR *get_dll_system_path(void)
597 static WCHAR *cached_path;
599 if (!cached_path)
601 WCHAR *p, *path;
602 int len = 1;
604 len += 2 * GetSystemDirectoryW( NULL, 0 );
605 len += GetWindowsDirectoryW( NULL, 0 );
606 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
607 GetSystemDirectoryW( p, path + len - p);
608 p += strlenW(p);
609 /* if system directory ends in "32" add 16-bit version too */
610 if (p[-2] == '3' && p[-1] == '2')
612 *p++ = ';';
613 GetSystemDirectoryW( p, path + len - p);
614 p += strlenW(p) - 2;
616 *p++ = ';';
617 GetWindowsDirectoryW( p, path + len - p);
618 cached_path = path;
620 return cached_path;
623 /***********************************************************************
624 * get_dll_safe_mode
626 static BOOL get_dll_safe_mode(void)
628 static const WCHAR keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
629 'M','a','c','h','i','n','e','\\',
630 'S','y','s','t','e','m','\\',
631 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
632 'C','o','n','t','r','o','l','\\',
633 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
634 static const WCHAR valueW[] = {'S','a','f','e','D','l','l','S','e','a','r','c','h','M','o','d','e',0};
636 static int safe_mode = -1;
638 if (safe_mode == -1)
640 char buffer[offsetof(KEY_VALUE_PARTIAL_INFORMATION, Data[sizeof(DWORD)])];
641 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
642 OBJECT_ATTRIBUTES attr;
643 UNICODE_STRING nameW;
644 HANDLE hkey;
645 DWORD size = sizeof(buffer);
647 attr.Length = sizeof(attr);
648 attr.RootDirectory = 0;
649 attr.ObjectName = &nameW;
650 attr.Attributes = 0;
651 attr.SecurityDescriptor = NULL;
652 attr.SecurityQualityOfService = NULL;
654 safe_mode = 1;
655 RtlInitUnicodeString( &nameW, keyW );
656 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
658 RtlInitUnicodeString( &nameW, valueW );
659 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ) &&
660 info->Type == REG_DWORD && info->DataLength == sizeof(DWORD))
661 safe_mode = !!*(DWORD *)info->Data;
662 NtClose( hkey );
664 if (!safe_mode) TRACE( "SafeDllSearchMode disabled through the registry\n" );
666 return safe_mode;
669 /******************************************************************
670 * get_module_path_end
672 * Returns the end of the directory component of the module path.
674 static inline const WCHAR *get_module_path_end(const WCHAR *module)
676 const WCHAR *p;
677 const WCHAR *mod_end = module;
678 if (!module) return mod_end;
680 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
681 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
682 if (mod_end == module + 2 && module[1] == ':') mod_end++;
683 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
685 return mod_end;
689 /******************************************************************
690 * append_path_len
692 * Append a counted string to the load path. Helper for MODULE_get_dll_load_path.
694 static inline WCHAR *append_path_len( WCHAR *p, const WCHAR *str, DWORD len )
696 if (!len) return p;
697 memcpy( p, str, len * sizeof(WCHAR) );
698 p[len] = ';';
699 return p + len + 1;
703 /******************************************************************
704 * append_path
706 * Append a string to the load path. Helper for MODULE_get_dll_load_path.
708 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str )
710 return append_path_len( p, str, strlenW(str) );
714 /******************************************************************
715 * MODULE_get_dll_load_path
717 * Compute the load path to use for a given dll.
718 * Returned pointer must be freed by caller.
720 WCHAR *MODULE_get_dll_load_path( LPCWSTR module, int safe_mode )
722 static const WCHAR pathW[] = {'P','A','T','H',0};
723 static const WCHAR dotW[] = {'.',0};
725 const WCHAR *system_path = get_dll_system_path();
726 const WCHAR *mod_end = NULL;
727 UNICODE_STRING name, value;
728 WCHAR *p, *ret;
729 int len = 0, path_len = 0;
731 /* adjust length for module name */
733 if (module)
734 mod_end = get_module_path_end( module );
735 /* if module is NULL or doesn't contain a path, fall back to directory
736 * process was loaded from */
737 if (module == mod_end)
739 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
740 mod_end = get_module_path_end( module );
742 len += (mod_end - module) + 1;
744 len += strlenW( system_path ) + 2;
746 /* get the PATH variable */
748 RtlInitUnicodeString( &name, pathW );
749 value.Length = 0;
750 value.MaximumLength = 0;
751 value.Buffer = NULL;
752 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
753 path_len = value.Length;
755 RtlEnterCriticalSection( &dlldir_section );
756 if (safe_mode == -1) safe_mode = get_dll_safe_mode();
757 if (dll_directory) len += strlenW(dll_directory) + 1;
758 else len += 2; /* current directory */
759 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
761 if (module) p = append_path_len( p, module, mod_end - module );
763 if (dll_directory) p = append_path( p, dll_directory );
764 else if (!safe_mode) p = append_path( p, dotW );
766 p = append_path( p, system_path );
768 if (!dll_directory && safe_mode) p = append_path( p, dotW );
770 RtlLeaveCriticalSection( &dlldir_section );
771 if (!ret) return NULL;
773 value.Buffer = p;
774 value.MaximumLength = path_len;
776 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
778 WCHAR *new_ptr;
780 /* grow the buffer and retry */
781 path_len = value.Length;
782 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
784 HeapFree( GetProcessHeap(), 0, ret );
785 return NULL;
787 value.Buffer = new_ptr + (value.Buffer - ret);
788 value.MaximumLength = path_len;
789 ret = new_ptr;
791 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
792 return ret;
796 /******************************************************************
797 * get_dll_load_path_search_flags
799 static WCHAR *get_dll_load_path_search_flags( LPCWSTR module, DWORD flags )
801 const WCHAR *image = NULL, *mod_end, *image_end;
802 struct dll_dir_entry *dir;
803 WCHAR *p, *ret;
804 int len = 1;
806 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
807 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
808 LOAD_LIBRARY_SEARCH_USER_DIRS |
809 LOAD_LIBRARY_SEARCH_SYSTEM32);
811 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
813 DWORD type = RtlDetermineDosPathNameType_U( module );
814 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH)
816 SetLastError( ERROR_INVALID_PARAMETER );
817 return NULL;
819 mod_end = get_module_path_end( module );
820 len += (mod_end - module) + 1;
822 else module = NULL;
824 RtlEnterCriticalSection( &dlldir_section );
826 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
828 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
829 image_end = get_module_path_end( image );
830 len += (image_end - image) + 1;
833 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
835 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
836 len += strlenW( dir->dir ) + 1;
837 if (dll_directory) len += strlenW(dll_directory) + 1;
840 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += GetSystemDirectoryW( NULL, 0 );
842 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
844 if (module) p = append_path_len( p, module, mod_end - module );
845 if (image) p = append_path_len( p, image, image_end - image );
846 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
848 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
849 p = append_path( p, dir->dir );
850 if (dll_directory) p = append_path( p, dll_directory );
852 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) GetSystemDirectoryW( p, ret + len - p );
853 else
855 if (p > ret) p--;
856 *p = 0;
860 RtlLeaveCriticalSection( &dlldir_section );
861 return ret;
865 /******************************************************************
866 * load_library_as_datafile
868 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
870 static const WCHAR dotDLL[] = {'.','d','l','l',0};
872 WCHAR filenameW[MAX_PATH];
873 HANDLE hFile = INVALID_HANDLE_VALUE;
874 HANDLE mapping;
875 HMODULE module = 0;
876 DWORD protect = PAGE_READONLY;
877 DWORD sharing = FILE_SHARE_READ | FILE_SHARE_DELETE;
879 *hmod = 0;
881 if (flags & LOAD_LIBRARY_AS_IMAGE_RESOURCE) protect |= SEC_IMAGE;
883 if (SearchPathW( NULL, name, dotDLL, ARRAY_SIZE( filenameW ), filenameW, NULL ))
885 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
887 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
889 mapping = CreateFileMappingW( hFile, NULL, protect, 0, 0, NULL );
890 if (!mapping) goto failed;
892 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
893 CloseHandle( mapping );
894 if (!module) goto failed;
896 if (!(flags & LOAD_LIBRARY_AS_IMAGE_RESOURCE))
898 /* make sure it's a valid PE file */
899 if (!RtlImageNtHeader( module )) goto failed;
900 *hmod = (HMODULE)((char *)module + 1); /* set bit 0 for data file module */
902 if (flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)
904 struct exclusive_datafile *file = HeapAlloc( GetProcessHeap(), 0, sizeof(*file) );
905 if (!file) goto failed;
906 file->module = *hmod;
907 file->file = hFile;
908 list_add_head( &exclusive_datafile_list, &file->entry );
909 TRACE( "delaying close %p for module %p\n", file->file, file->module );
910 return TRUE;
913 else *hmod = (HMODULE)((char *)module + 2); /* set bit 1 for image resource module */
915 CloseHandle( hFile );
916 return TRUE;
918 failed:
919 if (module) UnmapViewOfFile( module );
920 CloseHandle( hFile );
921 return FALSE;
925 /******************************************************************
926 * load_library
928 * Helper for LoadLibraryExA/W.
930 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
932 NTSTATUS nts;
933 HMODULE hModule;
934 WCHAR *load_path;
935 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
936 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
937 LOAD_LIBRARY_SEARCH_USER_DIRS |
938 LOAD_LIBRARY_SEARCH_SYSTEM32 |
939 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
940 const DWORD unsupported_flags = (LOAD_IGNORE_CODE_AUTHZ_LEVEL |
941 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
943 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
945 if( flags & unsupported_flags)
946 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
948 if (flags & load_library_search_flags)
949 load_path = get_dll_load_path_search_flags( libname->Buffer, flags );
950 else
951 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL, -1 );
952 if (!load_path) return 0;
954 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))
956 ULONG_PTR magic;
958 LdrLockLoaderLock( 0, NULL, &magic );
959 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
961 LdrAddRefDll( 0, hModule );
962 LdrUnlockLoaderLock( 0, magic );
963 goto done;
965 if (load_library_as_datafile( libname->Buffer, &hModule, flags ))
967 LdrUnlockLoaderLock( 0, magic );
968 goto done;
970 LdrUnlockLoaderLock( 0, magic );
971 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
972 /* Fallback to normal behaviour */
975 nts = LdrLoadDll( load_path, flags, libname, &hModule );
976 if (nts != STATUS_SUCCESS)
978 hModule = 0;
979 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
980 SetLastError( ERROR_DLL_NOT_FOUND );
981 else
982 SetLastError( RtlNtStatusToDosError( nts ) );
984 done:
985 HeapFree( GetProcessHeap(), 0, load_path );
986 return hModule;
990 /******************************************************************
991 * LoadLibraryExA (KERNEL32.@)
993 * Load a dll file into the process address space.
995 * PARAMS
996 * libname [I] Name of the file to load
997 * hfile [I] Reserved, must be 0.
998 * flags [I] Flags for loading the dll
1000 * RETURNS
1001 * Success: A handle to the loaded dll.
1002 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1004 * NOTES
1005 * The HFILE parameter is not used and marked reserved in the SDK. I can
1006 * only guess that it should force a file to be mapped, but I rather
1007 * ignore the parameter because it would be extremely difficult to
1008 * integrate this with different types of module representations.
1010 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1012 WCHAR *libnameW;
1014 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1015 return LoadLibraryExW( libnameW, hfile, flags );
1018 /***********************************************************************
1019 * LoadLibraryExW (KERNEL32.@)
1021 * Unicode version of LoadLibraryExA.
1023 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1025 UNICODE_STRING wstr;
1026 HMODULE res;
1028 if (!libnameW)
1030 SetLastError(ERROR_INVALID_PARAMETER);
1031 return 0;
1033 RtlInitUnicodeString( &wstr, libnameW );
1034 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1035 return load_library( &wstr, flags );
1037 /* Library name has trailing spaces */
1038 RtlCreateUnicodeString( &wstr, libnameW );
1039 while (wstr.Length > sizeof(WCHAR) &&
1040 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1042 wstr.Length -= sizeof(WCHAR);
1044 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1045 res = load_library( &wstr, flags );
1046 RtlFreeUnicodeString( &wstr );
1047 return res;
1050 /***********************************************************************
1051 * LoadLibraryA (KERNEL32.@)
1053 * Load a dll file into the process address space.
1055 * PARAMS
1056 * libname [I] Name of the file to load
1058 * RETURNS
1059 * Success: A handle to the loaded dll.
1060 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1062 * NOTES
1063 * See LoadLibraryExA().
1065 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1067 return LoadLibraryExA(libname, 0, 0);
1070 /***********************************************************************
1071 * LoadLibraryW (KERNEL32.@)
1073 * Unicode version of LoadLibraryA.
1075 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1077 return LoadLibraryExW(libnameW, 0, 0);
1080 /***********************************************************************
1081 * FreeLibrary (KERNEL32.@)
1083 * Free a dll loaded into the process address space.
1085 * PARAMS
1086 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1088 * RETURNS
1089 * Success: TRUE. The dll is removed if it is not still in use.
1090 * Failure: FALSE. Use GetLastError() to determine the cause.
1092 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1094 BOOL retv = FALSE;
1095 NTSTATUS nts;
1097 if (!hLibModule)
1099 SetLastError( ERROR_INVALID_HANDLE );
1100 return FALSE;
1103 if ((ULONG_PTR)hLibModule & 3) /* this is a datafile module */
1105 if ((ULONG_PTR)hLibModule & 1)
1107 struct exclusive_datafile *file;
1108 ULONG_PTR magic;
1110 LdrLockLoaderLock( 0, NULL, &magic );
1111 LIST_FOR_EACH_ENTRY( file, &exclusive_datafile_list, struct exclusive_datafile, entry )
1113 if (file->module != hLibModule) continue;
1114 TRACE( "closing %p for module %p\n", file->file, file->module );
1115 CloseHandle( file->file );
1116 list_remove( &file->entry );
1117 HeapFree( GetProcessHeap(), 0, file );
1118 break;
1120 LdrUnlockLoaderLock( 0, magic );
1122 return UnmapViewOfFile( (void *)((ULONG_PTR)hLibModule & ~3) );
1125 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1126 else SetLastError( RtlNtStatusToDosError( nts ) );
1128 return retv;
1131 /***********************************************************************
1132 * GetProcAddress (KERNEL32.@)
1134 * Find the address of an exported symbol in a loaded dll.
1136 * PARAMS
1137 * hModule [I] Handle to the dll returned by LoadLibraryA().
1138 * function [I] Name of the symbol, or an integer ordinal number < 16384
1140 * RETURNS
1141 * Success: A pointer to the symbol in the process address space.
1142 * Failure: NULL. Use GetLastError() to determine the cause.
1144 FARPROC get_proc_address( HMODULE hModule, LPCSTR function )
1146 NTSTATUS nts;
1147 FARPROC fp;
1149 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1151 if ((ULONG_PTR)function >> 16)
1153 ANSI_STRING str;
1155 RtlInitAnsiString( &str, function );
1156 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1158 else
1159 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1160 if (nts != STATUS_SUCCESS)
1162 SetLastError( RtlNtStatusToDosError( nts ) );
1163 fp = NULL;
1165 return fp;
1168 #ifdef __x86_64__
1170 * Work around a Delphi bug on x86_64. When delay loading a symbol,
1171 * Delphi saves rcx, rdx, r8 and r9 to the stack. It then calls
1172 * GetProcAddress(), pops the saved registers and calls the function.
1173 * This works fine if all of the parameters are ints. However, since
1174 * it does not save xmm0 - 3, it relies on GetProcAddress() preserving
1175 * these registers if the function takes floating point parameters.
1176 * This wrapper saves xmm0 - 3 to the stack.
1178 extern FARPROC get_proc_address_wrapper( HMODULE module, LPCSTR function );
1180 __ASM_GLOBAL_FUNC( get_proc_address_wrapper,
1181 "pushq %rbp\n\t"
1182 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
1183 __ASM_CFI(".cfi_rel_offset %rbp,0\n\t")
1184 "movq %rsp,%rbp\n\t"
1185 __ASM_CFI(".cfi_def_cfa_register %rbp\n\t")
1186 "subq $0x40,%rsp\n\t"
1187 "movaps %xmm0,-0x10(%rbp)\n\t"
1188 "movaps %xmm1,-0x20(%rbp)\n\t"
1189 "movaps %xmm2,-0x30(%rbp)\n\t"
1190 "movaps %xmm3,-0x40(%rbp)\n\t"
1191 "call " __ASM_NAME("get_proc_address") "\n\t"
1192 "movaps -0x40(%rbp), %xmm3\n\t"
1193 "movaps -0x30(%rbp), %xmm2\n\t"
1194 "movaps -0x20(%rbp), %xmm1\n\t"
1195 "movaps -0x10(%rbp), %xmm0\n\t"
1196 "movq %rbp,%rsp\n\t"
1197 __ASM_CFI(".cfi_def_cfa_register %rsp\n\t")
1198 "popq %rbp\n\t"
1199 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
1200 __ASM_CFI(".cfi_same_value %rbp\n\t")
1201 "ret" )
1202 #else /* __x86_64__ */
1204 static inline FARPROC get_proc_address_wrapper( HMODULE module, LPCSTR function )
1206 return get_proc_address( module, function );
1209 #endif /* __x86_64__ */
1211 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1213 return get_proc_address_wrapper( hModule, function );
1216 /***********************************************************************
1217 * DelayLoadFailureHook (KERNEL32.@)
1219 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1221 ULONG_PTR args[2];
1223 if ((ULONG_PTR)function >> 16)
1224 ERR( "failed to delay load %s.%s\n", name, function );
1225 else
1226 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1227 args[0] = (ULONG_PTR)name;
1228 args[1] = (ULONG_PTR)function;
1229 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1230 return NULL;
1233 typedef struct _PEB32
1235 BOOLEAN InheritedAddressSpace;
1236 BOOLEAN ReadImageFileExecOptions;
1237 BOOLEAN BeingDebugged;
1238 BOOLEAN SpareBool;
1239 DWORD Mutant;
1240 DWORD ImageBaseAddress;
1241 DWORD LdrData;
1242 } PEB32;
1244 typedef struct _LIST_ENTRY32
1246 DWORD Flink;
1247 DWORD Blink;
1248 } LIST_ENTRY32;
1250 typedef struct _PEB_LDR_DATA32
1252 ULONG Length;
1253 BOOLEAN Initialized;
1254 DWORD SsHandle;
1255 LIST_ENTRY32 InLoadOrderModuleList;
1256 } PEB_LDR_DATA32;
1258 typedef struct _UNICODE_STRING32
1260 USHORT Length;
1261 USHORT MaximumLength;
1262 DWORD Buffer;
1263 } UNICODE_STRING32;
1265 typedef struct _LDR_MODULE32
1267 LIST_ENTRY32 InLoadOrderModuleList;
1268 LIST_ENTRY32 InMemoryOrderModuleList;
1269 LIST_ENTRY32 InInitializationOrderModuleList;
1270 DWORD BaseAddress;
1271 DWORD EntryPoint;
1272 ULONG SizeOfImage;
1273 UNICODE_STRING32 FullDllName;
1274 UNICODE_STRING32 BaseDllName;
1275 } LDR_MODULE32;
1277 typedef struct {
1278 HANDLE process;
1279 PLIST_ENTRY head, current;
1280 LDR_MODULE ldr_module;
1281 BOOL wow64;
1282 LDR_MODULE32 ldr_module32;
1283 } MODULE_ITERATOR;
1285 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1287 PROCESS_BASIC_INFORMATION pbi;
1288 PPEB_LDR_DATA ldr_data;
1289 NTSTATUS status;
1291 if (!IsWow64Process(process, &iter->wow64))
1292 return FALSE;
1294 /* Get address of PEB */
1295 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1296 &pbi, sizeof(pbi), NULL);
1297 if (status != STATUS_SUCCESS)
1299 SetLastError(RtlNtStatusToDosError(status));
1300 return FALSE;
1303 if (sizeof(void *) == 8 && iter->wow64)
1305 PEB_LDR_DATA32 *ldr_data32_ptr;
1306 DWORD ldr_data32, first_module;
1307 PEB32 *peb32;
1309 peb32 = (PEB32 *)(DWORD_PTR)pbi.PebBaseAddress;
1311 if (!ReadProcessMemory(process, &peb32->LdrData, &ldr_data32,
1312 sizeof(ldr_data32), NULL))
1313 return FALSE;
1314 ldr_data32_ptr = (PEB_LDR_DATA32 *)(DWORD_PTR) ldr_data32;
1316 if (!ReadProcessMemory(process,
1317 &ldr_data32_ptr->InLoadOrderModuleList.Flink,
1318 &first_module, sizeof(first_module), NULL))
1319 return FALSE;
1320 iter->head = (LIST_ENTRY *)&ldr_data32_ptr->InLoadOrderModuleList;
1321 iter->current = (LIST_ENTRY *)(DWORD_PTR) first_module;
1322 iter->process = process;
1324 return TRUE;
1327 /* Read address of LdrData from PEB */
1328 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1329 &ldr_data, sizeof(ldr_data), NULL))
1330 return FALSE;
1332 /* Read address of first module from LdrData */
1333 if (!ReadProcessMemory(process,
1334 &ldr_data->InLoadOrderModuleList.Flink,
1335 &iter->current, sizeof(iter->current), NULL))
1336 return FALSE;
1338 iter->head = &ldr_data->InLoadOrderModuleList;
1339 iter->process = process;
1341 return TRUE;
1344 static int module_iterator_next(MODULE_ITERATOR *iter)
1346 if (iter->current == iter->head)
1347 return 0;
1349 if (sizeof(void *) == 8 && iter->wow64)
1351 LIST_ENTRY32 *entry32 = (LIST_ENTRY32 *)iter->current;
1353 if (!ReadProcessMemory(iter->process,
1354 CONTAINING_RECORD(entry32, LDR_MODULE32, InLoadOrderModuleList),
1355 &iter->ldr_module32, sizeof(iter->ldr_module32), NULL))
1356 return -1;
1358 iter->current = (LIST_ENTRY *)(DWORD_PTR) iter->ldr_module32.InLoadOrderModuleList.Flink;
1359 return 1;
1362 if (!ReadProcessMemory(iter->process,
1363 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1364 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1365 return -1;
1367 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1368 return 1;
1371 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1373 MODULE_ITERATOR iter;
1374 INT ret;
1376 if (!init_module_iterator(&iter, process))
1377 return FALSE;
1379 while ((ret = module_iterator_next(&iter)) > 0)
1380 /* When hModule is NULL we return the process image - which will be
1381 * the first module since our iterator uses InLoadOrderModuleList */
1382 if (!module || module == iter.ldr_module.BaseAddress)
1384 *ldr_module = iter.ldr_module;
1385 return TRUE;
1388 if (ret == 0)
1389 SetLastError(ERROR_INVALID_HANDLE);
1391 return FALSE;
1394 static BOOL get_ldr_module32(HANDLE process, HMODULE module, LDR_MODULE32 *ldr_module)
1396 MODULE_ITERATOR iter;
1397 INT ret;
1399 if (!init_module_iterator(&iter, process))
1400 return FALSE;
1402 while ((ret = module_iterator_next(&iter)) > 0)
1403 /* When hModule is NULL we return the process image - which will be
1404 * the first module since our iterator uses InLoadOrderModuleList */
1405 if (!module || (DWORD)(DWORD_PTR) module == iter.ldr_module32.BaseAddress)
1407 *ldr_module = iter.ldr_module32;
1408 return TRUE;
1411 if (ret == 0)
1412 SetLastError(ERROR_INVALID_HANDLE);
1414 return FALSE;
1417 /***********************************************************************
1418 * K32EnumProcessModules (KERNEL32.@)
1420 * NOTES
1421 * Returned list is in load order.
1423 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1424 DWORD cb, DWORD *needed)
1426 MODULE_ITERATOR iter;
1427 DWORD size = 0;
1428 INT ret;
1430 if (!init_module_iterator(&iter, process))
1431 return FALSE;
1433 if (cb && !lphModule)
1435 SetLastError(ERROR_NOACCESS);
1436 return FALSE;
1439 while ((ret = module_iterator_next(&iter)) > 0)
1441 if (cb >= sizeof(HMODULE))
1443 if (sizeof(void *) == 8 && iter.wow64)
1444 *lphModule++ = (HMODULE) (DWORD_PTR)iter.ldr_module32.BaseAddress;
1445 else
1446 *lphModule++ = iter.ldr_module.BaseAddress;
1447 cb -= sizeof(HMODULE);
1449 size += sizeof(HMODULE);
1452 if (!needed)
1454 SetLastError(ERROR_NOACCESS);
1455 return FALSE;
1457 *needed = size;
1459 return ret == 0;
1462 /***********************************************************************
1463 * K32EnumProcessModulesEx (KERNEL32.@)
1465 * NOTES
1466 * Returned list is in load order.
1468 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1469 DWORD cb, DWORD *needed, DWORD filter)
1471 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1472 process, lphModule, cb, needed, filter);
1473 return K32EnumProcessModules(process, lphModule, cb, needed);
1476 /***********************************************************************
1477 * K32GetModuleBaseNameW (KERNEL32.@)
1479 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1480 LPWSTR base_name, DWORD size)
1482 LDR_MODULE ldr_module;
1483 BOOL wow64;
1485 if (!IsWow64Process(process, &wow64))
1486 return 0;
1488 if (sizeof(void *) == 8 && wow64)
1490 LDR_MODULE32 ldr_module32;
1492 if (!get_ldr_module32(process, module, &ldr_module32))
1493 return 0;
1495 size = min(ldr_module32.BaseDllName.Length / sizeof(WCHAR), size);
1496 if (!ReadProcessMemory(process, (void *)(DWORD_PTR)ldr_module32.BaseDllName.Buffer,
1497 base_name, size * sizeof(WCHAR), NULL))
1498 return 0;
1500 else
1502 if (!get_ldr_module(process, module, &ldr_module))
1503 return 0;
1505 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1506 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1507 base_name, size * sizeof(WCHAR), NULL))
1508 return 0;
1511 base_name[size] = 0;
1512 return size;
1515 /***********************************************************************
1516 * K32GetModuleBaseNameA (KERNEL32.@)
1518 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1519 LPSTR base_name, DWORD size)
1521 WCHAR *base_name_w;
1522 DWORD len, ret = 0;
1524 if(!base_name || !size) {
1525 SetLastError(ERROR_INVALID_PARAMETER);
1526 return 0;
1529 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1530 if(!base_name_w)
1531 return 0;
1533 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1534 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1535 if (len)
1537 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1538 base_name, size, NULL, NULL);
1539 if (ret < size) base_name[ret] = 0;
1541 HeapFree(GetProcessHeap(), 0, base_name_w);
1542 return ret;
1545 /***********************************************************************
1546 * K32GetModuleFileNameExW (KERNEL32.@)
1548 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1549 LPWSTR file_name, DWORD size)
1551 LDR_MODULE ldr_module;
1552 BOOL wow64;
1553 DWORD len;
1555 if (!size) return 0;
1557 if (!IsWow64Process(process, &wow64))
1558 return 0;
1560 if (sizeof(void *) == 8 && wow64)
1562 LDR_MODULE32 ldr_module32;
1564 if (!get_ldr_module32(process, module, &ldr_module32))
1565 return 0;
1567 len = ldr_module32.FullDllName.Length / sizeof(WCHAR);
1568 if (!ReadProcessMemory(process, (void *)(DWORD_PTR)ldr_module32.FullDllName.Buffer,
1569 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1570 return 0;
1572 else
1574 if (!get_ldr_module(process, module, &ldr_module))
1575 return 0;
1577 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1578 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1579 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1580 return 0;
1583 if (len < size)
1585 file_name[len] = 0;
1586 return len;
1588 else
1590 file_name[size - 1] = 0;
1591 return size;
1595 /***********************************************************************
1596 * K32GetModuleFileNameExA (KERNEL32.@)
1598 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1599 LPSTR file_name, DWORD size)
1601 WCHAR *ptr;
1602 DWORD len;
1604 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1606 if (!file_name || !size)
1608 SetLastError( ERROR_INVALID_PARAMETER );
1609 return 0;
1612 if ( process == GetCurrentProcess() )
1614 len = GetModuleFileNameA( module, file_name, size );
1615 if (size) file_name[size - 1] = '\0';
1616 return len;
1619 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1621 len = K32GetModuleFileNameExW(process, module, ptr, size);
1622 if (!len)
1624 file_name[0] = '\0';
1626 else
1628 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1630 file_name[size - 1] = 0;
1631 len = size;
1633 else if (len < size) len = strlen( file_name );
1636 HeapFree(GetProcessHeap(), 0, ptr);
1637 return len;
1640 /***********************************************************************
1641 * K32GetModuleInformation (KERNEL32.@)
1643 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1644 MODULEINFO *modinfo, DWORD cb)
1646 LDR_MODULE ldr_module;
1647 BOOL wow64;
1649 if (cb < sizeof(MODULEINFO))
1651 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1652 return FALSE;
1655 if (!IsWow64Process(process, &wow64))
1656 return FALSE;
1658 if (sizeof(void *) == 8 && wow64)
1660 LDR_MODULE32 ldr_module32;
1662 if (!get_ldr_module32(process, module, &ldr_module32))
1663 return FALSE;
1665 modinfo->lpBaseOfDll = (void *)(DWORD_PTR)ldr_module32.BaseAddress;
1666 modinfo->SizeOfImage = ldr_module32.SizeOfImage;
1667 modinfo->EntryPoint = (void *)(DWORD_PTR)ldr_module32.EntryPoint;
1669 else
1671 if (!get_ldr_module(process, module, &ldr_module))
1672 return FALSE;
1674 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1675 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1676 modinfo->EntryPoint = ldr_module.EntryPoint;
1678 return TRUE;
1681 #ifdef __i386__
1683 /***********************************************************************
1684 * __wine_dll_register_16 (KERNEL32.@)
1686 * No longer used.
1688 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1690 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1694 /***********************************************************************
1695 * __wine_dll_unregister_16 (KERNEL32.@)
1697 * No longer used.
1699 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1703 #endif