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