4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "wine/port.h"
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
32 #define WIN32_NO_STATUS
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "wine/pthread.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
43 #include "ntdll_misc.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module
);
47 WINE_DECLARE_DEBUG_CHANNEL(relay
);
48 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
49 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
50 WINE_DECLARE_DEBUG_CHANNEL(imports
);
52 /* we don't want to include winuser.h */
53 #define RT_MANIFEST ((ULONG_PTR)24)
54 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
56 extern struct wine_pthread_functions pthread_functions
;
58 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
60 static int process_detaching
= 0; /* set on process detach to avoid deadlocks with thread detach */
61 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
63 static const char * const reason_names
[] =
69 NULL
, NULL
, NULL
, NULL
,
73 static const WCHAR dllW
[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
80 struct _wine_modref
**deps
;
83 /* info about the current builtin dll load */
84 /* used to keep track of things across the register_dll constructor call */
85 struct builtin_load_info
87 const WCHAR
*load_path
;
88 const WCHAR
*filename
;
93 static struct builtin_load_info default_load_info
;
94 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
96 static HANDLE main_exe_file
;
97 static UINT tls_module_count
; /* number of modules with TLS directory */
98 static UINT tls_total_size
; /* total size of TLS storage */
99 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
101 UNICODE_STRING windows_dir
= { 0, 0, NULL
}; /* windows directory */
102 UNICODE_STRING system_dir
= { 0, 0, NULL
}; /* system directory */
104 static RTL_CRITICAL_SECTION loader_section
;
105 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
107 0, 0, &loader_section
,
108 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
109 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
111 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
113 static WINE_MODREF
*cached_modref
;
114 static WINE_MODREF
*current_modref
;
115 static WINE_MODREF
*last_failed_modref
;
117 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
118 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
119 DWORD exp_size
, const char *name
, int hint
);
121 /* convert PE image VirtualAddress to Real Address */
122 static inline void *get_rva( HMODULE module
, DWORD va
)
124 return (void *)((char *)module
+ va
);
127 /* check whether the file name contains a path */
128 static inline int contains_path( LPCWSTR name
)
130 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
133 /* convert from straight ASCII to Unicode without depending on the current codepage */
134 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
136 while (len
--) *dst
++ = (unsigned char)*src
++;
140 /*************************************************************************
141 * call_dll_entry_point
143 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
144 * their entry point, so we need a small asm wrapper.
147 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
148 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
156 "movl 8(%ebp),%eax\n\t"
158 "leal -4(%ebp),%esp\n\t"
163 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
164 UINT reason
, void *reserved
)
166 return proc( module
, reason
, reserved
);
168 #endif /* __i386__ */
172 /*************************************************************************
175 * Entry point for stub functions.
177 static void stub_entry_point( const char *dll
, const char *name
, ... )
179 EXCEPTION_RECORD rec
;
181 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
182 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
183 rec
.ExceptionRecord
= NULL
;
185 rec
.ExceptionAddress
= __builtin_return_address(0);
187 rec
.ExceptionAddress
= *((void **)&dll
- 1);
189 rec
.NumberParameters
= 2;
190 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
191 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
192 for (;;) RtlRaiseException( &rec
);
196 #include "pshpack1.h"
199 BYTE popl_eax
; /* popl %eax */
200 BYTE pushl1
; /* pushl $name */
202 BYTE pushl2
; /* pushl $dll */
204 BYTE pushl_eax
; /* pushl %eax */
205 BYTE jmp
; /* jmp stub_entry_point */
210 /*************************************************************************
213 * Allocate a stub entry point.
215 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
217 #define MAX_SIZE 65536
218 static struct stub
*stubs
;
219 static unsigned int nb_stubs
;
222 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
226 SIZE_T size
= MAX_SIZE
;
227 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
228 MEM_COMMIT
, PAGE_EXECUTE_WRITECOPY
) != STATUS_SUCCESS
)
231 stub
= &stubs
[nb_stubs
++];
232 stub
->popl_eax
= 0x58; /* popl %eax */
233 stub
->pushl1
= 0x68; /* pushl $name */
235 stub
->pushl2
= 0x68; /* pushl $dll */
237 stub
->pushl_eax
= 0x50; /* pushl %eax */
238 stub
->jmp
= 0xe9; /* jmp stub_entry_point */
239 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
240 return (ULONG_PTR
)stub
;
244 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
245 #endif /* __i386__ */
248 /*************************************************************************
251 * Looks for the referenced HMODULE in the current process
252 * The loader_section must be locked while calling this function.
254 static WINE_MODREF
*get_modref( HMODULE hmod
)
256 PLIST_ENTRY mark
, entry
;
259 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
261 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
262 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
264 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
265 if (mod
->BaseAddress
== hmod
)
266 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
267 if (mod
->BaseAddress
> (void*)hmod
) break;
273 /**********************************************************************
274 * find_basename_module
276 * Find a module from its base name.
277 * The loader_section must be locked while calling this function
279 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
281 PLIST_ENTRY mark
, entry
;
283 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
284 return cached_modref
;
286 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
287 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
289 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
290 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
292 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
293 return cached_modref
;
300 /**********************************************************************
301 * find_fullname_module
303 * Find a module from its full path name.
304 * The loader_section must be locked while calling this function
306 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
308 PLIST_ENTRY mark
, entry
;
310 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
311 return cached_modref
;
313 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
314 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
316 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
317 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
319 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
320 return cached_modref
;
327 /*************************************************************************
328 * find_forwarded_export
330 * Find the final function pointer for a forwarded function.
331 * The loader_section must be locked while calling this function.
333 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
)
335 const IMAGE_EXPORT_DIRECTORY
*exports
;
339 const char *end
= strrchr(forward
, '.');
342 if (!end
) return NULL
;
343 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
344 ascii_to_unicode( mod_name
, forward
, end
- forward
);
345 mod_name
[end
- forward
] = 0;
346 if (!strchrW( mod_name
, '.' ))
348 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
349 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
352 if (!(wm
= find_basename_module( mod_name
)))
354 ERR("module not found for forward '%s' used by %s\n",
355 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
358 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
359 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
360 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1 );
364 ERR("function not found for forward '%s' used by %s."
365 " If you are using builtin %s, try using the native one instead.\n",
366 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
367 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
373 /*************************************************************************
374 * find_ordinal_export
376 * Find an exported function by ordinal.
377 * The exports base must have been subtracted from the ordinal already.
378 * The loader_section must be locked while calling this function.
380 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
381 DWORD exp_size
, DWORD ordinal
)
384 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
386 if (ordinal
>= exports
->NumberOfFunctions
)
388 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
391 if (!functions
[ordinal
]) return NULL
;
393 proc
= get_rva( module
, functions
[ordinal
] );
395 /* if the address falls into the export dir, it's a forward */
396 if (((const char *)proc
>= (const char *)exports
) &&
397 ((const char *)proc
< (const char *)exports
+ exp_size
))
398 return find_forwarded_export( module
, (const char *)proc
);
402 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
403 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
407 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
408 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
414 /*************************************************************************
417 * Find an exported function by name.
418 * The loader_section must be locked while calling this function.
420 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
421 DWORD exp_size
, const char *name
, int hint
)
423 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
424 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
425 int min
= 0, max
= exports
->NumberOfNames
- 1;
427 /* first check the hint */
428 if (hint
>= 0 && hint
<= max
)
430 char *ename
= get_rva( module
, names
[hint
] );
431 if (!strcmp( ename
, name
))
432 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
] );
435 /* then do a binary search */
438 int res
, pos
= (min
+ max
) / 2;
439 char *ename
= get_rva( module
, names
[pos
] );
440 if (!(res
= strcmp( ename
, name
)))
441 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
] );
442 if (res
> 0) max
= pos
- 1;
450 /*************************************************************************
453 * Import the dll specified by the given import descriptor.
454 * The loader_section must be locked while calling this function.
456 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
461 const IMAGE_EXPORT_DIRECTORY
*exports
;
463 const IMAGE_THUNK_DATA
*import_list
;
464 IMAGE_THUNK_DATA
*thunk_list
;
466 const char *name
= get_rva( module
, descr
->Name
);
467 DWORD len
= strlen(name
);
469 SIZE_T protect_size
= 0;
472 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
473 if (descr
->u
.OriginalFirstThunk
)
474 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
476 import_list
= thunk_list
;
478 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
480 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
482 ascii_to_unicode( buffer
, name
, len
);
484 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
486 else /* need to allocate a larger buffer */
488 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
489 if (!ptr
) return NULL
;
490 ascii_to_unicode( ptr
, name
, len
);
492 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
493 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
498 if (status
== STATUS_DLL_NOT_FOUND
)
499 ERR("Library %s (which is needed by %s) not found\n",
500 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
502 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
503 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
507 /* unprotect the import address table since it can be located in
508 * readonly section */
509 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
510 protect_base
= thunk_list
;
511 protect_size
*= sizeof(*thunk_list
);
512 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
513 &protect_size
, PAGE_WRITECOPY
, &protect_old
);
515 imp_mod
= wmImp
->ldr
.BaseAddress
;
516 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
520 /* set all imported function to deadbeef */
521 while (import_list
->u1
.Ordinal
)
523 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
525 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
526 WARN("No implementation for %s.%d", name
, ordinal
);
527 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
531 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
532 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
533 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
535 WARN(" imported from %s, allocating stub %p\n",
536 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
537 (void *)thunk_list
->u1
.Function
);
544 while (import_list
->u1
.Ordinal
)
546 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
548 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
550 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
551 ordinal
- exports
->Base
);
552 if (!thunk_list
->u1
.Function
)
554 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
555 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
556 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
557 (void *)thunk_list
->u1
.Function
);
559 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
561 else /* import by name */
563 IMAGE_IMPORT_BY_NAME
*pe_name
;
564 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
565 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
566 (const char*)pe_name
->Name
, pe_name
->Hint
);
567 if (!thunk_list
->u1
.Function
)
569 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
570 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
571 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
572 (void *)thunk_list
->u1
.Function
);
574 TRACE_(imports
)("--- %s %s.%d = %p\n",
575 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
582 /* restore old protection of the import address table */
583 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
588 /***********************************************************************
589 * create_module_activation_context
591 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
594 LDR_RESOURCE_INFO info
;
595 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
597 info
.Type
= RT_MANIFEST
;
598 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
600 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
603 ctx
.cbSize
= sizeof(ctx
);
605 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
606 ctx
.hModule
= module
->BaseAddress
;
607 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
608 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
614 /****************************************************************
617 * Fixup all imports of a given module.
618 * The loader_section must be locked while calling this function.
620 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
623 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
629 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
630 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
632 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
633 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
634 return STATUS_SUCCESS
;
637 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
639 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
641 if (!create_module_activation_context( &wm
->ldr
))
642 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
644 /* Allocate module dependency list */
645 wm
->nDeps
= nb_imports
;
646 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
648 /* load the imported modules. They are automatically
649 * added to the modref list of the process.
651 prev
= current_modref
;
653 status
= STATUS_SUCCESS
;
654 for (i
= 0; i
< nb_imports
; i
++)
656 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
657 status
= STATUS_DLL_NOT_FOUND
;
659 current_modref
= prev
;
660 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
665 /*************************************************************************
668 * Allocate a WINE_MODREF structure and add it to the process list
669 * The loader_section must be locked while calling this function.
671 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
675 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
676 PLIST_ENTRY entry
, mark
;
678 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
683 wm
->ldr
.BaseAddress
= hModule
;
684 wm
->ldr
.EntryPoint
= NULL
;
685 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
686 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
687 wm
->ldr
.LoadCount
= 1;
688 wm
->ldr
.TlsIndex
= -1;
689 wm
->ldr
.SectionHandle
= NULL
;
690 wm
->ldr
.CheckSum
= 0;
691 wm
->ldr
.TimeDateStamp
= 0;
692 wm
->ldr
.ActivationContext
= 0;
694 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
695 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
696 else p
= wm
->ldr
.FullDllName
.Buffer
;
697 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
699 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
701 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
702 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
703 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
706 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
707 &wm
->ldr
.InLoadOrderModuleList
);
709 /* insert module in MemoryList, sorted in increasing base addresses */
710 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
711 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
713 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
716 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
717 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
718 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
719 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
721 /* wait until init is called for inserting into this list */
722 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
723 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
725 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
727 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
728 VIRTUAL_SetForceExec( TRUE
);
734 /*************************************************************************
737 * Allocate the process-wide structure for module TLS storage.
739 static NTSTATUS
alloc_process_tls(void)
741 PLIST_ENTRY mark
, entry
;
743 const IMAGE_TLS_DIRECTORY
*dir
;
746 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
747 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
749 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
750 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
751 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
753 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
755 tls_total_size
+= size
;
758 if (!tls_module_count
) return STATUS_SUCCESS
;
760 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
762 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
763 if (!tls_dirs
) return STATUS_NO_MEMORY
;
765 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
767 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
768 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
769 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
772 *(DWORD
*)dir
->AddressOfIndex
= i
;
774 mod
->LoadCount
= -1; /* can't unload it */
777 return STATUS_SUCCESS
;
781 /*************************************************************************
784 * Allocate the per-thread structure for module TLS storage.
786 static NTSTATUS
alloc_thread_tls(void)
792 if (!tls_module_count
) return STATUS_SUCCESS
;
794 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0,
795 tls_module_count
* sizeof(*pointers
) )))
796 return STATUS_NO_MEMORY
;
798 if (!(data
= RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size
)))
800 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
801 return STATUS_NO_MEMORY
;
804 for (i
= 0; i
< tls_module_count
; i
++)
806 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
807 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
809 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
810 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
811 (void *)dir
->StartAddressOfRawData
, data
);
814 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
816 memset( data
, 0, dir
->SizeOfZeroFill
);
817 data
+= dir
->SizeOfZeroFill
;
819 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
820 return STATUS_SUCCESS
;
824 /*************************************************************************
827 static void call_tls_callbacks( HMODULE module
, UINT reason
)
829 const IMAGE_TLS_DIRECTORY
*dir
;
830 const PIMAGE_TLS_CALLBACK
*callback
;
833 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
834 if (!dir
|| !dir
->AddressOfCallBacks
) return;
836 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
839 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
840 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
843 (*callback
)( module
, reason
, NULL
);
848 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
849 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
854 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
855 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
860 /*************************************************************************
863 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
867 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
868 void *module
= wm
->ldr
.BaseAddress
;
870 /* Skip calls for modules loaded with special load flags */
872 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
873 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
874 if (!entry
) return TRUE
;
878 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
879 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
880 mod_name
[len
/ sizeof(WCHAR
)] = 0;
881 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
882 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
883 reason_names
[reason
], lpReserved
);
885 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
886 reason_names
[reason
], lpReserved
);
888 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
890 /* The state of the module list may have changed due to the call
891 to the dll. We cannot assume that this module has not been
894 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
895 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
896 reason_names
[reason
], lpReserved
, retv
);
897 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
903 /*************************************************************************
906 * Send the process attach notification to all DLLs the given module
907 * depends on (recursively). This is somewhat complicated due to the fact that
909 * - we have to respect the module dependencies, i.e. modules implicitly
910 * referenced by another module have to be initialized before the module
911 * itself can be initialized
913 * - the initialization routine of a DLL can itself call LoadLibrary,
914 * thereby introducing a whole new set of dependencies (even involving
915 * the 'old' modules) at any time during the whole process
917 * (Note that this routine can be recursively entered not only directly
918 * from itself, but also via LoadLibrary from one of the called initialization
921 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
922 * the process *detach* notifications to be sent in the correct order.
923 * This must not only take into account module dependencies, but also
924 * 'hidden' dependencies created by modules calling LoadLibrary in their
925 * attach notification routine.
927 * The strategy is rather simple: we move a WINE_MODREF to the head of the
928 * list after the attach notification has returned. This implies that the
929 * detach notifications are called in the reverse of the sequence the attach
930 * notifications *returned*.
932 * The loader_section must be locked while calling this function.
934 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
936 NTSTATUS status
= STATUS_SUCCESS
;
940 if (process_detaching
) return status
;
942 /* prevent infinite recursion in case of cyclical dependencies */
943 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
944 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
947 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
949 /* Tag current MODREF to prevent recursive loop */
950 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
951 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
952 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
954 /* Recursively attach all DLLs this one depends on */
955 for ( i
= 0; i
< wm
->nDeps
; i
++ )
957 if (!wm
->deps
[i
]) continue;
958 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
961 /* Call DLL entry point */
962 if (status
== STATUS_SUCCESS
)
964 WINE_MODREF
*prev
= current_modref
;
966 if (MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
))
968 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
972 /* point to the name so LdrInitializeThunk can print it */
973 last_failed_modref
= wm
;
974 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
975 status
= STATUS_DLL_INIT_FAILED
;
977 current_modref
= prev
;
980 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
981 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
982 &wm
->ldr
.InInitializationOrderModuleList
);
984 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
985 /* Remove recursion flag */
986 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
988 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
993 /**********************************************************************
994 * attach_implicitly_loaded_dlls
996 * Attach to the (builtin) dlls that have been implicitly loaded because
997 * of a dependency at the Unix level, but not imported at the Win32 level.
999 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1003 PLIST_ENTRY mark
, entry
;
1005 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1006 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1008 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1010 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1011 TRACE( "found implicitly loaded %s, attaching to it\n",
1012 debugstr_w(mod
->BaseDllName
.Buffer
));
1013 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1014 break; /* restart the search from the start */
1016 if (entry
== mark
) break; /* nothing found */
1021 /*************************************************************************
1024 * Send DLL process detach notifications. See the comment about calling
1025 * sequence at process_attach. Unless the bForceDetach flag
1026 * is set, only DLLs with zero refcount are notified.
1028 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
1030 PLIST_ENTRY mark
, entry
;
1033 RtlEnterCriticalSection( &loader_section
);
1034 if (bForceDetach
) process_detaching
= 1;
1035 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1038 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1040 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1041 InInitializationOrderModuleList
);
1042 /* Check whether to detach this DLL */
1043 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1045 if ( mod
->LoadCount
&& !bForceDetach
)
1048 /* Call detach notification */
1049 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1050 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1051 DLL_PROCESS_DETACH
, lpReserved
);
1053 /* Restart at head of WINE_MODREF list, as entries might have
1054 been added and/or removed while performing the call ... */
1057 } while (entry
!= mark
);
1059 RtlLeaveCriticalSection( &loader_section
);
1062 /*************************************************************************
1063 * MODULE_DllThreadAttach
1065 * Send DLL thread attach notifications. These are sent in the
1066 * reverse sequence of process detach notification.
1069 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1071 PLIST_ENTRY mark
, entry
;
1075 /* don't do any attach calls if process is exiting */
1076 if (process_detaching
) return STATUS_SUCCESS
;
1077 /* FIXME: there is still a race here */
1079 RtlEnterCriticalSection( &loader_section
);
1081 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1083 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1084 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1086 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1087 InInitializationOrderModuleList
);
1088 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1090 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1093 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1094 DLL_THREAD_ATTACH
, lpReserved
);
1098 RtlLeaveCriticalSection( &loader_section
);
1102 /******************************************************************
1103 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1106 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1109 NTSTATUS ret
= STATUS_SUCCESS
;
1111 RtlEnterCriticalSection( &loader_section
);
1113 wm
= get_modref( hModule
);
1114 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1115 ret
= STATUS_DLL_NOT_FOUND
;
1117 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1119 RtlLeaveCriticalSection( &loader_section
);
1124 /******************************************************************
1125 * LdrFindEntryForAddress (NTDLL.@)
1127 * The loader_section must be locked while calling this function
1129 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1131 PLIST_ENTRY mark
, entry
;
1134 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1135 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1137 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1138 if ((const void *)mod
->BaseAddress
<= addr
&&
1139 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1142 return STATUS_SUCCESS
;
1144 if ((const void *)mod
->BaseAddress
> addr
) break;
1146 return STATUS_NO_MORE_ENTRIES
;
1149 /******************************************************************
1150 * LdrLockLoaderLock (NTDLL.@)
1152 * Note: flags are not implemented.
1153 * Flag 0x01 is used to raise exceptions on errors.
1154 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1156 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1158 if (flags
) FIXME( "flags %x not supported\n", flags
);
1160 if (result
) *result
= 1;
1161 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1162 RtlEnterCriticalSection( &loader_section
);
1163 *magic
= GetCurrentThreadId();
1164 return STATUS_SUCCESS
;
1168 /******************************************************************
1169 * LdrUnlockLoaderUnlock (NTDLL.@)
1171 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1175 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1176 RtlLeaveCriticalSection( &loader_section
);
1178 return STATUS_SUCCESS
;
1182 /******************************************************************
1183 * LdrGetProcedureAddress (NTDLL.@)
1185 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1186 ULONG ord
, PVOID
*address
)
1188 IMAGE_EXPORT_DIRECTORY
*exports
;
1190 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1192 RtlEnterCriticalSection( &loader_section
);
1194 /* check if the module itself is invalid to return the proper error */
1195 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1196 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1197 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1199 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
1200 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
1204 ret
= STATUS_SUCCESS
;
1208 RtlLeaveCriticalSection( &loader_section
);
1213 /***********************************************************************
1216 * Check if a loaded native dll is a Wine fake dll.
1218 static BOOL
is_fake_dll( const void *base
)
1220 static const char fakedll_signature
[] = "Wine placeholder DLL";
1221 const IMAGE_DOS_HEADER
*dos
= base
;
1223 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1224 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1229 /***********************************************************************
1230 * get_builtin_fullname
1232 * Build the full pathname for a builtin dll.
1234 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1236 static const WCHAR soW
[] = {'.','s','o',0};
1237 WCHAR
*p
, *fullname
;
1238 size_t i
, len
= strlen(filename
);
1240 /* check if path can correspond to the dll we have */
1241 if (path
&& (p
= strrchrW( path
, '\\' )))
1244 for (i
= 0; i
< len
; i
++)
1245 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1246 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1248 /* the filename matches, use path as the full path */
1250 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1252 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1259 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1260 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1262 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1263 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1264 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1265 ascii_to_unicode( p
, filename
, len
+ 1 );
1271 /***********************************************************************
1272 * load_builtin_callback
1274 * Load a library in memory; callback function for wine_dll_register
1276 static void load_builtin_callback( void *module
, const char *filename
)
1278 static const WCHAR emptyW
[1];
1280 IMAGE_NT_HEADERS
*nt
;
1283 const WCHAR
*load_path
;
1288 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1291 if (!(nt
= RtlImageNtHeader( module
)))
1293 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1294 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1298 size
= nt
->OptionalHeader
.SizeOfImage
;
1299 NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 0, &size
,
1300 MEM_SYSTEM
| MEM_IMAGE
, PAGE_EXECUTE_WRITECOPY
);
1301 /* create the MODREF */
1303 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1305 ERR( "can't load %s\n", filename
);
1306 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1310 wm
= alloc_module( module
, fullname
);
1311 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1314 ERR( "can't load %s\n", filename
);
1315 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1318 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1320 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1321 !NtCurrentTeb()->Peb
->ImageBaseAddress
) /* if we already have an executable, ignore this one */
1323 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1329 load_path
= builtin_load_info
->load_path
;
1330 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1331 if (!load_path
) load_path
= emptyW
;
1332 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1334 /* the module has only be inserted in the load & memory order lists */
1335 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1336 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1337 /* FIXME: free the modref */
1338 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1343 builtin_load_info
->wm
= wm
;
1344 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1346 /* send the DLL load event */
1348 SERVER_START_REQ( load_dll
)
1352 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1353 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1354 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1355 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1356 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1357 wine_server_call( req
);
1361 /* setup relay debugging entry points */
1362 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1366 /******************************************************************************
1367 * load_native_dll (internal)
1369 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1370 DWORD flags
, WINE_MODREF
** pwm
)
1374 OBJECT_ATTRIBUTES attr
;
1376 IMAGE_NT_HEADERS
*nt
;
1381 TRACE("Trying native dll %s\n", debugstr_w(name
));
1383 attr
.Length
= sizeof(attr
);
1384 attr
.RootDirectory
= 0;
1385 attr
.ObjectName
= NULL
;
1386 attr
.Attributes
= 0;
1387 attr
.SecurityDescriptor
= NULL
;
1388 attr
.SecurityQualityOfService
= NULL
;
1391 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1392 &attr
, &size
, 0, SEC_IMAGE
, file
);
1393 if (status
!= STATUS_SUCCESS
) return status
;
1396 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1397 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1399 if (status
!= STATUS_SUCCESS
) return status
;
1401 if (is_fake_dll( module
))
1403 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name
) );
1404 NtUnmapViewOfSection( NtCurrentProcess(), module
);
1405 return STATUS_DLL_NOT_FOUND
;
1408 /* create the MODREF */
1410 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1414 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1416 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1418 /* the module has only be inserted in the load & memory order lists */
1419 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1420 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1422 /* FIXME: there are several more dangling references
1423 * left. Including dlls loaded by this dll before the
1424 * failed one. Unrolling is rather difficult with the
1425 * current structure and we can leave them lying
1426 * around with no problems, so we don't care.
1427 * As these might reference our wm, we don't free it.
1433 /* send DLL load event */
1435 nt
= RtlImageNtHeader( module
);
1437 SERVER_START_REQ( load_dll
)
1441 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1442 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1443 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1444 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1445 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1446 wine_server_call( req
);
1450 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1452 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1454 wm
->ldr
.LoadCount
= 1;
1456 return STATUS_SUCCESS
;
1460 /***********************************************************************
1463 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1464 DWORD flags
, WINE_MODREF
** pwm
)
1466 char error
[256], dllname
[MAX_PATH
];
1467 const WCHAR
*name
, *p
;
1469 void *handle
= NULL
;
1470 struct builtin_load_info info
, *prev_info
;
1472 /* Fix the name in case we have a full path and extension */
1474 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1475 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1477 /* load_library will modify info.status. Note also that load_library can be
1478 * called several times, if the .so file we're loading has dependencies.
1479 * info.status will gather all the errors we may get while loading all these
1482 info
.load_path
= load_path
;
1483 info
.filename
= NULL
;
1484 info
.status
= STATUS_SUCCESS
;
1487 if (file
) /* we have a real file, try to load it */
1489 UNICODE_STRING nt_name
;
1490 ANSI_STRING unix_name
;
1492 TRACE("Trying built-in %s\n", debugstr_w(path
));
1494 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1495 return STATUS_DLL_NOT_FOUND
;
1497 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1499 RtlFreeUnicodeString( &nt_name
);
1500 return STATUS_DLL_NOT_FOUND
;
1502 prev_info
= builtin_load_info
;
1503 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1504 builtin_load_info
= &info
;
1505 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1506 builtin_load_info
= prev_info
;
1507 RtlFreeUnicodeString( &nt_name
);
1508 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1511 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1512 return STATUS_INVALID_IMAGE_FORMAT
;
1519 TRACE("Trying built-in %s\n", debugstr_w(name
));
1521 /* we don't want to depend on the current codepage here */
1522 len
= strlenW( name
) + 1;
1523 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1524 for (i
= 0; i
< len
; i
++)
1526 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1527 dllname
[i
] = (char)name
[i
];
1528 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1531 prev_info
= builtin_load_info
;
1532 builtin_load_info
= &info
;
1533 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1534 builtin_load_info
= prev_info
;
1539 /* The file does not exist -> WARN() */
1540 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1541 return STATUS_DLL_NOT_FOUND
;
1543 /* ERR() for all other errors (missing functions, ...) */
1544 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1545 return STATUS_PROCEDURE_NOT_FOUND
;
1549 if (info
.status
!= STATUS_SUCCESS
)
1551 wine_dll_unload( handle
);
1557 PLIST_ENTRY mark
, entry
;
1559 /* The constructor wasn't called, this means the .so is already
1560 * loaded under a different name. Try to find the wm for it. */
1562 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1563 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1565 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1566 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1568 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1569 TRACE( "Found %s at %p for builtin %s\n",
1570 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1574 wine_dll_unload( handle
); /* release the libdl refcount */
1575 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1576 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1580 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1581 info
.wm
->ldr
.LoadCount
= 1;
1582 info
.wm
->ldr
.SectionHandle
= handle
;
1586 return STATUS_SUCCESS
;
1590 /***********************************************************************
1593 * Find the full path (if any) of the dll from the activation context.
1595 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
1597 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
1598 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
1600 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
1601 ACTCTX_SECTION_KEYED_DATA data
;
1602 UNICODE_STRING nameW
;
1604 SIZE_T needed
, size
= 1024;
1607 RtlInitUnicodeString( &nameW
, libname
);
1608 data
.cbSize
= sizeof(data
);
1609 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
1610 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
1612 if (status
!= STATUS_SUCCESS
) return status
;
1616 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1618 status
= STATUS_NO_MEMORY
;
1621 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
1622 AssemblyDetailedInformationInActivationContext
,
1623 info
, size
, &needed
);
1624 if (status
== STATUS_SUCCESS
) break;
1625 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
1626 RtlFreeHeap( GetProcessHeap(), 0, info
);
1628 /* restart with larger buffer */
1631 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
1633 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1636 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
1638 /* manifest name does not match directory name, so it's not a global
1639 * windows/winsxs manifest; use the manifest directory name instead */
1640 dirlen
= p
- info
->lpAssemblyManifestPath
;
1641 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
1642 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1644 status
= STATUS_NO_MEMORY
;
1647 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
1649 strcpyW( p
, libname
);
1654 needed
= (windows_dir
.Length
+ sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+
1655 nameW
.Length
+ 2*sizeof(WCHAR
));
1657 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1659 status
= STATUS_NO_MEMORY
;
1662 memcpy( p
, windows_dir
.Buffer
, windows_dir
.Length
);
1663 p
+= windows_dir
.Length
/ sizeof(WCHAR
);
1664 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
1665 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
1666 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
1667 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1669 strcpyW( p
, libname
);
1671 RtlFreeHeap( GetProcessHeap(), 0, info
);
1672 RtlReleaseActivationContext( data
.hActCtx
);
1677 /***********************************************************************
1680 * Find the file (or already loaded module) for a given dll name.
1682 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1683 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1685 OBJECT_ATTRIBUTES attr
;
1687 UNICODE_STRING nt_name
;
1688 WCHAR
*file_part
, *ext
, *dllname
;
1691 /* first append .dll if needed */
1694 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1696 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1697 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1698 return STATUS_NO_MEMORY
;
1699 strcpyW( dllname
, libname
);
1700 strcatW( dllname
, dllW
);
1704 nt_name
.Buffer
= NULL
;
1706 if (!contains_path( libname
))
1709 WCHAR
*fullname
= NULL
;
1711 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1713 status
= find_actctx_dll( libname
, &fullname
);
1714 if (status
== STATUS_SUCCESS
)
1716 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
1717 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1718 libname
= dllname
= fullname
;
1720 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
1722 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1727 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1729 /* we need to search for it */
1730 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1733 if (len
>= *size
) goto overflow
;
1734 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
1736 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1738 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1739 return STATUS_NO_MEMORY
;
1741 attr
.Length
= sizeof(attr
);
1742 attr
.RootDirectory
= 0;
1743 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1744 attr
.ObjectName
= &nt_name
;
1745 attr
.SecurityDescriptor
= NULL
;
1746 attr
.SecurityQualityOfService
= NULL
;
1747 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1753 if (!contains_path( libname
))
1755 /* if libname doesn't contain a path at all, we simply return the name as is,
1756 * to be loaded as builtin */
1757 len
= strlenW(libname
) * sizeof(WCHAR
);
1758 if (len
>= *size
) goto overflow
;
1759 strcpyW( filename
, libname
);
1764 /* absolute path name, or relative path name but not found above */
1766 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1768 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1769 return STATUS_NO_MEMORY
;
1771 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1772 if (len
>= *size
) goto overflow
;
1773 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1774 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
1776 attr
.Length
= sizeof(attr
);
1777 attr
.RootDirectory
= 0;
1778 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1779 attr
.ObjectName
= &nt_name
;
1780 attr
.SecurityDescriptor
= NULL
;
1781 attr
.SecurityQualityOfService
= NULL
;
1782 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1785 RtlFreeUnicodeString( &nt_name
);
1786 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1787 return STATUS_SUCCESS
;
1790 RtlFreeUnicodeString( &nt_name
);
1791 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1792 *size
= len
+ sizeof(WCHAR
);
1793 return STATUS_BUFFER_TOO_SMALL
;
1797 /***********************************************************************
1798 * load_dll (internal)
1800 * Load a PE style module according to the load order.
1801 * The loader_section must be locked while calling this function.
1803 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1805 enum loadorder loadorder
;
1809 WINE_MODREF
*main_exe
;
1813 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1816 size
= sizeof(buffer
);
1819 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1820 if (nts
== STATUS_SUCCESS
) break;
1821 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1822 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1823 /* grow the buffer and retry */
1824 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1827 if (*pwm
) /* found already loaded module */
1829 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1831 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
)) fixup_imports( *pwm
, load_path
);
1833 TRACE("Found %s for %s at %p, count=%d\n",
1834 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1835 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1836 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1837 return STATUS_SUCCESS
;
1840 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1841 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1846 nts
= STATUS_NO_MEMORY
;
1849 nts
= STATUS_DLL_NOT_FOUND
;
1852 case LO_NATIVE_BUILTIN
:
1853 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
1856 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1857 if (nts
== STATUS_INVALID_FILE_FOR_SECTION
)
1858 /* not in PE format, maybe it's a builtin */
1859 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1861 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
1862 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1865 case LO_BUILTIN_NATIVE
:
1866 case LO_DEFAULT
: /* default is builtin,native */
1867 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1868 if (!handle
) break; /* nothing else we can try */
1869 /* file is not a builtin library, try without using the specified file */
1870 if (nts
!= STATUS_SUCCESS
)
1871 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1872 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
1873 !MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
))
1875 /* stub-only dll, try native */
1876 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
1877 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
1878 nts
= STATUS_DLL_NOT_FOUND
;
1880 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
1881 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1885 if (nts
== STATUS_SUCCESS
)
1887 /* Initialize DLL just loaded */
1888 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
1889 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
1890 (*pwm
)->ldr
.BaseAddress
);
1891 if (handle
) NtClose( handle
);
1892 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1896 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
1897 if (handle
) NtClose( handle
);
1898 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1902 /******************************************************************
1903 * LdrLoadDll (NTDLL.@)
1905 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
1906 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
1911 RtlEnterCriticalSection( &loader_section
);
1913 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1914 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
1916 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
1918 nts
= process_attach( wm
, NULL
);
1919 if (nts
!= STATUS_SUCCESS
)
1921 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1925 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1927 RtlLeaveCriticalSection( &loader_section
);
1932 /******************************************************************
1933 * LdrGetDllHandle (NTDLL.@)
1935 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
1943 RtlEnterCriticalSection( &loader_section
);
1945 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1948 size
= sizeof(buffer
);
1951 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
1952 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1953 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
1954 /* grow the buffer and retry */
1955 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1957 status
= STATUS_NO_MEMORY
;
1962 if (status
== STATUS_SUCCESS
)
1964 if (wm
) *base
= wm
->ldr
.BaseAddress
;
1965 else status
= STATUS_DLL_NOT_FOUND
;
1968 RtlLeaveCriticalSection( &loader_section
);
1969 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
1974 /******************************************************************
1975 * LdrAddRefDll (NTDLL.@)
1977 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
1979 NTSTATUS ret
= STATUS_SUCCESS
;
1982 if (flags
) FIXME( "%p flags %x not implemented\n", module
, flags
);
1984 RtlEnterCriticalSection( &loader_section
);
1986 if ((wm
= get_modref( module
)))
1988 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
1989 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
1991 else ret
= STATUS_INVALID_PARAMETER
;
1993 RtlLeaveCriticalSection( &loader_section
);
1998 /******************************************************************
1999 * LdrQueryProcessModuleInformation
2002 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2003 ULONG buf_size
, ULONG
* req_size
)
2005 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2006 ULONG size
= sizeof(ULONG
);
2007 NTSTATUS nts
= STATUS_SUCCESS
;
2010 PLIST_ENTRY mark
, entry
;
2014 smi
->ModulesCount
= 0;
2016 RtlEnterCriticalSection( &loader_section
);
2017 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2018 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2020 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2021 size
+= sizeof(*sm
);
2022 if (size
<= buf_size
)
2024 sm
->Reserved1
= 0; /* FIXME */
2025 sm
->Reserved2
= 0; /* FIXME */
2026 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2027 sm
->ImageSize
= mod
->SizeOfImage
;
2028 sm
->Flags
= mod
->Flags
;
2030 sm
->Rank
= 0; /* FIXME */
2031 sm
->Unknown
= 0; /* FIXME */
2033 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2034 str
.Buffer
= (char*)sm
->Name
;
2035 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2036 ptr
= strrchr(str
.Buffer
, '\\');
2037 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2039 smi
->ModulesCount
++;
2042 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2044 RtlLeaveCriticalSection( &loader_section
);
2046 if (req_size
) *req_size
= size
;
2052 /******************************************************************
2053 * RtlDllShutdownInProgress (NTDLL.@)
2055 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2057 return process_detaching
;
2061 /******************************************************************
2062 * LdrShutdownProcess (NTDLL.@)
2065 void WINAPI
LdrShutdownProcess(void)
2068 process_detach( TRUE
, (LPVOID
)1 );
2071 /******************************************************************
2072 * LdrShutdownThread (NTDLL.@)
2075 void WINAPI
LdrShutdownThread(void)
2077 PLIST_ENTRY mark
, entry
;
2082 /* don't do any detach calls if process is exiting */
2083 if (process_detaching
) return;
2084 /* FIXME: there is still a race here */
2086 RtlEnterCriticalSection( &loader_section
);
2088 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2089 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2091 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2092 InInitializationOrderModuleList
);
2093 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2095 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2098 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2099 DLL_THREAD_DETACH
, NULL
);
2102 RtlLeaveCriticalSection( &loader_section
);
2103 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2107 /***********************************************************************
2111 static void free_modref( WINE_MODREF
*wm
)
2113 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2114 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2115 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2116 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2118 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2119 if (!TRACE_ON(module
))
2120 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2121 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2122 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2124 SERVER_START_REQ( unload_dll
)
2126 req
->base
= wm
->ldr
.BaseAddress
;
2127 wine_server_call( req
);
2131 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2132 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2133 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2134 if (cached_modref
== wm
) cached_modref
= NULL
;
2135 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2136 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2137 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2140 /***********************************************************************
2141 * MODULE_FlushModrefs
2143 * Remove all unused modrefs and call the internal unloading routines
2144 * for the library type.
2146 * The loader_section must be locked while calling this function.
2148 static void MODULE_FlushModrefs(void)
2150 PLIST_ENTRY mark
, entry
, prev
;
2154 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2155 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2157 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2158 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2159 prev
= entry
->Blink
;
2160 if (!mod
->LoadCount
) free_modref( wm
);
2163 /* check load order list too for modules that haven't been initialized yet */
2164 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2165 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2167 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2168 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2169 prev
= entry
->Blink
;
2170 if (!mod
->LoadCount
) free_modref( wm
);
2174 /***********************************************************************
2175 * MODULE_DecRefCount
2177 * The loader_section must be locked while calling this function.
2179 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2183 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2186 if ( wm
->ldr
.LoadCount
<= 0 )
2189 --wm
->ldr
.LoadCount
;
2190 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2192 if ( wm
->ldr
.LoadCount
== 0 )
2194 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2196 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2198 MODULE_DecRefCount( wm
->deps
[i
] );
2200 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2204 /******************************************************************
2205 * LdrUnloadDll (NTDLL.@)
2209 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2211 NTSTATUS retv
= STATUS_SUCCESS
;
2213 TRACE("(%p)\n", hModule
);
2215 RtlEnterCriticalSection( &loader_section
);
2217 /* if we're stopping the whole process (and forcing the removal of all
2218 * DLLs) the library will be freed anyway
2220 if (!process_detaching
)
2225 if ((wm
= get_modref( hModule
)) != NULL
)
2227 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2229 /* Recursively decrement reference counts */
2230 MODULE_DecRefCount( wm
);
2232 /* Call process detach notifications */
2233 if ( free_lib_count
<= 1 )
2235 process_detach( FALSE
, NULL
);
2236 MODULE_FlushModrefs();
2242 retv
= STATUS_DLL_NOT_FOUND
;
2247 RtlLeaveCriticalSection( &loader_section
);
2252 /***********************************************************************
2253 * RtlImageNtHeader (NTDLL.@)
2255 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2257 IMAGE_NT_HEADERS
*ret
;
2261 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2264 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2266 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2267 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2279 /******************************************************************
2280 * LdrInitializeThunk (NTDLL.@)
2283 void WINAPI
LdrInitializeThunk( ULONG unknown1
, ULONG unknown2
, ULONG unknown3
, ULONG unknown4
)
2288 PEB
*peb
= NtCurrentTeb()->Peb
;
2289 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
2291 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
2293 /* allocate the modref for the main exe (if not already done) */
2294 wm
= get_modref( peb
->ImageBaseAddress
);
2296 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
2298 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
2302 peb
->LoaderLock
= &loader_section
;
2303 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2304 version_init( wm
->ldr
.FullDllName
.Buffer
);
2306 /* the main exe needs to be the first in the load order list */
2307 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2308 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2310 status
= server_init_process_done();
2311 if (status
!= STATUS_SUCCESS
) goto error
;
2313 RtlEnterCriticalSection( &loader_section
);
2316 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2317 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2318 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2319 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2321 pthread_functions
.sigprocmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2323 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2325 if (last_failed_modref
)
2326 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2329 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2331 RtlLeaveCriticalSection( &loader_section
);
2333 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
) VIRTUAL_UseLargeAddressSpace();
2337 ERR( "Main exe initialization for %s failed, status %x\n",
2338 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2339 NtTerminateProcess( GetCurrentProcess(), status
);
2343 /***********************************************************************
2344 * RtlImageDirectoryEntryToData (NTDLL.@)
2346 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2348 const IMAGE_NT_HEADERS
*nt
;
2351 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2353 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2356 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2357 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2358 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2359 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
2360 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2362 /* not mapped as image, need to find the section containing the virtual address */
2363 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2367 /***********************************************************************
2368 * RtlImageRvaToSection (NTDLL.@)
2370 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2371 HMODULE module
, DWORD rva
)
2374 const IMAGE_SECTION_HEADER
*sec
;
2376 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2377 nt
->FileHeader
.SizeOfOptionalHeader
);
2378 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2380 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2381 return (PIMAGE_SECTION_HEADER
)sec
;
2387 /***********************************************************************
2388 * RtlImageRvaToVa (NTDLL.@)
2390 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2391 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2393 IMAGE_SECTION_HEADER
*sec
;
2395 if (section
&& *section
) /* try this section first */
2398 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2401 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2403 if (section
) *section
= sec
;
2404 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2408 /***********************************************************************
2409 * RtlPcToFileHeader (NTDLL.@)
2411 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
2416 RtlEnterCriticalSection( &loader_section
);
2417 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
2418 RtlLeaveCriticalSection( &loader_section
);
2424 /***********************************************************************
2425 * NtLoadDriver (NTDLL.@)
2426 * ZwLoadDriver (NTDLL.@)
2428 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2430 FIXME("(%p), stub!\n",DriverServiceName
);
2431 return STATUS_NOT_IMPLEMENTED
;
2435 /***********************************************************************
2436 * NtUnloadDriver (NTDLL.@)
2437 * ZwUnloadDriver (NTDLL.@)
2439 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2441 FIXME("(%p), stub!\n",DriverServiceName
);
2442 return STATUS_NOT_IMPLEMENTED
;
2446 /******************************************************************
2449 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2451 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2456 /******************************************************************
2457 * __wine_init_windows_dir (NTDLL.@)
2459 * Windows and system dir initialization once kernel32 has been loaded.
2461 void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2463 PLIST_ENTRY mark
, entry
;
2466 RtlCreateUnicodeString( &windows_dir
, windir
);
2467 RtlCreateUnicodeString( &system_dir
, sysdir
);
2468 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
2470 /* prepend the system dir to the name of the already created modules */
2471 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2472 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2474 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2476 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2478 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2479 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2480 if (!buffer
) continue;
2481 strcpyW( buffer
, system_dir
.Buffer
);
2482 p
= buffer
+ strlenW( buffer
);
2483 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2484 strcpyW( p
, mod
->FullDllName
.Buffer
);
2485 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2486 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2491 /***********************************************************************
2492 * __wine_process_init
2494 void __wine_process_init(void)
2496 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2500 ANSI_STRING func_name
;
2501 void (* DECLSPEC_NORETURN init_func
)(void);
2502 extern mode_t FILE_umask
;
2504 main_exe_file
= thread_init();
2506 /* retrieve current umask */
2507 FILE_umask
= umask(0777);
2508 umask( FILE_umask
);
2510 /* setup the load callback and create ntdll modref */
2511 wine_dll_set_callback( load_builtin_callback
);
2513 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
2515 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
2518 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2519 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2520 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2522 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);