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 )
139 unsigned char magic[4];
140 unsigned char ignored[12];
146 unsigned long cputype;
147 unsigned long cpusubtype;
148 unsigned long filetype;
156 /* Seek to the start of the file and read the header information. */
157 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
158 return BINARY_UNKNOWN;
159 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
160 return BINARY_UNKNOWN;
162 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
164 /* FIXME: we don't bother to check byte order, architecture, etc. */
165 switch(header.elf.type)
167 case 2: return BINARY_UNIX_EXE;
168 case 3: return BINARY_UNIX_LIB;
170 return BINARY_UNKNOWN;
173 /* Mach-o File with Endian set to Big Endian or Little Endian*/
174 if (header.macho.magic == 0xfeedface || header.macho.magic == 0xecafdeef)
176 switch(header.macho.filetype)
178 case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
180 return BINARY_UNKNOWN;
183 /* Not ELF, try DOS */
185 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
187 /* We do have a DOS image so we will now try to seek into
188 * the file by the amount indicated by the field
189 * "Offset to extended header" and read in the
190 * "magic" field information at that location.
191 * This will tell us if there is more header information
194 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
196 if (!ReadFile( hfile, magic, sizeof(magic), &len, NULL ) || len != sizeof(magic))
199 /* Reading the magic field succeeded so
200 * we will try to determine what type it is.
202 if (!memcmp( magic, "PE\0\0", 4 ))
204 IMAGE_FILE_HEADER FileHeader;
206 if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
208 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
209 return BINARY_PE_EXE;
214 if (!memcmp( magic, "NE", 2 ))
216 /* This is a Windows executable (NE) header. This can
217 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
218 * DOS program (running under a DOS extender). To decide
219 * which, we'll have to read the NE header.
222 if ( SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) != -1
223 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
224 && len == sizeof(ne) )
226 switch ( ne.ne_exetyp )
228 case 2: return BINARY_WIN16;
229 case 5: return BINARY_DOS;
230 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
233 /* Couldn't read header, so abort. */
237 /* Unknown extended header, but this file is nonetheless DOS-executable. */
241 return BINARY_UNKNOWN;
244 /***********************************************************************
245 * GetBinaryTypeW [KERNEL32.@]
247 * Determine whether a file is executable, and if so, what kind.
250 * lpApplicationName [I] Path of the file to check
251 * lpBinaryType [O] Destination for the binary type
254 * TRUE, if the file is an executable, in which case lpBinaryType is set.
255 * FALSE, if the file is not an executable or if the function fails.
258 * The type of executable is a property that determines which subsytem an
259 * executable file runs under. lpBinaryType can be set to one of the following
261 * SCS_32BIT_BINARY: A Win32 based application
262 * SCS_DOS_BINARY: An MS-Dos based application
263 * SCS_WOW_BINARY: A Win16 based application
264 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
265 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
266 * SCS_OS216_BINARY: A 16bit OS/2 based application
268 * To find the binary type, this function reads in the files header information.
269 * If extended header information is not present it will assume that the file
270 * is a DOS executable. If extended header information is present it will
271 * determine if the file is a 16 or 32 bit Windows executable by checking the
272 * flags in the header.
274 * ".com" and ".pif" files are only recognized by their file name extension,
275 * as per native Windows.
277 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
282 TRACE("%s\n", debugstr_w(lpApplicationName) );
286 if ( lpApplicationName == NULL || lpBinaryType == NULL )
289 /* Open the file indicated by lpApplicationName for reading.
291 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
292 NULL, OPEN_EXISTING, 0, 0 );
293 if ( hfile == INVALID_HANDLE_VALUE )
298 switch(MODULE_GetBinaryType( hfile ))
302 static const WCHAR comW[] = { '.','C','O','M',0 };
303 static const WCHAR pifW[] = { '.','P','I','F',0 };
306 /* try to determine from file name */
307 ptr = strrchrW( lpApplicationName, '.' );
309 if (!strcmpiW( ptr, comW ))
311 *lpBinaryType = SCS_DOS_BINARY;
314 else if (!strcmpiW( ptr, pifW ))
316 *lpBinaryType = SCS_PIF_BINARY;
323 *lpBinaryType = SCS_32BIT_BINARY;
327 *lpBinaryType = SCS_WOW_BINARY;
331 *lpBinaryType = SCS_OS216_BINARY;
335 *lpBinaryType = SCS_DOS_BINARY;
338 case BINARY_UNIX_EXE:
339 case BINARY_UNIX_LIB:
344 CloseHandle( hfile );
348 /***********************************************************************
349 * GetBinaryTypeA [KERNEL32.@]
350 * GetBinaryType [KERNEL32.@]
352 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
354 ANSI_STRING app_nameA;
357 TRACE("%s\n", debugstr_a(lpApplicationName));
361 if ( lpApplicationName == NULL || lpBinaryType == NULL )
364 RtlInitAnsiString(&app_nameA, lpApplicationName);
365 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
368 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
370 SetLastError(RtlNtStatusToDosError(status));
375 /***********************************************************************
376 * GetModuleHandleA (KERNEL32.@)
377 * GetModuleHandle32 (KERNEL.488)
379 * Get the handle of a dll loaded into the process address space.
382 * module [I] Name of the dll
385 * Success: A handle to the loaded dll.
386 * Failure: A NULL handle. Use GetLastError() to determine the cause.
388 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
392 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
393 if (!(moduleW = FILE_name_AtoW( module, FALSE ))) return 0;
394 return GetModuleHandleW( moduleW );
397 /***********************************************************************
398 * GetModuleHandleW (KERNEL32.@)
400 * Unicode version of GetModuleHandleA.
402 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
408 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
410 RtlInitUnicodeString( &wstr, module );
411 nts = LdrGetDllHandle( 0, 0, &wstr, &ret);
412 if (nts != STATUS_SUCCESS)
414 SetLastError( RtlNtStatusToDosError( nts ) );
421 /***********************************************************************
422 * GetModuleFileNameA (KERNEL32.@)
423 * GetModuleFileName32 (KERNEL.487)
425 * Get the file name of a loaded module from its handle.
428 * Success: The length of the file name, excluding the terminating NUL.
429 * Failure: 0. Use GetLastError() to determine the cause.
432 * This function always returns the long path of hModule (as opposed to
433 * GetModuleFileName16() which returns short paths when the modules version
436 DWORD WINAPI GetModuleFileNameA(
437 HMODULE hModule, /* [in] Module handle (32 bit) */
438 LPSTR lpFileName, /* [out] Destination for file name */
439 DWORD size ) /* [in] Size of lpFileName in characters */
441 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
445 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
448 GetModuleFileNameW( hModule, filenameW, size );
449 FILE_name_WtoA( filenameW, -1, lpFileName, size );
450 HeapFree( GetProcessHeap(), 0, filenameW );
451 return strlen( lpFileName );
454 /***********************************************************************
455 * GetModuleFileNameW (KERNEL32.@)
457 * Unicode version of GetModuleFileNameA.
459 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
464 WIN16_SUBSYSTEM_TIB *win16_tib;
468 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
470 lstrcpynW( lpFileName, win16_tib->exe_name->Buffer, size );
474 LdrLockLoaderLock( 0, NULL, &magic );
476 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
477 nts = LdrFindEntryForAddress( hModule, &pldr );
478 if (nts == STATUS_SUCCESS) lstrcpynW(lpFileName, pldr->FullDllName.Buffer, size);
479 else SetLastError( RtlNtStatusToDosError( nts ) );
481 LdrUnlockLoaderLock( 0, magic );
483 TRACE( "%s\n", debugstr_w(lpFileName) );
484 return strlenW(lpFileName);
488 /***********************************************************************
489 * get_dll_system_path
491 static const WCHAR *get_dll_system_path(void)
493 static WCHAR *cached_path;
500 len += GetSystemDirectoryW( NULL, 0 );
501 len += GetWindowsDirectoryW( NULL, 0 );
502 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
505 GetSystemDirectoryW( p, path + len - p);
508 GetWindowsDirectoryW( p, path + len - p);
515 /******************************************************************
516 * MODULE_get_dll_load_path
518 * Compute the load path to use for a given dll.
519 * Returned pointer must be freed by caller.
521 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
523 static const WCHAR pathW[] = {'P','A','T','H',0};
525 const WCHAR *system_path = get_dll_system_path();
526 const WCHAR *mod_end = NULL;
527 UNICODE_STRING name, value;
529 int len = 0, path_len = 0;
531 /* adjust length for module name */
533 if (!module) module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
537 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
538 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
539 if (mod_end == module + 2 && module[1] == ':') mod_end++;
540 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
541 len += (mod_end - module) + 1;
543 len += strlenW( system_path ) + 2;
545 /* get the PATH variable */
547 RtlInitUnicodeString( &name, pathW );
549 value.MaximumLength = 0;
551 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
552 path_len = value.Length;
554 if (!(ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) ))) return NULL;
558 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
559 p += (mod_end - module);
562 strcpyW( p, system_path );
566 value.MaximumLength = path_len;
568 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
572 /* grow the buffer and retry */
573 path_len = value.Length;
574 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
576 HeapFree( GetProcessHeap(), 0, ret );
579 value.Buffer = new_ptr + (value.Buffer - ret);
580 value.MaximumLength = path_len;
583 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
588 /******************************************************************
589 * load_library_as_datafile
591 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
593 static const WCHAR dotDLL[] = {'.','d','l','l',0};
595 WCHAR filenameW[MAX_PATH];
596 HANDLE hFile = INVALID_HANDLE_VALUE;
602 if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
605 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
606 NULL, OPEN_EXISTING, 0, 0 );
608 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
610 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
611 CloseHandle( hFile );
612 if (!mapping) return FALSE;
614 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
615 CloseHandle( mapping );
616 if (!module) return FALSE;
618 /* make sure it's a valid PE file */
619 if (!RtlImageNtHeader(module))
621 UnmapViewOfFile( module );
624 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
629 /******************************************************************
632 * Helper for LoadLibraryExA/W.
634 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
640 if (flags & LOAD_LIBRARY_AS_DATAFILE)
642 /* The method in load_library_as_datafile allows searching for the
643 * 'native' libraries only
645 if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
646 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
647 /* Fallback to normal behaviour */
650 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
651 nts = LdrLoadDll( load_path, flags, libname, &hModule );
652 HeapFree( GetProcessHeap(), 0, load_path );
653 if (nts != STATUS_SUCCESS)
656 SetLastError( RtlNtStatusToDosError( nts ) );
662 /******************************************************************
663 * LoadLibraryExA (KERNEL32.@)
665 * Load a dll file into the process address space.
668 * libname [I] Name of the file to load
669 * hfile [I] Reserved, must be 0.
670 * flags [I] Flags for loading the dll
673 * Success: A handle to the loaded dll.
674 * Failure: A NULL handle. Use GetLastError() to determine the cause.
677 * The HFILE parameter is not used and marked reserved in the SDK. I can
678 * only guess that it should force a file to be mapped, but I rather
679 * ignore the parameter because it would be extremely difficult to
680 * integrate this with different types of module representations.
682 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
686 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
687 return LoadLibraryExW( libnameW, hfile, flags );
690 /***********************************************************************
691 * LoadLibraryExW (KERNEL32.@)
693 * Unicode version of LoadLibraryExA.
695 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
701 SetLastError(ERROR_INVALID_PARAMETER);
704 RtlInitUnicodeString( &wstr, libnameW );
705 return load_library( &wstr, flags );
708 /***********************************************************************
709 * LoadLibraryA (KERNEL32.@)
711 * Load a dll file into the process address space.
714 * libname [I] Name of the file to load
717 * Success: A handle to the loaded dll.
718 * Failure: A NULL handle. Use GetLastError() to determine the cause.
721 * See LoadLibraryExA().
723 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
725 return LoadLibraryExA(libname, 0, 0);
728 /***********************************************************************
729 * LoadLibraryW (KERNEL32.@)
731 * Unicode version of LoadLibraryA.
733 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
735 return LoadLibraryExW(libnameW, 0, 0);
738 /***********************************************************************
739 * FreeLibrary (KERNEL32.@)
740 * FreeLibrary32 (KERNEL.486)
742 * Free a dll loaded into the process address space.
745 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
748 * Success: TRUE. The dll is removed if it is not still in use.
749 * Failure: FALSE. Use GetLastError() to determine the cause.
751 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
758 SetLastError( ERROR_INVALID_HANDLE );
762 if ((ULONG_PTR)hLibModule & 1)
764 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
765 char *ptr = (char *)hLibModule - 1;
766 UnmapViewOfFile( ptr );
770 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
771 else SetLastError( RtlNtStatusToDosError( nts ) );
776 /***********************************************************************
777 * GetProcAddress (KERNEL32.@)
779 * Find the address of an exported symbol in a loaded dll.
782 * hModule [I] Handle to the dll returned by LoadLibraryA().
783 * function [I] Name of the symbol, or an integer ordinal number < 16384
786 * Success: A pointer to the symbol in the process address space.
787 * Failure: NULL. Use GetLastError() to determine the cause.
789 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
794 if (HIWORD(function))
798 RtlInitAnsiString( &str, function );
799 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
802 nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
803 if (nts != STATUS_SUCCESS)
805 SetLastError( RtlNtStatusToDosError( nts ) );
811 /***********************************************************************
812 * GetProcAddress32 (KERNEL.453)
814 * Find the address of an exported symbol in a loaded dll.
817 * hModule [I] Handle to the dll returned by LoadLibraryA().
818 * function [I] Name of the symbol, or an integer ordinal number < 16384
821 * Success: A pointer to the symbol in the process address space.
822 * Failure: NULL. Use GetLastError() to determine the cause.
824 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
826 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
827 return GetProcAddress( hModule, function );