kernel32: Return the dll flag in MODULE_GetBinaryType for 16-bit modules too.
[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_HEADERS 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                 return ret;
315             }
316             return BINARY_DOS;
317         }
318
319         if (!memcmp( &ext_header.os2.ne_magic, "NE", 2 ))
320         {
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.
325              */
326             if (len >= sizeof(ext_header.os2))
327             {
328                 DWORD flags = (ext_header.os2.ne_flags & NE_FFLAGS_LIBMODULE) ? BINARY_FLAG_DLL : 0;
329                 switch ( ext_header.os2.ne_exetyp )
330                 {
331                 case 1:  return flags | BINARY_OS216; /* OS/2 */
332                 case 2:  return flags | BINARY_WIN16; /* Windows */
333                 case 3:  return flags | BINARY_DOS; /* European MS-DOS 4.x */
334                 case 4:  return flags | BINARY_WIN16; /* Windows 386; FIXME: is this 32bit??? */
335                 case 5:  return flags | BINARY_DOS; /* BOSS, Borland Operating System Services */
336                 /* other types, e.g. 0 is: "unknown" */
337                 default: return flags | MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ext_header.os2);
338                 }
339             }
340             /* Couldn't read header, so abort. */
341             return BINARY_DOS;
342         }
343
344         /* Unknown extended header, but this file is nonetheless DOS-executable. */
345         return BINARY_DOS;
346     }
347
348     return BINARY_UNKNOWN;
349 }
350
351 /***********************************************************************
352  *             GetBinaryTypeW                     [KERNEL32.@]
353  *
354  * Determine whether a file is executable, and if so, what kind.
355  *
356  * PARAMS
357  *  lpApplicationName [I] Path of the file to check
358  *  lpBinaryType      [O] Destination for the binary type
359  *
360  * RETURNS
361  *  TRUE, if the file is an executable, in which case lpBinaryType is set.
362  *  FALSE, if the file is not an executable or if the function fails.
363  *
364  * NOTES
365  *  The type of executable is a property that determines which subsystem an
366  *  executable file runs under. lpBinaryType can be set to one of the following
367  *  values:
368  *   SCS_32BIT_BINARY: A Win32 based application
369  *   SCS_DOS_BINARY: An MS-Dos based application
370  *   SCS_WOW_BINARY: A Win16 based application
371  *   SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
372  *   SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
373  *   SCS_OS216_BINARY: A 16bit OS/2 based application
374  *
375  *  To find the binary type, this function reads in the files header information.
376  *  If extended header information is not present it will assume that the file
377  *  is a DOS executable. If extended header information is present it will
378  *  determine if the file is a 16 or 32 bit Windows executable by checking the
379  *  flags in the header.
380  *
381  *  ".com" and ".pif" files are only recognized by their file name extension,
382  *  as per native Windows.
383  */
384 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
385 {
386     BOOL ret = FALSE;
387     HANDLE hfile;
388     DWORD binary_type;
389
390     TRACE("%s\n", debugstr_w(lpApplicationName) );
391
392     /* Sanity check.
393      */
394     if ( lpApplicationName == NULL || lpBinaryType == NULL )
395         return FALSE;
396
397     /* Open the file indicated by lpApplicationName for reading.
398      */
399     hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
400                          NULL, OPEN_EXISTING, 0, 0 );
401     if ( hfile == INVALID_HANDLE_VALUE )
402         return FALSE;
403
404     /* Check binary type
405      */
406     binary_type = MODULE_GetBinaryType( hfile, NULL, NULL );
407     switch (binary_type & BINARY_TYPE_MASK)
408     {
409     case BINARY_UNKNOWN:
410     {
411         static const WCHAR comW[] = { '.','C','O','M',0 };
412         static const WCHAR pifW[] = { '.','P','I','F',0 };
413         const WCHAR *ptr;
414
415         /* try to determine from file name */
416         ptr = strrchrW( lpApplicationName, '.' );
417         if (!ptr) break;
418         if (!strcmpiW( ptr, comW ))
419         {
420             *lpBinaryType = SCS_DOS_BINARY;
421             ret = TRUE;
422         }
423         else if (!strcmpiW( ptr, pifW ))
424         {
425             *lpBinaryType = SCS_PIF_BINARY;
426             ret = TRUE;
427         }
428         break;
429     }
430     case BINARY_PE:
431         *lpBinaryType = SCS_32BIT_BINARY;
432         ret = TRUE;
433         break;
434     case BINARY_WIN16:
435         *lpBinaryType = SCS_WOW_BINARY;
436         ret = TRUE;
437         break;
438     case BINARY_OS216:
439         *lpBinaryType = SCS_OS216_BINARY;
440         ret = TRUE;
441         break;
442     case BINARY_DOS:
443         *lpBinaryType = SCS_DOS_BINARY;
444         ret = TRUE;
445         break;
446     case BINARY_UNIX_EXE:
447     case BINARY_UNIX_LIB:
448         ret = FALSE;
449         break;
450     }
451
452     CloseHandle( hfile );
453     return ret;
454 }
455
456 /***********************************************************************
457  *             GetBinaryTypeA                     [KERNEL32.@]
458  *             GetBinaryType                      [KERNEL32.@]
459  *
460  * See GetBinaryTypeW.
461  */
462 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
463 {
464     ANSI_STRING app_nameA;
465     NTSTATUS status;
466
467     TRACE("%s\n", debugstr_a(lpApplicationName));
468
469     /* Sanity check.
470      */
471     if ( lpApplicationName == NULL || lpBinaryType == NULL )
472         return FALSE;
473
474     RtlInitAnsiString(&app_nameA, lpApplicationName);
475     status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
476                                           &app_nameA, FALSE);
477     if (!status)
478         return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
479
480     SetLastError(RtlNtStatusToDosError(status));
481     return FALSE;
482 }
483
484 /***********************************************************************
485  *              GetModuleHandleExA         (KERNEL32.@)
486  */
487 BOOL WINAPI GetModuleHandleExA( DWORD flags, LPCSTR name, HMODULE *module )
488 {
489     WCHAR *nameW;
490
491     if (!name || (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS))
492         return GetModuleHandleExW( flags, (LPCWSTR)name, module );
493
494     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return FALSE;
495     return GetModuleHandleExW( flags, nameW, module );
496 }
497
498 /***********************************************************************
499  *              GetModuleHandleExW         (KERNEL32.@)
500  */
501 BOOL WINAPI GetModuleHandleExW( DWORD flags, LPCWSTR name, HMODULE *module )
502 {
503     NTSTATUS status = STATUS_SUCCESS;
504     HMODULE ret;
505     ULONG magic;
506
507     /* if we are messing with the refcount, grab the loader lock */
508     if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
509         !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
510         LdrLockLoaderLock( 0, NULL, &magic );
511
512     if (!name)
513     {
514         ret = NtCurrentTeb()->Peb->ImageBaseAddress;
515     }
516     else if (flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
517     {
518         void *dummy;
519         if (!(ret = RtlPcToFileHeader( (void *)name, &dummy ))) status = STATUS_DLL_NOT_FOUND;
520     }
521     else
522     {
523         UNICODE_STRING wstr;
524         RtlInitUnicodeString( &wstr, name );
525         status = LdrGetDllHandle( NULL, 0, &wstr, &ret );
526     }
527
528     if (status == STATUS_SUCCESS)
529     {
530         if (flags & GET_MODULE_HANDLE_EX_FLAG_PIN)
531             FIXME( "should pin refcount for %p\n", ret );
532         else if (!(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
533             LdrAddRefDll( 0, ret );
534     }
535     else SetLastError( RtlNtStatusToDosError( status ) );
536
537     if ((flags & GET_MODULE_HANDLE_EX_FLAG_PIN) ||
538         !(flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
539         LdrUnlockLoaderLock( 0, magic );
540
541     if (module) *module = ret;
542     return (status == STATUS_SUCCESS);
543 }
544
545 /***********************************************************************
546  *              GetModuleHandleA         (KERNEL32.@)
547  *              GetModuleHandle32        (KERNEL.488)
548  *
549  * Get the handle of a dll loaded into the process address space.
550  *
551  * PARAMS
552  *  module [I] Name of the dll
553  *
554  * RETURNS
555  *  Success: A handle to the loaded dll.
556  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
557  */
558 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
559 {
560     HMODULE ret;
561
562     if (!GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
563     return ret;
564 }
565
566 /***********************************************************************
567  *              GetModuleHandleW (KERNEL32.@)
568  *
569  * Unicode version of GetModuleHandleA.
570  */
571 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
572 {
573     HMODULE ret;
574
575     if (!GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, module, &ret )) ret = 0;
576     return ret;
577 }
578
579
580 /***********************************************************************
581  *              GetModuleFileNameA      (KERNEL32.@)
582  *              GetModuleFileName32     (KERNEL.487)
583  *
584  * Get the file name of a loaded module from its handle.
585  *
586  * RETURNS
587  *  Success: The length of the file name, excluding the terminating NUL.
588  *  Failure: 0. Use GetLastError() to determine the cause.
589  *
590  * NOTES
591  *  This function always returns the long path of hModule (as opposed to
592  *  GetModuleFileName16() which returns short paths when the modules version
593  *  field is < 4.0).
594  *  The function doesn't write a terminating '\0' if the buffer is too 
595  *  small.
596  */
597 DWORD WINAPI GetModuleFileNameA(
598         HMODULE hModule,        /* [in] Module handle (32 bit) */
599         LPSTR lpFileName,       /* [out] Destination for file name */
600         DWORD size )            /* [in] Size of lpFileName in characters */
601 {
602     LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
603     DWORD len;
604
605     if (!filenameW)
606     {
607         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
608         return 0;
609     }
610     if ((len = GetModuleFileNameW( hModule, filenameW, size )))
611     {
612         len = FILE_name_WtoA( filenameW, len, lpFileName, size );
613         if (len < size)
614             lpFileName[len] = '\0';
615         else
616             SetLastError( ERROR_INSUFFICIENT_BUFFER );
617     }
618     HeapFree( GetProcessHeap(), 0, filenameW );
619     return len;
620 }
621
622 /***********************************************************************
623  *              GetModuleFileNameW      (KERNEL32.@)
624  *
625  * Unicode version of GetModuleFileNameA.
626  */
627 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
628 {
629     ULONG magic, len = 0;
630     LDR_MODULE *pldr;
631     NTSTATUS nts;
632     WIN16_SUBSYSTEM_TIB *win16_tib;
633
634     if (!hModule && ((win16_tib = NtCurrentTeb()->Tib.SubSystemTib)) && win16_tib->exe_name)
635     {
636         len = min(size, win16_tib->exe_name->Length / sizeof(WCHAR));
637         memcpy( lpFileName, win16_tib->exe_name->Buffer, len * sizeof(WCHAR) );
638         if (len < size) lpFileName[len] = '\0';
639         goto done;
640     }
641
642     LdrLockLoaderLock( 0, NULL, &magic );
643
644     if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
645     nts = LdrFindEntryForAddress( hModule, &pldr );
646     if (nts == STATUS_SUCCESS)
647     {
648         len = min(size, pldr->FullDllName.Length / sizeof(WCHAR));
649         memcpy(lpFileName, pldr->FullDllName.Buffer, len * sizeof(WCHAR));
650         if (len < size)
651             lpFileName[len] = '\0';
652         else
653             SetLastError( ERROR_INSUFFICIENT_BUFFER );
654     }
655     else SetLastError( RtlNtStatusToDosError( nts ) );
656
657     LdrUnlockLoaderLock( 0, magic );
658 done:
659     TRACE( "%s\n", debugstr_wn(lpFileName, len) );
660     return len;
661 }
662
663
664 /***********************************************************************
665  *           get_dll_system_path
666  */
667 static const WCHAR *get_dll_system_path(void)
668 {
669     static WCHAR *cached_path;
670
671     if (!cached_path)
672     {
673         WCHAR *p, *path;
674         int len = 3;
675
676         len += 2 * GetSystemDirectoryW( NULL, 0 );
677         len += GetWindowsDirectoryW( NULL, 0 );
678         p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
679         *p++ = '.';
680         *p++ = ';';
681         GetSystemDirectoryW( p, path + len - p);
682         p += strlenW(p);
683         /* if system directory ends in "32" add 16-bit version too */
684         if (p[-2] == '3' && p[-1] == '2')
685         {
686             *p++ = ';';
687             GetSystemDirectoryW( p, path + len - p);
688             p += strlenW(p) - 2;
689         }
690         *p++ = ';';
691         GetWindowsDirectoryW( p, path + len - p);
692         cached_path = path;
693     }
694     return cached_path;
695 }
696
697 /******************************************************************
698  *              get_module_path_end
699  *
700  * Returns the end of the directory component of the module path.
701  */
702 static inline const WCHAR *get_module_path_end(const WCHAR *module)
703 {
704     const WCHAR *p;
705     const WCHAR *mod_end = module;
706     if (!module) return mod_end;
707
708     if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
709     if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
710     if (mod_end == module + 2 && module[1] == ':') mod_end++;
711     if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
712
713     return mod_end;
714 }
715
716 /******************************************************************
717  *              MODULE_get_dll_load_path
718  *
719  * Compute the load path to use for a given dll.
720  * Returned pointer must be freed by caller.
721  */
722 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
723 {
724     static const WCHAR pathW[] = {'P','A','T','H',0};
725
726     const WCHAR *system_path = get_dll_system_path();
727     const WCHAR *mod_end = NULL;
728     UNICODE_STRING name, value;
729     WCHAR *p, *ret;
730     int len = 0, path_len = 0;
731
732     /* adjust length for module name */
733
734     if (module)
735         mod_end = get_module_path_end( module );
736     /* if module is NULL or doesn't contain a path, fall back to directory
737      * process was loaded from */
738     if (module == mod_end)
739     {
740         module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
741         mod_end = get_module_path_end( module );
742     }
743     len += (mod_end - module) + 1;
744
745     len += strlenW( system_path ) + 2;
746
747     /* get the PATH variable */
748
749     RtlInitUnicodeString( &name, pathW );
750     value.Length = 0;
751     value.MaximumLength = 0;
752     value.Buffer = NULL;
753     if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
754         path_len = value.Length;
755
756     RtlEnterCriticalSection( &dlldir_section );
757     if (dll_directory) len += strlenW(dll_directory) + 1;
758     if ((p = ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
759     {
760         if (module)
761         {
762             memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
763             p += (mod_end - module);
764             *p++ = ';';
765         }
766         if (dll_directory)
767         {
768             strcpyW( p, dll_directory );
769             p += strlenW(p);
770             *p++ = ';';
771         }
772     }
773     RtlLeaveCriticalSection( &dlldir_section );
774     if (!ret) return NULL;
775
776     strcpyW( p, system_path );
777     p += strlenW(p);
778     *p++ = ';';
779     value.Buffer = p;
780     value.MaximumLength = path_len;
781
782     while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
783     {
784         WCHAR *new_ptr;
785
786         /* grow the buffer and retry */
787         path_len = value.Length;
788         if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
789         {
790             HeapFree( GetProcessHeap(), 0, ret );
791             return NULL;
792         }
793         value.Buffer = new_ptr + (value.Buffer - ret);
794         value.MaximumLength = path_len;
795         ret = new_ptr;
796     }
797     value.Buffer[value.Length / sizeof(WCHAR)] = 0;
798     return ret;
799 }
800
801
802 /******************************************************************
803  *              load_library_as_datafile
804  */
805 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
806 {
807     static const WCHAR dotDLL[] = {'.','d','l','l',0};
808
809     WCHAR filenameW[MAX_PATH];
810     HANDLE hFile = INVALID_HANDLE_VALUE;
811     HANDLE mapping;
812     HMODULE module;
813
814     *hmod = 0;
815
816     if (SearchPathW( NULL, name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
817                      filenameW, NULL ))
818     {
819         hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
820                              NULL, OPEN_EXISTING, 0, 0 );
821     }
822     if (hFile == INVALID_HANDLE_VALUE) return FALSE;
823
824     mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
825     CloseHandle( hFile );
826     if (!mapping) return FALSE;
827
828     module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
829     CloseHandle( mapping );
830     if (!module) return FALSE;
831
832     /* make sure it's a valid PE file */
833     if (!RtlImageNtHeader(module))
834     {
835         UnmapViewOfFile( module );
836         return FALSE;
837     }
838     *hmod = (HMODULE)((char *)module + 1);  /* set low bit of handle to indicate datafile module */
839     return TRUE;
840 }
841
842
843 /******************************************************************
844  *              load_library
845  *
846  * Helper for LoadLibraryExA/W.
847  */
848 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
849 {
850     NTSTATUS nts;
851     HMODULE hModule;
852     WCHAR *load_path;
853
854     load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
855
856     if (flags & LOAD_LIBRARY_AS_DATAFILE)
857     {
858         ULONG magic;
859
860         LdrLockLoaderLock( 0, NULL, &magic );
861         if (!(nts = LdrGetDllHandle( load_path, flags, libname, &hModule )))
862         {
863             LdrAddRefDll( 0, hModule );
864             LdrUnlockLoaderLock( 0, magic );
865             goto done;
866         }
867         LdrUnlockLoaderLock( 0, magic );
868
869         /* The method in load_library_as_datafile allows searching for the
870          * 'native' libraries only
871          */
872         if (load_library_as_datafile( libname->Buffer, &hModule )) goto done;
873         flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
874         /* Fallback to normal behaviour */
875     }
876
877     nts = LdrLoadDll( load_path, flags, libname, &hModule );
878     if (nts != STATUS_SUCCESS)
879     {
880         hModule = 0;
881         SetLastError( RtlNtStatusToDosError( nts ) );
882     }
883 done:
884     HeapFree( GetProcessHeap(), 0, load_path );
885     return hModule;
886 }
887
888
889 /******************************************************************
890  *              LoadLibraryExA          (KERNEL32.@)
891  *
892  * Load a dll file into the process address space.
893  *
894  * PARAMS
895  *  libname [I] Name of the file to load
896  *  hfile   [I] Reserved, must be 0.
897  *  flags   [I] Flags for loading the dll
898  *
899  * RETURNS
900  *  Success: A handle to the loaded dll.
901  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
902  *
903  * NOTES
904  * The HFILE parameter is not used and marked reserved in the SDK. I can
905  * only guess that it should force a file to be mapped, but I rather
906  * ignore the parameter because it would be extremely difficult to
907  * integrate this with different types of module representations.
908  */
909 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
910 {
911     WCHAR *libnameW;
912
913     if (!(libnameW = FILE_name_AtoW( libname, FALSE ))) return 0;
914     return LoadLibraryExW( libnameW, hfile, flags );
915 }
916
917 /***********************************************************************
918  *           LoadLibraryExW       (KERNEL32.@)
919  *
920  * Unicode version of LoadLibraryExA.
921  */
922 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
923 {
924     UNICODE_STRING      wstr;
925     HMODULE             res;
926
927     if (!libnameW)
928     {
929         SetLastError(ERROR_INVALID_PARAMETER);
930         return 0;
931     }
932     RtlInitUnicodeString( &wstr, libnameW );
933     if (wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] != ' ')
934         return load_library( &wstr, flags );
935
936     /* Library name has trailing spaces */
937     RtlCreateUnicodeString( &wstr, libnameW );
938     while (wstr.Length > sizeof(WCHAR) &&
939            wstr.Buffer[wstr.Length/sizeof(WCHAR) - 1] == ' ')
940     {
941         wstr.Length -= sizeof(WCHAR);
942     }
943     wstr.Buffer[wstr.Length/sizeof(WCHAR)] = '\0';
944     res = load_library( &wstr, flags );
945     RtlFreeUnicodeString( &wstr );
946     return res;
947 }
948
949 /***********************************************************************
950  *           LoadLibraryA         (KERNEL32.@)
951  *
952  * Load a dll file into the process address space.
953  *
954  * PARAMS
955  *  libname [I] Name of the file to load
956  *
957  * RETURNS
958  *  Success: A handle to the loaded dll.
959  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
960  *
961  * NOTES
962  * See LoadLibraryExA().
963  */
964 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
965 {
966     return LoadLibraryExA(libname, 0, 0);
967 }
968
969 /***********************************************************************
970  *           LoadLibraryW         (KERNEL32.@)
971  *
972  * Unicode version of LoadLibraryA.
973  */
974 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
975 {
976     return LoadLibraryExW(libnameW, 0, 0);
977 }
978
979 /***********************************************************************
980  *           FreeLibrary   (KERNEL32.@)
981  *           FreeLibrary32 (KERNEL.486)
982  *
983  * Free a dll loaded into the process address space.
984  *
985  * PARAMS
986  *  hLibModule [I] Handle to the dll returned by LoadLibraryA().
987  *
988  * RETURNS
989  *  Success: TRUE. The dll is removed if it is not still in use.
990  *  Failure: FALSE. Use GetLastError() to determine the cause.
991  */
992 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
993 {
994     BOOL                retv = FALSE;
995     NTSTATUS            nts;
996
997     if (!hLibModule)
998     {
999         SetLastError( ERROR_INVALID_HANDLE );
1000         return FALSE;
1001     }
1002
1003     if ((ULONG_PTR)hLibModule & 1)
1004     {
1005         /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1006         char *ptr = (char *)hLibModule - 1;
1007         UnmapViewOfFile( ptr );
1008         return TRUE;
1009     }
1010
1011     if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
1012     else SetLastError( RtlNtStatusToDosError( nts ) );
1013
1014     return retv;
1015 }
1016
1017 /***********************************************************************
1018  *           GetProcAddress             (KERNEL32.@)
1019  *
1020  * Find the address of an exported symbol in a loaded dll.
1021  *
1022  * PARAMS
1023  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
1024  *  function [I] Name of the symbol, or an integer ordinal number < 16384
1025  *
1026  * RETURNS
1027  *  Success: A pointer to the symbol in the process address space.
1028  *  Failure: NULL. Use GetLastError() to determine the cause.
1029  */
1030 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1031 {
1032     NTSTATUS    nts;
1033     FARPROC     fp;
1034
1035     if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
1036
1037     if (HIWORD(function))
1038     {
1039         ANSI_STRING     str;
1040
1041         RtlInitAnsiString( &str, function );
1042         nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1043     }
1044     else
1045         nts = LdrGetProcedureAddress( hModule, NULL, LOWORD(function), (void**)&fp );
1046     if (nts != STATUS_SUCCESS)
1047     {
1048         SetLastError( RtlNtStatusToDosError( nts ) );
1049         fp = NULL;
1050     }
1051     return fp;
1052 }
1053
1054 /***********************************************************************
1055  *           GetProcAddress32                   (KERNEL.453)
1056  *
1057  * Find the address of an exported symbol in a loaded dll.
1058  *
1059  * PARAMS
1060  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
1061  *  function [I] Name of the symbol, or an integer ordinal number < 16384
1062  *
1063  * RETURNS
1064  *  Success: A pointer to the symbol in the process address space.
1065  *  Failure: NULL. Use GetLastError() to determine the cause.
1066  */
1067 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1068 {
1069     /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
1070     return GetProcAddress( hModule, function );
1071 }
1072
1073
1074 /***********************************************************************
1075  *           DelayLoadFailureHook  (KERNEL32.@)
1076  */
1077 FARPROC WINAPI DelayLoadFailureHook( LPCSTR name, LPCSTR function )
1078 {
1079     ULONG_PTR args[2];
1080
1081     if ((ULONG_PTR)function >> 16)
1082         ERR( "failed to delay load %s.%s\n", name, function );
1083     else
1084         ERR( "failed to delay load %s.%u\n", name, LOWORD(function) );
1085     args[0] = (ULONG_PTR)name;
1086     args[1] = (ULONG_PTR)function;
1087     RaiseException( EXCEPTION_WINE_STUB, EH_NONCONTINUABLE, 2, args );
1088     return NULL;
1089 }