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