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