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 unixlib_handle_t ntdll_unix_handle
= 0;
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 /* system search path */
87 static const WCHAR system_path
[] = L
"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
89 static BOOL is_prefix_bootstrap
; /* are we bootstrapping the prefix? */
90 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
91 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
92 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
93 static LONG path_safe_mode
; /* path mode set by RtlSetSearchPathMode */
94 static LONG dll_safe_mode
= 1; /* dll search mode */
95 static UNICODE_STRING dll_directory
; /* extra path for LdrSetDllDirectory */
96 static UNICODE_STRING system_dll_path
; /* path to search for system dependency dlls */
97 static DWORD default_search_flags
; /* default flags set by LdrSetDefaultDllDirectories */
98 static WCHAR
*default_load_path
; /* default dll search path */
106 static struct list dll_dir_list
= LIST_INIT( dll_dir_list
); /* extra dirs from LdrAddDllDirectory */
108 struct ldr_notification
111 PLDR_DLL_NOTIFICATION_FUNCTION callback
;
115 static struct list ldr_notifications
= LIST_INIT( ldr_notifications
);
117 static const char * const reason_names
[] =
130 /* internal representation of loaded modules */
131 typedef struct _wine_modref
133 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
, DWORD flags
, WINE_MODREF
** pwm
, BOOL system
);
188 static NTSTATUS
process_attach( LDR_DDAG_NODE
*node
, LPVOID lpReserved
);
189 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
190 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
191 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
192 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
194 /* convert PE image VirtualAddress to Real Address */
195 static inline void *get_rva( HMODULE module
, DWORD va
)
197 return (void *)((char *)module
+ va
);
200 /* check whether the file name contains a path */
201 static inline BOOL
contains_path( LPCWSTR name
)
203 return ((*name
&& (name
[1] == ':')) || wcschr(name
, '/') || wcschr(name
, '\\'));
206 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
208 typedef struct _RTL_UNLOAD_EVENT_TRACE
216 } RTL_UNLOAD_EVENT_TRACE
, *PRTL_UNLOAD_EVENT_TRACE
;
218 static RTL_UNLOAD_EVENT_TRACE unload_traces
[RTL_UNLOAD_EVENT_TRACE_NUMBER
];
219 static RTL_UNLOAD_EVENT_TRACE
*unload_trace_ptr
;
220 static unsigned int unload_trace_seq
;
222 static void module_push_unload_trace( const WINE_MODREF
*wm
)
224 RTL_UNLOAD_EVENT_TRACE
*ptr
= &unload_traces
[unload_trace_seq
];
225 const LDR_DATA_TABLE_ENTRY
*ldr
= &wm
->ldr
;
226 unsigned int len
= min(sizeof(ptr
->ImageName
) - sizeof(WCHAR
), ldr
->BaseDllName
.Length
);
228 ptr
->BaseAddress
= ldr
->DllBase
;
229 ptr
->SizeOfImage
= ldr
->SizeOfImage
;
230 ptr
->Sequence
= unload_trace_seq
;
231 ptr
->TimeDateStamp
= ldr
->TimeDateStamp
;
232 ptr
->CheckSum
= wm
->CheckSum
;
233 memcpy(ptr
->ImageName
, ldr
->BaseDllName
.Buffer
, len
);
234 ptr
->ImageName
[len
/ sizeof(*ptr
->ImageName
)] = 0;
236 unload_trace_seq
= (unload_trace_seq
+ 1) % ARRAY_SIZE(unload_traces
);
237 unload_trace_ptr
= unload_traces
;
240 /*********************************************************************
241 * RtlGetUnloadEventTrace [NTDLL.@]
243 RTL_UNLOAD_EVENT_TRACE
* WINAPI
RtlGetUnloadEventTrace(void)
245 return unload_traces
;
248 /*********************************************************************
249 * RtlGetUnloadEventTraceEx [NTDLL.@]
251 void WINAPI
RtlGetUnloadEventTraceEx(ULONG
**size
, ULONG
**count
, void **trace
)
253 static ULONG element_size
= sizeof(*unload_traces
);
254 static ULONG element_count
= ARRAY_SIZE(unload_traces
);
256 *size
= &element_size
;
257 *count
= &element_count
;
258 *trace
= &unload_trace_ptr
;
261 /*************************************************************************
262 * call_dll_entry_point
264 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
265 * their entry point, so we need a small asm wrapper. Testing indicates
266 * that only modifying esi leads to a crash, so use this one to backup
267 * ebp while running the dll entry proc.
269 #if defined(__i386__)
270 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
271 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
273 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
274 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
276 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
278 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
280 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
282 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
284 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
288 "movl 8(%ebp),%eax\n\t"
291 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
292 "leal -12(%ebp),%esp\n\t"
294 __ASM_CFI(".cfi_same_value %edi\n\t")
296 __ASM_CFI(".cfi_same_value %esi\n\t")
298 __ASM_CFI(".cfi_same_value %ebx\n\t")
300 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
301 __ASM_CFI(".cfi_same_value %ebp\n\t")
303 #elif defined(__x86_64__)
304 extern BOOL CDECL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
305 /* Some apps modify rbx in TLS entry point. */
306 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
308 __ASM_SEH(".seh_pushreg %rbx\n\t")
309 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
310 __ASM_CFI(".cfi_rel_offset %rbx,0\n\t")
312 __ASM_SEH(".seh_stackalloc 48\n\t")
313 __ASM_SEH(".seh_endprologue\n\t")
314 __ASM_CFI(".cfi_adjust_cfa_offset 48\n\t")
321 __ASM_CFI(".cfi_adjust_cfa_offset -48\n\t")
323 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
324 __ASM_CFI(".cfi_same_value %rbx\n\t")
327 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
328 UINT reason
, void *reserved
)
330 return proc( module
, reason
, reserved
);
335 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
336 /*************************************************************************
339 * Entry point for stub functions.
341 static void WINAPI
stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
343 EXCEPTION_RECORD rec
;
345 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
346 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
347 rec
.ExceptionRecord
= NULL
;
348 rec
.ExceptionAddress
= ret_addr
;
349 rec
.NumberParameters
= 2;
350 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
351 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
352 for (;;) RtlRaiseException( &rec
);
356 #include "pshpack1.h"
360 BYTE pushl1
; /* pushl $name */
362 BYTE pushl2
; /* pushl $dll */
364 BYTE call
; /* call stub_entry_point */
367 #elif defined(__arm__)
370 DWORD ldr_r0
; /* ldr r0, $dll */
371 DWORD ldr_r1
; /* ldr r1, $name */
372 DWORD mov_r2_lr
; /* mov r2, lr */
373 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
378 #elif defined(__aarch64__)
381 DWORD ldr_x0
; /* ldr x0, $dll */
382 DWORD ldr_x1
; /* ldr x1, $name */
383 DWORD mov_x2_lr
; /* mov x2, lr */
384 DWORD ldr_x16
; /* ldr x16, $entry */
385 DWORD br_x16
; /* br x16 */
393 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
395 BYTE movq_rsi
[2]; /* movq $name,%rsi */
397 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
398 BYTE movq_rax
[2]; /* movq $entry, %rax */
400 BYTE jmpq_rax
[2]; /* jmp %rax */
405 /*************************************************************************
408 * Allocate a stub entry point.
410 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
412 #define MAX_SIZE 65536
413 static struct stub
*stubs
;
414 static unsigned int nb_stubs
;
417 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
421 SIZE_T size
= MAX_SIZE
;
422 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
423 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
426 stub
= &stubs
[nb_stubs
++];
428 stub
->pushl1
= 0x68; /* pushl $name */
430 stub
->pushl2
= 0x68; /* pushl $dll */
432 stub
->call
= 0xe8; /* call stub_entry_point */
433 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
434 #elif defined(__arm__)
435 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
436 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
437 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
438 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
441 stub
->entry
= stub_entry_point
;
442 #elif defined(__aarch64__)
443 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
444 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
445 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
446 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
447 stub
->br_x16
= 0xd61f0200; /* br x16 */
450 stub
->entry
= stub_entry_point
;
452 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rcx */
453 stub
->movq_rdi
[1] = 0xb9;
455 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rdx */
456 stub
->movq_rsi
[1] = 0xba;
458 stub
->movq_rsp_rdx
[0] = 0x4c; /* movq (%rsp),%r8 */
459 stub
->movq_rsp_rdx
[1] = 0x8b;
460 stub
->movq_rsp_rdx
[2] = 0x04;
461 stub
->movq_rsp_rdx
[3] = 0x24;
462 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
463 stub
->movq_rax
[1] = 0xb8;
464 stub
->entry
= stub_entry_point
;
465 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
466 stub
->jmpq_rax
[1] = 0xe0;
468 return (ULONG_PTR
)stub
;
472 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
473 #endif /* __i386__ */
475 /* call ldr notifications */
476 static void call_ldr_notifications( ULONG reason
, LDR_DATA_TABLE_ENTRY
*module
)
478 struct ldr_notification
*notify
, *notify_next
;
479 LDR_DLL_NOTIFICATION_DATA data
;
481 data
.Loaded
.Flags
= 0;
482 data
.Loaded
.FullDllName
= &module
->FullDllName
;
483 data
.Loaded
.BaseDllName
= &module
->BaseDllName
;
484 data
.Loaded
.DllBase
= module
->DllBase
;
485 data
.Loaded
.SizeOfImage
= module
->SizeOfImage
;
487 LIST_FOR_EACH_ENTRY_SAFE( notify
, notify_next
, &ldr_notifications
, struct ldr_notification
, entry
)
489 TRACE_(relay
)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
490 notify
->callback
, reason
, &data
, notify
->context
);
492 notify
->callback(reason
, &data
, notify
->context
);
494 TRACE_(relay
)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
495 notify
->callback
, reason
, &data
, notify
->context
);
499 /*************************************************************************
502 * Looks for the referenced HMODULE in the current process
503 * The loader_section must be locked while calling this function.
505 static WINE_MODREF
*get_modref( HMODULE hmod
)
507 PLIST_ENTRY mark
, entry
;
508 PLDR_DATA_TABLE_ENTRY mod
;
510 if (cached_modref
&& cached_modref
->ldr
.DllBase
== hmod
) return cached_modref
;
512 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
513 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
515 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
516 if (mod
->DllBase
== hmod
)
517 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
523 /**********************************************************************
524 * find_basename_module
526 * Find a module from its base name.
527 * The loader_section must be locked while calling this function
529 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
531 PLIST_ENTRY mark
, entry
;
532 UNICODE_STRING name_str
;
534 RtlInitUnicodeString( &name_str
, name
);
536 if (cached_modref
&& RtlEqualUnicodeString( &name_str
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
537 return cached_modref
;
539 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
540 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
542 WINE_MODREF
*mod
= CONTAINING_RECORD(entry
, WINE_MODREF
, ldr
.InLoadOrderLinks
);
543 if (RtlEqualUnicodeString( &name_str
, &mod
->ldr
.BaseDllName
, TRUE
) && !mod
->system
)
545 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
546 return cached_modref
;
553 /**********************************************************************
554 * find_fullname_module
556 * Find a module from its full path name.
557 * The loader_section must be locked while calling this function
559 static WINE_MODREF
*find_fullname_module( const UNICODE_STRING
*nt_name
)
561 PLIST_ENTRY mark
, entry
;
562 UNICODE_STRING name
= *nt_name
;
564 if (name
.Length
<= 4 * sizeof(WCHAR
)) return NULL
;
565 name
.Length
-= 4 * sizeof(WCHAR
); /* for \??\ prefix */
568 if (cached_modref
&& RtlEqualUnicodeString( &name
, &cached_modref
->ldr
.FullDllName
, TRUE
))
569 return cached_modref
;
571 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
572 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
574 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
575 if (RtlEqualUnicodeString( &name
, &mod
->FullDllName
, TRUE
))
577 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
578 return cached_modref
;
585 /**********************************************************************
588 * Find a module from its file id.
589 * The loader_section must be locked while calling this function
591 static WINE_MODREF
*find_fileid_module( const struct file_id
*id
)
593 LIST_ENTRY
*mark
, *entry
;
595 if (cached_modref
&& !memcmp( &cached_modref
->id
, id
, sizeof(*id
) )) return cached_modref
;
597 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
598 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
600 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
601 WINE_MODREF
*wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
603 if (!memcmp( &wm
->id
, id
, sizeof(*id
) ))
613 /******************************************************************************
616 static NTSTATUS
get_apiset_entry( const API_SET_NAMESPACE
*map
, const WCHAR
*name
, ULONG len
,
617 const API_SET_NAMESPACE_ENTRY
**entry
)
619 const API_SET_HASH_ENTRY
*hash_entry
;
620 ULONG hash
, i
, hash_len
;
623 if (len
<= 4) return STATUS_INVALID_PARAMETER
;
624 if (wcsnicmp( name
, L
"api-", 4 ) && wcsnicmp( name
, L
"ext-", 4 )) return STATUS_INVALID_PARAMETER
;
625 if (!map
) return STATUS_APISET_NOT_PRESENT
;
627 for (i
= hash_len
= 0; i
< len
; i
++)
629 if (name
[i
] == '.') break;
630 if (name
[i
] == '-') hash_len
= i
;
632 for (i
= hash
= 0; i
< hash_len
; i
++)
633 hash
= hash
* map
->HashFactor
+ ((name
[i
] >= 'A' && name
[i
] <= 'Z') ? name
[i
] + 32 : name
[i
]);
635 hash_entry
= (API_SET_HASH_ENTRY
*)((char *)map
+ map
->HashOffset
);
637 max
= map
->Count
- 1;
640 int pos
= (min
+ max
) / 2;
641 if (hash_entry
[pos
].Hash
< hash
) min
= pos
+ 1;
642 else if (hash_entry
[pos
].Hash
> hash
) max
= pos
- 1;
645 *entry
= (API_SET_NAMESPACE_ENTRY
*)((char *)map
+ map
->EntryOffset
) + hash_entry
[pos
].Index
;
646 if ((*entry
)->HashedLength
!= hash_len
* sizeof(WCHAR
)) break;
647 if (wcsnicmp( (WCHAR
*)((char *)map
+ (*entry
)->NameOffset
), name
, hash_len
)) break;
648 return STATUS_SUCCESS
;
651 return STATUS_APISET_NOT_PRESENT
;
655 /******************************************************************************
658 static NTSTATUS
get_apiset_target( const API_SET_NAMESPACE
*map
, const API_SET_NAMESPACE_ENTRY
*entry
,
659 const WCHAR
*host
, UNICODE_STRING
*ret
)
661 const API_SET_VALUE_ENTRY
*value
= (API_SET_VALUE_ENTRY
*)((char *)map
+ entry
->ValueOffset
);
664 if (!entry
->ValueCount
) return STATUS_DLL_NOT_FOUND
;
667 /* look for specific host in entries 1..n, entry 0 is the default */
668 for (i
= 1; i
< entry
->ValueCount
; i
++)
670 len
= value
[i
].NameLength
/ sizeof(WCHAR
);
671 if (!wcsnicmp( host
, (WCHAR
*)((char *)map
+ value
[i
].NameOffset
), len
) && !host
[len
])
678 if (!value
->ValueOffset
) return STATUS_DLL_NOT_FOUND
;
679 ret
->Buffer
= (WCHAR
*)((char *)map
+ value
->ValueOffset
);
680 ret
->Length
= value
->ValueLength
;
681 return STATUS_SUCCESS
;
685 /**********************************************************************
688 static NTSTATUS
build_import_name( WCHAR buffer
[256], const char *import
, int len
)
690 const API_SET_NAMESPACE
*map
= NtCurrentTeb()->Peb
->ApiSetMap
;
691 const API_SET_NAMESPACE_ENTRY
*entry
;
692 const WCHAR
*host
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
695 while (len
&& import
[len
-1] == ' ') len
--; /* remove trailing spaces */
696 if (len
+ sizeof(".dll") > 256) return STATUS_DLL_NOT_FOUND
;
697 ascii_to_unicode( buffer
, import
, len
);
699 if (!wcschr( buffer
, '.' )) wcscpy( buffer
+ len
, L
".dll" );
701 if (get_apiset_entry( map
, buffer
, wcslen(buffer
), &entry
)) return STATUS_SUCCESS
;
703 if (get_apiset_target( map
, entry
, host
, &str
)) return STATUS_DLL_NOT_FOUND
;
704 if (str
.Length
>= 256 * sizeof(WCHAR
)) return STATUS_DLL_NOT_FOUND
;
706 TRACE( "found %s for %s\n", debugstr_us(&str
), debugstr_w(buffer
));
707 memcpy( buffer
, str
.Buffer
, str
.Length
);
708 buffer
[str
.Length
/ sizeof(WCHAR
)] = 0;
709 return STATUS_SUCCESS
;
713 /**********************************************************************
716 static WCHAR
*append_dll_ext( const WCHAR
*name
)
718 const WCHAR
*ext
= wcsrchr( name
, '.' );
720 if (!ext
|| wcschr( ext
, '/' ) || wcschr( ext
, '\\'))
722 WCHAR
*ret
= RtlAllocateHeap( GetProcessHeap(), 0,
723 wcslen(name
) * sizeof(WCHAR
) + sizeof(L
".dll") );
724 if (!ret
) return NULL
;
726 wcscat( ret
, L
".dll" );
733 /***********************************************************************
734 * is_import_dll_system
736 static BOOL
is_import_dll_system( LDR_DATA_TABLE_ENTRY
*mod
, const IMAGE_IMPORT_DESCRIPTOR
*import
)
738 const char *name
= get_rva( mod
->DllBase
, import
->Name
);
740 return !_stricmp( name
, "ntdll.dll" ) || !_stricmp( name
, "kernel32.dll" );
743 /**********************************************************************
744 * insert_single_list_tail
746 static void insert_single_list_after( LDRP_CSLIST
*list
, SINGLE_LIST_ENTRY
*prev
, SINGLE_LIST_ENTRY
*entry
)
757 /* Insert at head. */
758 entry
->Next
= list
->Tail
->Next
;
759 list
->Tail
->Next
= entry
;
762 entry
->Next
= prev
->Next
;
764 if (prev
== list
->Tail
) list
->Tail
= entry
;
767 /**********************************************************************
768 * remove_single_list_entry
770 static void remove_single_list_entry( LDRP_CSLIST
*list
, SINGLE_LIST_ENTRY
*entry
)
772 SINGLE_LIST_ENTRY
*prev
;
774 assert( list
->Tail
);
776 if (entry
->Next
== entry
)
778 assert( list
->Tail
== entry
);
783 prev
= list
->Tail
->Next
;
784 while (prev
->Next
!= entry
&& prev
!= list
->Tail
)
786 assert( prev
->Next
== entry
);
787 prev
->Next
= entry
->Next
;
788 if (list
->Tail
== entry
) list
->Tail
= prev
;
792 /**********************************************************************
793 * add_module_dependency_after
795 static BOOL
add_module_dependency_after( LDR_DDAG_NODE
*from
, LDR_DDAG_NODE
*to
,
796 SINGLE_LIST_ENTRY
*dep_after
)
800 if (!(dep
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*dep
) ))) return FALSE
;
802 dep
->dependency_from
= from
;
803 insert_single_list_after( &from
->Dependencies
, dep_after
, &dep
->dependency_to_entry
);
804 dep
->dependency_to
= to
;
805 insert_single_list_after( &to
->IncomingDependencies
, NULL
, &dep
->dependency_from_entry
);
810 /**********************************************************************
811 * add_module_dependency
813 static BOOL
add_module_dependency( LDR_DDAG_NODE
*from
, LDR_DDAG_NODE
*to
)
815 return add_module_dependency_after( from
, to
, from
->Dependencies
.Tail
);
818 /**********************************************************************
819 * remove_module_dependency
821 static void remove_module_dependency( LDR_DEPENDENCY
*dep
)
823 remove_single_list_entry( &dep
->dependency_to
->IncomingDependencies
, &dep
->dependency_from_entry
);
824 remove_single_list_entry( &dep
->dependency_from
->Dependencies
, &dep
->dependency_to_entry
);
825 RtlFreeHeap( GetProcessHeap(), 0, dep
);
828 /**********************************************************************
829 * walk_node_dependencies
831 static NTSTATUS
walk_node_dependencies( LDR_DDAG_NODE
*node
, void *context
,
832 NTSTATUS (*callback
)( LDR_DDAG_NODE
*, void * ))
834 SINGLE_LIST_ENTRY
*entry
;
838 if (!(entry
= node
->Dependencies
.Tail
)) return STATUS_SUCCESS
;
843 dep
= CONTAINING_RECORD( entry
, LDR_DEPENDENCY
, dependency_to_entry
);
844 assert( dep
->dependency_from
== node
);
845 if ((status
= callback( dep
->dependency_to
, context
))) break;
846 } while (entry
!= node
->Dependencies
.Tail
);
851 /*************************************************************************
852 * find_forwarded_export
854 * Find the final function pointer for a forwarded function.
855 * The loader_section must be locked while calling this function.
857 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
859 const IMAGE_EXPORT_DIRECTORY
*exports
;
863 const char *end
= strrchr(forward
, '.');
866 if (!end
) return NULL
;
867 if (build_import_name( mod_name
, forward
, end
- forward
)) return NULL
;
869 if (!(wm
= find_basename_module( mod_name
)))
871 WINE_MODREF
*imp
= get_modref( module
);
872 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
873 if (load_dll( load_path
, mod_name
, 0, &wm
, imp
->system
) == STATUS_SUCCESS
&&
874 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
876 if (!imports_fixup_done
&& current_modref
)
878 add_module_dependency( current_modref
->ldr
.DdagNode
, wm
->ldr
.DdagNode
);
880 else if (process_attach( wm
->ldr
.DdagNode
, NULL
) != STATUS_SUCCESS
)
882 LdrUnloadDll( wm
->ldr
.DllBase
);
889 ERR( "module not found for forward '%s' used by %s\n",
890 forward
, debugstr_w(imp
->ldr
.FullDllName
.Buffer
) );
894 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
895 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
897 const char *name
= end
+ 1;
899 if (*name
== '#') { /* ordinal */
900 proc
= find_ordinal_export( wm
->ldr
.DllBase
, exports
, exp_size
,
901 atoi(name
+1) - exports
->Base
, load_path
);
903 proc
= find_named_export( wm
->ldr
.DllBase
, exports
, exp_size
, name
, -1, load_path
);
908 ERR("function not found for forward '%s' used by %s."
909 " If you are using builtin %s, try using the native one instead.\n",
910 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
911 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
917 /*************************************************************************
918 * find_ordinal_export
920 * Find an exported function by ordinal.
921 * The exports base must have been subtracted from the ordinal already.
922 * The loader_section must be locked while calling this function.
924 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
925 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
928 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
930 if (ordinal
>= exports
->NumberOfFunctions
)
932 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
935 if (!functions
[ordinal
]) return NULL
;
937 proc
= get_rva( module
, functions
[ordinal
] );
939 /* if the address falls into the export dir, it's a forward */
940 if (((const char *)proc
>= (const char *)exports
) &&
941 ((const char *)proc
< (const char *)exports
+ exp_size
))
942 return find_forwarded_export( module
, (const char *)proc
, load_path
);
946 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
947 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
951 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
952 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
958 /*************************************************************************
959 * find_name_in_exports
961 * Helper for find_named_export.
963 static int find_name_in_exports( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
, const char *name
)
965 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
966 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
967 int min
= 0, max
= exports
->NumberOfNames
- 1;
971 int res
, pos
= (min
+ max
) / 2;
972 char *ename
= get_rva( module
, names
[pos
] );
973 if (!(res
= strcmp( ename
, name
))) return ordinals
[pos
];
974 if (res
> 0) max
= pos
- 1;
981 /*************************************************************************
984 * Find an exported function by name.
985 * The loader_section must be locked while calling this function.
987 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
988 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
990 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
991 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
994 /* first check the hint */
995 if (hint
>= 0 && hint
< exports
->NumberOfNames
)
997 char *ename
= get_rva( module
, names
[hint
] );
998 if (!strcmp( ename
, name
))
999 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
1002 /* then do a binary search */
1003 if ((ordinal
= find_name_in_exports( module
, exports
, name
)) == -1) return NULL
;
1004 return find_ordinal_export( module
, exports
, exp_size
, ordinal
, load_path
);
1009 /*************************************************************************
1010 * RtlFindExportedRoutineByName
1012 void * WINAPI
RtlFindExportedRoutineByName( HMODULE module
, const char *name
)
1014 const IMAGE_EXPORT_DIRECTORY
*exports
;
1015 const DWORD
*functions
;
1019 exports
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
1020 if (!exports
|| exp_size
< sizeof(*exports
)) return NULL
;
1022 if ((ordinal
= find_name_in_exports( module
, exports
, name
)) == -1) return NULL
;
1023 if (ordinal
>= exports
->NumberOfFunctions
) return NULL
;
1024 functions
= get_rva( module
, exports
->AddressOfFunctions
);
1025 if (!functions
[ordinal
]) return NULL
;
1026 return get_rva( module
, functions
[ordinal
] );
1030 /*************************************************************************
1033 * Import the dll specified by the given import descriptor.
1034 * The loader_section must be locked while calling this function.
1036 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
1038 BOOL system
= current_modref
->system
|| (current_modref
->ldr
.Flags
& LDR_WINE_INTERNAL
);
1042 const IMAGE_EXPORT_DIRECTORY
*exports
;
1044 const IMAGE_THUNK_DATA
*import_list
;
1045 IMAGE_THUNK_DATA
*thunk_list
;
1047 const char *name
= get_rva( module
, descr
->Name
);
1048 DWORD len
= strlen(name
);
1050 SIZE_T protect_size
= 0;
1053 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
1054 if (descr
->u
.OriginalFirstThunk
)
1055 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
1057 import_list
= thunk_list
;
1059 if (!import_list
->u1
.Ordinal
)
1061 WARN( "Skipping unused import %s\n", name
);
1066 status
= build_import_name( buffer
, name
, len
);
1067 if (!status
) status
= load_dll( load_path
, buffer
, 0, &wmImp
, system
);
1071 if (status
== STATUS_DLL_NOT_FOUND
)
1072 ERR("Library %s (which is needed by %s) not found\n",
1073 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
1075 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
1076 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
1080 /* unprotect the import address table since it can be located in
1081 * readonly section */
1082 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
1083 protect_base
= thunk_list
;
1084 protect_size
*= sizeof(*thunk_list
);
1085 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
1086 &protect_size
, PAGE_READWRITE
, &protect_old
);
1088 imp_mod
= wmImp
->ldr
.DllBase
;
1089 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
1093 /* set all imported function to deadbeef */
1094 while (import_list
->u1
.Ordinal
)
1096 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
1098 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
1099 WARN("No implementation for %s.%d", name
, ordinal
);
1100 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
1104 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
1105 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
1106 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
1108 WARN(" imported from %s, allocating stub %p\n",
1109 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
1110 (void *)thunk_list
->u1
.Function
);
1117 while (import_list
->u1
.Ordinal
)
1119 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
1121 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
1123 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
1124 ordinal
- exports
->Base
, load_path
);
1125 if (!thunk_list
->u1
.Function
)
1127 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
1128 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
1129 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
1130 (void *)thunk_list
->u1
.Function
);
1132 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
1134 else /* import by name */
1136 IMAGE_IMPORT_BY_NAME
*pe_name
;
1137 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
1138 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
1139 (const char*)pe_name
->Name
,
1140 pe_name
->Hint
, load_path
);
1141 if (!thunk_list
->u1
.Function
)
1143 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
1144 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
1145 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
1146 (void *)thunk_list
->u1
.Function
);
1148 TRACE_(imports
)("--- %s %s.%d = %p\n",
1149 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
1156 /* restore old protection of the import address table */
1157 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
1163 /***********************************************************************
1164 * create_module_activation_context
1166 static NTSTATUS
create_module_activation_context( LDR_DATA_TABLE_ENTRY
*module
)
1169 LDR_RESOURCE_INFO info
;
1170 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
1172 info
.Type
= RT_MANIFEST
;
1173 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
1175 if (!(status
= LdrFindResource_U( module
->DllBase
, &info
, 3, &entry
)))
1178 ctx
.cbSize
= sizeof(ctx
);
1179 ctx
.lpSource
= NULL
;
1180 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
1181 ctx
.hModule
= module
->DllBase
;
1182 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
1183 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
1189 /*************************************************************************
1190 * is_dll_native_subsystem
1192 * Check if dll is a proper native driver.
1193 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
1194 * while being perfectly normal DLLs. This heuristic should catch such breakages.
1196 static BOOL
is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY
*mod
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
1198 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1201 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
1202 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
1203 if (mod
->Flags
& LDR_WINE_INTERNAL
) return TRUE
;
1205 if ((imports
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
,
1206 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1208 for (i
= 0; imports
[i
].Name
; i
++)
1209 if (is_import_dll_system( mod
, &imports
[i
] ))
1211 TRACE( "%s imports system dll, assuming not native\n", debugstr_w(filename
) );
1218 /*************************************************************************
1221 * Allocate a TLS slot for a newly-loaded module.
1222 * The loader_section must be locked while calling this function.
1224 static SHORT
alloc_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
1226 const IMAGE_TLS_DIRECTORY
*dir
;
1231 if (!(dir
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
1234 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1235 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
1237 for (i
= 0; i
< tls_module_count
; i
++)
1239 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
1240 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
1244 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->DllBase
,
1245 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
1246 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
1248 if (i
== tls_module_count
)
1250 UINT new_count
= max( 32, tls_module_count
* 2 );
1253 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
1255 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
1256 new_count
* sizeof(*tls_dirs
) );
1257 if (!new_ptr
) return -1;
1259 /* resize the pointer block in all running threads */
1260 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1262 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
1263 void **old
= teb
->ThreadLocalStoragePointer
;
1264 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
1266 if (!new) return -1;
1267 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
1268 teb
->ThreadLocalStoragePointer
= new;
1269 #ifdef __x86_64__ /* macOS-specific hack */
1270 if (teb
->Reserved5
[0]) ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
1272 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
1273 /* FIXME: can't free old block here, should be freed at thread exit */
1277 tls_module_count
= new_count
;
1280 /* allocate the data block in all running threads */
1281 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1283 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
1285 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
1286 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
1287 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
1289 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1290 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
1292 RtlFreeHeap( GetProcessHeap(), 0,
1293 InterlockedExchangePointer( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
1296 *(DWORD
*)dir
->AddressOfIndex
= i
;
1302 /*************************************************************************
1305 * Free the module TLS slot on unload.
1306 * The loader_section must be locked while calling this function.
1308 static void free_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
1310 ULONG i
= (USHORT
)mod
->TlsIndex
;
1312 if (mod
->TlsIndex
== -1) return;
1313 assert( i
< tls_module_count
);
1314 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
1318 /****************************************************************
1319 * fixup_imports_ilonly
1321 * Fixup imports for an IL-only module. All we do is import mscoree.
1322 * The loader_section must be locked while calling this function.
1324 static NTSTATUS
fixup_imports_ilonly( WINE_MODREF
*wm
, LPCWSTR load_path
, void **entry
)
1329 WINE_MODREF
*prev
, *imp
;
1331 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1332 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1334 prev
= current_modref
;
1335 current_modref
= wm
;
1336 assert( !wm
->ldr
.DdagNode
->Dependencies
.Tail
);
1337 if (!(status
= load_dll( load_path
, L
"mscoree.dll", 0, &imp
, FALSE
))
1338 && !add_module_dependency_after( wm
->ldr
.DdagNode
, imp
->ldr
.DdagNode
, NULL
))
1339 status
= STATUS_NO_MEMORY
;
1340 current_modref
= prev
;
1343 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1344 debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1348 TRACE( "loaded mscoree for %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1350 name
= (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) ? "_CorDllMain" : "_CorExeMain";
1351 if (!(proc
= RtlFindExportedRoutineByName( imp
->ldr
.DllBase
, name
))) return STATUS_PROCEDURE_NOT_FOUND
;
1353 return STATUS_SUCCESS
;
1357 /****************************************************************
1360 * Fixup all imports of a given module.
1361 * The loader_section must be locked while calling this function.
1363 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
1365 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1366 SINGLE_LIST_ENTRY
*dep_after
;
1367 WINE_MODREF
*prev
, *imp
;
1373 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1374 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1376 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
1378 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
1379 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1380 return STATUS_SUCCESS
;
1383 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
1385 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
1387 if (!create_module_activation_context( &wm
->ldr
))
1388 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1390 /* load the imported modules. They are automatically
1391 * added to the modref list of the process.
1393 prev
= current_modref
;
1394 current_modref
= wm
;
1395 status
= STATUS_SUCCESS
;
1396 for (i
= 0; i
< nb_imports
; i
++)
1398 dep_after
= wm
->ldr
.DdagNode
->Dependencies
.Tail
;
1399 if (!import_dll( wm
->ldr
.DllBase
, &imports
[i
], load_path
, &imp
))
1402 status
= STATUS_DLL_NOT_FOUND
;
1404 else if (imp
&& !is_import_dll_system( &wm
->ldr
, &imports
[i
] ))
1406 add_module_dependency_after( wm
->ldr
.DdagNode
, imp
->ldr
.DdagNode
, dep_after
);
1409 current_modref
= prev
;
1410 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1415 /*************************************************************************
1418 * Allocate a WINE_MODREF structure and add it to the process list
1419 * The loader_section must be locked while calling this function.
1421 static WINE_MODREF
*alloc_module( HMODULE hModule
, const UNICODE_STRING
*nt_name
, BOOL builtin
)
1426 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
1428 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) ))) return NULL
;
1430 wm
->ldr
.DllBase
= hModule
;
1431 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
1432 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
| (builtin
? LDR_WINE_INTERNAL
: 0);
1433 wm
->ldr
.TlsIndex
= -1;
1434 wm
->ldr
.LoadCount
= 1;
1435 wm
->CheckSum
= nt
->OptionalHeader
.CheckSum
;
1436 wm
->ldr
.TimeDateStamp
= nt
->FileHeader
.TimeDateStamp
;
1438 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, nt_name
->Length
- 3 * sizeof(WCHAR
) )))
1440 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1444 if (!(wm
->ldr
.DdagNode
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
->ldr
.DdagNode
) )))
1446 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
1447 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1450 InitializeListHead(&wm
->ldr
.DdagNode
->Modules
);
1451 InsertTailList(&wm
->ldr
.DdagNode
->Modules
, &wm
->ldr
.NodeModuleLink
);
1453 memcpy( buffer
, nt_name
->Buffer
+ 4 /* \??\ prefix */, nt_name
->Length
- 4 * sizeof(WCHAR
) );
1454 buffer
[nt_name
->Length
/sizeof(WCHAR
) - 4] = 0;
1455 if ((p
= wcsrchr( buffer
, '\\' ))) p
++;
1457 RtlInitUnicodeString( &wm
->ldr
.FullDllName
, buffer
);
1458 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
1460 if (!is_dll_native_subsystem( &wm
->ldr
, nt
, p
))
1462 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
1463 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
1464 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
1465 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1468 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
1469 &wm
->ldr
.InLoadOrderLinks
);
1470 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
1471 &wm
->ldr
.InMemoryOrderLinks
);
1472 /* wait until init is called for inserting into InInitializationOrderModuleList */
1474 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
1476 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
1477 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1478 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1484 /*************************************************************************
1487 * Allocate the per-thread structure for module TLS storage.
1489 static NTSTATUS
alloc_thread_tls(void)
1494 if (!tls_module_count
) return STATUS_SUCCESS
;
1496 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1497 tls_module_count
* sizeof(*pointers
) )))
1498 return STATUS_NO_MEMORY
;
1500 for (i
= 0; i
< tls_module_count
; i
++)
1502 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1505 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1506 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1508 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1510 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1511 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1512 return STATUS_NO_MEMORY
;
1514 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1515 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1517 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1518 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1520 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1521 #ifdef __x86_64__ /* macOS-specific hack */
1522 if (NtCurrentTeb()->Reserved5
[0])
1523 ((TEB
*)NtCurrentTeb()->Reserved5
[0])->ThreadLocalStoragePointer
= pointers
;
1525 return STATUS_SUCCESS
;
1529 /*************************************************************************
1530 * call_tls_callbacks
1532 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1534 const IMAGE_TLS_DIRECTORY
*dir
;
1535 const PIMAGE_TLS_CALLBACK
*callback
;
1538 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1539 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1541 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1543 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1544 *callback
, module
, reason_names
[reason
] );
1547 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1551 TRACE_(relay
)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1552 GetExceptionCode(), callback
, module
, reason_names
[reason
] );
1556 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1557 *callback
, module
, reason_names
[reason
] );
1561 /*************************************************************************
1564 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1567 NTSTATUS status
= STATUS_SUCCESS
;
1568 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1569 void *module
= wm
->ldr
.DllBase
;
1572 /* Skip calls for modules loaded with special load flags */
1574 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1575 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, reason
);
1576 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
&& reason
== DLL_PROCESS_ATTACH
)
1577 NTDLL_UNIX_CALL( init_builtin_dll
, wm
->ldr
.DllBase
);
1578 if (!entry
) return STATUS_SUCCESS
;
1580 if (TRACE_ON(relay
))
1582 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1583 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1584 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1585 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1586 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1588 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1589 reason_names
[reason
], lpReserved
);
1593 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1595 status
= STATUS_DLL_INIT_FAILED
;
1599 status
= GetExceptionCode();
1600 TRACE_(relay
)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1601 status
, entry
, module
, reason_names
[reason
], lpReserved
);
1605 /* The state of the module list may have changed due to the call
1606 to the dll. We cannot assume that this module has not been
1608 if (TRACE_ON(relay
))
1609 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1610 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1612 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1618 /*************************************************************************
1621 * Send the process attach notification to all DLLs the given module
1622 * depends on (recursively). This is somewhat complicated due to the fact that
1624 * - we have to respect the module dependencies, i.e. modules implicitly
1625 * referenced by another module have to be initialized before the module
1626 * itself can be initialized
1628 * - the initialization routine of a DLL can itself call LoadLibrary,
1629 * thereby introducing a whole new set of dependencies (even involving
1630 * the 'old' modules) at any time during the whole process
1632 * (Note that this routine can be recursively entered not only directly
1633 * from itself, but also via LoadLibrary from one of the called initialization
1636 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1637 * the process *detach* notifications to be sent in the correct order.
1638 * This must not only take into account module dependencies, but also
1639 * 'hidden' dependencies created by modules calling LoadLibrary in their
1640 * attach notification routine.
1642 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1643 * list after the attach notification has returned. This implies that the
1644 * detach notifications are called in the reverse of the sequence the attach
1645 * notifications *returned*.
1647 * The loader_section must be locked while calling this function.
1649 static NTSTATUS
process_attach( LDR_DDAG_NODE
*node
, LPVOID lpReserved
)
1651 NTSTATUS status
= STATUS_SUCCESS
;
1652 LDR_DATA_TABLE_ENTRY
*mod
;
1656 if (process_detaching
) return status
;
1658 mod
= CONTAINING_RECORD( node
->Modules
.Flink
, LDR_DATA_TABLE_ENTRY
, NodeModuleLink
);
1659 wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
1661 /* prevent infinite recursion in case of cyclical dependencies */
1662 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1663 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1666 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1668 /* Tag current MODREF to prevent recursive loop */
1669 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1670 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1671 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1673 /* Recursively attach all DLLs this one depends on */
1674 status
= walk_node_dependencies( node
, lpReserved
, process_attach
);
1676 if (!wm
->ldr
.InInitializationOrderLinks
.Flink
)
1677 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1678 &wm
->ldr
.InInitializationOrderLinks
);
1680 /* Call DLL entry point */
1681 if (status
== STATUS_SUCCESS
)
1683 WINE_MODREF
*prev
= current_modref
;
1684 current_modref
= wm
;
1686 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED
, &wm
->ldr
);
1687 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1688 if (status
== STATUS_SUCCESS
)
1690 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1694 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1695 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, &wm
->ldr
);
1697 /* point to the name so LdrInitializeThunk can print it */
1698 last_failed_modref
= wm
;
1699 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1701 current_modref
= prev
;
1704 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1705 /* Remove recursion flag */
1706 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1708 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1713 /*************************************************************************
1716 * Send DLL process detach notifications. See the comment about calling
1717 * sequence at process_attach.
1719 static void process_detach(void)
1721 PLIST_ENTRY mark
, entry
;
1722 PLDR_DATA_TABLE_ENTRY mod
;
1724 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1727 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1729 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1730 InInitializationOrderLinks
);
1731 /* Check whether to detach this DLL */
1732 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1734 if ( mod
->LoadCount
&& !process_detaching
)
1737 /* Call detach notification */
1738 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1739 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1740 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1741 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, mod
);
1743 /* Restart at head of WINE_MODREF list, as entries might have
1744 been added and/or removed while performing the call ... */
1747 } while (entry
!= mark
);
1750 /*************************************************************************
1753 * Send DLL thread attach notifications. These are sent in the
1754 * reverse sequence of process detach notification.
1755 * The loader_section must be locked while calling this function.
1757 static void thread_attach(void)
1759 PLIST_ENTRY mark
, entry
;
1760 PLDR_DATA_TABLE_ENTRY mod
;
1762 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1763 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1765 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1766 InInitializationOrderLinks
);
1767 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1769 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1772 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1776 /******************************************************************
1777 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1780 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1783 NTSTATUS ret
= STATUS_SUCCESS
;
1785 RtlEnterCriticalSection( &loader_section
);
1787 wm
= get_modref( hModule
);
1788 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1789 ret
= STATUS_DLL_NOT_FOUND
;
1791 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1793 RtlLeaveCriticalSection( &loader_section
);
1798 /******************************************************************
1799 * LdrFindEntryForAddress (NTDLL.@)
1801 * The loader_section must be locked while calling this function
1803 NTSTATUS WINAPI
LdrFindEntryForAddress( const void *addr
, PLDR_DATA_TABLE_ENTRY
*pmod
)
1805 PLIST_ENTRY mark
, entry
;
1806 PLDR_DATA_TABLE_ENTRY mod
;
1808 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1809 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1811 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1812 if (mod
->DllBase
<= addr
&&
1813 (const char *)addr
< (char*)mod
->DllBase
+ mod
->SizeOfImage
)
1816 return STATUS_SUCCESS
;
1819 return STATUS_NO_MORE_ENTRIES
;
1822 /******************************************************************
1823 * LdrEnumerateLoadedModules (NTDLL.@)
1825 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1827 LIST_ENTRY
*mark
, *entry
;
1828 LDR_DATA_TABLE_ENTRY
*mod
;
1829 BOOLEAN stop
= FALSE
;
1831 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1833 if (unknown
|| !callback
)
1834 return STATUS_INVALID_PARAMETER
;
1836 RtlEnterCriticalSection( &loader_section
);
1838 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1839 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1841 mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1842 callback( mod
, context
, &stop
);
1846 RtlLeaveCriticalSection( &loader_section
);
1847 return STATUS_SUCCESS
;
1850 /******************************************************************
1851 * LdrRegisterDllNotification (NTDLL.@)
1853 NTSTATUS WINAPI
LdrRegisterDllNotification(ULONG flags
, PLDR_DLL_NOTIFICATION_FUNCTION callback
,
1854 void *context
, void **cookie
)
1856 struct ldr_notification
*notify
;
1858 TRACE( "(%x, %p, %p, %p)\n", flags
, callback
, context
, cookie
);
1860 if (!callback
|| !cookie
)
1861 return STATUS_INVALID_PARAMETER
;
1864 FIXME( "ignoring flags %x\n", flags
);
1866 notify
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify
) );
1867 if (!notify
) return STATUS_NO_MEMORY
;
1868 notify
->callback
= callback
;
1869 notify
->context
= context
;
1871 RtlEnterCriticalSection( &loader_section
);
1872 list_add_tail( &ldr_notifications
, ¬ify
->entry
);
1873 RtlLeaveCriticalSection( &loader_section
);
1876 return STATUS_SUCCESS
;
1879 /******************************************************************
1880 * LdrUnregisterDllNotification (NTDLL.@)
1882 NTSTATUS WINAPI
LdrUnregisterDllNotification( void *cookie
)
1884 struct ldr_notification
*notify
= cookie
;
1886 TRACE( "(%p)\n", cookie
);
1888 if (!notify
) return STATUS_INVALID_PARAMETER
;
1890 RtlEnterCriticalSection( &loader_section
);
1891 list_remove( ¬ify
->entry
);
1892 RtlLeaveCriticalSection( &loader_section
);
1894 RtlFreeHeap( GetProcessHeap(), 0, notify
);
1895 return STATUS_SUCCESS
;
1898 /******************************************************************
1899 * LdrLockLoaderLock (NTDLL.@)
1901 * Note: some flags are not implemented.
1902 * Flag 0x01 is used to raise exceptions on errors.
1904 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1906 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1908 if (result
) *result
= 0;
1909 if (magic
) *magic
= 0;
1910 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1911 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1912 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1916 if (!RtlTryEnterCriticalSection( &loader_section
))
1919 return STATUS_SUCCESS
;
1925 RtlEnterCriticalSection( &loader_section
);
1926 if (result
) *result
= 1;
1928 *magic
= GetCurrentThreadId();
1929 return STATUS_SUCCESS
;
1933 /******************************************************************
1934 * LdrUnlockLoaderUnlock (NTDLL.@)
1936 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1940 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1941 RtlLeaveCriticalSection( &loader_section
);
1943 return STATUS_SUCCESS
;
1947 /******************************************************************
1948 * LdrGetProcedureAddress (NTDLL.@)
1950 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1951 ULONG ord
, PVOID
*address
)
1953 IMAGE_EXPORT_DIRECTORY
*exports
;
1955 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1957 RtlEnterCriticalSection( &loader_section
);
1959 /* check if the module itself is invalid to return the proper error */
1960 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1961 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1962 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1964 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, NULL
)
1965 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, NULL
);
1969 ret
= STATUS_SUCCESS
;
1973 RtlLeaveCriticalSection( &loader_section
);
1978 /***********************************************************************
1979 * set_security_cookie
1981 * Create a random security cookie for buffer overflow protection. Make
1982 * sure it does not accidentally match the default cookie value.
1984 static void set_security_cookie( void *module
, SIZE_T len
)
1987 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1991 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1992 if (!loadcfg
) return;
1993 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1994 if (!loadcfg
->SecurityCookie
) return;
1995 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1996 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1998 WARN( "security cookie %p outside of image %p-%p\n",
1999 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
2003 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
2004 TRACE( "initializing security cookie %p\n", cookie
);
2006 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
2009 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
2010 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
2011 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
2012 *cookie
= RtlRandom( &seed
);
2013 #ifdef DEFAULT_SECURITY_COOKIE_64
2014 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
2016 *cookie
= RtlRandom( &seed
);
2017 /* fill up, but keep the highest word clear */
2018 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
2026 static NTSTATUS
perform_relocations( void *module
, IMAGE_NT_HEADERS
*nt
, SIZE_T len
)
2029 IMAGE_BASE_RELOCATION
*rel
, *end
;
2030 const IMAGE_DATA_DIRECTORY
*relocs
;
2031 const IMAGE_SECTION_HEADER
*sec
;
2033 ULONG protect_old
[96], i
;
2035 base
= (char *)nt
->OptionalHeader
.ImageBase
;
2036 if (module
== base
) return STATUS_SUCCESS
; /* nothing to do */
2038 /* no relocations are performed on non page-aligned binaries */
2039 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
2040 return STATUS_SUCCESS
;
2042 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
2043 return STATUS_SUCCESS
;
2045 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
2047 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
2049 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
2051 return STATUS_CONFLICTING_ADDRESSES
;
2054 if (!relocs
->Size
) return STATUS_SUCCESS
;
2055 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
2057 if (nt
->FileHeader
.NumberOfSections
> ARRAY_SIZE( protect_old
))
2058 return STATUS_INVALID_IMAGE_FORMAT
;
2060 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
2061 nt
->FileHeader
.SizeOfOptionalHeader
);
2062 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
2064 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
2065 SIZE_T size
= sec
[i
].SizeOfRawData
;
2066 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
2067 &size
, PAGE_READWRITE
, &protect_old
[i
] );
2070 TRACE( "relocating from %p-%p to %p-%p\n",
2071 base
, base
+ len
, module
, (char *)module
+ len
);
2073 rel
= get_rva( module
, relocs
->VirtualAddress
);
2074 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
2075 delta
= (char *)module
- base
;
2077 while (rel
< end
- 1 && rel
->SizeOfBlock
)
2079 if (rel
->VirtualAddress
>= len
)
2081 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
2082 return STATUS_ACCESS_VIOLATION
;
2084 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
2085 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
2086 (USHORT
*)(rel
+ 1), delta
);
2087 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
2090 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
2092 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
2093 SIZE_T size
= sec
[i
].SizeOfRawData
;
2094 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
2095 &size
, protect_old
[i
], &protect_old
[i
] );
2098 return STATUS_SUCCESS
;
2102 /*************************************************************************
2105 * Build the module data for a mapped dll.
2107 static NTSTATUS
build_module( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, void **module
,
2108 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
2109 DWORD flags
, BOOL system
, WINE_MODREF
**pwm
)
2111 static const char builtin_signature
[] = "Wine builtin DLL";
2112 char *signature
= (char *)((IMAGE_DOS_HEADER
*)*module
+ 1);
2114 IMAGE_NT_HEADERS
*nt
;
2119 if (!(nt
= RtlImageNtHeader( *module
))) return STATUS_INVALID_IMAGE_FORMAT
;
2121 map_size
= (nt
->OptionalHeader
.SizeOfImage
+ page_size
- 1) & ~(page_size
- 1);
2122 if ((status
= perform_relocations( *module
, nt
, map_size
))) return status
;
2124 is_builtin
= ((char *)nt
- signature
>= sizeof(builtin_signature
) &&
2125 !memcmp( signature
, builtin_signature
, sizeof(builtin_signature
) ));
2127 /* create the MODREF */
2129 if (!(wm
= alloc_module( *module
, nt_name
, is_builtin
))) return STATUS_NO_MEMORY
;
2131 if (id
) wm
->id
= *id
;
2132 if (image_info
->LoaderFlags
) wm
->ldr
.Flags
|= LDR_COR_IMAGE
;
2133 if (image_info
->u
.s
.ComPlusILOnly
) wm
->ldr
.Flags
|= LDR_COR_ILONLY
;
2134 wm
->system
= system
;
2136 set_security_cookie( *module
, map_size
);
2140 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
2141 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
2142 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
2144 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
2145 status
= fixup_imports_ilonly( wm
, load_path
, &wm
->ldr
.EntryPoint
);
2147 status
= fixup_imports( wm
, load_path
);
2148 if (status
!= STATUS_SUCCESS
)
2150 /* the module has only be inserted in the load & memory order lists */
2151 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
2152 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
2154 /* FIXME: there are several more dangling references
2155 * left. Including dlls loaded by this dll before the
2156 * failed one. Unrolling is rather difficult with the
2157 * current structure and we can leave them lying
2158 * around with no problems, so we don't care.
2159 * As these might reference our wm, we don't free it.
2166 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name
), wm
, *module
);
2170 if (TRACE_ON(relay
)) RELAY_SetupDLL( *module
);
2174 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( *module
);
2177 TRACE_(loaddll
)( "Loaded %s at %p: %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), *module
,
2178 is_builtin
? "builtin" : "native" );
2180 wm
->ldr
.LoadCount
= 1;
2183 return STATUS_SUCCESS
;
2187 /*************************************************************************
2188 * build_ntdll_module
2190 * Build the module data for the initially-loaded ntdll.
2192 static void build_ntdll_module(void)
2194 MEMORY_BASIC_INFORMATION meminfo
;
2195 UNICODE_STRING nt_name
;
2198 RtlInitUnicodeString( &nt_name
, L
"\\??\\C:\\windows\\system32\\ntdll.dll" );
2199 NtQueryVirtualMemory( GetCurrentProcess(), build_ntdll_module
, MemoryBasicInformation
,
2200 &meminfo
, sizeof(meminfo
), NULL
);
2201 wm
= alloc_module( meminfo
.AllocationBase
, &nt_name
, TRUE
);
2203 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
2204 node_ntdll
= wm
->ldr
.DdagNode
;
2205 if (TRACE_ON(relay
)) RELAY_SetupDLL( meminfo
.AllocationBase
);
2206 NtQueryVirtualMemory( GetCurrentProcess(), meminfo
.AllocationBase
, MemoryWineUnixFuncs
,
2207 &ntdll_unix_handle
, sizeof(ntdll_unix_handle
), NULL
);
2212 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
2213 static BOOL
convert_to_pe64( HMODULE module
, const SECTION_IMAGE_INFORMATION
*info
)
2215 static const ULONG copy_dirs
[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE
,
2216 IMAGE_DIRECTORY_ENTRY_SECURITY
,
2217 IMAGE_DIRECTORY_ENTRY_BASERELOC
,
2218 IMAGE_DIRECTORY_ENTRY_DEBUG
,
2219 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
};
2220 IMAGE_OPTIONAL_HEADER32 hdr32
= { IMAGE_NT_OPTIONAL_HDR32_MAGIC
};
2221 IMAGE_OPTIONAL_HEADER64 hdr64
= { IMAGE_NT_OPTIONAL_HDR64_MAGIC
};
2222 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
2223 SIZE_T hdr_size
= min( sizeof(hdr32
), nt
->FileHeader
.SizeOfOptionalHeader
);
2224 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char *)&nt
->OptionalHeader
+ hdr_size
);
2225 SIZE_T size
= min( nt
->OptionalHeader
.SizeOfHeaders
, nt
->OptionalHeader
.SizeOfImage
);
2226 void *addr
= module
;
2229 if (nt
->OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return TRUE
; /* already 64-bit */
2230 if (NtCurrentTeb()->WowTebOffset
) return TRUE
; /* no need to convert */
2231 if (!info
->ImageContainsCode
) return TRUE
; /* no need to convert */
2233 TRACE( "%p\n", module
);
2235 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, PAGE_READWRITE
, &old_prot
))
2238 if ((char *)module
+ size
< (char *)(nt
+ 1) + nt
->FileHeader
.NumberOfSections
* sizeof(*sec
))
2240 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
2244 memcpy( &hdr32
, &nt
->OptionalHeader
, hdr_size
);
2245 memcpy( &hdr64
, &hdr32
, offsetof( IMAGE_OPTIONAL_HEADER64
, SizeOfStackReserve
));
2246 hdr64
.Magic
= IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
2247 hdr64
.AddressOfEntryPoint
= 0;
2248 hdr64
.ImageBase
= hdr32
.ImageBase
;
2249 hdr64
.SizeOfStackReserve
= hdr32
.SizeOfStackReserve
;
2250 hdr64
.SizeOfStackCommit
= hdr32
.SizeOfStackCommit
;
2251 hdr64
.SizeOfHeapReserve
= hdr32
.SizeOfHeapReserve
;
2252 hdr64
.SizeOfHeapCommit
= hdr32
.SizeOfHeapCommit
;
2253 hdr64
.LoaderFlags
= hdr32
.LoaderFlags
;
2254 hdr64
.NumberOfRvaAndSizes
= hdr32
.NumberOfRvaAndSizes
;
2255 for (i
= 0; i
< ARRAY_SIZE( copy_dirs
); i
++)
2256 hdr64
.DataDirectory
[copy_dirs
[i
]] = hdr32
.DataDirectory
[copy_dirs
[i
]];
2258 memmove( nt
+ 1, sec
, nt
->FileHeader
.NumberOfSections
* sizeof(*sec
) );
2259 nt
->FileHeader
.SizeOfOptionalHeader
= sizeof(hdr64
);
2260 nt
->OptionalHeader
= hdr64
;
2261 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
2265 /* check COM header for ILONLY flag, ignoring runtime version */
2266 static BOOL
get_cor_header( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
, IMAGE_COR20_HEADER
*cor
)
2268 IMAGE_DOS_HEADER mz
;
2269 IMAGE_NT_HEADERS32 nt
;
2271 LARGE_INTEGER offset
;
2272 IMAGE_SECTION_HEADER sec
[96];
2273 unsigned int i
, count
;
2276 offset
.QuadPart
= 0;
2277 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &mz
, sizeof(mz
), &offset
, NULL
)) return FALSE
;
2278 if (io
.Information
!= sizeof(mz
)) return FALSE
;
2279 if (mz
.e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
2280 offset
.QuadPart
= mz
.e_lfanew
;
2281 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &nt
, sizeof(nt
), &offset
, NULL
)) return FALSE
;
2282 if (io
.Information
!= sizeof(nt
)) return FALSE
;
2283 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) return FALSE
;
2284 if (nt
.OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return FALSE
;
2285 va
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].VirtualAddress
;
2286 size
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].Size
;
2287 if (!va
|| size
< sizeof(*cor
)) return FALSE
;
2288 offset
.QuadPart
+= offsetof( IMAGE_NT_HEADERS32
, OptionalHeader
) + nt
.FileHeader
.SizeOfOptionalHeader
;
2289 count
= min( 96, nt
.FileHeader
.NumberOfSections
);
2290 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &sec
, count
* sizeof(*sec
), &offset
, NULL
)) return FALSE
;
2291 if (io
.Information
!= count
* sizeof(*sec
)) return FALSE
;
2292 for (i
= 0; i
< count
; i
++)
2294 if (va
< sec
[i
].VirtualAddress
) continue;
2295 if (sec
[i
].Misc
.VirtualSize
&& va
- sec
[i
].VirtualAddress
>= sec
[i
].Misc
.VirtualSize
) continue;
2296 offset
.QuadPart
= sec
->PointerToRawData
+ va
- sec
[i
].VirtualAddress
;
2297 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, cor
, sizeof(*cor
), &offset
, NULL
)) return FALSE
;
2298 return (io
.Information
== sizeof(*cor
));
2304 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2305 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2306 static BOOL
is_valid_binary( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
)
2309 return info
->Machine
== IMAGE_FILE_MACHINE_I386
;
2310 #elif defined(__arm__)
2311 return info
->Machine
== IMAGE_FILE_MACHINE_ARM
||
2312 info
->Machine
== IMAGE_FILE_MACHINE_THUMB
||
2313 info
->Machine
== IMAGE_FILE_MACHINE_ARMNT
;
2314 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2316 if (info
->Machine
== IMAGE_FILE_MACHINE_AMD64
) return TRUE
;
2318 if (info
->Machine
== IMAGE_FILE_MACHINE_ARM64
) return TRUE
;
2320 if (NtCurrentTeb()->WowTebOffset
) return TRUE
;
2321 if (!info
->ImageContainsCode
) return TRUE
;
2322 if (!(info
->u
.s
.ComPlusNativeReady
))
2324 IMAGE_COR20_HEADER cor_header
;
2325 if (!get_cor_header( file
, info
, &cor_header
)) return FALSE
;
2326 if (!(cor_header
.Flags
& COMIMAGE_FLAGS_ILONLY
)) return FALSE
;
2330 return FALSE
; /* no wow64 support on other platforms */
2335 /******************************************************************
2336 * get_module_path_end
2338 * Returns the end of the directory component of the module path.
2340 static inline const WCHAR
*get_module_path_end( const WCHAR
*module
)
2343 const WCHAR
*mod_end
= module
;
2345 if ((p
= wcsrchr( mod_end
, '\\' ))) mod_end
= p
;
2346 if ((p
= wcsrchr( mod_end
, '/' ))) mod_end
= p
;
2347 if (mod_end
== module
+ 2 && module
[1] == ':') mod_end
++;
2348 if (mod_end
== module
&& module
[0] && module
[1] == ':') mod_end
+= 2;
2353 /******************************************************************
2356 * Append a counted string to the load path. Helper for get_dll_load_path.
2358 static inline WCHAR
*append_path( WCHAR
*p
, const WCHAR
*str
, int len
)
2360 if (len
== -1) len
= wcslen(str
);
2362 memcpy( p
, str
, len
* sizeof(WCHAR
) );
2368 /******************************************************************
2371 static NTSTATUS
get_dll_load_path( LPCWSTR module
, LPCWSTR dll_dir
, ULONG safe_mode
, WCHAR
**path
)
2373 const WCHAR
*mod_end
= module
;
2374 UNICODE_STRING name
, value
;
2376 int len
= ARRAY_SIZE(system_path
) + 1, path_len
= 0;
2380 mod_end
= get_module_path_end( module
);
2381 len
+= (mod_end
- module
) + 1;
2384 RtlInitUnicodeString( &name
, L
"PATH" );
2386 value
.MaximumLength
= 0;
2387 value
.Buffer
= NULL
;
2388 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2389 path_len
= value
.Length
;
2391 if (dll_dir
) len
+= wcslen( dll_dir
) + 1;
2392 else len
+= 2; /* current directory */
2393 if (!(p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, path_len
+ len
* sizeof(WCHAR
) )))
2394 return STATUS_NO_MEMORY
;
2396 p
= append_path( p
, module
, mod_end
- module
);
2397 if (dll_dir
) p
= append_path( p
, dll_dir
, -1 );
2398 else if (!safe_mode
) p
= append_path( p
, L
".", -1 );
2399 p
= append_path( p
, system_path
, -1 );
2400 if (!dll_dir
&& safe_mode
) p
= append_path( p
, L
".", -1 );
2403 value
.MaximumLength
= path_len
;
2405 while (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2409 /* grow the buffer and retry */
2410 path_len
= value
.Length
;
2411 if (!(new_ptr
= RtlReAllocateHeap( GetProcessHeap(), 0, ret
, path_len
+ len
* sizeof(WCHAR
) )))
2413 RtlFreeHeap( GetProcessHeap(), 0, ret
);
2414 return STATUS_NO_MEMORY
;
2416 value
.Buffer
= new_ptr
+ (value
.Buffer
- ret
);
2417 value
.MaximumLength
= path_len
;
2420 value
.Buffer
[value
.Length
/ sizeof(WCHAR
)] = 0;
2422 return STATUS_SUCCESS
;
2426 /******************************************************************
2427 * get_dll_load_path_search_flags
2429 static NTSTATUS
get_dll_load_path_search_flags( LPCWSTR module
, DWORD flags
, WCHAR
**path
)
2431 const WCHAR
*image
= NULL
, *mod_end
, *image_end
;
2432 struct dll_dir_entry
*dir
;
2436 if (flags
& LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
)
2437 flags
|= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
2438 LOAD_LIBRARY_SEARCH_USER_DIRS
|
2439 LOAD_LIBRARY_SEARCH_SYSTEM32
);
2441 if (flags
& LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
)
2443 DWORD type
= RtlDetermineDosPathNameType_U( module
);
2444 if (type
!= ABSOLUTE_DRIVE_PATH
&& type
!= ABSOLUTE_PATH
&& type
!= DEVICE_PATH
)
2445 return STATUS_INVALID_PARAMETER
;
2446 mod_end
= get_module_path_end( module
);
2447 len
+= (mod_end
- module
) + 1;
2451 if (flags
& LOAD_LIBRARY_SEARCH_APPLICATION_DIR
)
2453 image
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
2454 image_end
= get_module_path_end( image
);
2455 len
+= (image_end
- image
) + 1;
2458 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2460 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2461 len
+= wcslen( dir
->dir
+ 4 /* \??\ */ ) + 1;
2462 if (dll_directory
.Length
) len
+= dll_directory
.Length
/ sizeof(WCHAR
) + 1;
2465 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) len
+= wcslen( system_dir
);
2467 if ((p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2469 if (module
) p
= append_path( p
, module
, mod_end
- module
);
2470 if (image
) p
= append_path( p
, image
, image_end
- image
);
2471 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2473 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2474 p
= append_path( p
, dir
->dir
+ 4 /* \??\ */, -1 );
2475 p
= append_path( p
, dll_directory
.Buffer
, dll_directory
.Length
/ sizeof(WCHAR
) );
2477 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) wcscpy( p
, system_dir
);
2485 return STATUS_SUCCESS
;
2489 /***********************************************************************
2492 * Open a file for a new dll. Helper for find_dll_file.
2494 static NTSTATUS
open_dll_file( UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2495 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2497 FILE_BASIC_INFORMATION info
;
2498 OBJECT_ATTRIBUTES attr
;
2501 FILE_OBJECTID_BUFFER fid
;
2505 if ((*pwm
= find_fullname_module( nt_name
))) return STATUS_SUCCESS
;
2507 attr
.Length
= sizeof(attr
);
2508 attr
.RootDirectory
= 0;
2509 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2510 attr
.ObjectName
= nt_name
;
2511 attr
.SecurityDescriptor
= NULL
;
2512 attr
.SecurityQualityOfService
= NULL
;
2513 if ((status
= NtOpenFile( &handle
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
,
2514 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2515 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
2517 if (status
!= STATUS_OBJECT_PATH_NOT_FOUND
&&
2518 status
!= STATUS_OBJECT_NAME_NOT_FOUND
&&
2519 !NtQueryAttributesFile( &attr
, &info
))
2521 /* if the file exists but failed to open, report the error */
2524 /* otherwise continue searching */
2525 return STATUS_DLL_NOT_FOUND
;
2528 if (!NtFsControlFile( handle
, 0, NULL
, NULL
, &io
, FSCTL_GET_OBJECT_ID
, NULL
, 0, &fid
, sizeof(fid
) ))
2530 memcpy( id
, fid
.ObjectId
, sizeof(*id
) );
2531 if ((*pwm
= find_fileid_module( id
)))
2533 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name
->Buffer
),
2534 (*pwm
)->ldr
.DllBase
, debugstr_w( (*pwm
)->ldr
.FullDllName
.Buffer
));
2536 return STATUS_SUCCESS
;
2541 status
= NtCreateSection( mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
2542 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
2543 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, handle
);
2546 NtQuerySection( *mapping
, SectionImageInformation
, image_info
, sizeof(*image_info
), NULL
);
2547 if (!is_valid_binary( handle
, image_info
))
2549 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name
), image_info
->Machine
);
2550 status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2551 NtClose( *mapping
);
2560 /******************************************************************************
2561 * find_existing_module
2563 * Find an existing module that is the same mapping as the new module.
2565 static WINE_MODREF
*find_existing_module( HMODULE module
)
2568 LIST_ENTRY
*mark
, *entry
;
2569 LDR_DATA_TABLE_ENTRY
*mod
;
2570 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
2572 if ((wm
= get_modref( module
))) return wm
;
2574 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
2575 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2577 mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
2578 if (mod
->TimeDateStamp
!= nt
->FileHeader
.TimeDateStamp
) continue;
2579 wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
2580 if (wm
->CheckSum
!= nt
->OptionalHeader
.CheckSum
) continue;
2581 if (NtAreMappedFilesTheSame( mod
->DllBase
, module
) != STATUS_SUCCESS
) continue;
2582 return CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
2588 /******************************************************************************
2589 * load_native_dll (internal)
2591 static NTSTATUS
load_native_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, HANDLE mapping
,
2592 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
2593 DWORD flags
, BOOL system
, WINE_MODREF
** pwm
)
2595 void *module
= NULL
;
2597 NTSTATUS status
= NtMapViewOfSection( mapping
, NtCurrentProcess(), &module
, 0, 0, NULL
, &len
,
2598 ViewShare
, 0, PAGE_EXECUTE_READ
);
2600 if (status
== STATUS_IMAGE_NOT_AT_BASE
) status
= STATUS_SUCCESS
;
2601 if (status
) return status
;
2603 if ((*pwm
= find_existing_module( module
))) /* already loaded */
2605 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2606 TRACE( "found %s for %s at %p, count=%d\n",
2607 debugstr_us(&(*pwm
)->ldr
.FullDllName
), debugstr_us(nt_name
),
2608 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2609 if (module
!= (*pwm
)->ldr
.DllBase
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2610 return STATUS_SUCCESS
;
2613 if (!convert_to_pe64( module
, image_info
)) status
= STATUS_INVALID_IMAGE_FORMAT
;
2615 if (!status
) status
= build_module( load_path
, nt_name
, &module
, image_info
, id
, flags
, system
, pwm
);
2616 if (status
&& module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2621 /***********************************************************************
2624 static NTSTATUS
load_so_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
,
2625 DWORD flags
, WINE_MODREF
**pwm
)
2630 struct load_so_dll_params params
= { *nt_name
, &module
};
2632 TRACE( "trying %s as so lib\n", debugstr_us(nt_name
) );
2633 if ((status
= NTDLL_UNIX_CALL( load_so_dll
, ¶ms
)))
2635 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name
) );
2636 if (status
== STATUS_INVALID_IMAGE_FORMAT
) status
= STATUS_INVALID_IMAGE_NOT_MZ
;
2640 if ((wm
= get_modref( module
))) /* already loaded */
2642 TRACE( "Found %s at %p for builtin %s\n",
2643 debugstr_w(wm
->ldr
.FullDllName
.Buffer
), wm
->ldr
.DllBase
, debugstr_us(nt_name
) );
2644 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2648 SECTION_IMAGE_INFORMATION image_info
= { 0 };
2650 if ((status
= build_module( load_path
, ¶ms
.nt_name
, &module
, &image_info
, NULL
, flags
, FALSE
, &wm
)))
2652 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2655 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name
), module
);
2658 return STATUS_SUCCESS
;
2662 /*************************************************************************
2665 * Build the module data for the main image.
2667 static WINE_MODREF
*build_main_module(void)
2669 SECTION_IMAGE_INFORMATION info
;
2670 UNICODE_STRING nt_name
;
2673 RTL_USER_PROCESS_PARAMETERS
*params
= NtCurrentTeb()->Peb
->ProcessParameters
;
2674 void *module
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
2676 default_load_path
= params
->DllPath
.Buffer
;
2677 if (!default_load_path
)
2678 get_dll_load_path( params
->ImagePathName
.Buffer
, NULL
, dll_safe_mode
, &default_load_path
);
2680 NtQueryInformationProcess( GetCurrentProcess(), ProcessImageInformation
, &info
, sizeof(info
), NULL
);
2681 if (info
.ImageCharacteristics
& IMAGE_FILE_DLL
)
2683 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_us(¶ms
->ImagePathName
) );
2684 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT
);
2687 if (!convert_to_pe64( module
, &info
))
2689 status
= STATUS_INVALID_IMAGE_FORMAT
;
2693 status
= RtlDosPathNameToNtPathName_U_WithStatus( params
->ImagePathName
.Buffer
, &nt_name
, NULL
, NULL
);
2694 if (status
) goto failed
;
2695 status
= build_module( NULL
, &nt_name
, &module
, &info
, NULL
, DONT_RESOLVE_DLL_REFERENCES
, FALSE
, &wm
);
2696 RtlFreeUnicodeString( &nt_name
);
2697 if (!status
) return wm
;
2699 MESSAGE( "wine: failed to create main module for %s, status %x\n",
2700 debugstr_us(¶ms
->ImagePathName
), status
);
2701 NtTerminateProcess( GetCurrentProcess(), status
);
2702 return NULL
; /* unreached */
2706 /***********************************************************************
2707 * build_dlldata_path
2709 * Helper for find_actctx_dll.
2711 static NTSTATUS
build_dlldata_path( LPCWSTR libname
, ACTCTX_SECTION_KEYED_DATA
*data
, LPWSTR
*fullname
)
2713 struct dllredirect_data
*dlldata
= data
->lpData
;
2714 char *base
= data
->lpSectionBase
;
2715 SIZE_T total
= dlldata
->total_len
+ (wcslen(libname
) + 1) * sizeof(WCHAR
);
2717 NTSTATUS status
= STATUS_SUCCESS
;
2720 if (!(p
= buffer
= RtlAllocateHeap( GetProcessHeap(), 0, total
))) return STATUS_NO_MEMORY
;
2721 for (i
= 0; i
< dlldata
->paths_count
; i
++)
2723 memcpy( p
, base
+ dlldata
->paths
[i
].offset
, dlldata
->paths
[i
].len
);
2724 p
+= dlldata
->paths
[i
].len
/ sizeof(WCHAR
);
2726 if (p
== buffer
|| p
[-1] == '\\') wcscpy( p
, libname
);
2729 if (dlldata
->flags
& DLL_REDIRECT_PATH_EXPAND
)
2731 RtlExpandEnvironmentStrings( NULL
, buffer
, wcslen(buffer
), NULL
, 0, &total
);
2732 if ((*fullname
= RtlAllocateHeap( GetProcessHeap(), 0, total
* sizeof(WCHAR
) )))
2733 RtlExpandEnvironmentStrings( NULL
, buffer
, wcslen(buffer
), *fullname
, total
, NULL
);
2735 status
= STATUS_NO_MEMORY
;
2737 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2739 else *fullname
= buffer
;
2745 /***********************************************************************
2748 * Find the full path (if any) of the dll from the activation context.
2750 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2752 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2754 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
= NULL
;
2755 ACTCTX_SECTION_KEYED_DATA data
;
2756 struct dllredirect_data
*dlldata
;
2757 UNICODE_STRING nameW
;
2759 SIZE_T needed
, size
= 1024;
2762 RtlInitUnicodeString( &nameW
, libname
);
2763 data
.cbSize
= sizeof(data
);
2764 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2765 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2767 if (status
!= STATUS_SUCCESS
) return status
;
2769 if (data
.ulLength
< offsetof( struct dllredirect_data
, paths
[0] ))
2771 status
= STATUS_SXS_KEY_NOT_FOUND
;
2774 dlldata
= data
.lpData
;
2775 if (!(dlldata
->flags
& DLL_REDIRECT_PATH_OMITS_ASSEMBLY_ROOT
))
2777 status
= build_dlldata_path( libname
, &data
, fullname
);
2783 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2785 status
= STATUS_NO_MEMORY
;
2788 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2789 AssemblyDetailedInformationInActivationContext
,
2790 info
, size
, &needed
);
2791 if (status
== STATUS_SUCCESS
) break;
2792 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2793 RtlFreeHeap( GetProcessHeap(), 0, info
);
2795 /* restart with larger buffer */
2798 if (!info
->lpAssemblyManifestPath
)
2800 status
= STATUS_SXS_KEY_NOT_FOUND
;
2804 if ((p
= wcsrchr( info
->lpAssemblyManifestPath
, '\\' )))
2806 DWORD len
, dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2809 if (!dirlen
|| len
<= dirlen
||
2810 RtlCompareUnicodeStrings( p
, dirlen
, info
->lpAssemblyDirectoryName
, dirlen
, TRUE
) ||
2811 wcsicmp( p
+ dirlen
, L
".manifest" ))
2813 /* manifest name does not match directory name, so it's not a global
2814 * windows/winsxs manifest; use the manifest directory name instead */
2815 dirlen
= p
- info
->lpAssemblyManifestPath
;
2816 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2817 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2819 status
= STATUS_NO_MEMORY
;
2822 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2824 wcscpy( p
, libname
);
2829 if (!info
->lpAssemblyDirectoryName
)
2831 status
= STATUS_SXS_KEY_NOT_FOUND
;
2835 needed
= (wcslen(windows_dir
) * sizeof(WCHAR
) +
2836 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2838 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2840 status
= STATUS_NO_MEMORY
;
2843 wcscpy( p
, windows_dir
);
2845 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2846 p
+= ARRAY_SIZE( winsxsW
);
2847 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2848 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2850 wcscpy( p
, libname
);
2852 RtlFreeHeap( GetProcessHeap(), 0, info
);
2853 RtlReleaseActivationContext( data
.hActCtx
);
2859 /******************************************************************************
2862 static NTSTATUS
find_apiset_dll( const WCHAR
*name
, WCHAR
**fullname
)
2864 const API_SET_NAMESPACE
*map
= NtCurrentTeb()->Peb
->ApiSetMap
;
2865 const API_SET_NAMESPACE_ENTRY
*entry
;
2869 if (get_apiset_entry( map
, name
, wcslen(name
), &entry
)) return STATUS_APISET_NOT_PRESENT
;
2870 if (get_apiset_target( map
, entry
, NULL
, &str
)) return STATUS_DLL_NOT_FOUND
;
2872 len
= wcslen( system_dir
) + str
.Length
/ sizeof(WCHAR
);
2873 if (!(*fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
2874 return STATUS_NO_MEMORY
;
2875 wcscpy( *fullname
, system_dir
);
2876 memcpy( *fullname
+ wcslen( system_dir
), str
.Buffer
, str
.Length
);
2877 (*fullname
)[len
] = 0;
2878 return STATUS_SUCCESS
;
2882 /***********************************************************************
2885 static NTSTATUS
get_env_var( const WCHAR
*name
, SIZE_T extra
, UNICODE_STRING
*ret
)
2888 SIZE_T len
, size
= 1024 + extra
;
2892 ret
->Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
* sizeof(WCHAR
) );
2893 status
= RtlQueryEnvironmentVariable( NULL
, name
, wcslen(name
),
2894 ret
->Buffer
, size
- extra
- 1, &len
);
2897 ret
->Buffer
[len
] = 0;
2898 ret
->Length
= len
* sizeof(WCHAR
);
2899 ret
->MaximumLength
= size
* sizeof(WCHAR
);
2902 RtlFreeHeap( GetProcessHeap(), 0, ret
->Buffer
);
2903 if (status
!= STATUS_BUFFER_TOO_SMALL
)
2908 size
= len
+ 1 + extra
;
2913 /***********************************************************************
2914 * find_builtin_without_file
2916 * Find a builtin dll when the corresponding file cannot be found in the prefix.
2917 * This is used during prefix bootstrap.
2919 static NTSTATUS
find_builtin_without_file( const WCHAR
*name
, UNICODE_STRING
*new_name
,
2920 WINE_MODREF
**pwm
, HANDLE
*mapping
,
2921 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2926 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
2927 BOOL found_image
= FALSE
;
2929 if (contains_path( name
)) return status
;
2931 if (!is_prefix_bootstrap
)
2933 /* 16-bit files can't be loaded from the prefix */
2934 if (!name
[1] || wcscmp( name
+ wcslen(name
) - 2, L
"16" )) return status
;
2937 if (!get_env_var( L
"WINEBUILDDIR", 20 + 2 * wcslen(name
) + wcslen(pe_dir
), new_name
))
2939 len
= new_name
->Length
;
2940 RtlAppendUnicodeToString( new_name
, L
"\\dlls\\" );
2941 RtlAppendUnicodeToString( new_name
, name
);
2942 if ((ext
= wcsrchr( name
, '.' )) && !wcscmp( ext
, L
".dll" )) new_name
->Length
-= 4 * sizeof(WCHAR
);
2943 RtlAppendUnicodeToString( new_name
, pe_dir
);
2944 RtlAppendUnicodeToString( new_name
, L
"\\" );
2945 RtlAppendUnicodeToString( new_name
, name
);
2946 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2947 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2949 new_name
->Length
= len
;
2950 RtlAppendUnicodeToString( new_name
, L
"\\programs\\" );
2951 RtlAppendUnicodeToString( new_name
, name
);
2952 RtlAppendUnicodeToString( new_name
, pe_dir
);
2953 RtlAppendUnicodeToString( new_name
, L
"\\" );
2954 RtlAppendUnicodeToString( new_name
, name
);
2955 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2956 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2957 RtlFreeUnicodeString( new_name
);
2962 swprintf( dllpath
, ARRAY_SIZE(dllpath
), L
"WINEDLLDIR%u", i
);
2963 if (get_env_var( dllpath
, wcslen(pe_dir
) + wcslen(name
) + 1, new_name
)) break;
2964 len
= new_name
->Length
;
2965 RtlAppendUnicodeToString( new_name
, pe_dir
);
2966 RtlAppendUnicodeToString( new_name
, L
"\\" );
2967 RtlAppendUnicodeToString( new_name
, name
);
2968 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2969 if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2970 new_name
->Length
= len
;
2971 RtlAppendUnicodeToString( new_name
, L
"\\" );
2972 RtlAppendUnicodeToString( new_name
, name
);
2973 status
= open_dll_file( new_name
, pwm
, mapping
, image_info
, id
);
2974 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) found_image
= TRUE
;
2975 else if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2976 RtlFreeUnicodeString( new_name
);
2978 if (found_image
) status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2981 RtlFreeUnicodeString( new_name
);
2984 new_name
->Length
= (4 + wcslen(system_dir
) + wcslen(name
)) * sizeof(WCHAR
);
2985 new_name
->Buffer
= RtlAllocateHeap( GetProcessHeap(), 0, new_name
->Length
+ sizeof(WCHAR
) );
2986 wcscpy( new_name
->Buffer
, L
"\\??\\" );
2987 wcscat( new_name
->Buffer
, system_dir
);
2988 wcscat( new_name
->Buffer
, name
);
2994 /***********************************************************************
2997 * Search for dll in the specified paths.
2999 static NTSTATUS
search_dll_file( LPCWSTR paths
, LPCWSTR search
, UNICODE_STRING
*nt_name
,
3000 WINE_MODREF
**pwm
, HANDLE
*mapping
, SECTION_IMAGE_INFORMATION
*image_info
,
3001 struct file_id
*id
)
3004 BOOL found_image
= FALSE
;
3005 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
3008 if (!paths
) paths
= default_load_path
;
3009 len
= wcslen( paths
);
3011 if (len
< wcslen( system_dir
)) len
= wcslen( system_dir
);
3012 len
+= wcslen( search
) + 2;
3014 if (!(name
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
3015 return STATUS_NO_MEMORY
;
3019 LPCWSTR ptr
= paths
;
3021 while (*ptr
&& *ptr
!= ';') ptr
++;
3023 if (*ptr
== ';') ptr
++;
3024 memcpy( name
, paths
, len
* sizeof(WCHAR
) );
3025 if (len
&& name
[len
- 1] != '\\') name
[len
++] = '\\';
3026 wcscpy( name
+ len
, search
);
3028 nt_name
->Buffer
= NULL
;
3029 if ((status
= RtlDosPathNameToNtPathName_U_WithStatus( name
, nt_name
, NULL
, NULL
))) goto done
;
3031 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
3032 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) found_image
= TRUE
;
3033 else if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
3034 RtlFreeUnicodeString( nt_name
);
3038 if (found_image
) status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
3041 RtlFreeHeap( GetProcessHeap(), 0, name
);
3045 /***********************************************************************
3048 * Find the file (or already loaded module) for a given dll name.
3050 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
, UNICODE_STRING
*nt_name
,
3051 WINE_MODREF
**pwm
, HANDLE
*mapping
, SECTION_IMAGE_INFORMATION
*image_info
,
3052 struct file_id
*id
)
3054 WCHAR
*fullname
= NULL
;
3056 ULONG wow64_old_value
= 0;
3060 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
3061 RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value
);
3063 nt_name
->Buffer
= NULL
;
3065 if (!contains_path( libname
))
3067 status
= find_apiset_dll( libname
, &fullname
);
3068 if (status
== STATUS_DLL_NOT_FOUND
) goto done
;
3070 if (status
) status
= find_actctx_dll( libname
, &fullname
);
3072 if (status
== STATUS_SUCCESS
)
3074 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
3079 if (status
!= STATUS_SXS_KEY_NOT_FOUND
) goto done
;
3080 if ((*pwm
= find_basename_module( libname
)) != NULL
)
3082 status
= STATUS_SUCCESS
;
3088 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
3090 status
= search_dll_file( load_path
, libname
, nt_name
, pwm
, mapping
, image_info
, id
);
3091 if (status
== STATUS_DLL_NOT_FOUND
)
3092 status
= find_builtin_without_file( libname
, nt_name
, pwm
, mapping
, image_info
, id
);
3094 else if (!(status
= RtlDosPathNameToNtPathName_U_WithStatus( libname
, nt_name
, NULL
, NULL
)))
3095 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
3097 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) status
= STATUS_INVALID_IMAGE_FORMAT
;
3100 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
3101 if (wow64_old_value
) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value
);
3106 /***********************************************************************
3107 * load_dll (internal)
3109 * Load a PE style module according to the load order.
3110 * The loader_section must be locked while calling this function.
3112 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, DWORD flags
, WINE_MODREF
** pwm
, BOOL system
)
3114 UNICODE_STRING nt_name
;
3117 SECTION_IMAGE_INFORMATION image_info
;
3118 NTSTATUS nts
= STATUS_DLL_NOT_FOUND
;
3121 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
3123 if (system
&& system_dll_path
.Buffer
)
3124 nts
= search_dll_file( system_dll_path
.Buffer
, libname
, &nt_name
, pwm
, &mapping
, &image_info
, &id
);
3128 nts
= find_dll_file( load_path
, libname
, &nt_name
, pwm
, &mapping
, &image_info
, &id
);
3132 if (*pwm
) /* found already loaded module */
3134 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
3136 TRACE("Found %s for %s at %p, count=%d\n",
3137 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
3138 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
3139 RtlFreeUnicodeString( &nt_name
);
3140 return STATUS_SUCCESS
;
3143 if (nts
&& nts
!= STATUS_INVALID_IMAGE_NOT_MZ
) goto done
;
3145 if (NtCurrentTeb64())
3147 prev
= NtCurrentTeb64()->Tib
.ArbitraryUserPointer
;
3148 NtCurrentTeb64()->Tib
.ArbitraryUserPointer
= (ULONG_PTR
)(nt_name
.Buffer
+ 4);
3152 prev
= (ULONG_PTR
)NtCurrentTeb()->Tib
.ArbitraryUserPointer
;
3153 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= nt_name
.Buffer
+ 4;
3158 case STATUS_INVALID_IMAGE_NOT_MZ
: /* not in PE format, maybe it's a .so file */
3159 if (ntdll_unix_handle
) nts
= load_so_dll( load_path
, &nt_name
, flags
, pwm
);
3162 case STATUS_SUCCESS
: /* valid PE file */
3163 nts
= load_native_dll( load_path
, &nt_name
, mapping
, &image_info
, &id
, flags
, system
, pwm
);
3167 if (NtCurrentTeb64())
3168 NtCurrentTeb64()->Tib
.ArbitraryUserPointer
= prev
;
3170 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= (void *)(ULONG_PTR
)prev
;
3173 if (nts
== STATUS_SUCCESS
)
3174 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name
), (*pwm
)->ldr
.DllBase
);
3176 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
3178 if (mapping
) NtClose( mapping
);
3179 RtlFreeUnicodeString( &nt_name
);
3184 /***********************************************************************
3185 * __wine_ctrl_routine
3187 NTSTATUS WINAPI
__wine_ctrl_routine( void *arg
)
3191 if (pCtrlRoutine
&& NtCurrentTeb()->Peb
->ProcessParameters
->ConsoleHandle
) ret
= pCtrlRoutine( arg
);
3192 RtlExitUserThread( ret
);
3195 /******************************************************************
3196 * LdrLoadDll (NTDLL.@)
3198 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
3199 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
3203 WCHAR
*dllname
= append_dll_ext( libname
->Buffer
);
3205 RtlEnterCriticalSection( &loader_section
);
3207 nts
= load_dll( path_name
, dllname
? dllname
: libname
->Buffer
, flags
, &wm
, FALSE
);
3209 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
3211 nts
= process_attach( wm
->ldr
.DdagNode
, NULL
);
3212 if (nts
!= STATUS_SUCCESS
)
3214 LdrUnloadDll(wm
->ldr
.DllBase
);
3218 *hModule
= (wm
) ? wm
->ldr
.DllBase
: NULL
;
3220 RtlLeaveCriticalSection( &loader_section
);
3221 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
3226 /******************************************************************
3227 * LdrGetDllFullName (NTDLL.@)
3229 NTSTATUS WINAPI
LdrGetDllFullName( HMODULE module
, UNICODE_STRING
*name
)
3234 TRACE( "module %p, name %p.\n", module
, name
);
3236 if (!module
) module
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
3238 RtlEnterCriticalSection( &loader_section
);
3239 wm
= get_modref( module
);
3242 RtlCopyUnicodeString( name
, &wm
->ldr
.FullDllName
);
3243 if (name
->MaximumLength
< wm
->ldr
.FullDllName
.Length
+ sizeof(WCHAR
)) status
= STATUS_BUFFER_TOO_SMALL
;
3244 else status
= STATUS_SUCCESS
;
3245 } else status
= STATUS_DLL_NOT_FOUND
;
3246 RtlLeaveCriticalSection( &loader_section
);
3252 /******************************************************************
3253 * LdrGetDllHandleEx (NTDLL.@)
3255 NTSTATUS WINAPI
LdrGetDllHandleEx( ULONG flags
, LPCWSTR load_path
, ULONG
*dll_characteristics
,
3256 const UNICODE_STRING
*name
, HMODULE
*base
)
3258 static const ULONG supported_flags
= LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
3259 | LDR_GET_DLL_HANDLE_EX_FLAG_PIN
;
3260 static const ULONG valid_flags
= LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
3261 | LDR_GET_DLL_HANDLE_EX_FLAG_PIN
| 4;
3262 SECTION_IMAGE_INFORMATION image_info
;
3263 UNICODE_STRING nt_name
;
3270 TRACE( "flags %#x, load_path %p, dll_characteristics %p, name %p, base %p.\n",
3271 flags
, load_path
, dll_characteristics
, name
, base
);
3273 if (flags
& ~valid_flags
) return STATUS_INVALID_PARAMETER
;
3275 if ((flags
& (LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
| LDR_GET_DLL_HANDLE_EX_FLAG_PIN
))
3276 == (LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
| LDR_GET_DLL_HANDLE_EX_FLAG_PIN
))
3277 return STATUS_INVALID_PARAMETER
;
3279 if (flags
& ~supported_flags
) FIXME( "Unsupported flags %#x.\n", flags
);
3280 if (dll_characteristics
) FIXME( "dll_characteristics unsupported.\n" );
3282 dllname
= append_dll_ext( name
->Buffer
);
3284 RtlEnterCriticalSection( &loader_section
);
3286 status
= find_dll_file( load_path
, dllname
? dllname
: name
->Buffer
,
3287 &nt_name
, &wm
, &mapping
, &image_info
, &id
);
3289 if (wm
) *base
= wm
->ldr
.DllBase
;
3292 if (status
== STATUS_SUCCESS
) NtClose( mapping
);
3293 status
= STATUS_DLL_NOT_FOUND
;
3295 RtlFreeUnicodeString( &nt_name
);
3299 if (flags
& LDR_GET_DLL_HANDLE_EX_FLAG_PIN
)
3300 LdrAddRefDll( LDR_ADDREF_DLL_PIN
, *base
);
3301 else if (!(flags
& LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
))
3302 LdrAddRefDll( 0, *base
);
3305 RtlLeaveCriticalSection( &loader_section
);
3306 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
3307 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
3312 /******************************************************************
3313 * LdrGetDllHandle (NTDLL.@)
3315 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
3317 return LdrGetDllHandleEx( LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
, load_path
, NULL
, name
, base
);
3321 /******************************************************************
3322 * LdrAddRefDll (NTDLL.@)
3324 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
3326 NTSTATUS ret
= STATUS_SUCCESS
;
3329 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
3331 RtlEnterCriticalSection( &loader_section
);
3333 if ((wm
= get_modref( module
)))
3335 if (flags
& LDR_ADDREF_DLL_PIN
)
3336 wm
->ldr
.LoadCount
= -1;
3338 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
3339 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3341 else ret
= STATUS_INVALID_PARAMETER
;
3343 RtlLeaveCriticalSection( &loader_section
);
3348 /***********************************************************************
3349 * LdrProcessRelocationBlock (NTDLL.@)
3351 * Apply relocations to a given page of a mapped PE image.
3353 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
3354 USHORT
*relocs
, INT_PTR delta
)
3358 USHORT offset
= *relocs
& 0xfff;
3359 int type
= *relocs
>> 12;
3362 case IMAGE_REL_BASED_ABSOLUTE
:
3364 case IMAGE_REL_BASED_HIGH
:
3365 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
3367 case IMAGE_REL_BASED_LOW
:
3368 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
3370 case IMAGE_REL_BASED_HIGHLOW
:
3371 *(int *)((char *)page
+ offset
) += delta
;
3374 case IMAGE_REL_BASED_DIR64
:
3375 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
3377 #elif defined(__arm__)
3378 case IMAGE_REL_BASED_THUMB_MOV32
:
3380 DWORD
*inst
= (DWORD
*)((char *)page
+ offset
);
3381 WORD lo
= ((inst
[0] << 1) & 0x0800) + ((inst
[0] << 12) & 0xf000) +
3382 ((inst
[0] >> 20) & 0x0700) + ((inst
[0] >> 16) & 0x00ff);
3383 WORD hi
= ((inst
[1] << 1) & 0x0800) + ((inst
[1] << 12) & 0xf000) +
3384 ((inst
[1] >> 20) & 0x0700) + ((inst
[1] >> 16) & 0x00ff);
3385 DWORD imm
= MAKELONG( lo
, hi
) + delta
;
3390 if ((inst
[0] & 0x8000fbf0) != 0x0000f240 || (inst
[1] & 0x8000fbf0) != 0x0000f2c0)
3391 ERR("wrong Thumb2 instruction @%p %08x:%08x, expected MOVW/MOVT\n",
3392 inst
, inst
[0], inst
[1] );
3394 inst
[0] = (inst
[0] & 0x8f00fbf0) + ((lo
>> 1) & 0x0400) + ((lo
>> 12) & 0x000f) +
3395 ((lo
<< 20) & 0x70000000) + ((lo
<< 16) & 0xff0000);
3396 inst
[1] = (inst
[1] & 0x8f00fbf0) + ((hi
>> 1) & 0x0400) + ((hi
>> 12) & 0x000f) +
3397 ((hi
<< 20) & 0x70000000) + ((hi
<< 16) & 0xff0000);
3402 FIXME("Unknown/unsupported fixup type %x.\n", type
);
3407 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
3411 /******************************************************************
3412 * LdrQueryProcessModuleInformation
3415 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(RTL_PROCESS_MODULES
*smi
,
3416 ULONG buf_size
, ULONG
* req_size
)
3418 RTL_PROCESS_MODULE_INFORMATION
*sm
= &smi
->Modules
[0];
3419 ULONG size
= sizeof(ULONG
);
3420 NTSTATUS nts
= STATUS_SUCCESS
;
3423 PLIST_ENTRY mark
, entry
;
3424 LDR_DATA_TABLE_ENTRY
*mod
;
3427 smi
->ModulesCount
= 0;
3429 RtlEnterCriticalSection( &loader_section
);
3430 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3431 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3433 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3434 size
+= sizeof(*sm
);
3435 if (size
<= buf_size
)
3437 sm
->Section
= 0; /* FIXME */
3438 sm
->MappedBaseAddress
= mod
->DllBase
;
3439 sm
->ImageBaseAddress
= mod
->DllBase
;
3440 sm
->ImageSize
= mod
->SizeOfImage
;
3441 sm
->Flags
= mod
->Flags
;
3442 sm
->LoadOrderIndex
= id
++;
3443 sm
->InitOrderIndex
= 0; /* FIXME */
3444 sm
->LoadCount
= mod
->LoadCount
;
3446 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
3447 str
.Buffer
= (char*)sm
->Name
;
3448 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
3449 ptr
= strrchr(str
.Buffer
, '\\');
3450 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
3452 smi
->ModulesCount
++;
3455 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
3457 RtlLeaveCriticalSection( &loader_section
);
3459 if (req_size
) *req_size
= size
;
3465 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, LONG
*value
)
3471 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3473 RtlInitUnicodeString( &str
, name
);
3475 size
= sizeof(buffer
) - sizeof(WCHAR
);
3476 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
3479 if (info
->Type
!= REG_DWORD
)
3481 buffer
[size
/ sizeof(WCHAR
)] = 0;
3482 *value
= wcstoul( (WCHAR
*)info
->Data
, 0, 16 );
3484 else memcpy( value
, info
->Data
, sizeof(*value
) );
3488 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
3489 void *data
, ULONG in_size
, ULONG
*out_size
)
3495 KEY_VALUE_PARTIAL_INFORMATION
*info
;
3496 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
3498 RtlInitUnicodeString( &str
, name
);
3500 size
= info_size
+ in_size
;
3501 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
3502 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3503 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
3504 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
3506 if (out_size
) *out_size
= info
->DataLength
;
3507 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
3509 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
3514 /******************************************************************
3515 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3517 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
3518 void *data
, ULONG in_size
, ULONG
*out_size
)
3520 static const WCHAR optionsW
[] = L
"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options";
3521 WCHAR path
[MAX_PATH
+ ARRAY_SIZE( optionsW
)];
3522 OBJECT_ATTRIBUTES attr
;
3523 UNICODE_STRING name_str
;
3529 attr
.Length
= sizeof(attr
);
3530 attr
.RootDirectory
= 0;
3531 attr
.ObjectName
= &name_str
;
3532 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3533 attr
.SecurityDescriptor
= NULL
;
3534 attr
.SecurityQualityOfService
= NULL
;
3536 p
= key
->Buffer
+ key
->Length
/ sizeof(WCHAR
);
3537 while (p
> key
->Buffer
&& p
[-1] != '\\') p
--;
3538 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
3539 name_str
.Buffer
= path
;
3540 name_str
.Length
= sizeof(optionsW
) + len
;
3541 name_str
.MaximumLength
= name_str
.Length
;
3542 memcpy( path
, optionsW
, sizeof(optionsW
) );
3543 memcpy( path
+ ARRAY_SIZE( optionsW
), p
, len
);
3544 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
3546 if (type
== REG_DWORD
)
3548 if (out_size
) *out_size
= sizeof(ULONG
);
3549 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
3550 else status
= STATUS_BUFFER_OVERFLOW
;
3552 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
3559 /******************************************************************
3560 * RtlDllShutdownInProgress (NTDLL.@)
3562 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
3564 return process_detaching
;
3567 /****************************************************************************
3568 * LdrResolveDelayLoadedAPI (NTDLL.@)
3570 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
3571 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
,
3572 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook
,
3573 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
3575 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
3576 DELAYLOAD_INFO delayinfo
;
3584 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
3586 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
3587 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
3588 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
3589 name
= get_rva(base
, desc
->DllNameRVA
);
3594 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
3596 nts
= STATUS_NO_MEMORY
;
3599 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
3600 RtlFreeUnicodeString(&mod
);
3604 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3605 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
3608 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3611 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
3612 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
3616 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
3621 delayinfo
.Size
= sizeof(delayinfo
);
3622 delayinfo
.DelayloadDescriptor
= desc
;
3623 delayinfo
.ThunkAddress
= addr
;
3624 delayinfo
.TargetDllName
= name
;
3625 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
3626 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
3627 delayinfo
.TargetModuleBase
= *phmod
;
3628 delayinfo
.Unused
= NULL
;
3629 delayinfo
.LastError
= nts
;
3632 return dllhook(4, &delayinfo
);
3634 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3636 DWORD_PTR ord
= LOWORD(pINT
[id
].u1
.Ordinal
);
3637 return syshook(name
, (const char *)ord
);
3641 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3642 return syshook(name
, (const char *)iibn
->Name
);
3646 /******************************************************************
3647 * LdrShutdownProcess (NTDLL.@)
3650 void WINAPI
LdrShutdownProcess(void)
3652 BOOL detaching
= process_detaching
;
3656 process_detaching
= TRUE
;
3658 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3664 /******************************************************************
3665 * RtlExitUserProcess (NTDLL.@)
3667 void WINAPI
RtlExitUserProcess( DWORD status
)
3669 RtlEnterCriticalSection( &loader_section
);
3670 RtlAcquirePebLock();
3671 NtTerminateProcess( 0, status
);
3672 LdrShutdownProcess();
3673 for (;;) NtTerminateProcess( GetCurrentProcess(), status
);
3676 /******************************************************************
3677 * LdrShutdownThread (NTDLL.@)
3680 void WINAPI
LdrShutdownThread(void)
3682 PLIST_ENTRY mark
, entry
;
3683 LDR_DATA_TABLE_ENTRY
*mod
;
3690 /* don't do any detach calls if process is exiting */
3691 if (process_detaching
) return;
3693 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3695 RtlEnterCriticalSection( &loader_section
);
3696 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3698 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3699 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
3701 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
3702 InInitializationOrderLinks
);
3703 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
3705 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
3708 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
3709 DLL_THREAD_DETACH
, NULL
);
3712 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_DETACH
);
3714 RtlAcquirePebLock();
3715 if (NtCurrentTeb()->TlsLinks
.Flink
) RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
3716 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
3718 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
3719 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
3721 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 2 );
3722 NtCurrentTeb()->FlsSlots
= NULL
;
3723 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
3724 NtCurrentTeb()->TlsExpansionSlots
= NULL
;
3725 RtlReleasePebLock();
3727 RtlLeaveCriticalSection( &loader_section
);
3728 /* don't call DbgUiGetThreadDebugObject as some apps hook it and terminate if called */
3729 if (NtCurrentTeb()->DbgSsReserved
[1]) NtClose( NtCurrentTeb()->DbgSsReserved
[1] );
3730 RtlFreeThreadActivationContextStack();
3734 /***********************************************************************
3738 static void free_modref( WINE_MODREF
*wm
)
3740 SINGLE_LIST_ENTRY
*entry
;
3741 LDR_DEPENDENCY
*dep
;
3743 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
3744 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
3745 if (wm
->ldr
.InInitializationOrderLinks
.Flink
)
3746 RemoveEntryList(&wm
->ldr
.InInitializationOrderLinks
);
3748 while ((entry
= wm
->ldr
.DdagNode
->Dependencies
.Tail
))
3750 dep
= CONTAINING_RECORD( entry
, LDR_DEPENDENCY
, dependency_to_entry
);
3751 assert( dep
->dependency_from
== wm
->ldr
.DdagNode
);
3752 remove_module_dependency( dep
);
3755 while ((entry
= wm
->ldr
.DdagNode
->IncomingDependencies
.Tail
))
3757 dep
= CONTAINING_RECORD( entry
, LDR_DEPENDENCY
, dependency_from_entry
);
3758 assert( dep
->dependency_to
== wm
->ldr
.DdagNode
);
3759 remove_module_dependency( dep
);
3762 RemoveEntryList(&wm
->ldr
.NodeModuleLink
);
3763 if (IsListEmpty(&wm
->ldr
.DdagNode
->Modules
))
3764 RtlFreeHeap( GetProcessHeap(), 0, wm
->ldr
.DdagNode
);
3766 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
3767 if (!TRACE_ON(module
))
3768 TRACE_(loaddll
)("Unloaded module %s : %s\n",
3769 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
3770 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
3772 free_tls_slot( &wm
->ldr
);
3773 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
3774 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.DllBase
);
3775 if (cached_modref
== wm
) cached_modref
= NULL
;
3776 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
3777 RtlFreeHeap( GetProcessHeap(), 0, wm
);
3780 /***********************************************************************
3781 * MODULE_FlushModrefs
3783 * Remove all unused modrefs and call the internal unloading routines
3784 * for the library type.
3786 * The loader_section must be locked while calling this function.
3788 static void MODULE_FlushModrefs(void)
3790 PLIST_ENTRY mark
, entry
, prev
;
3791 LDR_DATA_TABLE_ENTRY
*mod
;
3794 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3795 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3797 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
3798 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3799 prev
= entry
->Blink
;
3800 if (!mod
->LoadCount
) free_modref( wm
);
3803 /* check load order list too for modules that haven't been initialized yet */
3804 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3805 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3807 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3808 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3809 prev
= entry
->Blink
;
3810 if (!mod
->LoadCount
) free_modref( wm
);
3814 /***********************************************************************
3815 * MODULE_DecRefCount
3817 * The loader_section must be locked while calling this function.
3819 static NTSTATUS
MODULE_DecRefCount( LDR_DDAG_NODE
*node
, void *context
)
3821 LDR_DATA_TABLE_ENTRY
*mod
;
3824 mod
= CONTAINING_RECORD( node
->Modules
.Flink
, LDR_DATA_TABLE_ENTRY
, NodeModuleLink
);
3825 wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
3827 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
3828 return STATUS_SUCCESS
;
3830 if ( wm
->ldr
.LoadCount
<= 0 )
3831 return STATUS_SUCCESS
;
3833 --wm
->ldr
.LoadCount
;
3834 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3836 if ( wm
->ldr
.LoadCount
== 0 )
3838 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
3839 walk_node_dependencies( node
, context
, MODULE_DecRefCount
);
3840 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
3841 module_push_unload_trace( wm
);
3843 return STATUS_SUCCESS
;
3846 /******************************************************************
3847 * LdrUnloadDll (NTDLL.@)
3851 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
3854 NTSTATUS retv
= STATUS_SUCCESS
;
3856 if (process_detaching
) return retv
;
3858 TRACE("(%p)\n", hModule
);
3860 RtlEnterCriticalSection( &loader_section
);
3863 if ((wm
= get_modref( hModule
)) != NULL
)
3865 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
3867 /* Recursively decrement reference counts */
3868 MODULE_DecRefCount( wm
->ldr
.DdagNode
, NULL
);
3870 /* Call process detach notifications */
3871 if ( free_lib_count
<= 1 )
3874 MODULE_FlushModrefs();
3880 retv
= STATUS_DLL_NOT_FOUND
;
3884 RtlLeaveCriticalSection( &loader_section
);
3889 /***********************************************************************
3890 * RtlImageNtHeader (NTDLL.@)
3892 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
3894 IMAGE_NT_HEADERS
*ret
;
3898 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
3901 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
3903 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
3904 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
3915 /***********************************************************************
3916 * process_breakpoint
3918 * Trigger a debug breakpoint if the process is being debugged.
3920 static void process_breakpoint(void)
3924 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort
, &port
, sizeof(port
), NULL
);
3939 /***********************************************************************
3940 * load_global_options
3942 static void load_global_options(void)
3944 OBJECT_ATTRIBUTES attr
;
3945 UNICODE_STRING name_str
, val_str
;
3948 RtlInitUnicodeString( &name_str
, L
"WINEBOOTSTRAPMODE" );
3949 val_str
.MaximumLength
= 0;
3950 is_prefix_bootstrap
= RtlQueryEnvironmentVariable_U( NULL
, &name_str
, &val_str
) != STATUS_VARIABLE_NOT_FOUND
;
3952 attr
.Length
= sizeof(attr
);
3953 attr
.RootDirectory
= 0;
3954 attr
.ObjectName
= &name_str
;
3955 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3956 attr
.SecurityDescriptor
= NULL
;
3957 attr
.SecurityQualityOfService
= NULL
;
3958 RtlInitUnicodeString( &name_str
, L
"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3960 if (!NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))
3962 query_dword_option( hkey
, L
"SafeProcessSearchMode", &path_safe_mode
);
3963 query_dword_option( hkey
, L
"SafeDllSearchMode", &dll_safe_mode
);
3972 static void (WINAPI
*pWow64LdrpInitialize
)( CONTEXT
*ctx
);
3974 void (WINAPI
*pWow64PrepareForException
)( EXCEPTION_RECORD
*rec
, CONTEXT
*context
) = NULL
;
3976 static void init_wow64( CONTEXT
*context
)
3978 if (!imports_fixup_done
)
3983 static const WCHAR wow64_path
[] = L
"C:\\windows\\system32\\wow64.dll";
3985 if ((status
= load_dll( NULL
, wow64_path
, 0, &wm
, FALSE
)))
3987 ERR( "could not load %s, status %x\n", debugstr_w(wow64_path
), status
);
3988 NtTerminateProcess( GetCurrentProcess(), status
);
3990 wow64
= wm
->ldr
.DllBase
;
3991 #define GET_PTR(name) \
3992 if (!(p ## name = RtlFindExportedRoutineByName( wow64, #name ))) ERR( "failed to load %s\n", #name )
3994 GET_PTR( Wow64LdrpInitialize
);
3995 GET_PTR( Wow64PrepareForException
);
3997 imports_fixup_done
= TRUE
;
4000 RtlLeaveCriticalSection( &loader_section
);
4001 pWow64LdrpInitialize( context
);
4007 void *Wow64Transition
= NULL
;
4009 static void map_wow64cpu(void)
4012 OBJECT_ATTRIBUTES attr
;
4013 UNICODE_STRING string
;
4014 HANDLE file
, section
;
4018 RtlInitUnicodeString( &string
, L
"\\??\\C:\\windows\\sysnative\\wow64cpu.dll" );
4019 InitializeObjectAttributes( &attr
, &string
, 0, NULL
, NULL
);
4020 if ((status
= NtOpenFile( &file
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
,
4021 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
4023 WARN("failed to open wow64cpu, status %#x\n", status
);
4026 if (!NtCreateSection( §ion
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
4027 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
4028 NULL
, NULL
, PAGE_EXECUTE_READ
, SEC_COMMIT
, file
))
4030 NtMapViewOfSection( section
, NtCurrentProcess(), &Wow64Transition
, 0,
4031 0, NULL
, &size
, ViewShare
, 0, PAGE_EXECUTE_READ
);
4037 static void init_wow64( CONTEXT
*context
)
4039 PEB
*peb
= NtCurrentTeb()->Peb
;
4040 PEB64
*peb64
= UlongToPtr( NtCurrentTeb64()->Peb
);
4042 if (Wow64Transition
) return; /* already initialized */
4044 peb64
->OSMajorVersion
= peb
->OSMajorVersion
;
4045 peb64
->OSMinorVersion
= peb
->OSMinorVersion
;
4046 peb64
->OSBuildNumber
= peb
->OSBuildNumber
;
4047 peb64
->OSPlatformId
= peb
->OSPlatformId
;
4049 #define SET_INIT_BLOCK(func) LdrSystemDllInitBlock.p ## func = PtrToUlong( &func )
4050 SET_INIT_BLOCK( KiUserApcDispatcher
);
4051 SET_INIT_BLOCK( KiUserExceptionDispatcher
);
4052 SET_INIT_BLOCK( LdrInitializeThunk
);
4053 SET_INIT_BLOCK( LdrSystemDllInitBlock
);
4054 SET_INIT_BLOCK( RtlUserThreadStart
);
4055 SET_INIT_BLOCK( KiUserCallbackDispatcher
);
4056 /* SET_INIT_BLOCK( RtlpQueryProcessDebugInformationRemote ); */
4057 /* SET_INIT_BLOCK( RtlpFreezeTimeBias ); */
4058 /* LdrSystemDllInitBlock.ntdll_handle */
4059 #undef SET_INIT_BLOCK
4066 /* release some address space once dlls are loaded*/
4067 static void release_address_space(void)
4070 void *addr
= (void *)1;
4073 NtFreeVirtualMemory( GetCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
4077 /******************************************************************
4078 * LdrInitializeThunk (NTDLL.@)
4080 * Attach to all the loaded dlls.
4081 * If this is the first time, perform the full process initialization.
4083 void WINAPI
LdrInitializeThunk( CONTEXT
*context
, ULONG_PTR unknown2
, ULONG_PTR unknown3
, ULONG_PTR unknown4
)
4085 static int attach_done
;
4092 entry
= (void **)&context
->Eax
;
4093 #elif defined(__x86_64__)
4094 entry
= (void **)&context
->Rcx
;
4095 #elif defined(__arm__)
4096 entry
= (void **)&context
->R0
;
4097 #elif defined(__aarch64__)
4098 entry
= (void **)&context
->u
.s
.X0
;
4101 if (process_detaching
) NtTerminateThread( GetCurrentThread(), 0 );
4103 RtlEnterCriticalSection( &loader_section
);
4105 if (!imports_fixup_done
)
4107 ANSI_STRING func_name
;
4108 WINE_MODREF
*kernel32
;
4109 PEB
*peb
= NtCurrentTeb()->Peb
;
4111 peb
->LdrData
= &ldr
;
4112 peb
->FastPebLock
= &peb_lock
;
4113 peb
->TlsBitmap
= &tls_bitmap
;
4114 peb
->TlsExpansionBitmap
= &tls_expansion_bitmap
;
4115 peb
->LoaderLock
= &loader_section
;
4116 peb
->ProcessHeap
= RtlCreateHeap( HEAP_GROWABLE
, NULL
, 0, 0, NULL
, NULL
);
4118 RtlInitializeBitMap( &tls_bitmap
, peb
->TlsBitmapBits
, sizeof(peb
->TlsBitmapBits
) * 8 );
4119 RtlInitializeBitMap( &tls_expansion_bitmap
, peb
->TlsExpansionBitmapBits
,
4120 sizeof(peb
->TlsExpansionBitmapBits
) * 8 );
4121 RtlSetBits( peb
->TlsBitmap
, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
4123 init_user_process_params();
4124 load_global_options();
4127 get_env_var( L
"WINESYSTEMDLLPATH", 0, &system_dll_path
);
4129 wm
= build_main_module();
4130 wm
->ldr
.LoadCount
= -1;
4132 build_ntdll_module();
4134 if (NtCurrentTeb()->WowTebOffset
) init_wow64( context
);
4136 if ((status
= load_dll( NULL
, L
"kernel32.dll", 0, &kernel32
, FALSE
)) != STATUS_SUCCESS
)
4138 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
4139 NtTerminateProcess( GetCurrentProcess(), status
);
4141 node_kernel32
= kernel32
->ldr
.DdagNode
;
4142 RtlInitAnsiString( &func_name
, "BaseThreadInitThunk" );
4143 if ((status
= LdrGetProcedureAddress( kernel32
->ldr
.DllBase
, &func_name
,
4144 0, (void **)&pBaseThreadInitThunk
)) != STATUS_SUCCESS
)
4146 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status
);
4147 NtTerminateProcess( GetCurrentProcess(), status
);
4149 RtlInitAnsiString( &func_name
, "CtrlRoutine" );
4150 LdrGetProcedureAddress( kernel32
->ldr
.DllBase
, &func_name
, 0, (void **)&pCtrlRoutine
);
4154 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
4155 status
= fixup_imports_ilonly( wm
, NULL
, entry
);
4157 status
= fixup_imports( wm
, NULL
);
4161 ERR( "Importing dlls for %s failed, status %x\n",
4162 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4163 NtTerminateProcess( GetCurrentProcess(), status
);
4165 imports_fixup_done
= TRUE
;
4167 else wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
4170 if (NtCurrentTeb()->WowTebOffset
) init_wow64( context
);
4173 RtlAcquirePebLock();
4174 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
4175 RtlReleasePebLock();
4177 NtCurrentTeb()->FlsSlots
= fls_alloc_data();
4179 if (!attach_done
) /* first time around */
4182 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
4184 ERR( "TLS init failed when loading %s, status %x\n",
4185 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4186 NtTerminateProcess( GetCurrentProcess(), status
);
4188 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
; /* don't try to attach again */
4189 if (wm
->ldr
.ActivationContext
)
4190 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
4192 if ((status
= process_attach( node_ntdll
, context
))
4193 || (status
= process_attach( node_kernel32
, context
)))
4195 ERR( "Initializing system dll for %s failed, status %x\n",
4196 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4197 NtTerminateProcess( GetCurrentProcess(), status
);
4200 if ((status
= walk_node_dependencies( wm
->ldr
.DdagNode
, context
, process_attach
)))
4202 if (last_failed_modref
)
4203 ERR( "%s failed to initialize, aborting\n",
4204 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
4205 ERR( "Initializing dlls for %s failed, status %x\n",
4206 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
4207 NtTerminateProcess( GetCurrentProcess(), status
);
4209 release_address_space();
4210 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_PROCESS_ATTACH
);
4211 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) NTDLL_UNIX_CALL( init_builtin_dll
, wm
->ldr
.DllBase
);
4212 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
4213 process_breakpoint();
4217 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
4218 NtTerminateThread( GetCurrentThread(), status
);
4220 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_ATTACH
);
4223 RtlLeaveCriticalSection( &loader_section
);
4224 signal_start_thread( context
);
4228 /***********************************************************************
4229 * RtlImageDirectoryEntryToData (NTDLL.@)
4231 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
4233 const IMAGE_NT_HEADERS
*nt
;
4236 if ((ULONG_PTR
)module
& 1) image
= FALSE
; /* mapped as data file */
4237 module
= (HMODULE
)((ULONG_PTR
)module
& ~3);
4238 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
4239 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
4241 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
4243 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
4244 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
4245 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
4246 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
4248 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
4250 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
4252 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
4253 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
4254 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
4255 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
4259 /* not mapped as image, need to find the section containing the virtual address */
4260 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
4264 /***********************************************************************
4265 * RtlImageRvaToSection (NTDLL.@)
4267 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
4268 HMODULE module
, DWORD rva
)
4271 const IMAGE_SECTION_HEADER
*sec
;
4273 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
4274 nt
->FileHeader
.SizeOfOptionalHeader
);
4275 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
4277 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
4278 return (PIMAGE_SECTION_HEADER
)sec
;
4284 /***********************************************************************
4285 * RtlImageRvaToVa (NTDLL.@)
4287 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
4288 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
4290 IMAGE_SECTION_HEADER
*sec
;
4292 if (section
&& *section
) /* try this section first */
4295 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
4298 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
4300 if (section
) *section
= sec
;
4301 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
4305 /***********************************************************************
4306 * RtlPcToFileHeader (NTDLL.@)
4308 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
4310 LDR_DATA_TABLE_ENTRY
*module
;
4313 RtlEnterCriticalSection( &loader_section
);
4314 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->DllBase
;
4315 RtlLeaveCriticalSection( &loader_section
);
4321 /****************************************************************************
4322 * LdrGetDllDirectory (NTDLL.@)
4324 NTSTATUS WINAPI
LdrGetDllDirectory( UNICODE_STRING
*dir
)
4326 NTSTATUS status
= STATUS_SUCCESS
;
4328 RtlEnterCriticalSection( &dlldir_section
);
4329 dir
->Length
= dll_directory
.Length
+ sizeof(WCHAR
);
4330 if (dir
->MaximumLength
>= dir
->Length
) RtlCopyUnicodeString( dir
, &dll_directory
);
4333 status
= STATUS_BUFFER_TOO_SMALL
;
4334 if (dir
->MaximumLength
) dir
->Buffer
[0] = 0;
4336 RtlLeaveCriticalSection( &dlldir_section
);
4341 /****************************************************************************
4342 * LdrSetDllDirectory (NTDLL.@)
4344 NTSTATUS WINAPI
LdrSetDllDirectory( const UNICODE_STRING
*dir
)
4346 NTSTATUS status
= STATUS_SUCCESS
;
4349 if (!dir
->Buffer
) RtlInitUnicodeString( &new, NULL
);
4350 else if ((status
= RtlDuplicateUnicodeString( 1, dir
, &new ))) return status
;
4352 RtlEnterCriticalSection( &dlldir_section
);
4353 RtlFreeUnicodeString( &dll_directory
);
4354 dll_directory
= new;
4355 RtlLeaveCriticalSection( &dlldir_section
);
4360 /****************************************************************************
4361 * LdrAddDllDirectory (NTDLL.@)
4363 NTSTATUS WINAPI
LdrAddDllDirectory( const UNICODE_STRING
*dir
, void **cookie
)
4365 FILE_BASIC_INFORMATION info
;
4366 UNICODE_STRING nt_name
;
4368 OBJECT_ATTRIBUTES attr
;
4370 struct dll_dir_entry
*ptr
;
4371 DOS_PATHNAME_TYPE type
= RtlDetermineDosPathNameType_U( dir
->Buffer
);
4373 if (type
!= ABSOLUTE_PATH
&& type
!= ABSOLUTE_DRIVE_PATH
)
4374 return STATUS_INVALID_PARAMETER
;
4376 status
= RtlDosPathNameToNtPathName_U_WithStatus( dir
->Buffer
, &nt_name
, NULL
, NULL
);
4377 if (status
) return status
;
4378 len
= nt_name
.Length
/ sizeof(WCHAR
);
4379 if (!(ptr
= RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry
, dir
[++len
] ))))
4380 return STATUS_NO_MEMORY
;
4381 memcpy( ptr
->dir
, nt_name
.Buffer
, len
* sizeof(WCHAR
) );
4383 attr
.Length
= sizeof(attr
);
4384 attr
.RootDirectory
= 0;
4385 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
4386 attr
.ObjectName
= &nt_name
;
4387 attr
.SecurityDescriptor
= NULL
;
4388 attr
.SecurityQualityOfService
= NULL
;
4389 status
= NtQueryAttributesFile( &attr
, &info
);
4390 RtlFreeUnicodeString( &nt_name
);
4394 TRACE( "%s\n", debugstr_w( ptr
->dir
));
4395 RtlEnterCriticalSection( &dlldir_section
);
4396 list_add_head( &dll_dir_list
, &ptr
->entry
);
4397 RtlLeaveCriticalSection( &dlldir_section
);
4400 else RtlFreeHeap( GetProcessHeap(), 0, ptr
);
4405 /****************************************************************************
4406 * LdrRemoveDllDirectory (NTDLL.@)
4408 NTSTATUS WINAPI
LdrRemoveDllDirectory( void *cookie
)
4410 struct dll_dir_entry
*ptr
= cookie
;
4412 TRACE( "%s\n", debugstr_w( ptr
->dir
));
4414 RtlEnterCriticalSection( &dlldir_section
);
4415 list_remove( &ptr
->entry
);
4416 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
4417 RtlLeaveCriticalSection( &dlldir_section
);
4418 return STATUS_SUCCESS
;
4422 /*************************************************************************
4423 * LdrSetDefaultDllDirectories (NTDLL.@)
4425 NTSTATUS WINAPI
LdrSetDefaultDllDirectories( ULONG flags
)
4427 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
4428 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
4429 LOAD_LIBRARY_SEARCH_USER_DIRS
|
4430 LOAD_LIBRARY_SEARCH_SYSTEM32
|
4431 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
4433 if (!flags
|| (flags
& ~load_library_search_flags
)) return STATUS_INVALID_PARAMETER
;
4434 default_search_flags
= flags
;
4435 return STATUS_SUCCESS
;
4439 /******************************************************************
4440 * LdrGetDllPath (NTDLL.@)
4442 NTSTATUS WINAPI
LdrGetDllPath( PCWSTR module
, ULONG flags
, PWSTR
*path
, PWSTR
*unknown
)
4445 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
|
4446 LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
4447 LOAD_LIBRARY_SEARCH_USER_DIRS
|
4448 LOAD_LIBRARY_SEARCH_SYSTEM32
|
4449 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
4451 if (flags
& LOAD_WITH_ALTERED_SEARCH_PATH
)
4453 if (flags
& load_library_search_flags
) return STATUS_INVALID_PARAMETER
;
4454 if (default_search_flags
) flags
|= default_search_flags
| LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
;
4456 else if (!(flags
& load_library_search_flags
)) flags
|= default_search_flags
;
4458 RtlEnterCriticalSection( &dlldir_section
);
4460 if (flags
& load_library_search_flags
)
4462 status
= get_dll_load_path_search_flags( module
, flags
, path
);
4466 const WCHAR
*dlldir
= dll_directory
.Length
? dll_directory
.Buffer
: NULL
;
4467 if (!(flags
& LOAD_WITH_ALTERED_SEARCH_PATH
) || !wcschr( module
, L
'\\' ))
4468 module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
4469 status
= get_dll_load_path( module
, dlldir
, dll_safe_mode
, path
);
4472 RtlLeaveCriticalSection( &dlldir_section
);
4478 /*************************************************************************
4479 * RtlSetSearchPathMode (NTDLL.@)
4481 NTSTATUS WINAPI
RtlSetSearchPathMode( ULONG flags
)
4487 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
:
4490 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE
:
4493 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
| BASE_SEARCH_PATH_PERMANENT
:
4494 InterlockedExchange( &path_safe_mode
, 2 );
4495 return STATUS_SUCCESS
;
4497 return STATUS_INVALID_PARAMETER
;
4502 LONG prev
= path_safe_mode
;
4503 if (prev
== 2) break; /* permanently set */
4504 if (InterlockedCompareExchange( &path_safe_mode
, val
, prev
) == prev
) return STATUS_SUCCESS
;
4506 return STATUS_ACCESS_DENIED
;
4510 /******************************************************************
4511 * RtlGetExePath (NTDLL.@)
4513 NTSTATUS WINAPI
RtlGetExePath( PCWSTR name
, PWSTR
*path
)
4515 const WCHAR
*dlldir
= L
".";
4516 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
4518 /* same check as NeedCurrentDirectoryForExePathW */
4519 if (!wcschr( name
, '\\' ))
4521 UNICODE_STRING name
, value
= { 0 };
4523 RtlInitUnicodeString( &name
, L
"NoDefaultCurrentDirectoryInExePath" );
4524 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) != STATUS_VARIABLE_NOT_FOUND
)
4527 return get_dll_load_path( module
, dlldir
, FALSE
, path
);
4531 /******************************************************************
4532 * RtlGetSearchPath (NTDLL.@)
4534 NTSTATUS WINAPI
RtlGetSearchPath( PWSTR
*path
)
4536 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
4537 return get_dll_load_path( module
, NULL
, path_safe_mode
, path
);
4541 /******************************************************************
4542 * RtlReleasePath (NTDLL.@)
4544 void WINAPI
RtlReleasePath( PWSTR path
)
4546 RtlFreeHeap( GetProcessHeap(), 0, path
);
4550 /*********************************************************************
4551 * ApiSetQueryApiSetPresence (NTDLL.@)
4553 NTSTATUS WINAPI
ApiSetQueryApiSetPresence( const UNICODE_STRING
*name
, BOOLEAN
*present
)
4555 const API_SET_NAMESPACE
*map
= NtCurrentTeb()->Peb
->ApiSetMap
;
4556 const API_SET_NAMESPACE_ENTRY
*entry
;
4559 *present
= (!get_apiset_entry( map
, name
->Buffer
, name
->Length
/ sizeof(WCHAR
), &entry
) &&
4560 !get_apiset_target( map
, entry
, NULL
, &str
));
4561 return STATUS_SUCCESS
;
4565 /*********************************************************************
4566 * ApiSetQueryApiSetPresenceEx (NTDLL.@)
4568 NTSTATUS WINAPI
ApiSetQueryApiSetPresenceEx( const UNICODE_STRING
*name
, BOOLEAN
*in_schema
, BOOLEAN
*present
)
4570 const API_SET_NAMESPACE
*map
= NtCurrentTeb()->Peb
->ApiSetMap
;
4571 const API_SET_NAMESPACE_ENTRY
*entry
;
4574 ULONG i
, len
= name
->Length
/ sizeof(WCHAR
);
4576 /* extension not allowed */
4577 for (i
= 0; i
< len
; i
++) if (name
->Buffer
[i
] == '.') return STATUS_INVALID_PARAMETER
;
4579 status
= get_apiset_entry( map
, name
->Buffer
, len
, &entry
);
4580 if (status
== STATUS_APISET_NOT_PRESENT
)
4582 *in_schema
= *present
= FALSE
;
4583 return STATUS_SUCCESS
;
4585 if (status
) return status
;
4587 /* the name must match exactly */
4588 *in_schema
= (entry
->NameLength
== name
->Length
&&
4589 !wcsnicmp( (WCHAR
*)((char *)map
+ entry
->NameOffset
), name
->Buffer
, len
));
4590 *present
= *in_schema
&& !get_apiset_target( map
, entry
, NULL
, &str
);
4591 return STATUS_SUCCESS
;
4595 /******************************************************************
4598 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
4600 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);