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
27 #define WIN32_NO_STATUS
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
34 #include "delayloadhandler.h"
36 #include "wine/exception.h"
37 #include "wine/debug.h"
38 #include "wine/list.h"
39 #include "ntdll_misc.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(module
);
43 WINE_DECLARE_DEBUG_CHANNEL(relay
);
44 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
45 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
46 WINE_DECLARE_DEBUG_CHANNEL(imports
);
49 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
51 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
52 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
55 static const WCHAR pe_dir
[] = L
"\\i386-windows";
56 #elif defined __x86_64__
57 static const WCHAR pe_dir
[] = L
"\\x86_64-windows";
59 static const WCHAR pe_dir
[] = L
"\\arm-windows";
60 #elif defined __aarch64__
61 static const WCHAR pe_dir
[] = L
"\\aarch64-windows";
63 static const WCHAR pe_dir
[] = L
"";
66 /* we don't want to include winuser.h */
67 #define RT_MANIFEST ((ULONG_PTR)24)
68 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
70 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
71 typedef void (CALLBACK
*LDRENUMPROC
)(LDR_DATA_TABLE_ENTRY
*, void *, BOOLEAN
*);
73 void (FASTCALL
*pBaseThreadInitThunk
)(DWORD
,LPTHREAD_START_ROUTINE
,void *) = NULL
;
75 static DWORD (WINAPI
*pCtrlRoutine
)(void *);
77 SYSTEM_DLL_INIT_BLOCK LdrSystemDllInitBlock
= { 0xf0 };
79 const struct unix_funcs
*unix_funcs
= NULL
;
81 /* windows directory */
82 const WCHAR windows_dir
[] = L
"C:\\windows";
83 /* system directory with trailing backslash */
84 const WCHAR system_dir
[] = L
"C:\\windows\\system32\\";
86 HMODULE kernel32_handle
= 0;
88 /* system search path */
89 static const WCHAR system_path
[] = L
"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
91 static BOOL is_prefix_bootstrap
; /* are we bootstrapping the prefix? */
92 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
93 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
94 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
95 static ULONG path_safe_mode
; /* path mode set by RtlSetSearchPathMode */
96 static ULONG dll_safe_mode
= 1; /* dll search mode */
97 static UNICODE_STRING dll_directory
; /* extra path for LdrSetDllDirectory */
98 static DWORD default_search_flags
; /* default flags set by LdrSetDefaultDllDirectories */
99 static WCHAR
*default_load_path
; /* default dll search path */
107 static struct list dll_dir_list
= LIST_INIT( dll_dir_list
); /* extra dirs from LdrAddDllDirectory */
109 struct ldr_notification
112 PLDR_DLL_NOTIFICATION_FUNCTION callback
;
116 static struct list ldr_notifications
= LIST_INIT( ldr_notifications
);
118 static const char * const reason_names
[] =
131 /* internal representation of loaded modules */
132 typedef struct _wine_modref
134 LDR_DATA_TABLE_ENTRY ldr
;
139 static UINT tls_module_count
; /* number of modules with TLS directory */
140 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
141 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
143 static RTL_CRITICAL_SECTION loader_section
;
144 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
146 0, 0, &loader_section
,
147 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
148 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
150 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
152 static CRITICAL_SECTION dlldir_section
;
153 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug
=
155 0, 0, &dlldir_section
,
156 { &dlldir_critsect_debug
.ProcessLocksList
, &dlldir_critsect_debug
.ProcessLocksList
},
157 0, 0, { (DWORD_PTR
)(__FILE__
": dlldir_section") }
159 static CRITICAL_SECTION dlldir_section
= { &dlldir_critsect_debug
, -1, 0, 0, 0, 0 };
161 static RTL_CRITICAL_SECTION peb_lock
;
162 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug
=
165 { &peb_critsect_debug
.ProcessLocksList
, &peb_critsect_debug
.ProcessLocksList
},
166 0, 0, { (DWORD_PTR
)(__FILE__
": peb_lock") }
168 static RTL_CRITICAL_SECTION peb_lock
= { &peb_critsect_debug
, -1, 0, 0, 0, 0 };
170 static PEB_LDR_DATA ldr
=
172 sizeof(ldr
), TRUE
, NULL
,
173 { &ldr
.InLoadOrderModuleList
, &ldr
.InLoadOrderModuleList
},
174 { &ldr
.InMemoryOrderModuleList
, &ldr
.InMemoryOrderModuleList
},
175 { &ldr
.InInitializationOrderModuleList
, &ldr
.InInitializationOrderModuleList
}
178 static RTL_BITMAP tls_bitmap
;
179 static RTL_BITMAP tls_expansion_bitmap
;
181 static WINE_MODREF
*cached_modref
;
182 static WINE_MODREF
*current_modref
;
183 static WINE_MODREF
*last_failed_modref
;
185 static LDR_DDAG_NODE
*node_ntdll
, *node_kernel32
;
187 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
188 DWORD flags
, WINE_MODREF
** pwm
);
189 static NTSTATUS
process_attach( LDR_DDAG_NODE
*node
, LPVOID lpReserved
);
190 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
191 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
192 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
193 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
195 /* convert PE image VirtualAddress to Real Address */
196 static inline void *get_rva( HMODULE module
, DWORD va
)
198 return (void *)((char *)module
+ va
);
201 /* check whether the file name contains a path */
202 static inline BOOL
contains_path( LPCWSTR name
)
204 return ((*name
&& (name
[1] == ':')) || wcschr(name
, '/') || wcschr(name
, '\\'));
207 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
209 typedef struct _RTL_UNLOAD_EVENT_TRACE
217 } RTL_UNLOAD_EVENT_TRACE
, *PRTL_UNLOAD_EVENT_TRACE
;
219 static RTL_UNLOAD_EVENT_TRACE unload_traces
[RTL_UNLOAD_EVENT_TRACE_NUMBER
];
220 static RTL_UNLOAD_EVENT_TRACE
*unload_trace_ptr
;
221 static unsigned int unload_trace_seq
;
223 static void module_push_unload_trace( const WINE_MODREF
*wm
)
225 RTL_UNLOAD_EVENT_TRACE
*ptr
= &unload_traces
[unload_trace_seq
];
226 const LDR_DATA_TABLE_ENTRY
*ldr
= &wm
->ldr
;
227 unsigned int len
= min(sizeof(ptr
->ImageName
) - sizeof(WCHAR
), ldr
->BaseDllName
.Length
);
229 ptr
->BaseAddress
= ldr
->DllBase
;
230 ptr
->SizeOfImage
= ldr
->SizeOfImage
;
231 ptr
->Sequence
= unload_trace_seq
;
232 ptr
->TimeDateStamp
= ldr
->TimeDateStamp
;
233 ptr
->CheckSum
= wm
->CheckSum
;
234 memcpy(ptr
->ImageName
, ldr
->BaseDllName
.Buffer
, len
);
235 ptr
->ImageName
[len
/ sizeof(*ptr
->ImageName
)] = 0;
237 unload_trace_seq
= (unload_trace_seq
+ 1) % ARRAY_SIZE(unload_traces
);
238 unload_trace_ptr
= unload_traces
;
241 /*********************************************************************
242 * RtlGetUnloadEventTrace [NTDLL.@]
244 RTL_UNLOAD_EVENT_TRACE
* WINAPI
RtlGetUnloadEventTrace(void)
246 return unload_traces
;
249 /*********************************************************************
250 * RtlGetUnloadEventTraceEx [NTDLL.@]
252 void WINAPI
RtlGetUnloadEventTraceEx(ULONG
**size
, ULONG
**count
, void **trace
)
254 static unsigned int element_size
= sizeof(*unload_traces
);
255 static unsigned int element_count
= ARRAY_SIZE(unload_traces
);
257 *size
= &element_size
;
258 *count
= &element_count
;
259 *trace
= &unload_trace_ptr
;
262 /*************************************************************************
263 * call_dll_entry_point
265 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
266 * their entry point, so we need a small asm wrapper. Testing indicates
267 * that only modifying esi leads to a crash, so use this one to backup
268 * ebp while running the dll entry proc.
271 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
272 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
274 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
275 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
277 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
279 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
281 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
283 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
285 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
289 "movl 8(%ebp),%eax\n\t"
292 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
293 "leal -12(%ebp),%esp\n\t"
295 __ASM_CFI(".cfi_same_value %edi\n\t")
297 __ASM_CFI(".cfi_same_value %esi\n\t")
299 __ASM_CFI(".cfi_same_value %ebx\n\t")
301 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
302 __ASM_CFI(".cfi_same_value %ebp\n\t")
305 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
306 UINT reason
, void *reserved
)
308 return proc( module
, reason
, reserved
);
310 #endif /* __i386__ */
313 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
314 /*************************************************************************
317 * Entry point for stub functions.
319 static void WINAPI
stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
321 EXCEPTION_RECORD rec
;
323 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
324 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
325 rec
.ExceptionRecord
= NULL
;
326 rec
.ExceptionAddress
= ret_addr
;
327 rec
.NumberParameters
= 2;
328 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
329 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
330 for (;;) RtlRaiseException( &rec
);
334 #include "pshpack1.h"
338 BYTE pushl1
; /* pushl $name */
340 BYTE pushl2
; /* pushl $dll */
342 BYTE call
; /* call stub_entry_point */
345 #elif defined(__arm__)
348 DWORD ldr_r0
; /* ldr r0, $dll */
349 DWORD ldr_r1
; /* ldr r1, $name */
350 DWORD mov_r2_lr
; /* mov r2, lr */
351 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
356 #elif defined(__aarch64__)
359 DWORD ldr_x0
; /* ldr x0, $dll */
360 DWORD ldr_x1
; /* ldr x1, $name */
361 DWORD mov_x2_lr
; /* mov x2, lr */
362 DWORD ldr_x16
; /* ldr x16, $entry */
363 DWORD br_x16
; /* br x16 */
371 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
373 BYTE movq_rsi
[2]; /* movq $name,%rsi */
375 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
376 BYTE movq_rax
[2]; /* movq $entry, %rax */
378 BYTE jmpq_rax
[2]; /* jmp %rax */
383 /*************************************************************************
386 * Allocate a stub entry point.
388 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
390 #define MAX_SIZE 65536
391 static struct stub
*stubs
;
392 static unsigned int nb_stubs
;
395 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
399 SIZE_T size
= MAX_SIZE
;
400 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
401 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
404 stub
= &stubs
[nb_stubs
++];
406 stub
->pushl1
= 0x68; /* pushl $name */
408 stub
->pushl2
= 0x68; /* pushl $dll */
410 stub
->call
= 0xe8; /* call stub_entry_point */
411 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
412 #elif defined(__arm__)
413 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
414 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
415 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
416 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
419 stub
->entry
= stub_entry_point
;
420 #elif defined(__aarch64__)
421 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
422 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
423 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
424 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
425 stub
->br_x16
= 0xd61f0200; /* br x16 */
428 stub
->entry
= stub_entry_point
;
430 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rcx */
431 stub
->movq_rdi
[1] = 0xb9;
433 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rdx */
434 stub
->movq_rsi
[1] = 0xba;
436 stub
->movq_rsp_rdx
[0] = 0x4c; /* movq (%rsp),%r8 */
437 stub
->movq_rsp_rdx
[1] = 0x8b;
438 stub
->movq_rsp_rdx
[2] = 0x04;
439 stub
->movq_rsp_rdx
[3] = 0x24;
440 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
441 stub
->movq_rax
[1] = 0xb8;
442 stub
->entry
= stub_entry_point
;
443 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
444 stub
->jmpq_rax
[1] = 0xe0;
446 return (ULONG_PTR
)stub
;
450 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
451 #endif /* __i386__ */
453 /* call ldr notifications */
454 static void call_ldr_notifications( ULONG reason
, LDR_DATA_TABLE_ENTRY
*module
)
456 struct ldr_notification
*notify
, *notify_next
;
457 LDR_DLL_NOTIFICATION_DATA data
;
459 data
.Loaded
.Flags
= 0;
460 data
.Loaded
.FullDllName
= &module
->FullDllName
;
461 data
.Loaded
.BaseDllName
= &module
->BaseDllName
;
462 data
.Loaded
.DllBase
= module
->DllBase
;
463 data
.Loaded
.SizeOfImage
= module
->SizeOfImage
;
465 LIST_FOR_EACH_ENTRY_SAFE( notify
, notify_next
, &ldr_notifications
, struct ldr_notification
, entry
)
467 TRACE_(relay
)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
468 notify
->callback
, reason
, &data
, notify
->context
);
470 notify
->callback(reason
, &data
, notify
->context
);
472 TRACE_(relay
)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
473 notify
->callback
, reason
, &data
, notify
->context
);
477 /*************************************************************************
480 * Looks for the referenced HMODULE in the current process
481 * The loader_section must be locked while calling this function.
483 static WINE_MODREF
*get_modref( HMODULE hmod
)
485 PLIST_ENTRY mark
, entry
;
486 PLDR_DATA_TABLE_ENTRY mod
;
488 if (cached_modref
&& cached_modref
->ldr
.DllBase
== hmod
) return cached_modref
;
490 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
491 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
493 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
494 if (mod
->DllBase
== hmod
)
495 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
501 /**********************************************************************
502 * find_basename_module
504 * Find a module from its base name.
505 * The loader_section must be locked while calling this function
507 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
509 PLIST_ENTRY mark
, entry
;
510 UNICODE_STRING name_str
;
512 RtlInitUnicodeString( &name_str
, name
);
514 if (cached_modref
&& RtlEqualUnicodeString( &name_str
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
515 return cached_modref
;
517 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
518 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
520 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
521 if (RtlEqualUnicodeString( &name_str
, &mod
->BaseDllName
, TRUE
))
523 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
524 return cached_modref
;
531 /**********************************************************************
532 * find_fullname_module
534 * Find a module from its full path name.
535 * The loader_section must be locked while calling this function
537 static WINE_MODREF
*find_fullname_module( const UNICODE_STRING
*nt_name
)
539 PLIST_ENTRY mark
, entry
;
540 UNICODE_STRING name
= *nt_name
;
542 if (name
.Length
<= 4 * sizeof(WCHAR
)) return NULL
;
543 name
.Length
-= 4 * sizeof(WCHAR
); /* for \??\ prefix */
546 if (cached_modref
&& RtlEqualUnicodeString( &name
, &cached_modref
->ldr
.FullDllName
, TRUE
))
547 return cached_modref
;
549 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
550 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
552 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
553 if (RtlEqualUnicodeString( &name
, &mod
->FullDllName
, TRUE
))
555 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
556 return cached_modref
;
563 /**********************************************************************
566 * Find a module from its file id.
567 * The loader_section must be locked while calling this function
569 static WINE_MODREF
*find_fileid_module( const struct file_id
*id
)
571 LIST_ENTRY
*mark
, *entry
;
573 if (cached_modref
&& !memcmp( &cached_modref
->id
, id
, sizeof(*id
) )) return cached_modref
;
575 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
576 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
578 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
579 WINE_MODREF
*wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
581 if (!memcmp( &wm
->id
, id
, sizeof(*id
) ))
590 /***********************************************************************
591 * is_import_dll_system
593 static BOOL
is_import_dll_system( LDR_DATA_TABLE_ENTRY
*mod
, const IMAGE_IMPORT_DESCRIPTOR
*import
)
595 const char *name
= get_rva( mod
->DllBase
, import
->Name
);
597 return !strcmp( name
, "ntdll.dll" ) || !strcmp( name
, "kernel32.dll" );
600 /**********************************************************************
601 * insert_single_list_tail
603 static void insert_single_list_after( LDRP_CSLIST
*list
, SINGLE_LIST_ENTRY
*prev
, SINGLE_LIST_ENTRY
*entry
)
614 /* Insert at head. */
615 entry
->Next
= list
->Tail
->Next
;
616 list
->Tail
->Next
= entry
;
619 entry
->Next
= prev
->Next
;
621 if (prev
== list
->Tail
) list
->Tail
= entry
;
624 /**********************************************************************
625 * remove_single_list_entry
627 static void remove_single_list_entry( LDRP_CSLIST
*list
, SINGLE_LIST_ENTRY
*entry
)
629 SINGLE_LIST_ENTRY
*prev
;
631 assert( list
->Tail
);
633 if (entry
->Next
== entry
)
635 assert( list
->Tail
== entry
);
640 prev
= list
->Tail
->Next
;
641 while (prev
->Next
!= entry
&& prev
!= list
->Tail
)
643 assert( prev
->Next
== entry
);
644 prev
->Next
= entry
->Next
;
645 if (list
->Tail
== entry
) list
->Tail
= prev
;
649 /**********************************************************************
650 * add_module_dependency_after
652 static BOOL
add_module_dependency_after( LDR_DDAG_NODE
*from
, LDR_DDAG_NODE
*to
,
653 SINGLE_LIST_ENTRY
*dep_after
)
657 if (!(dep
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*dep
) ))) return FALSE
;
659 dep
->dependency_from
= from
;
660 insert_single_list_after( &from
->Dependencies
, dep_after
, &dep
->dependency_to_entry
);
661 dep
->dependency_to
= to
;
662 insert_single_list_after( &to
->IncomingDependencies
, NULL
, &dep
->dependency_from_entry
);
667 /**********************************************************************
668 * add_module_dependency
670 static BOOL
add_module_dependency( LDR_DDAG_NODE
*from
, LDR_DDAG_NODE
*to
)
672 return add_module_dependency_after( from
, to
, from
->Dependencies
.Tail
);
675 /**********************************************************************
676 * remove_module_dependency
678 static void remove_module_dependency( LDR_DEPENDENCY
*dep
)
680 remove_single_list_entry( &dep
->dependency_to
->IncomingDependencies
, &dep
->dependency_from_entry
);
681 remove_single_list_entry( &dep
->dependency_from
->Dependencies
, &dep
->dependency_to_entry
);
682 RtlFreeHeap( GetProcessHeap(), 0, dep
);
685 /**********************************************************************
686 * walk_node_dependencies
688 static NTSTATUS
walk_node_dependencies( LDR_DDAG_NODE
*node
, void *context
,
689 NTSTATUS (*callback
)( LDR_DDAG_NODE
*, void * ))
691 SINGLE_LIST_ENTRY
*entry
;
695 if (!(entry
= node
->Dependencies
.Tail
)) return STATUS_SUCCESS
;
700 dep
= CONTAINING_RECORD( entry
, LDR_DEPENDENCY
, dependency_to_entry
);
701 assert( dep
->dependency_from
== node
);
702 if ((status
= callback( dep
->dependency_to
, context
))) break;
703 } while (entry
!= node
->Dependencies
.Tail
);
708 /*************************************************************************
709 * find_forwarded_export
711 * Find the final function pointer for a forwarded function.
712 * The loader_section must be locked while calling this function.
714 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
716 const IMAGE_EXPORT_DIRECTORY
*exports
;
719 WCHAR buffer
[32], *mod_name
= buffer
;
720 const char *end
= strrchr(forward
, '.');
723 if (!end
) return NULL
;
724 if ((end
- forward
) * sizeof(WCHAR
) > sizeof(buffer
) - sizeof(L
".dll"))
726 if (!(mod_name
= RtlAllocateHeap( GetProcessHeap(), 0,
727 (end
- forward
+ sizeof(L
".dll")) * sizeof(WCHAR
) )))
730 ascii_to_unicode( mod_name
, forward
, end
- forward
);
731 mod_name
[end
- forward
] = 0;
732 if (!wcschr( mod_name
, '.' ))
733 memcpy( mod_name
+ (end
- forward
), L
".dll", sizeof(L
".dll") );
735 if (!(wm
= find_basename_module( mod_name
)))
737 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
738 if (load_dll( load_path
, mod_name
, L
".dll", 0, &wm
) == STATUS_SUCCESS
&&
739 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
741 if (!imports_fixup_done
&& current_modref
)
743 add_module_dependency( current_modref
->ldr
.DdagNode
, wm
->ldr
.DdagNode
);
745 else if (process_attach( wm
->ldr
.DdagNode
, NULL
) != STATUS_SUCCESS
)
747 LdrUnloadDll( wm
->ldr
.DllBase
);
754 if (mod_name
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, mod_name
);
755 ERR( "module not found for forward '%s' used by %s\n",
756 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
760 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
761 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
763 const char *name
= end
+ 1;
765 if (*name
== '#') { /* ordinal */
766 proc
= find_ordinal_export( wm
->ldr
.DllBase
, exports
, exp_size
,
767 atoi(name
+1) - exports
->Base
, load_path
);
769 proc
= find_named_export( wm
->ldr
.DllBase
, exports
, exp_size
, name
, -1, load_path
);
774 ERR("function not found for forward '%s' used by %s."
775 " If you are using builtin %s, try using the native one instead.\n",
776 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
777 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
779 if (mod_name
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, mod_name
);
784 /*************************************************************************
785 * find_ordinal_export
787 * Find an exported function by ordinal.
788 * The exports base must have been subtracted from the ordinal already.
789 * The loader_section must be locked while calling this function.
791 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
792 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
795 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
797 if (ordinal
>= exports
->NumberOfFunctions
)
799 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
802 if (!functions
[ordinal
]) return NULL
;
804 proc
= get_rva( module
, functions
[ordinal
] );
806 /* if the address falls into the export dir, it's a forward */
807 if (((const char *)proc
>= (const char *)exports
) &&
808 ((const char *)proc
< (const char *)exports
+ exp_size
))
809 return find_forwarded_export( module
, (const char *)proc
, load_path
);
813 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
814 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
818 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
819 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
825 /*************************************************************************
826 * find_name_in_exports
828 * Helper for find_named_export.
830 static int find_name_in_exports( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
, const char *name
)
832 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
833 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
834 int min
= 0, max
= exports
->NumberOfNames
- 1;
838 int res
, pos
= (min
+ max
) / 2;
839 char *ename
= get_rva( module
, names
[pos
] );
840 if (!(res
= strcmp( ename
, name
))) return ordinals
[pos
];
841 if (res
> 0) max
= pos
- 1;
848 /*************************************************************************
851 * Find an exported function by name.
852 * The loader_section must be locked while calling this function.
854 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
855 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
857 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
858 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
861 /* first check the hint */
862 if (hint
>= 0 && hint
< exports
->NumberOfNames
)
864 char *ename
= get_rva( module
, names
[hint
] );
865 if (!strcmp( ename
, name
))
866 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
869 /* then do a binary search */
870 if ((ordinal
= find_name_in_exports( module
, exports
, name
)) == -1) return NULL
;
871 return find_ordinal_export( module
, exports
, exp_size
, ordinal
, load_path
);
876 /*************************************************************************
877 * RtlFindExportedRoutineByName
879 void * WINAPI
RtlFindExportedRoutineByName( HMODULE module
, const char *name
)
881 const IMAGE_EXPORT_DIRECTORY
*exports
;
882 const DWORD
*functions
;
886 exports
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
887 if (!exports
|| exp_size
< sizeof(*exports
)) return NULL
;
889 if ((ordinal
= find_name_in_exports( module
, exports
, name
)) == -1) return NULL
;
890 if (ordinal
>= exports
->NumberOfFunctions
) return NULL
;
891 functions
= get_rva( module
, exports
->AddressOfFunctions
);
892 if (!functions
[ordinal
]) return NULL
;
893 return get_rva( module
, functions
[ordinal
] );
897 /*************************************************************************
900 * Import the dll specified by the given import descriptor.
901 * The loader_section must be locked while calling this function.
903 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
908 const IMAGE_EXPORT_DIRECTORY
*exports
;
910 const IMAGE_THUNK_DATA
*import_list
;
911 IMAGE_THUNK_DATA
*thunk_list
;
913 const char *name
= get_rva( module
, descr
->Name
);
914 DWORD len
= strlen(name
);
916 SIZE_T protect_size
= 0;
919 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
920 if (descr
->u
.OriginalFirstThunk
)
921 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
923 import_list
= thunk_list
;
925 if (!import_list
->u1
.Ordinal
)
927 WARN( "Skipping unused import %s\n", name
);
932 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
934 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
936 ascii_to_unicode( buffer
, name
, len
);
938 status
= load_dll( load_path
, buffer
, L
".dll", 0, &wmImp
);
940 else /* need to allocate a larger buffer */
942 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
943 if (!ptr
) return FALSE
;
944 ascii_to_unicode( ptr
, name
, len
);
946 status
= load_dll( load_path
, ptr
, L
".dll", 0, &wmImp
);
947 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
952 if (status
== STATUS_DLL_NOT_FOUND
)
953 ERR("Library %s (which is needed by %s) not found\n",
954 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
956 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
957 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
961 /* unprotect the import address table since it can be located in
962 * readonly section */
963 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
964 protect_base
= thunk_list
;
965 protect_size
*= sizeof(*thunk_list
);
966 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
967 &protect_size
, PAGE_READWRITE
, &protect_old
);
969 imp_mod
= wmImp
->ldr
.DllBase
;
970 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
974 /* set all imported function to deadbeef */
975 while (import_list
->u1
.Ordinal
)
977 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
979 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
980 WARN("No implementation for %s.%d", name
, ordinal
);
981 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
985 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
986 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
987 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
989 WARN(" imported from %s, allocating stub %p\n",
990 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
991 (void *)thunk_list
->u1
.Function
);
998 while (import_list
->u1
.Ordinal
)
1000 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
1002 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
1004 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
1005 ordinal
- exports
->Base
, load_path
);
1006 if (!thunk_list
->u1
.Function
)
1008 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
1009 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
1010 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
1011 (void *)thunk_list
->u1
.Function
);
1013 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
1015 else /* import by name */
1017 IMAGE_IMPORT_BY_NAME
*pe_name
;
1018 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
1019 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
1020 (const char*)pe_name
->Name
,
1021 pe_name
->Hint
, load_path
);
1022 if (!thunk_list
->u1
.Function
)
1024 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
1025 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
1026 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
1027 (void *)thunk_list
->u1
.Function
);
1029 TRACE_(imports
)("--- %s %s.%d = %p\n",
1030 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
1037 /* restore old protection of the import address table */
1038 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
1044 /***********************************************************************
1045 * create_module_activation_context
1047 static NTSTATUS
create_module_activation_context( LDR_DATA_TABLE_ENTRY
*module
)
1050 LDR_RESOURCE_INFO info
;
1051 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
1053 info
.Type
= RT_MANIFEST
;
1054 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
1056 if (!(status
= LdrFindResource_U( module
->DllBase
, &info
, 3, &entry
)))
1059 ctx
.cbSize
= sizeof(ctx
);
1060 ctx
.lpSource
= NULL
;
1061 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
1062 ctx
.hModule
= module
->DllBase
;
1063 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
1064 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
1070 /*************************************************************************
1071 * is_dll_native_subsystem
1073 * Check if dll is a proper native driver.
1074 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
1075 * while being perfectly normal DLLs. This heuristic should catch such breakages.
1077 static BOOL
is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY
*mod
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
1079 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1082 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
1083 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
1084 if (mod
->Flags
& LDR_WINE_INTERNAL
) return TRUE
;
1086 if ((imports
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
,
1087 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1089 for (i
= 0; imports
[i
].Name
; i
++)
1090 if (is_import_dll_system( mod
, &imports
[i
] ))
1092 TRACE( "%s imports system dll, assuming not native\n", debugstr_w(filename
) );
1099 /*************************************************************************
1102 * Allocate a TLS slot for a newly-loaded module.
1103 * The loader_section must be locked while calling this function.
1105 static SHORT
alloc_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
1107 const IMAGE_TLS_DIRECTORY
*dir
;
1112 if (!(dir
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
1115 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1116 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
1118 for (i
= 0; i
< tls_module_count
; i
++)
1120 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
1121 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
1125 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->DllBase
,
1126 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
1127 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
1129 if (i
== tls_module_count
)
1131 UINT new_count
= max( 32, tls_module_count
* 2 );
1134 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
1136 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
1137 new_count
* sizeof(*tls_dirs
) );
1138 if (!new_ptr
) return -1;
1140 /* resize the pointer block in all running threads */
1141 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1143 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
1144 void **old
= teb
->ThreadLocalStoragePointer
;
1145 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
1147 if (!new) return -1;
1148 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
1149 teb
->ThreadLocalStoragePointer
= new;
1150 #ifdef __x86_64__ /* macOS-specific hack */
1151 if (teb
->Reserved5
[0]) ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
1153 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
1154 /* FIXME: can't free old block here, should be freed at thread exit */
1158 tls_module_count
= new_count
;
1161 /* allocate the data block in all running threads */
1162 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1164 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
1166 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
1167 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
1168 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
1170 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1171 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
1173 RtlFreeHeap( GetProcessHeap(), 0,
1174 InterlockedExchangePointer( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
1177 *(DWORD
*)dir
->AddressOfIndex
= i
;
1183 /*************************************************************************
1186 * Free the module TLS slot on unload.
1187 * The loader_section must be locked while calling this function.
1189 static void free_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
1191 ULONG i
= (USHORT
)mod
->TlsIndex
;
1193 if (mod
->TlsIndex
== -1) return;
1194 assert( i
< tls_module_count
);
1195 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
1199 /****************************************************************
1200 * fixup_imports_ilonly
1202 * Fixup imports for an IL-only module. All we do is import mscoree.
1203 * The loader_section must be locked while calling this function.
1205 static NTSTATUS
fixup_imports_ilonly( WINE_MODREF
*wm
, LPCWSTR load_path
, void **entry
)
1210 WINE_MODREF
*prev
, *imp
;
1212 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1213 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1215 prev
= current_modref
;
1216 current_modref
= wm
;
1217 assert( !wm
->ldr
.DdagNode
->Dependencies
.Tail
);
1218 if (!(status
= load_dll( load_path
, L
"mscoree.dll", NULL
, 0, &imp
))
1219 && !add_module_dependency_after( wm
->ldr
.DdagNode
, imp
->ldr
.DdagNode
, NULL
))
1220 status
= STATUS_NO_MEMORY
;
1221 current_modref
= prev
;
1224 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1225 debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1229 TRACE( "loaded mscoree for %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1231 name
= (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) ? "_CorDllMain" : "_CorExeMain";
1232 if (!(proc
= RtlFindExportedRoutineByName( imp
->ldr
.DllBase
, name
))) return STATUS_PROCEDURE_NOT_FOUND
;
1234 return STATUS_SUCCESS
;
1238 /****************************************************************
1241 * Fixup all imports of a given module.
1242 * The loader_section must be locked while calling this function.
1244 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
1246 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1247 SINGLE_LIST_ENTRY
*dep_after
;
1248 WINE_MODREF
*prev
, *imp
;
1254 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1255 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1257 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
1259 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
1260 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1261 return STATUS_SUCCESS
;
1264 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
1266 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
1268 if (!create_module_activation_context( &wm
->ldr
))
1269 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1271 /* load the imported modules. They are automatically
1272 * added to the modref list of the process.
1274 prev
= current_modref
;
1275 current_modref
= wm
;
1276 status
= STATUS_SUCCESS
;
1277 for (i
= 0; i
< nb_imports
; i
++)
1279 dep_after
= wm
->ldr
.DdagNode
->Dependencies
.Tail
;
1280 if (!import_dll( wm
->ldr
.DllBase
, &imports
[i
], load_path
, &imp
))
1283 status
= STATUS_DLL_NOT_FOUND
;
1285 else if (!is_import_dll_system( &wm
->ldr
, &imports
[i
] ))
1287 add_module_dependency_after( wm
->ldr
.DdagNode
, imp
->ldr
.DdagNode
, dep_after
);
1290 current_modref
= prev
;
1291 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1296 /*************************************************************************
1299 * Allocate a WINE_MODREF structure and add it to the process list
1300 * The loader_section must be locked while calling this function.
1302 static WINE_MODREF
*alloc_module( HMODULE hModule
, const UNICODE_STRING
*nt_name
, BOOL builtin
)
1307 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
1309 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) ))) return NULL
;
1311 wm
->ldr
.DllBase
= hModule
;
1312 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
1313 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
| (builtin
? LDR_WINE_INTERNAL
: 0);
1314 wm
->ldr
.TlsIndex
= -1;
1315 wm
->ldr
.LoadCount
= 1;
1316 wm
->CheckSum
= nt
->OptionalHeader
.CheckSum
;
1317 wm
->ldr
.TimeDateStamp
= nt
->FileHeader
.TimeDateStamp
;
1319 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, nt_name
->Length
- 3 * sizeof(WCHAR
) )))
1321 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1325 if (!(wm
->ldr
.DdagNode
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
->ldr
.DdagNode
) )))
1327 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
1328 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1331 InitializeListHead(&wm
->ldr
.DdagNode
->Modules
);
1332 InsertTailList(&wm
->ldr
.DdagNode
->Modules
, &wm
->ldr
.NodeModuleLink
);
1334 memcpy( buffer
, nt_name
->Buffer
+ 4 /* \??\ prefix */, nt_name
->Length
- 4 * sizeof(WCHAR
) );
1335 buffer
[nt_name
->Length
/sizeof(WCHAR
) - 4] = 0;
1336 if ((p
= wcsrchr( buffer
, '\\' ))) p
++;
1338 RtlInitUnicodeString( &wm
->ldr
.FullDllName
, buffer
);
1339 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
1341 if (!is_dll_native_subsystem( &wm
->ldr
, nt
, p
))
1343 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
1344 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
1345 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
1346 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1349 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
1350 &wm
->ldr
.InLoadOrderLinks
);
1351 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
1352 &wm
->ldr
.InMemoryOrderLinks
);
1353 /* wait until init is called for inserting into InInitializationOrderModuleList */
1355 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
1357 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
1358 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1359 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1365 /*************************************************************************
1368 * Allocate the per-thread structure for module TLS storage.
1370 static NTSTATUS
alloc_thread_tls(void)
1375 if (!tls_module_count
) return STATUS_SUCCESS
;
1377 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1378 tls_module_count
* sizeof(*pointers
) )))
1379 return STATUS_NO_MEMORY
;
1381 for (i
= 0; i
< tls_module_count
; i
++)
1383 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1386 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1387 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1389 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1391 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1392 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1393 return STATUS_NO_MEMORY
;
1395 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1396 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1398 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1399 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1401 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1402 #ifdef __x86_64__ /* macOS-specific hack */
1403 if (NtCurrentTeb()->Reserved5
[0])
1404 ((TEB
*)NtCurrentTeb()->Reserved5
[0])->ThreadLocalStoragePointer
= pointers
;
1406 return STATUS_SUCCESS
;
1410 /*************************************************************************
1411 * call_tls_callbacks
1413 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1415 const IMAGE_TLS_DIRECTORY
*dir
;
1416 const PIMAGE_TLS_CALLBACK
*callback
;
1419 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1420 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1422 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1424 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1425 *callback
, module
, reason_names
[reason
] );
1428 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1432 TRACE_(relay
)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1433 GetExceptionCode(), callback
, module
, reason_names
[reason
] );
1437 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1438 *callback
, module
, reason_names
[reason
] );
1442 /*************************************************************************
1445 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1448 NTSTATUS status
= STATUS_SUCCESS
;
1449 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1450 void *module
= wm
->ldr
.DllBase
;
1453 /* Skip calls for modules loaded with special load flags */
1455 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1456 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, reason
);
1457 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
&& reason
== DLL_PROCESS_ATTACH
)
1458 unix_funcs
->init_builtin_dll( wm
->ldr
.DllBase
);
1459 if (!entry
) return STATUS_SUCCESS
;
1461 if (TRACE_ON(relay
))
1463 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1464 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1465 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1466 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1467 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1469 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1470 reason_names
[reason
], lpReserved
);
1474 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1476 status
= STATUS_DLL_INIT_FAILED
;
1480 status
= GetExceptionCode();
1481 TRACE_(relay
)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1482 status
, entry
, module
, reason_names
[reason
], lpReserved
);
1486 /* The state of the module list may have changed due to the call
1487 to the dll. We cannot assume that this module has not been
1489 if (TRACE_ON(relay
))
1490 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1491 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1493 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1499 /*************************************************************************
1502 * Send the process attach notification to all DLLs the given module
1503 * depends on (recursively). This is somewhat complicated due to the fact that
1505 * - we have to respect the module dependencies, i.e. modules implicitly
1506 * referenced by another module have to be initialized before the module
1507 * itself can be initialized
1509 * - the initialization routine of a DLL can itself call LoadLibrary,
1510 * thereby introducing a whole new set of dependencies (even involving
1511 * the 'old' modules) at any time during the whole process
1513 * (Note that this routine can be recursively entered not only directly
1514 * from itself, but also via LoadLibrary from one of the called initialization
1517 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1518 * the process *detach* notifications to be sent in the correct order.
1519 * This must not only take into account module dependencies, but also
1520 * 'hidden' dependencies created by modules calling LoadLibrary in their
1521 * attach notification routine.
1523 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1524 * list after the attach notification has returned. This implies that the
1525 * detach notifications are called in the reverse of the sequence the attach
1526 * notifications *returned*.
1528 * The loader_section must be locked while calling this function.
1530 static NTSTATUS
process_attach( LDR_DDAG_NODE
*node
, LPVOID lpReserved
)
1532 NTSTATUS status
= STATUS_SUCCESS
;
1533 LDR_DATA_TABLE_ENTRY
*mod
;
1537 if (process_detaching
) return status
;
1539 mod
= CONTAINING_RECORD( node
->Modules
.Flink
, LDR_DATA_TABLE_ENTRY
, NodeModuleLink
);
1540 wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
1542 /* prevent infinite recursion in case of cyclical dependencies */
1543 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1544 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1547 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1549 /* Tag current MODREF to prevent recursive loop */
1550 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1551 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1552 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1554 /* Recursively attach all DLLs this one depends on */
1555 walk_node_dependencies( node
, lpReserved
, process_attach
);
1557 if (!wm
->ldr
.InInitializationOrderLinks
.Flink
)
1558 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1559 &wm
->ldr
.InInitializationOrderLinks
);
1561 /* Call DLL entry point */
1562 if (status
== STATUS_SUCCESS
)
1564 WINE_MODREF
*prev
= current_modref
;
1565 current_modref
= wm
;
1567 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED
, &wm
->ldr
);
1568 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1569 if (status
== STATUS_SUCCESS
)
1571 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1575 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1576 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, &wm
->ldr
);
1578 /* point to the name so LdrInitializeThunk can print it */
1579 last_failed_modref
= wm
;
1580 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1582 current_modref
= prev
;
1585 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1586 /* Remove recursion flag */
1587 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1589 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1594 /*************************************************************************
1597 * Send DLL process detach notifications. See the comment about calling
1598 * sequence at process_attach.
1600 static void process_detach(void)
1602 PLIST_ENTRY mark
, entry
;
1603 PLDR_DATA_TABLE_ENTRY mod
;
1605 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1608 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1610 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1611 InInitializationOrderLinks
);
1612 /* Check whether to detach this DLL */
1613 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1615 if ( mod
->LoadCount
&& !process_detaching
)
1618 /* Call detach notification */
1619 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1620 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1621 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1622 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, mod
);
1624 /* Restart at head of WINE_MODREF list, as entries might have
1625 been added and/or removed while performing the call ... */
1628 } while (entry
!= mark
);
1631 /*************************************************************************
1634 * Send DLL thread attach notifications. These are sent in the
1635 * reverse sequence of process detach notification.
1636 * The loader_section must be locked while calling this function.
1638 static void thread_attach(void)
1640 PLIST_ENTRY mark
, entry
;
1641 PLDR_DATA_TABLE_ENTRY mod
;
1643 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1644 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1646 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1647 InInitializationOrderLinks
);
1648 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1650 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1653 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1657 /******************************************************************
1658 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1661 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1664 NTSTATUS ret
= STATUS_SUCCESS
;
1666 RtlEnterCriticalSection( &loader_section
);
1668 wm
= get_modref( hModule
);
1669 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1670 ret
= STATUS_DLL_NOT_FOUND
;
1672 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1674 RtlLeaveCriticalSection( &loader_section
);
1679 /******************************************************************
1680 * LdrFindEntryForAddress (NTDLL.@)
1682 * The loader_section must be locked while calling this function
1684 NTSTATUS WINAPI
LdrFindEntryForAddress( const void *addr
, PLDR_DATA_TABLE_ENTRY
*pmod
)
1686 PLIST_ENTRY mark
, entry
;
1687 PLDR_DATA_TABLE_ENTRY mod
;
1689 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1690 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1692 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1693 if (mod
->DllBase
<= addr
&&
1694 (const char *)addr
< (char*)mod
->DllBase
+ mod
->SizeOfImage
)
1697 return STATUS_SUCCESS
;
1700 return STATUS_NO_MORE_ENTRIES
;
1703 /******************************************************************
1704 * LdrEnumerateLoadedModules (NTDLL.@)
1706 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1708 LIST_ENTRY
*mark
, *entry
;
1709 LDR_DATA_TABLE_ENTRY
*mod
;
1710 BOOLEAN stop
= FALSE
;
1712 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1714 if (unknown
|| !callback
)
1715 return STATUS_INVALID_PARAMETER
;
1717 RtlEnterCriticalSection( &loader_section
);
1719 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1720 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1722 mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1723 callback( mod
, context
, &stop
);
1727 RtlLeaveCriticalSection( &loader_section
);
1728 return STATUS_SUCCESS
;
1731 /******************************************************************
1732 * LdrRegisterDllNotification (NTDLL.@)
1734 NTSTATUS WINAPI
LdrRegisterDllNotification(ULONG flags
, PLDR_DLL_NOTIFICATION_FUNCTION callback
,
1735 void *context
, void **cookie
)
1737 struct ldr_notification
*notify
;
1739 TRACE( "(%x, %p, %p, %p)\n", flags
, callback
, context
, cookie
);
1741 if (!callback
|| !cookie
)
1742 return STATUS_INVALID_PARAMETER
;
1745 FIXME( "ignoring flags %x\n", flags
);
1747 notify
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify
) );
1748 if (!notify
) return STATUS_NO_MEMORY
;
1749 notify
->callback
= callback
;
1750 notify
->context
= context
;
1752 RtlEnterCriticalSection( &loader_section
);
1753 list_add_tail( &ldr_notifications
, ¬ify
->entry
);
1754 RtlLeaveCriticalSection( &loader_section
);
1757 return STATUS_SUCCESS
;
1760 /******************************************************************
1761 * LdrUnregisterDllNotification (NTDLL.@)
1763 NTSTATUS WINAPI
LdrUnregisterDllNotification( void *cookie
)
1765 struct ldr_notification
*notify
= cookie
;
1767 TRACE( "(%p)\n", cookie
);
1769 if (!notify
) return STATUS_INVALID_PARAMETER
;
1771 RtlEnterCriticalSection( &loader_section
);
1772 list_remove( ¬ify
->entry
);
1773 RtlLeaveCriticalSection( &loader_section
);
1775 RtlFreeHeap( GetProcessHeap(), 0, notify
);
1776 return STATUS_SUCCESS
;
1779 /******************************************************************
1780 * LdrLockLoaderLock (NTDLL.@)
1782 * Note: some flags are not implemented.
1783 * Flag 0x01 is used to raise exceptions on errors.
1785 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1787 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1789 if (result
) *result
= 0;
1790 if (magic
) *magic
= 0;
1791 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1792 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1793 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1797 if (!RtlTryEnterCriticalSection( &loader_section
))
1800 return STATUS_SUCCESS
;
1806 RtlEnterCriticalSection( &loader_section
);
1807 if (result
) *result
= 1;
1809 *magic
= GetCurrentThreadId();
1810 return STATUS_SUCCESS
;
1814 /******************************************************************
1815 * LdrUnlockLoaderUnlock (NTDLL.@)
1817 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1821 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1822 RtlLeaveCriticalSection( &loader_section
);
1824 return STATUS_SUCCESS
;
1828 /******************************************************************
1829 * LdrGetProcedureAddress (NTDLL.@)
1831 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1832 ULONG ord
, PVOID
*address
)
1834 IMAGE_EXPORT_DIRECTORY
*exports
;
1836 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1838 RtlEnterCriticalSection( &loader_section
);
1840 /* check if the module itself is invalid to return the proper error */
1841 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1842 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1843 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1845 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, NULL
)
1846 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, NULL
);
1850 ret
= STATUS_SUCCESS
;
1854 RtlLeaveCriticalSection( &loader_section
);
1859 /***********************************************************************
1860 * set_security_cookie
1862 * Create a random security cookie for buffer overflow protection. Make
1863 * sure it does not accidentally match the default cookie value.
1865 static void set_security_cookie( void *module
, SIZE_T len
)
1868 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1872 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1873 if (!loadcfg
) return;
1874 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1875 if (!loadcfg
->SecurityCookie
) return;
1876 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1877 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1879 WARN( "security cookie %p outside of image %p-%p\n",
1880 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1884 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1885 TRACE( "initializing security cookie %p\n", cookie
);
1887 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1890 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1891 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1892 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1893 *cookie
= RtlRandom( &seed
);
1894 #ifdef DEFAULT_SECURITY_COOKIE_64
1895 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1897 *cookie
= RtlRandom( &seed
);
1898 /* fill up, but keep the highest word clear */
1899 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1907 static NTSTATUS
perform_relocations( void *module
, IMAGE_NT_HEADERS
*nt
, SIZE_T len
)
1910 IMAGE_BASE_RELOCATION
*rel
, *end
;
1911 const IMAGE_DATA_DIRECTORY
*relocs
;
1912 const IMAGE_SECTION_HEADER
*sec
;
1914 ULONG protect_old
[96], i
;
1916 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1917 if (module
== base
) return STATUS_SUCCESS
; /* nothing to do */
1919 /* no relocations are performed on non page-aligned binaries */
1920 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1921 return STATUS_SUCCESS
;
1923 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1924 return STATUS_SUCCESS
;
1926 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1928 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1930 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1932 return STATUS_CONFLICTING_ADDRESSES
;
1935 if (!relocs
->Size
) return STATUS_SUCCESS
;
1936 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1938 if (nt
->FileHeader
.NumberOfSections
> ARRAY_SIZE( protect_old
))
1939 return STATUS_INVALID_IMAGE_FORMAT
;
1941 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1942 nt
->FileHeader
.SizeOfOptionalHeader
);
1943 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1945 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1946 SIZE_T size
= sec
[i
].SizeOfRawData
;
1947 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1948 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1951 TRACE( "relocating from %p-%p to %p-%p\n",
1952 base
, base
+ len
, module
, (char *)module
+ len
);
1954 rel
= get_rva( module
, relocs
->VirtualAddress
);
1955 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1956 delta
= (char *)module
- base
;
1958 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1960 if (rel
->VirtualAddress
>= len
)
1962 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1963 return STATUS_ACCESS_VIOLATION
;
1965 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1966 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1967 (USHORT
*)(rel
+ 1), delta
);
1968 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1971 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1973 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1974 SIZE_T size
= sec
[i
].SizeOfRawData
;
1975 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1976 &size
, protect_old
[i
], &protect_old
[i
] );
1979 return STATUS_SUCCESS
;
1983 /*************************************************************************
1986 * Build the module data for a mapped dll.
1988 static NTSTATUS
build_module( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, void **module
,
1989 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
1990 DWORD flags
, WINE_MODREF
**pwm
)
1992 static const char builtin_signature
[] = "Wine builtin DLL";
1993 char *signature
= (char *)((IMAGE_DOS_HEADER
*)*module
+ 1);
1995 IMAGE_NT_HEADERS
*nt
;
2000 if (!(nt
= RtlImageNtHeader( *module
))) return STATUS_INVALID_IMAGE_FORMAT
;
2002 map_size
= (nt
->OptionalHeader
.SizeOfImage
+ page_size
- 1) & ~(page_size
- 1);
2003 if ((status
= perform_relocations( *module
, nt
, map_size
))) return status
;
2005 is_builtin
= ((char *)nt
- signature
>= sizeof(builtin_signature
) &&
2006 !memcmp( signature
, builtin_signature
, sizeof(builtin_signature
) ));
2008 /* create the MODREF */
2010 if (!(wm
= alloc_module( *module
, nt_name
, is_builtin
))) return STATUS_NO_MEMORY
;
2012 if (id
) wm
->id
= *id
;
2013 if (image_info
->LoaderFlags
) wm
->ldr
.Flags
|= LDR_COR_IMAGE
;
2014 if (image_info
->u
.s
.ComPlusILOnly
) wm
->ldr
.Flags
|= LDR_COR_ILONLY
;
2016 set_security_cookie( *module
, map_size
);
2020 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
2021 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
2022 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
2024 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
2025 status
= fixup_imports_ilonly( wm
, load_path
, &wm
->ldr
.EntryPoint
);
2027 status
= fixup_imports( wm
, load_path
);
2028 if (status
!= STATUS_SUCCESS
)
2030 /* the module has only be inserted in the load & memory order lists */
2031 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
2032 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
2034 /* FIXME: there are several more dangling references
2035 * left. Including dlls loaded by this dll before the
2036 * failed one. Unrolling is rather difficult with the
2037 * current structure and we can leave them lying
2038 * around with no problems, so we don't care.
2039 * As these might reference our wm, we don't free it.
2046 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name
), wm
, *module
);
2050 if (TRACE_ON(relay
)) RELAY_SetupDLL( *module
);
2054 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( *module
);
2057 TRACE_(loaddll
)( "Loaded %s at %p: %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), *module
,
2058 is_builtin
? "builtin" : "native" );
2060 wm
->ldr
.LoadCount
= 1;
2063 return STATUS_SUCCESS
;
2067 /*************************************************************************
2068 * build_ntdll_module
2070 * Build the module data for the initially-loaded ntdll.
2072 static void build_ntdll_module(void)
2074 MEMORY_BASIC_INFORMATION meminfo
;
2075 UNICODE_STRING nt_name
;
2078 RtlInitUnicodeString( &nt_name
, L
"\\??\\C:\\windows\\system32\\ntdll.dll" );
2079 NtQueryVirtualMemory( GetCurrentProcess(), build_ntdll_module
, MemoryBasicInformation
,
2080 &meminfo
, sizeof(meminfo
), NULL
);
2081 wm
= alloc_module( meminfo
.AllocationBase
, &nt_name
, TRUE
);
2083 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
2084 node_ntdll
= wm
->ldr
.DdagNode
;
2085 if (TRACE_ON(relay
)) RELAY_SetupDLL( meminfo
.AllocationBase
);
2090 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
2091 static BOOL
convert_to_pe64( HMODULE module
, const SECTION_IMAGE_INFORMATION
*info
)
2093 static const ULONG copy_dirs
[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE
,
2094 IMAGE_DIRECTORY_ENTRY_SECURITY
,
2095 IMAGE_DIRECTORY_ENTRY_BASERELOC
,
2096 IMAGE_DIRECTORY_ENTRY_DEBUG
,
2097 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
};
2098 IMAGE_OPTIONAL_HEADER32 hdr32
= { IMAGE_NT_OPTIONAL_HDR32_MAGIC
};
2099 IMAGE_OPTIONAL_HEADER64 hdr64
= { IMAGE_NT_OPTIONAL_HDR64_MAGIC
};
2100 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
2101 SIZE_T hdr_size
= min( sizeof(hdr32
), nt
->FileHeader
.SizeOfOptionalHeader
);
2102 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char *)&nt
->OptionalHeader
+ hdr_size
);
2103 SIZE_T size
= min( nt
->OptionalHeader
.SizeOfHeaders
, nt
->OptionalHeader
.SizeOfImage
);
2104 void *addr
= module
;
2107 if (nt
->OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return TRUE
; /* already 64-bit */
2108 if (!info
->ImageContainsCode
) return TRUE
; /* no need to convert */
2110 TRACE( "%p\n", module
);
2112 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, PAGE_READWRITE
, &old_prot
))
2115 if ((char *)module
+ size
< (char *)(nt
+ 1) + nt
->FileHeader
.NumberOfSections
* sizeof(*sec
))
2117 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
2121 memcpy( &hdr32
, &nt
->OptionalHeader
, hdr_size
);
2122 memcpy( &hdr64
, &hdr32
, offsetof( IMAGE_OPTIONAL_HEADER64
, SizeOfStackReserve
));
2123 hdr64
.Magic
= IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
2124 hdr64
.AddressOfEntryPoint
= 0;
2125 hdr64
.ImageBase
= hdr32
.ImageBase
;
2126 hdr64
.SizeOfStackReserve
= hdr32
.SizeOfStackReserve
;
2127 hdr64
.SizeOfStackCommit
= hdr32
.SizeOfStackCommit
;
2128 hdr64
.SizeOfHeapReserve
= hdr32
.SizeOfHeapReserve
;
2129 hdr64
.SizeOfHeapCommit
= hdr32
.SizeOfHeapCommit
;
2130 hdr64
.LoaderFlags
= hdr32
.LoaderFlags
;
2131 hdr64
.NumberOfRvaAndSizes
= hdr32
.NumberOfRvaAndSizes
;
2132 for (i
= 0; i
< ARRAY_SIZE( copy_dirs
); i
++)
2133 hdr64
.DataDirectory
[copy_dirs
[i
]] = hdr32
.DataDirectory
[copy_dirs
[i
]];
2135 memmove( nt
+ 1, sec
, nt
->FileHeader
.NumberOfSections
* sizeof(*sec
) );
2136 nt
->FileHeader
.SizeOfOptionalHeader
= sizeof(hdr64
);
2137 nt
->OptionalHeader
= hdr64
;
2138 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
2142 /* check COM header for ILONLY flag, ignoring runtime version */
2143 static BOOL
get_cor_header( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
, IMAGE_COR20_HEADER
*cor
)
2145 IMAGE_DOS_HEADER mz
;
2146 IMAGE_NT_HEADERS32 nt
;
2148 LARGE_INTEGER offset
;
2149 IMAGE_SECTION_HEADER sec
[96];
2150 unsigned int i
, count
;
2153 offset
.QuadPart
= 0;
2154 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &mz
, sizeof(mz
), &offset
, NULL
)) return FALSE
;
2155 if (io
.Information
!= sizeof(mz
)) return FALSE
;
2156 if (mz
.e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
2157 offset
.QuadPart
= mz
.e_lfanew
;
2158 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &nt
, sizeof(nt
), &offset
, NULL
)) return FALSE
;
2159 if (io
.Information
!= sizeof(nt
)) return FALSE
;
2160 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) return FALSE
;
2161 if (nt
.OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return FALSE
;
2162 va
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].VirtualAddress
;
2163 size
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].Size
;
2164 if (!va
|| size
< sizeof(*cor
)) return FALSE
;
2165 offset
.QuadPart
+= offsetof( IMAGE_NT_HEADERS32
, OptionalHeader
) + nt
.FileHeader
.SizeOfOptionalHeader
;
2166 count
= min( 96, nt
.FileHeader
.NumberOfSections
);
2167 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &sec
, count
* sizeof(*sec
), &offset
, NULL
)) return FALSE
;
2168 if (io
.Information
!= count
* sizeof(*sec
)) return FALSE
;
2169 for (i
= 0; i
< count
; i
++)
2171 if (va
< sec
[i
].VirtualAddress
) continue;
2172 if (sec
[i
].Misc
.VirtualSize
&& va
- sec
[i
].VirtualAddress
>= sec
[i
].Misc
.VirtualSize
) continue;
2173 offset
.QuadPart
= sec
->PointerToRawData
+ va
- sec
[i
].VirtualAddress
;
2174 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, cor
, sizeof(*cor
), &offset
, NULL
)) return FALSE
;
2175 return (io
.Information
== sizeof(*cor
));
2181 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2182 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2183 static BOOL
is_valid_binary( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
)
2186 return info
->Machine
== IMAGE_FILE_MACHINE_I386
;
2187 #elif defined(__arm__)
2188 return info
->Machine
== IMAGE_FILE_MACHINE_ARM
||
2189 info
->Machine
== IMAGE_FILE_MACHINE_THUMB
||
2190 info
->Machine
== IMAGE_FILE_MACHINE_ARMNT
;
2191 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2193 if (info
->Machine
== IMAGE_FILE_MACHINE_AMD64
) return TRUE
;
2195 if (info
->Machine
== IMAGE_FILE_MACHINE_ARM64
) return TRUE
;
2197 if (!info
->ImageContainsCode
) return TRUE
;
2198 if (!(info
->u
.s
.ComPlusNativeReady
))
2200 IMAGE_COR20_HEADER cor_header
;
2201 if (!get_cor_header( file
, info
, &cor_header
)) return FALSE
;
2202 if (!(cor_header
.Flags
& COMIMAGE_FLAGS_ILONLY
)) return FALSE
;
2206 return FALSE
; /* no wow64 support on other platforms */
2211 /******************************************************************
2212 * get_module_path_end
2214 * Returns the end of the directory component of the module path.
2216 static inline const WCHAR
*get_module_path_end( const WCHAR
*module
)
2219 const WCHAR
*mod_end
= module
;
2221 if ((p
= wcsrchr( mod_end
, '\\' ))) mod_end
= p
;
2222 if ((p
= wcsrchr( mod_end
, '/' ))) mod_end
= p
;
2223 if (mod_end
== module
+ 2 && module
[1] == ':') mod_end
++;
2224 if (mod_end
== module
&& module
[0] && module
[1] == ':') mod_end
+= 2;
2229 /******************************************************************
2232 * Append a counted string to the load path. Helper for get_dll_load_path.
2234 static inline WCHAR
*append_path( WCHAR
*p
, const WCHAR
*str
, int len
)
2236 if (len
== -1) len
= wcslen(str
);
2238 memcpy( p
, str
, len
* sizeof(WCHAR
) );
2244 /******************************************************************
2247 static NTSTATUS
get_dll_load_path( LPCWSTR module
, LPCWSTR dll_dir
, ULONG safe_mode
, WCHAR
**path
)
2249 const WCHAR
*mod_end
= module
;
2250 UNICODE_STRING name
, value
;
2252 int len
= ARRAY_SIZE(system_path
) + 1, path_len
= 0;
2256 mod_end
= get_module_path_end( module
);
2257 len
+= (mod_end
- module
) + 1;
2260 RtlInitUnicodeString( &name
, L
"PATH" );
2262 value
.MaximumLength
= 0;
2263 value
.Buffer
= NULL
;
2264 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2265 path_len
= value
.Length
;
2267 if (dll_dir
) len
+= wcslen( dll_dir
) + 1;
2268 else len
+= 2; /* current directory */
2269 if (!(p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, path_len
+ len
* sizeof(WCHAR
) )))
2270 return STATUS_NO_MEMORY
;
2272 p
= append_path( p
, module
, mod_end
- module
);
2273 if (dll_dir
) p
= append_path( p
, dll_dir
, -1 );
2274 else if (!safe_mode
) p
= append_path( p
, L
".", -1 );
2275 p
= append_path( p
, system_path
, -1 );
2276 if (!dll_dir
&& safe_mode
) p
= append_path( p
, L
".", -1 );
2279 value
.MaximumLength
= path_len
;
2281 while (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2285 /* grow the buffer and retry */
2286 path_len
= value
.Length
;
2287 if (!(new_ptr
= RtlReAllocateHeap( GetProcessHeap(), 0, ret
, path_len
+ len
* sizeof(WCHAR
) )))
2289 RtlFreeHeap( GetProcessHeap(), 0, ret
);
2290 return STATUS_NO_MEMORY
;
2292 value
.Buffer
= new_ptr
+ (value
.Buffer
- ret
);
2293 value
.MaximumLength
= path_len
;
2296 value
.Buffer
[value
.Length
/ sizeof(WCHAR
)] = 0;
2298 return STATUS_SUCCESS
;
2302 /******************************************************************
2303 * get_dll_load_path_search_flags
2305 static NTSTATUS
get_dll_load_path_search_flags( LPCWSTR module
, DWORD flags
, WCHAR
**path
)
2307 const WCHAR
*image
= NULL
, *mod_end
, *image_end
;
2308 struct dll_dir_entry
*dir
;
2312 if (flags
& LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
)
2313 flags
|= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
2314 LOAD_LIBRARY_SEARCH_USER_DIRS
|
2315 LOAD_LIBRARY_SEARCH_SYSTEM32
);
2317 if (flags
& LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
)
2319 DWORD type
= RtlDetermineDosPathNameType_U( module
);
2320 if (type
!= ABSOLUTE_DRIVE_PATH
&& type
!= ABSOLUTE_PATH
&& type
!= DEVICE_PATH
)
2321 return STATUS_INVALID_PARAMETER
;
2322 mod_end
= get_module_path_end( module
);
2323 len
+= (mod_end
- module
) + 1;
2327 if (flags
& LOAD_LIBRARY_SEARCH_APPLICATION_DIR
)
2329 image
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
2330 image_end
= get_module_path_end( image
);
2331 len
+= (image_end
- image
) + 1;
2334 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2336 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2337 len
+= wcslen( dir
->dir
+ 4 /* \??\ */ ) + 1;
2338 if (dll_directory
.Length
) len
+= dll_directory
.Length
/ sizeof(WCHAR
) + 1;
2341 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) len
+= wcslen( system_dir
);
2343 if ((p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2345 if (module
) p
= append_path( p
, module
, mod_end
- module
);
2346 if (image
) p
= append_path( p
, image
, image_end
- image
);
2347 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2349 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2350 p
= append_path( p
, dir
->dir
+ 4 /* \??\ */, -1 );
2351 p
= append_path( p
, dll_directory
.Buffer
, dll_directory
.Length
/ sizeof(WCHAR
) );
2353 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) wcscpy( p
, system_dir
);
2361 return STATUS_SUCCESS
;
2365 /***********************************************************************
2368 * Open a file for a new dll. Helper for find_dll_file.
2370 static NTSTATUS
open_dll_file( UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2371 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2373 FILE_BASIC_INFORMATION info
;
2374 OBJECT_ATTRIBUTES attr
;
2377 FILE_OBJECTID_BUFFER fid
;
2381 if ((*pwm
= find_fullname_module( nt_name
))) return STATUS_SUCCESS
;
2383 attr
.Length
= sizeof(attr
);
2384 attr
.RootDirectory
= 0;
2385 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2386 attr
.ObjectName
= nt_name
;
2387 attr
.SecurityDescriptor
= NULL
;
2388 attr
.SecurityQualityOfService
= NULL
;
2389 if ((status
= NtOpenFile( &handle
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
,
2390 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2391 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
2393 if (status
!= STATUS_OBJECT_PATH_NOT_FOUND
&&
2394 status
!= STATUS_OBJECT_NAME_NOT_FOUND
&&
2395 !NtQueryAttributesFile( &attr
, &info
))
2397 /* if the file exists but failed to open, report the error */
2400 /* otherwise continue searching */
2401 return STATUS_DLL_NOT_FOUND
;
2404 if (!NtFsControlFile( handle
, 0, NULL
, NULL
, &io
, FSCTL_GET_OBJECT_ID
, NULL
, 0, &fid
, sizeof(fid
) ))
2406 memcpy( id
, fid
.ObjectId
, sizeof(*id
) );
2407 if ((*pwm
= find_fileid_module( id
)))
2409 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name
->Buffer
),
2410 (*pwm
)->ldr
.DllBase
, debugstr_w( (*pwm
)->ldr
.FullDllName
.Buffer
));
2412 return STATUS_SUCCESS
;
2417 status
= NtCreateSection( mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
2418 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
2419 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, handle
);
2422 NtQuerySection( *mapping
, SectionImageInformation
, image_info
, sizeof(*image_info
), NULL
);
2423 if (!is_valid_binary( handle
, image_info
))
2425 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name
), image_info
->Machine
);
2426 status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2427 NtClose( *mapping
);
2436 /******************************************************************************
2437 * find_existing_module
2439 * Find an existing module that is the same mapping as the new module.
2441 static WINE_MODREF
*find_existing_module( HMODULE module
)
2444 LIST_ENTRY
*mark
, *entry
;
2445 LDR_DATA_TABLE_ENTRY
*mod
;
2446 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
2448 if ((wm
= get_modref( module
))) return wm
;
2450 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
2451 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2453 mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
2454 if (mod
->TimeDateStamp
!= nt
->FileHeader
.TimeDateStamp
) continue;
2455 wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
2456 if (wm
->CheckSum
!= nt
->OptionalHeader
.CheckSum
) continue;
2457 if (NtAreMappedFilesTheSame( mod
->DllBase
, module
) != STATUS_SUCCESS
) continue;
2458 return CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
2464 /******************************************************************************
2465 * load_native_dll (internal)
2467 static NTSTATUS
load_native_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, HANDLE mapping
,
2468 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
2469 DWORD flags
, WINE_MODREF
** pwm
)
2471 void *module
= NULL
;
2473 NTSTATUS status
= NtMapViewOfSection( mapping
, NtCurrentProcess(), &module
, 0, 0, NULL
, &len
,
2474 ViewShare
, 0, PAGE_EXECUTE_READ
);
2476 if (status
== STATUS_IMAGE_NOT_AT_BASE
) status
= STATUS_SUCCESS
;
2477 if (status
) return status
;
2479 if ((*pwm
= find_existing_module( module
))) /* already loaded */
2481 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2482 TRACE( "found %s for %s at %p, count=%d\n",
2483 debugstr_us(&(*pwm
)->ldr
.FullDllName
), debugstr_us(nt_name
),
2484 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2485 if (module
!= (*pwm
)->ldr
.DllBase
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2486 return STATUS_SUCCESS
;
2489 if (!convert_to_pe64( module
, image_info
)) status
= STATUS_INVALID_IMAGE_FORMAT
;
2491 if (!status
) status
= build_module( load_path
, nt_name
, &module
, image_info
, id
, flags
, pwm
);
2492 if (status
&& module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2497 /***********************************************************************
2500 static NTSTATUS
load_so_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
,
2501 DWORD flags
, WINE_MODREF
**pwm
)
2506 UNICODE_STRING win_name
= *nt_name
;
2508 TRACE( "trying %s as so lib\n", debugstr_us(&win_name
) );
2509 if ((status
= unix_funcs
->load_so_dll( &win_name
, &module
)))
2511 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name
) );
2512 if (status
== STATUS_INVALID_IMAGE_FORMAT
) status
= STATUS_INVALID_IMAGE_NOT_MZ
;
2516 if ((wm
= get_modref( module
))) /* already loaded */
2518 TRACE( "Found %s at %p for builtin %s\n",
2519 debugstr_w(wm
->ldr
.FullDllName
.Buffer
), wm
->ldr
.DllBase
, debugstr_us(nt_name
) );
2520 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2524 SECTION_IMAGE_INFORMATION image_info
= { 0 };
2526 if ((status
= build_module( load_path
, &win_name
, &module
, &image_info
, NULL
, flags
, &wm
)))
2528 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2531 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name
), module
);
2534 return STATUS_SUCCESS
;
2538 /*************************************************************************
2541 * Build the module data for the main image.
2543 static WINE_MODREF
*build_main_module(void)
2545 SECTION_IMAGE_INFORMATION info
;
2546 UNICODE_STRING nt_name
;
2549 RTL_USER_PROCESS_PARAMETERS
*params
= NtCurrentTeb()->Peb
->ProcessParameters
;
2550 void *module
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
2552 default_load_path
= params
->DllPath
.Buffer
;
2553 if (!default_load_path
)
2554 get_dll_load_path( params
->ImagePathName
.Buffer
, NULL
, dll_safe_mode
, &default_load_path
);
2556 NtQueryInformationProcess( GetCurrentProcess(), ProcessImageInformation
, &info
, sizeof(info
), NULL
);
2557 if (info
.ImageCharacteristics
& IMAGE_FILE_DLL
)
2559 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_us(¶ms
->ImagePathName
) );
2560 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT
);
2563 if (!convert_to_pe64( module
, &info
))
2565 status
= STATUS_INVALID_IMAGE_FORMAT
;
2569 status
= RtlDosPathNameToNtPathName_U_WithStatus( params
->ImagePathName
.Buffer
, &nt_name
, NULL
, NULL
);
2570 if (status
) goto failed
;
2571 status
= build_module( NULL
, &nt_name
, &module
, &info
, NULL
, DONT_RESOLVE_DLL_REFERENCES
, &wm
);
2572 RtlFreeUnicodeString( &nt_name
);
2573 if (!status
) return wm
;
2575 MESSAGE( "wine: failed to create main module for %s, status %x\n",
2576 debugstr_us(¶ms
->ImagePathName
), status
);
2577 NtTerminateProcess( GetCurrentProcess(), status
);
2578 return NULL
; /* unreached */
2582 /***********************************************************************
2583 * build_dlldata_path
2585 * Helper for find_actctx_dll.
2587 static NTSTATUS
build_dlldata_path( LPCWSTR libname
, ACTCTX_SECTION_KEYED_DATA
*data
, LPWSTR
*fullname
)
2589 struct dllredirect_data
*dlldata
= data
->lpData
;
2590 char *base
= data
->lpSectionBase
;
2591 SIZE_T total
= dlldata
->total_len
+ (wcslen(libname
) + 1) * sizeof(WCHAR
);
2593 NTSTATUS status
= STATUS_SUCCESS
;
2596 if (!(p
= buffer
= RtlAllocateHeap( GetProcessHeap(), 0, total
))) return STATUS_NO_MEMORY
;
2597 for (i
= 0; i
< dlldata
->paths_count
; i
++)
2599 memcpy( p
, base
+ dlldata
->paths
[i
].offset
, dlldata
->paths
[i
].len
);
2600 p
+= dlldata
->paths
[i
].len
/ sizeof(WCHAR
);
2602 if (p
== buffer
|| p
[-1] == '\\') wcscpy( p
, libname
);
2605 if (dlldata
->flags
& DLL_REDIRECT_PATH_EXPAND
)
2607 RtlExpandEnvironmentStrings( NULL
, buffer
, wcslen(buffer
), NULL
, 0, &total
);
2608 if ((*fullname
= RtlAllocateHeap( GetProcessHeap(), 0, total
* sizeof(WCHAR
) )))
2609 RtlExpandEnvironmentStrings( NULL
, buffer
, wcslen(buffer
), *fullname
, total
, NULL
);
2611 status
= STATUS_NO_MEMORY
;
2613 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2615 else *fullname
= buffer
;
2621 /***********************************************************************
2624 * Find the full path (if any) of the dll from the activation context.
2626 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2628 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2630 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
= NULL
;
2631 ACTCTX_SECTION_KEYED_DATA data
;
2632 struct dllredirect_data
*dlldata
;
2633 UNICODE_STRING nameW
;
2635 SIZE_T needed
, size
= 1024;
2638 RtlInitUnicodeString( &nameW
, libname
);
2639 data
.cbSize
= sizeof(data
);
2640 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2641 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2643 if (status
!= STATUS_SUCCESS
) return status
;
2645 if (data
.ulLength
< offsetof( struct dllredirect_data
, paths
[0] ))
2647 status
= STATUS_SXS_KEY_NOT_FOUND
;
2650 dlldata
= data
.lpData
;
2651 if (!(dlldata
->flags
& DLL_REDIRECT_PATH_OMITS_ASSEMBLY_ROOT
))
2653 status
= build_dlldata_path( libname
, &data
, fullname
);
2659 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2661 status
= STATUS_NO_MEMORY
;
2664 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2665 AssemblyDetailedInformationInActivationContext
,
2666 info
, size
, &needed
);
2667 if (status
== STATUS_SUCCESS
) break;
2668 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2669 RtlFreeHeap( GetProcessHeap(), 0, info
);
2671 /* restart with larger buffer */
2674 if (!info
->lpAssemblyManifestPath
)
2676 status
= STATUS_SXS_KEY_NOT_FOUND
;
2680 if ((p
= wcsrchr( info
->lpAssemblyManifestPath
, '\\' )))
2682 DWORD len
, dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2685 if (!dirlen
|| len
<= dirlen
||
2686 RtlCompareUnicodeStrings( p
, dirlen
, info
->lpAssemblyDirectoryName
, dirlen
, TRUE
) ||
2687 wcsicmp( p
+ dirlen
, L
".manifest" ))
2689 /* manifest name does not match directory name, so it's not a global
2690 * windows/winsxs manifest; use the manifest directory name instead */
2691 dirlen
= p
- info
->lpAssemblyManifestPath
;
2692 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2693 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2695 status
= STATUS_NO_MEMORY
;
2698 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2700 wcscpy( p
, libname
);
2705 if (!info
->lpAssemblyDirectoryName
)
2707 status
= STATUS_SXS_KEY_NOT_FOUND
;
2711 needed
= (wcslen(windows_dir
) * sizeof(WCHAR
) +
2712 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2714 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2716 status
= STATUS_NO_MEMORY
;
2719 wcscpy( p
, windows_dir
);
2721 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2722 p
+= ARRAY_SIZE( winsxsW
);
2723 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2724 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2726 wcscpy( p
, libname
);
2728 RtlFreeHeap( GetProcessHeap(), 0, info
);
2729 RtlReleaseActivationContext( data
.hActCtx
);
2734 /***********************************************************************
2737 static NTSTATUS
get_env_var( const WCHAR
*name
, SIZE_T extra
, UNICODE_STRING
*ret
)
2740 SIZE_T len
, size
= 1024 + extra
;
2744 ret
->Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
* sizeof(WCHAR
) );
2745 status
= RtlQueryEnvironmentVariable( NULL
, name
, wcslen(name
),
2746 ret
->Buffer
, size
- extra
- 1, &len
);
2749 ret
->Buffer
[len
] = 0;
2750 ret
->Length
= len
* sizeof(WCHAR
);
2751 ret
->MaximumLength
= size
* sizeof(WCHAR
);
2754 RtlFreeHeap( GetProcessHeap(), 0, ret
->Buffer
);
2755 if (status
!= STATUS_BUFFER_TOO_SMALL
)
2760 size
= len
+ 1 + extra
;
2765 /***********************************************************************
2766 * find_builtin_without_file
2768 * Find a builtin dll when the corresponding file cannot be found in the prefix.
2769 * This is used during prefix bootstrap.
2771 static NTSTATUS
find_builtin_without_file( const WCHAR
*name
, UNICODE_STRING
*new_name
,
2772 WINE_MODREF
**pwm
, HANDLE
*mapping
,
2773 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2778 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
2779 BOOL found_image
= FALSE
;
2781 if (!get_env_var( L
"WINEBUILDDIR", 20 + 2 * wcslen(name
), new_name
))
2783 len
= new_name
->Length
;
2784 RtlAppendUnicodeToString( new_name
, L
"\\dlls\\" );
2785 RtlAppendUnicodeToString( new_name
, name
);
2786 if ((ext
= wcsrchr( name
, '.' )) && !wcscmp( ext
, L
".dll" )) new_name
->Length
-= 4 * sizeof(WCHAR
);
2787 RtlAppendUnicodeToString( new_name
, L
"\\" );
2788 RtlAppendUnicodeToString( new_name
, name
);
2789 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2790 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2791 RtlAppendUnicodeToString( new_name
, L
".fake" );
2792 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2793 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2795 new_name
->Length
= len
;
2796 RtlAppendUnicodeToString( new_name
, L
"\\programs\\" );
2797 RtlAppendUnicodeToString( new_name
, name
);
2798 RtlAppendUnicodeToString( new_name
, L
"\\" );
2799 RtlAppendUnicodeToString( new_name
, name
);
2800 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2801 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2802 RtlAppendUnicodeToString( new_name
, L
".fake" );
2803 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2804 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2805 RtlFreeUnicodeString( new_name
);
2810 swprintf( dllpath
, ARRAY_SIZE(dllpath
), L
"WINEDLLDIR%u", i
);
2811 if (get_env_var( dllpath
, wcslen(pe_dir
) + wcslen(name
) + 1, new_name
)) break;
2812 len
= new_name
->Length
;
2813 RtlAppendUnicodeToString( new_name
, pe_dir
);
2814 RtlAppendUnicodeToString( new_name
, L
"\\" );
2815 RtlAppendUnicodeToString( new_name
, name
);
2816 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2817 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2818 new_name
->Length
= len
;
2819 RtlAppendUnicodeToString( new_name
, L
"\\" );
2820 RtlAppendUnicodeToString( new_name
, name
);
2821 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2822 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) found_image
= TRUE
;
2823 else if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2824 RtlFreeUnicodeString( new_name
);
2826 if (found_image
) status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2829 RtlFreeUnicodeString( new_name
);
2832 new_name
->Length
= (4 + wcslen(system_dir
) + wcslen(name
)) * sizeof(WCHAR
);
2833 new_name
->Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, new_name
->Length
+ sizeof(WCHAR
) );
2834 wcscpy( new_name
->Buffer
, L
"\\??\\" );
2835 wcscat( new_name
->Buffer
, system_dir
);
2836 wcscat( new_name
->Buffer
, name
);
2842 /***********************************************************************
2845 * Search for dll in the specified paths.
2847 static NTSTATUS
search_dll_file( LPCWSTR paths
, LPCWSTR search
, UNICODE_STRING
*nt_name
,
2848 WINE_MODREF
**pwm
, HANDLE
*mapping
, SECTION_IMAGE_INFORMATION
*image_info
,
2849 struct file_id
*id
)
2852 BOOL found_image
= FALSE
;
2853 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
2856 if (!paths
) paths
= default_load_path
;
2857 len
= wcslen( paths
);
2859 if (len
< wcslen( system_dir
)) len
= wcslen( system_dir
);
2860 len
+= wcslen( search
) + 2;
2862 if (!(name
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2863 return STATUS_NO_MEMORY
;
2867 LPCWSTR ptr
= paths
;
2869 while (*ptr
&& *ptr
!= ';') ptr
++;
2871 if (*ptr
== ';') ptr
++;
2872 memcpy( name
, paths
, len
* sizeof(WCHAR
) );
2873 if (len
&& name
[len
- 1] != '\\') name
[len
++] = '\\';
2874 wcscpy( name
+ len
, search
);
2876 nt_name
->Buffer
= NULL
;
2877 if ((status
= RtlDosPathNameToNtPathName_U_WithStatus( name
, nt_name
, NULL
, NULL
))) goto done
;
2879 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
2880 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) found_image
= TRUE
;
2881 else if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2882 RtlFreeUnicodeString( nt_name
);
2887 status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2888 else if (is_prefix_bootstrap
&& !contains_path( search
))
2889 status
= find_builtin_without_file( search
, nt_name
, pwm
, mapping
, image_info
, id
);
2892 RtlFreeHeap( GetProcessHeap(), 0, name
);
2897 /***********************************************************************
2900 * Find the file (or already loaded module) for a given dll name.
2902 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
2903 UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2904 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2906 WCHAR
*ext
, *dllname
;
2908 ULONG wow64_old_value
= 0;
2913 if (default_ext
) /* first append default extension */
2915 if (!(ext
= wcsrchr( libname
, '.')) || wcschr( ext
, '/' ) || wcschr( ext
, '\\'))
2917 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2918 (wcslen(libname
)+wcslen(default_ext
)+1) * sizeof(WCHAR
))))
2919 return STATUS_NO_MEMORY
;
2920 wcscpy( dllname
, libname
);
2921 wcscat( dllname
, default_ext
);
2926 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2927 RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value
);
2929 nt_name
->Buffer
= NULL
;
2931 if (!contains_path( libname
))
2933 WCHAR
*fullname
= NULL
;
2935 status
= find_actctx_dll( libname
, &fullname
);
2936 if (status
== STATUS_SUCCESS
)
2938 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2939 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2940 libname
= dllname
= fullname
;
2944 if (status
!= STATUS_SXS_KEY_NOT_FOUND
) goto done
;
2945 if ((*pwm
= find_basename_module( libname
)) != NULL
)
2947 status
= STATUS_SUCCESS
;
2953 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2954 status
= search_dll_file( load_path
, libname
, nt_name
, pwm
, mapping
, image_info
, id
);
2955 else if (!(status
= RtlDosPathNameToNtPathName_U_WithStatus( libname
, nt_name
, NULL
, NULL
)))
2956 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
2958 /* 16-bit files can't be loaded from the prefix */
2959 if (status
&& libname
[0] && libname
[1] && !wcscmp( libname
+ wcslen(libname
) - 2, L
"16" ) && !contains_path( libname
))
2960 status
= find_builtin_without_file( libname
, nt_name
, pwm
, mapping
, image_info
, id
);
2962 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) status
= STATUS_INVALID_IMAGE_FORMAT
;
2965 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2966 if (wow64_old_value
) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value
);
2971 /***********************************************************************
2972 * load_dll (internal)
2974 * Load a PE style module according to the load order.
2975 * The loader_section must be locked while calling this function.
2977 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
2978 DWORD flags
, WINE_MODREF
** pwm
)
2980 UNICODE_STRING nt_name
;
2983 SECTION_IMAGE_INFORMATION image_info
;
2987 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2989 nts
= find_dll_file( load_path
, libname
, default_ext
, &nt_name
, pwm
, &mapping
, &image_info
, &id
);
2991 if (*pwm
) /* found already loaded module */
2993 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2995 TRACE("Found %s for %s at %p, count=%d\n",
2996 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2997 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2998 RtlFreeUnicodeString( &nt_name
);
2999 return STATUS_SUCCESS
;
3002 if (nts
&& nts
!= STATUS_INVALID_IMAGE_NOT_MZ
) goto done
;
3004 if (NtCurrentTeb64())
3006 prev
= NtCurrentTeb64()->Tib
.ArbitraryUserPointer
;
3007 NtCurrentTeb64()->Tib
.ArbitraryUserPointer
= (ULONG_PTR
)(nt_name
.Buffer
+ 4);
3011 prev
= (ULONG_PTR
)NtCurrentTeb()->Tib
.ArbitraryUserPointer
;
3012 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= nt_name
.Buffer
+ 4;
3017 case STATUS_INVALID_IMAGE_NOT_MZ
: /* not in PE format, maybe it's a .so file */
3018 nts
= load_so_dll( load_path
, &nt_name
, flags
, pwm
);
3021 case STATUS_SUCCESS
: /* valid PE file */
3022 nts
= load_native_dll( load_path
, &nt_name
, mapping
, &image_info
, &id
, flags
, pwm
);
3026 if (NtCurrentTeb64())
3027 NtCurrentTeb64()->Tib
.ArbitraryUserPointer
= prev
;
3029 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= (void *)(ULONG_PTR
)prev
;
3032 if (nts
== STATUS_SUCCESS
)
3033 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name
), (*pwm
)->ldr
.DllBase
);
3035 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
3037 if (mapping
) NtClose( mapping
);
3038 RtlFreeUnicodeString( &nt_name
);
3043 /***********************************************************************
3044 * __wine_init_unix_lib
3046 NTSTATUS __cdecl
__wine_init_unix_lib( HMODULE module
, DWORD reason
, const void *ptr_in
, void *ptr_out
)
3051 RtlEnterCriticalSection( &loader_section
);
3053 if ((wm
= get_modref( module
))) ret
= unix_funcs
->init_unix_lib( module
, reason
, ptr_in
, ptr_out
);
3054 else ret
= STATUS_INVALID_HANDLE
;
3056 RtlLeaveCriticalSection( &loader_section
);
3061 /***********************************************************************
3062 * __wine_ctrl_routine
3064 NTSTATUS WINAPI
__wine_ctrl_routine( void *arg
)
3068 if (pCtrlRoutine
&& NtCurrentTeb()->Peb
->ProcessParameters
->ConsoleHandle
) ret
= pCtrlRoutine( arg
);
3069 RtlExitUserThread( ret
);
3072 /******************************************************************
3073 * LdrLoadDll (NTDLL.@)
3075 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
3076 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
3081 RtlEnterCriticalSection( &loader_section
);
3083 nts
= load_dll( path_name
, libname
->Buffer
, L
".dll", flags
, &wm
);
3085 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
3087 nts
= process_attach( wm
->ldr
.DdagNode
, NULL
);
3088 if (nts
!= STATUS_SUCCESS
)
3090 LdrUnloadDll(wm
->ldr
.DllBase
);
3094 *hModule
= (wm
) ? wm
->ldr
.DllBase
: NULL
;
3096 RtlLeaveCriticalSection( &loader_section
);
3101 /******************************************************************
3102 * LdrGetDllFullName (NTDLL.@)
3104 NTSTATUS WINAPI
LdrGetDllFullName( HMODULE module
, UNICODE_STRING
*name
)
3109 TRACE( "module %p, name %p.\n", module
, name
);
3111 if (!module
) module
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
3113 RtlEnterCriticalSection( &loader_section
);
3114 wm
= get_modref( module
);
3117 RtlCopyUnicodeString( name
, &wm
->ldr
.FullDllName
);
3118 if (name
->MaximumLength
< wm
->ldr
.FullDllName
.Length
+ sizeof(WCHAR
)) status
= STATUS_BUFFER_TOO_SMALL
;
3119 else status
= STATUS_SUCCESS
;
3120 } else status
= STATUS_DLL_NOT_FOUND
;
3121 RtlLeaveCriticalSection( &loader_section
);
3127 /******************************************************************
3128 * LdrGetDllHandleEx (NTDLL.@)
3130 NTSTATUS WINAPI
LdrGetDllHandleEx( ULONG flags
, LPCWSTR load_path
, ULONG
*dll_characteristics
,
3131 const UNICODE_STRING
*name
, HMODULE
*base
)
3133 static const ULONG supported_flags
= LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
3134 | LDR_GET_DLL_HANDLE_EX_FLAG_PIN
;
3135 static const ULONG valid_flags
= LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
3136 | LDR_GET_DLL_HANDLE_EX_FLAG_PIN
| 4;
3137 SECTION_IMAGE_INFORMATION image_info
;
3138 UNICODE_STRING nt_name
;
3144 TRACE( "flag %#x, load_path %p, dll_characteristics %p, name %p, base %p.\n",
3145 flags
, load_path
, dll_characteristics
, name
, base
);
3147 if (flags
& ~valid_flags
) return STATUS_INVALID_PARAMETER
;
3149 if ((flags
& (LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
| LDR_GET_DLL_HANDLE_EX_FLAG_PIN
))
3150 == (LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
| LDR_GET_DLL_HANDLE_EX_FLAG_PIN
))
3151 return STATUS_INVALID_PARAMETER
;
3153 if (flags
& ~supported_flags
) FIXME( "Unsupported flags %#x.\n", flags
);
3154 if (dll_characteristics
) FIXME( "dll_characteristics unsupported.\n" );
3156 RtlEnterCriticalSection( &loader_section
);
3158 status
= find_dll_file( load_path
, name
->Buffer
, L
".dll", &nt_name
, &wm
, &mapping
, &image_info
, &id
);
3160 if (wm
) *base
= wm
->ldr
.DllBase
;
3163 if (status
== STATUS_SUCCESS
) NtClose( mapping
);
3164 status
= STATUS_DLL_NOT_FOUND
;
3166 RtlFreeUnicodeString( &nt_name
);
3170 if (flags
& LDR_GET_DLL_HANDLE_EX_FLAG_PIN
)
3171 LdrAddRefDll( LDR_ADDREF_DLL_PIN
, *base
);
3172 else if (!(flags
& LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
))
3173 LdrAddRefDll( 0, *base
);
3176 RtlLeaveCriticalSection( &loader_section
);
3177 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
3182 /******************************************************************
3183 * LdrGetDllHandle (NTDLL.@)
3185 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
3187 return LdrGetDllHandleEx( LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
, load_path
, NULL
, name
, base
);
3191 /******************************************************************
3192 * LdrAddRefDll (NTDLL.@)
3194 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
3196 NTSTATUS ret
= STATUS_SUCCESS
;
3199 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
3201 RtlEnterCriticalSection( &loader_section
);
3203 if ((wm
= get_modref( module
)))
3205 if (flags
& LDR_ADDREF_DLL_PIN
)
3206 wm
->ldr
.LoadCount
= -1;
3208 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
3209 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3211 else ret
= STATUS_INVALID_PARAMETER
;
3213 RtlLeaveCriticalSection( &loader_section
);
3218 /***********************************************************************
3219 * LdrProcessRelocationBlock (NTDLL.@)
3221 * Apply relocations to a given page of a mapped PE image.
3223 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
3224 USHORT
*relocs
, INT_PTR delta
)
3228 USHORT offset
= *relocs
& 0xfff;
3229 int type
= *relocs
>> 12;
3232 case IMAGE_REL_BASED_ABSOLUTE
:
3234 case IMAGE_REL_BASED_HIGH
:
3235 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
3237 case IMAGE_REL_BASED_LOW
:
3238 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
3240 case IMAGE_REL_BASED_HIGHLOW
:
3241 *(int *)((char *)page
+ offset
) += delta
;
3244 case IMAGE_REL_BASED_DIR64
:
3245 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
3247 #elif defined(__arm__)
3248 case IMAGE_REL_BASED_THUMB_MOV32
:
3250 DWORD
*inst
= (DWORD
*)((char *)page
+ offset
);
3251 WORD lo
= ((inst
[0] << 1) & 0x0800) + ((inst
[0] << 12) & 0xf000) +
3252 ((inst
[0] >> 20) & 0x0700) + ((inst
[0] >> 16) & 0x00ff);
3253 WORD hi
= ((inst
[1] << 1) & 0x0800) + ((inst
[1] << 12) & 0xf000) +
3254 ((inst
[1] >> 20) & 0x0700) + ((inst
[1] >> 16) & 0x00ff);
3255 DWORD imm
= MAKELONG( lo
, hi
) + delta
;
3260 if ((inst
[0] & 0x8000fbf0) != 0x0000f240 || (inst
[1] & 0x8000fbf0) != 0x0000f2c0)
3261 ERR("wrong Thumb2 instruction @%p %08x:%08x, expected MOVW/MOVT\n",
3262 inst
, inst
[0], inst
[1] );
3264 inst
[0] = (inst
[0] & 0x8f00fbf0) + ((lo
>> 1) & 0x0400) + ((lo
>> 12) & 0x000f) +
3265 ((lo
<< 20) & 0x70000000) + ((lo
<< 16) & 0xff0000);
3266 inst
[1] = (inst
[1] & 0x8f00fbf0) + ((hi
>> 1) & 0x0400) + ((hi
>> 12) & 0x000f) +
3267 ((hi
<< 20) & 0x70000000) + ((hi
<< 16) & 0xff0000);
3272 FIXME("Unknown/unsupported fixup type %x.\n", type
);
3277 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
3281 /******************************************************************
3282 * LdrQueryProcessModuleInformation
3285 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(RTL_PROCESS_MODULES
*smi
,
3286 ULONG buf_size
, ULONG
* req_size
)
3288 RTL_PROCESS_MODULE_INFORMATION
*sm
= &smi
->Modules
[0];
3289 ULONG size
= sizeof(ULONG
);
3290 NTSTATUS nts
= STATUS_SUCCESS
;
3293 PLIST_ENTRY mark
, entry
;
3294 LDR_DATA_TABLE_ENTRY
*mod
;
3297 smi
->ModulesCount
= 0;
3299 RtlEnterCriticalSection( &loader_section
);
3300 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3301 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3303 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3304 size
+= sizeof(*sm
);
3305 if (size
<= buf_size
)
3307 sm
->Section
= 0; /* FIXME */
3308 sm
->MappedBaseAddress
= mod
->DllBase
;
3309 sm
->ImageBaseAddress
= mod
->DllBase
;
3310 sm
->ImageSize
= mod
->SizeOfImage
;
3311 sm
->Flags
= mod
->Flags
;
3312 sm
->LoadOrderIndex
= id
++;
3313 sm
->InitOrderIndex
= 0; /* FIXME */
3314 sm
->LoadCount
= mod
->LoadCount
;
3316 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
3317 str
.Buffer
= (char*)sm
->Name
;
3318 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
3319 ptr
= strrchr(str
.Buffer
, '\\');
3320 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
3322 smi
->ModulesCount
++;
3325 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
3327 RtlLeaveCriticalSection( &loader_section
);
3329 if (req_size
) *req_size
= size
;
3335 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
3341 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3343 RtlInitUnicodeString( &str
, name
);
3345 size
= sizeof(buffer
) - sizeof(WCHAR
);
3346 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
3349 if (info
->Type
!= REG_DWORD
)
3351 buffer
[size
/ sizeof(WCHAR
)] = 0;
3352 *value
= wcstoul( (WCHAR
*)info
->Data
, 0, 16 );
3354 else memcpy( value
, info
->Data
, sizeof(*value
) );
3358 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
3359 void *data
, ULONG in_size
, ULONG
*out_size
)
3365 KEY_VALUE_PARTIAL_INFORMATION
*info
;
3366 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
3368 RtlInitUnicodeString( &str
, name
);
3370 size
= info_size
+ in_size
;
3371 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
3372 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3373 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
3374 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
3376 if (out_size
) *out_size
= info
->DataLength
;
3377 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
3379 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
3384 /******************************************************************
3385 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3387 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
3388 void *data
, ULONG in_size
, ULONG
*out_size
)
3390 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
3391 'S','o','f','t','w','a','r','e','\\',
3392 'M','i','c','r','o','s','o','f','t','\\',
3393 'W','i','n','d','o','w','s',' ','N','T','\\',
3394 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3395 'I','m','a','g','e',' ','F','i','l','e',' ',
3396 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3397 WCHAR path
[MAX_PATH
+ ARRAY_SIZE( optionsW
)];
3398 OBJECT_ATTRIBUTES attr
;
3399 UNICODE_STRING name_str
;
3405 attr
.Length
= sizeof(attr
);
3406 attr
.RootDirectory
= 0;
3407 attr
.ObjectName
= &name_str
;
3408 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3409 attr
.SecurityDescriptor
= NULL
;
3410 attr
.SecurityQualityOfService
= NULL
;
3412 p
= key
->Buffer
+ key
->Length
/ sizeof(WCHAR
);
3413 while (p
> key
->Buffer
&& p
[-1] != '\\') p
--;
3414 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
3415 name_str
.Buffer
= path
;
3416 name_str
.Length
= sizeof(optionsW
) + len
;
3417 name_str
.MaximumLength
= name_str
.Length
;
3418 memcpy( path
, optionsW
, sizeof(optionsW
) );
3419 memcpy( path
+ ARRAY_SIZE( optionsW
), p
, len
);
3420 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
3422 if (type
== REG_DWORD
)
3424 if (out_size
) *out_size
= sizeof(ULONG
);
3425 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
3426 else status
= STATUS_BUFFER_OVERFLOW
;
3428 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
3435 /******************************************************************
3436 * RtlDllShutdownInProgress (NTDLL.@)
3438 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
3440 return process_detaching
;
3443 /****************************************************************************
3444 * LdrResolveDelayLoadedAPI (NTDLL.@)
3446 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
3447 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
,
3448 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook
,
3449 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
3451 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
3452 DELAYLOAD_INFO delayinfo
;
3460 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
3462 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
3463 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
3464 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
3465 name
= get_rva(base
, desc
->DllNameRVA
);
3470 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
3472 nts
= STATUS_NO_MEMORY
;
3475 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
3476 RtlFreeUnicodeString(&mod
);
3480 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3481 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
3484 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3487 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
3488 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
3492 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
3497 delayinfo
.Size
= sizeof(delayinfo
);
3498 delayinfo
.DelayloadDescriptor
= desc
;
3499 delayinfo
.ThunkAddress
= addr
;
3500 delayinfo
.TargetDllName
= name
;
3501 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
3502 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
3503 delayinfo
.TargetModuleBase
= *phmod
;
3504 delayinfo
.Unused
= NULL
;
3505 delayinfo
.LastError
= nts
;
3508 return dllhook(4, &delayinfo
);
3510 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3512 DWORD_PTR ord
= LOWORD(pINT
[id
].u1
.Ordinal
);
3513 return syshook(name
, (const char *)ord
);
3517 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3518 return syshook(name
, (const char *)iibn
->Name
);
3522 /******************************************************************
3523 * LdrShutdownProcess (NTDLL.@)
3526 void WINAPI
LdrShutdownProcess(void)
3528 BOOL detaching
= process_detaching
;
3532 process_detaching
= TRUE
;
3534 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3540 /******************************************************************
3541 * RtlExitUserProcess (NTDLL.@)
3543 void WINAPI
RtlExitUserProcess( DWORD status
)
3545 RtlEnterCriticalSection( &loader_section
);
3546 RtlAcquirePebLock();
3547 NtTerminateProcess( 0, status
);
3548 LdrShutdownProcess();
3549 for (;;) NtTerminateProcess( GetCurrentProcess(), status
);
3552 /******************************************************************
3553 * LdrShutdownThread (NTDLL.@)
3556 void WINAPI
LdrShutdownThread(void)
3558 PLIST_ENTRY mark
, entry
;
3559 LDR_DATA_TABLE_ENTRY
*mod
;
3566 /* don't do any detach calls if process is exiting */
3567 if (process_detaching
) return;
3569 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3571 RtlEnterCriticalSection( &loader_section
);
3572 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3574 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3575 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
3577 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
3578 InInitializationOrderLinks
);
3579 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
3581 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
3584 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
3585 DLL_THREAD_DETACH
, NULL
);
3588 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_DETACH
);
3590 RtlAcquirePebLock();
3591 if (NtCurrentTeb()->TlsLinks
.Flink
) RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
3592 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
3594 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
3595 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
3597 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 2 );
3598 NtCurrentTeb()->FlsSlots
= NULL
;
3599 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
3600 NtCurrentTeb()->TlsExpansionSlots
= NULL
;
3601 RtlReleasePebLock();
3603 RtlLeaveCriticalSection( &loader_section
);
3604 /* don't call DbgUiGetThreadDebugObject as some apps hook it and terminate if called */
3605 if (NtCurrentTeb()->DbgSsReserved
[1]) NtClose( NtCurrentTeb()->DbgSsReserved
[1] );
3606 RtlFreeThreadActivationContextStack();
3610 /***********************************************************************
3614 static void free_modref( WINE_MODREF
*wm
)
3616 SINGLE_LIST_ENTRY
*entry
;
3617 LDR_DEPENDENCY
*dep
;
3619 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
3620 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
3621 if (wm
->ldr
.InInitializationOrderLinks
.Flink
)
3622 RemoveEntryList(&wm
->ldr
.InInitializationOrderLinks
);
3624 while ((entry
= wm
->ldr
.DdagNode
->Dependencies
.Tail
))
3626 dep
= CONTAINING_RECORD( entry
, LDR_DEPENDENCY
, dependency_to_entry
);
3627 assert( dep
->dependency_from
== wm
->ldr
.DdagNode
);
3628 remove_module_dependency( dep
);
3631 while ((entry
= wm
->ldr
.DdagNode
->IncomingDependencies
.Tail
))
3633 dep
= CONTAINING_RECORD( entry
, LDR_DEPENDENCY
, dependency_from_entry
);
3634 assert( dep
->dependency_to
== wm
->ldr
.DdagNode
);
3635 remove_module_dependency( dep
);
3638 RemoveEntryList(&wm
->ldr
.NodeModuleLink
);
3639 if (IsListEmpty(&wm
->ldr
.DdagNode
->Modules
))
3640 RtlFreeHeap( GetProcessHeap(), 0, wm
->ldr
.DdagNode
);
3642 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
3643 if (!TRACE_ON(module
))
3644 TRACE_(loaddll
)("Unloaded module %s : %s\n",
3645 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
3646 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
3648 free_tls_slot( &wm
->ldr
);
3649 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
3650 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.DllBase
);
3651 if (cached_modref
== wm
) cached_modref
= NULL
;
3652 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
3653 RtlFreeHeap( GetProcessHeap(), 0, wm
);
3656 /***********************************************************************
3657 * MODULE_FlushModrefs
3659 * Remove all unused modrefs and call the internal unloading routines
3660 * for the library type.
3662 * The loader_section must be locked while calling this function.
3664 static void MODULE_FlushModrefs(void)
3666 PLIST_ENTRY mark
, entry
, prev
;
3667 LDR_DATA_TABLE_ENTRY
*mod
;
3670 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3671 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3673 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
3674 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3675 prev
= entry
->Blink
;
3676 if (!mod
->LoadCount
) free_modref( wm
);
3679 /* check load order list too for modules that haven't been initialized yet */
3680 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3681 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3683 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3684 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3685 prev
= entry
->Blink
;
3686 if (!mod
->LoadCount
) free_modref( wm
);
3690 /***********************************************************************
3691 * MODULE_DecRefCount
3693 * The loader_section must be locked while calling this function.
3695 static NTSTATUS
MODULE_DecRefCount( LDR_DDAG_NODE
*node
, void *context
)
3697 LDR_DATA_TABLE_ENTRY
*mod
;
3700 mod
= CONTAINING_RECORD( node
->Modules
.Flink
, LDR_DATA_TABLE_ENTRY
, NodeModuleLink
);
3701 wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
3703 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
3704 return STATUS_SUCCESS
;
3706 if ( wm
->ldr
.LoadCount
<= 0 )
3707 return STATUS_SUCCESS
;
3709 --wm
->ldr
.LoadCount
;
3710 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3712 if ( wm
->ldr
.LoadCount
== 0 )
3714 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
3715 walk_node_dependencies( node
, context
, MODULE_DecRefCount
);
3716 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
3717 module_push_unload_trace( wm
);
3719 return STATUS_SUCCESS
;
3722 /******************************************************************
3723 * LdrUnloadDll (NTDLL.@)
3727 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
3730 NTSTATUS retv
= STATUS_SUCCESS
;
3732 if (process_detaching
) return retv
;
3734 TRACE("(%p)\n", hModule
);
3736 RtlEnterCriticalSection( &loader_section
);
3739 if ((wm
= get_modref( hModule
)) != NULL
)
3741 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
3743 /* Recursively decrement reference counts */
3744 MODULE_DecRefCount( wm
->ldr
.DdagNode
, NULL
);
3746 /* Call process detach notifications */
3747 if ( free_lib_count
<= 1 )
3750 MODULE_FlushModrefs();
3756 retv
= STATUS_DLL_NOT_FOUND
;
3760 RtlLeaveCriticalSection( &loader_section
);
3765 /***********************************************************************
3766 * RtlImageNtHeader (NTDLL.@)
3768 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
3770 IMAGE_NT_HEADERS
*ret
;
3774 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
3777 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
3779 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
3780 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
3791 /***********************************************************************
3792 * process_breakpoint
3794 * Trigger a debug breakpoint if the process is being debugged.
3796 static void process_breakpoint(void)
3800 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort
, &port
, sizeof(port
), NULL
);
3815 /***********************************************************************
3816 * load_global_options
3818 static void load_global_options(void)
3820 OBJECT_ATTRIBUTES attr
;
3821 UNICODE_STRING name_str
, val_str
;
3824 RtlInitUnicodeString( &name_str
, L
"WINEBOOTSTRAPMODE" );
3825 val_str
.MaximumLength
= 0;
3826 is_prefix_bootstrap
= RtlQueryEnvironmentVariable_U( NULL
, &name_str
, &val_str
) != STATUS_VARIABLE_NOT_FOUND
;
3828 attr
.Length
= sizeof(attr
);
3829 attr
.RootDirectory
= 0;
3830 attr
.ObjectName
= &name_str
;
3831 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3832 attr
.SecurityDescriptor
= NULL
;
3833 attr
.SecurityQualityOfService
= NULL
;
3834 RtlInitUnicodeString( &name_str
, L
"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3836 if (!NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))
3838 query_dword_option( hkey
, L
"SafeProcessSearchMode", &path_safe_mode
);
3839 query_dword_option( hkey
, L
"SafeDllSearchMode", &dll_safe_mode
);
3848 static void (WINAPI
*pWow64LdrpInitialize
)( CONTEXT
*ctx
);
3850 static void init_wow64( CONTEXT
*context
)
3852 if (!imports_fixup_done
)
3857 static const WCHAR wow64_path
[] = L
"C:\\windows\\system32\\wow64.dll";
3859 if ((status
= load_dll( NULL
, wow64_path
, NULL
, 0, &wm
)))
3861 ERR( "could not load %s, status %x\n", debugstr_w(wow64_path
), status
);
3862 NtTerminateProcess( GetCurrentProcess(), status
);
3864 wow64
= wm
->ldr
.DllBase
;
3865 #define GET_PTR(name) \
3866 if (!(p ## name = RtlFindExportedRoutineByName( wow64, #name ))) ERR( "failed to load %s\n", #name )
3868 GET_PTR( Wow64LdrpInitialize
);
3870 imports_fixup_done
= TRUE
;
3873 RtlLeaveCriticalSection( &loader_section
);
3874 pWow64LdrpInitialize( context
);
3880 void *Wow64Transition
= NULL
;
3882 static void map_wow64cpu(void)
3885 OBJECT_ATTRIBUTES attr
;
3886 UNICODE_STRING string
;
3887 HANDLE file
, section
;
3891 RtlInitUnicodeString( &string
, L
"\\??\\C:\\windows\\sysnative\\wow64cpu.dll" );
3892 InitializeObjectAttributes( &attr
, &string
, 0, NULL
, NULL
);
3893 if ((status
= NtOpenFile( &file
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
,
3894 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
3896 WARN("failed to open wow64cpu, status %#x\n", status
);
3899 if (!NtCreateSection( §ion
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
3900 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
3901 NULL
, NULL
, PAGE_EXECUTE_READ
, SEC_COMMIT
, file
))
3903 NtMapViewOfSection( section
, NtCurrentProcess(), &Wow64Transition
, 0,
3904 0, NULL
, &size
, ViewShare
, 0, PAGE_EXECUTE_READ
);
3910 static void init_wow64( CONTEXT
*context
)
3912 PEB
*peb
= NtCurrentTeb()->Peb
;
3913 PEB64
*peb64
= UlongToPtr( NtCurrentTeb64()->Peb
);
3915 if (Wow64Transition
) return; /* already initialized */
3917 peb64
->OSMajorVersion
= peb
->OSMajorVersion
;
3918 peb64
->OSMinorVersion
= peb
->OSMinorVersion
;
3919 peb64
->OSBuildNumber
= peb
->OSBuildNumber
;
3920 peb64
->OSPlatformId
= peb
->OSPlatformId
;
3922 #define SET_INIT_BLOCK(func) LdrSystemDllInitBlock.p ## func = PtrToUlong( &func )
3923 SET_INIT_BLOCK( KiUserApcDispatcher
);
3924 SET_INIT_BLOCK( KiUserExceptionDispatcher
);
3925 SET_INIT_BLOCK( LdrInitializeThunk
);
3926 SET_INIT_BLOCK( LdrSystemDllInitBlock
);
3927 SET_INIT_BLOCK( RtlUserThreadStart
);
3928 SET_INIT_BLOCK( KiUserCallbackDispatcher
);
3929 /* SET_INIT_BLOCK( RtlpQueryProcessDebugInformationRemote ); */
3930 /* SET_INIT_BLOCK( RtlpFreezeTimeBias ); */
3931 /* LdrSystemDllInitBlock.ntdll_handle */
3932 #undef SET_INIT_BLOCK
3939 /* release some address space once dlls are loaded*/
3940 static void release_address_space(void)
3943 void *addr
= (void *)1;
3946 NtFreeVirtualMemory( GetCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
3950 /******************************************************************
3951 * LdrInitializeThunk (NTDLL.@)
3953 * Attach to all the loaded dlls.
3954 * If this is the first time, perform the full process initialization.
3956 void WINAPI
LdrInitializeThunk( CONTEXT
*context
, ULONG_PTR unknown2
, ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3958 static int attach_done
;
3965 entry
= (void **)&context
->Eax
;
3966 #elif defined(__x86_64__)
3967 entry
= (void **)&context
->Rcx
;
3968 #elif defined(__arm__)
3969 entry
= (void **)&context
->R0
;
3970 #elif defined(__aarch64__)
3971 entry
= (void **)&context
->u
.s
.X0
;
3974 if (process_detaching
) NtTerminateThread( GetCurrentThread(), 0 );
3976 RtlEnterCriticalSection( &loader_section
);
3978 if (!imports_fixup_done
)
3980 ANSI_STRING func_name
;
3981 WINE_MODREF
*kernel32
;
3982 PEB
*peb
= NtCurrentTeb()->Peb
;
3984 peb
->LdrData
= &ldr
;
3985 peb
->FastPebLock
= &peb_lock
;
3986 peb
->TlsBitmap
= &tls_bitmap
;
3987 peb
->TlsExpansionBitmap
= &tls_expansion_bitmap
;
3988 peb
->LoaderLock
= &loader_section
;
3989 peb
->ProcessHeap
= RtlCreateHeap( HEAP_GROWABLE
, NULL
, 0, 0, NULL
, NULL
);
3991 RtlInitializeBitMap( &tls_bitmap
, peb
->TlsBitmapBits
, sizeof(peb
->TlsBitmapBits
) * 8 );
3992 RtlInitializeBitMap( &tls_expansion_bitmap
, peb
->TlsExpansionBitmapBits
,
3993 sizeof(peb
->TlsExpansionBitmapBits
) * 8 );
3994 RtlSetBits( peb
->TlsBitmap
, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
3996 init_user_process_params();
3997 load_global_options();
4000 wm
= build_main_module();
4001 wm
->ldr
.LoadCount
= -1;
4003 build_ntdll_module();
4005 if (NtCurrentTeb()->WowTebOffset
) init_wow64( context
);
4007 if ((status
= load_dll( NULL
, L
"kernel32.dll", NULL
, 0, &kernel32
)) != STATUS_SUCCESS
)
4009 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
4010 NtTerminateProcess( GetCurrentProcess(), status
);
4012 kernel32_handle
= kernel32
->ldr
.DllBase
;
4013 node_kernel32
= kernel32
->ldr
.DdagNode
;
4014 RtlInitAnsiString( &func_name
, "BaseThreadInitThunk" );
4015 if ((status
= LdrGetProcedureAddress( kernel32_handle
, &func_name
,
4016 0, (void **)&pBaseThreadInitThunk
)) != STATUS_SUCCESS
)
4018 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status
);
4019 NtTerminateProcess( GetCurrentProcess(), status
);
4021 RtlInitAnsiString( &func_name
, "CtrlRoutine" );
4022 LdrGetProcedureAddress( kernel32_handle
, &func_name
, 0, (void **)&pCtrlRoutine
);
4025 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
4026 status
= fixup_imports_ilonly( wm
, NULL
, entry
);
4028 status
= fixup_imports( wm
, NULL
);
4032 ERR( "Importing dlls for %s failed, status %x\n",
4033 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4034 NtTerminateProcess( GetCurrentProcess(), status
);
4036 imports_fixup_done
= TRUE
;
4038 else wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
4041 if (NtCurrentTeb()->WowTebOffset
) init_wow64( context
);
4044 RtlAcquirePebLock();
4045 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
4046 RtlReleasePebLock();
4048 NtCurrentTeb()->FlsSlots
= fls_alloc_data();
4050 if (!attach_done
) /* first time around */
4053 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
4055 ERR( "TLS init failed when loading %s, status %x\n",
4056 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4057 NtTerminateProcess( GetCurrentProcess(), status
);
4059 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
; /* don't try to attach again */
4060 if (wm
->ldr
.ActivationContext
)
4061 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
4063 if ((status
= process_attach( node_ntdll
, context
))
4064 || (status
= process_attach( node_kernel32
, context
)))
4066 ERR( "Initializing system dll for %s failed, status %x\n",
4067 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4068 NtTerminateProcess( GetCurrentProcess(), status
);
4071 if ((status
= walk_node_dependencies( wm
->ldr
.DdagNode
, context
, process_attach
)))
4073 if (last_failed_modref
)
4074 ERR( "%s failed to initialize, aborting\n",
4075 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
4076 ERR( "Initializing dlls for %s failed, status %x\n",
4077 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4078 NtTerminateProcess( GetCurrentProcess(), status
);
4080 release_address_space();
4081 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_PROCESS_ATTACH
);
4082 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) unix_funcs
->init_builtin_dll( wm
->ldr
.DllBase
);
4083 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
4084 process_breakpoint();
4088 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
4089 NtTerminateThread( GetCurrentThread(), status
);
4091 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_ATTACH
);
4094 RtlLeaveCriticalSection( &loader_section
);
4095 signal_start_thread( context
);
4099 /***********************************************************************
4100 * RtlImageDirectoryEntryToData (NTDLL.@)
4102 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
4104 const IMAGE_NT_HEADERS
*nt
;
4107 if ((ULONG_PTR
)module
& 1) image
= FALSE
; /* mapped as data file */
4108 module
= (HMODULE
)((ULONG_PTR
)module
& ~3);
4109 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
4110 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
4112 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
4114 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
4115 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
4116 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
4117 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
4119 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
4121 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
4123 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
4124 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
4125 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
4126 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
4130 /* not mapped as image, need to find the section containing the virtual address */
4131 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
4135 /***********************************************************************
4136 * RtlImageRvaToSection (NTDLL.@)
4138 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
4139 HMODULE module
, DWORD rva
)
4142 const IMAGE_SECTION_HEADER
*sec
;
4144 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
4145 nt
->FileHeader
.SizeOfOptionalHeader
);
4146 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
4148 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
4149 return (PIMAGE_SECTION_HEADER
)sec
;
4155 /***********************************************************************
4156 * RtlImageRvaToVa (NTDLL.@)
4158 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
4159 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
4161 IMAGE_SECTION_HEADER
*sec
;
4163 if (section
&& *section
) /* try this section first */
4166 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
4169 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
4171 if (section
) *section
= sec
;
4172 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
4176 /***********************************************************************
4177 * RtlPcToFileHeader (NTDLL.@)
4179 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
4181 LDR_DATA_TABLE_ENTRY
*module
;
4184 RtlEnterCriticalSection( &loader_section
);
4185 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->DllBase
;
4186 RtlLeaveCriticalSection( &loader_section
);
4192 /****************************************************************************
4193 * LdrGetDllDirectory (NTDLL.@)
4195 NTSTATUS WINAPI
LdrGetDllDirectory( UNICODE_STRING
*dir
)
4197 NTSTATUS status
= STATUS_SUCCESS
;
4199 RtlEnterCriticalSection( &dlldir_section
);
4200 dir
->Length
= dll_directory
.Length
+ sizeof(WCHAR
);
4201 if (dir
->MaximumLength
>= dir
->Length
) RtlCopyUnicodeString( dir
, &dll_directory
);
4204 status
= STATUS_BUFFER_TOO_SMALL
;
4205 if (dir
->MaximumLength
) dir
->Buffer
[0] = 0;
4207 RtlLeaveCriticalSection( &dlldir_section
);
4212 /****************************************************************************
4213 * LdrSetDllDirectory (NTDLL.@)
4215 NTSTATUS WINAPI
LdrSetDllDirectory( const UNICODE_STRING
*dir
)
4217 NTSTATUS status
= STATUS_SUCCESS
;
4220 if (!dir
->Buffer
) RtlInitUnicodeString( &new, NULL
);
4221 else if ((status
= RtlDuplicateUnicodeString( 1, dir
, &new ))) return status
;
4223 RtlEnterCriticalSection( &dlldir_section
);
4224 RtlFreeUnicodeString( &dll_directory
);
4225 dll_directory
= new;
4226 RtlLeaveCriticalSection( &dlldir_section
);
4231 /****************************************************************************
4232 * LdrAddDllDirectory (NTDLL.@)
4234 NTSTATUS WINAPI
LdrAddDllDirectory( const UNICODE_STRING
*dir
, void **cookie
)
4236 FILE_BASIC_INFORMATION info
;
4237 UNICODE_STRING nt_name
;
4239 OBJECT_ATTRIBUTES attr
;
4241 struct dll_dir_entry
*ptr
;
4242 DOS_PATHNAME_TYPE type
= RtlDetermineDosPathNameType_U( dir
->Buffer
);
4244 if (type
!= ABSOLUTE_PATH
&& type
!= ABSOLUTE_DRIVE_PATH
)
4245 return STATUS_INVALID_PARAMETER
;
4247 status
= RtlDosPathNameToNtPathName_U_WithStatus( dir
->Buffer
, &nt_name
, NULL
, NULL
);
4248 if (status
) return status
;
4249 len
= nt_name
.Length
/ sizeof(WCHAR
);
4250 if (!(ptr
= RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry
, dir
[++len
] ))))
4251 return STATUS_NO_MEMORY
;
4252 memcpy( ptr
->dir
, nt_name
.Buffer
, len
* sizeof(WCHAR
) );
4254 attr
.Length
= sizeof(attr
);
4255 attr
.RootDirectory
= 0;
4256 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
4257 attr
.ObjectName
= &nt_name
;
4258 attr
.SecurityDescriptor
= NULL
;
4259 attr
.SecurityQualityOfService
= NULL
;
4260 status
= NtQueryAttributesFile( &attr
, &info
);
4261 RtlFreeUnicodeString( &nt_name
);
4265 TRACE( "%s\n", debugstr_w( ptr
->dir
));
4266 RtlEnterCriticalSection( &dlldir_section
);
4267 list_add_head( &dll_dir_list
, &ptr
->entry
);
4268 RtlLeaveCriticalSection( &dlldir_section
);
4271 else RtlFreeHeap( GetProcessHeap(), 0, ptr
);
4276 /****************************************************************************
4277 * LdrRemoveDllDirectory (NTDLL.@)
4279 NTSTATUS WINAPI
LdrRemoveDllDirectory( void *cookie
)
4281 struct dll_dir_entry
*ptr
= cookie
;
4283 TRACE( "%s\n", debugstr_w( ptr
->dir
));
4285 RtlEnterCriticalSection( &dlldir_section
);
4286 list_remove( &ptr
->entry
);
4287 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
4288 RtlLeaveCriticalSection( &dlldir_section
);
4289 return STATUS_SUCCESS
;
4293 /*************************************************************************
4294 * LdrSetDefaultDllDirectories (NTDLL.@)
4296 NTSTATUS WINAPI
LdrSetDefaultDllDirectories( ULONG flags
)
4298 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
4299 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
4300 LOAD_LIBRARY_SEARCH_USER_DIRS
|
4301 LOAD_LIBRARY_SEARCH_SYSTEM32
|
4302 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
4304 if (!flags
|| (flags
& ~load_library_search_flags
)) return STATUS_INVALID_PARAMETER
;
4305 default_search_flags
= flags
;
4306 return STATUS_SUCCESS
;
4310 /******************************************************************
4311 * LdrGetDllPath (NTDLL.@)
4313 NTSTATUS WINAPI
LdrGetDllPath( PCWSTR module
, ULONG flags
, PWSTR
*path
, PWSTR
*unknown
)
4316 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
|
4317 LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
4318 LOAD_LIBRARY_SEARCH_USER_DIRS
|
4319 LOAD_LIBRARY_SEARCH_SYSTEM32
|
4320 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
4322 if (flags
& LOAD_WITH_ALTERED_SEARCH_PATH
)
4324 if (flags
& load_library_search_flags
) return STATUS_INVALID_PARAMETER
;
4325 if (default_search_flags
) flags
|= default_search_flags
| LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
;
4327 else if (!(flags
& load_library_search_flags
)) flags
|= default_search_flags
;
4329 RtlEnterCriticalSection( &dlldir_section
);
4331 if (flags
& load_library_search_flags
)
4333 status
= get_dll_load_path_search_flags( module
, flags
, path
);
4337 const WCHAR
*dlldir
= dll_directory
.Length
? dll_directory
.Buffer
: NULL
;
4338 if (!(flags
& LOAD_WITH_ALTERED_SEARCH_PATH
))
4339 module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
4340 status
= get_dll_load_path( module
, dlldir
, dll_safe_mode
, path
);
4343 RtlLeaveCriticalSection( &dlldir_section
);
4349 /*************************************************************************
4350 * RtlSetSearchPathMode (NTDLL.@)
4352 NTSTATUS WINAPI
RtlSetSearchPathMode( ULONG flags
)
4358 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
:
4361 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE
:
4364 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
| BASE_SEARCH_PATH_PERMANENT
:
4365 InterlockedExchange( (int *)&path_safe_mode
, 2 );
4366 return STATUS_SUCCESS
;
4368 return STATUS_INVALID_PARAMETER
;
4373 int prev
= path_safe_mode
;
4374 if (prev
== 2) break; /* permanently set */
4375 if (InterlockedCompareExchange( (int *)&path_safe_mode
, val
, prev
) == prev
) return STATUS_SUCCESS
;
4377 return STATUS_ACCESS_DENIED
;
4381 /******************************************************************
4382 * RtlGetExePath (NTDLL.@)
4384 NTSTATUS WINAPI
RtlGetExePath( PCWSTR name
, PWSTR
*path
)
4386 const WCHAR
*dlldir
= L
".";
4387 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
4389 /* same check as NeedCurrentDirectoryForExePathW */
4390 if (!wcschr( name
, '\\' ))
4392 UNICODE_STRING name
, value
= { 0 };
4394 RtlInitUnicodeString( &name
, L
"NoDefaultCurrentDirectoryInExePath" );
4395 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) != STATUS_VARIABLE_NOT_FOUND
)
4398 return get_dll_load_path( module
, dlldir
, FALSE
, path
);
4402 /******************************************************************
4403 * RtlGetSearchPath (NTDLL.@)
4405 NTSTATUS WINAPI
RtlGetSearchPath( PWSTR
*path
)
4407 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
4408 return get_dll_load_path( module
, NULL
, path_safe_mode
, path
);
4412 /******************************************************************
4413 * RtlReleasePath (NTDLL.@)
4415 void WINAPI
RtlReleasePath( PWSTR path
)
4417 RtlFreeHeap( GetProcessHeap(), 0, path
);
4421 /******************************************************************
4424 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
4426 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
4431 /***********************************************************************
4432 * __wine_set_unix_funcs
4434 NTSTATUS CDECL
__wine_set_unix_funcs( int version
, const struct unix_funcs
*funcs
)
4436 if (version
!= NTDLL_UNIXLIB_VERSION
) return STATUS_REVISION_MISMATCH
;
4438 return STATUS_SUCCESS
;