jscript: Added postfix increment expression implementation.
[wine.git] / dlls / kernel32 / module.c
blob1b259e57d2ad09de84bf07a5f56614763f7f0822
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 <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 "kernel_private.h"
41 #include "wine/exception.h"
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(module);
47 static WCHAR *dll_directory; /* extra path for SetDllDirectoryW */
49 static CRITICAL_SECTION dlldir_section;
50 static CRITICAL_SECTION_DEBUG critsect_debug =
52 0, 0, &dlldir_section,
53 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
54 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
56 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
59 /****************************************************************************
60 * GetDllDirectoryA (KERNEL32.@)
62 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
64 DWORD len;
66 RtlEnterCriticalSection( &dlldir_section );
67 len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
68 if (buffer && buf_len > len)
70 if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
71 else *buffer = 0;
73 else
75 len++; /* for terminating null */
76 if (buffer) *buffer = 0;
78 RtlLeaveCriticalSection( &dlldir_section );
79 return len;
83 /****************************************************************************
84 * GetDllDirectoryW (KERNEL32.@)
86 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
88 DWORD len;
90 RtlEnterCriticalSection( &dlldir_section );
91 len = dll_directory ? strlenW( dll_directory ) : 0;
92 if (buffer && buf_len > len)
94 if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
95 else *buffer = 0;
97 else
99 len++; /* for terminating null */
100 if (buffer) *buffer = 0;
102 RtlLeaveCriticalSection( &dlldir_section );
103 return len;
107 /****************************************************************************
108 * SetDllDirectoryA (KERNEL32.@)
110 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
112 WCHAR *dirW;
113 BOOL ret;
115 if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
116 ret = SetDllDirectoryW( dirW );
117 HeapFree( GetProcessHeap(), 0, dirW );
118 return ret;
122 /****************************************************************************
123 * SetDllDirectoryW (KERNEL32.@)
125 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
127 WCHAR *newdir = NULL;
129 if (dir)
131 DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
132 if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
134 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
135 return FALSE;
137 memcpy( newdir, dir, len );
140 RtlEnterCriticalSection( &dlldir_section );
141 HeapFree( GetProcessHeap(), 0, dll_directory );
142 dll_directory = newdir;
143 RtlLeaveCriticalSection( &dlldir_section );
144 return TRUE;
148 /****************************************************************************
149 * DisableThreadLibraryCalls (KERNEL32.@)
151 * Inform the module loader that thread notifications are not required for a dll.
153 * PARAMS
154 * hModule [I] Module handle to skip calls for
156 * RETURNS
157 * Success: TRUE. Thread attach and detach notifications will not be sent
158 * to hModule.
159 * Failure: FALSE. Use GetLastError() to determine the cause.
161 * NOTES
162 * This is typically called from the dll entry point of a dll during process
163 * attachment, for dlls that do not need to process thread notifications.
165 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
167 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
168 if (nts == STATUS_SUCCESS) return TRUE;
170 SetLastError( RtlNtStatusToDosError( nts ) );
171 return FALSE;
175 /* Check whether a file is an OS/2 or a very old Windows executable
176 * by testing on import of KERNEL.
178 * FIXME: is reading the module imports the only way of discerning
179 * old Windows binaries from OS/2 ones ? At least it seems so...
181 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
182 const IMAGE_OS2_HEADER *ne)
184 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
185 enum binary_type ret = BINARY_OS216;
186 LPWORD modtab = NULL;
187 LPSTR nametab = NULL;
188 DWORD len;
189 int i;
191 /* read modref table */
192 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
193 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
194 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
195 || (len != ne->ne_cmod*sizeof(WORD)) )
196 goto broken;
198 /* read imported names table */
199 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
200 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
201 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
202 || (len != ne->ne_enttab - ne->ne_imptab) )
203 goto broken;
205 for (i=0; i < ne->ne_cmod; i++)
207 LPSTR module = &nametab[modtab[i]];
208 TRACE("modref: %.*s\n", module[0], &module[1]);
209 if (!(strncmp(&module[1], "KERNEL", module[0])))
210 { /* very old Windows file */
211 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
212 ret = BINARY_WIN16;
213 goto good;
217 broken:
218 ERR("Hmm, an error occurred. Is this binary file broken?\n");
220 good:
221 HeapFree( GetProcessHeap(), 0, modtab);
222 HeapFree( GetProcessHeap(), 0, nametab);
223 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
224 return ret;
227 /***********************************************************************
228 * MODULE_GetBinaryType
230 enum binary_type MODULE_GetBinaryType( HANDLE hfile, void **res_start, void **res_end )
232 union
234 struct
236 unsigned char magic[4];
237 unsigned char ignored[12];
238 unsigned short type;
239 } elf;
240 struct
242 unsigned long magic;
243 unsigned long cputype;
244 unsigned long cpusubtype;
245 unsigned long filetype;
246 } macho;
247 IMAGE_DOS_HEADER mz;
248 } header;
250 DWORD len;
252 /* Seek to the start of the file and read the header information. */
253 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
254 return BINARY_UNKNOWN;
255 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
256 return BINARY_UNKNOWN;
258 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
260 /* FIXME: we don't bother to check byte order, architecture, etc. */
261 switch(header.elf.type)
263 case 2: return BINARY_UNIX_EXE;
264 case 3: return BINARY_UNIX_LIB;
266 return BINARY_UNKNOWN;
269 /* Mach-o File with Endian set to Big Endian or Little Endian */
270 if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
272 switch(header.macho.filetype)
274 case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
276 return BINARY_UNKNOWN;
279 /* Not ELF, try DOS */
281 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
283 union
285 IMAGE_OS2_HEADER os2;
286 IMAGE_NT_HEADERS nt;
287 } ext_header;
289 /* We do have a DOS image so we will now try to seek into
290 * the file by the amount indicated by the field
291 * "Offset to extended header" and read in the
292 * "magic" field information at that location.
293 * This will tell us if there is more header information
294 * to read or not.
296 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
297 return BINARY_DOS;
298 if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4)
299 return BINARY_DOS;
301 /* Reading the magic field succeeded so
302 * we will try to determine what type it is.
304 if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
306 if (len >= sizeof(ext_header.nt.FileHeader))
308 if (len < sizeof(ext_header.nt)) /* clear remaining part of header if missing */
309 memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
310 if (res_start) *res_start = (void *)ext_header.nt.OptionalHeader.ImageBase;
311 if (res_end) *res_end = (void *)(ext_header.nt.OptionalHeader.ImageBase +
312 ext_header.nt.OptionalHeader.SizeOfImage);
313 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
314 return BINARY_PE_EXE;
316 return BINARY_DOS;
319 if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
321 /* This is a Windows executable (NE) header. This can
322 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
323 * DOS program (running under a DOS extender). To decide
324 * which, we'll have to read the NE header.
326 if (len >= sizeof(ext_header.os2))
328 switch ( ext_header.os2.ne_exetyp )
330 case 1: return BINARY_OS216; /* OS/2 */
331 case 2: return BINARY_WIN16; /* Windows */
332 case 3: return BINARY_DOS; /* European MS-DOS 4.x */
333 case 4: return BINARY_WIN16; /* Windows 386; FIXME: is this 32bit??? */
334 case 5: return BINARY_DOS; /* BOSS, Borland Operating System Services */
335 /* other types, e.g. 0 is: "unknown" */
336 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2);
339 /* Couldn't read header, so abort. */
340 return BINARY_DOS;
343 /* Unknown extended header, but this file is nonetheless DOS-executable. */
344 return BINARY_DOS;
347 return BINARY_UNKNOWN;
350 /***********************************************************************
351 * GetBinaryTypeW [KERNEL32.@]
353 * Determine whether a file is executable, and if so, what kind.
355 * PARAMS
356 * lpApplicationName [I] Path of the file to check
357 * lpBinaryType [O] Destination for the binary type
359 * RETURNS
360 * TRUE, if the file is an executable, in which case lpBinaryType is set.
361 * FALSE, if the file is not an executable or if the function fails.
363 * NOTES
364 * The type of executable is a property that determines which subsystem an
365 * executable file runs under. lpBinaryType can be set to one of the following
366 * values:
367 * SCS_32BIT_BINARY: A Win32 based application
368 * SCS_DOS_BINARY: An MS-Dos based application
369 * SCS_WOW_BINARY: A Win16 based application
370 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
371 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
372 * SCS_OS216_BINARY: A 16bit OS/2 based application
374 * To find the binary type, this function reads in the files header information.
375 * If extended header information is not present it will assume that the file
376 * is a DOS executable. If extended header information is present it will
377 * determine if the file is a 16 or 32 bit Windows executable by checking the
378 * flags in the header.
380 * ".com" and ".pif" files are only recognized by their file name extension,
381 * as per native Windows.
383 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
385 BOOL ret = FALSE;
386 HANDLE hfile;
388 TRACE("%s\n", debugstr_w(lpApplicationName) );
390 /* Sanity check.
392 if ( lpApplicationName == NULL || lpBinaryType == NULL )
393 return FALSE;
395 /* Open the file indicated by lpApplicationName for reading.
397 hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
398 NULL, OPEN_EXISTING, 0, 0 );
399 if ( hfile == INVALID_HANDLE_VALUE )
400 return FALSE;
402 /* Check binary type
404 switch(MODULE_GetBinaryType( hfile, NULL, NULL ))
406 case BINARY_UNKNOWN:
408 static const WCHAR comW[] = { '.','C','O','M',0 };
409 static const WCHAR pifW[] = { '.','P','I','F',0 };
410 const WCHAR *ptr;
412 /* try to determine from file name */
413 ptr = strrchrW( lpApplicationName, '.' );
414 if (!ptr) break;
415 if (!strcmpiW( ptr, comW ))
417 *lpBinaryType = SCS_DOS_BINARY;
418 ret = TRUE;
420 else if (!strcmpiW( ptr, pifW ))
422 *lpBinaryType = SCS_PIF_BINARY;
423 ret = TRUE;
425 break;
427 case BINARY_PE_EXE:
428 case BINARY_PE_DLL:
429 *lpBinaryType = SCS_32BIT_BINARY;
430 ret = TRUE;
431 break;
432 case BINARY_WIN16:
433 *lpBinaryType = SCS_WOW_BINARY;
434 ret = TRUE;
435 break;
436 case BINARY_OS216:
437 *lpBinaryType = SCS_OS216_BINARY;
438 ret = TRUE;
439 break;
440 case BINARY_DOS:
441 *lpBinaryType = SCS_DOS_BINARY;
442 ret = TRUE;
443 break;
444 case BINARY_UNIX_EXE:
445 case BINARY_UNIX_LIB:
446 ret = FALSE;
447 break;
450 CloseHandle( hfile );
451 return ret;
454 /***********************************************************************
455 * GetBinaryTypeA [KERNEL32.@]
456 * GetBinaryType [KERNEL32.@]
458 * See GetBinaryTypeW.
460 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
462 ANSI_STRING app_nameA;
463 NTSTATUS status;
465 TRACE("%s\n", debugstr_a(lpApplicationName));
467 /* Sanity check.
469 if ( lpApplicationName == NULL || lpBinaryType == NULL )
470 return FALSE;
472 RtlInitAnsiString(&app_nameA, lpApplicationName);
473 status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
474 &app_nameA, FALSE);
475 if (!status)
476 return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
478 SetLastError(RtlNtStatusToDosError(status));
479 return FALSE;
482 /***********************************************************************
483 * GetModuleHandleExA (KERNEL32.@)
485 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
487 WCHAR *nameW;
489 if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
490 return GetModuleHandleExW( flags, (LPCWSTR)name, module );
492 if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
493 return GetModuleHandleExW( flags, nameW, module );
496 /***********************************************************************
497 * GetModuleHandleExW (KERNEL32.@)
499 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
501 NTSTATUS status = STATUS_SUCCESS;
502 HMODULE ret;
503 ULONG magic;
505 /* if we are messing with the refcount, grab the loader lock */
506 if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
507 !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
508 LdrLockLoaderLock( 0, NULL, &magic );
510 if (!name)
512 ret = NtCurrentTeb()->Peb->ImageBaseAddress;
514 else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
516 void *dummy;
517 if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
519 else
521 UNICODE_STRING wstr;
522 RtlInitUnicodeString( &wstr, name );
523 status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
526 if (status == STATUS_SUCCESS)
528 if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
529 FIXME( "should pin refcount for %p\n", ret );
530 else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
531 LdrAddRefDll( 0, ret );
533 else SetLastError( RtlNtStatusToDosError( status ) );
535 if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
536 !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
537 LdrUnlockLoaderLock( 0, magic );
539 if (module) *module = ret;
540 return (status == STATUS_SUCCESS);
543 /***********************************************************************
544 * GetModuleHandleA (KERNEL32.@)
545 * GetModuleHandle32 (KERNEL.488)
547 * Get the handle of a dll loaded into the process address space.
549 * PARAMS
550 * module [I] Name of the dll
552 * RETURNS
553 * Success: A handle to the loaded dll.
554 * Failure: A NULL handle. Use GetLastError() to determine the cause.
556 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
558 HMODULE ret;
560 if (!GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
561 return ret;
564 /***********************************************************************
565 * GetModuleHandleW (KERNEL32.@)
567 * Unicode version of GetModuleHandleA.
569 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
571 HMODULE ret;
573 if (!GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
574 return ret;
578 /***********************************************************************
579 * GetModuleFileNameA (KERNEL32.@)
580 * GetModuleFileName32 (KERNEL.487)
582 * Get the file name of a loaded module from its handle.
584 * RETURNS
585 * Success: The length of the file name, excluding the terminating NUL.
586 * Failure: 0. Use GetLastError() to determine the cause.
588 * NOTES
589 * This function always returns the long path of hModule (as opposed to
590 * GetModuleFileName16() which returns short paths when the modules version
591 * field is < 4.0).
592 * The function doesn't write a terminating '\0' if the buffer is too
593 * small.
595 DWORD WINAPI GetModuleFileNameA(
596 HMODULE hModule, /* [in] Module handle (32 bit) */
597 LPSTR lpFileName, /* [out] Destination for file name */
598 DWORD size ) /* [in] Size of lpFileName in characters */
600 LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
601 DWORD len;
603 if (!filenameW)
605 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
606 return 0;
608 if ((len = GetModuleFileNameW( hModule, filenameW, size )))
610 len = FILE_name_WtoA( filenameW, len, lpFileName, size );
611 if (len < size)
612 lpFileName[len] = '\0';
613 else
614 SetLastError( ERROR_INSUFFICIENT_BUFFER );
616 HeapFree( GetProcessHeap(), 0, filenameW );
617 return len;
620 /***********************************************************************
621 * GetModuleFileNameW (KERNEL32.@)
623 * Unicode version of GetModuleFileNameA.
625 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
627 ULONG magic, len = 0;
628 LDR_MODULE *pldr;
629 NTSTATUS nts;
630 WIN16_SUBSYSTEM_TIB *win16_tib;
632 if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
634 len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
635 memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
636 if (len < size) lpFileName[len] = '\0';
637 goto done;
640 LdrLockLoaderLock( 0, NULL, &magic );
642 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
643 nts = LdrFindEntryForAddress( hModule, &pldr );
644 if (nts == STATUS_SUCCESS)
646 len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
647 memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
648 if (len < size)
649 lpFileName[len] = '\0';
650 else
651 SetLastError( ERROR_INSUFFICIENT_BUFFER );
653 else SetLastError( RtlNtStatusToDosError( nts ) );
655 LdrUnlockLoaderLock( 0, magic );
656 done:
657 TRACE( "%s\n", debugstr_wn(lpFileName, len) );
658 return len;
662 /***********************************************************************
663 * get_dll_system_path
665 static const WCHAR *get_dll_system_path(void)
667 static WCHAR *cached_path;
669 if (!cached_path)
671 WCHAR *p, *path;
672 int len = 3;
674 len += 2 * GetSystemDirectoryW( NULL, 0 );
675 len += GetWindowsDirectoryW( NULL, 0 );
676 p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
677 *p++ = '.';
678 *p++ = ';';
679 GetSystemDirectoryW( p, path + len - p);
680 p += strlenW(p);
681 /* if system directory ends in "32" add 16-bit version too */
682 if (p[-2] == '3' && p[-1] == '2')
684 *p++ = ';';
685 GetSystemDirectoryW( p, path + len - p);
686 p += strlenW(p) - 2;
688 *p++ = ';';
689 GetWindowsDirectoryW( p, path + len - p);
690 cached_path = path;
692 return cached_path;
695 /******************************************************************
696 * get_module_path_end
698 * Returns the end of the directory component of the module path.
700 static inline const WCHAR *get_module_path_end(const WCHAR *module)
702 const WCHAR *p;
703 const WCHAR *mod_end = module;
704 if (!module) return mod_end;
706 if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
707 if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
708 if (mod_end == module + 2 && module[1] == ':') mod_end++;
709 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
711 return mod_end;
714 /******************************************************************
715 * MODULE_get_dll_load_path
717 * Compute the load path to use for a given dll.
718 * Returned pointer must be freed by caller.
720 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
722 static const WCHAR pathW[] = {'P','A','T','H',0};
724 const WCHAR *system_path = get_dll_system_path();
725 const WCHAR *mod_end = NULL;
726 UNICODE_STRING name, value;
727 WCHAR *p, *ret;
728 int len = 0, path_len = 0;
730 /* adjust length for module name */
732 if (module)
733 mod_end = get_module_path_end( module );
734 /* if module is NULL or doesn't contain a path, fall back to directory
735 * process was loaded from */
736 if (module == mod_end)
738 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
739 mod_end = get_module_path_end( module );
741 len += (mod_end - module) + 1;
743 len += strlenW( system_path ) + 2;
745 /* get the PATH variable */
747 RtlInitUnicodeString( &name, pathW );
748 value.Length = 0;
749 value.MaximumLength = 0;
750 value.Buffer = NULL;
751 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
752 path_len = value.Length;
754 RtlEnterCriticalSection( &dlldir_section );
755 if (dll_directory) len += strlenW(dll_directory) + 1;
756 if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
758 if (module)
760 memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
761 p += (mod_end - module);
762 *p++ = ';';
764 if (dll_directory)
766 strcpyW( p, dll_directory );
767 p += strlenW(p);
768 *p++ = ';';
771 RtlLeaveCriticalSection( &dlldir_section );
772 if (!ret) return NULL;
774 strcpyW( p, system_path );
775 p += strlenW(p);
776 *p++ = ';';
777 value.Buffer = p;
778 value.MaximumLength = path_len;
780 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
782 WCHAR *new_ptr;
784 /* grow the buffer and retry */
785 path_len = value.Length;
786 if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
788 HeapFree( GetProcessHeap(), 0, ret );
789 return NULL;
791 value.Buffer = new_ptr + (value.Buffer - ret);
792 value.MaximumLength = path_len;
793 ret = new_ptr;
795 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
796 return ret;
800 /******************************************************************
801 * load_library_as_datafile
803 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
805 static const WCHAR dotDLL[] = {'.','d','l','l',0};
807 WCHAR filenameW[MAX_PATH];
808 HANDLE hFile = INVALID_HANDLE_VALUE;
809 HANDLE mapping;
810 HMODULE module;
812 *hmod = 0;
814 if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
815 filenameW, NULL ))
817 hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
818 NULL, OPEN_EXISTING, 0, 0 );
820 if (hFile == INVALID_HANDLE_VALUE) return FALSE;
822 mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
823 CloseHandle( hFile );
824 if (!mapping) return FALSE;
826 module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
827 CloseHandle( mapping );
828 if (!module) return FALSE;
830 /* make sure it's a valid PE file */
831 if (!RtlImageNtHeader(module))
833 UnmapViewOfFile( module );
834 return FALSE;
836 *hmod = (HMODULE)((char *)module + 1); /* set low bit of handle to indicate datafile module */
837 return TRUE;
841 /******************************************************************
842 * load_library
844 * Helper for LoadLibraryExA/W.
846 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
848 NTSTATUS nts;
849 HMODULE hModule;
850 WCHAR *load_path;
852 load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
854 if (flags & LOAD_LIBRARY_AS_DATAFILE)
856 ULONG magic;
858 LdrLockLoaderLock( 0, NULL, &magic );
859 if (!(nts = LdrGetDllHandle( load_path, flags, libname, &hModule )))
861 LdrAddRefDll( 0, hModule );
862 LdrUnlockLoaderLock( 0, magic );
863 goto done;
865 LdrUnlockLoaderLock( 0, magic );
867 /* The method in load_library_as_datafile allows searching for the
868 * 'native' libraries only
870 if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
871 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
872 /* Fallback to normal behaviour */
875 nts = LdrLoadDll( load_path, flags, libname, &hModule );
876 if (nts != STATUS_SUCCESS)
878 hModule = 0;
879 SetLastError( RtlNtStatusToDosError( nts ) );
881 done:
882 HeapFree( GetProcessHeap(), 0, load_path );
883 return hModule;
887 /******************************************************************
888 * LoadLibraryExA (KERNEL32.@)
890 * Load a dll file into the process address space.
892 * PARAMS
893 * libname [I] Name of the file to load
894 * hfile [I] Reserved, must be 0.
895 * flags [I] Flags for loading the dll
897 * RETURNS
898 * Success: A handle to the loaded dll.
899 * Failure: A NULL handle. Use GetLastError() to determine the cause.
901 * NOTES
902 * The HFILE parameter is not used and marked reserved in the SDK. I can
903 * only guess that it should force a file to be mapped, but I rather
904 * ignore the parameter because it would be extremely difficult to
905 * integrate this with different types of module representations.
907 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
909 WCHAR *libnameW;
911 if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
912 return LoadLibraryExW( libnameW, hfile, flags );
915 /***********************************************************************
916 * LoadLibraryExW (KERNEL32.@)
918 * Unicode version of LoadLibraryExA.
920 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
922 UNICODE_STRING wstr;
923 HMODULE res;
925 if (hfile)
927 SetLastError(ERROR_INVALID_PARAMETER);
928 return 0;
931 if (!libnameW)
933 SetLastError(ERROR_INVALID_PARAMETER);
934 return 0;
936 RtlInitUnicodeString( &wstr, libnameW );
937 if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
938 return load_library( &wstr, flags );
940 /* Library name has trailing spaces */
941 RtlCreateUnicodeString( &wstr, libnameW );
942 while (wstr.Length > sizeof(WCHAR) &&
943 wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
945 wstr.Length -= sizeof(WCHAR);
947 wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
948 res = load_library( &wstr, flags );
949 RtlFreeUnicodeString( &wstr );
950 return res;
953 /***********************************************************************
954 * LoadLibraryA (KERNEL32.@)
956 * Load a dll file into the process address space.
958 * PARAMS
959 * libname [I] Name of the file to load
961 * RETURNS
962 * Success: A handle to the loaded dll.
963 * Failure: A NULL handle. Use GetLastError() to determine the cause.
965 * NOTES
966 * See LoadLibraryExA().
968 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
970 return LoadLibraryExA(libname, 0, 0);
973 /***********************************************************************
974 * LoadLibraryW (KERNEL32.@)
976 * Unicode version of LoadLibraryA.
978 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
980 return LoadLibraryExW(libnameW, 0, 0);
983 /***********************************************************************
984 * FreeLibrary (KERNEL32.@)
985 * FreeLibrary32 (KERNEL.486)
987 * Free a dll loaded into the process address space.
989 * PARAMS
990 * hLibModule [I] Handle to the dll returned by LoadLibraryA().
992 * RETURNS
993 * Success: TRUE. The dll is removed if it is not still in use.
994 * Failure: FALSE. Use GetLastError() to determine the cause.
996 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
998 BOOL retv = FALSE;
999 NTSTATUS nts;
1001 if (!hLibModule)
1003 SetLastError( ERROR_INVALID_HANDLE );
1004 return FALSE;
1007 if ((ULONG_PTR)hLibModule & 1)
1009 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1010 char *ptr = (char *)hLibModule - 1;
1011 UnmapViewOfFile( ptr );
1012 return TRUE;
1015 if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1016 else SetLastError( RtlNtStatusToDosError( nts ) );
1018 return retv;
1021 /***********************************************************************
1022 * GetProcAddress (KERNEL32.@)
1024 * Find the address of an exported symbol in a loaded dll.
1026 * PARAMS
1027 * hModule [I] Handle to the dll returned by LoadLibraryA().
1028 * function [I] Name of the symbol, or an integer ordinal number < 16384
1030 * RETURNS
1031 * Success: A pointer to the symbol in the process address space.
1032 * Failure: NULL. Use GetLastError() to determine the cause.
1034 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1036 NTSTATUS nts;
1037 FARPROC fp;
1039 if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1041 if (HIWORD(function))
1043 ANSI_STRING str;
1045 RtlInitAnsiString( &str, function );
1046 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1048 else
1049 nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1050 if (nts != STATUS_SUCCESS)
1052 SetLastError( RtlNtStatusToDosError( nts ) );
1053 fp = NULL;
1055 return fp;
1058 /***********************************************************************
1059 * GetProcAddress32 (KERNEL.453)
1061 * Find the address of an exported symbol in a loaded dll.
1063 * PARAMS
1064 * hModule [I] Handle to the dll returned by LoadLibraryA().
1065 * function [I] Name of the symbol, or an integer ordinal number < 16384
1067 * RETURNS
1068 * Success: A pointer to the symbol in the process address space.
1069 * Failure: NULL. Use GetLastError() to determine the cause.
1071 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1073 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
1074 return GetProcAddress( hModule, function );
1078 /***********************************************************************
1079 * DelayLoadFailureHook (KERNEL32.@)
1081 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1083 ULONG_PTR args[2];
1085 if ((ULONG_PTR)function >> 16)
1086 ERR( "failed to delay load %s.%s\n", name, function );
1087 else
1088 ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1089 args[0] = (ULONG_PTR)name;
1090 args[1] = (ULONG_PTR)function;
1091 RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1092 return NULL;