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