Clear a new hardware buffer to proper silence values based on format.
[wine] / loader / 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 <stdlib.h>
26 #include <string.h>
27 #ifdef HAVE_SYS_TYPES_H
28 # include <sys/types.h>
29 #endif
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include "wine/winbase16.h"
34 #include "winerror.h"
35 #include "ntstatus.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winreg.h"
39 #include "winternl.h"
40 #include "thread.h"
41 #include "module.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         /* But before we do we will make sure that header
195          * structure encompasses the "Offset to extended header"
196          * field.
197          */
198         if (header.mz.e_lfanew < sizeof(IMAGE_DOS_HEADER))
199             return BINARY_DOS;
200         if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
201             return BINARY_DOS;
202         if (!ReadFile( hfile, magic, sizeof(magic), &len, NULL ) || len != sizeof(magic))
203             return BINARY_DOS;
204
205         /* Reading the magic field succeeded so
206          * we will try to determine what type it is.
207          */
208         if (!memcmp( magic, "PE\0\0", 4 ))
209         {
210             IMAGE_FILE_HEADER FileHeader;
211
212             if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
213             {
214                 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
215                 return BINARY_PE_EXE;
216             }
217             return BINARY_DOS;
218         }
219
220         if (!memcmp( magic, "NE", 2 ))
221         {
222             /* This is a Windows executable (NE) header.  This can
223              * mean either a 16-bit OS/2 or a 16-bit Windows or even a
224              * DOS program (running under a DOS extender).  To decide
225              * which, we'll have to read the NE header.
226              */
227             IMAGE_OS2_HEADER ne;
228             if (    SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) != -1
229                     && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
230                     && len == sizeof(ne) )
231             {
232                 switch ( ne.ne_exetyp )
233                 {
234                 case 2:  return BINARY_WIN16;
235                 case 5:  return BINARY_DOS;
236                 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
237                 }
238             }
239             /* Couldn't read header, so abort. */
240             return BINARY_DOS;
241         }
242
243         /* Unknown extended header, but this file is nonetheless DOS-executable. */
244         return BINARY_DOS;
245     }
246
247     return BINARY_UNKNOWN;
248 }
249
250 /***********************************************************************
251  *             GetBinaryTypeW                     [KERNEL32.@]
252  *
253  * Determine whether a file is executable, and if so, what kind.
254  *
255  * PARAMS
256  *  lpApplicationName [I] Path of the file to check
257  *  lpBinaryType      [O] Destination for the binary type
258  *
259  * RETURNS
260  *  TRUE, if the file is an executable, in which case lpBinaryType is set.
261  *  FALSE, if the file is not an executable or if the function fails.
262  *
263  * NOTES
264  *  The type of executable is a property that determines which subsytem an
265  *  executable file runs under. lpBinaryType can be set to one of the following
266  *  values:
267  *   SCS_32BIT_BINARY: A Win32 based application
268  *   SCS_DOS_BINARY: An MS-Dos based application
269  *   SCS_WOW_BINARY: A Win16 based application
270  *   SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
271  *   SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
272  *   SCS_OS216_BINARY: A 16bit OS/2 based application
273  *
274  *  To find the binary type, this function reads in the files header information.
275  *  If extended header information is not present it will assume that the file
276  *  is a DOS executable. If extended header information is present it will
277  *  determine if the file is a 16 or 32 bit Windows executable by checking the
278  *  flags in the header.
279  *
280  *  ".com" and ".pif" files are only recognized by their file name extension,
281  *  as per native Windows.
282  */
283 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
284 {
285     BOOL ret = FALSE;
286     HANDLE hfile;
287
288     TRACE("%s\n", debugstr_w(lpApplicationName) );
289
290     /* Sanity check.
291      */
292     if ( lpApplicationName == NULL || lpBinaryType == NULL )
293         return FALSE;
294
295     /* Open the file indicated by lpApplicationName for reading.
296      */
297     hfile = CreateFileW( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
298                          NULL, OPEN_EXISTING, 0, 0 );
299     if ( hfile == INVALID_HANDLE_VALUE )
300         return FALSE;
301
302     /* Check binary type
303      */
304     switch(MODULE_GetBinaryType( hfile ))
305     {
306     case BINARY_UNKNOWN:
307     {
308         static const WCHAR comW[] = { '.','C','O','M',0 };
309         static const WCHAR pifW[] = { '.','P','I','F',0 };
310         const WCHAR *ptr;
311
312         /* try to determine from file name */
313         ptr = strrchrW( lpApplicationName, '.' );
314         if (!ptr) break;
315         if (!strcmpiW( ptr, comW ))
316         {
317             *lpBinaryType = SCS_DOS_BINARY;
318             ret = TRUE;
319         }
320         else if (!strcmpiW( ptr, pifW ))
321         {
322             *lpBinaryType = SCS_PIF_BINARY;
323             ret = TRUE;
324         }
325         break;
326     }
327     case BINARY_PE_EXE:
328     case BINARY_PE_DLL:
329         *lpBinaryType = SCS_32BIT_BINARY;
330         ret = TRUE;
331         break;
332     case BINARY_WIN16:
333         *lpBinaryType = SCS_WOW_BINARY;
334         ret = TRUE;
335         break;
336     case BINARY_OS216:
337         *lpBinaryType = SCS_OS216_BINARY;
338         ret = TRUE;
339         break;
340     case BINARY_DOS:
341         *lpBinaryType = SCS_DOS_BINARY;
342         ret = TRUE;
343         break;
344     case BINARY_UNIX_EXE:
345     case BINARY_UNIX_LIB:
346         ret = FALSE;
347         break;
348     }
349
350     CloseHandle( hfile );
351     return ret;
352 }
353
354 /***********************************************************************
355  *             GetBinaryTypeA                     [KERNEL32.@]
356  *             GetBinaryType                      [KERNEL32.@]
357  */
358 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
359 {
360     ANSI_STRING app_nameA;
361     NTSTATUS status;
362
363     TRACE("%s\n", debugstr_a(lpApplicationName));
364
365     /* Sanity check.
366      */
367     if ( lpApplicationName == NULL || lpBinaryType == NULL )
368         return FALSE;
369
370     RtlInitAnsiString(&app_nameA, lpApplicationName);
371     status = RtlAnsiStringToUnicodeString(&NtCurrentTeb()->StaticUnicodeString,
372                                           &app_nameA, FALSE);
373     if (!status)
374         return GetBinaryTypeW(NtCurrentTeb()->StaticUnicodeString.Buffer, lpBinaryType);
375
376     SetLastError(RtlNtStatusToDosError(status));
377     return FALSE;
378 }
379
380
381 /***********************************************************************
382  *              GetModuleHandleA         (KERNEL32.@)
383  *              GetModuleHandle32        (KERNEL.488)
384  *
385  * Get the handle of a dll loaded into the process address space.
386  *
387  * PARAMS
388  *  module [I] Name of the dll
389  *
390  * RETURNS
391  *  Success: A handle to the loaded dll.
392  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
393  */
394 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
395 {
396     NTSTATUS            nts;
397     HMODULE             ret;
398     UNICODE_STRING      wstr;
399
400     if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
401
402     RtlCreateUnicodeStringFromAsciiz(&wstr, module);
403     nts = LdrGetDllHandle(0, 0, &wstr, &ret);
404     RtlFreeUnicodeString( &wstr );
405     if (nts != STATUS_SUCCESS)
406     {
407         ret = 0;
408         SetLastError( RtlNtStatusToDosError( nts ) );
409     }
410     return ret;
411 }
412
413 /***********************************************************************
414  *              GetModuleHandleW (KERNEL32.@)
415  *
416  * Unicode version of GetModuleHandleA.
417  */
418 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
419 {
420     NTSTATUS            nts;
421     HMODULE             ret;
422     UNICODE_STRING      wstr;
423
424     if (!module) return NtCurrentTeb()->Peb->ImageBaseAddress;
425
426     RtlInitUnicodeString( &wstr, module );
427     nts = LdrGetDllHandle( 0, 0, &wstr, &ret);
428     if (nts != STATUS_SUCCESS)
429     {
430         SetLastError( RtlNtStatusToDosError( nts ) );
431         ret = 0;
432     }
433     return ret;
434 }
435
436
437 /***********************************************************************
438  *              GetModuleFileNameA      (KERNEL32.@)
439  *              GetModuleFileName32     (KERNEL.487)
440  *
441  * Get the file name of a loaded module from its handle.
442  *
443  * RETURNS
444  *  Success: The length of the file name, excluding the terminating NUL.
445  *  Failure: 0. Use GetLastError() to determine the cause.
446  *
447  * NOTES
448  *  This function always returns the long path of hModule (as opposed to
449  *  GetModuleFileName16() which returns short paths when the modules version
450  *  field is < 4.0).
451  */
452 DWORD WINAPI GetModuleFileNameA(
453         HMODULE hModule,        /* [in] Module handle (32 bit) */
454         LPSTR lpFileName,       /* [out] Destination for file name */
455         DWORD size )            /* [in] Size of lpFileName in characters */
456 {
457     LPWSTR filenameW = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) );
458
459     if (!filenameW)
460     {
461         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
462         return 0;
463     }
464     GetModuleFileNameW( hModule, filenameW, size );
465     WideCharToMultiByte( CP_ACP, 0, filenameW, -1, lpFileName, size, NULL, NULL );
466     HeapFree( GetProcessHeap(), 0, filenameW );
467     return strlen( lpFileName );
468 }
469
470 /***********************************************************************
471  *              GetModuleFileNameW      (KERNEL32.@)
472  *
473  * Unicode version of GetModuleFileNameA.
474  */
475 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
476 {
477     ULONG magic;
478
479     lpFileName[0] = 0;
480
481     LdrLockLoaderLock( 0, NULL, &magic );
482     if (!hModule && !(NtCurrentTeb()->tibflags & TEBF_WIN32))
483     {
484         /* 16-bit task - get current NE module name */
485         NE_MODULE *pModule = NE_GetPtr( GetCurrentTask() );
486         if (pModule)
487         {
488             WCHAR    path[MAX_PATH];
489
490             MultiByteToWideChar( CP_ACP, 0, NE_MODULE_NAME(pModule), -1, path, MAX_PATH );
491             GetLongPathNameW(path, lpFileName, size);
492         }
493     }
494     else
495     {
496         LDR_MODULE* pldr;
497         NTSTATUS    nts;
498
499         if (!hModule) hModule = NtCurrentTeb()->Peb->ImageBaseAddress;
500         nts = LdrFindEntryForAddress( hModule, &pldr );
501         if (nts == STATUS_SUCCESS) lstrcpynW(lpFileName, pldr->FullDllName.Buffer, size);
502         else SetLastError( RtlNtStatusToDosError( nts ) );
503
504     }
505     LdrUnlockLoaderLock( 0, magic );
506
507     TRACE( "%s\n", debugstr_w(lpFileName) );
508     return strlenW(lpFileName);
509 }
510
511
512 /***********************************************************************
513  *           get_dll_system_path
514  */
515 static const WCHAR *get_dll_system_path(void)
516 {
517     static WCHAR *path;
518
519     if (!path)
520     {
521         WCHAR *p, *exe_name;
522         int len = 3;
523
524         exe_name = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
525         if (!(p = strrchrW( exe_name, '\\' ))) p = exe_name;
526         /* include trailing backslash only on drive root */
527         if (p == exe_name + 2 && exe_name[1] == ':') p++;
528         len += p - exe_name;
529         len += GetSystemDirectoryW( NULL, 0 );
530         len += GetWindowsDirectoryW( NULL, 0 );
531         path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
532         memcpy( path, exe_name, (p - exe_name) * sizeof(WCHAR) );
533         p = path + (p - exe_name);
534         *p++ = ';';
535         *p++ = '.';
536         *p++ = ';';
537         GetSystemDirectoryW( p, path + len - p);
538         p += strlenW(p);
539         *p++ = ';';
540         GetWindowsDirectoryW( p, path + len - p);
541     }
542     return path;
543 }
544
545
546 /******************************************************************
547  *              get_dll_load_path
548  *
549  * Compute the load path to use for a given dll.
550  * Returned pointer must be freed by caller.
551  */
552 static WCHAR *get_dll_load_path( LPCWSTR module )
553 {
554     static const WCHAR pathW[] = {'P','A','T','H',0};
555
556     const WCHAR *system_path = get_dll_system_path();
557     const WCHAR *mod_end = NULL;
558     UNICODE_STRING name, value;
559     WCHAR *p, *ret;
560     int len = 0, path_len = 0;
561
562     /* adjust length for module name */
563
564     if (module)
565     {
566         mod_end = module;
567         if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
568         if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
569         if (mod_end == module + 2 && module[1] == ':') mod_end++;
570         if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
571         len += (mod_end - module);
572         system_path = strchrW( system_path, ';' );
573     }
574     len += strlenW( system_path ) + 2;
575
576     /* get the PATH variable */
577
578     RtlInitUnicodeString( &name, pathW );
579     value.Length = 0;
580     value.MaximumLength = 0;
581     value.Buffer = NULL;
582     if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
583         path_len = value.Length;
584
585     if (!(ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) ))) return NULL;
586     p = ret;
587     if (module)
588     {
589         memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
590         p += (mod_end - module);
591     }
592     strcpyW( p, system_path );
593     p += strlenW(p);
594     *p++ = ';';
595     value.Buffer = p;
596     value.MaximumLength = path_len;
597
598     while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
599     {
600         WCHAR *new_ptr;
601
602         /* grow the buffer and retry */
603         path_len = value.Length;
604         if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
605         {
606             HeapFree( GetProcessHeap(), 0, ret );
607             return NULL;
608         }
609         value.Buffer = new_ptr + (value.Buffer - ret);
610         value.MaximumLength = path_len;
611         ret = new_ptr;
612     }
613     value.Buffer[value.Length / sizeof(WCHAR)] = 0;
614     return ret;
615 }
616
617
618 /******************************************************************
619  *              MODULE_InitLoadPath
620  *
621  * Create the initial dll load path.
622  */
623 void MODULE_InitLoadPath(void)
624 {
625     WCHAR *path = get_dll_load_path( NULL );
626     RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath, path );
627 }
628
629
630 /******************************************************************
631  *              load_library_as_datafile
632  */
633 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
634 {
635     static const WCHAR dotDLL[] = {'.','d','l','l',0};
636
637     WCHAR filenameW[MAX_PATH];
638     HANDLE hFile = INVALID_HANDLE_VALUE;
639     HANDLE mapping;
640     HMODULE module;
641
642     *hmod = 0;
643
644     if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
645                      filenameW, NULL ))
646     {
647         hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
648                              NULL, OPEN_EXISTING, 0, 0 );
649     }
650     if (hFile == INVALID_HANDLE_VALUE) return FALSE;
651
652     mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
653     CloseHandle( hFile );
654     if (!mapping) return FALSE;
655
656     module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
657     CloseHandle( mapping );
658     if (!module) return FALSE;
659
660     /* make sure it's a valid PE file */
661     if (!RtlImageNtHeader(module))
662     {
663         UnmapViewOfFile( module );
664         return FALSE;
665     }
666     *hmod = (HMODULE)((char *)module + 1);  /* set low bit of handle to indicate datafile module */
667     return TRUE;
668 }
669
670
671 /******************************************************************
672  *              load_library
673  *
674  * Helper for LoadLibraryExA/W.
675  */
676 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
677 {
678     NTSTATUS nts;
679     HMODULE hModule;
680     WCHAR *load_path;
681
682     if (flags & LOAD_LIBRARY_AS_DATAFILE)
683     {
684         /* The method in load_library_as_datafile allows searching for the
685          * 'native' libraries only
686          */
687         if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
688         flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
689         /* Fallback to normal behaviour */
690     }
691
692     load_path = get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
693     nts = LdrLoadDll( load_path, flags, libname, &hModule );
694     HeapFree( GetProcessHeap(), 0, load_path );
695     if (nts != STATUS_SUCCESS)
696     {
697         hModule = 0;
698         SetLastError( RtlNtStatusToDosError( nts ) );
699     }
700     return hModule;
701 }
702
703
704 /******************************************************************
705  *              LoadLibraryExA          (KERNEL32.@)
706  *
707  * Load a dll file into the process address space.
708  *
709  * PARAMS
710  *  libname [I] Name of the file to load
711  *  hfile   [I] Reserved, must be 0.
712  *  flags   [I] Flags for loading the dll
713  *
714  * RETURNS
715  *  Success: A handle to the loaded dll.
716  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
717  *
718  * NOTES
719  * The HFILE parameter is not used and marked reserved in the SDK. I can
720  * only guess that it should force a file to be mapped, but I rather
721  * ignore the parameter because it would be extremely difficult to
722  * integrate this with different types of module representations.
723  */
724 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
725 {
726     UNICODE_STRING      wstr;
727     HMODULE             hModule;
728
729     if (!libname)
730     {
731         SetLastError(ERROR_INVALID_PARAMETER);
732         return 0;
733     }
734     RtlCreateUnicodeStringFromAsciiz( &wstr, libname );
735     hModule = load_library( &wstr, flags );
736     RtlFreeUnicodeString( &wstr );
737     return hModule;
738 }
739
740 /***********************************************************************
741  *           LoadLibraryExW       (KERNEL32.@)
742  *
743  * Unicode version of LoadLibraryExA.
744  */
745 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
746 {
747     UNICODE_STRING      wstr;
748
749     if (!libnameW)
750     {
751         SetLastError(ERROR_INVALID_PARAMETER);
752         return 0;
753     }
754     RtlInitUnicodeString( &wstr, libnameW );
755     return load_library( &wstr, flags );
756 }
757
758 /***********************************************************************
759  *           LoadLibraryA         (KERNEL32.@)
760  *
761  * Load a dll file into the process address space.
762  *
763  * PARAMS
764  *  libname [I] Name of the file to load
765  *
766  * RETURNS
767  *  Success: A handle to the loaded dll.
768  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
769  *
770  * NOTES
771  * See LoadLibraryExA().
772  */
773 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
774 {
775     return LoadLibraryExA(libname, 0, 0);
776 }
777
778 /***********************************************************************
779  *           LoadLibraryW         (KERNEL32.@)
780  *
781  * Unicode version of LoadLibraryA.
782  */
783 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
784 {
785     return LoadLibraryExW(libnameW, 0, 0);
786 }
787
788 /***********************************************************************
789  *           FreeLibrary   (KERNEL32.@)
790  *           FreeLibrary32 (KERNEL.486)
791  *
792  * Free a dll loaded into the process address space.
793  *
794  * PARAMS
795  *  hLibModule [I] Handle to the dll returned by LoadLibraryA().
796  *
797  * RETURNS
798  *  Success: TRUE. The dll is removed if it is not still in use.
799  *  Failure: FALSE. Use GetLastError() to determine the cause.
800  */
801 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
802 {
803     BOOL                retv = FALSE;
804     NTSTATUS            nts;
805
806     if (!hLibModule)
807     {
808         SetLastError( ERROR_INVALID_HANDLE );
809         return FALSE;
810     }
811
812     if ((ULONG_PTR)hLibModule & 1)
813     {
814         /* this is a LOAD_LIBRARY_AS_DATAFILE module */
815         char *ptr = (char *)hLibModule - 1;
816         UnmapViewOfFile( ptr );
817         return TRUE;
818     }
819
820     if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
821     else SetLastError( RtlNtStatusToDosError( nts ) );
822
823     return retv;
824 }
825
826 /***********************************************************************
827  *           GetProcAddress             (KERNEL32.@)
828  *
829  * Find the address of an exported symbol in a loaded dll.
830  *
831  * PARAMS
832  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
833  *  function [I] Name of the symbol, or an integer ordinal number < 16384
834  *
835  * RETURNS
836  *  Success: A pointer to the symbol in the process address space.
837  *  Failure: NULL. Use GetLastError() to determine the cause.
838  */
839 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
840 {
841     NTSTATUS    nts;
842     FARPROC     fp;
843
844     if (HIWORD(function))
845     {
846         ANSI_STRING     str;
847
848         RtlInitAnsiString( &str, function );
849         nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
850     }
851     else
852         nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
853     if (nts != STATUS_SUCCESS)
854     {
855         SetLastError( RtlNtStatusToDosError( nts ) );
856         fp = NULL;
857     }
858     return fp;
859 }
860
861 /***********************************************************************
862  *           GetProcAddress32                   (KERNEL.453)
863  *
864  * Find the address of an exported symbol in a loaded dll.
865  *
866  * PARAMS
867  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
868  *  function [I] Name of the symbol, or an integer ordinal number < 16384
869  *
870  * RETURNS
871  *  Success: A pointer to the symbol in the process address space.
872  *  Failure: NULL. Use GetLastError() to determine the cause.
873  */
874 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
875 {
876     /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
877     return GetProcAddress( hModule, function );
878 }