Reimplemented SearchPathW using ntdll functions.
[wine] / dlls / kernel / 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 "wine/winbase16.h"
33 #include "winerror.h"
34 #include "ntstatus.h"
35 #include "windef.h"
36 #include "winbase.h"
37 #include "winreg.h"
38 #include "winternl.h"
39 #include "thread.h"
40 #include "module.h"
41
42 #include "wine/debug.h"
43 #include "wine/unicode.h"
44 #include "wine/server.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
47 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
48
49
50 /****************************************************************************
51  *              DisableThreadLibraryCalls (KERNEL32.@)
52  *
53  * Inform the module loader that thread notifications are not required for a dll.
54  *
55  * PARAMS
56  *  hModule [I] Module handle to skip calls for
57  *
58  * RETURNS
59  *  Success: TRUE. Thread attach and detach notifications will not be sent
60  *           to hModule.
61  *  Failure: FALSE. Use GetLastError() to determine the cause.
62  *
63  * NOTES
64  *  This is typically called from the dll entry point of a dll during process
65  *  attachment, for dlls that do not need to process thread notifications.
66  */
67 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
68 {
69     NTSTATUS    nts = LdrDisableThreadCalloutsForDll( hModule );
70     if (nts == STATUS_SUCCESS) return TRUE;
71
72     SetLastError( RtlNtStatusToDosError( nts ) );
73     return FALSE;
74 }
75
76
77 /* Check whether a file is an OS/2 or a very old Windows executable
78  * by testing on import of KERNEL.
79  *
80  * FIXME: is reading the module imports the only way of discerning
81  *        old Windows binaries from OS/2 ones ? At least it seems so...
82  */
83 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
84                                                  const IMAGE_OS2_HEADER *ne)
85 {
86     DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
87     enum binary_type ret = BINARY_OS216;
88     LPWORD modtab = NULL;
89     LPSTR nametab = NULL;
90     DWORD len;
91     int i;
92
93     /* read modref table */
94     if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
95       || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
96       || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
97       || (len != ne->ne_cmod*sizeof(WORD)) )
98         goto broken;
99
100     /* read imported names table */
101     if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
102       || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
103       || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
104       || (len != ne->ne_enttab - ne->ne_imptab) )
105         goto broken;
106
107     for (i=0; i < ne->ne_cmod; i++)
108     {
109         LPSTR module = &nametab[modtab[i]];
110         TRACE("modref: %.*s\n", module[0], &module[1]);
111         if (!(strncmp(&module[1], "KERNEL", module[0])))
112         { /* very old Windows file */
113             MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
114             ret = BINARY_WIN16;
115             goto good;
116         }
117     }
118
119 broken:
120     ERR("Hmm, an error occurred. Is this binary file broken ?\n");
121
122 good:
123     HeapFree( GetProcessHeap(), 0, modtab);
124     HeapFree( GetProcessHeap(), 0, nametab);
125     SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
126     return ret;
127 }
128
129 /***********************************************************************
130  *           MODULE_GetBinaryType
131  */
132 enum binary_type MODULE_GetBinaryType( HANDLE hfile )
133 {
134     union
135     {
136         struct
137         {
138             unsigned char magic[4];
139             unsigned char ignored[12];
140             unsigned short type;
141         } elf;
142         struct
143         {
144             unsigned long magic;
145             unsigned long cputype;
146             unsigned long cpusubtype;
147             unsigned long filetype;
148         } macho;
149         IMAGE_DOS_HEADER mz;
150     } header;
151
152     char magic[4];
153     DWORD len;
154
155     /* Seek to the start of the file and read the header information. */
156     if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
157         return BINARY_UNKNOWN;
158     if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
159         return BINARY_UNKNOWN;
160
161     if (!memcmp( header.elf.magic, "\177ELF", 4 ))
162     {
163         /* FIXME: we don't bother to check byte order, architecture, etc. */
164         switch(header.elf.type)
165         {
166         case 2: return BINARY_UNIX_EXE;
167         case 3: return BINARY_UNIX_LIB;
168         }
169         return BINARY_UNKNOWN;
170     }
171
172     /* Mach-o File with Endian set to Big Endian  or Little Endian*/
173     if (header.macho.magic == 0xfeedface || header.macho.magic == 0xecafdeef)
174     {
175         switch(header.macho.filetype)
176         {
177             case 0x8: /* MH_BUNDLE */ return BINARY_UNIX_LIB;
178         }
179         return BINARY_UNKNOWN;
180     }
181
182     /* Not ELF, try DOS */
183
184     if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
185     {
186         /* We do have a DOS image so we will now try to seek into
187          * the file by the amount indicated by the field
188          * "Offset to extended header" and read in the
189          * "magic" field information at that location.
190          * This will tell us if there is more header information
191          * to read or not.
192          */
193         if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
194             return BINARY_DOS;
195         if (!ReadFile( hfile, magic, sizeof(magic), &len, NULL ) || len != sizeof(magic))
196             return BINARY_DOS;
197
198         /* Reading the magic field succeeded so
199          * we will try to determine what type it is.
200          */
201         if (!memcmp( magic, "PE\0\0", 4 ))
202         {
203             IMAGE_FILE_HEADER FileHeader;
204
205             if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
206             {
207                 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
208                 return BINARY_PE_EXE;
209             }
210             return BINARY_DOS;
211         }
212
213         if (!memcmp( magic, "NE", 2 ))
214         {
215             /* This is a Windows executable (NE) header.  This can
216              * mean either a 16-bit OS/2 or a 16-bit Windows or even a
217              * DOS program (running under a DOS extender).  To decide
218              * which, we'll have to read the NE header.
219              */
220             IMAGE_OS2_HEADER ne;
221             if (    SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) != -1
222                     && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
223                     && len == sizeof(ne) )
224             {
225                 switch ( ne.ne_exetyp )
226                 {
227                 case 2:  return BINARY_WIN16;
228                 case 5:  return BINARY_DOS;
229                 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
230                 }
231             }
232             /* Couldn't read header, so abort. */
233             return BINARY_DOS;
234         }
235
236         /* Unknown extended header, but this file is nonetheless DOS-executable. */
237         return BINARY_DOS;
238     }
239
240     return BINARY_UNKNOWN;
241 }
242
243 /***********************************************************************
244  *             GetBinaryTypeW                     [KERNEL32.@]
245  *
246  * Determine whether a file is executable, and if so, what kind.
247  *
248  * PARAMS
249  *  lpApplicationName [I] Path of the file to check
250  *  lpBinaryType      [O] Destination for the binary type
251  *
252  * RETURNS
253  *  TRUE, if the file is an executable, in which case lpBinaryType is set.
254  *  FALSE, if the file is not an executable or if the function fails.
255  *
256  * NOTES
257  *  The type of executable is a property that determines which subsytem an
258  *  executable file runs under. lpBinaryType can be set to one of the following
259  *  values:
260  *   SCS_32BIT_BINARY: A Win32 based application
261  *   SCS_DOS_BINARY: An MS-Dos based application
262  *   SCS_WOW_BINARY: A Win16 based application
263  *   SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
264  *   SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
265  *   SCS_OS216_BINARY: A 16bit OS/2 based application
266  *
267  *  To find the binary type, this function reads in the files header information.
268  *  If extended header information is not present it will assume that the file
269  *  is a DOS executable. If extended header information is present it will
270  *  determine if the file is a 16 or 32 bit Windows executable by checking the
271  *  flags in the header.
272  *
273  *  ".com" and ".pif" files are only recognized by their file name extension,
274  *  as per native Windows.
275  */
276 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
277 {
278     BOOL ret = FALSE;
279     HANDLE hfile;
280
281     TRACE("%s\n", debugstr_w(lpApplicationName) );
282
283     /* Sanity check.
284      */
285     if ( lpApplicationName == NULL || lpBinaryType == NULL )
286         return FALSE;
287
288     /* Open the file indicated by lpApplicationName for reading.
289      */
290     hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
291                          NULL, OPEN_EXISTING, 0, 0 );
292     if ( hfile == INVALID_HANDLE_VALUE )
293         return FALSE;
294
295     /* Check binary type
296      */
297     switch(MODULE_GetBinaryType( hfile ))
298     {
299     case BINARY_UNKNOWN:
300     {
301         static const WCHAR comW[] = { '.','C','O','M',0 };
302         static const WCHAR pifW[] = { '.','P','I','F',0 };
303         const WCHAR *ptr;
304
305         /* try to determine from file name */
306         ptr = strrchrW( lpApplicationName, '.' );
307         if (!ptr) break;
308         if (!strcmpiW( ptr, comW ))
309         {
310             *lpBinaryType = SCS_DOS_BINARY;
311             ret = TRUE;
312         }
313         else if (!strcmpiW( ptr, pifW ))
314         {
315             *lpBinaryType = SCS_PIF_BINARY;
316             ret = TRUE;
317         }
318         break;
319     }
320     case BINARY_PE_EXE:
321     case BINARY_PE_DLL:
322         *lpBinaryType = SCS_32BIT_BINARY;
323         ret = TRUE;
324         break;
325     case BINARY_WIN16:
326         *lpBinaryType = SCS_WOW_BINARY;
327         ret = TRUE;
328         break;
329     case BINARY_OS216:
330         *lpBinaryType = SCS_OS216_BINARY;
331         ret = TRUE;
332         break;
333     case BINARY_DOS:
334         *lpBinaryType = SCS_DOS_BINARY;
335         ret = TRUE;
336         break;
337     case BINARY_UNIX_EXE:
338     case BINARY_UNIX_LIB:
339         ret = FALSE;
340         break;
341     }
342
343     CloseHandle( hfile );
344     return ret;
345 }
346
347 /***********************************************************************
348  *             GetBinaryTypeA                     [KERNEL32.@]
349  *             GetBinaryType                      [KERNEL32.@]
350  */
351 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
352 {
353     ANSI_STRING app_nameA;
354     NTSTATUS status;
355
356     TRACE("%s\n", debugstr_a(lpApplicationName));
357
358     /* Sanity check.
359      */
360     if ( lpApplicationName == NULL || lpBinaryType == NULL )
361         return FALSE;
362
363     RtlInitAnsiString(&app_nameA, lpApplicationName);
364     status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
365                                           &app_nameA, FALSE);
366     if (!status)
367         return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
368
369     SetLastError(RtlNtStatusToDosError(status));
370     return FALSE;
371 }
372
373
374 /***********************************************************************
375  *              GetModuleHandleA         (KERNEL32.@)
376  *              GetModuleHandle32        (KERNEL.488)
377  *
378  * Get the handle of a dll loaded into the process address space.
379  *
380  * PARAMS
381  *  module [I] Name of the dll
382  *
383  * RETURNS
384  *  Success: A handle to the loaded dll.
385  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
386  */
387 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
388 {
389     NTSTATUS            nts;
390     HMODULE             ret;
391     UNICODE_STRING      wstr;
392
393     if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
394
395     RtlCreateUnicodeStringFromAsciiz(&wstr, module);
396     nts = LdrGetDllHandle(0, 0, &wstr, &ret);
397     RtlFreeUnicodeString( &wstr );
398     if (nts != STATUS_SUCCESS)
399     {
400         ret = 0;
401         SetLastError( RtlNtStatusToDosError( nts ) );
402     }
403     return ret;
404 }
405
406 /***********************************************************************
407  *              GetModuleHandleW (KERNEL32.@)
408  *
409  * Unicode version of GetModuleHandleA.
410  */
411 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
412 {
413     NTSTATUS            nts;
414     HMODULE             ret;
415     UNICODE_STRING      wstr;
416
417     if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
418
419     RtlInitUnicodeString( &wstr, module );
420     nts = LdrGetDllHandle( 0, 0, &wstr, &ret);
421     if (nts != STATUS_SUCCESS)
422     {
423         SetLastError( RtlNtStatusToDosError( nts ) );
424         ret = 0;
425     }
426     return ret;
427 }
428
429
430 /***********************************************************************
431  *              GetModuleFileNameA      (KERNEL32.@)
432  *              GetModuleFileName32     (KERNEL.487)
433  *
434  * Get the file name of a loaded module from its handle.
435  *
436  * RETURNS
437  *  Success: The length of the file name, excluding the terminating NUL.
438  *  Failure: 0. Use GetLastError() to determine the cause.
439  *
440  * NOTES
441  *  This function always returns the long path of hModule (as opposed to
442  *  GetModuleFileName16() which returns short paths when the modules version
443  *  field is < 4.0).
444  */
445 DWORD WINAPI GetModuleFileNameA(
446         HMODULE hModule,        /* [in] Module handle (32 bit) */
447         LPSTR lpFileName,       /* [out] Destination for file name */
448         DWORD size )            /* [in] Size of lpFileName in characters */
449 {
450     LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
451
452     if (!filenameW)
453     {
454         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
455         return 0;
456     }
457     GetModuleFileNameW( hModule, filenameW, size );
458     WideCharToMultiByte( CP_ACP, 0, filenameW, -1, lpFileName, size, NULL, NULL );
459     HeapFree( GetProcessHeap(), 0, filenameW );
460     return strlen( lpFileName );
461 }
462
463 /***********************************************************************
464  *              GetModuleFileNameW      (KERNEL32.@)
465  *
466  * Unicode version of GetModuleFileNameA.
467  */
468 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
469 {
470     ULONG magic;
471
472     lpFileName[0] = 0;
473
474     LdrLockLoaderLock( 0, NULL, &magic );
475     if (!hModule && !(NtCurrentTeb()->tibflags & TEBF_WIN32))
476     {
477         /* 16-bit task - get current NE module name */
478         NE_MODULE *pModule = NE_GetPtr( GetCurrentTask() );
479         if (pModule)
480         {
481             WCHAR    path[MAX_PATH];
482
483             MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
484             GetLongPathNameW(path, lpFileName, size);
485         }
486     }
487     else
488     {
489         LDR_MODULE* pldr;
490         NTSTATUS    nts;
491
492         if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
493         nts = LdrFindEntryForAddress( hModule, &pldr );
494         if (nts == STATUS_SUCCESS) lstrcpynW(lpFileName, pldr->FullDllName.Buffer, size);
495         else SetLastError( RtlNtStatusToDosError( nts ) );
496
497     }
498     LdrUnlockLoaderLock( 0, magic );
499
500     TRACE( "%s\n", debugstr_w(lpFileName) );
501     return strlenW(lpFileName);
502 }
503
504
505 /***********************************************************************
506  *           get_dll_system_path
507  */
508 static const WCHAR *get_dll_system_path(void)
509 {
510     static WCHAR *cached_path;
511
512     if (!cached_path)
513     {
514         WCHAR *p, *path;
515         int len = 3;
516
517         len += GetSystemDirectoryW( NULL, 0 );
518         len += GetWindowsDirectoryW( NULL, 0 );
519         p = path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
520         *p++ = '.';
521         *p++ = ';';
522         GetSystemDirectoryW( p, path + len - p);
523         p += strlenW(p);
524         *p++ = ';';
525         GetWindowsDirectoryW( p, path + len - p);
526         cached_path = path;
527     }
528     return cached_path;
529 }
530
531
532 /******************************************************************
533  *              MODULE_get_dll_load_path
534  *
535  * Compute the load path to use for a given dll.
536  * Returned pointer must be freed by caller.
537  */
538 WCHAR *MODULE_get_dll_load_path( LPCWSTR module )
539 {
540     static const WCHAR pathW[] = {'P','A','T','H',0};
541
542     const WCHAR *system_path = get_dll_system_path();
543     const WCHAR *mod_end = NULL;
544     UNICODE_STRING name, value;
545     WCHAR *p, *ret;
546     int len = 0, path_len = 0;
547
548     /* adjust length for module name */
549
550     if (!module) module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
551     if (module)
552     {
553         mod_end = module;
554         if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
555         if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
556         if (mod_end == module + 2 && module[1] == ':') mod_end++;
557         if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
558         len += (mod_end - module) + 1;
559     }
560     len += strlenW( system_path ) + 2;
561
562     /* get the PATH variable */
563
564     RtlInitUnicodeString( &name, pathW );
565     value.Length = 0;
566     value.MaximumLength = 0;
567     value.Buffer = NULL;
568     if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
569         path_len = value.Length;
570
571     if (!(ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) ))) return NULL;
572     p = ret;
573     if (module)
574     {
575         memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
576         p += (mod_end - module);
577         *p++ = ';';
578     }
579     strcpyW( p, system_path );
580     p += strlenW(p);
581     *p++ = ';';
582     value.Buffer = p;
583     value.MaximumLength = path_len;
584
585     while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
586     {
587         WCHAR *new_ptr;
588
589         /* grow the buffer and retry */
590         path_len = value.Length;
591         if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
592         {
593             HeapFree( GetProcessHeap(), 0, ret );
594             return NULL;
595         }
596         value.Buffer = new_ptr + (value.Buffer - ret);
597         value.MaximumLength = path_len;
598         ret = new_ptr;
599     }
600     value.Buffer[value.Length / sizeof(WCHAR)] = 0;
601     return ret;
602 }
603
604
605 /******************************************************************
606  *              load_library_as_datafile
607  */
608 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
609 {
610     static const WCHAR dotDLL[] = {'.','d','l','l',0};
611
612     WCHAR filenameW[MAX_PATH];
613     HANDLE hFile = INVALID_HANDLE_VALUE;
614     HANDLE mapping;
615     HMODULE module;
616
617     *hmod = 0;
618
619     if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
620                      filenameW, NULL ))
621     {
622         hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
623                              NULL, OPEN_EXISTING, 0, 0 );
624     }
625     if (hFile == INVALID_HANDLE_VALUE) return FALSE;
626
627     mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
628     CloseHandle( hFile );
629     if (!mapping) return FALSE;
630
631     module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
632     CloseHandle( mapping );
633     if (!module) return FALSE;
634
635     /* make sure it's a valid PE file */
636     if (!RtlImageNtHeader(module))
637     {
638         UnmapViewOfFile( module );
639         return FALSE;
640     }
641     *hmod = (HMODULE)((char *)module + 1);  /* set low bit of handle to indicate datafile module */
642     return TRUE;
643 }
644
645
646 /******************************************************************
647  *              load_library
648  *
649  * Helper for LoadLibraryExA/W.
650  */
651 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
652 {
653     NTSTATUS nts;
654     HMODULE hModule;
655     WCHAR *load_path;
656
657     if (flags & LOAD_LIBRARY_AS_DATAFILE)
658     {
659         /* The method in load_library_as_datafile allows searching for the
660          * 'native' libraries only
661          */
662         if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
663         flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
664         /* Fallback to normal behaviour */
665     }
666
667     load_path = MODULE_get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
668     nts = LdrLoadDll( load_path, flags, libname, &hModule );
669     HeapFree( GetProcessHeap(), 0, load_path );
670     if (nts != STATUS_SUCCESS)
671     {
672         hModule = 0;
673         SetLastError( RtlNtStatusToDosError( nts ) );
674     }
675     return hModule;
676 }
677
678
679 /******************************************************************
680  *              LoadLibraryExA          (KERNEL32.@)
681  *
682  * Load a dll file into the process address space.
683  *
684  * PARAMS
685  *  libname [I] Name of the file to load
686  *  hfile   [I] Reserved, must be 0.
687  *  flags   [I] Flags for loading the dll
688  *
689  * RETURNS
690  *  Success: A handle to the loaded dll.
691  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
692  *
693  * NOTES
694  * The HFILE parameter is not used and marked reserved in the SDK. I can
695  * only guess that it should force a file to be mapped, but I rather
696  * ignore the parameter because it would be extremely difficult to
697  * integrate this with different types of module representations.
698  */
699 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
700 {
701     UNICODE_STRING      wstr;
702     HMODULE             hModule;
703
704     if (!libname)
705     {
706         SetLastError(ERROR_INVALID_PARAMETER);
707         return 0;
708     }
709     RtlCreateUnicodeStringFromAsciiz( &wstr, libname );
710     hModule = load_library( &wstr, flags );
711     RtlFreeUnicodeString( &wstr );
712     return hModule;
713 }
714
715 /***********************************************************************
716  *           LoadLibraryExW       (KERNEL32.@)
717  *
718  * Unicode version of LoadLibraryExA.
719  */
720 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
721 {
722     UNICODE_STRING      wstr;
723
724     if (!libnameW)
725     {
726         SetLastError(ERROR_INVALID_PARAMETER);
727         return 0;
728     }
729     RtlInitUnicodeString( &wstr, libnameW );
730     return load_library( &wstr, flags );
731 }
732
733 /***********************************************************************
734  *           LoadLibraryA         (KERNEL32.@)
735  *
736  * Load a dll file into the process address space.
737  *
738  * PARAMS
739  *  libname [I] Name of the file to load
740  *
741  * RETURNS
742  *  Success: A handle to the loaded dll.
743  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
744  *
745  * NOTES
746  * See LoadLibraryExA().
747  */
748 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
749 {
750     return LoadLibraryExA(libname, 0, 0);
751 }
752
753 /***********************************************************************
754  *           LoadLibraryW         (KERNEL32.@)
755  *
756  * Unicode version of LoadLibraryA.
757  */
758 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
759 {
760     return LoadLibraryExW(libnameW, 0, 0);
761 }
762
763 /***********************************************************************
764  *           FreeLibrary   (KERNEL32.@)
765  *           FreeLibrary32 (KERNEL.486)
766  *
767  * Free a dll loaded into the process address space.
768  *
769  * PARAMS
770  *  hLibModule [I] Handle to the dll returned by LoadLibraryA().
771  *
772  * RETURNS
773  *  Success: TRUE. The dll is removed if it is not still in use.
774  *  Failure: FALSE. Use GetLastError() to determine the cause.
775  */
776 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
777 {
778     BOOL                retv = FALSE;
779     NTSTATUS            nts;
780
781     if (!hLibModule)
782     {
783         SetLastError( ERROR_INVALID_HANDLE );
784         return FALSE;
785     }
786
787     if ((ULONG_PTR)hLibModule & 1)
788     {
789         /* this is a LOAD_LIBRARY_AS_DATAFILE module */
790         char *ptr = (char *)hLibModule - 1;
791         UnmapViewOfFile( ptr );
792         return TRUE;
793     }
794
795     if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
796     else SetLastError( RtlNtStatusToDosError( nts ) );
797
798     return retv;
799 }
800
801 /***********************************************************************
802  *           GetProcAddress             (KERNEL32.@)
803  *
804  * Find the address of an exported symbol in a loaded dll.
805  *
806  * PARAMS
807  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
808  *  function [I] Name of the symbol, or an integer ordinal number < 16384
809  *
810  * RETURNS
811  *  Success: A pointer to the symbol in the process address space.
812  *  Failure: NULL. Use GetLastError() to determine the cause.
813  */
814 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
815 {
816     NTSTATUS    nts;
817     FARPROC     fp;
818
819     if (HIWORD(function))
820     {
821         ANSI_STRING     str;
822
823         RtlInitAnsiString( &str, function );
824         nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
825     }
826     else
827         nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
828     if (nts != STATUS_SUCCESS)
829     {
830         SetLastError( RtlNtStatusToDosError( nts ) );
831         fp = NULL;
832     }
833     return fp;
834 }
835
836 /***********************************************************************
837  *           GetProcAddress32                   (KERNEL.453)
838  *
839  * Find the address of an exported symbol in a loaded dll.
840  *
841  * PARAMS
842  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
843  *  function [I] Name of the symbol, or an integer ordinal number < 16384
844  *
845  * RETURNS
846  *  Success: A pointer to the symbol in the process address space.
847  *  Failure: NULL. Use GetLastError() to determine the cause.
848  */
849 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
850 {
851     /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
852     return GetProcAddress( hModule, function );
853 }