gdiplus/metafile: Implement playback for EmfPlusRecordTypeFillPath.
[wine.git] / dlls / kernel32 / module.c
blob02c94c5f3ff8670fa299101bcc6661495f1eec6e
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, int safe_mode )
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 WCHAR *p, *ret;
933 int len = 0, path_len = 0;
935 /* adjust length for module name */
937 if (module)
938 mod_end = get_module_path_end( module );
939 /* if module is NULL or doesn't contain a path, fall back to directory
940 * process was loaded from */
941 if (module == mod_end)
943 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
944 mod_end = get_module_path_end( module );
946 len += (mod_end - module) + 1;
948 len += strlenW( system_path ) + 2;
950 /* get the PATH variable */
952 RtlInitUnicodeString( &name, pathW );
953 value.Length = 0;
954 value.MaximumLength = 0;
955 value.Buffer = NULL;
956 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
957 path_len = value.Length;
959 RtlEnterCriticalSection( &dlldir_section );
960 if (safe_mode == -1) safe_mode = get_dll_safe_mode();
961 if (dll_directory) len += strlenW(dll_directory) + 1;
962 else len += 2; /* current directory */
963 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
965 if (module) p = append_path_len( p, module, mod_end - module );
967 if (dll_directory) p = append_path( p, dll_directory );
968 else if (!safe_mode) p = append_path( p, dotW );
970 p = append_path( p, system_path );
972 if (!dll_directory && safe_mode) p = append_path( p, dotW );
974 RtlLeaveCriticalSection( &dlldir_section );
975 if (!ret) return NULL;
977 value.Buffer = p;
978 value.MaximumLength = path_len;
980 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
982 WCHAR *new_ptr;
984 /* grow the buffer and retry */
985 path_len = value.Length;
986 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
988 HeapFree( GetProcessHeap(), 0, ret );
989 return NULL;
991 value.Buffer = new_ptr + (value.Buffer - ret);
992 value.MaximumLength = path_len;
993 ret = new_ptr;
995 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
996 return ret;
1000 /******************************************************************
1001 * get_dll_load_path_search_flags
1003 static WCHAR *get_dll_load_path_search_flags( LPCWSTR module, DWORD flags )
1005 const WCHAR *image = NULL, *mod_end, *image_end;
1006 struct dll_dir_entry *dir;
1007 WCHAR *p, *ret;
1008 int len = 1;
1010 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
1011 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1012 LOAD_LIBRARY_SEARCH_USER_DIRS |
1013 LOAD_LIBRARY_SEARCH_SYSTEM32);
1015 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
1017 DWORD type = RtlDetermineDosPathNameType_U( module );
1018 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH)
1020 SetLastError( ERROR_INVALID_PARAMETER );
1021 return NULL;
1023 mod_end = get_module_path_end( module );
1024 len += (mod_end - module) + 1;
1026 else module = NULL;
1028 RtlEnterCriticalSection( &dlldir_section );
1030 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
1032 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
1033 image_end = get_module_path_end( image );
1034 len += (image_end - image) + 1;
1037 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1039 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1040 len += strlenW( dir->dir ) + 1;
1041 if (dll_directory) len += strlenW(dll_directory) + 1;
1044 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += GetSystemDirectoryW( NULL, 0 );
1046 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1048 if (module) p = append_path_len( p, module, mod_end - module );
1049 if (image) p = append_path_len( p, image, image_end - image );
1050 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1052 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1053 p = append_path( p, dir->dir );
1054 if (dll_directory) p = append_path( p, dll_directory );
1056 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) GetSystemDirectoryW( p, ret + len - p );
1057 else
1059 if (p > ret) p--;
1060 *p = 0;
1064 RtlLeaveCriticalSection( &dlldir_section );
1065 return ret;
1069 /******************************************************************
1070 * load_library_as_datafile
1072 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
1074 static const WCHAR dotDLL[] = {'.','d','l','l',0};
1076 WCHAR filenameW[MAX_PATH];
1077 HANDLE hFile = INVALID_HANDLE_VALUE;
1078 HANDLE mapping;
1079 HMODULE module;
1080 DWORD sharing = FILE_SHARE_READ;
1082 *hmod = 0;
1084 if (!(flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)) sharing |= FILE_SHARE_WRITE;
1086 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
1087 filenameW, NULL ))
1089 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
1091 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1093 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1094 CloseHandle( hFile );
1095 if (!mapping) return FALSE;
1097 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1098 CloseHandle( mapping );
1099 if (!module) return FALSE;
1101 /* make sure it's a valid PE file */
1102 if (!RtlImageNtHeader(module))
1104 UnmapViewOfFile( module );
1105 return FALSE;
1107 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
1108 return TRUE;
1112 /******************************************************************
1113 * load_library
1115 * Helper for LoadLibraryExA/W.
1117 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
1119 NTSTATUS nts;
1120 HMODULE hModule;
1121 WCHAR *load_path;
1122 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
1123 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1124 LOAD_LIBRARY_SEARCH_USER_DIRS |
1125 LOAD_LIBRARY_SEARCH_SYSTEM32 |
1126 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
1127 const DWORD unsupported_flags = (LOAD_IGNORE_CODE_AUTHZ_LEVEL |
1128 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
1129 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
1131 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
1133 if( flags & unsupported_flags)
1134 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
1136 if (flags & load_library_search_flags)
1137 load_path = get_dll_load_path_search_flags( libname->Buffer, flags );
1138 else
1139 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL, -1 );
1140 if (!load_path) return 0;
1142 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE))
1144 ULONG_PTR magic;
1146 LdrLockLoaderLock( 0, NULL, &magic );
1147 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
1149 LdrAddRefDll( 0, hModule );
1150 LdrUnlockLoaderLock( 0, magic );
1151 goto done;
1153 LdrUnlockLoaderLock( 0, magic );
1155 /* The method in load_library_as_datafile allows searching for the
1156 * 'native' libraries only
1158 if (load_library_as_datafile( libname->Buffer, &hModule, flags )) goto done;
1159 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1160 /* Fallback to normal behaviour */
1163 nts = LdrLoadDll( load_path, flags, libname, &hModule );
1164 if (nts != STATUS_SUCCESS)
1166 hModule = 0;
1167 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
1168 SetLastError( ERROR_DLL_NOT_FOUND );
1169 else
1170 SetLastError( RtlNtStatusToDosError( nts ) );
1172 done:
1173 HeapFree( GetProcessHeap(), 0, load_path );
1174 return hModule;
1178 /******************************************************************
1179 * LoadLibraryExA (KERNEL32.@)
1181 * Load a dll file into the process address space.
1183 * PARAMS
1184 * libname [I] Name of the file to load
1185 * hfile [I] Reserved, must be 0.
1186 * flags [I] Flags for loading the dll
1188 * RETURNS
1189 * Success: A handle to the loaded dll.
1190 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1192 * NOTES
1193 * The HFILE parameter is not used and marked reserved in the SDK. I can
1194 * only guess that it should force a file to be mapped, but I rather
1195 * ignore the parameter because it would be extremely difficult to
1196 * integrate this with different types of module representations.
1198 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1200 WCHAR *libnameW;
1202 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1203 return LoadLibraryExW( libnameW, hfile, flags );
1206 /***********************************************************************
1207 * LoadLibraryExW (KERNEL32.@)
1209 * Unicode version of LoadLibraryExA.
1211 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1213 UNICODE_STRING wstr;
1214 HMODULE res;
1216 if (!libnameW)
1218 SetLastError(ERROR_INVALID_PARAMETER);
1219 return 0;
1221 RtlInitUnicodeString( &wstr, libnameW );
1222 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1223 return load_library( &wstr, flags );
1225 /* Library name has trailing spaces */
1226 RtlCreateUnicodeString( &wstr, libnameW );
1227 while (wstr.Length > sizeof(WCHAR) &&
1228 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1230 wstr.Length -= sizeof(WCHAR);
1232 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1233 res = load_library( &wstr, flags );
1234 RtlFreeUnicodeString( &wstr );
1235 return res;
1238 /***********************************************************************
1239 * LoadLibraryA (KERNEL32.@)
1241 * Load a dll file into the process address space.
1243 * PARAMS
1244 * libname [I] Name of the file to load
1246 * RETURNS
1247 * Success: A handle to the loaded dll.
1248 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1250 * NOTES
1251 * See LoadLibraryExA().
1253 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1255 return LoadLibraryExA(libname, 0, 0);
1258 /***********************************************************************
1259 * LoadLibraryW (KERNEL32.@)
1261 * Unicode version of LoadLibraryA.
1263 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1265 return LoadLibraryExW(libnameW, 0, 0);
1268 /***********************************************************************
1269 * FreeLibrary (KERNEL32.@)
1271 * Free a dll loaded into the process address space.
1273 * PARAMS
1274 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1276 * RETURNS
1277 * Success: TRUE. The dll is removed if it is not still in use.
1278 * Failure: FALSE. Use GetLastError() to determine the cause.
1280 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1282 BOOL retv = FALSE;
1283 NTSTATUS nts;
1285 if (!hLibModule)
1287 SetLastError( ERROR_INVALID_HANDLE );
1288 return FALSE;
1291 if ((ULONG_PTR)hLibModule & 1)
1293 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1294 char *ptr = (char *)hLibModule - 1;
1295 return UnmapViewOfFile( ptr );
1298 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1299 else SetLastError( RtlNtStatusToDosError( nts ) );
1301 return retv;
1304 /***********************************************************************
1305 * GetProcAddress (KERNEL32.@)
1307 * Find the address of an exported symbol in a loaded dll.
1309 * PARAMS
1310 * hModule [I] Handle to the dll returned by LoadLibraryA().
1311 * function [I] Name of the symbol, or an integer ordinal number < 16384
1313 * RETURNS
1314 * Success: A pointer to the symbol in the process address space.
1315 * Failure: NULL. Use GetLastError() to determine the cause.
1317 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1319 NTSTATUS nts;
1320 FARPROC fp;
1322 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1324 if ((ULONG_PTR)function >> 16)
1326 ANSI_STRING str;
1328 RtlInitAnsiString( &str, function );
1329 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1331 else
1332 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1333 if (nts != STATUS_SUCCESS)
1335 SetLastError( RtlNtStatusToDosError( nts ) );
1336 fp = NULL;
1338 return fp;
1341 /***********************************************************************
1342 * DelayLoadFailureHook (KERNEL32.@)
1344 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1346 ULONG_PTR args[2];
1348 if ((ULONG_PTR)function >> 16)
1349 ERR( "failed to delay load %s.%s\n", name, function );
1350 else
1351 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1352 args[0] = (ULONG_PTR)name;
1353 args[1] = (ULONG_PTR)function;
1354 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1355 return NULL;
1358 typedef struct {
1359 HANDLE process;
1360 PLIST_ENTRY head, current;
1361 LDR_MODULE ldr_module;
1362 } MODULE_ITERATOR;
1364 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1366 PROCESS_BASIC_INFORMATION pbi;
1367 PPEB_LDR_DATA ldr_data;
1368 NTSTATUS status;
1370 /* Get address of PEB */
1371 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1372 &pbi, sizeof(pbi), NULL);
1373 if (status != STATUS_SUCCESS)
1375 SetLastError(RtlNtStatusToDosError(status));
1376 return FALSE;
1379 /* Read address of LdrData from PEB */
1380 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1381 &ldr_data, sizeof(ldr_data), NULL))
1382 return FALSE;
1384 /* Read address of first module from LdrData */
1385 if (!ReadProcessMemory(process,
1386 &ldr_data->InLoadOrderModuleList.Flink,
1387 &iter->current, sizeof(iter->current), NULL))
1388 return FALSE;
1390 iter->head = &ldr_data->InLoadOrderModuleList;
1391 iter->process = process;
1393 return TRUE;
1396 static int module_iterator_next(MODULE_ITERATOR *iter)
1398 if (iter->current == iter->head)
1399 return 0;
1401 if (!ReadProcessMemory(iter->process,
1402 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1403 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1404 return -1;
1406 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1407 return 1;
1410 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1412 MODULE_ITERATOR iter;
1413 INT ret;
1415 if (!init_module_iterator(&iter, process))
1416 return FALSE;
1418 while ((ret = module_iterator_next(&iter)) > 0)
1419 /* When hModule is NULL we return the process image - which will be
1420 * the first module since our iterator uses InLoadOrderModuleList */
1421 if (!module || module == iter.ldr_module.BaseAddress)
1423 *ldr_module = iter.ldr_module;
1424 return TRUE;
1427 if (ret == 0)
1428 SetLastError(ERROR_INVALID_HANDLE);
1430 return FALSE;
1433 /***********************************************************************
1434 * K32EnumProcessModules (KERNEL32.@)
1436 * NOTES
1437 * Returned list is in load order.
1439 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1440 DWORD cb, DWORD *needed)
1442 MODULE_ITERATOR iter;
1443 INT ret;
1445 if (!init_module_iterator(&iter, process))
1446 return FALSE;
1448 if ((cb && !lphModule) || !needed)
1450 SetLastError(ERROR_NOACCESS);
1451 return FALSE;
1454 *needed = 0;
1456 while ((ret = module_iterator_next(&iter)) > 0)
1458 if (cb >= sizeof(HMODULE))
1460 *lphModule++ = iter.ldr_module.BaseAddress;
1461 cb -= sizeof(HMODULE);
1463 *needed += sizeof(HMODULE);
1466 return ret == 0;
1469 /***********************************************************************
1470 * K32EnumProcessModulesEx (KERNEL32.@)
1472 * NOTES
1473 * Returned list is in load order.
1475 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1476 DWORD cb, DWORD *needed, DWORD filter)
1478 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1479 process, lphModule, cb, needed, filter);
1480 return K32EnumProcessModules(process, lphModule, cb, needed);
1483 /***********************************************************************
1484 * K32GetModuleBaseNameW (KERNEL32.@)
1486 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1487 LPWSTR base_name, DWORD size)
1489 LDR_MODULE ldr_module;
1491 if (!get_ldr_module(process, module, &ldr_module))
1492 return 0;
1494 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1495 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1496 base_name, size * sizeof(WCHAR), NULL))
1497 return 0;
1499 base_name[size] = 0;
1500 return size;
1503 /***********************************************************************
1504 * K32GetModuleBaseNameA (KERNEL32.@)
1506 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1507 LPSTR base_name, DWORD size)
1509 WCHAR *base_name_w;
1510 DWORD len, ret = 0;
1512 if(!base_name || !size) {
1513 SetLastError(ERROR_INVALID_PARAMETER);
1514 return 0;
1517 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1518 if(!base_name_w)
1519 return 0;
1521 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1522 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1523 if (len)
1525 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1526 base_name, size, NULL, NULL);
1527 if (ret < size) base_name[ret] = 0;
1529 HeapFree(GetProcessHeap(), 0, base_name_w);
1530 return ret;
1533 /***********************************************************************
1534 * K32GetModuleFileNameExW (KERNEL32.@)
1536 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1537 LPWSTR file_name, DWORD size)
1539 LDR_MODULE ldr_module;
1540 DWORD len;
1542 if (!size) return 0;
1544 if(!get_ldr_module(process, module, &ldr_module))
1545 return 0;
1547 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1548 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1549 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1550 return 0;
1552 if (len < size)
1554 file_name[len] = 0;
1555 return len;
1557 else
1559 file_name[size - 1] = 0;
1560 return size;
1564 /***********************************************************************
1565 * K32GetModuleFileNameExA (KERNEL32.@)
1567 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1568 LPSTR file_name, DWORD size)
1570 WCHAR *ptr;
1571 DWORD len;
1573 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1575 if (!file_name || !size)
1577 SetLastError( ERROR_INVALID_PARAMETER );
1578 return 0;
1581 if ( process == GetCurrentProcess() )
1583 len = GetModuleFileNameA( module, file_name, size );
1584 if (size) file_name[size - 1] = '\0';
1585 return len;
1588 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1590 len = K32GetModuleFileNameExW(process, module, ptr, size);
1591 if (!len)
1593 file_name[0] = '\0';
1595 else
1597 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1599 file_name[size - 1] = 0;
1600 len = size;
1602 else if (len < size) len = strlen( file_name );
1605 HeapFree(GetProcessHeap(), 0, ptr);
1606 return len;
1609 /***********************************************************************
1610 * K32GetModuleInformation (KERNEL32.@)
1612 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1613 MODULEINFO *modinfo, DWORD cb)
1615 LDR_MODULE ldr_module;
1617 if (cb < sizeof(MODULEINFO))
1619 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1620 return FALSE;
1623 if (!get_ldr_module(process, module, &ldr_module))
1624 return FALSE;
1626 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1627 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1628 modinfo->EntryPoint = ldr_module.EntryPoint;
1629 return TRUE;
1632 #ifdef __i386__
1634 /***********************************************************************
1635 * __wine_dll_register_16 (KERNEL32.@)
1637 * No longer used.
1639 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1641 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1645 /***********************************************************************
1646 * __wine_dll_unregister_16 (KERNEL32.@)
1648 * No longer used.
1650 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1654 #endif