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