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