msvcrt: Only check for flag presence in isatty function.
[wine/multimedia.git] / dlls / kernel32 / module.c
blob514b6be7dcefe2177bf2fe38d613f563048dfbfe
1 /*
2 * Modules
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <fcntl.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/types.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include "ntstatus.h"
34 #define WIN32_NO_STATUS
35 #include "winerror.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winternl.h"
39 #include "kernel_private.h"
40 #include "psapi.h"
42 #include "wine/exception.h"
43 #include "wine/debug.h"
44 #include "wine/unicode.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 #define NE_FFLAGS_LIBMODULE 0x8000
50 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
52 static CRITICAL_SECTION dlldir_section;
53 static CRITICAL_SECTION_DEBUG critsect_debug =
55 0, 0, &dlldir_section,
56 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
57 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
59 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
62 /****************************************************************************
63 * GetDllDirectoryA (KERNEL32.@)
65 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
67 DWORD len;
69 RtlEnterCriticalSection( &dlldir_section );
70 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
71 if (buffer && buf_len > len)
73 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
74 else *buffer = 0;
76 else
78 len++; /* for terminating null */
79 if (buffer) *buffer = 0;
81 RtlLeaveCriticalSection( &dlldir_section );
82 return len;
86 /****************************************************************************
87 * GetDllDirectoryW (KERNEL32.@)
89 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
91 DWORD len;
93 RtlEnterCriticalSection( &dlldir_section );
94 len = dll_directory ? strlenW( dll_directory ) : 0;
95 if (buffer && buf_len > len)
97 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
98 else *buffer = 0;
100 else
102 len++; /* for terminating null */
103 if (buffer) *buffer = 0;
105 RtlLeaveCriticalSection( &dlldir_section );
106 return len;
110 /****************************************************************************
111 * SetDllDirectoryA (KERNEL32.@)
113 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
115 WCHAR *dirW;
116 BOOL ret;
118 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
119 ret = SetDllDirectoryW( dirW );
120 HeapFree( GetProcessHeap(), 0, dirW );
121 return ret;
125 /****************************************************************************
126 * SetDllDirectoryW (KERNEL32.@)
128 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
130 WCHAR *newdir = NULL;
132 if (dir)
134 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
135 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
137 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
138 return FALSE;
140 memcpy( newdir, dir, len );
143 RtlEnterCriticalSection( &dlldir_section );
144 HeapFree( GetProcessHeap(), 0, dll_directory );
145 dll_directory = newdir;
146 RtlLeaveCriticalSection( &dlldir_section );
147 return TRUE;
151 /****************************************************************************
152 * DisableThreadLibraryCalls (KERNEL32.@)
154 * Inform the module loader that thread notifications are not required for a dll.
156 * PARAMS
157 * hModule [I] Module handle to skip calls for
159 * RETURNS
160 * Success: TRUE. Thread attach and detach notifications will not be sent
161 * to hModule.
162 * Failure: FALSE. Use GetLastError() to determine the cause.
164 * NOTES
165 * This is typically called from the dll entry point of a dll during process
166 * attachment, for dlls that do not need to process thread notifications.
168 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
170 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
171 if (nts == STATUS_SUCCESS) return TRUE;
173 SetLastError( RtlNtStatusToDosError( nts ) );
174 return FALSE;
178 /* Check whether a file is an OS/2 or a very old Windows executable
179 * by testing on import of KERNEL.
181 * FIXME: is reading the module imports the only way of discerning
182 * old Windows binaries from OS/2 ones ? At least it seems so...
184 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
186 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
187 DWORD ret = BINARY_OS216;
188 LPWORD modtab = NULL;
189 LPSTR nametab = NULL;
190 DWORD len;
191 int i;
193 /* read modref table */
194 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
195 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
196 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
197 || (len != ne->ne_cmod*sizeof(WORD)) )
198 goto broken;
200 /* read imported names table */
201 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
202 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
203 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
204 || (len != ne->ne_enttab - ne->ne_imptab) )
205 goto broken;
207 for (i=0; i < ne->ne_cmod; i++)
209 LPSTR module = &nametab[modtab[i]];
210 TRACE("modref: %.*s\n", module[0], &module[1]);
211 if (!(strncmp(&module[1], "KERNEL", module[0])))
212 { /* very old Windows file */
213 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
214 ret = BINARY_WIN16;
215 goto good;
219 broken:
220 ERR("Hmm, an error occurred. Is this binary file broken?\n");
222 good:
223 HeapFree( GetProcessHeap(), 0, modtab);
224 HeapFree( GetProcessHeap(), 0, nametab);
225 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
226 return ret;
229 /***********************************************************************
230 * MODULE_GetBinaryType
232 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
234 union
236 struct
238 unsigned char magic[4];
239 unsigned char class;
240 unsigned char data;
241 unsigned char version;
242 unsigned char ignored[9];
243 unsigned short type;
244 unsigned short machine;
245 } elf;
246 struct
248 unsigned int magic;
249 unsigned int cputype;
250 unsigned int cpusubtype;
251 unsigned int filetype;
252 } macho;
253 IMAGE_DOS_HEADER mz;
254 } header;
256 DWORD len;
258 memset( info, 0, sizeof(*info) );
260 /* Seek to the start of the file and read the header information. */
261 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
262 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
264 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
266 if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
267 #ifdef WORDS_BIGENDIAN
268 if (header.elf.data == 1)
269 #else
270 if (header.elf.data == 2)
271 #endif
273 header.elf.type = RtlUshortByteSwap( header.elf.type );
274 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
276 switch(header.elf.type)
278 case 2: info->type = BINARY_UNIX_EXE; break;
279 case 3: info->type = BINARY_UNIX_LIB; break;
281 switch(header.elf.machine)
283 case 3: info->arch = IMAGE_FILE_MACHINE_I386; break;
284 case 20: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
285 case 40: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
286 case 50: info->arch = IMAGE_FILE_MACHINE_IA64; break;
287 case 62: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
288 case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
291 /* Mach-o File with Endian set to Big Endian or Little Endian */
292 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
294 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
295 if (header.macho.magic == 0xcefaedfe)
297 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
298 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
300 switch(header.macho.filetype)
302 case 2: info->type = BINARY_UNIX_EXE; break;
303 case 8: info->type = BINARY_UNIX_LIB; break;
305 switch(header.macho.cputype)
307 case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
308 case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
309 case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
310 case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
311 case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
314 /* Not ELF, try DOS */
315 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
317 union
319 IMAGE_OS2_HEADER os2;
320 IMAGE_NT_HEADERS32 nt;
321 } ext_header;
323 /* We do have a DOS image so we will now try to seek into
324 * the file by the amount indicated by the field
325 * "Offset to extended header" and read in the
326 * "magic" field information at that location.
327 * This will tell us if there is more header information
328 * to read or not.
330 info->type = BINARY_DOS;
331 info->arch = IMAGE_FILE_MACHINE_I386;
332 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
333 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
335 /* Reading the magic field succeeded so
336 * we will try to determine what type it is.
338 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
340 if (len >= sizeof(ext_header.nt.FileHeader))
342 info->type = BINARY_PE;
343 info->arch = ext_header.nt.FileHeader.Machine;
344 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
345 info->flags |= BINARY_FLAG_DLL;
346 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
347 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
348 switch (ext_header.nt.OptionalHeader.Magic)
350 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
351 info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
352 info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
353 ext_header.nt.OptionalHeader.SizeOfImage);
354 break;
355 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
356 info->flags |= BINARY_FLAG_64BIT;
357 break;
361 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
363 /* This is a Windows executable (NE) header. This can
364 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
365 * DOS program (running under a DOS extender). To decide
366 * which, we'll have to read the NE header.
368 if (len >= sizeof(ext_header.os2))
370 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
371 switch ( ext_header.os2.ne_exetyp )
373 case 1: info->type = BINARY_OS216; break; /* OS/2 */
374 case 2: info->type = BINARY_WIN16; break; /* Windows */
375 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
376 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
377 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
378 /* other types, e.g. 0 is: "unknown" */
379 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
386 /***********************************************************************
387 * GetBinaryTypeW [KERNEL32.@]
389 * Determine whether a file is executable, and if so, what kind.
391 * PARAMS
392 * lpApplicationName [I] Path of the file to check
393 * lpBinaryType [O] Destination for the binary type
395 * RETURNS
396 * TRUE, if the file is an executable, in which case lpBinaryType is set.
397 * FALSE, if the file is not an executable or if the function fails.
399 * NOTES
400 * The type of executable is a property that determines which subsystem an
401 * executable file runs under. lpBinaryType can be set to one of the following
402 * values:
403 * SCS_32BIT_BINARY: A Win32 based application
404 * SCS_64BIT_BINARY: A Win64 based application
405 * SCS_DOS_BINARY: An MS-Dos based application
406 * SCS_WOW_BINARY: A Win16 based application
407 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
408 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
409 * SCS_OS216_BINARY: A 16bit OS/2 based application
411 * To find the binary type, this function reads in the files header information.
412 * If extended header information is not present it will assume that the file
413 * is a DOS executable. If extended header information is present it will
414 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
415 * flags in the header.
417 * ".com" and ".pif" files are only recognized by their file name extension,
418 * as per native Windows.
420 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
422 BOOL ret = FALSE;
423 HANDLE hfile;
424 struct binary_info binary_info;
426 TRACE("%s\n", debugstr_w(lpApplicationName) );
428 /* Sanity check.
430 if ( lpApplicationName == NULL || lpBinaryType == NULL )
431 return FALSE;
433 /* Open the file indicated by lpApplicationName for reading.
435 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
436 NULL, OPEN_EXISTING, 0, 0 );
437 if ( hfile == INVALID_HANDLE_VALUE )
438 return FALSE;
440 /* Check binary type
442 MODULE_get_binary_info( hfile, &binary_info );
443 switch (binary_info.type)
445 case BINARY_UNKNOWN:
447 static const WCHAR comW[] = { '.','C','O','M',0 };
448 static const WCHAR pifW[] = { '.','P','I','F',0 };
449 const WCHAR *ptr;
451 /* try to determine from file name */
452 ptr = strrchrW( lpApplicationName, '.' );
453 if (!ptr) break;
454 if (!strcmpiW( ptr, comW ))
456 *lpBinaryType = SCS_DOS_BINARY;
457 ret = TRUE;
459 else if (!strcmpiW( ptr, pifW ))
461 *lpBinaryType = SCS_PIF_BINARY;
462 ret = TRUE;
464 break;
466 case BINARY_PE:
467 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
468 ret = TRUE;
469 break;
470 case BINARY_WIN16:
471 *lpBinaryType = SCS_WOW_BINARY;
472 ret = TRUE;
473 break;
474 case BINARY_OS216:
475 *lpBinaryType = SCS_OS216_BINARY;
476 ret = TRUE;
477 break;
478 case BINARY_DOS:
479 *lpBinaryType = SCS_DOS_BINARY;
480 ret = TRUE;
481 break;
482 case BINARY_UNIX_EXE:
483 case BINARY_UNIX_LIB:
484 ret = FALSE;
485 break;
488 CloseHandle( hfile );
489 return ret;
492 /***********************************************************************
493 * GetBinaryTypeA [KERNEL32.@]
494 * GetBinaryType [KERNEL32.@]
496 * See GetBinaryTypeW.
498 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
500 ANSI_STRING app_nameA;
501 NTSTATUS status;
503 TRACE("%s\n", debugstr_a(lpApplicationName));
505 /* Sanity check.
507 if ( lpApplicationName == NULL || lpBinaryType == NULL )
508 return FALSE;
510 RtlInitAnsiString(&app_nameA, lpApplicationName);
511 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
512 &app_nameA, FALSE);
513 if (!status)
514 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
516 SetLastError(RtlNtStatusToDosError(status));
517 return FALSE;
520 /***********************************************************************
521 * GetModuleHandleExA (KERNEL32.@)
523 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
525 WCHAR *nameW;
527 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
528 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
530 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
531 return GetModuleHandleExW( flags, nameW, module );
534 /***********************************************************************
535 * GetModuleHandleExW (KERNEL32.@)
537 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
539 NTSTATUS status = STATUS_SUCCESS;
540 HMODULE ret;
541 ULONG_PTR magic;
542 BOOL lock;
544 if (!module)
546 SetLastError( ERROR_INVALID_PARAMETER );
547 return FALSE;
550 /* if we are messing with the refcount, grab the loader lock */
551 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
552 if (lock)
553 LdrLockLoaderLock( 0, NULL, &magic );
555 if (!name)
557 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
559 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
561 void *dummy;
562 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
564 else
566 UNICODE_STRING wstr;
567 RtlInitUnicodeString( &wstr, name );
568 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
571 if (status == STATUS_SUCCESS)
573 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
574 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
575 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
576 LdrAddRefDll( 0, ret );
578 else SetLastError( RtlNtStatusToDosError( status ) );
580 if (lock)
581 LdrUnlockLoaderLock( 0, magic );
583 if (status == STATUS_SUCCESS) *module = ret;
584 else *module = NULL;
586 return (status == STATUS_SUCCESS);
589 /***********************************************************************
590 * GetModuleHandleA (KERNEL32.@)
592 * Get the handle of a dll loaded into the process address space.
594 * PARAMS
595 * module [I] Name of the dll
597 * RETURNS
598 * Success: A handle to the loaded dll.
599 * Failure: A NULL handle. Use GetLastError() to determine the cause.
601 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
603 HMODULE ret;
605 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
606 return ret;
609 /***********************************************************************
610 * GetModuleHandleW (KERNEL32.@)
612 * Unicode version of GetModuleHandleA.
614 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
616 HMODULE ret;
618 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
619 return ret;
623 /***********************************************************************
624 * GetModuleFileNameA (KERNEL32.@)
626 * Get the file name of a loaded module from its handle.
628 * RETURNS
629 * Success: The length of the file name, excluding the terminating NUL.
630 * Failure: 0. Use GetLastError() to determine the cause.
632 * NOTES
633 * This function always returns the long path of hModule
634 * The function doesn't write a terminating '\0' if the buffer is too
635 * small.
637 DWORD WINAPI GetModuleFileNameA(
638 HMODULE hModule, /* [in] Module handle (32 bit) */
639 LPSTR lpFileName, /* [out] Destination for file name */
640 DWORD size ) /* [in] Size of lpFileName in characters */
642 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
643 DWORD len;
645 if (!filenameW)
647 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
648 return 0;
650 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
652 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
653 if (len < size)
654 lpFileName[len] = '\0';
655 else
656 SetLastError( ERROR_INSUFFICIENT_BUFFER );
658 HeapFree( GetProcessHeap(), 0, filenameW );
659 return len;
662 /***********************************************************************
663 * GetModuleFileNameW (KERNEL32.@)
665 * Unicode version of GetModuleFileNameA.
667 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
669 ULONG len = 0;
670 ULONG_PTR magic;
671 LDR_MODULE *pldr;
672 NTSTATUS nts;
673 WIN16_SUBSYSTEM_TIB *win16_tib;
675 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
677 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
678 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
679 if (len < size) lpFileName[len] = '\0';
680 goto done;
683 LdrLockLoaderLock( 0, NULL, &magic );
685 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
686 nts = LdrFindEntryForAddress( hModule, &pldr );
687 if (nts == STATUS_SUCCESS)
689 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
690 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
691 if (len < size)
693 lpFileName[len] = '\0';
694 SetLastError( 0 );
696 else
697 SetLastError( ERROR_INSUFFICIENT_BUFFER );
699 else SetLastError( RtlNtStatusToDosError( nts ) );
701 LdrUnlockLoaderLock( 0, magic );
702 done:
703 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
704 return len;
708 /***********************************************************************
709 * get_dll_system_path
711 static const WCHAR *get_dll_system_path(void)
713 static WCHAR *cached_path;
715 if (!cached_path)
717 WCHAR *p, *path;
718 int len = 3;
720 len += 2 * GetSystemDirectoryW( NULL, 0 );
721 len += GetWindowsDirectoryW( NULL, 0 );
722 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
723 *p++ = '.';
724 *p++ = ';';
725 GetSystemDirectoryW( p, path + len - p);
726 p += strlenW(p);
727 /* if system directory ends in "32" add 16-bit version too */
728 if (p[-2] == '3' && p[-1] == '2')
730 *p++ = ';';
731 GetSystemDirectoryW( p, path + len - p);
732 p += strlenW(p) - 2;
734 *p++ = ';';
735 GetWindowsDirectoryW( p, path + len - p);
736 cached_path = path;
738 return cached_path;
741 /******************************************************************
742 * get_module_path_end
744 * Returns the end of the directory component of the module path.
746 static inline const WCHAR *get_module_path_end(const WCHAR *module)
748 const WCHAR *p;
749 const WCHAR *mod_end = module;
750 if (!module) return mod_end;
752 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
753 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
754 if (mod_end == module + 2 && module[1] == ':') mod_end++;
755 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
757 return mod_end;
760 /******************************************************************
761 * MODULE_get_dll_load_path
763 * Compute the load path to use for a given dll.
764 * Returned pointer must be freed by caller.
766 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
768 static const WCHAR pathW[] = {'P','A','T','H',0};
770 const WCHAR *system_path = get_dll_system_path();
771 const WCHAR *mod_end = NULL;
772 UNICODE_STRING name, value;
773 WCHAR *p, *ret;
774 int len = 0, path_len = 0;
776 /* adjust length for module name */
778 if (module)
779 mod_end = get_module_path_end( module );
780 /* if module is NULL or doesn't contain a path, fall back to directory
781 * process was loaded from */
782 if (module == mod_end)
784 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
785 mod_end = get_module_path_end( module );
787 len += (mod_end - module) + 1;
789 len += strlenW( system_path ) + 2;
791 /* get the PATH variable */
793 RtlInitUnicodeString( &name, pathW );
794 value.Length = 0;
795 value.MaximumLength = 0;
796 value.Buffer = NULL;
797 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
798 path_len = value.Length;
800 RtlEnterCriticalSection( &dlldir_section );
801 if (dll_directory) len += strlenW(dll_directory) + 1;
802 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
804 if (module)
806 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
807 p += (mod_end - module);
808 *p++ = ';';
810 if (dll_directory)
812 strcpyW( p, dll_directory );
813 p += strlenW(p);
814 *p++ = ';';
817 RtlLeaveCriticalSection( &dlldir_section );
818 if (!ret) return NULL;
820 strcpyW( p, system_path );
821 p += strlenW(p);
822 *p++ = ';';
823 value.Buffer = p;
824 value.MaximumLength = path_len;
826 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
828 WCHAR *new_ptr;
830 /* grow the buffer and retry */
831 path_len = value.Length;
832 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
834 HeapFree( GetProcessHeap(), 0, ret );
835 return NULL;
837 value.Buffer = new_ptr + (value.Buffer - ret);
838 value.MaximumLength = path_len;
839 ret = new_ptr;
841 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
842 return ret;
846 /******************************************************************
847 * load_library_as_datafile
849 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
851 static const WCHAR dotDLL[] = {'.','d','l','l',0};
853 WCHAR filenameW[MAX_PATH];
854 HANDLE hFile = INVALID_HANDLE_VALUE;
855 HANDLE mapping;
856 HMODULE module;
858 *hmod = 0;
860 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
861 filenameW, NULL ))
863 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
864 NULL, OPEN_EXISTING, 0, 0 );
866 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
868 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
869 CloseHandle( hFile );
870 if (!mapping) return FALSE;
872 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
873 CloseHandle( mapping );
874 if (!module) return FALSE;
876 /* make sure it's a valid PE file */
877 if (!RtlImageNtHeader(module))
879 UnmapViewOfFile( module );
880 return FALSE;
882 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
883 return TRUE;
887 /******************************************************************
888 * load_library
890 * Helper for LoadLibraryExA/W.
892 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
894 NTSTATUS nts;
895 HMODULE hModule;
896 WCHAR *load_path;
897 static const DWORD unsupported_flags =
898 LOAD_IGNORE_CODE_AUTHZ_LEVEL |
899 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
900 LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE |
901 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET |
902 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
903 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
904 LOAD_LIBRARY_SEARCH_USER_DIRS |
905 LOAD_LIBRARY_SEARCH_SYSTEM32 |
906 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS;
908 if( flags & unsupported_flags)
909 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
911 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
913 if (flags & LOAD_LIBRARY_AS_DATAFILE)
915 ULONG_PTR magic;
917 LdrLockLoaderLock( 0, NULL, &magic );
918 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
920 LdrAddRefDll( 0, hModule );
921 LdrUnlockLoaderLock( 0, magic );
922 goto done;
924 LdrUnlockLoaderLock( 0, magic );
926 /* The method in load_library_as_datafile allows searching for the
927 * 'native' libraries only
929 if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
930 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
931 /* Fallback to normal behaviour */
934 nts = LdrLoadDll( load_path, flags, libname, &hModule );
935 if (nts != STATUS_SUCCESS)
937 hModule = 0;
938 SetLastError( RtlNtStatusToDosError( nts ) );
940 done:
941 HeapFree( GetProcessHeap(), 0, load_path );
942 return hModule;
946 /******************************************************************
947 * LoadLibraryExA (KERNEL32.@)
949 * Load a dll file into the process address space.
951 * PARAMS
952 * libname [I] Name of the file to load
953 * hfile [I] Reserved, must be 0.
954 * flags [I] Flags for loading the dll
956 * RETURNS
957 * Success: A handle to the loaded dll.
958 * Failure: A NULL handle. Use GetLastError() to determine the cause.
960 * NOTES
961 * The HFILE parameter is not used and marked reserved in the SDK. I can
962 * only guess that it should force a file to be mapped, but I rather
963 * ignore the parameter because it would be extremely difficult to
964 * integrate this with different types of module representations.
966 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
968 WCHAR *libnameW;
970 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
971 return LoadLibraryExW( libnameW, hfile, flags );
974 /***********************************************************************
975 * LoadLibraryExW (KERNEL32.@)
977 * Unicode version of LoadLibraryExA.
979 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
981 UNICODE_STRING wstr;
982 HMODULE res;
984 if (!libnameW)
986 SetLastError(ERROR_INVALID_PARAMETER);
987 return 0;
989 RtlInitUnicodeString( &wstr, libnameW );
990 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
991 return load_library( &wstr, flags );
993 /* Library name has trailing spaces */
994 RtlCreateUnicodeString( &wstr, libnameW );
995 while (wstr.Length > sizeof(WCHAR) &&
996 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
998 wstr.Length -= sizeof(WCHAR);
1000 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1001 res = load_library( &wstr, flags );
1002 RtlFreeUnicodeString( &wstr );
1003 return res;
1006 /***********************************************************************
1007 * LoadLibraryA (KERNEL32.@)
1009 * Load a dll file into the process address space.
1011 * PARAMS
1012 * libname [I] Name of the file to load
1014 * RETURNS
1015 * Success: A handle to the loaded dll.
1016 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1018 * NOTES
1019 * See LoadLibraryExA().
1021 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1023 return LoadLibraryExA(libname, 0, 0);
1026 /***********************************************************************
1027 * LoadLibraryW (KERNEL32.@)
1029 * Unicode version of LoadLibraryA.
1031 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1033 return LoadLibraryExW(libnameW, 0, 0);
1036 /***********************************************************************
1037 * FreeLibrary (KERNEL32.@)
1039 * Free a dll loaded into the process address space.
1041 * PARAMS
1042 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1044 * RETURNS
1045 * Success: TRUE. The dll is removed if it is not still in use.
1046 * Failure: FALSE. Use GetLastError() to determine the cause.
1048 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1050 BOOL retv = FALSE;
1051 NTSTATUS nts;
1053 if (!hLibModule)
1055 SetLastError( ERROR_INVALID_HANDLE );
1056 return FALSE;
1059 if ((ULONG_PTR)hLibModule & 1)
1061 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1062 char *ptr = (char *)hLibModule - 1;
1063 return UnmapViewOfFile( ptr );
1066 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1067 else SetLastError( RtlNtStatusToDosError( nts ) );
1069 return retv;
1072 /***********************************************************************
1073 * GetProcAddress (KERNEL32.@)
1075 * Find the address of an exported symbol in a loaded dll.
1077 * PARAMS
1078 * hModule [I] Handle to the dll returned by LoadLibraryA().
1079 * function [I] Name of the symbol, or an integer ordinal number < 16384
1081 * RETURNS
1082 * Success: A pointer to the symbol in the process address space.
1083 * Failure: NULL. Use GetLastError() to determine the cause.
1085 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1087 NTSTATUS nts;
1088 FARPROC fp;
1090 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1092 if ((ULONG_PTR)function >> 16)
1094 ANSI_STRING str;
1096 RtlInitAnsiString( &str, function );
1097 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1099 else
1100 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1101 if (nts != STATUS_SUCCESS)
1103 SetLastError( RtlNtStatusToDosError( nts ) );
1104 fp = NULL;
1106 return fp;
1109 /***********************************************************************
1110 * DelayLoadFailureHook (KERNEL32.@)
1112 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1114 ULONG_PTR args[2];
1116 if ((ULONG_PTR)function >> 16)
1117 ERR( "failed to delay load %s.%s\n", name, function );
1118 else
1119 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1120 args[0] = (ULONG_PTR)name;
1121 args[1] = (ULONG_PTR)function;
1122 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1123 return NULL;
1126 typedef struct {
1127 HANDLE process;
1128 PLIST_ENTRY head, current;
1129 LDR_MODULE ldr_module;
1130 } MODULE_ITERATOR;
1132 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1134 PROCESS_BASIC_INFORMATION pbi;
1135 PPEB_LDR_DATA ldr_data;
1136 NTSTATUS status;
1138 /* Get address of PEB */
1139 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1140 &pbi, sizeof(pbi), NULL);
1141 if (status != STATUS_SUCCESS)
1143 SetLastError(RtlNtStatusToDosError(status));
1144 return FALSE;
1147 /* Read address of LdrData from PEB */
1148 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1149 &ldr_data, sizeof(ldr_data), NULL))
1150 return FALSE;
1152 /* Read address of first module from LdrData */
1153 if (!ReadProcessMemory(process,
1154 &ldr_data->InLoadOrderModuleList.Flink,
1155 &iter->current, sizeof(iter->current), NULL))
1156 return FALSE;
1158 iter->head = &ldr_data->InLoadOrderModuleList;
1159 iter->process = process;
1161 return TRUE;
1164 static int module_iterator_next(MODULE_ITERATOR *iter)
1166 if (iter->current == iter->head)
1167 return 0;
1169 if (!ReadProcessMemory(iter->process,
1170 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1171 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1172 return -1;
1174 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1175 return 1;
1178 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1180 MODULE_ITERATOR iter;
1181 INT ret;
1183 if (!init_module_iterator(&iter, process))
1184 return FALSE;
1186 while ((ret = module_iterator_next(&iter)) > 0)
1187 /* When hModule is NULL we return the process image - which will be
1188 * the first module since our iterator uses InLoadOrderModuleList */
1189 if (!module || module == iter.ldr_module.BaseAddress)
1191 *ldr_module = iter.ldr_module;
1192 return TRUE;
1195 if (ret == 0)
1196 SetLastError(ERROR_INVALID_HANDLE);
1198 return FALSE;
1201 /***********************************************************************
1202 * K32EnumProcessModules (KERNEL32.@)
1204 * NOTES
1205 * Returned list is in load order.
1207 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1208 DWORD cb, DWORD *needed)
1210 MODULE_ITERATOR iter;
1211 INT ret;
1213 if (!init_module_iterator(&iter, process))
1214 return FALSE;
1216 if (!needed)
1218 SetLastError(ERROR_NOACCESS);
1219 return FALSE;
1222 *needed = 0;
1224 while ((ret = module_iterator_next(&iter)) > 0)
1226 if (cb >= sizeof(HMODULE))
1228 *lphModule++ = iter.ldr_module.BaseAddress;
1229 cb -= sizeof(HMODULE);
1231 *needed += sizeof(HMODULE);
1234 return ret == 0;
1237 /***********************************************************************
1238 * K32GetModuleBaseNameW (KERNEL32.@)
1240 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1241 LPWSTR base_name, DWORD size)
1243 LDR_MODULE ldr_module;
1245 if (!get_ldr_module(process, module, &ldr_module))
1246 return 0;
1248 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1249 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1250 base_name, size * sizeof(WCHAR), NULL))
1251 return 0;
1253 base_name[size] = 0;
1254 return size;
1257 /***********************************************************************
1258 * K32GetModuleBaseNameA (KERNEL32.@)
1260 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1261 LPSTR base_name, DWORD size)
1263 WCHAR *base_name_w;
1264 DWORD len, ret = 0;
1266 if(!base_name || !size) {
1267 SetLastError(ERROR_INVALID_PARAMETER);
1268 return 0;
1271 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1272 if(!base_name_w)
1273 return 0;
1275 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1276 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1277 if (len)
1279 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1280 base_name, size, NULL, NULL);
1281 if (ret < size) base_name[ret] = 0;
1283 HeapFree(GetProcessHeap(), 0, base_name_w);
1284 return ret;
1287 /***********************************************************************
1288 * K32GetModuleFileNameExW (KERNEL32.@)
1290 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1291 LPWSTR file_name, DWORD size)
1293 LDR_MODULE ldr_module;
1294 DWORD len;
1296 if (!size) return 0;
1298 if(!get_ldr_module(process, module, &ldr_module))
1299 return 0;
1301 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1302 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1303 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1304 return 0;
1306 if (len < size)
1308 file_name[len] = 0;
1309 return len;
1311 else
1313 file_name[size - 1] = 0;
1314 return size;
1318 /***********************************************************************
1319 * K32GetModuleFileNameExA (KERNEL32.@)
1321 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1322 LPSTR file_name, DWORD size)
1324 WCHAR *ptr;
1325 DWORD len;
1327 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1329 if (!file_name || !size)
1331 SetLastError( ERROR_INVALID_PARAMETER );
1332 return 0;
1335 if ( process == GetCurrentProcess() )
1337 len = GetModuleFileNameA( module, file_name, size );
1338 if (size) file_name[size - 1] = '\0';
1339 return len;
1342 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1344 len = K32GetModuleFileNameExW(process, module, ptr, size);
1345 if (!len)
1347 file_name[0] = '\0';
1349 else
1351 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1353 file_name[size - 1] = 0;
1354 len = size;
1356 else if (len < size) len = strlen( file_name );
1359 HeapFree(GetProcessHeap(), 0, ptr);
1360 return len;
1363 /***********************************************************************
1364 * K32GetModuleInformation (KERNEL32.@)
1366 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1367 MODULEINFO *modinfo, DWORD cb)
1369 LDR_MODULE ldr_module;
1371 if (cb < sizeof(MODULEINFO))
1373 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1374 return FALSE;
1377 if (!get_ldr_module(process, module, &ldr_module))
1378 return FALSE;
1380 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1381 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1382 modinfo->EntryPoint = ldr_module.EntryPoint;
1383 return TRUE;
1386 #ifdef __i386__
1388 /***********************************************************************
1389 * __wine_dll_register_16 (KERNEL32.@)
1391 * No longer used.
1393 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1395 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1399 /***********************************************************************
1400 * __wine_dll_unregister_16 (KERNEL32.@)
1402 * No longer used.
1404 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1408 #endif