Fix subclassing to support nested messages.
[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 *path;
511
512     if (!path)
513     {
514         WCHAR *p, *exe_name;
515         int len = 3;
516
517         exe_name = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
518         if (!(p = strrchrW( exe_name, '\\' ))) p = exe_name;
519         /* include trailing backslash only on drive root */
520         if (p == exe_name + 2 && exe_name[1] == ':') p++;
521         len += p - exe_name;
522         len += GetSystemDirectoryW( NULL, 0 );
523         len += GetWindowsDirectoryW( NULL, 0 );
524         path = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
525         memcpy( path, exe_name, (p - exe_name) * sizeof(WCHAR) );
526         p = path + (p - exe_name);
527         *p++ = ';';
528         *p++ = '.';
529         *p++ = ';';
530         GetSystemDirectoryW( p, path + len - p);
531         p += strlenW(p);
532         *p++ = ';';
533         GetWindowsDirectoryW( p, path + len - p);
534     }
535     return path;
536 }
537
538
539 /******************************************************************
540  *              get_dll_load_path
541  *
542  * Compute the load path to use for a given dll.
543  * Returned pointer must be freed by caller.
544  */
545 static WCHAR *get_dll_load_path( LPCWSTR module )
546 {
547     static const WCHAR pathW[] = {'P','A','T','H',0};
548
549     const WCHAR *system_path = get_dll_system_path();
550     const WCHAR *mod_end = NULL;
551     UNICODE_STRING name, value;
552     WCHAR *p, *ret;
553     int len = 0, path_len = 0;
554
555     /* adjust length for module name */
556
557     if (module)
558     {
559         mod_end = module;
560         if ((p = strrchrW( mod_end, '\\' ))) mod_end = p;
561         if ((p = strrchrW( mod_end, '/' ))) mod_end = p;
562         if (mod_end == module + 2 && module[1] == ':') mod_end++;
563         if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
564         len += (mod_end - module);
565         system_path = strchrW( system_path, ';' );
566     }
567     len += strlenW( system_path ) + 2;
568
569     /* get the PATH variable */
570
571     RtlInitUnicodeString( &name, pathW );
572     value.Length = 0;
573     value.MaximumLength = 0;
574     value.Buffer = NULL;
575     if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
576         path_len = value.Length;
577
578     if (!(ret = HeapAlloc( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) ))) return NULL;
579     p = ret;
580     if (module)
581     {
582         memcpy( ret, module, (mod_end - module) * sizeof(WCHAR) );
583         p += (mod_end - module);
584     }
585     strcpyW( p, system_path );
586     p += strlenW(p);
587     *p++ = ';';
588     value.Buffer = p;
589     value.MaximumLength = path_len;
590
591     while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
592     {
593         WCHAR *new_ptr;
594
595         /* grow the buffer and retry */
596         path_len = value.Length;
597         if (!(new_ptr = HeapReAlloc( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
598         {
599             HeapFree( GetProcessHeap(), 0, ret );
600             return NULL;
601         }
602         value.Buffer = new_ptr + (value.Buffer - ret);
603         value.MaximumLength = path_len;
604         ret = new_ptr;
605     }
606     value.Buffer[value.Length / sizeof(WCHAR)] = 0;
607     return ret;
608 }
609
610
611 /******************************************************************
612  *              MODULE_InitLoadPath
613  *
614  * Create the initial dll load path.
615  */
616 void MODULE_InitLoadPath(void)
617 {
618     WCHAR *path = get_dll_load_path( NULL );
619     RtlInitUnicodeString( &NtCurrentTeb()->Peb->ProcessParameters->DllPath, path );
620 }
621
622
623 /******************************************************************
624  *              load_library_as_datafile
625  */
626 static BOOL load_library_as_datafile( LPCWSTR name, HMODULE* hmod)
627 {
628     static const WCHAR dotDLL[] = {'.','d','l','l',0};
629
630     WCHAR filenameW[MAX_PATH];
631     HANDLE hFile = INVALID_HANDLE_VALUE;
632     HANDLE mapping;
633     HMODULE module;
634
635     *hmod = 0;
636
637     if (SearchPathW( NULL, (LPCWSTR)name, dotDLL, sizeof(filenameW) / sizeof(filenameW[0]),
638                      filenameW, NULL ))
639     {
640         hFile = CreateFileW( filenameW, GENERIC_READ, FILE_SHARE_READ,
641                              NULL, OPEN_EXISTING, 0, 0 );
642     }
643     if (hFile == INVALID_HANDLE_VALUE) return FALSE;
644
645     mapping = CreateFileMappingW( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
646     CloseHandle( hFile );
647     if (!mapping) return FALSE;
648
649     module = MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
650     CloseHandle( mapping );
651     if (!module) return FALSE;
652
653     /* make sure it's a valid PE file */
654     if (!RtlImageNtHeader(module))
655     {
656         UnmapViewOfFile( module );
657         return FALSE;
658     }
659     *hmod = (HMODULE)((char *)module + 1);  /* set low bit of handle to indicate datafile module */
660     return TRUE;
661 }
662
663
664 /******************************************************************
665  *              load_library
666  *
667  * Helper for LoadLibraryExA/W.
668  */
669 static HMODULE load_library( const UNICODE_STRING *libname, DWORD flags )
670 {
671     NTSTATUS nts;
672     HMODULE hModule;
673     WCHAR *load_path;
674
675     if (flags & LOAD_LIBRARY_AS_DATAFILE)
676     {
677         /* The method in load_library_as_datafile allows searching for the
678          * 'native' libraries only
679          */
680         if (load_library_as_datafile( libname->Buffer, &hModule )) return hModule;
681         flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
682         /* Fallback to normal behaviour */
683     }
684
685     load_path = get_dll_load_path( flags & LOAD_WITH_ALTERED_SEARCH_PATH ? libname->Buffer : NULL );
686     nts = LdrLoadDll( load_path, flags, libname, &hModule );
687     HeapFree( GetProcessHeap(), 0, load_path );
688     if (nts != STATUS_SUCCESS)
689     {
690         hModule = 0;
691         SetLastError( RtlNtStatusToDosError( nts ) );
692     }
693     return hModule;
694 }
695
696
697 /******************************************************************
698  *              LoadLibraryExA          (KERNEL32.@)
699  *
700  * Load a dll file into the process address space.
701  *
702  * PARAMS
703  *  libname [I] Name of the file to load
704  *  hfile   [I] Reserved, must be 0.
705  *  flags   [I] Flags for loading the dll
706  *
707  * RETURNS
708  *  Success: A handle to the loaded dll.
709  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
710  *
711  * NOTES
712  * The HFILE parameter is not used and marked reserved in the SDK. I can
713  * only guess that it should force a file to be mapped, but I rather
714  * ignore the parameter because it would be extremely difficult to
715  * integrate this with different types of module representations.
716  */
717 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
718 {
719     UNICODE_STRING      wstr;
720     HMODULE             hModule;
721
722     if (!libname)
723     {
724         SetLastError(ERROR_INVALID_PARAMETER);
725         return 0;
726     }
727     RtlCreateUnicodeStringFromAsciiz( &wstr, libname );
728     hModule = load_library( &wstr, flags );
729     RtlFreeUnicodeString( &wstr );
730     return hModule;
731 }
732
733 /***********************************************************************
734  *           LoadLibraryExW       (KERNEL32.@)
735  *
736  * Unicode version of LoadLibraryExA.
737  */
738 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW, HANDLE hfile, DWORD flags)
739 {
740     UNICODE_STRING      wstr;
741
742     if (!libnameW)
743     {
744         SetLastError(ERROR_INVALID_PARAMETER);
745         return 0;
746     }
747     RtlInitUnicodeString( &wstr, libnameW );
748     return load_library( &wstr, flags );
749 }
750
751 /***********************************************************************
752  *           LoadLibraryA         (KERNEL32.@)
753  *
754  * Load a dll file into the process address space.
755  *
756  * PARAMS
757  *  libname [I] Name of the file to load
758  *
759  * RETURNS
760  *  Success: A handle to the loaded dll.
761  *  Failure: A NULL handle. Use GetLastError() to determine the cause.
762  *
763  * NOTES
764  * See LoadLibraryExA().
765  */
766 HMODULE WINAPI LoadLibraryA(LPCSTR libname)
767 {
768     return LoadLibraryExA(libname, 0, 0);
769 }
770
771 /***********************************************************************
772  *           LoadLibraryW         (KERNEL32.@)
773  *
774  * Unicode version of LoadLibraryA.
775  */
776 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
777 {
778     return LoadLibraryExW(libnameW, 0, 0);
779 }
780
781 /***********************************************************************
782  *           FreeLibrary   (KERNEL32.@)
783  *           FreeLibrary32 (KERNEL.486)
784  *
785  * Free a dll loaded into the process address space.
786  *
787  * PARAMS
788  *  hLibModule [I] Handle to the dll returned by LoadLibraryA().
789  *
790  * RETURNS
791  *  Success: TRUE. The dll is removed if it is not still in use.
792  *  Failure: FALSE. Use GetLastError() to determine the cause.
793  */
794 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
795 {
796     BOOL                retv = FALSE;
797     NTSTATUS            nts;
798
799     if (!hLibModule)
800     {
801         SetLastError( ERROR_INVALID_HANDLE );
802         return FALSE;
803     }
804
805     if ((ULONG_PTR)hLibModule & 1)
806     {
807         /* this is a LOAD_LIBRARY_AS_DATAFILE module */
808         char *ptr = (char *)hLibModule - 1;
809         UnmapViewOfFile( ptr );
810         return TRUE;
811     }
812
813     if ((nts = LdrUnloadDll( hLibModule )) == STATUS_SUCCESS) retv = TRUE;
814     else SetLastError( RtlNtStatusToDosError( nts ) );
815
816     return retv;
817 }
818
819 /***********************************************************************
820  *           GetProcAddress             (KERNEL32.@)
821  *
822  * Find the address of an exported symbol in a loaded dll.
823  *
824  * PARAMS
825  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
826  *  function [I] Name of the symbol, or an integer ordinal number < 16384
827  *
828  * RETURNS
829  *  Success: A pointer to the symbol in the process address space.
830  *  Failure: NULL. Use GetLastError() to determine the cause.
831  */
832 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
833 {
834     NTSTATUS    nts;
835     FARPROC     fp;
836
837     if (HIWORD(function))
838     {
839         ANSI_STRING     str;
840
841         RtlInitAnsiString( &str, function );
842         nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
843     }
844     else
845         nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
846     if (nts != STATUS_SUCCESS)
847     {
848         SetLastError( RtlNtStatusToDosError( nts ) );
849         fp = NULL;
850     }
851     return fp;
852 }
853
854 /***********************************************************************
855  *           GetProcAddress32                   (KERNEL.453)
856  *
857  * Find the address of an exported symbol in a loaded dll.
858  *
859  * PARAMS
860  *  hModule  [I] Handle to the dll returned by LoadLibraryA().
861  *  function [I] Name of the symbol, or an integer ordinal number < 16384
862  *
863  * RETURNS
864  *  Success: A pointer to the symbol in the process address space.
865  *  Failure: NULL. Use GetLastError() to determine the cause.
866  */
867 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
868 {
869     /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
870     return GetProcAddress( hModule, function );
871 }