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"
40 #include "kernel_private.h"
42 #include "wine/exception.h"
43 #include "wine/debug.h"
44 #include "wine/unicode.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
50 static CRITICAL_SECTION dlldir_section;
51 static CRITICAL_SECTION_DEBUG critsect_debug =
53 0, 0, &dlldir_section,
54 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
55 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
57 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
60 /****************************************************************************
61 * GetDllDirectoryA (KERNEL32.@)
63 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
67 RtlEnterCriticalSection( &dlldir_section );
68 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
69 if (buffer && buf_len > len)
71 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
76 len++; /* for terminating null */
77 if (buffer) *buffer = 0;
79 RtlLeaveCriticalSection( &dlldir_section );
84 /****************************************************************************
85 * GetDllDirectoryW (KERNEL32.@)
87 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
91 RtlEnterCriticalSection( &dlldir_section );
92 len = dll_directory ? strlenW( dll_directory ) : 0;
93 if (buffer && buf_len > len)
95 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
100 len++; /* for terminating null */
101 if (buffer) *buffer = 0;
103 RtlLeaveCriticalSection( &dlldir_section );
108 /****************************************************************************
109 * SetDllDirectoryA (KERNEL32.@)
111 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
116 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
117 ret = SetDllDirectoryW( dirW );
118 HeapFree( GetProcessHeap(), 0, dirW );
123 /****************************************************************************
124 * SetDllDirectoryW (KERNEL32.@)
126 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
128 WCHAR *newdir = NULL;
132 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
133 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
135 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
138 memcpy( newdir, dir, len );
141 RtlEnterCriticalSection( &dlldir_section );
142 HeapFree( GetProcessHeap(), 0, dll_directory );
143 dll_directory = newdir;
144 RtlLeaveCriticalSection( &dlldir_section );
149 /****************************************************************************
150 * DisableThreadLibraryCalls (KERNEL32.@)
152 * Inform the module loader that thread notifications are not required for a dll.
155 * hModule [I] Module handle to skip calls for
158 * Success: TRUE. Thread attach and detach notifications will not be sent
160 * Failure: FALSE. Use GetLastError() to determine the cause.
163 * This is typically called from the dll entry point of a dll during process
164 * attachment, for dlls that do not need to process thread notifications.
166 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
168 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
169 if (nts == STATUS_SUCCESS) return TRUE;
171 SetLastError( RtlNtStatusToDosError( nts ) );
176 /* Check whether a file is an OS/2 or a very old Windows executable
177 * by testing on import of KERNEL.
179 * FIXME: is reading the module imports the only way of discerning
180 * old Windows binaries from OS/2 ones ? At least it seems so...
182 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
183 const IMAGE_OS2_HEADER *ne)
185 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
186 enum binary_type ret = BINARY_OS216;
187 LPWORD modtab = NULL;
188 LPSTR nametab = NULL;
192 /* read modref table */
193 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
194 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
195 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
196 || (len != ne->ne_cmod*sizeof(WORD)) )
199 /* read imported names table */
200 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
201 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
202 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
203 || (len != ne->ne_enttab - ne->ne_imptab) )
206 for (i=0; i < ne->ne_cmod; i++)
208 LPSTR module = &nametab[modtab[i]];
209 TRACE("modref: %.*s\n", module[0], &module[1]);
210 if (!(strncmp(&module[1], "KERNEL", module[0])))
211 { /* very old Windows file */
212 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
219 ERR("Hmm, an error occurred. Is this binary file broken?\n");
222 HeapFree( GetProcessHeap(), 0, modtab);
223 HeapFree( GetProcessHeap(), 0, nametab);
224 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
228 /***********************************************************************
229 * MODULE_GetBinaryType
231 enum binary_type MODULE_GetBinaryType( HANDLE hfile, void **res_start, void **res_end )
237 unsigned char magic[4];
238 unsigned char ignored[12];
244 unsigned long cputype;
245 unsigned long cpusubtype;
246 unsigned long filetype;
253 /* Seek to the start of the file and read the header information. */
254 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
255 return BINARY_UNKNOWN;
256 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
257 return BINARY_UNKNOWN;
259 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
261 /* FIXME: we don't bother to check byte order, architecture, etc. */
262 switch(header.elf.type)
264 case 2: return BINARY_UNIX_EXE;
265 case 3: return BINARY_UNIX_LIB;
267 return BINARY_UNKNOWN;
270 /* Mach-o File with Endian set to Big Endian or Little Endian */
271 if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
273 switch(header.macho.filetype)
275 case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
277 return BINARY_UNKNOWN;
280 /* Not ELF, try DOS */
282 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
286 IMAGE_OS2_HEADER os2;
290 /* We do have a DOS image so we will now try to seek into
291 * the file by the amount indicated by the field
292 * "Offset to extended header" and read in the
293 * "magic" field information at that location.
294 * This will tell us if there is more header information
297 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
299 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4)
302 /* Reading the magic field succeeded so
303 * we will try to determine what type it is.
305 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
307 if (len >= sizeof(ext_header.nt.FileHeader))
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);
314 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
315 return BINARY_PE_EXE;
320 if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
322 /* This is a Windows executable (NE) header. This can
323 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
324 * DOS program (running under a DOS extender). To decide
325 * which, we'll have to read the NE header.
327 if (len >= sizeof(ext_header.os2))
329 switch ( ext_header.os2.ne_exetyp )
331 case 1: return BINARY_OS216; /* OS/2 */
332 case 2: return BINARY_WIN16; /* Windows */
333 case 3: return BINARY_DOS; /* European MS-DOS 4.x */
334 case 4: return BINARY_WIN16; /* Windows 386; FIXME: is this 32bit??? */
335 case 5: return BINARY_DOS; /* BOSS, Borland Operating System Services */
336 /* other types, e.g. 0 is: "unknown" */
337 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2);
340 /* Couldn't read header, so abort. */
344 /* Unknown extended header, but this file is nonetheless DOS-executable. */
348 return BINARY_UNKNOWN;
351 /***********************************************************************
352 * GetBinaryTypeW [KERNEL32.@]
354 * Determine whether a file is executable, and if so, what kind.
357 * lpApplicationName [I] Path of the file to check
358 * lpBinaryType [O] Destination for the binary type
361 * TRUE, if the file is an executable, in which case lpBinaryType is set.
362 * FALSE, if the file is not an executable or if the function fails.
365 * The type of executable is a property that determines which subsytem an
366 * executable file runs under. lpBinaryType can be set to one of the following
368 * SCS_32BIT_BINARY: A Win32 based application
369 * SCS_DOS_BINARY: An MS-Dos based application
370 * SCS_WOW_BINARY: A Win16 based application
371 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
372 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
373 * SCS_OS216_BINARY: A 16bit OS/2 based application
375 * To find the binary type, this function reads in the files header information.
376 * If extended header information is not present it will assume that the file
377 * is a DOS executable. If extended header information is present it will
378 * determine if the file is a 16 or 32 bit Windows executable by checking the
379 * flags in the header.
381 * ".com" and ".pif" files are only recognized by their file name extension,
382 * as per native Windows.
384 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 switch(MODULE_GetBinaryType( hfile, NULL, NULL ))
409 static const WCHAR comW[] = { '.','C','O','M',0 };
410 static const WCHAR pifW[] = { '.','P','I','F',0 };
413 /* try to determine from file name */
414 ptr = strrchrW( lpApplicationName, '.' );
416 if (!strcmpiW( ptr, comW ))
418 *lpBinaryType = SCS_DOS_BINARY;
421 else if (!strcmpiW( ptr, pifW ))
423 *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 );
612 if (len < size) lpFileName[len] = '\0';
614 HeapFree( GetProcessHeap(), 0, filenameW );
618 /***********************************************************************
619 * GetModuleFileNameW (KERNEL32.@)
621 * Unicode version of GetModuleFileNameA.
623 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
625 ULONG magic, len = 0;
628 WIN16_SUBSYSTEM_TIB *win16_tib;
630 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
632 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
633 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
634 if (len < size) lpFileName[len] = '\0';
638 LdrLockLoaderLock( 0, NULL, &magic );
640 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
641 nts = LdrFindEntryForAddress( hModule, &pldr );
642 if (nts == STATUS_SUCCESS)
644 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
645 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
646 if (len < size) lpFileName[len] = '\0';
648 else SetLastError( RtlNtStatusToDosError( nts ) );
650 LdrUnlockLoaderLock( 0, magic );
652 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
657 /***********************************************************************
658 * get_dll_system_path
660 static const WCHAR *get_dll_system_path(void)
662 static WCHAR *cached_path;
669 len += 2 * GetSystemDirectoryW( NULL, 0 );
670 len += GetWindowsDirectoryW( NULL, 0 );
671 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
674 GetSystemDirectoryW( p, path + len - p);
676 /* if system directory ends in "32" add 16-bit version too */
677 if (p[-2] == '3' && p[-1] == '2')
680 GetSystemDirectoryW( p, path + len - p);
684 GetWindowsDirectoryW( p, path + len - p);
690 /******************************************************************
691 * get_module_path_end
693 * Returns the end of the directory component of the module path.
695 static inline const WCHAR *get_module_path_end(const WCHAR *module)
698 const WCHAR *mod_end = module;
699 if (!module) return mod_end;
701 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
702 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
703 if (mod_end == module + 2 && module[1] == ':') mod_end++;
704 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
709 /******************************************************************
710 * MODULE_get_dll_load_path
712 * Compute the load path to use for a given dll.
713 * Returned pointer must be freed by caller.
715 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
717 static const WCHAR pathW[] = {'P','A','T','H',0};
719 const WCHAR *system_path = get_dll_system_path();
720 const WCHAR *mod_end = NULL;
721 UNICODE_STRING name, value;
723 int len = 0, path_len = 0;
725 /* adjust length for module name */
728 mod_end = get_module_path_end( module );
729 /* if module is NULL or doesn't contain a path, fall back to directory
730 * process was loaded from */
731 if (module == mod_end)
733 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
734 mod_end = get_module_path_end( module );
736 len += (mod_end - module) + 1;
738 len += strlenW( system_path ) + 2;
740 /* get the PATH variable */
742 RtlInitUnicodeString( &name, pathW );
744 value.MaximumLength = 0;
746 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
747 path_len = value.Length;
749 RtlEnterCriticalSection( &dlldir_section );
750 if (dll_directory) len += strlenW(dll_directory) + 1;
751 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
755 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
756 p += (mod_end - module);
761 strcpyW( p, dll_directory );
766 RtlLeaveCriticalSection( &dlldir_section );
767 if (!ret) return NULL;
769 strcpyW( p, system_path );
773 value.MaximumLength = path_len;
775 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
779 /* grow the buffer and retry */
780 path_len = value.Length;
781 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
783 HeapFree( GetProcessHeap(), 0, ret );
786 value.Buffer = new_ptr + (value.Buffer - ret);
787 value.MaximumLength = path_len;
790 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
795 /******************************************************************
796 * load_library_as_datafile
798 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
800 static const WCHAR dotDLL[] = {'.','d','l','l',0};
802 WCHAR filenameW[MAX_PATH];
803 HANDLE hFile = INVALID_HANDLE_VALUE;
809 if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
812 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
813 NULL, OPEN_EXISTING, 0, 0 );
815 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
817 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
818 CloseHandle( hFile );
819 if (!mapping) return FALSE;
821 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
822 CloseHandle( mapping );
823 if (!module) return FALSE;
825 /* make sure it's a valid PE file */
826 if (!RtlImageNtHeader(module))
828 UnmapViewOfFile( module );
831 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
836 /******************************************************************
839 * Helper for LoadLibraryExA/W.
841 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
847 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
849 if (flags & LOAD_LIBRARY_AS_DATAFILE)
853 LdrLockLoaderLock( 0, NULL, &magic );
854 if (!(nts = LdrGetDllHandle( load_path, flags, libname, &hModule )))
856 LdrAddRefDll( 0, hModule );
857 LdrUnlockLoaderLock( 0, magic );
860 LdrUnlockLoaderLock( 0, magic );
862 /* The method in load_library_as_datafile allows searching for the
863 * 'native' libraries only
865 if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
866 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
867 /* Fallback to normal behaviour */
870 nts = LdrLoadDll( load_path, flags, libname, &hModule );
871 if (nts != STATUS_SUCCESS)
874 SetLastError( RtlNtStatusToDosError( nts ) );
877 HeapFree( GetProcessHeap(), 0, load_path );
882 /******************************************************************
883 * LoadLibraryExA (KERNEL32.@)
885 * Load a dll file into the process address space.
888 * libname [I] Name of the file to load
889 * hfile [I] Reserved, must be 0.
890 * flags [I] Flags for loading the dll
893 * Success: A handle to the loaded dll.
894 * Failure: A NULL handle. Use GetLastError() to determine the cause.
897 * The HFILE parameter is not used and marked reserved in the SDK. I can
898 * only guess that it should force a file to be mapped, but I rather
899 * ignore the parameter because it would be extremely difficult to
900 * integrate this with different types of module representations.
902 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
906 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
907 return LoadLibraryExW( libnameW, hfile, flags );
910 /***********************************************************************
911 * LoadLibraryExW (KERNEL32.@)
913 * Unicode version of LoadLibraryExA.
915 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
922 SetLastError(ERROR_INVALID_PARAMETER);
925 RtlInitUnicodeString( &wstr, libnameW );
926 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
927 return load_library( &wstr, flags );
929 /* Library name has trailing spaces */
930 RtlCreateUnicodeString( &wstr, libnameW );
931 while (wstr.Length > sizeof(WCHAR) &&
932 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
934 wstr.Length -= sizeof(WCHAR);
936 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
937 res = load_library( &wstr, flags );
938 RtlFreeUnicodeString( &wstr );
942 /***********************************************************************
943 * LoadLibraryA (KERNEL32.@)
945 * Load a dll file into the process address space.
948 * libname [I] Name of the file to load
951 * Success: A handle to the loaded dll.
952 * Failure: A NULL handle. Use GetLastError() to determine the cause.
955 * See LoadLibraryExA().
957 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
959 return LoadLibraryExA(libname, 0, 0);
962 /***********************************************************************
963 * LoadLibraryW (KERNEL32.@)
965 * Unicode version of LoadLibraryA.
967 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
969 return LoadLibraryExW(libnameW, 0, 0);
972 /***********************************************************************
973 * FreeLibrary (KERNEL32.@)
974 * FreeLibrary32 (KERNEL.486)
976 * Free a dll loaded into the process address space.
979 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
982 * Success: TRUE. The dll is removed if it is not still in use.
983 * Failure: FALSE. Use GetLastError() to determine the cause.
985 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
992 SetLastError( ERROR_INVALID_HANDLE );
996 if ((ULONG_PTR)hLibModule & 1)
998 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
999 char *ptr = (char *)hLibModule - 1;
1000 UnmapViewOfFile( ptr );
1004 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1005 else SetLastError( RtlNtStatusToDosError( nts ) );
1010 /***********************************************************************
1011 * GetProcAddress (KERNEL32.@)
1013 * Find the address of an exported symbol in a loaded dll.
1016 * hModule [I] Handle to the dll returned by LoadLibraryA().
1017 * function [I] Name of the symbol, or an integer ordinal number < 16384
1020 * Success: A pointer to the symbol in the process address space.
1021 * Failure: NULL. Use GetLastError() to determine the cause.
1023 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1028 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1030 if (HIWORD(function))
1034 RtlInitAnsiString( &str, function );
1035 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1038 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1039 if (nts != STATUS_SUCCESS)
1041 SetLastError( RtlNtStatusToDosError( nts ) );
1047 /***********************************************************************
1048 * GetProcAddress32 (KERNEL.453)
1050 * Find the address of an exported symbol in a loaded dll.
1053 * hModule [I] Handle to the dll returned by LoadLibraryA().
1054 * function [I] Name of the symbol, or an integer ordinal number < 16384
1057 * Success: A pointer to the symbol in the process address space.
1058 * Failure: NULL. Use GetLastError() to determine the cause.
1060 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1062 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
1063 return GetProcAddress( hModule, function );
1067 /***********************************************************************
1068 * DelayLoadFailureHook (KERNEL32.@)
1070 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1074 if ((ULONG_PTR)function >> 16)
1075 ERR( "failed to delay load %s.%s\n", name, function );
1077 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1078 args[0] = (ULONG_PTR)name;
1079 args[1] = (ULONG_PTR)function;
1080 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );