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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
28 #include <sys/types.h>
32 #include "wine/winbase16.h"
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
44 #include "wine/server.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
47 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
50 /****************************************************************************
51 * DisableThreadLibraryCalls (KERNEL32.@)
53 * Inform the module loader that thread notifications are not required for a dll.
56 * hModule [I] Module handle to skip calls for
59 * Success: TRUE. Thread attach and detach notifications will not be sent
61 * Failure: FALSE. Use GetLastError() to determine the cause.
64 * This is typically called from the dll entry point of a dll during process
65 * attachment, for dlls that do not need to process thread notifications.
67 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
69 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
70 if (nts == STATUS_SUCCESS) return TRUE;
72 SetLastError( RtlNtStatusToDosError( nts ) );
77 /* Check whether a file is an OS/2 or a very old Windows executable
78 * by testing on import of KERNEL.
80 * FIXME: is reading the module imports the only way of discerning
81 * old Windows binaries from OS/2 ones ? At least it seems so...
83 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
84 const IMAGE_OS2_HEADER *ne)
86 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
87 enum binary_type ret = BINARY_OS216;
93 /* read modref table */
94 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
95 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
96 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
97 || (len != ne->ne_cmod*sizeof(WORD)) )
100 /* read imported names table */
101 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
102 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
103 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
104 || (len != ne->ne_enttab - ne->ne_imptab) )
107 for (i=0; i < ne->ne_cmod; i++)
109 LPSTR module = &nametab[modtab[i]];
110 TRACE("modref: %.*s\n", module[0], &module[1]);
111 if (!(strncmp(&module[1], "KERNEL", module[0])))
112 { /* very old Windows file */
113 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
120 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
123 HeapFree( GetProcessHeap(), 0, modtab);
124 HeapFree( GetProcessHeap(), 0, nametab);
125 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
129 /***********************************************************************
130 * MODULE_GetBinaryType
132 enum binary_type MODULE_GetBinaryType( HANDLE hfile )
138 unsigned char magic[4];
139 unsigned char ignored[12];
145 unsigned long cputype;
146 unsigned long cpusubtype;
147 unsigned long filetype;
155 /* Seek to the start of the file and read the header information. */
156 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
157 return BINARY_UNKNOWN;
158 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
159 return BINARY_UNKNOWN;
161 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
163 /* FIXME: we don't bother to check byte order, architecture, etc. */
164 switch(header.elf.type)
166 case 2: return BINARY_UNIX_EXE;
167 case 3: return BINARY_UNIX_LIB;
169 return BINARY_UNKNOWN;
172 /* Mach-o File with Endian set to Big Endian or Little Endian*/
173 if (header.macho.magic == 0xfeedface || header.macho.magic == 0xecafdeef)
175 switch(header.macho.filetype)
177 case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
179 return BINARY_UNKNOWN;
182 /* Not ELF, try DOS */
184 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
186 /* We do have a DOS image so we will now try to seek into
187 * the file by the amount indicated by the field
188 * "Offset to extended header" and read in the
189 * "magic" field information at that location.
190 * This will tell us if there is more header information
193 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
195 if (!ReadFile( hfile, magic, sizeof(magic), &len, NULL ) || len != sizeof(magic))
198 /* Reading the magic field succeeded so
199 * we will try to determine what type it is.
201 if (!memcmp( magic, "PE\0\0", 4 ))
203 IMAGE_FILE_HEADER FileHeader;
205 if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
207 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
208 return BINARY_PE_EXE;
213 if (!memcmp( magic, "NE", 2 ))
215 /* This is a Windows executable (NE) header. This can
216 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
217 * DOS program (running under a DOS extender). To decide
218 * which, we'll have to read the NE header.
221 if ( SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) != -1
222 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
223 && len == sizeof(ne) )
225 switch ( ne.ne_exetyp )
227 case 2: return BINARY_WIN16;
228 case 5: return BINARY_DOS;
229 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
232 /* Couldn't read header, so abort. */
236 /* Unknown extended header, but this file is nonetheless DOS-executable. */
240 return BINARY_UNKNOWN;
243 /***********************************************************************
244 * GetBinaryTypeW [KERNEL32.@]
246 * Determine whether a file is executable, and if so, what kind.
249 * lpApplicationName [I] Path of the file to check
250 * lpBinaryType [O] Destination for the binary type
253 * TRUE, if the file is an executable, in which case lpBinaryType is set.
254 * FALSE, if the file is not an executable or if the function fails.
257 * The type of executable is a property that determines which subsytem an
258 * executable file runs under. lpBinaryType can be set to one of the following
260 * SCS_32BIT_BINARY: A Win32 based application
261 * SCS_DOS_BINARY: An MS-Dos based application
262 * SCS_WOW_BINARY: A Win16 based application
263 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
264 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
265 * SCS_OS216_BINARY: A 16bit OS/2 based application
267 * To find the binary type, this function reads in the files header information.
268 * If extended header information is not present it will assume that the file
269 * is a DOS executable. If extended header information is present it will
270 * determine if the file is a 16 or 32 bit Windows executable by checking the
271 * flags in the header.
273 * ".com" and ".pif" files are only recognized by their file name extension,
274 * as per native Windows.
276 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
281 TRACE("%s\n", debugstr_w(lpApplicationName) );
285 if ( lpApplicationName == NULL || lpBinaryType == NULL )
288 /* Open the file indicated by lpApplicationName for reading.
290 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
291 NULL, OPEN_EXISTING, 0, 0 );
292 if ( hfile == INVALID_HANDLE_VALUE )
297 switch(MODULE_GetBinaryType( hfile ))
301 static const WCHAR comW[] = { '.','C','O','M',0 };
302 static const WCHAR pifW[] = { '.','P','I','F',0 };
305 /* try to determine from file name */
306 ptr = strrchrW( lpApplicationName, '.' );
308 if (!strcmpiW( ptr, comW ))
310 *lpBinaryType = SCS_DOS_BINARY;
313 else if (!strcmpiW( ptr, pifW ))
315 *lpBinaryType = SCS_PIF_BINARY;
322 *lpBinaryType = SCS_32BIT_BINARY;
326 *lpBinaryType = SCS_WOW_BINARY;
330 *lpBinaryType = SCS_OS216_BINARY;
334 *lpBinaryType = SCS_DOS_BINARY;
337 case BINARY_UNIX_EXE:
338 case BINARY_UNIX_LIB:
343 CloseHandle( hfile );
347 /***********************************************************************
348 * GetBinaryTypeA [KERNEL32.@]
349 * GetBinaryType [KERNEL32.@]
351 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
353 ANSI_STRING app_nameA;
356 TRACE("%s\n", debugstr_a(lpApplicationName));
360 if ( lpApplicationName == NULL || lpBinaryType == NULL )
363 RtlInitAnsiString(&app_nameA, lpApplicationName);
364 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
367 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
369 SetLastError(RtlNtStatusToDosError(status));
374 /***********************************************************************
375 * GetModuleHandleA (KERNEL32.@)
376 * GetModuleHandle32 (KERNEL.488)
378 * Get the handle of a dll loaded into the process address space.
381 * module [I] Name of the dll
384 * Success: A handle to the loaded dll.
385 * Failure: A NULL handle. Use GetLastError() to determine the cause.
387 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
393 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
395 RtlCreateUnicodeStringFromAsciiz(&wstr, module);
396 nts = LdrGetDllHandle(0, 0, &wstr, &ret);
397 RtlFreeUnicodeString( &wstr );
398 if (nts != STATUS_SUCCESS)
401 SetLastError( RtlNtStatusToDosError( nts ) );
406 /***********************************************************************
407 * GetModuleHandleW (KERNEL32.@)
409 * Unicode version of GetModuleHandleA.
411 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
417 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
419 RtlInitUnicodeString( &wstr, module );
420 nts = LdrGetDllHandle( 0, 0, &wstr, &ret);
421 if (nts != STATUS_SUCCESS)
423 SetLastError( RtlNtStatusToDosError( nts ) );
430 /***********************************************************************
431 * GetModuleFileNameA (KERNEL32.@)
432 * GetModuleFileName32 (KERNEL.487)
434 * Get the file name of a loaded module from its handle.
437 * Success: The length of the file name, excluding the terminating NUL.
438 * Failure: 0. Use GetLastError() to determine the cause.
441 * This function always returns the long path of hModule (as opposed to
442 * GetModuleFileName16() which returns short paths when the modules version
445 DWORD WINAPI GetModuleFileNameA(
446 HMODULE hModule, /* [in] Module handle (32 bit) */
447 LPSTR lpFileName, /* [out] Destination for file name */
448 DWORD size ) /* [in] Size of lpFileName in characters */
450 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
454 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
457 GetModuleFileNameW( hModule, filenameW, size );
458 WideCharToMultiByte( CP_ACP, 0, filenameW, -1, lpFileName, size, NULL, NULL );
459 HeapFree( GetProcessHeap(), 0, filenameW );
460 return strlen( lpFileName );
463 /***********************************************************************
464 * GetModuleFileNameW (KERNEL32.@)
466 * Unicode version of GetModuleFileNameA.
468 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
474 LdrLockLoaderLock( 0, NULL, &magic );
475 if (!hModule && !(NtCurrentTeb()->tibflags & TEBF_WIN32))
477 /* 16-bit task - get current NE module name */
478 NE_MODULE *pModule = NE_GetPtr( GetCurrentTask() );
481 WCHAR path[MAX_PATH];
483 MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
484 GetLongPathNameW(path, lpFileName, size);
492 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
493 nts = LdrFindEntryForAddress( hModule, &pldr );
494 if (nts == STATUS_SUCCESS) lstrcpynW(lpFileName, pldr->FullDllName.Buffer, size);
495 else SetLastError( RtlNtStatusToDosError( nts ) );
498 LdrUnlockLoaderLock( 0, magic );
500 TRACE( "%s\n", debugstr_w(lpFileName) );
501 return strlenW(lpFileName);
505 /***********************************************************************
506 * get_dll_system_path
508 static const WCHAR *get_dll_system_path(void)
510 static WCHAR *cached_path;
517 len += GetSystemDirectoryW( NULL, 0 );
518 len += GetWindowsDirectoryW( NULL, 0 );
519 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
522 GetSystemDirectoryW( p, path + len - p);
525 GetWindowsDirectoryW( p, path + len - p);
532 /******************************************************************
533 * MODULE_get_dll_load_path
535 * Compute the load path to use for a given dll.
536 * Returned pointer must be freed by caller.
538 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
540 static const WCHAR pathW[] = {'P','A','T','H',0};
542 const WCHAR *system_path = get_dll_system_path();
543 const WCHAR *mod_end = NULL;
544 UNICODE_STRING name, value;
546 int len = 0, path_len = 0;
548 /* adjust length for module name */
550 if (!module) module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
554 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
555 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
556 if (mod_end == module + 2 && module[1] == ':') mod_end++;
557 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
558 len += (mod_end - module) + 1;
560 len += strlenW( system_path ) + 2;
562 /* get the PATH variable */
564 RtlInitUnicodeString( &name, pathW );
566 value.MaximumLength = 0;
568 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
569 path_len = value.Length;
571 if (!(ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) ))) return NULL;
575 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
576 p += (mod_end - module);
579 strcpyW( p, system_path );
583 value.MaximumLength = path_len;
585 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
589 /* grow the buffer and retry */
590 path_len = value.Length;
591 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
593 HeapFree( GetProcessHeap(), 0, ret );
596 value.Buffer = new_ptr + (value.Buffer - ret);
597 value.MaximumLength = path_len;
600 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
605 /******************************************************************
606 * load_library_as_datafile
608 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
610 static const WCHAR dotDLL[] = {'.','d','l','l',0};
612 WCHAR filenameW[MAX_PATH];
613 HANDLE hFile = INVALID_HANDLE_VALUE;
619 if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
622 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
623 NULL, OPEN_EXISTING, 0, 0 );
625 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
627 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
628 CloseHandle( hFile );
629 if (!mapping) return FALSE;
631 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
632 CloseHandle( mapping );
633 if (!module) return FALSE;
635 /* make sure it's a valid PE file */
636 if (!RtlImageNtHeader(module))
638 UnmapViewOfFile( module );
641 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
646 /******************************************************************
649 * Helper for LoadLibraryExA/W.
651 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
657 if (flags & LOAD_LIBRARY_AS_DATAFILE)
659 /* The method in load_library_as_datafile allows searching for the
660 * 'native' libraries only
662 if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
663 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
664 /* Fallback to normal behaviour */
667 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
668 nts = LdrLoadDll( load_path, flags, libname, &hModule );
669 HeapFree( GetProcessHeap(), 0, load_path );
670 if (nts != STATUS_SUCCESS)
673 SetLastError( RtlNtStatusToDosError( nts ) );
679 /******************************************************************
680 * LoadLibraryExA (KERNEL32.@)
682 * Load a dll file into the process address space.
685 * libname [I] Name of the file to load
686 * hfile [I] Reserved, must be 0.
687 * flags [I] Flags for loading the dll
690 * Success: A handle to the loaded dll.
691 * Failure: A NULL handle. Use GetLastError() to determine the cause.
694 * The HFILE parameter is not used and marked reserved in the SDK. I can
695 * only guess that it should force a file to be mapped, but I rather
696 * ignore the parameter because it would be extremely difficult to
697 * integrate this with different types of module representations.
699 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
706 SetLastError(ERROR_INVALID_PARAMETER);
709 RtlCreateUnicodeStringFromAsciiz( &wstr, libname );
710 hModule = load_library( &wstr, flags );
711 RtlFreeUnicodeString( &wstr );
715 /***********************************************************************
716 * LoadLibraryExW (KERNEL32.@)
718 * Unicode version of LoadLibraryExA.
720 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
726 SetLastError(ERROR_INVALID_PARAMETER);
729 RtlInitUnicodeString( &wstr, libnameW );
730 return load_library( &wstr, flags );
733 /***********************************************************************
734 * LoadLibraryA (KERNEL32.@)
736 * Load a dll file into the process address space.
739 * libname [I] Name of the file to load
742 * Success: A handle to the loaded dll.
743 * Failure: A NULL handle. Use GetLastError() to determine the cause.
746 * See LoadLibraryExA().
748 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
750 return LoadLibraryExA(libname, 0, 0);
753 /***********************************************************************
754 * LoadLibraryW (KERNEL32.@)
756 * Unicode version of LoadLibraryA.
758 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
760 return LoadLibraryExW(libnameW, 0, 0);
763 /***********************************************************************
764 * FreeLibrary (KERNEL32.@)
765 * FreeLibrary32 (KERNEL.486)
767 * Free a dll loaded into the process address space.
770 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
773 * Success: TRUE. The dll is removed if it is not still in use.
774 * Failure: FALSE. Use GetLastError() to determine the cause.
776 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
783 SetLastError( ERROR_INVALID_HANDLE );
787 if ((ULONG_PTR)hLibModule & 1)
789 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
790 char *ptr = (char *)hLibModule - 1;
791 UnmapViewOfFile( ptr );
795 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
796 else SetLastError( RtlNtStatusToDosError( nts ) );
801 /***********************************************************************
802 * GetProcAddress (KERNEL32.@)
804 * Find the address of an exported symbol in a loaded dll.
807 * hModule [I] Handle to the dll returned by LoadLibraryA().
808 * function [I] Name of the symbol, or an integer ordinal number < 16384
811 * Success: A pointer to the symbol in the process address space.
812 * Failure: NULL. Use GetLastError() to determine the cause.
814 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
819 if (HIWORD(function))
823 RtlInitAnsiString( &str, function );
824 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
827 nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
828 if (nts != STATUS_SUCCESS)
830 SetLastError( RtlNtStatusToDosError( nts ) );
836 /***********************************************************************
837 * GetProcAddress32 (KERNEL.453)
839 * Find the address of an exported symbol in a loaded dll.
842 * hModule [I] Handle to the dll returned by LoadLibraryA().
843 * function [I] Name of the symbol, or an integer ordinal number < 16384
846 * Success: A pointer to the symbol in the process address space.
847 * Failure: NULL. Use GetLastError() to determine the cause.
849 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
851 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
852 return GetProcAddress( hModule, function );