wmc: Move WineHQ URLs to https.
[wine.git] / dlls / kernel32 / module.c
blobb4d5fe7c2e25db00eb6484a55b917e72a62cfd6e
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 IMAGE_NT_HEADERS64 nt64;
398 } ext_header;
400 /* We do have a DOS image so we will now try to seek into
401 * the file by the amount indicated by the field
402 * "Offset to extended header" and read in the
403 * "magic" field information at that location.
404 * This will tell us if there is more header information
405 * to read or not.
407 info->type = BINARY_DOS;
408 info->arch = IMAGE_FILE_MACHINE_I386;
409 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
410 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
412 /* Reading the magic field succeeded so
413 * we will try to determine what type it is.
415 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
417 if (len >= sizeof(ext_header.nt.FileHeader))
419 static const char fakedll_signature[] = "Wine placeholder DLL";
420 char buffer[sizeof(fakedll_signature)];
422 info->type = BINARY_PE;
423 info->arch = ext_header.nt.FileHeader.Machine;
424 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
425 info->flags |= BINARY_FLAG_DLL;
426 if (len < sizeof(ext_header)) /* clear remaining part of header if missing */
427 memset( (char *)&ext_header + len, 0, sizeof(ext_header) - len );
428 switch (ext_header.nt.OptionalHeader.Magic)
430 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
431 info->res_start = ext_header.nt.OptionalHeader.ImageBase;
432 info->res_end = info->res_start + ext_header.nt.OptionalHeader.SizeOfImage;
433 break;
434 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
435 info->res_start = ext_header.nt64.OptionalHeader.ImageBase;
436 info->res_end = info->res_start + ext_header.nt64.OptionalHeader.SizeOfImage;
437 info->flags |= BINARY_FLAG_64BIT;
438 break;
441 if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
442 SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
443 ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
444 len == sizeof(fakedll_signature) &&
445 !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
447 info->flags |= BINARY_FLAG_FAKEDLL;
451 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
453 /* This is a Windows executable (NE) header. This can
454 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
455 * DOS program (running under a DOS extender). To decide
456 * which, we'll have to read the NE header.
458 if (len >= sizeof(ext_header.os2))
460 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
461 switch ( ext_header.os2.ne_exetyp )
463 case 1: info->type = BINARY_OS216; break; /* OS/2 */
464 case 2: info->type = BINARY_WIN16; break; /* Windows */
465 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
466 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
467 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
468 /* other types, e.g. 0 is: "unknown" */
469 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
476 /***********************************************************************
477 * GetBinaryTypeW [KERNEL32.@]
479 * Determine whether a file is executable, and if so, what kind.
481 * PARAMS
482 * lpApplicationName [I] Path of the file to check
483 * lpBinaryType [O] Destination for the binary type
485 * RETURNS
486 * TRUE, if the file is an executable, in which case lpBinaryType is set.
487 * FALSE, if the file is not an executable or if the function fails.
489 * NOTES
490 * The type of executable is a property that determines which subsystem an
491 * executable file runs under. lpBinaryType can be set to one of the following
492 * values:
493 * SCS_32BIT_BINARY: A Win32 based application
494 * SCS_64BIT_BINARY: A Win64 based application
495 * SCS_DOS_BINARY: An MS-Dos based application
496 * SCS_WOW_BINARY: A Win16 based application
497 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
498 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
499 * SCS_OS216_BINARY: A 16bit OS/2 based application
501 * To find the binary type, this function reads in the files header information.
502 * If extended header information is not present it will assume that the file
503 * is a DOS executable. If extended header information is present it will
504 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
505 * flags in the header.
507 * ".com" and ".pif" files are only recognized by their file name extension,
508 * as per native Windows.
510 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
512 BOOL ret = FALSE;
513 HANDLE hfile;
514 struct binary_info binary_info;
516 TRACE("%s\n", debugstr_w(lpApplicationName) );
518 /* Sanity check.
520 if ( lpApplicationName == NULL || lpBinaryType == NULL )
521 return FALSE;
523 /* Open the file indicated by lpApplicationName for reading.
525 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
526 NULL, OPEN_EXISTING, 0, 0 );
527 if ( hfile == INVALID_HANDLE_VALUE )
528 return FALSE;
530 /* Check binary type
532 MODULE_get_binary_info( hfile, &binary_info );
533 switch (binary_info.type)
535 case BINARY_UNKNOWN:
537 static const WCHAR comW[] = { '.','C','O','M',0 };
538 static const WCHAR pifW[] = { '.','P','I','F',0 };
539 const WCHAR *ptr;
541 /* try to determine from file name */
542 ptr = strrchrW( lpApplicationName, '.' );
543 if (!ptr) break;
544 if (!strcmpiW( ptr, comW ))
546 *lpBinaryType = SCS_DOS_BINARY;
547 ret = TRUE;
549 else if (!strcmpiW( ptr, pifW ))
551 *lpBinaryType = SCS_PIF_BINARY;
552 ret = TRUE;
554 break;
556 case BINARY_PE:
557 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
558 ret = TRUE;
559 break;
560 case BINARY_WIN16:
561 *lpBinaryType = SCS_WOW_BINARY;
562 ret = TRUE;
563 break;
564 case BINARY_OS216:
565 *lpBinaryType = SCS_OS216_BINARY;
566 ret = TRUE;
567 break;
568 case BINARY_DOS:
569 *lpBinaryType = SCS_DOS_BINARY;
570 ret = TRUE;
571 break;
572 case BINARY_UNIX_EXE:
573 case BINARY_UNIX_LIB:
574 ret = FALSE;
575 break;
578 CloseHandle( hfile );
579 return ret;
582 /***********************************************************************
583 * GetBinaryTypeA [KERNEL32.@]
584 * GetBinaryType [KERNEL32.@]
586 * See GetBinaryTypeW.
588 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
590 ANSI_STRING app_nameA;
591 NTSTATUS status;
593 TRACE("%s\n", debugstr_a(lpApplicationName));
595 /* Sanity check.
597 if ( lpApplicationName == NULL || lpBinaryType == NULL )
598 return FALSE;
600 RtlInitAnsiString(&app_nameA, lpApplicationName);
601 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
602 &app_nameA, FALSE);
603 if (!status)
604 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
606 SetLastError(RtlNtStatusToDosError(status));
607 return FALSE;
610 /***********************************************************************
611 * GetModuleHandleExA (KERNEL32.@)
613 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
615 WCHAR *nameW;
617 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
618 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
620 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
621 return GetModuleHandleExW( flags, nameW, module );
624 /***********************************************************************
625 * GetModuleHandleExW (KERNEL32.@)
627 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
629 NTSTATUS status = STATUS_SUCCESS;
630 HMODULE ret;
631 ULONG_PTR magic;
632 BOOL lock;
634 if (!module)
636 SetLastError( ERROR_INVALID_PARAMETER );
637 return FALSE;
640 /* if we are messing with the refcount, grab the loader lock */
641 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
642 if (lock)
643 LdrLockLoaderLock( 0, NULL, &magic );
645 if (!name)
647 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
649 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
651 void *dummy;
652 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
654 else
656 UNICODE_STRING wstr;
657 RtlInitUnicodeString( &wstr, name );
658 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
661 if (status == STATUS_SUCCESS)
663 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
664 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
665 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
666 LdrAddRefDll( 0, ret );
668 else SetLastError( RtlNtStatusToDosError( status ) );
670 if (lock)
671 LdrUnlockLoaderLock( 0, magic );
673 if (status == STATUS_SUCCESS) *module = ret;
674 else *module = NULL;
676 return (status == STATUS_SUCCESS);
679 /***********************************************************************
680 * GetModuleHandleA (KERNEL32.@)
682 * Get the handle of a dll loaded into the process address space.
684 * PARAMS
685 * module [I] Name of the dll
687 * RETURNS
688 * Success: A handle to the loaded dll.
689 * Failure: A NULL handle. Use GetLastError() to determine the cause.
691 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
693 HMODULE ret;
695 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
696 return ret;
699 /***********************************************************************
700 * GetModuleHandleW (KERNEL32.@)
702 * Unicode version of GetModuleHandleA.
704 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
706 HMODULE ret;
708 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
709 return ret;
713 /***********************************************************************
714 * GetModuleFileNameA (KERNEL32.@)
716 * Get the file name of a loaded module from its handle.
718 * RETURNS
719 * Success: The length of the file name, excluding the terminating NUL.
720 * Failure: 0. Use GetLastError() to determine the cause.
722 * NOTES
723 * This function always returns the long path of hModule
724 * The function doesn't write a terminating '\0' if the buffer is too
725 * small.
727 DWORD WINAPI GetModuleFileNameA(
728 HMODULE hModule, /* [in] Module handle (32 bit) */
729 LPSTR lpFileName, /* [out] Destination for file name */
730 DWORD size ) /* [in] Size of lpFileName in characters */
732 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
733 DWORD len;
735 if (!filenameW)
737 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
738 return 0;
740 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
742 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
743 if (len < size)
744 lpFileName[len] = '\0';
745 else
746 SetLastError( ERROR_INSUFFICIENT_BUFFER );
748 HeapFree( GetProcessHeap(), 0, filenameW );
749 return len;
752 /***********************************************************************
753 * GetModuleFileNameW (KERNEL32.@)
755 * Unicode version of GetModuleFileNameA.
757 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
759 ULONG len = 0;
760 ULONG_PTR magic;
761 LDR_MODULE *pldr;
762 NTSTATUS nts;
763 WIN16_SUBSYSTEM_TIB *win16_tib;
765 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
767 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
768 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
769 if (len < size) lpFileName[len] = '\0';
770 goto done;
773 LdrLockLoaderLock( 0, NULL, &magic );
775 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
776 nts = LdrFindEntryForAddress( hModule, &pldr );
777 if (nts == STATUS_SUCCESS)
779 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
780 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
781 if (len < size)
783 lpFileName[len] = '\0';
784 SetLastError( 0 );
786 else
787 SetLastError( ERROR_INSUFFICIENT_BUFFER );
789 else SetLastError( RtlNtStatusToDosError( nts ) );
791 LdrUnlockLoaderLock( 0, magic );
792 done:
793 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
794 return len;
798 /***********************************************************************
799 * get_dll_system_path
801 static const WCHAR *get_dll_system_path(void)
803 static WCHAR *cached_path;
805 if (!cached_path)
807 WCHAR *p, *path;
808 int len = 1;
810 len += 2 * GetSystemDirectoryW( NULL, 0 );
811 len += GetWindowsDirectoryW( NULL, 0 );
812 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
813 GetSystemDirectoryW( p, path + len - p);
814 p += strlenW(p);
815 /* if system directory ends in "32" add 16-bit version too */
816 if (p[-2] == '3' && p[-1] == '2')
818 *p++ = ';';
819 GetSystemDirectoryW( p, path + len - p);
820 p += strlenW(p) - 2;
822 *p++ = ';';
823 GetWindowsDirectoryW( p, path + len - p);
824 cached_path = path;
826 return cached_path;
829 /***********************************************************************
830 * get_dll_safe_mode
832 static BOOL get_dll_safe_mode(void)
834 static const WCHAR keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
835 'M','a','c','h','i','n','e','\\',
836 'S','y','s','t','e','m','\\',
837 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
838 'C','o','n','t','r','o','l','\\',
839 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
840 static const WCHAR valueW[] = {'S','a','f','e','D','l','l','S','e','a','r','c','h','M','o','d','e',0};
842 static int safe_mode = -1;
844 if (safe_mode == -1)
846 char buffer[offsetof(KEY_VALUE_PARTIAL_INFORMATION, Data[sizeof(DWORD)])];
847 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
848 OBJECT_ATTRIBUTES attr;
849 UNICODE_STRING nameW;
850 HANDLE hkey;
851 DWORD size = sizeof(buffer);
853 attr.Length = sizeof(attr);
854 attr.RootDirectory = 0;
855 attr.ObjectName = &nameW;
856 attr.Attributes = 0;
857 attr.SecurityDescriptor = NULL;
858 attr.SecurityQualityOfService = NULL;
860 safe_mode = 1;
861 RtlInitUnicodeString( &nameW, keyW );
862 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
864 RtlInitUnicodeString( &nameW, valueW );
865 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ) &&
866 info->Type == REG_DWORD && info->DataLength == sizeof(DWORD))
867 safe_mode = !!*(DWORD *)info->Data;
868 NtClose( hkey );
870 if (!safe_mode) TRACE( "SafeDllSearchMode disabled through the registry\n" );
872 return safe_mode;
875 /******************************************************************
876 * get_module_path_end
878 * Returns the end of the directory component of the module path.
880 static inline const WCHAR *get_module_path_end(const WCHAR *module)
882 const WCHAR *p;
883 const WCHAR *mod_end = module;
884 if (!module) return mod_end;
886 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
887 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
888 if (mod_end == module + 2 && module[1] == ':') mod_end++;
889 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
891 return mod_end;
895 /******************************************************************
896 * append_path_len
898 * Append a counted string to the load path. Helper for MODULE_get_dll_load_path.
900 static inline WCHAR *append_path_len( WCHAR *p, const WCHAR *str, DWORD len )
902 if (!len) return p;
903 memcpy( p, str, len * sizeof(WCHAR) );
904 p[len] = ';';
905 return p + len + 1;
909 /******************************************************************
910 * append_path
912 * Append a string to the load path. Helper for MODULE_get_dll_load_path.
914 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str )
916 return append_path_len( p, str, strlenW(str) );
920 /******************************************************************
921 * MODULE_get_dll_load_path
923 * Compute the load path to use for a given dll.
924 * Returned pointer must be freed by caller.
926 WCHAR *MODULE_get_dll_load_path( LPCWSTR module, int safe_mode )
928 static const WCHAR pathW[] = {'P','A','T','H',0};
929 static const WCHAR dotW[] = {'.',0};
931 const WCHAR *system_path = get_dll_system_path();
932 const WCHAR *mod_end = NULL;
933 UNICODE_STRING name, value;
934 WCHAR *p, *ret;
935 int len = 0, path_len = 0;
937 /* adjust length for module name */
939 if (module)
940 mod_end = get_module_path_end( module );
941 /* if module is NULL or doesn't contain a path, fall back to directory
942 * process was loaded from */
943 if (module == mod_end)
945 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
946 mod_end = get_module_path_end( module );
948 len += (mod_end - module) + 1;
950 len += strlenW( system_path ) + 2;
952 /* get the PATH variable */
954 RtlInitUnicodeString( &name, pathW );
955 value.Length = 0;
956 value.MaximumLength = 0;
957 value.Buffer = NULL;
958 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
959 path_len = value.Length;
961 RtlEnterCriticalSection( &dlldir_section );
962 if (safe_mode == -1) safe_mode = get_dll_safe_mode();
963 if (dll_directory) len += strlenW(dll_directory) + 1;
964 else len += 2; /* current directory */
965 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
967 if (module) p = append_path_len( p, module, mod_end - module );
969 if (dll_directory) p = append_path( p, dll_directory );
970 else if (!safe_mode) p = append_path( p, dotW );
972 p = append_path( p, system_path );
974 if (!dll_directory && safe_mode) p = append_path( p, dotW );
976 RtlLeaveCriticalSection( &dlldir_section );
977 if (!ret) return NULL;
979 value.Buffer = p;
980 value.MaximumLength = path_len;
982 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
984 WCHAR *new_ptr;
986 /* grow the buffer and retry */
987 path_len = value.Length;
988 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
990 HeapFree( GetProcessHeap(), 0, ret );
991 return NULL;
993 value.Buffer = new_ptr + (value.Buffer - ret);
994 value.MaximumLength = path_len;
995 ret = new_ptr;
997 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
998 return ret;
1002 /******************************************************************
1003 * get_dll_load_path_search_flags
1005 static WCHAR *get_dll_load_path_search_flags( LPCWSTR module, DWORD flags )
1007 const WCHAR *image = NULL, *mod_end, *image_end;
1008 struct dll_dir_entry *dir;
1009 WCHAR *p, *ret;
1010 int len = 1;
1012 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
1013 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1014 LOAD_LIBRARY_SEARCH_USER_DIRS |
1015 LOAD_LIBRARY_SEARCH_SYSTEM32);
1017 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
1019 DWORD type = RtlDetermineDosPathNameType_U( module );
1020 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH)
1022 SetLastError( ERROR_INVALID_PARAMETER );
1023 return NULL;
1025 mod_end = get_module_path_end( module );
1026 len += (mod_end - module) + 1;
1028 else module = NULL;
1030 RtlEnterCriticalSection( &dlldir_section );
1032 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
1034 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
1035 image_end = get_module_path_end( image );
1036 len += (image_end - image) + 1;
1039 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1041 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1042 len += strlenW( dir->dir ) + 1;
1043 if (dll_directory) len += strlenW(dll_directory) + 1;
1046 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += GetSystemDirectoryW( NULL, 0 );
1048 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1050 if (module) p = append_path_len( p, module, mod_end - module );
1051 if (image) p = append_path_len( p, image, image_end - image );
1052 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1054 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1055 p = append_path( p, dir->dir );
1056 if (dll_directory) p = append_path( p, dll_directory );
1058 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) GetSystemDirectoryW( p, ret + len - p );
1059 else
1061 if (p > ret) p--;
1062 *p = 0;
1066 RtlLeaveCriticalSection( &dlldir_section );
1067 return ret;
1071 /******************************************************************
1072 * load_library_as_datafile
1074 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
1076 static const WCHAR dotDLL[] = {'.','d','l','l',0};
1078 WCHAR filenameW[MAX_PATH];
1079 HANDLE hFile = INVALID_HANDLE_VALUE;
1080 HANDLE mapping;
1081 HMODULE module;
1082 DWORD sharing = FILE_SHARE_READ;
1084 *hmod = 0;
1086 if (!(flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)) sharing |= FILE_SHARE_WRITE;
1088 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
1089 filenameW, NULL ))
1091 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
1093 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1095 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1096 CloseHandle( hFile );
1097 if (!mapping) return FALSE;
1099 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1100 CloseHandle( mapping );
1101 if (!module) return FALSE;
1103 /* make sure it's a valid PE file */
1104 if (!RtlImageNtHeader(module))
1106 UnmapViewOfFile( module );
1107 return FALSE;
1109 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
1110 return TRUE;
1114 /******************************************************************
1115 * load_library
1117 * Helper for LoadLibraryExA/W.
1119 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
1121 NTSTATUS nts;
1122 HMODULE hModule;
1123 WCHAR *load_path;
1124 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
1125 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1126 LOAD_LIBRARY_SEARCH_USER_DIRS |
1127 LOAD_LIBRARY_SEARCH_SYSTEM32 |
1128 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
1129 const DWORD unsupported_flags = (LOAD_IGNORE_CODE_AUTHZ_LEVEL |
1130 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
1131 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
1133 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
1135 if( flags & unsupported_flags)
1136 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
1138 if (flags & load_library_search_flags)
1139 load_path = get_dll_load_path_search_flags( libname->Buffer, flags );
1140 else
1141 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL, -1 );
1142 if (!load_path) return 0;
1144 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE))
1146 ULONG_PTR magic;
1148 LdrLockLoaderLock( 0, NULL, &magic );
1149 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
1151 LdrAddRefDll( 0, hModule );
1152 LdrUnlockLoaderLock( 0, magic );
1153 goto done;
1155 LdrUnlockLoaderLock( 0, magic );
1157 /* The method in load_library_as_datafile allows searching for the
1158 * 'native' libraries only
1160 if (load_library_as_datafile( libname->Buffer, &hModule, flags )) goto done;
1161 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1162 /* Fallback to normal behaviour */
1165 nts = LdrLoadDll( load_path, flags, libname, &hModule );
1166 if (nts != STATUS_SUCCESS)
1168 hModule = 0;
1169 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
1170 SetLastError( ERROR_DLL_NOT_FOUND );
1171 else
1172 SetLastError( RtlNtStatusToDosError( nts ) );
1174 done:
1175 HeapFree( GetProcessHeap(), 0, load_path );
1176 return hModule;
1180 /******************************************************************
1181 * LoadLibraryExA (KERNEL32.@)
1183 * Load a dll file into the process address space.
1185 * PARAMS
1186 * libname [I] Name of the file to load
1187 * hfile [I] Reserved, must be 0.
1188 * flags [I] Flags for loading the dll
1190 * RETURNS
1191 * Success: A handle to the loaded dll.
1192 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1194 * NOTES
1195 * The HFILE parameter is not used and marked reserved in the SDK. I can
1196 * only guess that it should force a file to be mapped, but I rather
1197 * ignore the parameter because it would be extremely difficult to
1198 * integrate this with different types of module representations.
1200 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1202 WCHAR *libnameW;
1204 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1205 return LoadLibraryExW( libnameW, hfile, flags );
1208 /***********************************************************************
1209 * LoadLibraryExW (KERNEL32.@)
1211 * Unicode version of LoadLibraryExA.
1213 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1215 UNICODE_STRING wstr;
1216 HMODULE res;
1218 if (!libnameW)
1220 SetLastError(ERROR_INVALID_PARAMETER);
1221 return 0;
1223 RtlInitUnicodeString( &wstr, libnameW );
1224 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1225 return load_library( &wstr, flags );
1227 /* Library name has trailing spaces */
1228 RtlCreateUnicodeString( &wstr, libnameW );
1229 while (wstr.Length > sizeof(WCHAR) &&
1230 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1232 wstr.Length -= sizeof(WCHAR);
1234 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1235 res = load_library( &wstr, flags );
1236 RtlFreeUnicodeString( &wstr );
1237 return res;
1240 /***********************************************************************
1241 * LoadLibraryA (KERNEL32.@)
1243 * Load a dll file into the process address space.
1245 * PARAMS
1246 * libname [I] Name of the file to load
1248 * RETURNS
1249 * Success: A handle to the loaded dll.
1250 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1252 * NOTES
1253 * See LoadLibraryExA().
1255 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1257 return LoadLibraryExA(libname, 0, 0);
1260 /***********************************************************************
1261 * LoadLibraryW (KERNEL32.@)
1263 * Unicode version of LoadLibraryA.
1265 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1267 return LoadLibraryExW(libnameW, 0, 0);
1270 /***********************************************************************
1271 * FreeLibrary (KERNEL32.@)
1273 * Free a dll loaded into the process address space.
1275 * PARAMS
1276 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1278 * RETURNS
1279 * Success: TRUE. The dll is removed if it is not still in use.
1280 * Failure: FALSE. Use GetLastError() to determine the cause.
1282 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1284 BOOL retv = FALSE;
1285 NTSTATUS nts;
1287 if (!hLibModule)
1289 SetLastError( ERROR_INVALID_HANDLE );
1290 return FALSE;
1293 if ((ULONG_PTR)hLibModule & 1)
1295 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1296 char *ptr = (char *)hLibModule - 1;
1297 return UnmapViewOfFile( ptr );
1300 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1301 else SetLastError( RtlNtStatusToDosError( nts ) );
1303 return retv;
1306 /***********************************************************************
1307 * GetProcAddress (KERNEL32.@)
1309 * Find the address of an exported symbol in a loaded dll.
1311 * PARAMS
1312 * hModule [I] Handle to the dll returned by LoadLibraryA().
1313 * function [I] Name of the symbol, or an integer ordinal number < 16384
1315 * RETURNS
1316 * Success: A pointer to the symbol in the process address space.
1317 * Failure: NULL. Use GetLastError() to determine the cause.
1319 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1321 NTSTATUS nts;
1322 FARPROC fp;
1324 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1326 if ((ULONG_PTR)function >> 16)
1328 ANSI_STRING str;
1330 RtlInitAnsiString( &str, function );
1331 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1333 else
1334 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1335 if (nts != STATUS_SUCCESS)
1337 SetLastError( RtlNtStatusToDosError( nts ) );
1338 fp = NULL;
1340 return fp;
1343 /***********************************************************************
1344 * DelayLoadFailureHook (KERNEL32.@)
1346 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1348 ULONG_PTR args[2];
1350 if ((ULONG_PTR)function >> 16)
1351 ERR( "failed to delay load %s.%s\n", name, function );
1352 else
1353 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1354 args[0] = (ULONG_PTR)name;
1355 args[1] = (ULONG_PTR)function;
1356 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1357 return NULL;
1360 typedef struct {
1361 HANDLE process;
1362 PLIST_ENTRY head, current;
1363 LDR_MODULE ldr_module;
1364 } MODULE_ITERATOR;
1366 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1368 PROCESS_BASIC_INFORMATION pbi;
1369 PPEB_LDR_DATA ldr_data;
1370 NTSTATUS status;
1372 /* Get address of PEB */
1373 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1374 &pbi, sizeof(pbi), NULL);
1375 if (status != STATUS_SUCCESS)
1377 SetLastError(RtlNtStatusToDosError(status));
1378 return FALSE;
1381 /* Read address of LdrData from PEB */
1382 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1383 &ldr_data, sizeof(ldr_data), NULL))
1384 return FALSE;
1386 /* Read address of first module from LdrData */
1387 if (!ReadProcessMemory(process,
1388 &ldr_data->InLoadOrderModuleList.Flink,
1389 &iter->current, sizeof(iter->current), NULL))
1390 return FALSE;
1392 iter->head = &ldr_data->InLoadOrderModuleList;
1393 iter->process = process;
1395 return TRUE;
1398 static int module_iterator_next(MODULE_ITERATOR *iter)
1400 if (iter->current == iter->head)
1401 return 0;
1403 if (!ReadProcessMemory(iter->process,
1404 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1405 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1406 return -1;
1408 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1409 return 1;
1412 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1414 MODULE_ITERATOR iter;
1415 INT ret;
1417 if (!init_module_iterator(&iter, process))
1418 return FALSE;
1420 while ((ret = module_iterator_next(&iter)) > 0)
1421 /* When hModule is NULL we return the process image - which will be
1422 * the first module since our iterator uses InLoadOrderModuleList */
1423 if (!module || module == iter.ldr_module.BaseAddress)
1425 *ldr_module = iter.ldr_module;
1426 return TRUE;
1429 if (ret == 0)
1430 SetLastError(ERROR_INVALID_HANDLE);
1432 return FALSE;
1435 /***********************************************************************
1436 * K32EnumProcessModules (KERNEL32.@)
1438 * NOTES
1439 * Returned list is in load order.
1441 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1442 DWORD cb, DWORD *needed)
1444 MODULE_ITERATOR iter;
1445 INT ret;
1447 if (!init_module_iterator(&iter, process))
1448 return FALSE;
1450 if ((cb && !lphModule) || !needed)
1452 SetLastError(ERROR_NOACCESS);
1453 return FALSE;
1456 *needed = 0;
1458 while ((ret = module_iterator_next(&iter)) > 0)
1460 if (cb >= sizeof(HMODULE))
1462 *lphModule++ = iter.ldr_module.BaseAddress;
1463 cb -= sizeof(HMODULE);
1465 *needed += sizeof(HMODULE);
1468 return ret == 0;
1471 /***********************************************************************
1472 * K32EnumProcessModulesEx (KERNEL32.@)
1474 * NOTES
1475 * Returned list is in load order.
1477 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1478 DWORD cb, DWORD *needed, DWORD filter)
1480 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1481 process, lphModule, cb, needed, filter);
1482 return K32EnumProcessModules(process, lphModule, cb, needed);
1485 /***********************************************************************
1486 * K32GetModuleBaseNameW (KERNEL32.@)
1488 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1489 LPWSTR base_name, DWORD size)
1491 LDR_MODULE ldr_module;
1493 if (!get_ldr_module(process, module, &ldr_module))
1494 return 0;
1496 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1497 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1498 base_name, size * sizeof(WCHAR), NULL))
1499 return 0;
1501 base_name[size] = 0;
1502 return size;
1505 /***********************************************************************
1506 * K32GetModuleBaseNameA (KERNEL32.@)
1508 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1509 LPSTR base_name, DWORD size)
1511 WCHAR *base_name_w;
1512 DWORD len, ret = 0;
1514 if(!base_name || !size) {
1515 SetLastError(ERROR_INVALID_PARAMETER);
1516 return 0;
1519 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1520 if(!base_name_w)
1521 return 0;
1523 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1524 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1525 if (len)
1527 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1528 base_name, size, NULL, NULL);
1529 if (ret < size) base_name[ret] = 0;
1531 HeapFree(GetProcessHeap(), 0, base_name_w);
1532 return ret;
1535 /***********************************************************************
1536 * K32GetModuleFileNameExW (KERNEL32.@)
1538 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1539 LPWSTR file_name, DWORD size)
1541 LDR_MODULE ldr_module;
1542 DWORD len;
1544 if (!size) return 0;
1546 if(!get_ldr_module(process, module, &ldr_module))
1547 return 0;
1549 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1550 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1551 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1552 return 0;
1554 if (len < size)
1556 file_name[len] = 0;
1557 return len;
1559 else
1561 file_name[size - 1] = 0;
1562 return size;
1566 /***********************************************************************
1567 * K32GetModuleFileNameExA (KERNEL32.@)
1569 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1570 LPSTR file_name, DWORD size)
1572 WCHAR *ptr;
1573 DWORD len;
1575 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1577 if (!file_name || !size)
1579 SetLastError( ERROR_INVALID_PARAMETER );
1580 return 0;
1583 if ( process == GetCurrentProcess() )
1585 len = GetModuleFileNameA( module, file_name, size );
1586 if (size) file_name[size - 1] = '\0';
1587 return len;
1590 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1592 len = K32GetModuleFileNameExW(process, module, ptr, size);
1593 if (!len)
1595 file_name[0] = '\0';
1597 else
1599 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1601 file_name[size - 1] = 0;
1602 len = size;
1604 else if (len < size) len = strlen( file_name );
1607 HeapFree(GetProcessHeap(), 0, ptr);
1608 return len;
1611 /***********************************************************************
1612 * K32GetModuleInformation (KERNEL32.@)
1614 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1615 MODULEINFO *modinfo, DWORD cb)
1617 LDR_MODULE ldr_module;
1619 if (cb < sizeof(MODULEINFO))
1621 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1622 return FALSE;
1625 if (!get_ldr_module(process, module, &ldr_module))
1626 return FALSE;
1628 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1629 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1630 modinfo->EntryPoint = ldr_module.EntryPoint;
1631 return TRUE;
1634 #ifdef __i386__
1636 /***********************************************************************
1637 * __wine_dll_register_16 (KERNEL32.@)
1639 * No longer used.
1641 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1643 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1647 /***********************************************************************
1648 * __wine_dll_unregister_16 (KERNEL32.@)
1650 * No longer used.
1652 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1656 #endif