wined3d: Get rid of convert_p8_uint_b8g8r8a8_unorm().
[wine.git] / dlls / kernel32 / module.c
blob6f123ca219780ed34e747e5c6f40049a9fb6e708
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <fcntl.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include "ntstatus.h"
34 #define WIN32_NO_STATUS
35 #include "winerror.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winternl.h"
39 #include "kernel_private.h"
40 #include "psapi.h"
42 #include "wine/exception.h"
43 #include "wine/list.h"
44 #include "wine/debug.h"
45 #include "wine/unicode.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 #define NE_FFLAGS_LIBMODULE 0x8000
51 struct dll_dir_entry
53 struct list entry;
54 WCHAR dir[1];
57 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from AddDllDirectory */
58 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
59 static DWORD default_search_flags; /* default flags set by SetDefaultDllDirectories */
61 /* to keep track of LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE file handles */
62 struct exclusive_datafile
64 struct list entry;
65 HMODULE module;
66 HANDLE file;
68 static struct list exclusive_datafile_list = LIST_INIT( exclusive_datafile_list );
70 static CRITICAL_SECTION dlldir_section;
71 static CRITICAL_SECTION_DEBUG critsect_debug =
73 0, 0, &dlldir_section,
74 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
75 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
77 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
79 /****************************************************************************
80 * GetDllDirectoryA (KERNEL32.@)
82 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
84 DWORD len;
86 RtlEnterCriticalSection( &dlldir_section );
87 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
88 if (buffer && buf_len > len)
90 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
91 else *buffer = 0;
93 else
95 len++; /* for terminating null */
96 if (buffer) *buffer = 0;
98 RtlLeaveCriticalSection( &dlldir_section );
99 return len;
103 /****************************************************************************
104 * GetDllDirectoryW (KERNEL32.@)
106 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
108 DWORD len;
110 RtlEnterCriticalSection( &dlldir_section );
111 len = dll_directory ? strlenW( dll_directory ) : 0;
112 if (buffer && buf_len > len)
114 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
115 else *buffer = 0;
117 else
119 len++; /* for terminating null */
120 if (buffer) *buffer = 0;
122 RtlLeaveCriticalSection( &dlldir_section );
123 return len;
127 /****************************************************************************
128 * SetDllDirectoryA (KERNEL32.@)
130 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
132 WCHAR *dirW;
133 BOOL ret;
135 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
136 ret = SetDllDirectoryW( dirW );
137 HeapFree( GetProcessHeap(), 0, dirW );
138 return ret;
142 /****************************************************************************
143 * SetDllDirectoryW (KERNEL32.@)
145 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
147 WCHAR *newdir = NULL;
149 if (dir)
151 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
152 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
154 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
155 return FALSE;
157 memcpy( newdir, dir, len );
160 RtlEnterCriticalSection( &dlldir_section );
161 HeapFree( GetProcessHeap(), 0, dll_directory );
162 dll_directory = newdir;
163 RtlLeaveCriticalSection( &dlldir_section );
164 return TRUE;
168 /****************************************************************************
169 * AddDllDirectory (KERNEL32.@)
171 DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory( const WCHAR *dir )
173 WCHAR path[MAX_PATH];
174 DWORD len;
175 struct dll_dir_entry *ptr;
176 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir );
178 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
180 SetLastError( ERROR_INVALID_PARAMETER );
181 return NULL;
183 if (!(len = GetFullPathNameW( dir, MAX_PATH, path, NULL ))) return NULL;
184 if (GetFileAttributesW( path ) == INVALID_FILE_ATTRIBUTES) return NULL;
186 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] )))) return NULL;
187 memcpy( ptr->dir, path, len * sizeof(WCHAR) );
188 TRACE( "%s\n", debugstr_w( ptr->dir ));
190 RtlEnterCriticalSection( &dlldir_section );
191 list_add_head( &dll_dir_list, &ptr->entry );
192 RtlLeaveCriticalSection( &dlldir_section );
193 return ptr;
197 /****************************************************************************
198 * RemoveDllDirectory (KERNEL32.@)
200 BOOL WINAPI RemoveDllDirectory( DLL_DIRECTORY_COOKIE cookie )
202 struct dll_dir_entry *ptr = cookie;
204 TRACE( "%s\n", debugstr_w( ptr->dir ));
206 RtlEnterCriticalSection( &dlldir_section );
207 list_remove( &ptr->entry );
208 HeapFree( GetProcessHeap(), 0, ptr );
209 RtlLeaveCriticalSection( &dlldir_section );
210 return TRUE;
214 /*************************************************************************
215 * SetDefaultDllDirectories (KERNEL32.@)
217 BOOL WINAPI SetDefaultDllDirectories( DWORD flags )
219 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
220 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
221 LOAD_LIBRARY_SEARCH_USER_DIRS |
222 LOAD_LIBRARY_SEARCH_SYSTEM32 |
223 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
225 if (!flags || (flags & ~load_library_search_flags))
227 SetLastError( ERROR_INVALID_PARAMETER );
228 return FALSE;
230 default_search_flags = flags;
231 return TRUE;
235 /****************************************************************************
236 * DisableThreadLibraryCalls (KERNEL32.@)
238 * Inform the module loader that thread notifications are not required for a dll.
240 * PARAMS
241 * hModule [I] Module handle to skip calls for
243 * RETURNS
244 * Success: TRUE. Thread attach and detach notifications will not be sent
245 * to hModule.
246 * Failure: FALSE. Use GetLastError() to determine the cause.
248 * NOTES
249 * This is typically called from the dll entry point of a dll during process
250 * attachment, for dlls that do not need to process thread notifications.
252 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
254 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
255 if (nts == STATUS_SUCCESS) return TRUE;
257 SetLastError( RtlNtStatusToDosError( nts ) );
258 return FALSE;
262 /* Check whether a file is an OS/2 or a very old Windows executable
263 * by testing on import of KERNEL.
265 * Reading the module imports is the only reasonable way of discerning
266 * old Windows binaries from OS/2 ones.
268 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
270 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
271 DWORD ret = BINARY_OS216;
272 LPWORD modtab = NULL;
273 LPSTR nametab = NULL;
274 DWORD len;
275 int i;
277 /* read modref table */
278 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
279 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
280 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
281 || (len != ne->ne_cmod*sizeof(WORD)) )
282 goto done;
284 /* read imported names table */
285 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
286 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
287 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
288 || (len != ne->ne_enttab - ne->ne_imptab) )
289 goto done;
291 for (i=0; i < ne->ne_cmod; i++)
293 LPSTR module = &nametab[modtab[i]];
294 TRACE("modref: %.*s\n", module[0], &module[1]);
295 if (!(strncmp(&module[1], "KERNEL", module[0])))
296 { /* very old Windows file */
297 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
298 ret = BINARY_WIN16;
299 break;
303 done:
304 HeapFree( GetProcessHeap(), 0, modtab);
305 HeapFree( GetProcessHeap(), 0, nametab);
306 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
307 return ret;
310 /***********************************************************************
311 * MODULE_GetBinaryType
313 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
315 union
317 struct
319 unsigned char magic[4];
320 unsigned char class;
321 unsigned char data;
322 unsigned char ignored1[10];
323 unsigned short type;
324 unsigned short machine;
325 unsigned char ignored2[8];
326 unsigned int phoff;
327 unsigned char ignored3[12];
328 unsigned short phnum;
329 } elf;
330 struct
332 unsigned char magic[4];
333 unsigned char class;
334 unsigned char data;
335 unsigned char ignored1[10];
336 unsigned short type;
337 unsigned short machine;
338 unsigned char ignored2[12];
339 unsigned __int64 phoff;
340 unsigned char ignored3[16];
341 unsigned short phnum;
342 } elf64;
343 struct
345 unsigned int magic;
346 unsigned int cputype;
347 unsigned int cpusubtype;
348 unsigned int filetype;
349 } macho;
350 IMAGE_DOS_HEADER mz;
351 } header;
353 DWORD len;
355 memset( info, 0, sizeof(*info) );
357 /* Seek to the start of the file and read the header information. */
358 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
359 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
361 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
363 #ifdef WORDS_BIGENDIAN
364 BOOL byteswap = (header.elf.data == 1);
365 #else
366 BOOL byteswap = (header.elf.data == 2);
367 #endif
368 if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
369 if (byteswap)
371 header.elf.type = RtlUshortByteSwap( header.elf.type );
372 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
374 switch(header.elf.type)
376 case 2:
377 info->type = BINARY_UNIX_EXE;
378 break;
379 case 3:
381 LARGE_INTEGER phoff;
382 unsigned short phnum;
383 unsigned int type;
384 if (header.elf.class == 2)
386 phoff.QuadPart = byteswap ? RtlUlonglongByteSwap( header.elf64.phoff ) : header.elf64.phoff;
387 phnum = byteswap ? RtlUshortByteSwap( header.elf64.phnum ) : header.elf64.phnum;
389 else
391 phoff.QuadPart = byteswap ? RtlUlongByteSwap( header.elf.phoff ) : header.elf.phoff;
392 phnum = byteswap ? RtlUshortByteSwap( header.elf.phnum ) : header.elf.phnum;
394 while (phnum--)
396 if (SetFilePointerEx( hfile, phoff, NULL, FILE_BEGIN ) == -1) return;
397 if (!ReadFile( hfile, &type, sizeof(type), &len, NULL ) || len < sizeof(type)) return;
398 if (byteswap) type = RtlUlongByteSwap( type );
399 if (type == 3)
401 info->type = BINARY_UNIX_EXE;
402 break;
404 phoff.QuadPart += (header.elf.class == 2) ? 56 : 32;
406 if (!info->type) info->type = BINARY_UNIX_LIB;
407 break;
409 default:
410 return;
412 switch(header.elf.machine)
414 case 3: info->arch = IMAGE_FILE_MACHINE_I386; break;
415 case 20: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
416 case 40: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
417 case 50: info->arch = IMAGE_FILE_MACHINE_IA64; break;
418 case 62: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
419 case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
422 /* Mach-o File with Endian set to Big Endian or Little Endian */
423 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
424 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
426 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
427 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
429 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
430 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
432 switch(header.macho.filetype)
434 case 2: info->type = BINARY_UNIX_EXE; break;
435 case 8: info->type = BINARY_UNIX_LIB; break;
437 switch(header.macho.cputype)
439 case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
440 case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
441 case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
442 case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
443 case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
446 /* Not ELF, try DOS */
447 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
449 union
451 IMAGE_OS2_HEADER os2;
452 IMAGE_NT_HEADERS32 nt;
453 IMAGE_NT_HEADERS64 nt64;
454 } ext_header;
456 /* We do have a DOS image so we will now try to seek into
457 * the file by the amount indicated by the field
458 * "Offset to extended header" and read in the
459 * "magic" field information at that location.
460 * This will tell us if there is more header information
461 * to read or not.
463 info->type = BINARY_DOS;
464 info->arch = IMAGE_FILE_MACHINE_I386;
465 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
466 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
468 /* Reading the magic field succeeded so
469 * we will try to determine what type it is.
471 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
473 if (len >= sizeof(ext_header.nt.FileHeader))
475 static const char fakedll_signature[] = "Wine placeholder DLL";
476 char buffer[sizeof(fakedll_signature)];
478 info->type = BINARY_PE;
479 info->arch = ext_header.nt.FileHeader.Machine;
480 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
481 info->flags |= BINARY_FLAG_DLL;
482 if (len < sizeof(ext_header)) /* clear remaining part of header if missing */
483 memset( (char *)&ext_header + len, 0, sizeof(ext_header) - len );
484 switch (ext_header.nt.OptionalHeader.Magic)
486 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
487 info->res_start = ext_header.nt.OptionalHeader.ImageBase;
488 info->res_end = info->res_start + ext_header.nt.OptionalHeader.SizeOfImage;
489 break;
490 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
491 info->res_start = ext_header.nt64.OptionalHeader.ImageBase;
492 info->res_end = info->res_start + ext_header.nt64.OptionalHeader.SizeOfImage;
493 info->flags |= BINARY_FLAG_64BIT;
494 break;
497 if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
498 SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
499 ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
500 len == sizeof(fakedll_signature) &&
501 !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
503 info->flags |= BINARY_FLAG_FAKEDLL;
507 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
509 /* This is a Windows executable (NE) header. This can
510 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
511 * DOS program (running under a DOS extender). To decide
512 * which, we'll have to read the NE header.
514 if (len >= sizeof(ext_header.os2))
516 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
517 switch ( ext_header.os2.ne_exetyp )
519 case 1: info->type = BINARY_OS216; break; /* OS/2 */
520 case 2: info->type = BINARY_WIN16; break; /* Windows */
521 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
522 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
523 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
524 /* other types, e.g. 0 is: "unknown" */
525 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
532 /***********************************************************************
533 * GetBinaryTypeW [KERNEL32.@]
535 * Determine whether a file is executable, and if so, what kind.
537 * PARAMS
538 * lpApplicationName [I] Path of the file to check
539 * lpBinaryType [O] Destination for the binary type
541 * RETURNS
542 * TRUE, if the file is an executable, in which case lpBinaryType is set.
543 * FALSE, if the file is not an executable or if the function fails.
545 * NOTES
546 * The type of executable is a property that determines which subsystem an
547 * executable file runs under. lpBinaryType can be set to one of the following
548 * values:
549 * SCS_32BIT_BINARY: A Win32 based application
550 * SCS_64BIT_BINARY: A Win64 based application
551 * SCS_DOS_BINARY: An MS-Dos based application
552 * SCS_WOW_BINARY: A Win16 based application
553 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
554 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
555 * SCS_OS216_BINARY: A 16bit OS/2 based application
557 * To find the binary type, this function reads in the files header information.
558 * If extended header information is not present it will assume that the file
559 * is a DOS executable. If extended header information is present it will
560 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
561 * flags in the header.
563 * ".com" and ".pif" files are only recognized by their file name extension,
564 * as per native Windows.
566 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
568 BOOL ret = FALSE;
569 HANDLE hfile;
570 struct binary_info binary_info;
572 TRACE("%s\n", debugstr_w(lpApplicationName) );
574 /* Sanity check.
576 if ( lpApplicationName == NULL || lpBinaryType == NULL )
577 return FALSE;
579 /* Open the file indicated by lpApplicationName for reading.
581 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
582 NULL, OPEN_EXISTING, 0, 0 );
583 if ( hfile == INVALID_HANDLE_VALUE )
584 return FALSE;
586 /* Check binary type
588 MODULE_get_binary_info( hfile, &binary_info );
589 switch (binary_info.type)
591 case BINARY_UNKNOWN:
593 static const WCHAR comW[] = { '.','C','O','M',0 };
594 static const WCHAR pifW[] = { '.','P','I','F',0 };
595 const WCHAR *ptr;
597 /* try to determine from file name */
598 ptr = strrchrW( lpApplicationName, '.' );
599 if (!ptr) break;
600 if (!strcmpiW( ptr, comW ))
602 *lpBinaryType = SCS_DOS_BINARY;
603 ret = TRUE;
605 else if (!strcmpiW( ptr, pifW ))
607 *lpBinaryType = SCS_PIF_BINARY;
608 ret = TRUE;
610 break;
612 case BINARY_PE:
613 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
614 ret = TRUE;
615 break;
616 case BINARY_WIN16:
617 *lpBinaryType = SCS_WOW_BINARY;
618 ret = TRUE;
619 break;
620 case BINARY_OS216:
621 *lpBinaryType = SCS_OS216_BINARY;
622 ret = TRUE;
623 break;
624 case BINARY_DOS:
625 *lpBinaryType = SCS_DOS_BINARY;
626 ret = TRUE;
627 break;
628 case BINARY_UNIX_EXE:
629 case BINARY_UNIX_LIB:
630 ret = FALSE;
631 break;
634 CloseHandle( hfile );
635 return ret;
638 /***********************************************************************
639 * GetBinaryTypeA [KERNEL32.@]
640 * GetBinaryType [KERNEL32.@]
642 * See GetBinaryTypeW.
644 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
646 ANSI_STRING app_nameA;
647 NTSTATUS status;
649 TRACE("%s\n", debugstr_a(lpApplicationName));
651 /* Sanity check.
653 if ( lpApplicationName == NULL || lpBinaryType == NULL )
654 return FALSE;
656 RtlInitAnsiString(&app_nameA, lpApplicationName);
657 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
658 &app_nameA, FALSE);
659 if (!status)
660 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
662 SetLastError(RtlNtStatusToDosError(status));
663 return FALSE;
666 /***********************************************************************
667 * GetModuleHandleExA (KERNEL32.@)
669 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
671 WCHAR *nameW;
673 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
674 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
676 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
677 return GetModuleHandleExW( flags, nameW, module );
680 /***********************************************************************
681 * GetModuleHandleExW (KERNEL32.@)
683 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
685 NTSTATUS status = STATUS_SUCCESS;
686 HMODULE ret;
687 ULONG_PTR magic;
688 BOOL lock;
690 if (!module)
692 SetLastError( ERROR_INVALID_PARAMETER );
693 return FALSE;
696 /* if we are messing with the refcount, grab the loader lock */
697 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
698 if (lock)
699 LdrLockLoaderLock( 0, NULL, &magic );
701 if (!name)
703 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
705 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
707 void *dummy;
708 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
710 else
712 UNICODE_STRING wstr;
713 RtlInitUnicodeString( &wstr, name );
714 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
717 if (status == STATUS_SUCCESS)
719 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
720 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
721 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
722 LdrAddRefDll( 0, ret );
724 else SetLastError( RtlNtStatusToDosError( status ) );
726 if (lock)
727 LdrUnlockLoaderLock( 0, magic );
729 if (status == STATUS_SUCCESS) *module = ret;
730 else *module = NULL;
732 return (status == STATUS_SUCCESS);
735 /***********************************************************************
736 * GetModuleHandleA (KERNEL32.@)
738 * Get the handle of a dll loaded into the process address space.
740 * PARAMS
741 * module [I] Name of the dll
743 * RETURNS
744 * Success: A handle to the loaded dll.
745 * Failure: A NULL handle. Use GetLastError() to determine the cause.
747 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
749 HMODULE ret;
751 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
752 return ret;
755 /***********************************************************************
756 * GetModuleHandleW (KERNEL32.@)
758 * Unicode version of GetModuleHandleA.
760 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
762 HMODULE ret;
764 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
765 return ret;
769 /***********************************************************************
770 * GetModuleFileNameA (KERNEL32.@)
772 * Get the file name of a loaded module from its handle.
774 * RETURNS
775 * Success: The length of the file name, excluding the terminating NUL.
776 * Failure: 0. Use GetLastError() to determine the cause.
778 * NOTES
779 * This function always returns the long path of hModule
780 * The function doesn't write a terminating '\0' if the buffer is too
781 * small.
783 DWORD WINAPI GetModuleFileNameA(
784 HMODULE hModule, /* [in] Module handle (32 bit) */
785 LPSTR lpFileName, /* [out] Destination for file name */
786 DWORD size ) /* [in] Size of lpFileName in characters */
788 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
789 DWORD len;
791 if (!filenameW)
793 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
794 return 0;
796 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
798 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
799 if (len < size)
800 lpFileName[len] = '\0';
801 else
802 SetLastError( ERROR_INSUFFICIENT_BUFFER );
804 HeapFree( GetProcessHeap(), 0, filenameW );
805 return len;
808 /***********************************************************************
809 * GetModuleFileNameW (KERNEL32.@)
811 * Unicode version of GetModuleFileNameA.
813 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
815 ULONG len = 0;
816 ULONG_PTR magic;
817 LDR_MODULE *pldr;
818 NTSTATUS nts;
819 WIN16_SUBSYSTEM_TIB *win16_tib;
821 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
823 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
824 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
825 if (len < size) lpFileName[len] = '\0';
826 goto done;
829 LdrLockLoaderLock( 0, NULL, &magic );
831 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
832 nts = LdrFindEntryForAddress( hModule, &pldr );
833 if (nts == STATUS_SUCCESS)
835 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
836 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
837 if (len < size)
839 lpFileName[len] = '\0';
840 SetLastError( 0 );
842 else
843 SetLastError( ERROR_INSUFFICIENT_BUFFER );
845 else SetLastError( RtlNtStatusToDosError( nts ) );
847 LdrUnlockLoaderLock( 0, magic );
848 done:
849 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
850 return len;
854 /***********************************************************************
855 * get_dll_system_path
857 static const WCHAR *get_dll_system_path(void)
859 static WCHAR *cached_path;
861 if (!cached_path)
863 WCHAR *p, *path;
864 int len = 1;
866 len += 2 * GetSystemDirectoryW( NULL, 0 );
867 len += GetWindowsDirectoryW( NULL, 0 );
868 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
869 GetSystemDirectoryW( p, path + len - p);
870 p += strlenW(p);
871 /* if system directory ends in "32" add 16-bit version too */
872 if (p[-2] == '3' && p[-1] == '2')
874 *p++ = ';';
875 GetSystemDirectoryW( p, path + len - p);
876 p += strlenW(p) - 2;
878 *p++ = ';';
879 GetWindowsDirectoryW( p, path + len - p);
880 cached_path = path;
882 return cached_path;
885 /***********************************************************************
886 * get_dll_safe_mode
888 static BOOL get_dll_safe_mode(void)
890 static const WCHAR keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
891 'M','a','c','h','i','n','e','\\',
892 'S','y','s','t','e','m','\\',
893 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
894 'C','o','n','t','r','o','l','\\',
895 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
896 static const WCHAR valueW[] = {'S','a','f','e','D','l','l','S','e','a','r','c','h','M','o','d','e',0};
898 static int safe_mode = -1;
900 if (safe_mode == -1)
902 char buffer[offsetof(KEY_VALUE_PARTIAL_INFORMATION, Data[sizeof(DWORD)])];
903 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
904 OBJECT_ATTRIBUTES attr;
905 UNICODE_STRING nameW;
906 HANDLE hkey;
907 DWORD size = sizeof(buffer);
909 attr.Length = sizeof(attr);
910 attr.RootDirectory = 0;
911 attr.ObjectName = &nameW;
912 attr.Attributes = 0;
913 attr.SecurityDescriptor = NULL;
914 attr.SecurityQualityOfService = NULL;
916 safe_mode = 1;
917 RtlInitUnicodeString( &nameW, keyW );
918 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
920 RtlInitUnicodeString( &nameW, valueW );
921 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ) &&
922 info->Type == REG_DWORD && info->DataLength == sizeof(DWORD))
923 safe_mode = !!*(DWORD *)info->Data;
924 NtClose( hkey );
926 if (!safe_mode) TRACE( "SafeDllSearchMode disabled through the registry\n" );
928 return safe_mode;
931 /******************************************************************
932 * get_module_path_end
934 * Returns the end of the directory component of the module path.
936 static inline const WCHAR *get_module_path_end(const WCHAR *module)
938 const WCHAR *p;
939 const WCHAR *mod_end = module;
940 if (!module) return mod_end;
942 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
943 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
944 if (mod_end == module + 2 && module[1] == ':') mod_end++;
945 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
947 return mod_end;
951 /******************************************************************
952 * append_path_len
954 * Append a counted string to the load path. Helper for MODULE_get_dll_load_path.
956 static inline WCHAR *append_path_len( WCHAR *p, const WCHAR *str, DWORD len )
958 if (!len) return p;
959 memcpy( p, str, len * sizeof(WCHAR) );
960 p[len] = ';';
961 return p + len + 1;
965 /******************************************************************
966 * append_path
968 * Append a string to the load path. Helper for MODULE_get_dll_load_path.
970 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str )
972 return append_path_len( p, str, strlenW(str) );
976 /******************************************************************
977 * MODULE_get_dll_load_path
979 * Compute the load path to use for a given dll.
980 * Returned pointer must be freed by caller.
982 WCHAR *MODULE_get_dll_load_path( LPCWSTR module, int safe_mode )
984 static const WCHAR pathW[] = {'P','A','T','H',0};
985 static const WCHAR dotW[] = {'.',0};
987 const WCHAR *system_path = get_dll_system_path();
988 const WCHAR *mod_end = NULL;
989 UNICODE_STRING name, value;
990 WCHAR *p, *ret;
991 int len = 0, path_len = 0;
993 /* adjust length for module name */
995 if (module)
996 mod_end = get_module_path_end( module );
997 /* if module is NULL or doesn't contain a path, fall back to directory
998 * process was loaded from */
999 if (module == mod_end)
1001 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
1002 mod_end = get_module_path_end( module );
1004 len += (mod_end - module) + 1;
1006 len += strlenW( system_path ) + 2;
1008 /* get the PATH variable */
1010 RtlInitUnicodeString( &name, pathW );
1011 value.Length = 0;
1012 value.MaximumLength = 0;
1013 value.Buffer = NULL;
1014 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
1015 path_len = value.Length;
1017 RtlEnterCriticalSection( &dlldir_section );
1018 if (safe_mode == -1) safe_mode = get_dll_safe_mode();
1019 if (dll_directory) len += strlenW(dll_directory) + 1;
1020 else len += 2; /* current directory */
1021 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
1023 if (module) p = append_path_len( p, module, mod_end - module );
1025 if (dll_directory) p = append_path( p, dll_directory );
1026 else if (!safe_mode) p = append_path( p, dotW );
1028 p = append_path( p, system_path );
1030 if (!dll_directory && safe_mode) p = append_path( p, dotW );
1032 RtlLeaveCriticalSection( &dlldir_section );
1033 if (!ret) return NULL;
1035 value.Buffer = p;
1036 value.MaximumLength = path_len;
1038 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
1040 WCHAR *new_ptr;
1042 /* grow the buffer and retry */
1043 path_len = value.Length;
1044 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
1046 HeapFree( GetProcessHeap(), 0, ret );
1047 return NULL;
1049 value.Buffer = new_ptr + (value.Buffer - ret);
1050 value.MaximumLength = path_len;
1051 ret = new_ptr;
1053 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
1054 return ret;
1058 /******************************************************************
1059 * get_dll_load_path_search_flags
1061 static WCHAR *get_dll_load_path_search_flags( LPCWSTR module, DWORD flags )
1063 const WCHAR *image = NULL, *mod_end, *image_end;
1064 struct dll_dir_entry *dir;
1065 WCHAR *p, *ret;
1066 int len = 1;
1068 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
1069 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1070 LOAD_LIBRARY_SEARCH_USER_DIRS |
1071 LOAD_LIBRARY_SEARCH_SYSTEM32);
1073 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
1075 DWORD type = RtlDetermineDosPathNameType_U( module );
1076 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH)
1078 SetLastError( ERROR_INVALID_PARAMETER );
1079 return NULL;
1081 mod_end = get_module_path_end( module );
1082 len += (mod_end - module) + 1;
1084 else module = NULL;
1086 RtlEnterCriticalSection( &dlldir_section );
1088 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
1090 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
1091 image_end = get_module_path_end( image );
1092 len += (image_end - image) + 1;
1095 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1097 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1098 len += strlenW( dir->dir ) + 1;
1099 if (dll_directory) len += strlenW(dll_directory) + 1;
1102 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += GetSystemDirectoryW( NULL, 0 );
1104 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
1106 if (module) p = append_path_len( p, module, mod_end - module );
1107 if (image) p = append_path_len( p, image, image_end - image );
1108 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
1110 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
1111 p = append_path( p, dir->dir );
1112 if (dll_directory) p = append_path( p, dll_directory );
1114 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) GetSystemDirectoryW( p, ret + len - p );
1115 else
1117 if (p > ret) p--;
1118 *p = 0;
1122 RtlLeaveCriticalSection( &dlldir_section );
1123 return ret;
1127 /******************************************************************
1128 * load_library_as_datafile
1130 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
1132 static const WCHAR dotDLL[] = {'.','d','l','l',0};
1134 WCHAR filenameW[MAX_PATH];
1135 HANDLE hFile = INVALID_HANDLE_VALUE;
1136 HANDLE mapping;
1137 HMODULE module = 0;
1138 DWORD protect = PAGE_READONLY;
1139 DWORD sharing = FILE_SHARE_READ | FILE_SHARE_DELETE;
1141 *hmod = 0;
1143 if (flags & LOAD_LIBRARY_AS_IMAGE_RESOURCE) protect |= SEC_IMAGE;
1145 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
1146 filenameW, NULL ))
1148 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
1150 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1152 mapping = CreateFileMappingW( hFile, NULL, protect, 0, 0, NULL );
1153 if (!mapping) goto failed;
1155 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1156 CloseHandle( mapping );
1157 if (!module) goto failed;
1159 if (!(flags & LOAD_LIBRARY_AS_IMAGE_RESOURCE))
1161 /* make sure it's a valid PE file */
1162 if (!RtlImageNtHeader( module )) goto failed;
1163 *hmod = (HMODULE)((char *)module + 1); /* set bit 0 for data file module */
1165 if (flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)
1167 struct exclusive_datafile *file = HeapAlloc( GetProcessHeap(), 0, sizeof(*file) );
1168 if (!file) goto failed;
1169 file->module = *hmod;
1170 file->file = hFile;
1171 list_add_head( &exclusive_datafile_list, &file->entry );
1172 TRACE( "delaying close %p for module %p\n", file->file, file->module );
1173 return TRUE;
1176 else *hmod = (HMODULE)((char *)module + 2); /* set bit 1 for image resource module */
1178 CloseHandle( hFile );
1179 return TRUE;
1181 failed:
1182 if (module) UnmapViewOfFile( module );
1183 CloseHandle( hFile );
1184 return FALSE;
1188 /******************************************************************
1189 * load_library
1191 * Helper for LoadLibraryExA/W.
1193 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
1195 NTSTATUS nts;
1196 HMODULE hModule;
1197 WCHAR *load_path;
1198 const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
1199 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
1200 LOAD_LIBRARY_SEARCH_USER_DIRS |
1201 LOAD_LIBRARY_SEARCH_SYSTEM32 |
1202 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
1203 const DWORD unsupported_flags = (LOAD_IGNORE_CODE_AUTHZ_LEVEL |
1204 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET);
1206 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
1208 if( flags & unsupported_flags)
1209 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
1211 if (flags & load_library_search_flags)
1212 load_path = get_dll_load_path_search_flags( libname->Buffer, flags );
1213 else
1214 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL, -1 );
1215 if (!load_path) return 0;
1217 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE))
1219 ULONG_PTR magic;
1221 LdrLockLoaderLock( 0, NULL, &magic );
1222 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
1224 LdrAddRefDll( 0, hModule );
1225 LdrUnlockLoaderLock( 0, magic );
1226 goto done;
1228 if (load_library_as_datafile( libname->Buffer, &hModule, flags ))
1230 LdrUnlockLoaderLock( 0, magic );
1231 goto done;
1233 LdrUnlockLoaderLock( 0, magic );
1234 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1235 /* Fallback to normal behaviour */
1238 nts = LdrLoadDll( load_path, flags, libname, &hModule );
1239 if (nts != STATUS_SUCCESS)
1241 hModule = 0;
1242 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
1243 SetLastError( ERROR_DLL_NOT_FOUND );
1244 else
1245 SetLastError( RtlNtStatusToDosError( nts ) );
1247 done:
1248 HeapFree( GetProcessHeap(), 0, load_path );
1249 return hModule;
1253 /******************************************************************
1254 * LoadLibraryExA (KERNEL32.@)
1256 * Load a dll file into the process address space.
1258 * PARAMS
1259 * libname [I] Name of the file to load
1260 * hfile [I] Reserved, must be 0.
1261 * flags [I] Flags for loading the dll
1263 * RETURNS
1264 * Success: A handle to the loaded dll.
1265 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1267 * NOTES
1268 * The HFILE parameter is not used and marked reserved in the SDK. I can
1269 * only guess that it should force a file to be mapped, but I rather
1270 * ignore the parameter because it would be extremely difficult to
1271 * integrate this with different types of module representations.
1273 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1275 WCHAR *libnameW;
1277 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1278 return LoadLibraryExW( libnameW, hfile, flags );
1281 /***********************************************************************
1282 * LoadLibraryExW (KERNEL32.@)
1284 * Unicode version of LoadLibraryExA.
1286 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1288 UNICODE_STRING wstr;
1289 HMODULE res;
1291 if (!libnameW)
1293 SetLastError(ERROR_INVALID_PARAMETER);
1294 return 0;
1296 RtlInitUnicodeString( &wstr, libnameW );
1297 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1298 return load_library( &wstr, flags );
1300 /* Library name has trailing spaces */
1301 RtlCreateUnicodeString( &wstr, libnameW );
1302 while (wstr.Length > sizeof(WCHAR) &&
1303 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1305 wstr.Length -= sizeof(WCHAR);
1307 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1308 res = load_library( &wstr, flags );
1309 RtlFreeUnicodeString( &wstr );
1310 return res;
1313 /***********************************************************************
1314 * LoadLibraryA (KERNEL32.@)
1316 * Load a dll file into the process address space.
1318 * PARAMS
1319 * libname [I] Name of the file to load
1321 * RETURNS
1322 * Success: A handle to the loaded dll.
1323 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1325 * NOTES
1326 * See LoadLibraryExA().
1328 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1330 return LoadLibraryExA(libname, 0, 0);
1333 /***********************************************************************
1334 * LoadLibraryW (KERNEL32.@)
1336 * Unicode version of LoadLibraryA.
1338 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1340 return LoadLibraryExW(libnameW, 0, 0);
1343 /***********************************************************************
1344 * FreeLibrary (KERNEL32.@)
1346 * Free a dll loaded into the process address space.
1348 * PARAMS
1349 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1351 * RETURNS
1352 * Success: TRUE. The dll is removed if it is not still in use.
1353 * Failure: FALSE. Use GetLastError() to determine the cause.
1355 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1357 BOOL retv = FALSE;
1358 NTSTATUS nts;
1360 if (!hLibModule)
1362 SetLastError( ERROR_INVALID_HANDLE );
1363 return FALSE;
1366 if ((ULONG_PTR)hLibModule & 3) /* this is a datafile module */
1368 if ((ULONG_PTR)hLibModule & 1)
1370 struct exclusive_datafile *file;
1371 ULONG_PTR magic;
1373 LdrLockLoaderLock( 0, NULL, &magic );
1374 LIST_FOR_EACH_ENTRY( file, &exclusive_datafile_list, struct exclusive_datafile, entry )
1376 if (file->module != hLibModule) continue;
1377 TRACE( "closing %p for module %p\n", file->file, file->module );
1378 CloseHandle( file->file );
1379 list_remove( &file->entry );
1380 HeapFree( GetProcessHeap(), 0, file );
1381 break;
1383 LdrUnlockLoaderLock( 0, magic );
1385 return UnmapViewOfFile( (void *)((ULONG_PTR)hLibModule & ~3) );
1388 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1389 else SetLastError( RtlNtStatusToDosError( nts ) );
1391 return retv;
1394 /***********************************************************************
1395 * GetProcAddress (KERNEL32.@)
1397 * Find the address of an exported symbol in a loaded dll.
1399 * PARAMS
1400 * hModule [I] Handle to the dll returned by LoadLibraryA().
1401 * function [I] Name of the symbol, or an integer ordinal number < 16384
1403 * RETURNS
1404 * Success: A pointer to the symbol in the process address space.
1405 * Failure: NULL. Use GetLastError() to determine the cause.
1407 FARPROC get_proc_address( HMODULE hModule, LPCSTR function )
1409 NTSTATUS nts;
1410 FARPROC fp;
1412 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1414 if ((ULONG_PTR)function >> 16)
1416 ANSI_STRING str;
1418 RtlInitAnsiString( &str, function );
1419 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1421 else
1422 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1423 if (nts != STATUS_SUCCESS)
1425 SetLastError( RtlNtStatusToDosError( nts ) );
1426 fp = NULL;
1428 return fp;
1431 #ifdef __x86_64__
1433 * Work around a Delphi bug on x86_64. When delay loading a symbol,
1434 * Delphi saves rcx, rdx, r8 and r9 to the stack. It then calls
1435 * GetProcAddress(), pops the saved registers and calls the function.
1436 * This works fine if all of the parameters are ints. However, since
1437 * it does not save xmm0 - 3, it relies on GetProcAddress() preserving
1438 * these registers if the function takes floating point parameters.
1439 * This wrapper saves xmm0 - 3 to the stack.
1441 extern FARPROC get_proc_address_wrapper( HMODULE module, LPCSTR function );
1443 __ASM_GLOBAL_FUNC( get_proc_address_wrapper,
1444 "pushq %rbp\n\t"
1445 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
1446 __ASM_CFI(".cfi_rel_offset %rbp,0\n\t")
1447 "movq %rsp,%rbp\n\t"
1448 __ASM_CFI(".cfi_def_cfa_register %rbp\n\t")
1449 "subq $0x40,%rsp\n\t"
1450 "movaps %xmm0,-0x10(%rbp)\n\t"
1451 "movaps %xmm1,-0x20(%rbp)\n\t"
1452 "movaps %xmm2,-0x30(%rbp)\n\t"
1453 "movaps %xmm3,-0x40(%rbp)\n\t"
1454 "call " __ASM_NAME("get_proc_address") "\n\t"
1455 "movaps -0x40(%rbp), %xmm3\n\t"
1456 "movaps -0x30(%rbp), %xmm2\n\t"
1457 "movaps -0x20(%rbp), %xmm1\n\t"
1458 "movaps -0x10(%rbp), %xmm0\n\t"
1459 "movq %rbp,%rsp\n\t"
1460 __ASM_CFI(".cfi_def_cfa_register %rsp\n\t")
1461 "popq %rbp\n\t"
1462 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
1463 __ASM_CFI(".cfi_same_value %rbp\n\t")
1464 "ret" )
1465 #else /* __x86_64__ */
1467 static inline FARPROC get_proc_address_wrapper( HMODULE module, LPCSTR function )
1469 return get_proc_address( module, function );
1472 #endif /* __x86_64__ */
1474 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1476 return get_proc_address_wrapper( hModule, function );
1479 /***********************************************************************
1480 * DelayLoadFailureHook (KERNEL32.@)
1482 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1484 ULONG_PTR args[2];
1486 if ((ULONG_PTR)function >> 16)
1487 ERR( "failed to delay load %s.%s\n", name, function );
1488 else
1489 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1490 args[0] = (ULONG_PTR)name;
1491 args[1] = (ULONG_PTR)function;
1492 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1493 return NULL;
1496 typedef struct {
1497 HANDLE process;
1498 PLIST_ENTRY head, current;
1499 LDR_MODULE ldr_module;
1500 } MODULE_ITERATOR;
1502 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1504 PROCESS_BASIC_INFORMATION pbi;
1505 PPEB_LDR_DATA ldr_data;
1506 NTSTATUS status;
1508 /* Get address of PEB */
1509 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1510 &pbi, sizeof(pbi), NULL);
1511 if (status != STATUS_SUCCESS)
1513 SetLastError(RtlNtStatusToDosError(status));
1514 return FALSE;
1517 /* Read address of LdrData from PEB */
1518 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1519 &ldr_data, sizeof(ldr_data), NULL))
1520 return FALSE;
1522 /* Read address of first module from LdrData */
1523 if (!ReadProcessMemory(process,
1524 &ldr_data->InLoadOrderModuleList.Flink,
1525 &iter->current, sizeof(iter->current), NULL))
1526 return FALSE;
1528 iter->head = &ldr_data->InLoadOrderModuleList;
1529 iter->process = process;
1531 return TRUE;
1534 static int module_iterator_next(MODULE_ITERATOR *iter)
1536 if (iter->current == iter->head)
1537 return 0;
1539 if (!ReadProcessMemory(iter->process,
1540 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1541 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1542 return -1;
1544 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1545 return 1;
1548 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1550 MODULE_ITERATOR iter;
1551 INT ret;
1553 if (!init_module_iterator(&iter, process))
1554 return FALSE;
1556 while ((ret = module_iterator_next(&iter)) > 0)
1557 /* When hModule is NULL we return the process image - which will be
1558 * the first module since our iterator uses InLoadOrderModuleList */
1559 if (!module || module == iter.ldr_module.BaseAddress)
1561 *ldr_module = iter.ldr_module;
1562 return TRUE;
1565 if (ret == 0)
1566 SetLastError(ERROR_INVALID_HANDLE);
1568 return FALSE;
1571 /***********************************************************************
1572 * K32EnumProcessModules (KERNEL32.@)
1574 * NOTES
1575 * Returned list is in load order.
1577 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1578 DWORD cb, DWORD *needed)
1580 MODULE_ITERATOR iter;
1581 DWORD size = 0;
1582 INT ret;
1584 if (!init_module_iterator(&iter, process))
1585 return FALSE;
1587 if (cb && !lphModule)
1589 SetLastError(ERROR_NOACCESS);
1590 return FALSE;
1593 while ((ret = module_iterator_next(&iter)) > 0)
1595 if (cb >= sizeof(HMODULE))
1597 *lphModule++ = iter.ldr_module.BaseAddress;
1598 cb -= sizeof(HMODULE);
1600 size += sizeof(HMODULE);
1603 if (!needed)
1605 SetLastError(ERROR_NOACCESS);
1606 return FALSE;
1608 *needed = size;
1610 return ret == 0;
1613 /***********************************************************************
1614 * K32EnumProcessModulesEx (KERNEL32.@)
1616 * NOTES
1617 * Returned list is in load order.
1619 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1620 DWORD cb, DWORD *needed, DWORD filter)
1622 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1623 process, lphModule, cb, needed, filter);
1624 return K32EnumProcessModules(process, lphModule, cb, needed);
1627 /***********************************************************************
1628 * K32GetModuleBaseNameW (KERNEL32.@)
1630 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1631 LPWSTR base_name, DWORD size)
1633 LDR_MODULE ldr_module;
1635 if (!get_ldr_module(process, module, &ldr_module))
1636 return 0;
1638 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1639 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1640 base_name, size * sizeof(WCHAR), NULL))
1641 return 0;
1643 base_name[size] = 0;
1644 return size;
1647 /***********************************************************************
1648 * K32GetModuleBaseNameA (KERNEL32.@)
1650 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1651 LPSTR base_name, DWORD size)
1653 WCHAR *base_name_w;
1654 DWORD len, ret = 0;
1656 if(!base_name || !size) {
1657 SetLastError(ERROR_INVALID_PARAMETER);
1658 return 0;
1661 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1662 if(!base_name_w)
1663 return 0;
1665 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1666 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1667 if (len)
1669 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1670 base_name, size, NULL, NULL);
1671 if (ret < size) base_name[ret] = 0;
1673 HeapFree(GetProcessHeap(), 0, base_name_w);
1674 return ret;
1677 /***********************************************************************
1678 * K32GetModuleFileNameExW (KERNEL32.@)
1680 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1681 LPWSTR file_name, DWORD size)
1683 LDR_MODULE ldr_module;
1684 DWORD len;
1686 if (!size) return 0;
1688 if(!get_ldr_module(process, module, &ldr_module))
1689 return 0;
1691 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1692 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1693 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1694 return 0;
1696 if (len < size)
1698 file_name[len] = 0;
1699 return len;
1701 else
1703 file_name[size - 1] = 0;
1704 return size;
1708 /***********************************************************************
1709 * K32GetModuleFileNameExA (KERNEL32.@)
1711 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1712 LPSTR file_name, DWORD size)
1714 WCHAR *ptr;
1715 DWORD len;
1717 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1719 if (!file_name || !size)
1721 SetLastError( ERROR_INVALID_PARAMETER );
1722 return 0;
1725 if ( process == GetCurrentProcess() )
1727 len = GetModuleFileNameA( module, file_name, size );
1728 if (size) file_name[size - 1] = '\0';
1729 return len;
1732 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1734 len = K32GetModuleFileNameExW(process, module, ptr, size);
1735 if (!len)
1737 file_name[0] = '\0';
1739 else
1741 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1743 file_name[size - 1] = 0;
1744 len = size;
1746 else if (len < size) len = strlen( file_name );
1749 HeapFree(GetProcessHeap(), 0, ptr);
1750 return len;
1753 /***********************************************************************
1754 * K32GetModuleInformation (KERNEL32.@)
1756 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1757 MODULEINFO *modinfo, DWORD cb)
1759 LDR_MODULE ldr_module;
1761 if (cb < sizeof(MODULEINFO))
1763 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1764 return FALSE;
1767 if (!get_ldr_module(process, module, &ldr_module))
1768 return FALSE;
1770 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1771 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1772 modinfo->EntryPoint = ldr_module.EntryPoint;
1773 return TRUE;
1776 #ifdef __i386__
1778 /***********************************************************************
1779 * __wine_dll_register_16 (KERNEL32.@)
1781 * No longer used.
1783 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1785 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1789 /***********************************************************************
1790 * __wine_dll_unregister_16 (KERNEL32.@)
1792 * No longer used.
1794 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1798 #endif