msi: Don't ignore disabled components when resolving install states.
[wine] / dlls / kernel32 / module.c
1 /*
2  * Modules
3  *
4  * Copyright 1995 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
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
41 #include "wine/exception.h"
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(module);
46
47 #define NE_FFLAGS_LIBMODULE 0x8000
48
49 static WCHAR *dll_directory;  /* extra path for SetDllDirectoryW */
50
51 static CRITICAL_SECTION dlldir_section;
52 static CRITICAL_SECTION_DEBUG critsect_debug =
53 {
54     0, 0, &dlldir_section,
55     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
56       0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
57 };
58 static CRITICAL_SECTION dlldir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
59
60
61 /****************************************************************************
62  *              GetDllDirectoryA   (KERNEL32.@)
63  */
64 DWORD WINAPI GetDllDirectoryA( DWORD buf_len, LPSTR buffer )
65 {
66     DWORD len;
67
68     RtlEnterCriticalSection( &dlldir_section );
69     len = dll_directory ? FILE_name_WtoA( dll_directory, strlenW(dll_directory), NULL, 0 ) : 0;
70     if (buffer && buf_len > len)
71     {
72         if (dll_directory) FILE_name_WtoA( dll_directory, -1, buffer, buf_len );
73         else *buffer = 0;
74     }
75     else
76     {
77         len++;  /* for terminating null */
78         if (buffer) *buffer = 0;
79     }
80     RtlLeaveCriticalSection( &dlldir_section );
81     return len;
82 }
83
84
85 /****************************************************************************
86  *              GetDllDirectoryW   (KERNEL32.@)
87  */
88 DWORD WINAPI GetDllDirectoryW( DWORD buf_len, LPWSTR buffer )
89 {
90     DWORD len;
91
92     RtlEnterCriticalSection( &dlldir_section );
93     len = dll_directory ? strlenW( dll_directory ) : 0;
94     if (buffer && buf_len > len)
95     {
96         if (dll_directory) memcpy( buffer, dll_directory, (len + 1) * sizeof(WCHAR) );
97         else *buffer = 0;
98     }
99     else
100     {
101         len++;  /* for terminating null */
102         if (buffer) *buffer = 0;
103     }
104     RtlLeaveCriticalSection( &dlldir_section );
105     return len;
106 }
107
108
109 /****************************************************************************
110  *              SetDllDirectoryA   (KERNEL32.@)
111  */
112 BOOL WINAPI SetDllDirectoryA( LPCSTR dir )
113 {
114     WCHAR *dirW;
115     BOOL ret;
116
117     if (!(dirW = FILE_name_AtoW( dir, TRUE ))) return FALSE;
118     ret = SetDllDirectoryW( dirW );
119     HeapFree( GetProcessHeap(), 0, dirW );
120     return ret;
121 }
122
123
124 /****************************************************************************
125  *              SetDllDirectoryW   (KERNEL32.@)
126  */
127 BOOL WINAPI SetDllDirectoryW( LPCWSTR dir )
128 {
129     WCHAR *newdir = NULL;
130
131     if (dir)
132     {
133         DWORD len = (strlenW(dir) + 1) * sizeof(WCHAR);
134         if (!(newdir = HeapAlloc( GetProcessHeap(), 0, len )))
135         {
136             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
137             return FALSE;
138         }
139         memcpy( newdir, dir, len );
140     }
141
142     RtlEnterCriticalSection( &dlldir_section );
143     HeapFree( GetProcessHeap(), 0, dll_directory );
144     dll_directory = newdir;
145     RtlLeaveCriticalSection( &dlldir_section );
146     return TRUE;
147 }
148
149
150 /****************************************************************************
151  *              DisableThreadLibraryCalls (KERNEL32.@)
152  *
153  * Inform the module loader that thread notifications are not required for a dll.
154  *
155  * PARAMS
156  *  hModule [I] Module handle to skip calls for
157  *
158  * RETURNS
159  *  Success: TRUE. Thread attach and detach notifications will not be sent
160  *           to hModule.
161  *  Failure: FALSE. Use GetLastError() to determine the cause.
162  *
163  * NOTES
164  *  This is typically called from the dll entry point of a dll during process
165  *  attachment, for dlls that do not need to process thread notifications.
166  */
167 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
168 {
169     NTSTATUS    nts = LdrDisableThreadCalloutsForDll( hModule );
170     if (nts == STATUS_SUCCESS) return TRUE;
171
172     SetLastError( RtlNtStatusToDosError( nts ) );
173     return FALSE;
174 }
175
176
177 /* Check whether a file is an OS/2 or a very old Windows executable
178  * by testing on import of KERNEL.
179  *
180  * FIXME: is reading the module imports the only way of discerning
181  *        old Windows binaries from OS/2 ones ? At least it seems so...
182  */
183 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz, const IMAGE_OS2_HEADER *ne)
184 {
185     DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
186     DWORD ret = BINARY_OS216;
187     LPWORD modtab = NULL;
188     LPSTR nametab = NULL;
189     DWORD len;
190     int i;
191
192     /* read modref table */
193     if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
194       || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
195       || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
196       || (len != ne->ne_cmod*sizeof(WORD)) )
197         goto broken;
198
199     /* read imported names table */
200     if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
201       || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
202       || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
203       || (len != ne->ne_enttab - ne->ne_imptab) )
204         goto broken;
205
206     for (i=0; i < ne->ne_cmod; i++)
207     {
208         LPSTR module = &nametab[modtab[i]];
209         TRACE("modref: %.*s\n", module[0], &module[1]);
210         if (!(strncmp(&module[1], "KERNEL", module[0])))
211         { /* very old Windows file */
212             MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
213             ret = BINARY_WIN16;
214             goto good;
215         }
216     }
217
218 broken:
219     ERR("Hmm, an error occurred. Is this binary file broken?\n");
220
221 good:
222     HeapFree( GetProcessHeap(), 0, modtab);
223     HeapFree( GetProcessHeap(), 0, nametab);
224     SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
225     return ret;
226 }
227
228 /***********************************************************************
229  *           MODULE_GetBinaryType
230  */
231 void MODULE_get_binary_info( HANDLE hfile, struct binary_info *info )
232 {
233     union
234     {
235         struct
236         {
237             unsigned char magic[4];
238             unsigned char class;
239             unsigned char data;
240             unsigned char version;
241             unsigned char ignored[9];
242             unsigned short type;
243             unsigned short machine;
244         } elf;
245         struct
246         {
247             unsigned int magic;
248             unsigned int cputype;
249             unsigned int cpusubtype;
250             unsigned int filetype;
251         } macho;
252         IMAGE_DOS_HEADER mz;
253     } header;
254
255     DWORD len;
256
257     memset( info, 0, sizeof(*info) );
258
259     /* Seek to the start of the file and read the header information. */
260     if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1) return;
261     if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header)) return;
262
263     if (!memcmp( header.elf.magic, "\177ELF", 4 ))
264     {
265         if (header.elf.class == 2) info->flags |= BINARY_FLAG_64BIT;
266         /* FIXME: we don't bother to check byte order, architecture, etc. */
267         switch(header.elf.type)
268         {
269         case 2: info->type = BINARY_UNIX_EXE; break;
270         case 3: info->type = BINARY_UNIX_LIB; break;
271         }
272     }
273     /* Mach-o File with Endian set to Big Endian or Little Endian */
274     else if (header.macho.magic == 0xfeedface || header.macho.magic == 0xcefaedfe)
275     {
276         if ((header.macho.cputype >> 24) == 1) info->flags |= BINARY_FLAG_64BIT;
277         switch(header.macho.filetype)
278         {
279         case 2: info->type = BINARY_UNIX_EXE; break;
280         case 8: info->type = BINARY_UNIX_LIB; break;
281         }
282     }
283     /* Not ELF, try DOS */
284     else if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
285     {
286         union
287         {
288             IMAGE_OS2_HEADER os2;
289             IMAGE_NT_HEADERS32 nt;
290         } ext_header;
291
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.
298          */
299         info->type = BINARY_DOS;
300         if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1) return;
301         if (!ReadFile( hfile, &ext_header, sizeof(ext_header), &len, NULL ) || len < 4) return;
302
303         /* Reading the magic field succeeded so
304          * we will try to determine what type it is.
305          */
306         if (!memcmp( &ext_header.nt.Signature, "PE\0\0", 4 ))
307         {
308             if (len >= sizeof(ext_header.nt.FileHeader))
309             {
310                 info->type = BINARY_PE;
311                 if (ext_header.nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
312                     info->flags |= BINARY_FLAG_DLL;
313                 if (len < sizeof(ext_header.nt))  /* clear remaining part of header if missing */
314                     memset( (char *)&ext_header.nt + len, 0, sizeof(ext_header.nt) - len );
315                 switch (ext_header.nt.OptionalHeader.Magic)
316                 {
317                 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
318                     info->res_start = (void *)(ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase;
319                     info->res_end = (void *)((ULONG_PTR)ext_header.nt.OptionalHeader.ImageBase +
320                                                      ext_header.nt.OptionalHeader.SizeOfImage);
321                     break;
322                 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
323                     info->flags |= BINARY_FLAG_64BIT;
324                     break;
325                 }
326             }
327         }
328         else if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
329         {
330             /* This is a Windows executable (NE) header.  This can
331              * mean either a 16-bit OS/2 or a 16-bit Windows or even a
332              * DOS program (running under a DOS extender).  To decide
333              * which, we'll have to read the NE header.
334              */
335             if (len >= sizeof(ext_header.os2))
336             {
337                 if (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) info->flags |= BINARY_FLAG_DLL;
338                 switch ( ext_header.os2.ne_exetyp )
339                 {
340                 case 1:  info->type = BINARY_OS216; break; /* OS/2 */
341                 case 2:  info->type = BINARY_WIN16; break; /* Windows */
342                 case 3:  info->type = BINARY_DOS; break; /* European MS-DOS 4.x */
343                 case 4:  info->type = BINARY_WIN16; break; /* Windows 386; FIXME: is this 32bit??? */
344                 case 5:  info->type = BINARY_DOS; break; /* BOSS, Borland Operating System Services */
345                 /* other types, e.g. 0 is: "unknown" */
346                 default: info->type = MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2); break;
347                 }
348             }
349         }
350     }
351 }
352
353 /***********************************************************************
354  *             GetBinaryTypeW                     [KERNEL32.@]
355  *
356  * Determine whether a file is executable, and if so, what kind.
357  *
358  * PARAMS
359  *  lpApplicationName [I] Path of the file to check
360  *  lpBinaryType      [O] Destination for the binary type
361  *
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.
365  *
366  * NOTES
367  *  The type of executable is a property that determines which subsystem 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_64BIT_BINARY: A Win64 based application
372  *   SCS_DOS_BINARY: An MS-Dos based application
373  *   SCS_WOW_BINARY: A Win16 based application
374  *   SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
375  *   SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
376  *   SCS_OS216_BINARY: A 16bit OS/2 based application
377  *
378  *  To find the binary type, this function reads in the files header information.
379  *  If extended header information is not present it will assume that the file
380  *  is a DOS executable. If extended header information is present it will
381  *  determine if the file is a 16, 32 or 64 bit Windows executable by checking the
382  *  flags in the header.
383  *
384  *  ".com" and ".pif" files are only recognized by their file name extension,
385  *  as per native Windows.
386  */
387 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
388 {
389     BOOL ret = FALSE;
390     HANDLE hfile;
391     struct binary_info binary_info;
392
393     TRACE("%s\n", debugstr_w(lpApplicationName) );
394
395     /* Sanity check.
396      */
397     if ( lpApplicationName == NULL || lpBinaryType == NULL )
398         return FALSE;
399
400     /* Open the file indicated by lpApplicationName for reading.
401      */
402     hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
403                          NULL, OPEN_EXISTING, 0, 0 );
404     if ( hfile == INVALID_HANDLE_VALUE )
405         return FALSE;
406
407     /* Check binary type
408      */
409     MODULE_get_binary_info( hfile, &binary_info );
410     switch (binary_info.type)
411     {
412     case BINARY_UNKNOWN:
413     {
414         static const WCHAR comW[] = { '.','C','O','M',0 };
415         static const WCHAR pifW[] = { '.','P','I','F',0 };
416         const WCHAR *ptr;
417
418         /* try to determine from file name */
419         ptr = strrchrW( lpApplicationName, '.' );
420         if (!ptr) break;
421         if (!strcmpiW( ptr, comW ))
422         {
423             *lpBinaryType = SCS_DOS_BINARY;
424             ret = TRUE;
425         }
426         else if (!strcmpiW( ptr, pifW ))
427         {
428             *lpBinaryType = SCS_PIF_BINARY;
429             ret = TRUE;
430         }
431         break;
432     }
433     case BINARY_PE:
434         *lpBinaryType = (binary_info.flags & BINARY_FLAG_64BIT) ? SCS_64BIT_BINARY : SCS_32BIT_BINARY;
435         ret = TRUE;
436         break;
437     case BINARY_WIN16:
438         *lpBinaryType = SCS_WOW_BINARY;
439         ret = TRUE;
440         break;
441     case BINARY_OS216:
442         *lpBinaryType = SCS_OS216_BINARY;
443         ret = TRUE;
444         break;
445     case BINARY_DOS:
446         *lpBinaryType = SCS_DOS_BINARY;
447         ret = TRUE;
448         break;
449     case BINARY_UNIX_EXE:
450     case BINARY_UNIX_LIB:
451         ret = FALSE;
452         break;
453     }
454
455     CloseHandle( hfile );
456     return ret;
457 }
458
459 /***********************************************************************
460  *             GetBinaryTypeA                     [KERNEL32.@]
461  *             GetBinaryType                      [KERNEL32.@]
462  *
463  * See GetBinaryTypeW.
464  */
465 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
466 {
467     ANSI_STRING app_nameA;
468     NTSTATUS status;
469
470     TRACE("%s\n", debugstr_a(lpApplicationName));
471
472     /* Sanity check.
473      */
474     if ( lpApplicationName == NULL || lpBinaryType == NULL )
475         return FALSE;
476
477     RtlInitAnsiString(&app_nameA, lpApplicationName);
478     status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
479                                           &app_nameA, FALSE);
480     if (!status)
481         return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
482
483     SetLastError(RtlNtStatusToDosError(status));
484     return FALSE;
485 }
486
487 /***********************************************************************
488  *              GetModuleHandleExA         (KERNEL32.@)
489  */
490 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
491 {
492     WCHAR *nameW;
493
494     if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
495         return GetModuleHandleExW( flags, (LPCWSTR)name, module );
496
497     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
498     return GetModuleHandleExW( flags, nameW, module );
499 }
500
501 /***********************************************************************
502  *              GetModuleHandleExW         (KERNEL32.@)
503  */
504 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
505 {
506     NTSTATUS status = STATUS_SUCCESS;
507     HMODULE ret;
508     ULONG magic;
509
510     /* if we are messing with the refcount, grab the loader lock */
511     if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
512         !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
513         LdrLockLoaderLock( 0, NULL, &magic );
514
515     if (!name)
516     {
517         ret = NtCurrentTeb()->Peb->ImageBaseAddress;
518     }
519     else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
520     {
521         void *dummy;
522         if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
523     }
524     else
525     {
526         UNICODE_STRING wstr;
527         RtlInitUnicodeString( &wstr, name );
528         status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
529     }
530
531     if (status == STATUS_SUCCESS)
532     {
533         if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
534             FIXME( "should pin refcount for %p\n", ret );
535         else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
536             LdrAddRefDll( 0, ret );
537     }
538     else SetLastError( RtlNtStatusToDosError( status ) );
539
540     if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
541         !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
542         LdrUnlockLoaderLock( 0, magic );
543
544     if (module) *module = ret;
545     return (status == STATUS_SUCCESS);
546 }
547
548 /***********************************************************************
549  *              GetModuleHandleA         (KERNEL32.@)
550  *
551  * Get the handle of a dll loaded into the process address space.
552  *
553  * PARAMS
554  *  module [I] Name of the dll
555  *
556  * RETURNS
557  *  Success: A handle to the loaded dll.
558  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
559  */
560 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
561 {
562     HMODULE ret;
563
564     if (!GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
565     return ret;
566 }
567
568 /***********************************************************************
569  *              GetModuleHandleW (KERNEL32.@)
570  *
571  * Unicode version of GetModuleHandleA.
572  */
573 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
574 {
575     HMODULE ret;
576
577     if (!GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
578     return ret;
579 }
580
581
582 /***********************************************************************
583  *              GetModuleFileNameA      (KERNEL32.@)
584  *
585  * Get the file name of a loaded module from its handle.
586  *
587  * RETURNS
588  *  Success: The length of the file name, excluding the terminating NUL.
589  *  Failure: 0. Use GetLastError() to determine the cause.
590  *
591  * NOTES
592  *  This function always returns the long path of hModule
593  *  The function doesn't write a terminating '\0' if the buffer is too 
594  *  small.
595  */
596 DWORD WINAPI GetModuleFileNameA(
597         HMODULE hModule,        /* [in] Module handle (32 bit) */
598         LPSTR lpFileName,       /* [out] Destination for file name */
599         DWORD size )            /* [in] Size of lpFileName in characters */
600 {
601     LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
602     DWORD len;
603
604     if (!filenameW)
605     {
606         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
607         return 0;
608     }
609     if ((len = GetModuleFileNameW( hModule, filenameW, size )))
610     {
611         len = FILE_name_WtoA( filenameW, len, lpFileName, size );
612         if (len < size)
613             lpFileName[len] = '\0';
614         else
615             SetLastError( ERROR_INSUFFICIENT_BUFFER );
616     }
617     HeapFree( GetProcessHeap(), 0, filenameW );
618     return len;
619 }
620
621 /***********************************************************************
622  *              GetModuleFileNameW      (KERNEL32.@)
623  *
624  * Unicode version of GetModuleFileNameA.
625  */
626 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
627 {
628     ULONG magic, len = 0;
629     LDR_MODULE *pldr;
630     NTSTATUS nts;
631     WIN16_SUBSYSTEM_TIB *win16_tib;
632
633     if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
634     {
635         len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
636         memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
637         if (len < size) lpFileName[len] = '\0';
638         goto done;
639     }
640
641     LdrLockLoaderLock( 0, NULL, &magic );
642
643     if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
644     nts = LdrFindEntryForAddress( hModule, &pldr );
645     if (nts == STATUS_SUCCESS)
646     {
647         len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
648         memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
649         if (len < size)
650             lpFileName[len] = '\0';
651         else
652             SetLastError( ERROR_INSUFFICIENT_BUFFER );
653     }
654     else SetLastError( RtlNtStatusToDosError( nts ) );
655
656     LdrUnlockLoaderLock( 0, magic );
657 done:
658     TRACE( "%s\n", debugstr_wn(lpFileName, len) );
659     return len;
660 }
661
662
663 /***********************************************************************
664  *           get_dll_system_path
665  */
666 static const WCHAR *get_dll_system_path(void)
667 {
668     static WCHAR *cached_path;
669
670     if (!cached_path)
671     {
672         WCHAR *p, *path;
673         int len = 3;
674
675         len += 2 * GetSystemDirectoryW( NULL, 0 );
676         len += GetWindowsDirectoryW( NULL, 0 );
677         p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
678         *p++ = '.';
679         *p++ = ';';
680         GetSystemDirectoryW( p, path + len - p);
681         p += strlenW(p);
682         /* if system directory ends in "32" add 16-bit version too */
683         if (p[-2] == '3' && p[-1] == '2')
684         {
685             *p++ = ';';
686             GetSystemDirectoryW( p, path + len - p);
687             p += strlenW(p) - 2;
688         }
689         *p++ = ';';
690         GetWindowsDirectoryW( p, path + len - p);
691         cached_path = path;
692     }
693     return cached_path;
694 }
695
696 /******************************************************************
697  *              get_module_path_end
698  *
699  * Returns the end of the directory component of the module path.
700  */
701 static inline const WCHAR *get_module_path_end(const WCHAR *module)
702 {
703     const WCHAR *p;
704     const WCHAR *mod_end = module;
705     if (!module) return mod_end;
706
707     if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
708     if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
709     if (mod_end == module + 2 && module[1] == ':') mod_end++;
710     if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
711
712     return mod_end;
713 }
714
715 /******************************************************************
716  *              MODULE_get_dll_load_path
717  *
718  * Compute the load path to use for a given dll.
719  * Returned pointer must be freed by caller.
720  */
721 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
722 {
723     static const WCHAR pathW[] = {'P','A','T','H',0};
724
725     const WCHAR *system_path = get_dll_system_path();
726     const WCHAR *mod_end = NULL;
727     UNICODE_STRING name, value;
728     WCHAR *p, *ret;
729     int len = 0, path_len = 0;
730
731     /* adjust length for module name */
732
733     if (module)
734         mod_end = get_module_path_end( module );
735     /* if module is NULL or doesn't contain a path, fall back to directory
736      * process was loaded from */
737     if (module == mod_end)
738     {
739         module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
740         mod_end = get_module_path_end( module );
741     }
742     len += (mod_end - module) + 1;
743
744     len += strlenW( system_path ) + 2;
745
746     /* get the PATH variable */
747
748     RtlInitUnicodeString( &name, pathW );
749     value.Length = 0;
750     value.MaximumLength = 0;
751     value.Buffer = NULL;
752     if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
753         path_len = value.Length;
754
755     RtlEnterCriticalSection( &dlldir_section );
756     if (dll_directory) len += strlenW(dll_directory) + 1;
757     if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
758     {
759         if (module)
760         {
761             memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
762             p += (mod_end - module);
763             *p++ = ';';
764         }
765         if (dll_directory)
766         {
767             strcpyW( p, dll_directory );
768             p += strlenW(p);
769             *p++ = ';';
770         }
771     }
772     RtlLeaveCriticalSection( &dlldir_section );
773     if (!ret) return NULL;
774
775     strcpyW( p, system_path );
776     p += strlenW(p);
777     *p++ = ';';
778     value.Buffer = p;
779     value.MaximumLength = path_len;
780
781     while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
782     {
783         WCHAR *new_ptr;
784
785         /* grow the buffer and retry */
786         path_len = value.Length;
787         if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
788         {
789             HeapFree( GetProcessHeap(), 0, ret );
790             return NULL;
791         }
792         value.Buffer = new_ptr + (value.Buffer - ret);
793         value.MaximumLength = path_len;
794         ret = new_ptr;
795     }
796     value.Buffer[value.Length / sizeof(WCHAR)] = 0;
797     return ret;
798 }
799
800
801 /******************************************************************
802  *              load_library_as_datafile
803  */
804 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
805 {
806     static const WCHAR dotDLL[] = {'.','d','l','l',0};
807
808     WCHAR filenameW[MAX_PATH];
809     HANDLE hFile = INVALID_HANDLE_VALUE;
810     HANDLE mapping;
811     HMODULE module;
812
813     *hmod = 0;
814
815     if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
816                      filenameW, NULL ))
817     {
818         hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
819                              NULL, OPEN_EXISTING, 0, 0 );
820     }
821     if (hFile == INVALID_HANDLE_VALUE) return FALSE;
822
823     mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
824     CloseHandle( hFile );
825     if (!mapping) return FALSE;
826
827     module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
828     CloseHandle( mapping );
829     if (!module) return FALSE;
830
831     /* make sure it's a valid PE file */
832     if (!RtlImageNtHeader(module))
833     {
834         UnmapViewOfFile( module );
835         return FALSE;
836     }
837     *hmod = (HMODULE)((char *)module + 1);  /* set low bit of handle to indicate datafile module */
838     return TRUE;
839 }
840
841
842 /******************************************************************
843  *              load_library
844  *
845  * Helper for LoadLibraryExA/W.
846  */
847 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
848 {
849     NTSTATUS nts;
850     HMODULE hModule;
851     WCHAR *load_path;
852     static const DWORD unsupported_flags = 
853         LOAD_IGNORE_CODE_AUTHZ_LEVEL |
854         LOAD_LIBRARY_AS_IMAGE_RESOURCE |
855         LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE |
856         LOAD_LIBRARY_REQUIRE_SIGNED_TARGET;
857
858     if( flags & unsupported_flags)
859         FIXME("unsupported flag(s) used (flags: 0x%08x)\n", flags & ~unsupported_flags);
860
861     load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
862
863     if (flags & LOAD_LIBRARY_AS_DATAFILE)
864     {
865         ULONG magic;
866
867         LdrLockLoaderLock( 0, NULL, &magic );
868         if (!LdrGetDllHandle( load_path, flags, libname, &hModule ))
869         {
870             LdrAddRefDll( 0, hModule );
871             LdrUnlockLoaderLock( 0, magic );
872             goto done;
873         }
874         LdrUnlockLoaderLock( 0, magic );
875
876         /* The method in load_library_as_datafile allows searching for the
877          * 'native' libraries only
878          */
879         if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
880         flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
881         /* Fallback to normal behaviour */
882     }
883
884     nts = LdrLoadDll( load_path, flags, libname, &hModule );
885     if (nts != STATUS_SUCCESS)
886     {
887         hModule = 0;
888         SetLastError( RtlNtStatusToDosError( nts ) );
889     }
890 done:
891     HeapFree( GetProcessHeap(), 0, load_path );
892     return hModule;
893 }
894
895
896 /******************************************************************
897  *              LoadLibraryExA          (KERNEL32.@)
898  *
899  * Load a dll file into the process address space.
900  *
901  * PARAMS
902  *  libname [I] Name of the file to load
903  *  hfile   [I] Reserved, must be 0.
904  *  flags   [I] Flags for loading the dll
905  *
906  * RETURNS
907  *  Success: A handle to the loaded dll.
908  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
909  *
910  * NOTES
911  * The HFILE parameter is not used and marked reserved in the SDK. I can
912  * only guess that it should force a file to be mapped, but I rather
913  * ignore the parameter because it would be extremely difficult to
914  * integrate this with different types of module representations.
915  */
916 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
917 {
918     WCHAR *libnameW;
919
920     if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
921     return LoadLibraryExW( libnameW, hfile, flags );
922 }
923
924 /***********************************************************************
925  *           LoadLibraryExW       (KERNEL32.@)
926  *
927  * Unicode version of LoadLibraryExA.
928  */
929 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
930 {
931     UNICODE_STRING      wstr;
932     HMODULE             res;
933
934     if (!libnameW)
935     {
936         SetLastError(ERROR_INVALID_PARAMETER);
937         return 0;
938     }
939     RtlInitUnicodeString( &wstr, libnameW );
940     if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
941         return load_library( &wstr, flags );
942
943     /* Library name has trailing spaces */
944     RtlCreateUnicodeString( &wstr, libnameW );
945     while (wstr.Length > sizeof(WCHAR) &&
946            wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
947     {
948         wstr.Length -= sizeof(WCHAR);
949     }
950     wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
951     res = load_library( &wstr, flags );
952     RtlFreeUnicodeString( &wstr );
953     return res;
954 }
955
956 /***********************************************************************
957  *           LoadLibraryA         (KERNEL32.@)
958  *
959  * Load a dll file into the process address space.
960  *
961  * PARAMS
962  *  libname [I] Name of the file to load
963  *
964  * RETURNS
965  *  Success: A handle to the loaded dll.
966  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
967  *
968  * NOTES
969  * See LoadLibraryExA().
970  */
971 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryA(LPCSTR libname)
972 {
973     return LoadLibraryExA(libname, 0, 0);
974 }
975
976 /***********************************************************************
977  *           LoadLibraryW         (KERNEL32.@)
978  *
979  * Unicode version of LoadLibraryA.
980  */
981 HMODULE WINAPI DECLSPEC_HOTPATCH LoadLibraryW(LPCWSTR libnameW)
982 {
983     return LoadLibraryExW(libnameW, 0, 0);
984 }
985
986 /***********************************************************************
987  *           FreeLibrary   (KERNEL32.@)
988  *
989  * Free a dll loaded into the process address space.
990  *
991  * PARAMS
992  *  hLibModule [I] Handle to the dll returned by LoadLibraryA().
993  *
994  * RETURNS
995  *  Success: TRUE. The dll is removed if it is not still in use.
996  *  Failure: FALSE. Use GetLastError() to determine the cause.
997  */
998 BOOL WINAPI DECLSPEC_HOTPATCH FreeLibrary(HINSTANCE hLibModule)
999 {
1000     BOOL                retv = FALSE;
1001     NTSTATUS            nts;
1002
1003     if (!hLibModule)
1004     {
1005         SetLastError( ERROR_INVALID_HANDLE );
1006         return FALSE;
1007     }
1008
1009     if ((ULONG_PTR)hLibModule & 1)
1010     {
1011         /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1012         char *ptr = (char *)hLibModule - 1;
1013         return UnmapViewOfFile( ptr );
1014     }
1015
1016     if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1017     else SetLastError( RtlNtStatusToDosError( nts ) );
1018
1019     return retv;
1020 }
1021
1022 /***********************************************************************
1023  *           GetProcAddress             (KERNEL32.@)
1024  *
1025  * Find the address of an exported symbol in a loaded dll.
1026  *
1027  * PARAMS
1028  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
1029  *  function [I] Name of the symbol, or an integer ordinal number < 16384
1030  *
1031  * RETURNS
1032  *  Success: A pointer to the symbol in the process address space.
1033  *  Failure: NULL. Use GetLastError() to determine the cause.
1034  */
1035 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1036 {
1037     NTSTATUS    nts;
1038     FARPROC     fp;
1039
1040     if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1041
1042     if ((ULONG_PTR)function >> 16)
1043     {
1044         ANSI_STRING     str;
1045
1046         RtlInitAnsiString( &str, function );
1047         nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1048     }
1049     else
1050         nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1051     if (nts != STATUS_SUCCESS)
1052     {
1053         SetLastError( RtlNtStatusToDosError( nts ) );
1054         fp = NULL;
1055     }
1056     return fp;
1057 }
1058
1059 /***********************************************************************
1060  *           DelayLoadFailureHook  (KERNEL32.@)
1061  */
1062 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1063 {
1064     ULONG_PTR args[2];
1065
1066     if ((ULONG_PTR)function >> 16)
1067         ERR( "failed to delay load %s.%s\n", name, function );
1068     else
1069         ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1070     args[0] = (ULONG_PTR)name;
1071     args[1] = (ULONG_PTR)function;
1072     RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1073     return NULL;
1074 }
1075
1076
1077 #ifdef __i386__
1078
1079 /***********************************************************************
1080  *           __wine_dll_register_16 (KERNEL32.@)
1081  *
1082  * No longer used.
1083  */
1084 void __wine_dll_register_16( const IMAGE_DOS_HEADER *header, const char *file_name )
1085 {
1086     ERR( "loading old style 16-bit dll %s no longer supported\n", file_name );
1087 }
1088
1089
1090 /***********************************************************************
1091  *           __wine_dll_unregister_16 (KERNEL32.@)
1092  *
1093  * No longer used.
1094  */
1095 void __wine_dll_unregister_16( const IMAGE_DOS_HEADER *header )
1096 {
1097 }
1098
1099 #endif