kernel: DelayLoadFailureHook crash fix.
[wine/hacks.git] / dlls / kernel / module.c
blob4610adfcd1ca6cef79ea01c851f1c2b1bdf50349
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <fcntl.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #include "ntstatus.h"
33 #define WIN32_NO_STATUS
34 #include "wine/winbase16.h"
35 #include "winerror.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winternl.h"
39 #include "thread.h"
40 #include "module.h"
41 #include "kernel_private.h"
43 #include "wine/exception.h"
44 #include "wine/debug.h"
45 #include "wine/unicode.h"
46 #include "wine/server.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module);
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 enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
185 const IMAGE_OS2_HEADER *ne)
187 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
188 enum binary_type ret = BINARY_OS216;
189 LPWORD modtab = NULL;
190 LPSTR nametab = NULL;
191 DWORD len;
192 int i;
194 /* read modref table */
195 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
196 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
197 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
198 || (len != ne->ne_cmod*sizeof(WORD)) )
199 goto broken;
201 /* read imported names table */
202 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
203 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
204 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
205 || (len != ne->ne_enttab - ne->ne_imptab) )
206 goto broken;
208 for (i=0; i < ne->ne_cmod; i++)
210 LPSTR module = &nametab[modtab[i]];
211 TRACE("modref: %.*s\n", module[0], &module[1]);
212 if (!(strncmp(&module[1], "KERNEL", module[0])))
213 { /* very old Windows file */
214 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
215 ret = BINARY_WIN16;
216 goto good;
220 broken:
221 ERR("Hmm, an error occurred. Is this binary file broken?\n");
223 good:
224 HeapFree( GetProcessHeap(), 0, modtab);
225 HeapFree( GetProcessHeap(), 0, nametab);
226 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
227 return ret;
230 /***********************************************************************
231 * MODULE_GetBinaryType
233 enum binary_type MODULE_GetBinaryType( HANDLE hfile, void **res_start, void **res_end )
235 union
237 struct
239 unsigned char magic[4];
240 unsigned char ignored[12];
241 unsigned short type;
242 } elf;
243 struct
245 unsigned long magic;
246 unsigned long cputype;
247 unsigned long cpusubtype;
248 unsigned long filetype;
249 } macho;
250 IMAGE_DOS_HEADER mz;
251 } header;
253 DWORD len;
255 /* Seek to the start of the file and read the header information. */
256 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
257 return BINARY_UNKNOWN;
258 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
259 return BINARY_UNKNOWN;
261 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
263 /* FIXME: we don't bother to check byte order, architecture, etc. */
264 switch(header.elf.type)
266 case 2: return BINARY_UNIX_EXE;
267 case 3: return BINARY_UNIX_LIB;
269 return BINARY_UNKNOWN;
272 /* Mach-o File with Endian set to Big Endian or Little Endian */
273 if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
275 switch(header.macho.filetype)
277 case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
279 return BINARY_UNKNOWN;
282 /* Not ELF, try DOS */
284 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
286 union
288 IMAGE_OS2_HEADER os2;
289 IMAGE_NT_HEADERS nt;
290 } ext_header;
292 /* We do have a DOS image so we will now try to seek into
293 * the file by the amount indicated by the field
294 * "Offset to extended header" and read in the
295 * "magic" field information at that location.
296 * This will tell us if there is more header information
297 * to read or not.
299 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
300 return BINARY_DOS;
301 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4)
302 return BINARY_DOS;
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 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
312 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
313 if (res_start) *res_start = (void *)ext_header.nt.OptionalHeader.ImageBase;
314 if (res_end) *res_end = (void *)(ext_header.nt.OptionalHeader.ImageBase +
315 ext_header.nt.OptionalHeader.SizeOfImage);
316 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
317 return BINARY_PE_EXE;
319 return BINARY_DOS;
322 if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
324 /* This is a Windows executable (NE) header. This can
325 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
326 * DOS program (running under a DOS extender). To decide
327 * which, we'll have to read the NE header.
329 if (len >= sizeof(ext_header.os2))
331 switch ( ext_header.os2.ne_exetyp )
333 case 1: return BINARY_OS216; /* OS/2 */
334 case 2: return BINARY_WIN16; /* Windows */
335 case 3: return BINARY_DOS; /* European MS-DOS 4.x */
336 case 4: return BINARY_WIN16; /* Windows 386; FIXME: is this 32bit??? */
337 case 5: return BINARY_DOS; /* BOSS, Borland Operating System Services */
338 /* other types, e.g. 0 is: "unknown" */
339 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2);
342 /* Couldn't read header, so abort. */
343 return BINARY_DOS;
346 /* Unknown extended header, but this file is nonetheless DOS-executable. */
347 return BINARY_DOS;
350 return BINARY_UNKNOWN;
353 /***********************************************************************
354 * GetBinaryTypeW [KERNEL32.@]
356 * Determine whether a file is executable, and if so, what kind.
358 * PARAMS
359 * lpApplicationName [I] Path of the file to check
360 * lpBinaryType [O] Destination for the binary type
362 * RETURNS
363 * TRUE, if the file is an executable, in which case lpBinaryType is set.
364 * FALSE, if the file is not an executable or if the function fails.
366 * NOTES
367 * The type of executable is a property that determines which subsytem an
368 * executable file runs under. lpBinaryType can be set to one of the following
369 * values:
370 * SCS_32BIT_BINARY: A Win32 based application
371 * SCS_DOS_BINARY: An MS-Dos based application
372 * SCS_WOW_BINARY: A Win16 based application
373 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
374 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
375 * SCS_OS216_BINARY: A 16bit OS/2 based application
377 * To find the binary type, this function reads in the files header information.
378 * If extended header information is not present it will assume that the file
379 * is a DOS executable. If extended header information is present it will
380 * determine if the file is a 16 or 32 bit Windows executable by checking the
381 * flags in the header.
383 * ".com" and ".pif" files are only recognized by their file name extension,
384 * as per native Windows.
386 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
388 BOOL ret = FALSE;
389 HANDLE hfile;
391 TRACE("%s\n", debugstr_w(lpApplicationName) );
393 /* Sanity check.
395 if ( lpApplicationName == NULL || lpBinaryType == NULL )
396 return FALSE;
398 /* Open the file indicated by lpApplicationName for reading.
400 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
401 NULL, OPEN_EXISTING, 0, 0 );
402 if ( hfile == INVALID_HANDLE_VALUE )
403 return FALSE;
405 /* Check binary type
407 switch(MODULE_GetBinaryType( hfile, NULL, NULL ))
409 case BINARY_UNKNOWN:
411 static const WCHAR comW[] = { '.','C','O','M',0 };
412 static const WCHAR pifW[] = { '.','P','I','F',0 };
413 const WCHAR *ptr;
415 /* try to determine from file name */
416 ptr = strrchrW( lpApplicationName, '.' );
417 if (!ptr) break;
418 if (!strcmpiW( ptr, comW ))
420 *lpBinaryType = SCS_DOS_BINARY;
421 ret = TRUE;
423 else if (!strcmpiW( ptr, pifW ))
425 *lpBinaryType = SCS_PIF_BINARY;
426 ret = TRUE;
428 break;
430 case BINARY_PE_EXE:
431 case BINARY_PE_DLL:
432 *lpBinaryType = SCS_32BIT_BINARY;
433 ret = TRUE;
434 break;
435 case BINARY_WIN16:
436 *lpBinaryType = SCS_WOW_BINARY;
437 ret = TRUE;
438 break;
439 case BINARY_OS216:
440 *lpBinaryType = SCS_OS216_BINARY;
441 ret = TRUE;
442 break;
443 case BINARY_DOS:
444 *lpBinaryType = SCS_DOS_BINARY;
445 ret = TRUE;
446 break;
447 case BINARY_UNIX_EXE:
448 case BINARY_UNIX_LIB:
449 ret = FALSE;
450 break;
453 CloseHandle( hfile );
454 return ret;
457 /***********************************************************************
458 * GetBinaryTypeA [KERNEL32.@]
459 * GetBinaryType [KERNEL32.@]
461 * See GetBinaryTypeW.
463 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
465 ANSI_STRING app_nameA;
466 NTSTATUS status;
468 TRACE("%s\n", debugstr_a(lpApplicationName));
470 /* Sanity check.
472 if ( lpApplicationName == NULL || lpBinaryType == NULL )
473 return FALSE;
475 RtlInitAnsiString(&app_nameA, lpApplicationName);
476 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
477 &app_nameA, FALSE);
478 if (!status)
479 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
481 SetLastError(RtlNtStatusToDosError(status));
482 return FALSE;
486 /***********************************************************************
487 * GetModuleHandleA (KERNEL32.@)
488 * GetModuleHandle32 (KERNEL.488)
490 * Get the handle of a dll loaded into the process address space.
492 * PARAMS
493 * module [I] Name of the dll
495 * RETURNS
496 * Success: A handle to the loaded dll.
497 * Failure: A NULL handle. Use GetLastError() to determine the cause.
499 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
501 WCHAR *moduleW;
503 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
504 if (!(moduleW = FILE_name_AtoW( module, FALSE ))) return 0;
505 return GetModuleHandleW( moduleW );
508 /***********************************************************************
509 * GetModuleHandleW (KERNEL32.@)
511 * Unicode version of GetModuleHandleA.
513 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
515 NTSTATUS nts;
516 HMODULE ret;
517 UNICODE_STRING wstr;
519 if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
521 RtlInitUnicodeString( &wstr, module );
522 nts = LdrGetDllHandle( 0, 0, &wstr, &ret);
523 if (nts != STATUS_SUCCESS)
525 SetLastError( RtlNtStatusToDosError( nts ) );
526 ret = 0;
528 return ret;
532 /***********************************************************************
533 * GetModuleFileNameA (KERNEL32.@)
534 * GetModuleFileName32 (KERNEL.487)
536 * Get the file name of a loaded module from its handle.
538 * RETURNS
539 * Success: The length of the file name, excluding the terminating NUL.
540 * Failure: 0. Use GetLastError() to determine the cause.
542 * NOTES
543 * This function always returns the long path of hModule (as opposed to
544 * GetModuleFileName16() which returns short paths when the modules version
545 * field is < 4.0).
546 * The function doesn't write a terminating '\0' if the buffer is too
547 * small.
549 DWORD WINAPI GetModuleFileNameA(
550 HMODULE hModule, /* [in] Module handle (32 bit) */
551 LPSTR lpFileName, /* [out] Destination for file name */
552 DWORD size ) /* [in] Size of lpFileName in characters */
554 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
555 DWORD len;
557 if (!filenameW)
559 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
560 return 0;
562 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
564 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
565 if (len < size) lpFileName[len] = '\0';
567 HeapFree( GetProcessHeap(), 0, filenameW );
568 return len;
571 /***********************************************************************
572 * GetModuleFileNameW (KERNEL32.@)
574 * Unicode version of GetModuleFileNameA.
576 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
578 ULONG magic, len = 0;
579 LDR_MODULE *pldr;
580 NTSTATUS nts;
581 WIN16_SUBSYSTEM_TIB *win16_tib;
583 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
585 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
586 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
587 if (len < size) lpFileName[len] = '\0';
588 goto done;
591 LdrLockLoaderLock( 0, NULL, &magic );
593 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
594 nts = LdrFindEntryForAddress( hModule, &pldr );
595 if (nts == STATUS_SUCCESS)
597 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
598 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
599 if (len < size) lpFileName[len] = '\0';
601 else SetLastError( RtlNtStatusToDosError( nts ) );
603 LdrUnlockLoaderLock( 0, magic );
604 done:
605 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
606 return len;
610 /***********************************************************************
611 * get_dll_system_path
613 static const WCHAR *get_dll_system_path(void)
615 static WCHAR *cached_path;
617 if (!cached_path)
619 WCHAR *p, *path;
620 int len = 3;
622 len += 2 * GetSystemDirectoryW( NULL, 0 );
623 len += GetWindowsDirectoryW( NULL, 0 );
624 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
625 *p++ = '.';
626 *p++ = ';';
627 GetSystemDirectoryW( p, path + len - p);
628 p += strlenW(p);
629 /* if system directory ends in "32" add 16-bit version too */
630 if (p[-2] == '3' && p[-1] == '2')
632 *p++ = ';';
633 GetSystemDirectoryW( p, path + len - p);
634 p += strlenW(p) - 2;
636 *p++ = ';';
637 GetWindowsDirectoryW( p, path + len - p);
638 cached_path = path;
640 return cached_path;
644 /******************************************************************
645 * MODULE_get_dll_load_path
647 * Compute the load path to use for a given dll.
648 * Returned pointer must be freed by caller.
650 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
652 static const WCHAR pathW[] = {'P','A','T','H',0};
654 const WCHAR *system_path = get_dll_system_path();
655 const WCHAR *mod_end = NULL;
656 UNICODE_STRING name, value;
657 WCHAR *p, *ret;
658 int len = 0, path_len = 0;
660 /* adjust length for module name */
662 if (!module) module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
663 if (module)
665 mod_end = module;
666 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
667 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
668 if (mod_end == module + 2 && module[1] == ':') mod_end++;
669 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
670 len += (mod_end - module) + 1;
672 len += strlenW( system_path ) + 2;
674 /* get the PATH variable */
676 RtlInitUnicodeString( &name, pathW );
677 value.Length = 0;
678 value.MaximumLength = 0;
679 value.Buffer = NULL;
680 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
681 path_len = value.Length;
683 RtlEnterCriticalSection( &dlldir_section );
684 if (dll_directory) len += strlenW(dll_directory) + 1;
685 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
687 if (module)
689 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
690 p += (mod_end - module);
691 *p++ = ';';
693 if (dll_directory)
695 strcpyW( p, dll_directory );
696 p += strlenW(p);
697 *p++ = ';';
700 RtlLeaveCriticalSection( &dlldir_section );
701 if (!ret) return NULL;
703 strcpyW( p, system_path );
704 p += strlenW(p);
705 *p++ = ';';
706 value.Buffer = p;
707 value.MaximumLength = path_len;
709 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
711 WCHAR *new_ptr;
713 /* grow the buffer and retry */
714 path_len = value.Length;
715 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
717 HeapFree( GetProcessHeap(), 0, ret );
718 return NULL;
720 value.Buffer = new_ptr + (value.Buffer - ret);
721 value.MaximumLength = path_len;
722 ret = new_ptr;
724 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
725 return ret;
729 /******************************************************************
730 * load_library_as_datafile
732 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
734 static const WCHAR dotDLL[] = {'.','d','l','l',0};
736 WCHAR filenameW[MAX_PATH];
737 HANDLE hFile = INVALID_HANDLE_VALUE;
738 HANDLE mapping;
739 HMODULE module;
741 *hmod = 0;
743 if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
744 filenameW, NULL ))
746 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
747 NULL, OPEN_EXISTING, 0, 0 );
749 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
751 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
752 CloseHandle( hFile );
753 if (!mapping) return FALSE;
755 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
756 CloseHandle( mapping );
757 if (!module) return FALSE;
759 /* make sure it's a valid PE file */
760 if (!RtlImageNtHeader(module))
762 UnmapViewOfFile( module );
763 return FALSE;
765 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
766 return TRUE;
770 /******************************************************************
771 * load_library
773 * Helper for LoadLibraryExA/W.
775 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
777 NTSTATUS nts;
778 HMODULE hModule;
779 WCHAR *load_path;
781 if (flags & LOAD_LIBRARY_AS_DATAFILE)
783 /* The method in load_library_as_datafile allows searching for the
784 * 'native' libraries only
786 if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
787 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
788 /* Fallback to normal behaviour */
791 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
792 nts = LdrLoadDll( load_path, flags, libname, &hModule );
793 HeapFree( GetProcessHeap(), 0, load_path );
794 if (nts != STATUS_SUCCESS)
796 hModule = 0;
797 SetLastError( RtlNtStatusToDosError( nts ) );
799 return hModule;
803 /******************************************************************
804 * LoadLibraryExA (KERNEL32.@)
806 * Load a dll file into the process address space.
808 * PARAMS
809 * libname [I] Name of the file to load
810 * hfile [I] Reserved, must be 0.
811 * flags [I] Flags for loading the dll
813 * RETURNS
814 * Success: A handle to the loaded dll.
815 * Failure: A NULL handle. Use GetLastError() to determine the cause.
817 * NOTES
818 * The HFILE parameter is not used and marked reserved in the SDK. I can
819 * only guess that it should force a file to be mapped, but I rather
820 * ignore the parameter because it would be extremely difficult to
821 * integrate this with different types of module representations.
823 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
825 WCHAR *libnameW;
827 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
828 return LoadLibraryExW( libnameW, hfile, flags );
831 /***********************************************************************
832 * LoadLibraryExW (KERNEL32.@)
834 * Unicode version of LoadLibraryExA.
836 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
838 UNICODE_STRING wstr;
839 HMODULE res;
841 if (!libnameW)
843 SetLastError(ERROR_INVALID_PARAMETER);
844 return 0;
846 RtlInitUnicodeString( &wstr, libnameW );
847 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
848 return load_library( &wstr, flags );
850 /* Library name has trailing spaces */
851 RtlCreateUnicodeString( &wstr, libnameW );
852 while (wstr.Length > sizeof(WCHAR) &&
853 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
855 wstr.Length -= sizeof(WCHAR);
857 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
858 res = load_library( &wstr, flags );
859 RtlFreeUnicodeString( &wstr );
860 return res;
863 /***********************************************************************
864 * LoadLibraryA (KERNEL32.@)
866 * Load a dll file into the process address space.
868 * PARAMS
869 * libname [I] Name of the file to load
871 * RETURNS
872 * Success: A handle to the loaded dll.
873 * Failure: A NULL handle. Use GetLastError() to determine the cause.
875 * NOTES
876 * See LoadLibraryExA().
878 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
880 return LoadLibraryExA(libname, 0, 0);
883 /***********************************************************************
884 * LoadLibraryW (KERNEL32.@)
886 * Unicode version of LoadLibraryA.
888 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
890 return LoadLibraryExW(libnameW, 0, 0);
893 /***********************************************************************
894 * FreeLibrary (KERNEL32.@)
895 * FreeLibrary32 (KERNEL.486)
897 * Free a dll loaded into the process address space.
899 * PARAMS
900 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
902 * RETURNS
903 * Success: TRUE. The dll is removed if it is not still in use.
904 * Failure: FALSE. Use GetLastError() to determine the cause.
906 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
908 BOOL retv = FALSE;
909 NTSTATUS nts;
911 if (!hLibModule)
913 SetLastError( ERROR_INVALID_HANDLE );
914 return FALSE;
917 if ((ULONG_PTR)hLibModule & 1)
919 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
920 char *ptr = (char *)hLibModule - 1;
921 UnmapViewOfFile( ptr );
922 return TRUE;
925 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
926 else SetLastError( RtlNtStatusToDosError( nts ) );
928 return retv;
931 /***********************************************************************
932 * GetProcAddress (KERNEL32.@)
934 * Find the address of an exported symbol in a loaded dll.
936 * PARAMS
937 * hModule [I] Handle to the dll returned by LoadLibraryA().
938 * function [I] Name of the symbol, or an integer ordinal number < 16384
940 * RETURNS
941 * Success: A pointer to the symbol in the process address space.
942 * Failure: NULL. Use GetLastError() to determine the cause.
944 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
946 NTSTATUS nts;
947 FARPROC fp;
949 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
951 if (HIWORD(function))
953 ANSI_STRING str;
955 RtlInitAnsiString( &str, function );
956 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
958 else
959 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
960 if (nts != STATUS_SUCCESS)
962 SetLastError( RtlNtStatusToDosError( nts ) );
963 fp = NULL;
965 return fp;
968 /***********************************************************************
969 * GetProcAddress32 (KERNEL.453)
971 * Find the address of an exported symbol in a loaded dll.
973 * PARAMS
974 * hModule [I] Handle to the dll returned by LoadLibraryA().
975 * function [I] Name of the symbol, or an integer ordinal number < 16384
977 * RETURNS
978 * Success: A pointer to the symbol in the process address space.
979 * Failure: NULL. Use GetLastError() to determine the cause.
981 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
983 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
984 return GetProcAddress( hModule, function );
988 /***********************************************************************
989 * DelayLoadFailureHook (KERNEL32.@)
991 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
993 ULONG_PTR args[2];
995 if ((ULONG_PTR)function >> 16)
996 ERR( "failed to delay load %s.%s\n", name, function );
997 else
998 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
999 args[0] = (ULONG_PTR)name;
1000 args[1] = (ULONG_PTR)function;
1001 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1002 return NULL;