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