include: Move struct WSABUF and WSAMSG to ws2def.h.
[wine.git] / dlls / kernel32 / module.c
blob9913f1b5820ceec988673d8f7c7b0420d6add546
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 /* FIXME: we don't bother to check byte order, architecture, etc. */
268 switch(header.elf.type)
270 case 2: info->type = BINARY_UNIX_EXE; break;
271 case 3: info->type = BINARY_UNIX_LIB; break;
274 /* Mach-o File with Endian set to Big Endian or Little Endian */
275 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
277 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
278 switch(header.macho.filetype)
280 case 2: info->type = BINARY_UNIX_EXE; break;
281 case 8: info->type = BINARY_UNIX_LIB; break;
284 /* Not ELF, try DOS */
285 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
287 union
289 IMAGE_OS2_HEADER os2;
290 IMAGE_NT_HEADERS32 nt;
291 } ext_header;
293 /* We do have a DOS image so we will now try to seek into
294 * the file by the amount indicated by the field
295 * "Offset to extended header" and read in the
296 * "magic" field information at that location.
297 * This will tell us if there is more header information
298 * to read or not.
300 info->type = BINARY_DOS;
301 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
302 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
304 /* Reading the magic field succeeded so
305 * we will try to determine what type it is.
307 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
309 if (len >= sizeof(ext_header.nt.FileHeader))
311 info->type = BINARY_PE;
312 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
313 info->flags |= BINARY_FLAG_DLL;
314 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
315 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
316 switch (ext_header.nt.OptionalHeader.Magic)
318 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
319 info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
320 info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
321 ext_header.nt.OptionalHeader.SizeOfImage);
322 break;
323 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
324 info->flags |= BINARY_FLAG_64BIT;
325 break;
329 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
331 /* This is a Windows executable (NE) header. This can
332 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
333 * DOS program (running under a DOS extender). To decide
334 * which, we'll have to read the NE header.
336 if (len >= sizeof(ext_header.os2))
338 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
339 switch ( ext_header.os2.ne_exetyp )
341 case 1: info->type = BINARY_OS216; break; /* OS/2 */
342 case 2: info->type = BINARY_WIN16; break; /* Windows */
343 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
344 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
345 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
346 /* other types, e.g. 0 is: "unknown" */
347 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
354 /***********************************************************************
355 * GetBinaryTypeW [KERNEL32.@]
357 * Determine whether a file is executable, and if so, what kind.
359 * PARAMS
360 * lpApplicationName [I] Path of the file to check
361 * lpBinaryType [O] Destination for the binary type
363 * RETURNS
364 * TRUE, if the file is an executable, in which case lpBinaryType is set.
365 * FALSE, if the file is not an executable or if the function fails.
367 * NOTES
368 * The type of executable is a property that determines which subsystem an
369 * executable file runs under. lpBinaryType can be set to one of the following
370 * values:
371 * SCS_32BIT_BINARY: A Win32 based application
372 * SCS_64BIT_BINARY: A Win64 based application
373 * SCS_DOS_BINARY: An MS-Dos based application
374 * SCS_WOW_BINARY: A Win16 based application
375 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
376 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
377 * SCS_OS216_BINARY: A 16bit OS/2 based application
379 * To find the binary type, this function reads in the files header information.
380 * If extended header information is not present it will assume that the file
381 * is a DOS executable. If extended header information is present it will
382 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
383 * flags in the header.
385 * ".com" and ".pif" files are only recognized by their file name extension,
386 * as per native Windows.
388 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
390 BOOL ret = FALSE;
391 HANDLE hfile;
392 struct binary_info binary_info;
394 TRACE("%s\n", debugstr_w(lpApplicationName) );
396 /* Sanity check.
398 if ( lpApplicationName == NULL || lpBinaryType == NULL )
399 return FALSE;
401 /* Open the file indicated by lpApplicationName for reading.
403 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
404 NULL, OPEN_EXISTING, 0, 0 );
405 if ( hfile == INVALID_HANDLE_VALUE )
406 return FALSE;
408 /* Check binary type
410 MODULE_get_binary_info( hfile, &binary_info );
411 switch (binary_info.type)
413 case BINARY_UNKNOWN:
415 static const WCHAR comW[] = { '.','C','O','M',0 };
416 static const WCHAR pifW[] = { '.','P','I','F',0 };
417 const WCHAR *ptr;
419 /* try to determine from file name */
420 ptr = strrchrW( lpApplicationName, '.' );
421 if (!ptr) break;
422 if (!strcmpiW( ptr, comW ))
424 *lpBinaryType = SCS_DOS_BINARY;
425 ret = TRUE;
427 else if (!strcmpiW( ptr, pifW ))
429 *lpBinaryType = SCS_PIF_BINARY;
430 ret = TRUE;
432 break;
434 case BINARY_PE:
435 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
436 ret = TRUE;
437 break;
438 case BINARY_WIN16:
439 *lpBinaryType = SCS_WOW_BINARY;
440 ret = TRUE;
441 break;
442 case BINARY_OS216:
443 *lpBinaryType = SCS_OS216_BINARY;
444 ret = TRUE;
445 break;
446 case BINARY_DOS:
447 *lpBinaryType = SCS_DOS_BINARY;
448 ret = TRUE;
449 break;
450 case BINARY_UNIX_EXE:
451 case BINARY_UNIX_LIB:
452 ret = FALSE;
453 break;
456 CloseHandle( hfile );
457 return ret;
460 /***********************************************************************
461 * GetBinaryTypeA [KERNEL32.@]
462 * GetBinaryType [KERNEL32.@]
464 * See GetBinaryTypeW.
466 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
468 ANSI_STRING app_nameA;
469 NTSTATUS status;
471 TRACE("%s\n", debugstr_a(lpApplicationName));
473 /* Sanity check.
475 if ( lpApplicationName == NULL || lpBinaryType == NULL )
476 return FALSE;
478 RtlInitAnsiString(&app_nameA, lpApplicationName);
479 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
480 &app_nameA, FALSE);
481 if (!status)
482 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
484 SetLastError(RtlNtStatusToDosError(status));
485 return FALSE;
488 /***********************************************************************
489 * GetModuleHandleExA (KERNEL32.@)
491 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
493 WCHAR *nameW;
495 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
496 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
498 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
499 return GetModuleHandleExW( flags, nameW, module );
502 /***********************************************************************
503 * GetModuleHandleExW (KERNEL32.@)
505 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
507 NTSTATUS status = STATUS_SUCCESS;
508 HMODULE ret;
509 ULONG magic;
511 if (!module)
513 SetLastError( ERROR_INVALID_PARAMETER );
514 return FALSE;
517 /* if we are messing with the refcount, grab the loader lock */
518 if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
519 !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
520 LdrLockLoaderLock( 0, NULL, &magic );
522 if (!name)
524 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
526 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
528 void *dummy;
529 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
531 else
533 UNICODE_STRING wstr;
534 RtlInitUnicodeString( &wstr, name );
535 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
538 if (status == STATUS_SUCCESS)
540 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
541 FIXME( "should pin refcount for %p\n", ret );
542 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
543 LdrAddRefDll( 0, ret );
545 else SetLastError( RtlNtStatusToDosError( status ) );
547 if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
548 !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
549 LdrUnlockLoaderLock( 0, magic );
551 if (status == STATUS_SUCCESS) *module = ret;
552 else *module = NULL;
554 return (status == STATUS_SUCCESS);
557 /***********************************************************************
558 * GetModuleHandleA (KERNEL32.@)
560 * Get the handle of a dll loaded into the process address space.
562 * PARAMS
563 * module [I] Name of the dll
565 * RETURNS
566 * Success: A handle to the loaded dll.
567 * Failure: A NULL handle. Use GetLastError() to determine the cause.
569 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
571 HMODULE ret;
573 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
574 return ret;
577 /***********************************************************************
578 * GetModuleHandleW (KERNEL32.@)
580 * Unicode version of GetModuleHandleA.
582 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
584 HMODULE ret;
586 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
587 return ret;
591 /***********************************************************************
592 * GetModuleFileNameA (KERNEL32.@)
594 * Get the file name of a loaded module from its handle.
596 * RETURNS
597 * Success: The length of the file name, excluding the terminating NUL.
598 * Failure: 0. Use GetLastError() to determine the cause.
600 * NOTES
601 * This function always returns the long path of hModule
602 * The function doesn't write a terminating '\0' if the buffer is too
603 * small.
605 DWORD WINAPI GetModuleFileNameA(
606 HMODULE hModule, /* [in] Module handle (32 bit) */
607 LPSTR lpFileName, /* [out] Destination for file name */
608 DWORD size ) /* [in] Size of lpFileName in characters */
610 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
611 DWORD len;
613 if (!filenameW)
615 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
616 return 0;
618 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
620 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
621 if (len < size)
622 lpFileName[len] = '\0';
623 else
624 SetLastError( ERROR_INSUFFICIENT_BUFFER );
626 HeapFree( GetProcessHeap(), 0, filenameW );
627 return len;
630 /***********************************************************************
631 * GetModuleFileNameW (KERNEL32.@)
633 * Unicode version of GetModuleFileNameA.
635 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
637 ULONG magic, len = 0;
638 LDR_MODULE *pldr;
639 NTSTATUS nts;
640 WIN16_SUBSYSTEM_TIB *win16_tib;
642 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
644 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
645 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
646 if (len < size) lpFileName[len] = '\0';
647 goto done;
650 LdrLockLoaderLock( 0, NULL, &magic );
652 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
653 nts = LdrFindEntryForAddress( hModule, &pldr );
654 if (nts == STATUS_SUCCESS)
656 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
657 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
658 if (len < size)
660 lpFileName[len] = '\0';
661 SetLastError( 0 );
663 else
664 SetLastError( ERROR_INSUFFICIENT_BUFFER );
666 else SetLastError( RtlNtStatusToDosError( nts ) );
668 LdrUnlockLoaderLock( 0, magic );
669 done:
670 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
671 return len;
675 /***********************************************************************
676 * get_dll_system_path
678 static const WCHAR *get_dll_system_path(void)
680 static WCHAR *cached_path;
682 if (!cached_path)
684 WCHAR *p, *path;
685 int len = 3;
687 len += 2 * GetSystemDirectoryW( NULL, 0 );
688 len += GetWindowsDirectoryW( NULL, 0 );
689 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
690 *p++ = '.';
691 *p++ = ';';
692 GetSystemDirectoryW( p, path + len - p);
693 p += strlenW(p);
694 /* if system directory ends in "32" add 16-bit version too */
695 if (p[-2] == '3' && p[-1] == '2')
697 *p++ = ';';
698 GetSystemDirectoryW( p, path + len - p);
699 p += strlenW(p) - 2;
701 *p++ = ';';
702 GetWindowsDirectoryW( p, path + len - p);
703 cached_path = path;
705 return cached_path;
708 /******************************************************************
709 * get_module_path_end
711 * Returns the end of the directory component of the module path.
713 static inline const WCHAR *get_module_path_end(const WCHAR *module)
715 const WCHAR *p;
716 const WCHAR *mod_end = module;
717 if (!module) return mod_end;
719 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
720 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
721 if (mod_end == module + 2 && module[1] == ':') mod_end++;
722 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
724 return mod_end;
727 /******************************************************************
728 * MODULE_get_dll_load_path
730 * Compute the load path to use for a given dll.
731 * Returned pointer must be freed by caller.
733 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
735 static const WCHAR pathW[] = {'P','A','T','H',0};
737 const WCHAR *system_path = get_dll_system_path();
738 const WCHAR *mod_end = NULL;
739 UNICODE_STRING name, value;
740 WCHAR *p, *ret;
741 int len = 0, path_len = 0;
743 /* adjust length for module name */
745 if (module)
746 mod_end = get_module_path_end( module );
747 /* if module is NULL or doesn't contain a path, fall back to directory
748 * process was loaded from */
749 if (module == mod_end)
751 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
752 mod_end = get_module_path_end( module );
754 len += (mod_end - module) + 1;
756 len += strlenW( system_path ) + 2;
758 /* get the PATH variable */
760 RtlInitUnicodeString( &name, pathW );
761 value.Length = 0;
762 value.MaximumLength = 0;
763 value.Buffer = NULL;
764 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
765 path_len = value.Length;
767 RtlEnterCriticalSection( &dlldir_section );
768 if (dll_directory) len += strlenW(dll_directory) + 1;
769 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
771 if (module)
773 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
774 p += (mod_end - module);
775 *p++ = ';';
777 if (dll_directory)
779 strcpyW( p, dll_directory );
780 p += strlenW(p);
781 *p++ = ';';
784 RtlLeaveCriticalSection( &dlldir_section );
785 if (!ret) return NULL;
787 strcpyW( p, system_path );
788 p += strlenW(p);
789 *p++ = ';';
790 value.Buffer = p;
791 value.MaximumLength = path_len;
793 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
795 WCHAR *new_ptr;
797 /* grow the buffer and retry */
798 path_len = value.Length;
799 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
801 HeapFree( GetProcessHeap(), 0, ret );
802 return NULL;
804 value.Buffer = new_ptr + (value.Buffer - ret);
805 value.MaximumLength = path_len;
806 ret = new_ptr;
808 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
809 return ret;
813 /******************************************************************
814 * load_library_as_datafile
816 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
818 static const WCHAR dotDLL[] = {'.','d','l','l',0};
820 WCHAR filenameW[MAX_PATH];
821 HANDLE hFile = INVALID_HANDLE_VALUE;
822 HANDLE mapping;
823 HMODULE module;
825 *hmod = 0;
827 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
828 filenameW, NULL ))
830 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
831 NULL, OPEN_EXISTING, 0, 0 );
833 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
835 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
836 CloseHandle( hFile );
837 if (!mapping) return FALSE;
839 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
840 CloseHandle( mapping );
841 if (!module) return FALSE;
843 /* make sure it's a valid PE file */
844 if (!RtlImageNtHeader(module))
846 UnmapViewOfFile( module );
847 return FALSE;
849 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
850 return TRUE;
854 /******************************************************************
855 * load_library
857 * Helper for LoadLibraryExA/W.
859 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
861 NTSTATUS nts;
862 HMODULE hModule;
863 WCHAR *load_path;
864 static const DWORD unsupported_flags =
865 LOAD_IGNORE_CODE_AUTHZ_LEVEL |
866 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
867 LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE |
868 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET;
870 if( flags & unsupported_flags)
871 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
873 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
875 if (flags & LOAD_LIBRARY_AS_DATAFILE)
877 ULONG magic;
879 LdrLockLoaderLock( 0, NULL, &magic );
880 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
882 LdrAddRefDll( 0, hModule );
883 LdrUnlockLoaderLock( 0, magic );
884 goto done;
886 LdrUnlockLoaderLock( 0, magic );
888 /* The method in load_library_as_datafile allows searching for the
889 * 'native' libraries only
891 if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
892 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
893 /* Fallback to normal behaviour */
896 nts = LdrLoadDll( load_path, flags, libname, &hModule );
897 if (nts != STATUS_SUCCESS)
899 hModule = 0;
900 SetLastError( RtlNtStatusToDosError( nts ) );
902 done:
903 HeapFree( GetProcessHeap(), 0, load_path );
904 return hModule;
908 /******************************************************************
909 * LoadLibraryExA (KERNEL32.@)
911 * Load a dll file into the process address space.
913 * PARAMS
914 * libname [I] Name of the file to load
915 * hfile [I] Reserved, must be 0.
916 * flags [I] Flags for loading the dll
918 * RETURNS
919 * Success: A handle to the loaded dll.
920 * Failure: A NULL handle. Use GetLastError() to determine the cause.
922 * NOTES
923 * The HFILE parameter is not used and marked reserved in the SDK. I can
924 * only guess that it should force a file to be mapped, but I rather
925 * ignore the parameter because it would be extremely difficult to
926 * integrate this with different types of module representations.
928 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
930 WCHAR *libnameW;
932 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
933 return LoadLibraryExW( libnameW, hfile, flags );
936 /***********************************************************************
937 * LoadLibraryExW (KERNEL32.@)
939 * Unicode version of LoadLibraryExA.
941 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
943 UNICODE_STRING wstr;
944 HMODULE res;
946 if (!libnameW)
948 SetLastError(ERROR_INVALID_PARAMETER);
949 return 0;
951 RtlInitUnicodeString( &wstr, libnameW );
952 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
953 return load_library( &wstr, flags );
955 /* Library name has trailing spaces */
956 RtlCreateUnicodeString( &wstr, libnameW );
957 while (wstr.Length > sizeof(WCHAR) &&
958 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
960 wstr.Length -= sizeof(WCHAR);
962 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
963 res = load_library( &wstr, flags );
964 RtlFreeUnicodeString( &wstr );
965 return res;
968 /***********************************************************************
969 * LoadLibraryA (KERNEL32.@)
971 * Load a dll file into the process address space.
973 * PARAMS
974 * libname [I] Name of the file to load
976 * RETURNS
977 * Success: A handle to the loaded dll.
978 * Failure: A NULL handle. Use GetLastError() to determine the cause.
980 * NOTES
981 * See LoadLibraryExA().
983 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
985 return LoadLibraryExA(libname, 0, 0);
988 /***********************************************************************
989 * LoadLibraryW (KERNEL32.@)
991 * Unicode version of LoadLibraryA.
993 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
995 return LoadLibraryExW(libnameW, 0, 0);
998 /***********************************************************************
999 * FreeLibrary (KERNEL32.@)
1001 * Free a dll loaded into the process address space.
1003 * PARAMS
1004 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1006 * RETURNS
1007 * Success: TRUE. The dll is removed if it is not still in use.
1008 * Failure: FALSE. Use GetLastError() to determine the cause.
1010 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1012 BOOL retv = FALSE;
1013 NTSTATUS nts;
1015 if (!hLibModule)
1017 SetLastError( ERROR_INVALID_HANDLE );
1018 return FALSE;
1021 if ((ULONG_PTR)hLibModule & 1)
1023 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1024 char *ptr = (char *)hLibModule - 1;
1025 return UnmapViewOfFile( ptr );
1028 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1029 else SetLastError( RtlNtStatusToDosError( nts ) );
1031 return retv;
1034 /***********************************************************************
1035 * GetProcAddress (KERNEL32.@)
1037 * Find the address of an exported symbol in a loaded dll.
1039 * PARAMS
1040 * hModule [I] Handle to the dll returned by LoadLibraryA().
1041 * function [I] Name of the symbol, or an integer ordinal number < 16384
1043 * RETURNS
1044 * Success: A pointer to the symbol in the process address space.
1045 * Failure: NULL. Use GetLastError() to determine the cause.
1047 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1049 NTSTATUS nts;
1050 FARPROC fp;
1052 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1054 if ((ULONG_PTR)function >> 16)
1056 ANSI_STRING str;
1058 RtlInitAnsiString( &str, function );
1059 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1061 else
1062 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1063 if (nts != STATUS_SUCCESS)
1065 SetLastError( RtlNtStatusToDosError( nts ) );
1066 fp = NULL;
1068 return fp;
1071 /***********************************************************************
1072 * DelayLoadFailureHook (KERNEL32.@)
1074 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1076 ULONG_PTR args[2];
1078 if ((ULONG_PTR)function >> 16)
1079 ERR( "failed to delay load %s.%s\n", name, function );
1080 else
1081 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1082 args[0] = (ULONG_PTR)name;
1083 args[1] = (ULONG_PTR)function;
1084 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1085 return NULL;
1088 typedef struct {
1089 HANDLE process;
1090 PLIST_ENTRY head, current;
1091 LDR_MODULE ldr_module;
1092 } MODULE_ITERATOR;
1094 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1096 PROCESS_BASIC_INFORMATION pbi;
1097 PPEB_LDR_DATA ldr_data;
1098 NTSTATUS status;
1100 /* Get address of PEB */
1101 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1102 &pbi, sizeof(pbi), NULL);
1103 if (status != STATUS_SUCCESS)
1105 SetLastError(RtlNtStatusToDosError(status));
1106 return FALSE;
1109 /* Read address of LdrData from PEB */
1110 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1111 &ldr_data, sizeof(ldr_data), NULL))
1112 return FALSE;
1114 /* Read address of first module from LdrData */
1115 if (!ReadProcessMemory(process,
1116 &ldr_data->InLoadOrderModuleList.Flink,
1117 &iter->current, sizeof(iter->current), NULL))
1118 return FALSE;
1120 iter->head = &ldr_data->InLoadOrderModuleList;
1121 iter->process = process;
1123 return TRUE;
1126 static int module_iterator_next(MODULE_ITERATOR *iter)
1128 if (iter->current == iter->head)
1129 return 0;
1131 if (!ReadProcessMemory(iter->process,
1132 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1133 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1134 return -1;
1136 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1137 return 1;
1140 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1142 MODULE_ITERATOR iter;
1143 INT ret;
1145 if (!init_module_iterator(&iter, process))
1146 return FALSE;
1148 while ((ret = module_iterator_next(&iter)) > 0)
1149 /* When hModule is NULL we return the process image - which will be
1150 * the first module since our iterator uses InLoadOrderModuleList */
1151 if (!module || module == iter.ldr_module.BaseAddress)
1153 *ldr_module = iter.ldr_module;
1154 return TRUE;
1157 if (ret == 0)
1158 SetLastError(ERROR_INVALID_HANDLE);
1160 return FALSE;
1163 /***********************************************************************
1164 * K32EnumProcessModules (KERNEL32.@)
1166 * NOTES
1167 * Returned list is in load order.
1169 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1170 DWORD cb, DWORD *needed)
1172 MODULE_ITERATOR iter;
1173 INT ret;
1175 if (!init_module_iterator(&iter, process))
1176 return FALSE;
1178 if (!needed)
1180 SetLastError(ERROR_NOACCESS);
1181 return FALSE;
1184 *needed = 0;
1186 while ((ret = module_iterator_next(&iter)) > 0)
1188 if (cb >= sizeof(HMODULE))
1190 *lphModule++ = iter.ldr_module.BaseAddress;
1191 cb -= sizeof(HMODULE);
1193 *needed += sizeof(HMODULE);
1196 return ret == 0;
1199 /***********************************************************************
1200 * K32GetModuleBaseNameW (KERNEL32.@)
1202 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1203 LPWSTR base_name, DWORD size)
1205 LDR_MODULE ldr_module;
1207 if (!get_ldr_module(process, module, &ldr_module))
1208 return 0;
1210 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1211 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1212 base_name, size * sizeof(WCHAR), NULL))
1213 return 0;
1215 base_name[size] = 0;
1216 return size;
1219 /***********************************************************************
1220 * K32GetModuleBaseNameA (KERNEL32.@)
1222 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1223 LPSTR base_name, DWORD size)
1225 WCHAR *base_name_w;
1226 DWORD len, ret = 0;
1228 if(!base_name || !size) {
1229 SetLastError(ERROR_INVALID_PARAMETER);
1230 return 0;
1233 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1234 if(!base_name_w)
1235 return 0;
1237 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1238 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1239 if (len)
1241 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1242 base_name, size, NULL, NULL);
1243 if (ret < size) base_name[ret] = 0;
1245 HeapFree(GetProcessHeap(), 0, base_name_w);
1246 return ret;
1249 /***********************************************************************
1250 * K32GetModuleFileNameExW (KERNEL32.@)
1252 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1253 LPWSTR file_name, DWORD size)
1255 LDR_MODULE ldr_module;
1256 DWORD len;
1258 if (!size) return 0;
1260 if(!get_ldr_module(process, module, &ldr_module))
1261 return 0;
1263 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1264 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1265 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1266 return 0;
1268 if (len < size)
1270 file_name[len] = 0;
1271 return len;
1273 else
1275 file_name[size - 1] = 0;
1276 return size;
1280 /***********************************************************************
1281 * K32GetModuleFileNameExA (KERNEL32.@)
1283 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1284 LPSTR file_name, DWORD size)
1286 WCHAR *ptr;
1287 DWORD len;
1289 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1291 if (!file_name || !size)
1293 SetLastError( ERROR_INVALID_PARAMETER );
1294 return 0;
1297 if ( process == GetCurrentProcess() )
1299 len = GetModuleFileNameA( module, file_name, size );
1300 if (size) file_name[size - 1] = '\0';
1301 return len;
1304 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1306 len = K32GetModuleFileNameExW(process, module, ptr, size);
1307 if (!len)
1309 file_name[0] = '\0';
1311 else
1313 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1315 file_name[size - 1] = 0;
1316 len = size;
1318 else if (len < size) len = strlen( file_name );
1321 HeapFree(GetProcessHeap(), 0, ptr);
1322 return len;
1325 /***********************************************************************
1326 * K32GetModuleInformation (KERNEL32.@)
1328 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1329 MODULEINFO *modinfo, DWORD cb)
1331 LDR_MODULE ldr_module;
1333 if (cb < sizeof(MODULEINFO))
1335 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1336 return FALSE;
1339 if (!get_ldr_module(process, module, &ldr_module))
1340 return FALSE;
1342 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1343 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1344 modinfo->EntryPoint = ldr_module.EntryPoint;
1345 return TRUE;
1348 #ifdef __i386__
1350 /***********************************************************************
1351 * __wine_dll_register_16 (KERNEL32.@)
1353 * No longer used.
1355 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1357 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1361 /***********************************************************************
1362 * __wine_dll_unregister_16 (KERNEL32.@)
1364 * No longer used.
1366 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1370 #endif