kernel32: Implement LOAD_LIBRARY_SEARCH_* flags.
[wine.git] / dlls / kernel32 / module.c
blob9bd11c77b4d898795139eb99674f84b899f26bc8
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 static CRITICAL_SECTION dlldir_section;
62 static CRITICAL_SECTION_DEBUG critsect_debug =
64 0, 0, &dlldir_section,
65 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
66 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
68 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
70 /****************************************************************************
71 * GetDllDirectoryA (KERNEL32.@)
73 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
75 DWORD len;
77 RtlEnterCriticalSection( &dlldir_section );
78 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
79 if (buffer && buf_len > len)
81 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
82 else *buffer = 0;
84 else
86 len++; /* for terminating null */
87 if (buffer) *buffer = 0;
89 RtlLeaveCriticalSection( &dlldir_section );
90 return len;
94 /****************************************************************************
95 * GetDllDirectoryW (KERNEL32.@)
97 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
99 DWORD len;
101 RtlEnterCriticalSection( &dlldir_section );
102 len = dll_directory ? strlenW( dll_directory ) : 0;
103 if (buffer && buf_len > len)
105 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
106 else *buffer = 0;
108 else
110 len++; /* for terminating null */
111 if (buffer) *buffer = 0;
113 RtlLeaveCriticalSection( &dlldir_section );
114 return len;
118 /****************************************************************************
119 * SetDllDirectoryA (KERNEL32.@)
121 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
123 WCHAR *dirW;
124 BOOL ret;
126 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
127 ret = SetDllDirectoryW( dirW );
128 HeapFree( GetProcessHeap(), 0, dirW );
129 return ret;
133 /****************************************************************************
134 * SetDllDirectoryW (KERNEL32.@)
136 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
138 WCHAR *newdir = NULL;
140 if (dir)
142 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
143 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
145 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
146 return FALSE;
148 memcpy( newdir, dir, len );
151 RtlEnterCriticalSection( &dlldir_section );
152 HeapFree( GetProcessHeap(), 0, dll_directory );
153 dll_directory = newdir;
154 RtlLeaveCriticalSection( &dlldir_section );
155 return TRUE;
159 /****************************************************************************
160 * AddDllDirectory (KERNEL32.@)
162 DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory( const WCHAR *dir )
164 WCHAR path[MAX_PATH];
165 DWORD len;
166 struct dll_dir_entry *ptr;
167 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir );
169 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
171 SetLastError( ERROR_INVALID_PARAMETER );
172 return NULL;
174 if (!(len = GetFullPathNameW( dir, MAX_PATH, path, NULL ))) return NULL;
175 if (GetFileAttributesW( path ) == INVALID_FILE_ATTRIBUTES) return NULL;
177 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] )))) return NULL;
178 memcpy( ptr->dir, path, len * sizeof(WCHAR) );
179 TRACE( "%s\n", debugstr_w( ptr->dir ));
181 RtlEnterCriticalSection( &dlldir_section );
182 list_add_head( &dll_dir_list, &ptr->entry );
183 RtlLeaveCriticalSection( &dlldir_section );
184 return ptr;
188 /****************************************************************************
189 * RemoveDllDirectory (KERNEL32.@)
191 BOOL WINAPI RemoveDllDirectory( DLL_DIRECTORY_COOKIE cookie )
193 struct dll_dir_entry *ptr = cookie;
195 TRACE( "%s\n", debugstr_w( ptr->dir ));
197 RtlEnterCriticalSection( &dlldir_section );
198 list_remove( &ptr->entry );
199 HeapFree( GetProcessHeap(), 0, ptr );
200 RtlLeaveCriticalSection( &dlldir_section );
201 return TRUE;
205 /*************************************************************************
206 * SetDefaultDllDirectories (KERNEL32.@)
208 BOOL WINAPI SetDefaultDllDirectories( DWORD flags )
210 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
211 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
212 LOAD_LIBRARY_SEARCH_USER_DIRS |
213 LOAD_LIBRARY_SEARCH_SYSTEM32 |
214 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
216 if (!flags || (flags & ~load_library_search_flags))
218 SetLastError( ERROR_INVALID_PARAMETER );
219 return FALSE;
221 default_search_flags = flags;
222 return TRUE;
226 /****************************************************************************
227 * DisableThreadLibraryCalls (KERNEL32.@)
229 * Inform the module loader that thread notifications are not required for a dll.
231 * PARAMS
232 * hModule [I] Module handle to skip calls for
234 * RETURNS
235 * Success: TRUE. Thread attach and detach notifications will not be sent
236 * to hModule.
237 * Failure: FALSE. Use GetLastError() to determine the cause.
239 * NOTES
240 * This is typically called from the dll entry point of a dll during process
241 * attachment, for dlls that do not need to process thread notifications.
243 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
245 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
246 if (nts == STATUS_SUCCESS) return TRUE;
248 SetLastError( RtlNtStatusToDosError( nts ) );
249 return FALSE;
253 /* Check whether a file is an OS/2 or a very old Windows executable
254 * by testing on import of KERNEL.
256 * FIXME: is reading the module imports the only way of discerning
257 * old Windows binaries from OS/2 ones ? At least it seems so...
259 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
261 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
262 DWORD ret = BINARY_OS216;
263 LPWORD modtab = NULL;
264 LPSTR nametab = NULL;
265 DWORD len;
266 int i;
268 /* read modref table */
269 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
270 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
271 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
272 || (len != ne->ne_cmod*sizeof(WORD)) )
273 goto broken;
275 /* read imported names table */
276 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
277 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
278 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
279 || (len != ne->ne_enttab - ne->ne_imptab) )
280 goto broken;
282 for (i=0; i < ne->ne_cmod; i++)
284 LPSTR module = &nametab[modtab[i]];
285 TRACE("modref: %.*s\n", module[0], &module[1]);
286 if (!(strncmp(&module[1], "KERNEL", module[0])))
287 { /* very old Windows file */
288 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
289 ret = BINARY_WIN16;
290 goto good;
294 broken:
295 ERR("Hmm, an error occurred. Is this binary file broken?\n");
297 good:
298 HeapFree( GetProcessHeap(), 0, modtab);
299 HeapFree( GetProcessHeap(), 0, nametab);
300 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
301 return ret;
304 /***********************************************************************
305 * MODULE_GetBinaryType
307 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
309 union
311 struct
313 unsigned char magic[4];
314 unsigned char class;
315 unsigned char data;
316 unsigned char version;
317 unsigned char ignored[9];
318 unsigned short type;
319 unsigned short machine;
320 } elf;
321 struct
323 unsigned int magic;
324 unsigned int cputype;
325 unsigned int cpusubtype;
326 unsigned int filetype;
327 } macho;
328 IMAGE_DOS_HEADER mz;
329 } header;
331 DWORD len;
333 memset( info, 0, sizeof(*info) );
335 /* Seek to the start of the file and read the header information. */
336 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
337 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
339 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
341 if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
342 #ifdef WORDS_BIGENDIAN
343 if (header.elf.data == 1)
344 #else
345 if (header.elf.data == 2)
346 #endif
348 header.elf.type = RtlUshortByteSwap( header.elf.type );
349 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
351 switch(header.elf.type)
353 case 2: info->type = BINARY_UNIX_EXE; break;
354 case 3: info->type = BINARY_UNIX_LIB; break;
356 switch(header.elf.machine)
358 case 3: info->arch = IMAGE_FILE_MACHINE_I386; break;
359 case 20: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
360 case 40: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
361 case 50: info->arch = IMAGE_FILE_MACHINE_IA64; break;
362 case 62: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
363 case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
366 /* Mach-o File with Endian set to Big Endian or Little Endian */
367 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
368 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
370 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
371 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
373 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
374 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
376 switch(header.macho.filetype)
378 case 2: info->type = BINARY_UNIX_EXE; break;
379 case 8: info->type = BINARY_UNIX_LIB; break;
381 switch(header.macho.cputype)
383 case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
384 case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
385 case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
386 case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
387 case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
390 /* Not ELF, try DOS */
391 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
393 union
395 IMAGE_OS2_HEADER os2;
396 IMAGE_NT_HEADERS32 nt;
397 } ext_header;
399 /* We do have a DOS image so we will now try to seek into
400 * the file by the amount indicated by the field
401 * "Offset to extended header" and read in the
402 * "magic" field information at that location.
403 * This will tell us if there is more header information
404 * to read or not.
406 info->type = BINARY_DOS;
407 info->arch = IMAGE_FILE_MACHINE_I386;
408 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
409 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
411 /* Reading the magic field succeeded so
412 * we will try to determine what type it is.
414 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
416 if (len >= sizeof(ext_header.nt.FileHeader))
418 static const char fakedll_signature[] = "Wine placeholder DLL";
419 char buffer[sizeof(fakedll_signature)];
421 info->type = BINARY_PE;
422 info->arch = ext_header.nt.FileHeader.Machine;
423 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
424 info->flags |= BINARY_FLAG_DLL;
425 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
426 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
427 switch (ext_header.nt.OptionalHeader.Magic)
429 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
430 info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
431 info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
432 ext_header.nt.OptionalHeader.SizeOfImage);
433 break;
434 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
435 info->flags |= BINARY_FLAG_64BIT;
436 break;
439 if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
440 SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
441 ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
442 len == sizeof(fakedll_signature) &&
443 !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
445 info->flags |= BINARY_FLAG_FAKEDLL;
449 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
451 /* This is a Windows executable (NE) header. This can
452 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
453 * DOS program (running under a DOS extender). To decide
454 * which, we'll have to read the NE header.
456 if (len >= sizeof(ext_header.os2))
458 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
459 switch ( ext_header.os2.ne_exetyp )
461 case 1: info->type = BINARY_OS216; break; /* OS/2 */
462 case 2: info->type = BINARY_WIN16; break; /* Windows */
463 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
464 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
465 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
466 /* other types, e.g. 0 is: "unknown" */
467 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
474 /***********************************************************************
475 * GetBinaryTypeW [KERNEL32.@]
477 * Determine whether a file is executable, and if so, what kind.
479 * PARAMS
480 * lpApplicationName [I] Path of the file to check
481 * lpBinaryType [O] Destination for the binary type
483 * RETURNS
484 * TRUE, if the file is an executable, in which case lpBinaryType is set.
485 * FALSE, if the file is not an executable or if the function fails.
487 * NOTES
488 * The type of executable is a property that determines which subsystem an
489 * executable file runs under. lpBinaryType can be set to one of the following
490 * values:
491 * SCS_32BIT_BINARY: A Win32 based application
492 * SCS_64BIT_BINARY: A Win64 based application
493 * SCS_DOS_BINARY: An MS-Dos based application
494 * SCS_WOW_BINARY: A Win16 based application
495 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
496 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
497 * SCS_OS216_BINARY: A 16bit OS/2 based application
499 * To find the binary type, this function reads in the files header information.
500 * If extended header information is not present it will assume that the file
501 * is a DOS executable. If extended header information is present it will
502 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
503 * flags in the header.
505 * ".com" and ".pif" files are only recognized by their file name extension,
506 * as per native Windows.
508 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
510 BOOL ret = FALSE;
511 HANDLE hfile;
512 struct binary_info binary_info;
514 TRACE("%s\n", debugstr_w(lpApplicationName) );
516 /* Sanity check.
518 if ( lpApplicationName == NULL || lpBinaryType == NULL )
519 return FALSE;
521 /* Open the file indicated by lpApplicationName for reading.
523 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
524 NULL, OPEN_EXISTING, 0, 0 );
525 if ( hfile == INVALID_HANDLE_VALUE )
526 return FALSE;
528 /* Check binary type
530 MODULE_get_binary_info( hfile, &binary_info );
531 switch (binary_info.type)
533 case BINARY_UNKNOWN:
535 static const WCHAR comW[] = { '.','C','O','M',0 };
536 static const WCHAR pifW[] = { '.','P','I','F',0 };
537 const WCHAR *ptr;
539 /* try to determine from file name */
540 ptr = strrchrW( lpApplicationName, '.' );
541 if (!ptr) break;
542 if (!strcmpiW( ptr, comW ))
544 *lpBinaryType = SCS_DOS_BINARY;
545 ret = TRUE;
547 else if (!strcmpiW( ptr, pifW ))
549 *lpBinaryType = SCS_PIF_BINARY;
550 ret = TRUE;
552 break;
554 case BINARY_PE:
555 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
556 ret = TRUE;
557 break;
558 case BINARY_WIN16:
559 *lpBinaryType = SCS_WOW_BINARY;
560 ret = TRUE;
561 break;
562 case BINARY_OS216:
563 *lpBinaryType = SCS_OS216_BINARY;
564 ret = TRUE;
565 break;
566 case BINARY_DOS:
567 *lpBinaryType = SCS_DOS_BINARY;
568 ret = TRUE;
569 break;
570 case BINARY_UNIX_EXE:
571 case BINARY_UNIX_LIB:
572 ret = FALSE;
573 break;
576 CloseHandle( hfile );
577 return ret;
580 /***********************************************************************
581 * GetBinaryTypeA [KERNEL32.@]
582 * GetBinaryType [KERNEL32.@]
584 * See GetBinaryTypeW.
586 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
588 ANSI_STRING app_nameA;
589 NTSTATUS status;
591 TRACE("%s\n", debugstr_a(lpApplicationName));
593 /* Sanity check.
595 if ( lpApplicationName == NULL || lpBinaryType == NULL )
596 return FALSE;
598 RtlInitAnsiString(&app_nameA, lpApplicationName);
599 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
600 &app_nameA, FALSE);
601 if (!status)
602 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
604 SetLastError(RtlNtStatusToDosError(status));
605 return FALSE;
608 /***********************************************************************
609 * GetModuleHandleExA (KERNEL32.@)
611 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
613 WCHAR *nameW;
615 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
616 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
618 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
619 return GetModuleHandleExW( flags, nameW, module );
622 /***********************************************************************
623 * GetModuleHandleExW (KERNEL32.@)
625 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
627 NTSTATUS status = STATUS_SUCCESS;
628 HMODULE ret;
629 ULONG_PTR magic;
630 BOOL lock;
632 if (!module)
634 SetLastError( ERROR_INVALID_PARAMETER );
635 return FALSE;
638 /* if we are messing with the refcount, grab the loader lock */
639 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
640 if (lock)
641 LdrLockLoaderLock( 0, NULL, &magic );
643 if (!name)
645 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
647 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
649 void *dummy;
650 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
652 else
654 UNICODE_STRING wstr;
655 RtlInitUnicodeString( &wstr, name );
656 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
659 if (status == STATUS_SUCCESS)
661 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
662 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
663 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
664 LdrAddRefDll( 0, ret );
666 else SetLastError( RtlNtStatusToDosError( status ) );
668 if (lock)
669 LdrUnlockLoaderLock( 0, magic );
671 if (status == STATUS_SUCCESS) *module = ret;
672 else *module = NULL;
674 return (status == STATUS_SUCCESS);
677 /***********************************************************************
678 * GetModuleHandleA (KERNEL32.@)
680 * Get the handle of a dll loaded into the process address space.
682 * PARAMS
683 * module [I] Name of the dll
685 * RETURNS
686 * Success: A handle to the loaded dll.
687 * Failure: A NULL handle. Use GetLastError() to determine the cause.
689 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
691 HMODULE ret;
693 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
694 return ret;
697 /***********************************************************************
698 * GetModuleHandleW (KERNEL32.@)
700 * Unicode version of GetModuleHandleA.
702 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
704 HMODULE ret;
706 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
707 return ret;
711 /***********************************************************************
712 * GetModuleFileNameA (KERNEL32.@)
714 * Get the file name of a loaded module from its handle.
716 * RETURNS
717 * Success: The length of the file name, excluding the terminating NUL.
718 * Failure: 0. Use GetLastError() to determine the cause.
720 * NOTES
721 * This function always returns the long path of hModule
722 * The function doesn't write a terminating '\0' if the buffer is too
723 * small.
725 DWORD WINAPI GetModuleFileNameA(
726 HMODULE hModule, /* [in] Module handle (32 bit) */
727 LPSTR lpFileName, /* [out] Destination for file name */
728 DWORD size ) /* [in] Size of lpFileName in characters */
730 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
731 DWORD len;
733 if (!filenameW)
735 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
736 return 0;
738 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
740 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
741 if (len < size)
742 lpFileName[len] = '\0';
743 else
744 SetLastError( ERROR_INSUFFICIENT_BUFFER );
746 HeapFree( GetProcessHeap(), 0, filenameW );
747 return len;
750 /***********************************************************************
751 * GetModuleFileNameW (KERNEL32.@)
753 * Unicode version of GetModuleFileNameA.
755 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
757 ULONG len = 0;
758 ULONG_PTR magic;
759 LDR_MODULE *pldr;
760 NTSTATUS nts;
761 WIN16_SUBSYSTEM_TIB *win16_tib;
763 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
765 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
766 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
767 if (len < size) lpFileName[len] = '\0';
768 goto done;
771 LdrLockLoaderLock( 0, NULL, &magic );
773 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
774 nts = LdrFindEntryForAddress( hModule, &pldr );
775 if (nts == STATUS_SUCCESS)
777 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
778 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
779 if (len < size)
781 lpFileName[len] = '\0';
782 SetLastError( 0 );
784 else
785 SetLastError( ERROR_INSUFFICIENT_BUFFER );
787 else SetLastError( RtlNtStatusToDosError( nts ) );
789 LdrUnlockLoaderLock( 0, magic );
790 done:
791 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
792 return len;
796 /***********************************************************************
797 * get_dll_system_path
799 static const WCHAR *get_dll_system_path(void)
801 static WCHAR *cached_path;
803 if (!cached_path)
805 WCHAR *p, *path;
806 int len = 1;
808 len += 2 * GetSystemDirectoryW( NULL, 0 );
809 len += GetWindowsDirectoryW( NULL, 0 );
810 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
811 GetSystemDirectoryW( p, path + len - p);
812 p += strlenW(p);
813 /* if system directory ends in "32" add 16-bit version too */
814 if (p[-2] == '3' && p[-1] == '2')
816 *p++ = ';';
817 GetSystemDirectoryW( p, path + len - p);
818 p += strlenW(p) - 2;
820 *p++ = ';';
821 GetWindowsDirectoryW( p, path + len - p);
822 cached_path = path;
824 return cached_path;
827 /***********************************************************************
828 * get_dll_safe_mode
830 static BOOL get_dll_safe_mode(void)
832 static const WCHAR keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
833 'M','a','c','h','i','n','e','\\',
834 'S','y','s','t','e','m','\\',
835 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
836 'C','o','n','t','r','o','l','\\',
837 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
838 static const WCHAR valueW[] = {'S','a','f','e','D','l','l','S','e','a','r','c','h','M','o','d','e',0};
840 static int safe_mode = -1;
842 if (safe_mode == -1)
844 char buffer[offsetof(KEY_VALUE_PARTIAL_INFORMATION, Data[sizeof(DWORD)])];
845 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
846 OBJECT_ATTRIBUTES attr;
847 UNICODE_STRING nameW;
848 HANDLE hkey;
849 DWORD size = sizeof(buffer);
851 attr.Length = sizeof(attr);
852 attr.RootDirectory = 0;
853 attr.ObjectName = &nameW;
854 attr.Attributes = 0;
855 attr.SecurityDescriptor = NULL;
856 attr.SecurityQualityOfService = NULL;
858 safe_mode = 1;
859 RtlInitUnicodeString( &nameW, keyW );
860 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
862 RtlInitUnicodeString( &nameW, valueW );
863 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ) &&
864 info->Type == REG_DWORD && info->DataLength == sizeof(DWORD))
865 safe_mode = !!*(DWORD *)info->Data;
866 NtClose( hkey );
868 if (!safe_mode) TRACE( "SafeDllSearchMode disabled through the registry\n" );
870 return safe_mode;
873 /******************************************************************
874 * get_module_path_end
876 * Returns the end of the directory component of the module path.
878 static inline const WCHAR *get_module_path_end(const WCHAR *module)
880 const WCHAR *p;
881 const WCHAR *mod_end = module;
882 if (!module) return mod_end;
884 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
885 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
886 if (mod_end == module + 2 && module[1] == ':') mod_end++;
887 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
889 return mod_end;
893 /******************************************************************
894 * append_path_len
896 * Append a counted string to the load path. Helper for MODULE_get_dll_load_path.
898 static inline WCHAR *append_path_len( WCHAR *p, const WCHAR *str, DWORD len )
900 if (!len) return p;
901 memcpy( p, str, len * sizeof(WCHAR) );
902 p[len] = ';';
903 return p + len + 1;
907 /******************************************************************
908 * append_path
910 * Append a string to the load path. Helper for MODULE_get_dll_load_path.
912 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str )
914 return append_path_len( p, str, strlenW(str) );
918 /******************************************************************
919 * MODULE_get_dll_load_path
921 * Compute the load path to use for a given dll.
922 * Returned pointer must be freed by caller.
924 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
926 static const WCHAR pathW[] = {'P','A','T','H',0};
927 static const WCHAR dotW[] = {'.',0};
929 const WCHAR *system_path = get_dll_system_path();
930 const WCHAR *mod_end = NULL;
931 UNICODE_STRING name, value;
932 BOOL safe_mode;
933 WCHAR *p, *ret;
934 int len = 0, path_len = 0;
936 /* adjust length for module name */
938 if (module)
939 mod_end = get_module_path_end( module );
940 /* if module is NULL or doesn't contain a path, fall back to directory
941 * process was loaded from */
942 if (module == mod_end)
944 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
945 mod_end = get_module_path_end( module );
947 len += (mod_end - module) + 1;
949 len += strlenW( system_path ) + 2;
951 /* get the PATH variable */
953 RtlInitUnicodeString( &name, pathW );
954 value.Length = 0;
955 value.MaximumLength = 0;
956 value.Buffer = NULL;
957 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
958 path_len = value.Length;
960 RtlEnterCriticalSection( &dlldir_section );
961 safe_mode = get_dll_safe_mode();
962 if (dll_directory) len += strlenW(dll_directory) + 1;
963 else len += 2; /* current directory */
964 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
966 if (module) p = append_path_len( p, module, mod_end - module );
968 if (dll_directory) p = append_path( p, dll_directory );
969 else if (!safe_mode) p = append_path( p, dotW );
971 p = append_path( p, system_path );
973 if (!dll_directory && safe_mode) p = append_path( p, dotW );
975 RtlLeaveCriticalSection( &dlldir_section );
976 if (!ret) return NULL;
978 value.Buffer = p;
979 value.MaximumLength = path_len;
981 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
983 WCHAR *new_ptr;
985 /* grow the buffer and retry */
986 path_len = value.Length;
987 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
989 HeapFree( GetProcessHeap(), 0, ret );
990 return NULL;
992 value.Buffer = new_ptr + (value.Buffer - ret);
993 value.MaximumLength = path_len;
994 ret = new_ptr;
996 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
997 return ret;
1001 /******************************************************************
1002 * get_dll_load_path_search_flags
1004 static WCHAR *get_dll_load_path_search_flags( LPCWSTR module, DWORD flags )
1006 const WCHAR *image = NULL, *mod_end, *image_end;
1007 struct dll_dir_entry *dir;
1008 WCHAR *p, *ret;
1009 int len = 1;
1011 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
1012 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1013 LOAD_LIBRARY_SEARCH_USER_DIRS |
1014 LOAD_LIBRARY_SEARCH_SYSTEM32);
1016 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
1018 DWORD type = RtlDetermineDosPathNameType_U( module );
1019 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH)
1021 SetLastError( ERROR_INVALID_PARAMETER );
1022 return NULL;
1024 mod_end = get_module_path_end( module );
1025 len += (mod_end - module) + 1;
1027 else module = NULL;
1029 RtlEnterCriticalSection( &dlldir_section );
1031 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
1033 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
1034 image_end = get_module_path_end( image );
1035 len += (image_end - image) + 1;
1038 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1040 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1041 len += strlenW( dir->dir ) + 1;
1042 if (dll_directory) len += strlenW(dll_directory) + 1;
1045 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += GetSystemDirectoryW( NULL, 0 );
1047 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1049 if (module) p = append_path_len( p, module, mod_end - module );
1050 if (image) p = append_path_len( p, image, image_end - image );
1051 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1053 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1054 p = append_path( p, dir->dir );
1055 if (dll_directory) p = append_path( p, dll_directory );
1057 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) GetSystemDirectoryW( p, ret + len - p );
1058 else
1060 if (p > ret) p--;
1061 *p = 0;
1065 RtlLeaveCriticalSection( &dlldir_section );
1066 return ret;
1070 /******************************************************************
1071 * load_library_as_datafile
1073 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
1075 static const WCHAR dotDLL[] = {'.','d','l','l',0};
1077 WCHAR filenameW[MAX_PATH];
1078 HANDLE hFile = INVALID_HANDLE_VALUE;
1079 HANDLE mapping;
1080 HMODULE module;
1081 DWORD sharing = FILE_SHARE_READ;
1083 *hmod = 0;
1085 if (!(flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)) sharing |= FILE_SHARE_WRITE;
1087 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
1088 filenameW, NULL ))
1090 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
1092 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1094 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1095 CloseHandle( hFile );
1096 if (!mapping) return FALSE;
1098 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1099 CloseHandle( mapping );
1100 if (!module) return FALSE;
1102 /* make sure it's a valid PE file */
1103 if (!RtlImageNtHeader(module))
1105 UnmapViewOfFile( module );
1106 return FALSE;
1108 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
1109 return TRUE;
1113 /******************************************************************
1114 * load_library
1116 * Helper for LoadLibraryExA/W.
1118 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
1120 NTSTATUS nts;
1121 HMODULE hModule;
1122 WCHAR *load_path;
1123 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
1124 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1125 LOAD_LIBRARY_SEARCH_USER_DIRS |
1126 LOAD_LIBRARY_SEARCH_SYSTEM32 |
1127 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
1128 const DWORD unsupported_flags = (LOAD_IGNORE_CODE_AUTHZ_LEVEL |
1129 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
1130 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
1132 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
1134 if( flags & unsupported_flags)
1135 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
1137 if (flags & load_library_search_flags)
1138 load_path = get_dll_load_path_search_flags( libname->Buffer, flags );
1139 else
1140 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
1141 if (!load_path) return 0;
1143 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE))
1145 ULONG_PTR magic;
1147 LdrLockLoaderLock( 0, NULL, &magic );
1148 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
1150 LdrAddRefDll( 0, hModule );
1151 LdrUnlockLoaderLock( 0, magic );
1152 goto done;
1154 LdrUnlockLoaderLock( 0, magic );
1156 /* The method in load_library_as_datafile allows searching for the
1157 * 'native' libraries only
1159 if (load_library_as_datafile( libname->Buffer, &hModule, flags )) goto done;
1160 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1161 /* Fallback to normal behaviour */
1164 nts = LdrLoadDll( load_path, flags, libname, &hModule );
1165 if (nts != STATUS_SUCCESS)
1167 hModule = 0;
1168 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
1169 SetLastError( ERROR_DLL_NOT_FOUND );
1170 else
1171 SetLastError( RtlNtStatusToDosError( nts ) );
1173 done:
1174 HeapFree( GetProcessHeap(), 0, load_path );
1175 return hModule;
1179 /******************************************************************
1180 * LoadLibraryExA (KERNEL32.@)
1182 * Load a dll file into the process address space.
1184 * PARAMS
1185 * libname [I] Name of the file to load
1186 * hfile [I] Reserved, must be 0.
1187 * flags [I] Flags for loading the dll
1189 * RETURNS
1190 * Success: A handle to the loaded dll.
1191 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1193 * NOTES
1194 * The HFILE parameter is not used and marked reserved in the SDK. I can
1195 * only guess that it should force a file to be mapped, but I rather
1196 * ignore the parameter because it would be extremely difficult to
1197 * integrate this with different types of module representations.
1199 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1201 WCHAR *libnameW;
1203 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1204 return LoadLibraryExW( libnameW, hfile, flags );
1207 /***********************************************************************
1208 * LoadLibraryExW (KERNEL32.@)
1210 * Unicode version of LoadLibraryExA.
1212 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1214 UNICODE_STRING wstr;
1215 HMODULE res;
1217 if (!libnameW)
1219 SetLastError(ERROR_INVALID_PARAMETER);
1220 return 0;
1222 RtlInitUnicodeString( &wstr, libnameW );
1223 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1224 return load_library( &wstr, flags );
1226 /* Library name has trailing spaces */
1227 RtlCreateUnicodeString( &wstr, libnameW );
1228 while (wstr.Length > sizeof(WCHAR) &&
1229 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1231 wstr.Length -= sizeof(WCHAR);
1233 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1234 res = load_library( &wstr, flags );
1235 RtlFreeUnicodeString( &wstr );
1236 return res;
1239 /***********************************************************************
1240 * LoadLibraryA (KERNEL32.@)
1242 * Load a dll file into the process address space.
1244 * PARAMS
1245 * libname [I] Name of the file to load
1247 * RETURNS
1248 * Success: A handle to the loaded dll.
1249 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1251 * NOTES
1252 * See LoadLibraryExA().
1254 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1256 return LoadLibraryExA(libname, 0, 0);
1259 /***********************************************************************
1260 * LoadLibraryW (KERNEL32.@)
1262 * Unicode version of LoadLibraryA.
1264 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1266 return LoadLibraryExW(libnameW, 0, 0);
1269 /***********************************************************************
1270 * FreeLibrary (KERNEL32.@)
1272 * Free a dll loaded into the process address space.
1274 * PARAMS
1275 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1277 * RETURNS
1278 * Success: TRUE. The dll is removed if it is not still in use.
1279 * Failure: FALSE. Use GetLastError() to determine the cause.
1281 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1283 BOOL retv = FALSE;
1284 NTSTATUS nts;
1286 if (!hLibModule)
1288 SetLastError( ERROR_INVALID_HANDLE );
1289 return FALSE;
1292 if ((ULONG_PTR)hLibModule & 1)
1294 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1295 char *ptr = (char *)hLibModule - 1;
1296 return UnmapViewOfFile( ptr );
1299 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1300 else SetLastError( RtlNtStatusToDosError( nts ) );
1302 return retv;
1305 /***********************************************************************
1306 * GetProcAddress (KERNEL32.@)
1308 * Find the address of an exported symbol in a loaded dll.
1310 * PARAMS
1311 * hModule [I] Handle to the dll returned by LoadLibraryA().
1312 * function [I] Name of the symbol, or an integer ordinal number < 16384
1314 * RETURNS
1315 * Success: A pointer to the symbol in the process address space.
1316 * Failure: NULL. Use GetLastError() to determine the cause.
1318 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1320 NTSTATUS nts;
1321 FARPROC fp;
1323 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1325 if ((ULONG_PTR)function >> 16)
1327 ANSI_STRING str;
1329 RtlInitAnsiString( &str, function );
1330 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1332 else
1333 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1334 if (nts != STATUS_SUCCESS)
1336 SetLastError( RtlNtStatusToDosError( nts ) );
1337 fp = NULL;
1339 return fp;
1342 /***********************************************************************
1343 * DelayLoadFailureHook (KERNEL32.@)
1345 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1347 ULONG_PTR args[2];
1349 if ((ULONG_PTR)function >> 16)
1350 ERR( "failed to delay load %s.%s\n", name, function );
1351 else
1352 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1353 args[0] = (ULONG_PTR)name;
1354 args[1] = (ULONG_PTR)function;
1355 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1356 return NULL;
1359 typedef struct {
1360 HANDLE process;
1361 PLIST_ENTRY head, current;
1362 LDR_MODULE ldr_module;
1363 } MODULE_ITERATOR;
1365 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1367 PROCESS_BASIC_INFORMATION pbi;
1368 PPEB_LDR_DATA ldr_data;
1369 NTSTATUS status;
1371 /* Get address of PEB */
1372 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1373 &pbi, sizeof(pbi), NULL);
1374 if (status != STATUS_SUCCESS)
1376 SetLastError(RtlNtStatusToDosError(status));
1377 return FALSE;
1380 /* Read address of LdrData from PEB */
1381 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1382 &ldr_data, sizeof(ldr_data), NULL))
1383 return FALSE;
1385 /* Read address of first module from LdrData */
1386 if (!ReadProcessMemory(process,
1387 &ldr_data->InLoadOrderModuleList.Flink,
1388 &iter->current, sizeof(iter->current), NULL))
1389 return FALSE;
1391 iter->head = &ldr_data->InLoadOrderModuleList;
1392 iter->process = process;
1394 return TRUE;
1397 static int module_iterator_next(MODULE_ITERATOR *iter)
1399 if (iter->current == iter->head)
1400 return 0;
1402 if (!ReadProcessMemory(iter->process,
1403 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1404 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1405 return -1;
1407 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1408 return 1;
1411 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1413 MODULE_ITERATOR iter;
1414 INT ret;
1416 if (!init_module_iterator(&iter, process))
1417 return FALSE;
1419 while ((ret = module_iterator_next(&iter)) > 0)
1420 /* When hModule is NULL we return the process image - which will be
1421 * the first module since our iterator uses InLoadOrderModuleList */
1422 if (!module || module == iter.ldr_module.BaseAddress)
1424 *ldr_module = iter.ldr_module;
1425 return TRUE;
1428 if (ret == 0)
1429 SetLastError(ERROR_INVALID_HANDLE);
1431 return FALSE;
1434 /***********************************************************************
1435 * K32EnumProcessModules (KERNEL32.@)
1437 * NOTES
1438 * Returned list is in load order.
1440 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1441 DWORD cb, DWORD *needed)
1443 MODULE_ITERATOR iter;
1444 INT ret;
1446 if (!init_module_iterator(&iter, process))
1447 return FALSE;
1449 if ((cb && !lphModule) || !needed)
1451 SetLastError(ERROR_NOACCESS);
1452 return FALSE;
1455 *needed = 0;
1457 while ((ret = module_iterator_next(&iter)) > 0)
1459 if (cb >= sizeof(HMODULE))
1461 *lphModule++ = iter.ldr_module.BaseAddress;
1462 cb -= sizeof(HMODULE);
1464 *needed += sizeof(HMODULE);
1467 return ret == 0;
1470 /***********************************************************************
1471 * K32EnumProcessModulesEx (KERNEL32.@)
1473 * NOTES
1474 * Returned list is in load order.
1476 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1477 DWORD cb, DWORD *needed, DWORD filter)
1479 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1480 process, lphModule, cb, needed, filter);
1481 return K32EnumProcessModules(process, lphModule, cb, needed);
1484 /***********************************************************************
1485 * K32GetModuleBaseNameW (KERNEL32.@)
1487 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1488 LPWSTR base_name, DWORD size)
1490 LDR_MODULE ldr_module;
1492 if (!get_ldr_module(process, module, &ldr_module))
1493 return 0;
1495 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1496 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1497 base_name, size * sizeof(WCHAR), NULL))
1498 return 0;
1500 base_name[size] = 0;
1501 return size;
1504 /***********************************************************************
1505 * K32GetModuleBaseNameA (KERNEL32.@)
1507 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1508 LPSTR base_name, DWORD size)
1510 WCHAR *base_name_w;
1511 DWORD len, ret = 0;
1513 if(!base_name || !size) {
1514 SetLastError(ERROR_INVALID_PARAMETER);
1515 return 0;
1518 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1519 if(!base_name_w)
1520 return 0;
1522 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1523 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1524 if (len)
1526 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1527 base_name, size, NULL, NULL);
1528 if (ret < size) base_name[ret] = 0;
1530 HeapFree(GetProcessHeap(), 0, base_name_w);
1531 return ret;
1534 /***********************************************************************
1535 * K32GetModuleFileNameExW (KERNEL32.@)
1537 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1538 LPWSTR file_name, DWORD size)
1540 LDR_MODULE ldr_module;
1541 DWORD len;
1543 if (!size) return 0;
1545 if(!get_ldr_module(process, module, &ldr_module))
1546 return 0;
1548 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1549 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1550 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1551 return 0;
1553 if (len < size)
1555 file_name[len] = 0;
1556 return len;
1558 else
1560 file_name[size - 1] = 0;
1561 return size;
1565 /***********************************************************************
1566 * K32GetModuleFileNameExA (KERNEL32.@)
1568 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1569 LPSTR file_name, DWORD size)
1571 WCHAR *ptr;
1572 DWORD len;
1574 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1576 if (!file_name || !size)
1578 SetLastError( ERROR_INVALID_PARAMETER );
1579 return 0;
1582 if ( process == GetCurrentProcess() )
1584 len = GetModuleFileNameA( module, file_name, size );
1585 if (size) file_name[size - 1] = '\0';
1586 return len;
1589 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1591 len = K32GetModuleFileNameExW(process, module, ptr, size);
1592 if (!len)
1594 file_name[0] = '\0';
1596 else
1598 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1600 file_name[size - 1] = 0;
1601 len = size;
1603 else if (len < size) len = strlen( file_name );
1606 HeapFree(GetProcessHeap(), 0, ptr);
1607 return len;
1610 /***********************************************************************
1611 * K32GetModuleInformation (KERNEL32.@)
1613 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1614 MODULEINFO *modinfo, DWORD cb)
1616 LDR_MODULE ldr_module;
1618 if (cb < sizeof(MODULEINFO))
1620 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1621 return FALSE;
1624 if (!get_ldr_module(process, module, &ldr_module))
1625 return FALSE;
1627 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1628 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1629 modinfo->EntryPoint = ldr_module.EntryPoint;
1630 return TRUE;
1633 #ifdef __i386__
1635 /***********************************************************************
1636 * __wine_dll_register_16 (KERNEL32.@)
1638 * No longer used.
1640 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1642 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1646 /***********************************************************************
1647 * __wine_dll_unregister_16 (KERNEL32.@)
1649 * No longer used.
1651 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1655 #endif