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"
41 #include "kernel_private.h"
43 #include "wine/debug.h"
44 #include "wine/unicode.h"
45 #include "wine/server.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
51 /****************************************************************************
52 * DisableThreadLibraryCalls (KERNEL32.@)
54 * Inform the module loader that thread notifications are not required for a dll.
57 * hModule [I] Module handle to skip calls for
60 * Success: TRUE. Thread attach and detach notifications will not be sent
62 * Failure: FALSE. Use GetLastError() to determine the cause.
65 * This is typically called from the dll entry point of a dll during process
66 * attachment, for dlls that do not need to process thread notifications.
68 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
70 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
71 if (nts == STATUS_SUCCESS) return TRUE;
73 SetLastError( RtlNtStatusToDosError( nts ) );
78 /* Check whether a file is an OS/2 or a very old Windows executable
79 * by testing on import of KERNEL.
81 * FIXME: is reading the module imports the only way of discerning
82 * old Windows binaries from OS/2 ones ? At least it seems so...
84 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
85 const IMAGE_OS2_HEADER *ne)
87 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
88 enum binary_type ret = BINARY_OS216;
94 /* read modref table */
95 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
96 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
97 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
98 || (len != ne->ne_cmod*sizeof(WORD)) )
101 /* read imported names table */
102 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
103 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
104 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
105 || (len != ne->ne_enttab - ne->ne_imptab) )
108 for (i=0; i < ne->ne_cmod; i++)
110 LPSTR module = &nametab[modtab[i]];
111 TRACE("modref: %.*s\n", module[0], &module[1]);
112 if (!(strncmp(&module[1], "KERNEL", module[0])))
113 { /* very old Windows file */
114 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
121 ERR("Hmm, an error occurred. Is this binary file broken?\n");
124 HeapFree( GetProcessHeap(), 0, modtab);
125 HeapFree( GetProcessHeap(), 0, nametab);
126 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
130 /***********************************************************************
131 * MODULE_GetBinaryType
133 enum binary_type MODULE_GetBinaryType( HANDLE hfile, void **res_start, void **res_end )
139 unsigned char magic[4];
140 unsigned char ignored[12];
146 unsigned long cputype;
147 unsigned long cpusubtype;
148 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)
188 IMAGE_OS2_HEADER os2;
192 /* We do have a DOS image so we will now try to seek into
193 * the file by the amount indicated by the field
194 * "Offset to extended header" and read in the
195 * "magic" field information at that location.
196 * This will tell us if there is more header information
199 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
201 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4)
204 /* Reading the magic field succeeded so
205 * we will try to determine what type it is.
207 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
209 if (len >= sizeof(ext_header.nt.FileHeader))
211 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
212 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
213 if (res_start) *res_start = (void *)ext_header.nt.OptionalHeader.ImageBase;
214 if (res_end) *res_end = (void *)(ext_header.nt.OptionalHeader.ImageBase +
215 ext_header.nt.OptionalHeader.SizeOfImage);
216 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
217 return BINARY_PE_EXE;
222 if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
224 /* This is a Windows executable (NE) header. This can
225 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
226 * DOS program (running under a DOS extender). To decide
227 * which, we'll have to read the NE header.
229 if (len >= sizeof(ext_header.os2))
231 switch ( ext_header.os2.ne_exetyp )
233 case 1: return BINARY_OS216; /* OS/2 */
234 case 2: return BINARY_WIN16; /* Windows */
235 case 3: return BINARY_DOS; /* European MS-DOS 4.x */
236 case 4: return BINARY_WIN16; /* Windows 386; FIXME: is this 32bit??? */
237 case 5: return BINARY_DOS; /* BOSS, Borland Operating System Services */
238 /* other types, e.g. 0 is: "unknown" */
239 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2);
242 /* Couldn't read header, so abort. */
246 /* Unknown extended header, but this file is nonetheless DOS-executable. */
250 return BINARY_UNKNOWN;
253 /***********************************************************************
254 * GetBinaryTypeW [KERNEL32.@]
256 * Determine whether a file is executable, and if so, what kind.
259 * lpApplicationName [I] Path of the file to check
260 * lpBinaryType [O] Destination for the binary type
263 * TRUE, if the file is an executable, in which case lpBinaryType is set.
264 * FALSE, if the file is not an executable or if the function fails.
267 * The type of executable is a property that determines which subsytem an
268 * executable file runs under. lpBinaryType can be set to one of the following
270 * SCS_32BIT_BINARY: A Win32 based application
271 * SCS_DOS_BINARY: An MS-Dos based application
272 * SCS_WOW_BINARY: A Win16 based application
273 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
274 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
275 * SCS_OS216_BINARY: A 16bit OS/2 based application
277 * To find the binary type, this function reads in the files header information.
278 * If extended header information is not present it will assume that the file
279 * is a DOS executable. If extended header information is present it will
280 * determine if the file is a 16 or 32 bit Windows executable by checking the
281 * flags in the header.
283 * ".com" and ".pif" files are only recognized by their file name extension,
284 * as per native Windows.
286 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
291 TRACE("%s\n", debugstr_w(lpApplicationName) );
295 if ( lpApplicationName == NULL || lpBinaryType == NULL )
298 /* Open the file indicated by lpApplicationName for reading.
300 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
301 NULL, OPEN_EXISTING, 0, 0 );
302 if ( hfile == INVALID_HANDLE_VALUE )
307 switch(MODULE_GetBinaryType( hfile, NULL, NULL ))
311 static const WCHAR comW[] = { '.','C','O','M',0 };
312 static const WCHAR pifW[] = { '.','P','I','F',0 };
315 /* try to determine from file name */
316 ptr = strrchrW( lpApplicationName, '.' );
318 if (!strcmpiW( ptr, comW ))
320 *lpBinaryType = SCS_DOS_BINARY;
323 else if (!strcmpiW( ptr, pifW ))
325 *lpBinaryType = SCS_PIF_BINARY;
332 *lpBinaryType = SCS_32BIT_BINARY;
336 *lpBinaryType = SCS_WOW_BINARY;
340 *lpBinaryType = SCS_OS216_BINARY;
344 *lpBinaryType = SCS_DOS_BINARY;
347 case BINARY_UNIX_EXE:
348 case BINARY_UNIX_LIB:
353 CloseHandle( hfile );
357 /***********************************************************************
358 * GetBinaryTypeA [KERNEL32.@]
359 * GetBinaryType [KERNEL32.@]
361 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
363 ANSI_STRING app_nameA;
366 TRACE("%s\n", debugstr_a(lpApplicationName));
370 if ( lpApplicationName == NULL || lpBinaryType == NULL )
373 RtlInitAnsiString(&app_nameA, lpApplicationName);
374 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
377 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
379 SetLastError(RtlNtStatusToDosError(status));
384 /***********************************************************************
385 * GetModuleHandleA (KERNEL32.@)
386 * GetModuleHandle32 (KERNEL.488)
388 * Get the handle of a dll loaded into the process address space.
391 * module [I] Name of the dll
394 * Success: A handle to the loaded dll.
395 * Failure: A NULL handle. Use GetLastError() to determine the cause.
397 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
401 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
402 if (!(moduleW = FILE_name_AtoW( module, FALSE ))) return 0;
403 return GetModuleHandleW( moduleW );
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
444 * The function doesn't write a terminating '\0' is the buffer is too
447 DWORD WINAPI GetModuleFileNameA(
448 HMODULE hModule, /* [in] Module handle (32 bit) */
449 LPSTR lpFileName, /* [out] Destination for file name */
450 DWORD size ) /* [in] Size of lpFileName in characters */
452 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
457 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
460 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
462 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
463 if (len < size) lpFileName[len] = '\0';
465 HeapFree( GetProcessHeap(), 0, filenameW );
469 /***********************************************************************
470 * GetModuleFileNameW (KERNEL32.@)
472 * Unicode version of GetModuleFileNameA.
474 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
476 ULONG magic, len = 0;
479 WIN16_SUBSYSTEM_TIB *win16_tib;
481 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
483 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
484 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
485 if (len < size) lpFileName[len] = '\0';
489 LdrLockLoaderLock( 0, NULL, &magic );
491 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
492 nts = LdrFindEntryForAddress( hModule, &pldr );
493 if (nts == STATUS_SUCCESS)
495 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
496 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
497 if (len < size) lpFileName[len] = '\0';
499 else SetLastError( RtlNtStatusToDosError( nts ) );
501 LdrUnlockLoaderLock( 0, magic );
503 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
508 /***********************************************************************
509 * get_dll_system_path
511 static const WCHAR *get_dll_system_path(void)
513 static WCHAR *cached_path;
520 len += GetSystemDirectoryW( NULL, 0 );
521 len += GetWindowsDirectoryW( NULL, 0 );
522 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
525 GetSystemDirectoryW( p, path + len - p);
528 GetWindowsDirectoryW( p, path + len - p);
535 /******************************************************************
536 * MODULE_get_dll_load_path
538 * Compute the load path to use for a given dll.
539 * Returned pointer must be freed by caller.
541 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
543 static const WCHAR pathW[] = {'P','A','T','H',0};
545 const WCHAR *system_path = get_dll_system_path();
546 const WCHAR *mod_end = NULL;
547 UNICODE_STRING name, value;
549 int len = 0, path_len = 0;
551 /* adjust length for module name */
553 if (!module) module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
557 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
558 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
559 if (mod_end == module + 2 && module[1] == ':') mod_end++;
560 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
561 len += (mod_end - module) + 1;
563 len += strlenW( system_path ) + 2;
565 /* get the PATH variable */
567 RtlInitUnicodeString( &name, pathW );
569 value.MaximumLength = 0;
571 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
572 path_len = value.Length;
574 if (!(ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) ))) return NULL;
578 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
579 p += (mod_end - module);
582 strcpyW( p, system_path );
586 value.MaximumLength = path_len;
588 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
592 /* grow the buffer and retry */
593 path_len = value.Length;
594 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
596 HeapFree( GetProcessHeap(), 0, ret );
599 value.Buffer = new_ptr + (value.Buffer - ret);
600 value.MaximumLength = path_len;
603 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
608 /******************************************************************
609 * load_library_as_datafile
611 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
613 static const WCHAR dotDLL[] = {'.','d','l','l',0};
615 WCHAR filenameW[MAX_PATH];
616 HANDLE hFile = INVALID_HANDLE_VALUE;
622 if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
625 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
626 NULL, OPEN_EXISTING, 0, 0 );
628 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
630 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
631 CloseHandle( hFile );
632 if (!mapping) return FALSE;
634 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
635 CloseHandle( mapping );
636 if (!module) return FALSE;
638 /* make sure it's a valid PE file */
639 if (!RtlImageNtHeader(module))
641 UnmapViewOfFile( module );
644 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
649 /******************************************************************
652 * Helper for LoadLibraryExA/W.
654 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
660 if (flags & LOAD_LIBRARY_AS_DATAFILE)
662 /* The method in load_library_as_datafile allows searching for the
663 * 'native' libraries only
665 if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
666 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
667 /* Fallback to normal behaviour */
670 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
671 nts = LdrLoadDll( load_path, flags, libname, &hModule );
672 HeapFree( GetProcessHeap(), 0, load_path );
673 if (nts != STATUS_SUCCESS)
676 SetLastError( RtlNtStatusToDosError( nts ) );
682 /******************************************************************
683 * LoadLibraryExA (KERNEL32.@)
685 * Load a dll file into the process address space.
688 * libname [I] Name of the file to load
689 * hfile [I] Reserved, must be 0.
690 * flags [I] Flags for loading the dll
693 * Success: A handle to the loaded dll.
694 * Failure: A NULL handle. Use GetLastError() to determine the cause.
697 * The HFILE parameter is not used and marked reserved in the SDK. I can
698 * only guess that it should force a file to be mapped, but I rather
699 * ignore the parameter because it would be extremely difficult to
700 * integrate this with different types of module representations.
702 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
706 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
707 return LoadLibraryExW( libnameW, hfile, flags );
710 /***********************************************************************
711 * LoadLibraryExW (KERNEL32.@)
713 * Unicode version of LoadLibraryExA.
715 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
721 SetLastError(ERROR_INVALID_PARAMETER);
724 RtlInitUnicodeString( &wstr, libnameW );
725 return load_library( &wstr, flags );
728 /***********************************************************************
729 * LoadLibraryA (KERNEL32.@)
731 * Load a dll file into the process address space.
734 * libname [I] Name of the file to load
737 * Success: A handle to the loaded dll.
738 * Failure: A NULL handle. Use GetLastError() to determine the cause.
741 * See LoadLibraryExA().
743 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
745 return LoadLibraryExA(libname, 0, 0);
748 /***********************************************************************
749 * LoadLibraryW (KERNEL32.@)
751 * Unicode version of LoadLibraryA.
753 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
755 return LoadLibraryExW(libnameW, 0, 0);
758 /***********************************************************************
759 * FreeLibrary (KERNEL32.@)
760 * FreeLibrary32 (KERNEL.486)
762 * Free a dll loaded into the process address space.
765 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
768 * Success: TRUE. The dll is removed if it is not still in use.
769 * Failure: FALSE. Use GetLastError() to determine the cause.
771 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
778 SetLastError( ERROR_INVALID_HANDLE );
782 if ((ULONG_PTR)hLibModule & 1)
784 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
785 char *ptr = (char *)hLibModule - 1;
786 UnmapViewOfFile( ptr );
790 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
791 else SetLastError( RtlNtStatusToDosError( nts ) );
796 /***********************************************************************
797 * GetProcAddress (KERNEL32.@)
799 * Find the address of an exported symbol in a loaded dll.
802 * hModule [I] Handle to the dll returned by LoadLibraryA().
803 * function [I] Name of the symbol, or an integer ordinal number < 16384
806 * Success: A pointer to the symbol in the process address space.
807 * Failure: NULL. Use GetLastError() to determine the cause.
809 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
814 if (HIWORD(function))
818 RtlInitAnsiString( &str, function );
819 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
822 nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
823 if (nts != STATUS_SUCCESS)
825 SetLastError( RtlNtStatusToDosError( nts ) );
831 /***********************************************************************
832 * GetProcAddress32 (KERNEL.453)
834 * Find the address of an exported symbol in a loaded dll.
837 * hModule [I] Handle to the dll returned by LoadLibraryA().
838 * function [I] Name of the symbol, or an integer ordinal number < 16384
841 * Success: A pointer to the symbol in the process address space.
842 * Failure: NULL. Use GetLastError() to determine the cause.
844 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
846 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
847 return GetProcAddress( hModule, function );