kernel32: Add helper functions for building the load path.
[wine.git] / dlls / kernel32 / module.c
blob30f33a6140c6805d0c37c1b3199aa2439443d8bf
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/list.h"
44 #include "wine/debug.h"
45 #include "wine/unicode.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 #define NE_FFLAGS_LIBMODULE 0x8000
51 struct dll_dir_entry
53 struct list entry;
54 WCHAR dir[1];
57 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from AddDllDirectory */
58 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
59 static DWORD default_search_flags; /* default flags set by SetDefaultDllDirectories */
61 static CRITICAL_SECTION dlldir_section;
62 static CRITICAL_SECTION_DEBUG critsect_debug =
64 0, 0, &dlldir_section,
65 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
66 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
68 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
70 static const DWORD load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
71 LOAD_LIBRARY_SEARCH_USER_DIRS |
72 LOAD_LIBRARY_SEARCH_SYSTEM32 |
73 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
75 /****************************************************************************
76 * GetDllDirectoryA (KERNEL32.@)
78 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
80 DWORD len;
82 RtlEnterCriticalSection( &dlldir_section );
83 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
84 if (buffer && buf_len > len)
86 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
87 else *buffer = 0;
89 else
91 len++; /* for terminating null */
92 if (buffer) *buffer = 0;
94 RtlLeaveCriticalSection( &dlldir_section );
95 return len;
99 /****************************************************************************
100 * GetDllDirectoryW (KERNEL32.@)
102 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
104 DWORD len;
106 RtlEnterCriticalSection( &dlldir_section );
107 len = dll_directory ? strlenW( dll_directory ) : 0;
108 if (buffer && buf_len > len)
110 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
111 else *buffer = 0;
113 else
115 len++; /* for terminating null */
116 if (buffer) *buffer = 0;
118 RtlLeaveCriticalSection( &dlldir_section );
119 return len;
123 /****************************************************************************
124 * SetDllDirectoryA (KERNEL32.@)
126 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
128 WCHAR *dirW;
129 BOOL ret;
131 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
132 ret = SetDllDirectoryW( dirW );
133 HeapFree( GetProcessHeap(), 0, dirW );
134 return ret;
138 /****************************************************************************
139 * SetDllDirectoryW (KERNEL32.@)
141 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
143 WCHAR *newdir = NULL;
145 if (dir)
147 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
148 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
150 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
151 return FALSE;
153 memcpy( newdir, dir, len );
156 RtlEnterCriticalSection( &dlldir_section );
157 HeapFree( GetProcessHeap(), 0, dll_directory );
158 dll_directory = newdir;
159 RtlLeaveCriticalSection( &dlldir_section );
160 return TRUE;
164 /****************************************************************************
165 * AddDllDirectory (KERNEL32.@)
167 DLL_DIRECTORY_COOKIE WINAPI AddDllDirectory( const WCHAR *dir )
169 WCHAR path[MAX_PATH];
170 DWORD len;
171 struct dll_dir_entry *ptr;
172 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir );
174 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
176 SetLastError( ERROR_INVALID_PARAMETER );
177 return NULL;
179 if (!(len = GetFullPathNameW( dir, MAX_PATH, path, NULL ))) return NULL;
180 if (GetFileAttributesW( path ) == INVALID_FILE_ATTRIBUTES) return NULL;
182 if (!(ptr = HeapAlloc( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] )))) return NULL;
183 memcpy( ptr->dir, path, len * sizeof(WCHAR) );
184 TRACE( "%s\n", debugstr_w( ptr->dir ));
186 RtlEnterCriticalSection( &dlldir_section );
187 list_add_head( &dll_dir_list, &ptr->entry );
188 RtlLeaveCriticalSection( &dlldir_section );
189 return ptr;
193 /****************************************************************************
194 * RemoveDllDirectory (KERNEL32.@)
196 BOOL WINAPI RemoveDllDirectory( DLL_DIRECTORY_COOKIE cookie )
198 struct dll_dir_entry *ptr = cookie;
200 TRACE( "%s\n", debugstr_w( ptr->dir ));
202 RtlEnterCriticalSection( &dlldir_section );
203 list_remove( &ptr->entry );
204 HeapFree( GetProcessHeap(), 0, ptr );
205 RtlLeaveCriticalSection( &dlldir_section );
206 return TRUE;
210 /*************************************************************************
211 * SetDefaultDllDirectories (KERNEL32.@)
213 BOOL WINAPI SetDefaultDllDirectories( DWORD flags )
215 if (!flags || (flags & ~load_library_search_flags))
217 SetLastError( ERROR_INVALID_PARAMETER );
218 return FALSE;
220 default_search_flags = flags;
221 return TRUE;
225 /****************************************************************************
226 * DisableThreadLibraryCalls (KERNEL32.@)
228 * Inform the module loader that thread notifications are not required for a dll.
230 * PARAMS
231 * hModule [I] Module handle to skip calls for
233 * RETURNS
234 * Success: TRUE. Thread attach and detach notifications will not be sent
235 * to hModule.
236 * Failure: FALSE. Use GetLastError() to determine the cause.
238 * NOTES
239 * This is typically called from the dll entry point of a dll during process
240 * attachment, for dlls that do not need to process thread notifications.
242 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
244 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
245 if (nts == STATUS_SUCCESS) return TRUE;
247 SetLastError( RtlNtStatusToDosError( nts ) );
248 return FALSE;
252 /* Check whether a file is an OS/2 or a very old Windows executable
253 * by testing on import of KERNEL.
255 * FIXME: is reading the module imports the only way of discerning
256 * old Windows binaries from OS/2 ones ? At least it seems so...
258 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
260 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
261 DWORD ret = BINARY_OS216;
262 LPWORD modtab = NULL;
263 LPSTR nametab = NULL;
264 DWORD len;
265 int i;
267 /* read modref table */
268 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
269 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
270 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
271 || (len != ne->ne_cmod*sizeof(WORD)) )
272 goto broken;
274 /* read imported names table */
275 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
276 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
277 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
278 || (len != ne->ne_enttab - ne->ne_imptab) )
279 goto broken;
281 for (i=0; i < ne->ne_cmod; i++)
283 LPSTR module = &nametab[modtab[i]];
284 TRACE("modref: %.*s\n", module[0], &module[1]);
285 if (!(strncmp(&module[1], "KERNEL", module[0])))
286 { /* very old Windows file */
287 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
288 ret = BINARY_WIN16;
289 goto good;
293 broken:
294 ERR("Hmm, an error occurred. Is this binary file broken?\n");
296 good:
297 HeapFree( GetProcessHeap(), 0, modtab);
298 HeapFree( GetProcessHeap(), 0, nametab);
299 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
300 return ret;
303 /***********************************************************************
304 * MODULE_GetBinaryType
306 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
308 union
310 struct
312 unsigned char magic[4];
313 unsigned char class;
314 unsigned char data;
315 unsigned char version;
316 unsigned char ignored[9];
317 unsigned short type;
318 unsigned short machine;
319 } elf;
320 struct
322 unsigned int magic;
323 unsigned int cputype;
324 unsigned int cpusubtype;
325 unsigned int filetype;
326 } macho;
327 IMAGE_DOS_HEADER mz;
328 } header;
330 DWORD len;
332 memset( info, 0, sizeof(*info) );
334 /* Seek to the start of the file and read the header information. */
335 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
336 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
338 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
340 if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
341 #ifdef WORDS_BIGENDIAN
342 if (header.elf.data == 1)
343 #else
344 if (header.elf.data == 2)
345 #endif
347 header.elf.type = RtlUshortByteSwap( header.elf.type );
348 header.elf.machine = RtlUshortByteSwap( header.elf.machine );
350 switch(header.elf.type)
352 case 2: info->type = BINARY_UNIX_EXE; break;
353 case 3: info->type = BINARY_UNIX_LIB; break;
355 switch(header.elf.machine)
357 case 3: info->arch = IMAGE_FILE_MACHINE_I386; break;
358 case 20: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
359 case 40: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
360 case 50: info->arch = IMAGE_FILE_MACHINE_IA64; break;
361 case 62: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
362 case 183: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
365 /* Mach-o File with Endian set to Big Endian or Little Endian */
366 else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe ||
367 header.macho.magic == 0xfeedfacf || header.macho.magic == 0xcffaedfe)
369 if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
370 if (header.macho.magic == 0xcefaedfe || header.macho.magic == 0xcffaedfe)
372 header.macho.filetype = RtlUlongByteSwap( header.macho.filetype );
373 header.macho.cputype = RtlUlongByteSwap( header.macho.cputype );
375 switch(header.macho.filetype)
377 case 2: info->type = BINARY_UNIX_EXE; break;
378 case 8: info->type = BINARY_UNIX_LIB; break;
380 switch(header.macho.cputype)
382 case 0x00000007: info->arch = IMAGE_FILE_MACHINE_I386; break;
383 case 0x01000007: info->arch = IMAGE_FILE_MACHINE_AMD64; break;
384 case 0x0000000c: info->arch = IMAGE_FILE_MACHINE_ARMNT; break;
385 case 0x0100000c: info->arch = IMAGE_FILE_MACHINE_ARM64; break;
386 case 0x00000012: info->arch = IMAGE_FILE_MACHINE_POWERPC; break;
389 /* Not ELF, try DOS */
390 else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
392 union
394 IMAGE_OS2_HEADER os2;
395 IMAGE_NT_HEADERS32 nt;
396 } ext_header;
398 /* We do have a DOS image so we will now try to seek into
399 * the file by the amount indicated by the field
400 * "Offset to extended header" and read in the
401 * "magic" field information at that location.
402 * This will tell us if there is more header information
403 * to read or not.
405 info->type = BINARY_DOS;
406 info->arch = IMAGE_FILE_MACHINE_I386;
407 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
408 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
410 /* Reading the magic field succeeded so
411 * we will try to determine what type it is.
413 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
415 if (len >= sizeof(ext_header.nt.FileHeader))
417 static const char fakedll_signature[] = "Wine placeholder DLL";
418 char buffer[sizeof(fakedll_signature)];
420 info->type = BINARY_PE;
421 info->arch = ext_header.nt.FileHeader.Machine;
422 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
423 info->flags |= BINARY_FLAG_DLL;
424 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
425 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
426 switch (ext_header.nt.OptionalHeader.Magic)
428 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
429 info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
430 info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
431 ext_header.nt.OptionalHeader.SizeOfImage);
432 break;
433 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
434 info->flags |= BINARY_FLAG_64BIT;
435 break;
438 if (header.mz.e_lfanew >= sizeof(header.mz) + sizeof(fakedll_signature) &&
439 SetFilePointer( hfile, sizeof(header.mz), NULL, SEEK_SET ) == sizeof(header.mz) &&
440 ReadFile( hfile, buffer, sizeof(fakedll_signature), &len, NULL ) &&
441 len == sizeof(fakedll_signature) &&
442 !memcmp( buffer, fakedll_signature, sizeof(fakedll_signature) ))
444 info->flags |= BINARY_FLAG_FAKEDLL;
448 else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
450 /* This is a Windows executable (NE) header. This can
451 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
452 * DOS program (running under a DOS extender). To decide
453 * which, we'll have to read the NE header.
455 if (len >= sizeof(ext_header.os2))
457 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
458 switch ( ext_header.os2.ne_exetyp )
460 case 1: info->type = BINARY_OS216; break; /* OS/2 */
461 case 2: info->type = BINARY_WIN16; break; /* Windows */
462 case 3: info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
463 case 4: info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
464 case 5: info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
465 /* other types, e.g. 0 is: "unknown" */
466 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
473 /***********************************************************************
474 * GetBinaryTypeW [KERNEL32.@]
476 * Determine whether a file is executable, and if so, what kind.
478 * PARAMS
479 * lpApplicationName [I] Path of the file to check
480 * lpBinaryType [O] Destination for the binary type
482 * RETURNS
483 * TRUE, if the file is an executable, in which case lpBinaryType is set.
484 * FALSE, if the file is not an executable or if the function fails.
486 * NOTES
487 * The type of executable is a property that determines which subsystem an
488 * executable file runs under. lpBinaryType can be set to one of the following
489 * values:
490 * SCS_32BIT_BINARY: A Win32 based application
491 * SCS_64BIT_BINARY: A Win64 based application
492 * SCS_DOS_BINARY: An MS-Dos based application
493 * SCS_WOW_BINARY: A Win16 based application
494 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
495 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
496 * SCS_OS216_BINARY: A 16bit OS/2 based application
498 * To find the binary type, this function reads in the files header information.
499 * If extended header information is not present it will assume that the file
500 * is a DOS executable. If extended header information is present it will
501 * determine if the file is a 16, 32 or 64 bit Windows executable by checking the
502 * flags in the header.
504 * ".com" and ".pif" files are only recognized by their file name extension,
505 * as per native Windows.
507 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
509 BOOL ret = FALSE;
510 HANDLE hfile;
511 struct binary_info binary_info;
513 TRACE("%s\n", debugstr_w(lpApplicationName) );
515 /* Sanity check.
517 if ( lpApplicationName == NULL || lpBinaryType == NULL )
518 return FALSE;
520 /* Open the file indicated by lpApplicationName for reading.
522 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
523 NULL, OPEN_EXISTING, 0, 0 );
524 if ( hfile == INVALID_HANDLE_VALUE )
525 return FALSE;
527 /* Check binary type
529 MODULE_get_binary_info( hfile, &binary_info );
530 switch (binary_info.type)
532 case BINARY_UNKNOWN:
534 static const WCHAR comW[] = { '.','C','O','M',0 };
535 static const WCHAR pifW[] = { '.','P','I','F',0 };
536 const WCHAR *ptr;
538 /* try to determine from file name */
539 ptr = strrchrW( lpApplicationName, '.' );
540 if (!ptr) break;
541 if (!strcmpiW( ptr, comW ))
543 *lpBinaryType = SCS_DOS_BINARY;
544 ret = TRUE;
546 else if (!strcmpiW( ptr, pifW ))
548 *lpBinaryType = SCS_PIF_BINARY;
549 ret = TRUE;
551 break;
553 case BINARY_PE:
554 *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
555 ret = TRUE;
556 break;
557 case BINARY_WIN16:
558 *lpBinaryType = SCS_WOW_BINARY;
559 ret = TRUE;
560 break;
561 case BINARY_OS216:
562 *lpBinaryType = SCS_OS216_BINARY;
563 ret = TRUE;
564 break;
565 case BINARY_DOS:
566 *lpBinaryType = SCS_DOS_BINARY;
567 ret = TRUE;
568 break;
569 case BINARY_UNIX_EXE:
570 case BINARY_UNIX_LIB:
571 ret = FALSE;
572 break;
575 CloseHandle( hfile );
576 return ret;
579 /***********************************************************************
580 * GetBinaryTypeA [KERNEL32.@]
581 * GetBinaryType [KERNEL32.@]
583 * See GetBinaryTypeW.
585 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
587 ANSI_STRING app_nameA;
588 NTSTATUS status;
590 TRACE("%s\n", debugstr_a(lpApplicationName));
592 /* Sanity check.
594 if ( lpApplicationName == NULL || lpBinaryType == NULL )
595 return FALSE;
597 RtlInitAnsiString(&app_nameA, lpApplicationName);
598 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
599 &app_nameA, FALSE);
600 if (!status)
601 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
603 SetLastError(RtlNtStatusToDosError(status));
604 return FALSE;
607 /***********************************************************************
608 * GetModuleHandleExA (KERNEL32.@)
610 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
612 WCHAR *nameW;
614 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
615 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
617 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
618 return GetModuleHandleExW( flags, nameW, module );
621 /***********************************************************************
622 * GetModuleHandleExW (KERNEL32.@)
624 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
626 NTSTATUS status = STATUS_SUCCESS;
627 HMODULE ret;
628 ULONG_PTR magic;
629 BOOL lock;
631 if (!module)
633 SetLastError( ERROR_INVALID_PARAMETER );
634 return FALSE;
637 /* if we are messing with the refcount, grab the loader lock */
638 lock = (flags & GET_MODULE_HANDLE_EX_FLAG_PIN) || !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT);
639 if (lock)
640 LdrLockLoaderLock( 0, NULL, &magic );
642 if (!name)
644 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
646 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
648 void *dummy;
649 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
651 else
653 UNICODE_STRING wstr;
654 RtlInitUnicodeString( &wstr, name );
655 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
658 if (status == STATUS_SUCCESS)
660 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
661 LdrAddRefDll( LDR_ADDREF_DLL_PIN, ret );
662 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
663 LdrAddRefDll( 0, ret );
665 else SetLastError( RtlNtStatusToDosError( status ) );
667 if (lock)
668 LdrUnlockLoaderLock( 0, magic );
670 if (status == STATUS_SUCCESS) *module = ret;
671 else *module = NULL;
673 return (status == STATUS_SUCCESS);
676 /***********************************************************************
677 * GetModuleHandleA (KERNEL32.@)
679 * Get the handle of a dll loaded into the process address space.
681 * PARAMS
682 * module [I] Name of the dll
684 * RETURNS
685 * Success: A handle to the loaded dll.
686 * Failure: A NULL handle. Use GetLastError() to determine the cause.
688 HMODULE WINAPI DECLSPEC_HOTPATCH GetModuleHandleA(LPCSTR module)
690 HMODULE ret;
692 GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
693 return ret;
696 /***********************************************************************
697 * GetModuleHandleW (KERNEL32.@)
699 * Unicode version of GetModuleHandleA.
701 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
703 HMODULE ret;
705 GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret );
706 return ret;
710 /***********************************************************************
711 * GetModuleFileNameA (KERNEL32.@)
713 * Get the file name of a loaded module from its handle.
715 * RETURNS
716 * Success: The length of the file name, excluding the terminating NUL.
717 * Failure: 0. Use GetLastError() to determine the cause.
719 * NOTES
720 * This function always returns the long path of hModule
721 * The function doesn't write a terminating '\0' if the buffer is too
722 * small.
724 DWORD WINAPI GetModuleFileNameA(
725 HMODULE hModule, /* [in] Module handle (32 bit) */
726 LPSTR lpFileName, /* [out] Destination for file name */
727 DWORD size ) /* [in] Size of lpFileName in characters */
729 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
730 DWORD len;
732 if (!filenameW)
734 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
735 return 0;
737 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
739 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
740 if (len < size)
741 lpFileName[len] = '\0';
742 else
743 SetLastError( ERROR_INSUFFICIENT_BUFFER );
745 HeapFree( GetProcessHeap(), 0, filenameW );
746 return len;
749 /***********************************************************************
750 * GetModuleFileNameW (KERNEL32.@)
752 * Unicode version of GetModuleFileNameA.
754 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
756 ULONG len = 0;
757 ULONG_PTR magic;
758 LDR_MODULE *pldr;
759 NTSTATUS nts;
760 WIN16_SUBSYSTEM_TIB *win16_tib;
762 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
764 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
765 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
766 if (len < size) lpFileName[len] = '\0';
767 goto done;
770 LdrLockLoaderLock( 0, NULL, &magic );
772 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
773 nts = LdrFindEntryForAddress( hModule, &pldr );
774 if (nts == STATUS_SUCCESS)
776 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
777 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
778 if (len < size)
780 lpFileName[len] = '\0';
781 SetLastError( 0 );
783 else
784 SetLastError( ERROR_INSUFFICIENT_BUFFER );
786 else SetLastError( RtlNtStatusToDosError( nts ) );
788 LdrUnlockLoaderLock( 0, magic );
789 done:
790 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
791 return len;
795 /***********************************************************************
796 * get_dll_system_path
798 static const WCHAR *get_dll_system_path(void)
800 static WCHAR *cached_path;
802 if (!cached_path)
804 WCHAR *p, *path;
805 int len = 1;
807 len += 2 * GetSystemDirectoryW( NULL, 0 );
808 len += GetWindowsDirectoryW( NULL, 0 );
809 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
810 GetSystemDirectoryW( p, path + len - p);
811 p += strlenW(p);
812 /* if system directory ends in "32" add 16-bit version too */
813 if (p[-2] == '3' && p[-1] == '2')
815 *p++ = ';';
816 GetSystemDirectoryW( p, path + len - p);
817 p += strlenW(p) - 2;
819 *p++ = ';';
820 GetWindowsDirectoryW( p, path + len - p);
821 cached_path = path;
823 return cached_path;
826 /***********************************************************************
827 * get_dll_safe_mode
829 static BOOL get_dll_safe_mode(void)
831 static const WCHAR keyW[] = {'\\','R','e','g','i','s','t','r','y','\\',
832 'M','a','c','h','i','n','e','\\',
833 'S','y','s','t','e','m','\\',
834 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
835 'C','o','n','t','r','o','l','\\',
836 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
837 static const WCHAR valueW[] = {'S','a','f','e','D','l','l','S','e','a','r','c','h','M','o','d','e',0};
839 static int safe_mode = -1;
841 if (safe_mode == -1)
843 char buffer[offsetof(KEY_VALUE_PARTIAL_INFORMATION, Data[sizeof(DWORD)])];
844 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
845 OBJECT_ATTRIBUTES attr;
846 UNICODE_STRING nameW;
847 HANDLE hkey;
848 DWORD size = sizeof(buffer);
850 attr.Length = sizeof(attr);
851 attr.RootDirectory = 0;
852 attr.ObjectName = &nameW;
853 attr.Attributes = 0;
854 attr.SecurityDescriptor = NULL;
855 attr.SecurityQualityOfService = NULL;
857 safe_mode = 1;
858 RtlInitUnicodeString( &nameW, keyW );
859 if (!NtOpenKey( &hkey, KEY_READ, &attr ))
861 RtlInitUnicodeString( &nameW, valueW );
862 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, buffer, size, &size ) &&
863 info->Type == REG_DWORD && info->DataLength == sizeof(DWORD))
864 safe_mode = !!*(DWORD *)info->Data;
865 NtClose( hkey );
867 if (!safe_mode) TRACE( "SafeDllSearchMode disabled through the registry\n" );
869 return safe_mode;
872 /******************************************************************
873 * get_module_path_end
875 * Returns the end of the directory component of the module path.
877 static inline const WCHAR *get_module_path_end(const WCHAR *module)
879 const WCHAR *p;
880 const WCHAR *mod_end = module;
881 if (!module) return mod_end;
883 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
884 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
885 if (mod_end == module + 2 && module[1] == ':') mod_end++;
886 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
888 return mod_end;
892 /******************************************************************
893 * append_path_len
895 * Append a counted string to the load path. Helper for MODULE_get_dll_load_path.
897 static inline WCHAR *append_path_len( WCHAR *p, const WCHAR *str, DWORD len )
899 if (!len) return p;
900 memcpy( p, str, len * sizeof(WCHAR) );
901 p[len] = ';';
902 return p + len + 1;
906 /******************************************************************
907 * append_path
909 * Append a string to the load path. Helper for MODULE_get_dll_load_path.
911 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str )
913 return append_path_len( p, str, strlenW(str) );
917 /******************************************************************
918 * MODULE_get_dll_load_path
920 * Compute the load path to use for a given dll.
921 * Returned pointer must be freed by caller.
923 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
925 static const WCHAR pathW[] = {'P','A','T','H',0};
926 static const WCHAR dotW[] = {'.',0};
928 const WCHAR *system_path = get_dll_system_path();
929 const WCHAR *mod_end = NULL;
930 UNICODE_STRING name, value;
931 BOOL safe_mode;
932 WCHAR *p, *ret;
933 int len = 0, path_len = 0;
935 /* adjust length for module name */
937 if (module)
938 mod_end = get_module_path_end( module );
939 /* if module is NULL or doesn't contain a path, fall back to directory
940 * process was loaded from */
941 if (module == mod_end)
943 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
944 mod_end = get_module_path_end( module );
946 len += (mod_end - module) + 1;
948 len += strlenW( system_path ) + 2;
950 /* get the PATH variable */
952 RtlInitUnicodeString( &name, pathW );
953 value.Length = 0;
954 value.MaximumLength = 0;
955 value.Buffer = NULL;
956 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
957 path_len = value.Length;
959 RtlEnterCriticalSection( &dlldir_section );
960 safe_mode = get_dll_safe_mode();
961 if (dll_directory) len += strlenW(dll_directory) + 1;
962 else len += 2; /* current directory */
963 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
965 if (module) p = append_path_len( p, module, mod_end - module );
967 if (dll_directory) p = append_path( p, dll_directory );
968 else if (!safe_mode) p = append_path( p, dotW );
970 p = append_path( p, system_path );
972 if (!dll_directory && safe_mode) p = append_path( p, dotW );
974 RtlLeaveCriticalSection( &dlldir_section );
975 if (!ret) return NULL;
977 value.Buffer = p;
978 value.MaximumLength = path_len;
980 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
982 WCHAR *new_ptr;
984 /* grow the buffer and retry */
985 path_len = value.Length;
986 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
988 HeapFree( GetProcessHeap(), 0, ret );
989 return NULL;
991 value.Buffer = new_ptr + (value.Buffer - ret);
992 value.MaximumLength = path_len;
993 ret = new_ptr;
995 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
996 return ret;
1000 /******************************************************************
1001 * load_library_as_datafile
1003 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE *hmod, DWORD flags )
1005 static const WCHAR dotDLL[] = {'.','d','l','l',0};
1007 WCHAR filenameW[MAX_PATH];
1008 HANDLE hFile = INVALID_HANDLE_VALUE;
1009 HANDLE mapping;
1010 HMODULE module;
1011 DWORD sharing = FILE_SHARE_READ;
1013 *hmod = 0;
1015 if (!(flags & LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE)) sharing |= FILE_SHARE_WRITE;
1017 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
1018 filenameW, NULL ))
1020 hFile = CreateFileW( filenameW, GENERIC_READ, sharing, NULL, OPEN_EXISTING, 0, 0 );
1022 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
1024 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1025 CloseHandle( hFile );
1026 if (!mapping) return FALSE;
1028 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1029 CloseHandle( mapping );
1030 if (!module) return FALSE;
1032 /* make sure it's a valid PE file */
1033 if (!RtlImageNtHeader(module))
1035 UnmapViewOfFile( module );
1036 return FALSE;
1038 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
1039 return TRUE;
1043 /******************************************************************
1044 * load_library
1046 * Helper for LoadLibraryExA/W.
1048 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
1050 NTSTATUS nts;
1051 HMODULE hModule;
1052 WCHAR *load_path;
1053 static const DWORD unsupported_flags = load_library_search_flags |
1054 LOAD_IGNORE_CODE_AUTHZ_LEVEL |
1055 LOAD_LIBRARY_AS_IMAGE_RESOURCE |
1056 LOAD_LIBRARY_REQUIRE_SIGNED_TARGET |
1057 LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
1059 if (!(flags & load_library_search_flags)) flags |= default_search_flags;
1061 if( flags & unsupported_flags)
1062 FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags);
1064 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
1066 if (flags & (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE))
1068 ULONG_PTR magic;
1070 LdrLockLoaderLock( 0, NULL, &magic );
1071 if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
1073 LdrAddRefDll( 0, hModule );
1074 LdrUnlockLoaderLock( 0, magic );
1075 goto done;
1077 LdrUnlockLoaderLock( 0, magic );
1079 /* The method in load_library_as_datafile allows searching for the
1080 * 'native' libraries only
1082 if (load_library_as_datafile( libname->Buffer, &hModule, flags )) goto done;
1083 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1084 /* Fallback to normal behaviour */
1087 nts = LdrLoadDll( load_path, flags, libname, &hModule );
1088 if (nts != STATUS_SUCCESS)
1090 hModule = 0;
1091 if (nts == STATUS_DLL_NOT_FOUND && (GetVersion() & 0x80000000))
1092 SetLastError( ERROR_DLL_NOT_FOUND );
1093 else
1094 SetLastError( RtlNtStatusToDosError( nts ) );
1096 done:
1097 HeapFree( GetProcessHeap(), 0, load_path );
1098 return hModule;
1102 /******************************************************************
1103 * LoadLibraryExA (KERNEL32.@)
1105 * Load a dll file into the process address space.
1107 * PARAMS
1108 * libname [I] Name of the file to load
1109 * hfile [I] Reserved, must be 0.
1110 * flags [I] Flags for loading the dll
1112 * RETURNS
1113 * Success: A handle to the loaded dll.
1114 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1116 * NOTES
1117 * The HFILE parameter is not used and marked reserved in the SDK. I can
1118 * only guess that it should force a file to be mapped, but I rather
1119 * ignore the parameter because it would be extremely difficult to
1120 * integrate this with different types of module representations.
1122 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1124 WCHAR *libnameW;
1126 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
1127 return LoadLibraryExW( libnameW, hfile, flags );
1130 /***********************************************************************
1131 * LoadLibraryExW (KERNEL32.@)
1133 * Unicode version of LoadLibraryExA.
1135 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
1137 UNICODE_STRING wstr;
1138 HMODULE res;
1140 if (!libnameW)
1142 SetLastError(ERROR_INVALID_PARAMETER);
1143 return 0;
1145 RtlInitUnicodeString( &wstr, libnameW );
1146 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
1147 return load_library( &wstr, flags );
1149 /* Library name has trailing spaces */
1150 RtlCreateUnicodeString( &wstr, libnameW );
1151 while (wstr.Length > sizeof(WCHAR) &&
1152 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
1154 wstr.Length -= sizeof(WCHAR);
1156 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
1157 res = load_library( &wstr, flags );
1158 RtlFreeUnicodeString( &wstr );
1159 return res;
1162 /***********************************************************************
1163 * LoadLibraryA (KERNEL32.@)
1165 * Load a dll file into the process address space.
1167 * PARAMS
1168 * libname [I] Name of the file to load
1170 * RETURNS
1171 * Success: A handle to the loaded dll.
1172 * Failure: A NULL handle. Use GetLastError() to determine the cause.
1174 * NOTES
1175 * See LoadLibraryExA().
1177 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
1179 return LoadLibraryExA(libname, 0, 0);
1182 /***********************************************************************
1183 * LoadLibraryW (KERNEL32.@)
1185 * Unicode version of LoadLibraryA.
1187 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
1189 return LoadLibraryExW(libnameW, 0, 0);
1192 /***********************************************************************
1193 * FreeLibrary (KERNEL32.@)
1195 * Free a dll loaded into the process address space.
1197 * PARAMS
1198 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
1200 * RETURNS
1201 * Success: TRUE. The dll is removed if it is not still in use.
1202 * Failure: FALSE. Use GetLastError() to determine the cause.
1204 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
1206 BOOL retv = FALSE;
1207 NTSTATUS nts;
1209 if (!hLibModule)
1211 SetLastError( ERROR_INVALID_HANDLE );
1212 return FALSE;
1215 if ((ULONG_PTR)hLibModule & 1)
1217 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1218 char *ptr = (char *)hLibModule - 1;
1219 return UnmapViewOfFile( ptr );
1222 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1223 else SetLastError( RtlNtStatusToDosError( nts ) );
1225 return retv;
1228 /***********************************************************************
1229 * GetProcAddress (KERNEL32.@)
1231 * Find the address of an exported symbol in a loaded dll.
1233 * PARAMS
1234 * hModule [I] Handle to the dll returned by LoadLibraryA().
1235 * function [I] Name of the symbol, or an integer ordinal number < 16384
1237 * RETURNS
1238 * Success: A pointer to the symbol in the process address space.
1239 * Failure: NULL. Use GetLastError() to determine the cause.
1241 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1243 NTSTATUS nts;
1244 FARPROC fp;
1246 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1248 if ((ULONG_PTR)function >> 16)
1250 ANSI_STRING str;
1252 RtlInitAnsiString( &str, function );
1253 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1255 else
1256 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1257 if (nts != STATUS_SUCCESS)
1259 SetLastError( RtlNtStatusToDosError( nts ) );
1260 fp = NULL;
1262 return fp;
1265 /***********************************************************************
1266 * DelayLoadFailureHook (KERNEL32.@)
1268 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1270 ULONG_PTR args[2];
1272 if ((ULONG_PTR)function >> 16)
1273 ERR( "failed to delay load %s.%s\n", name, function );
1274 else
1275 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1276 args[0] = (ULONG_PTR)name;
1277 args[1] = (ULONG_PTR)function;
1278 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1279 return NULL;
1282 typedef struct {
1283 HANDLE process;
1284 PLIST_ENTRY head, current;
1285 LDR_MODULE ldr_module;
1286 } MODULE_ITERATOR;
1288 static BOOL init_module_iterator(MODULE_ITERATOR *iter, HANDLE process)
1290 PROCESS_BASIC_INFORMATION pbi;
1291 PPEB_LDR_DATA ldr_data;
1292 NTSTATUS status;
1294 /* Get address of PEB */
1295 status = NtQueryInformationProcess(process, ProcessBasicInformation,
1296 &pbi, sizeof(pbi), NULL);
1297 if (status != STATUS_SUCCESS)
1299 SetLastError(RtlNtStatusToDosError(status));
1300 return FALSE;
1303 /* Read address of LdrData from PEB */
1304 if (!ReadProcessMemory(process, &pbi.PebBaseAddress->LdrData,
1305 &ldr_data, sizeof(ldr_data), NULL))
1306 return FALSE;
1308 /* Read address of first module from LdrData */
1309 if (!ReadProcessMemory(process,
1310 &ldr_data->InLoadOrderModuleList.Flink,
1311 &iter->current, sizeof(iter->current), NULL))
1312 return FALSE;
1314 iter->head = &ldr_data->InLoadOrderModuleList;
1315 iter->process = process;
1317 return TRUE;
1320 static int module_iterator_next(MODULE_ITERATOR *iter)
1322 if (iter->current == iter->head)
1323 return 0;
1325 if (!ReadProcessMemory(iter->process,
1326 CONTAINING_RECORD(iter->current, LDR_MODULE, InLoadOrderModuleList),
1327 &iter->ldr_module, sizeof(iter->ldr_module), NULL))
1328 return -1;
1330 iter->current = iter->ldr_module.InLoadOrderModuleList.Flink;
1331 return 1;
1334 static BOOL get_ldr_module(HANDLE process, HMODULE module, LDR_MODULE *ldr_module)
1336 MODULE_ITERATOR iter;
1337 INT ret;
1339 if (!init_module_iterator(&iter, process))
1340 return FALSE;
1342 while ((ret = module_iterator_next(&iter)) > 0)
1343 /* When hModule is NULL we return the process image - which will be
1344 * the first module since our iterator uses InLoadOrderModuleList */
1345 if (!module || module == iter.ldr_module.BaseAddress)
1347 *ldr_module = iter.ldr_module;
1348 return TRUE;
1351 if (ret == 0)
1352 SetLastError(ERROR_INVALID_HANDLE);
1354 return FALSE;
1357 /***********************************************************************
1358 * K32EnumProcessModules (KERNEL32.@)
1360 * NOTES
1361 * Returned list is in load order.
1363 BOOL WINAPI K32EnumProcessModules(HANDLE process, HMODULE *lphModule,
1364 DWORD cb, DWORD *needed)
1366 MODULE_ITERATOR iter;
1367 INT ret;
1369 if (!init_module_iterator(&iter, process))
1370 return FALSE;
1372 if ((cb && !lphModule) || !needed)
1374 SetLastError(ERROR_NOACCESS);
1375 return FALSE;
1378 *needed = 0;
1380 while ((ret = module_iterator_next(&iter)) > 0)
1382 if (cb >= sizeof(HMODULE))
1384 *lphModule++ = iter.ldr_module.BaseAddress;
1385 cb -= sizeof(HMODULE);
1387 *needed += sizeof(HMODULE);
1390 return ret == 0;
1393 /***********************************************************************
1394 * K32EnumProcessModulesEx (KERNEL32.@)
1396 * NOTES
1397 * Returned list is in load order.
1399 BOOL WINAPI K32EnumProcessModulesEx(HANDLE process, HMODULE *lphModule,
1400 DWORD cb, DWORD *needed, DWORD filter)
1402 FIXME("(%p, %p, %d, %p, %d) semi-stub\n",
1403 process, lphModule, cb, needed, filter);
1404 return K32EnumProcessModules(process, lphModule, cb, needed);
1407 /***********************************************************************
1408 * K32GetModuleBaseNameW (KERNEL32.@)
1410 DWORD WINAPI K32GetModuleBaseNameW(HANDLE process, HMODULE module,
1411 LPWSTR base_name, DWORD size)
1413 LDR_MODULE ldr_module;
1415 if (!get_ldr_module(process, module, &ldr_module))
1416 return 0;
1418 size = min(ldr_module.BaseDllName.Length / sizeof(WCHAR), size);
1419 if (!ReadProcessMemory(process, ldr_module.BaseDllName.Buffer,
1420 base_name, size * sizeof(WCHAR), NULL))
1421 return 0;
1423 base_name[size] = 0;
1424 return size;
1427 /***********************************************************************
1428 * K32GetModuleBaseNameA (KERNEL32.@)
1430 DWORD WINAPI K32GetModuleBaseNameA(HANDLE process, HMODULE module,
1431 LPSTR base_name, DWORD size)
1433 WCHAR *base_name_w;
1434 DWORD len, ret = 0;
1436 if(!base_name || !size) {
1437 SetLastError(ERROR_INVALID_PARAMETER);
1438 return 0;
1441 base_name_w = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * size);
1442 if(!base_name_w)
1443 return 0;
1445 len = K32GetModuleBaseNameW(process, module, base_name_w, size);
1446 TRACE("%d, %s\n", len, debugstr_w(base_name_w));
1447 if (len)
1449 ret = WideCharToMultiByte(CP_ACP, 0, base_name_w, len,
1450 base_name, size, NULL, NULL);
1451 if (ret < size) base_name[ret] = 0;
1453 HeapFree(GetProcessHeap(), 0, base_name_w);
1454 return ret;
1457 /***********************************************************************
1458 * K32GetModuleFileNameExW (KERNEL32.@)
1460 DWORD WINAPI K32GetModuleFileNameExW(HANDLE process, HMODULE module,
1461 LPWSTR file_name, DWORD size)
1463 LDR_MODULE ldr_module;
1464 DWORD len;
1466 if (!size) return 0;
1468 if(!get_ldr_module(process, module, &ldr_module))
1469 return 0;
1471 len = ldr_module.FullDllName.Length / sizeof(WCHAR);
1472 if (!ReadProcessMemory(process, ldr_module.FullDllName.Buffer,
1473 file_name, min( len, size ) * sizeof(WCHAR), NULL))
1474 return 0;
1476 if (len < size)
1478 file_name[len] = 0;
1479 return len;
1481 else
1483 file_name[size - 1] = 0;
1484 return size;
1488 /***********************************************************************
1489 * K32GetModuleFileNameExA (KERNEL32.@)
1491 DWORD WINAPI K32GetModuleFileNameExA(HANDLE process, HMODULE module,
1492 LPSTR file_name, DWORD size)
1494 WCHAR *ptr;
1495 DWORD len;
1497 TRACE("(hProcess=%p, hModule=%p, %p, %d)\n", process, module, file_name, size);
1499 if (!file_name || !size)
1501 SetLastError( ERROR_INVALID_PARAMETER );
1502 return 0;
1505 if ( process == GetCurrentProcess() )
1507 len = GetModuleFileNameA( module, file_name, size );
1508 if (size) file_name[size - 1] = '\0';
1509 return len;
1512 if (!(ptr = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR)))) return 0;
1514 len = K32GetModuleFileNameExW(process, module, ptr, size);
1515 if (!len)
1517 file_name[0] = '\0';
1519 else
1521 if (!WideCharToMultiByte( CP_ACP, 0, ptr, -1, file_name, size, NULL, NULL ))
1523 file_name[size - 1] = 0;
1524 len = size;
1526 else if (len < size) len = strlen( file_name );
1529 HeapFree(GetProcessHeap(), 0, ptr);
1530 return len;
1533 /***********************************************************************
1534 * K32GetModuleInformation (KERNEL32.@)
1536 BOOL WINAPI K32GetModuleInformation(HANDLE process, HMODULE module,
1537 MODULEINFO *modinfo, DWORD cb)
1539 LDR_MODULE ldr_module;
1541 if (cb < sizeof(MODULEINFO))
1543 SetLastError(ERROR_INSUFFICIENT_BUFFER);
1544 return FALSE;
1547 if (!get_ldr_module(process, module, &ldr_module))
1548 return FALSE;
1550 modinfo->lpBaseOfDll = ldr_module.BaseAddress;
1551 modinfo->SizeOfImage = ldr_module.SizeOfImage;
1552 modinfo->EntryPoint = ldr_module.EntryPoint;
1553 return TRUE;
1556 #ifdef __i386__
1558 /***********************************************************************
1559 * __wine_dll_register_16 (KERNEL32.@)
1561 * No longer used.
1563 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1565 ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1569 /***********************************************************************
1570 * __wine_dll_unregister_16 (KERNEL32.@)
1572 * No longer used.
1574 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1578 #endif