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