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