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
22 #include "wine/port.h"
28 #include <sys/types.h>
33 #define WIN32_NO_STATUS
34 #include "wine/winbase16.h"
39 #include "kernel_private.h"
41 #include "wine/exception.h"
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(module);
47 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
49 static CRITICAL_SECTION dlldir_section;
50 static CRITICAL_SECTION_DEBUG critsect_debug =
52 0, 0, &dlldir_section,
53 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
54 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
56 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
59 /****************************************************************************
60 * GetDllDirectoryA (KERNEL32.@)
62 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
66 RtlEnterCriticalSection( &dlldir_section );
67 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
68 if (buffer && buf_len > len)
70 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
75 len++; /* for terminating null */
76 if (buffer) *buffer = 0;
78 RtlLeaveCriticalSection( &dlldir_section );
83 /****************************************************************************
84 * GetDllDirectoryW (KERNEL32.@)
86 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
90 RtlEnterCriticalSection( &dlldir_section );
91 len = dll_directory ? strlenW( dll_directory ) : 0;
92 if (buffer && buf_len > len)
94 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
99 len++; /* for terminating null */
100 if (buffer) *buffer = 0;
102 RtlLeaveCriticalSection( &dlldir_section );
107 /****************************************************************************
108 * SetDllDirectoryA (KERNEL32.@)
110 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
115 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
116 ret = SetDllDirectoryW( dirW );
117 HeapFree( GetProcessHeap(), 0, dirW );
122 /****************************************************************************
123 * SetDllDirectoryW (KERNEL32.@)
125 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
127 WCHAR *newdir = NULL;
131 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
132 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
134 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
137 memcpy( newdir, dir, len );
140 RtlEnterCriticalSection( &dlldir_section );
141 HeapFree( GetProcessHeap(), 0, dll_directory );
142 dll_directory = newdir;
143 RtlLeaveCriticalSection( &dlldir_section );
148 /****************************************************************************
149 * DisableThreadLibraryCalls (KERNEL32.@)
151 * Inform the module loader that thread notifications are not required for a dll.
154 * hModule [I] Module handle to skip calls for
157 * Success: TRUE. Thread attach and detach notifications will not be sent
159 * Failure: FALSE. Use GetLastError() to determine the cause.
162 * This is typically called from the dll entry point of a dll during process
163 * attachment, for dlls that do not need to process thread notifications.
165 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
167 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
168 if (nts == STATUS_SUCCESS) return TRUE;
170 SetLastError( RtlNtStatusToDosError( nts ) );
175 /* Check whether a file is an OS/2 or a very old Windows executable
176 * by testing on import of KERNEL.
178 * FIXME: is reading the module imports the only way of discerning
179 * old Windows binaries from OS/2 ones ? At least it seems so...
181 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
183 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
184 DWORD ret = BINARY_OS216;
185 LPWORD modtab = NULL;
186 LPSTR nametab = NULL;
190 /* read modref table */
191 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
192 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
193 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
194 || (len != ne->ne_cmod*sizeof(WORD)) )
197 /* read imported names table */
198 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
199 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
200 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
201 || (len != ne->ne_enttab - ne->ne_imptab) )
204 for (i=0; i < ne->ne_cmod; i++)
206 LPSTR module = &nametab[modtab[i]];
207 TRACE("modref: %.*s\n", module[0], &module[1]);
208 if (!(strncmp(&module[1], "KERNEL", module[0])))
209 { /* very old Windows file */
210 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
217 ERR("Hmm, an error occurred. Is this binary file broken?\n");
220 HeapFree( GetProcessHeap(), 0, modtab);
221 HeapFree( GetProcessHeap(), 0, nametab);
222 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
226 /***********************************************************************
227 * MODULE_GetBinaryType
229 DWORD MODULE_GetBinaryType( HANDLE hfile, void **res_start, void **res_end )
235 unsigned char magic[4];
236 unsigned char ignored[12];
242 unsigned long cputype;
243 unsigned long cpusubtype;
244 unsigned long filetype;
251 /* Seek to the start of the file and read the header information. */
252 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
253 return BINARY_UNKNOWN;
254 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
255 return BINARY_UNKNOWN;
257 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
259 /* FIXME: we don't bother to check byte order, architecture, etc. */
260 switch(header.elf.type)
262 case 2: return BINARY_UNIX_EXE;
263 case 3: return BINARY_UNIX_LIB;
265 return BINARY_UNKNOWN;
268 /* Mach-o File with Endian set to Big Endian or Little Endian */
269 if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
271 switch(header.macho.filetype)
273 case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
275 return BINARY_UNKNOWN;
278 /* Not ELF, try DOS */
280 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
284 IMAGE_OS2_HEADER os2;
288 /* We do have a DOS image so we will now try to seek into
289 * the file by the amount indicated by the field
290 * "Offset to extended header" and read in the
291 * "magic" field information at that location.
292 * This will tell us if there is more header information
295 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
297 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4)
300 /* Reading the magic field succeeded so
301 * we will try to determine what type it is.
303 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
305 if (len >= sizeof(ext_header.nt.FileHeader))
307 DWORD ret = BINARY_PE;
308 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL) ret |= BINARY_FLAG_DLL;
309 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
310 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
311 if (res_start) *res_start = (void *)ext_header.nt.OptionalHeader.ImageBase;
312 if (res_end) *res_end = (void *)(ext_header.nt.OptionalHeader.ImageBase +
313 ext_header.nt.OptionalHeader.SizeOfImage);
319 if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
321 /* This is a Windows executable (NE) header. This can
322 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
323 * DOS program (running under a DOS extender). To decide
324 * which, we'll have to read the NE header.
326 if (len >= sizeof(ext_header.os2))
328 switch ( ext_header.os2.ne_exetyp )
330 case 1: return BINARY_OS216; /* OS/2 */
331 case 2: return BINARY_WIN16; /* Windows */
332 case 3: return BINARY_DOS; /* European MS-DOS 4.x */
333 case 4: return BINARY_WIN16; /* Windows 386; FIXME: is this 32bit??? */
334 case 5: return BINARY_DOS; /* BOSS, Borland Operating System Services */
335 /* other types, e.g. 0 is: "unknown" */
336 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2);
339 /* Couldn't read header, so abort. */
343 /* Unknown extended header, but this file is nonetheless DOS-executable. */
347 return BINARY_UNKNOWN;
350 /***********************************************************************
351 * GetBinaryTypeW [KERNEL32.@]
353 * Determine whether a file is executable, and if so, what kind.
356 * lpApplicationName [I] Path of the file to check
357 * lpBinaryType [O] Destination for the binary type
360 * TRUE, if the file is an executable, in which case lpBinaryType is set.
361 * FALSE, if the file is not an executable or if the function fails.
364 * The type of executable is a property that determines which subsystem an
365 * executable file runs under. lpBinaryType can be set to one of the following
367 * SCS_32BIT_BINARY: A Win32 based application
368 * SCS_DOS_BINARY: An MS-Dos based application
369 * SCS_WOW_BINARY: A Win16 based application
370 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
371 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
372 * SCS_OS216_BINARY: A 16bit OS/2 based application
374 * To find the binary type, this function reads in the files header information.
375 * If extended header information is not present it will assume that the file
376 * is a DOS executable. If extended header information is present it will
377 * determine if the file is a 16 or 32 bit Windows executable by checking the
378 * flags in the header.
380 * ".com" and ".pif" files are only recognized by their file name extension,
381 * as per native Windows.
383 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
389 TRACE("%s\n", debugstr_w(lpApplicationName) );
393 if ( lpApplicationName == NULL || lpBinaryType == NULL )
396 /* Open the file indicated by lpApplicationName for reading.
398 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
399 NULL, OPEN_EXISTING, 0, 0 );
400 if ( hfile == INVALID_HANDLE_VALUE )
405 binary_type = MODULE_GetBinaryType( hfile, NULL, NULL );
406 switch (binary_type & BINARY_TYPE_MASK)
410 static const WCHAR comW[] = { '.','C','O','M',0 };
411 static const WCHAR pifW[] = { '.','P','I','F',0 };
414 /* try to determine from file name */
415 ptr = strrchrW( lpApplicationName, '.' );
417 if (!strcmpiW( ptr, comW ))
419 *lpBinaryType = SCS_DOS_BINARY;
422 else if (!strcmpiW( ptr, pifW ))
424 *lpBinaryType = SCS_PIF_BINARY;
430 *lpBinaryType = SCS_32BIT_BINARY;
434 *lpBinaryType = SCS_WOW_BINARY;
438 *lpBinaryType = SCS_OS216_BINARY;
442 *lpBinaryType = SCS_DOS_BINARY;
445 case BINARY_UNIX_EXE:
446 case BINARY_UNIX_LIB:
451 CloseHandle( hfile );
455 /***********************************************************************
456 * GetBinaryTypeA [KERNEL32.@]
457 * GetBinaryType [KERNEL32.@]
459 * See GetBinaryTypeW.
461 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
463 ANSI_STRING app_nameA;
466 TRACE("%s\n", debugstr_a(lpApplicationName));
470 if ( lpApplicationName == NULL || lpBinaryType == NULL )
473 RtlInitAnsiString(&app_nameA, lpApplicationName);
474 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
477 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
479 SetLastError(RtlNtStatusToDosError(status));
483 /***********************************************************************
484 * GetModuleHandleExA (KERNEL32.@)
486 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
490 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
491 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
493 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
494 return GetModuleHandleExW( flags, nameW, module );
497 /***********************************************************************
498 * GetModuleHandleExW (KERNEL32.@)
500 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
502 NTSTATUS status = STATUS_SUCCESS;
506 /* if we are messing with the refcount, grab the loader lock */
507 if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
508 !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
509 LdrLockLoaderLock( 0, NULL, &magic );
513 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
515 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
518 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
523 RtlInitUnicodeString( &wstr, name );
524 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
527 if (status == STATUS_SUCCESS)
529 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
530 FIXME( "should pin refcount for %p\n", ret );
531 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
532 LdrAddRefDll( 0, ret );
534 else SetLastError( RtlNtStatusToDosError( status ) );
536 if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
537 !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
538 LdrUnlockLoaderLock( 0, magic );
540 if (module) *module = ret;
541 return (status == STATUS_SUCCESS);
544 /***********************************************************************
545 * GetModuleHandleA (KERNEL32.@)
546 * GetModuleHandle32 (KERNEL.488)
548 * Get the handle of a dll loaded into the process address space.
551 * module [I] Name of the dll
554 * Success: A handle to the loaded dll.
555 * Failure: A NULL handle. Use GetLastError() to determine the cause.
557 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
561 if (!GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
565 /***********************************************************************
566 * GetModuleHandleW (KERNEL32.@)
568 * Unicode version of GetModuleHandleA.
570 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
574 if (!GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
579 /***********************************************************************
580 * GetModuleFileNameA (KERNEL32.@)
581 * GetModuleFileName32 (KERNEL.487)
583 * Get the file name of a loaded module from its handle.
586 * Success: The length of the file name, excluding the terminating NUL.
587 * Failure: 0. Use GetLastError() to determine the cause.
590 * This function always returns the long path of hModule (as opposed to
591 * GetModuleFileName16() which returns short paths when the modules version
593 * The function doesn't write a terminating '\0' if the buffer is too
596 DWORD WINAPI GetModuleFileNameA(
597 HMODULE hModule, /* [in] Module handle (32 bit) */
598 LPSTR lpFileName, /* [out] Destination for file name */
599 DWORD size ) /* [in] Size of lpFileName in characters */
601 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
606 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
609 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
611 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
613 lpFileName[len] = '\0';
615 SetLastError( ERROR_INSUFFICIENT_BUFFER );
617 HeapFree( GetProcessHeap(), 0, filenameW );
621 /***********************************************************************
622 * GetModuleFileNameW (KERNEL32.@)
624 * Unicode version of GetModuleFileNameA.
626 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
628 ULONG magic, len = 0;
631 WIN16_SUBSYSTEM_TIB *win16_tib;
633 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
635 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
636 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
637 if (len < size) lpFileName[len] = '\0';
641 LdrLockLoaderLock( 0, NULL, &magic );
643 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
644 nts = LdrFindEntryForAddress( hModule, &pldr );
645 if (nts == STATUS_SUCCESS)
647 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
648 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
650 lpFileName[len] = '\0';
652 SetLastError( ERROR_INSUFFICIENT_BUFFER );
654 else SetLastError( RtlNtStatusToDosError( nts ) );
656 LdrUnlockLoaderLock( 0, magic );
658 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
663 /***********************************************************************
664 * get_dll_system_path
666 static const WCHAR *get_dll_system_path(void)
668 static WCHAR *cached_path;
675 len += 2 * GetSystemDirectoryW( NULL, 0 );
676 len += GetWindowsDirectoryW( NULL, 0 );
677 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
680 GetSystemDirectoryW( p, path + len - p);
682 /* if system directory ends in "32" add 16-bit version too */
683 if (p[-2] == '3' && p[-1] == '2')
686 GetSystemDirectoryW( p, path + len - p);
690 GetWindowsDirectoryW( p, path + len - p);
696 /******************************************************************
697 * get_module_path_end
699 * Returns the end of the directory component of the module path.
701 static inline const WCHAR *get_module_path_end(const WCHAR *module)
704 const WCHAR *mod_end = module;
705 if (!module) return mod_end;
707 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
708 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
709 if (mod_end == module + 2 && module[1] == ':') mod_end++;
710 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
715 /******************************************************************
716 * MODULE_get_dll_load_path
718 * Compute the load path to use for a given dll.
719 * Returned pointer must be freed by caller.
721 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
723 static const WCHAR pathW[] = {'P','A','T','H',0};
725 const WCHAR *system_path = get_dll_system_path();
726 const WCHAR *mod_end = NULL;
727 UNICODE_STRING name, value;
729 int len = 0, path_len = 0;
731 /* adjust length for module name */
734 mod_end = get_module_path_end( module );
735 /* if module is NULL or doesn't contain a path, fall back to directory
736 * process was loaded from */
737 if (module == mod_end)
739 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
740 mod_end = get_module_path_end( module );
742 len += (mod_end - module) + 1;
744 len += strlenW( system_path ) + 2;
746 /* get the PATH variable */
748 RtlInitUnicodeString( &name, pathW );
750 value.MaximumLength = 0;
752 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
753 path_len = value.Length;
755 RtlEnterCriticalSection( &dlldir_section );
756 if (dll_directory) len += strlenW(dll_directory) + 1;
757 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
761 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
762 p += (mod_end - module);
767 strcpyW( p, dll_directory );
772 RtlLeaveCriticalSection( &dlldir_section );
773 if (!ret) return NULL;
775 strcpyW( p, system_path );
779 value.MaximumLength = path_len;
781 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
785 /* grow the buffer and retry */
786 path_len = value.Length;
787 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
789 HeapFree( GetProcessHeap(), 0, ret );
792 value.Buffer = new_ptr + (value.Buffer - ret);
793 value.MaximumLength = path_len;
796 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
801 /******************************************************************
802 * load_library_as_datafile
804 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
806 static const WCHAR dotDLL[] = {'.','d','l','l',0};
808 WCHAR filenameW[MAX_PATH];
809 HANDLE hFile = INVALID_HANDLE_VALUE;
815 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
818 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
819 NULL, OPEN_EXISTING, 0, 0 );
821 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
823 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
824 CloseHandle( hFile );
825 if (!mapping) return FALSE;
827 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
828 CloseHandle( mapping );
829 if (!module) return FALSE;
831 /* make sure it's a valid PE file */
832 if (!RtlImageNtHeader(module))
834 UnmapViewOfFile( module );
837 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
842 /******************************************************************
845 * Helper for LoadLibraryExA/W.
847 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
853 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
855 if (flags & LOAD_LIBRARY_AS_DATAFILE)
859 LdrLockLoaderLock( 0, NULL, &magic );
860 if (!(nts = LdrGetDllHandle( load_path, flags, libname, &hModule )))
862 LdrAddRefDll( 0, hModule );
863 LdrUnlockLoaderLock( 0, magic );
866 LdrUnlockLoaderLock( 0, magic );
868 /* The method in load_library_as_datafile allows searching for the
869 * 'native' libraries only
871 if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
872 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
873 /* Fallback to normal behaviour */
876 nts = LdrLoadDll( load_path, flags, libname, &hModule );
877 if (nts != STATUS_SUCCESS)
880 SetLastError( RtlNtStatusToDosError( nts ) );
883 HeapFree( GetProcessHeap(), 0, load_path );
888 /******************************************************************
889 * LoadLibraryExA (KERNEL32.@)
891 * Load a dll file into the process address space.
894 * libname [I] Name of the file to load
895 * hfile [I] Reserved, must be 0.
896 * flags [I] Flags for loading the dll
899 * Success: A handle to the loaded dll.
900 * Failure: A NULL handle. Use GetLastError() to determine the cause.
903 * The HFILE parameter is not used and marked reserved in the SDK. I can
904 * only guess that it should force a file to be mapped, but I rather
905 * ignore the parameter because it would be extremely difficult to
906 * integrate this with different types of module representations.
908 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
912 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
913 return LoadLibraryExW( libnameW, hfile, flags );
916 /***********************************************************************
917 * LoadLibraryExW (KERNEL32.@)
919 * Unicode version of LoadLibraryExA.
921 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
928 SetLastError(ERROR_INVALID_PARAMETER);
931 RtlInitUnicodeString( &wstr, libnameW );
932 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
933 return load_library( &wstr, flags );
935 /* Library name has trailing spaces */
936 RtlCreateUnicodeString( &wstr, libnameW );
937 while (wstr.Length > sizeof(WCHAR) &&
938 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
940 wstr.Length -= sizeof(WCHAR);
942 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
943 res = load_library( &wstr, flags );
944 RtlFreeUnicodeString( &wstr );
948 /***********************************************************************
949 * LoadLibraryA (KERNEL32.@)
951 * Load a dll file into the process address space.
954 * libname [I] Name of the file to load
957 * Success: A handle to the loaded dll.
958 * Failure: A NULL handle. Use GetLastError() to determine the cause.
961 * See LoadLibraryExA().
963 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
965 return LoadLibraryExA(libname, 0, 0);
968 /***********************************************************************
969 * LoadLibraryW (KERNEL32.@)
971 * Unicode version of LoadLibraryA.
973 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
975 return LoadLibraryExW(libnameW, 0, 0);
978 /***********************************************************************
979 * FreeLibrary (KERNEL32.@)
980 * FreeLibrary32 (KERNEL.486)
982 * Free a dll loaded into the process address space.
985 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
988 * Success: TRUE. The dll is removed if it is not still in use.
989 * Failure: FALSE. Use GetLastError() to determine the cause.
991 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
998 SetLastError( ERROR_INVALID_HANDLE );
1002 if ((ULONG_PTR)hLibModule & 1)
1004 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1005 char *ptr = (char *)hLibModule - 1;
1006 UnmapViewOfFile( ptr );
1010 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1011 else SetLastError( RtlNtStatusToDosError( nts ) );
1016 /***********************************************************************
1017 * GetProcAddress (KERNEL32.@)
1019 * Find the address of an exported symbol in a loaded dll.
1022 * hModule [I] Handle to the dll returned by LoadLibraryA().
1023 * function [I] Name of the symbol, or an integer ordinal number < 16384
1026 * Success: A pointer to the symbol in the process address space.
1027 * Failure: NULL. Use GetLastError() to determine the cause.
1029 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1034 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1036 if (HIWORD(function))
1040 RtlInitAnsiString( &str, function );
1041 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1044 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1045 if (nts != STATUS_SUCCESS)
1047 SetLastError( RtlNtStatusToDosError( nts ) );
1053 /***********************************************************************
1054 * GetProcAddress32 (KERNEL.453)
1056 * Find the address of an exported symbol in a loaded dll.
1059 * hModule [I] Handle to the dll returned by LoadLibraryA().
1060 * function [I] Name of the symbol, or an integer ordinal number < 16384
1063 * Success: A pointer to the symbol in the process address space.
1064 * Failure: NULL. Use GetLastError() to determine the cause.
1066 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1068 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
1069 return GetProcAddress( hModule, function );
1073 /***********************************************************************
1074 * DelayLoadFailureHook (KERNEL32.@)
1076 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1080 if ((ULONG_PTR)function >> 16)
1081 ERR( "failed to delay load %s.%s\n", name, function );
1083 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1084 args[0] = (ULONG_PTR)name;
1085 args[1] = (ULONG_PTR)function;
1086 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );