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
26 #define WIN32_NO_STATUS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
33 #include "delayloadhandler.h"
35 #include "wine/exception.h"
36 #include "wine/debug.h"
37 #include "wine/list.h"
38 #include "wine/server.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)
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
59 typedef void (CALLBACK
*LDRENUMPROC
)(LDR_DATA_TABLE_ENTRY
*, void *, BOOLEAN
*);
61 void (FASTCALL
*pBaseThreadInitThunk
)(DWORD
,LPTHREAD_START_ROUTINE
,void *) = NULL
;
63 const struct unix_funcs
*unix_funcs
= NULL
;
65 /* windows directory */
66 const WCHAR windows_dir
[] = L
"C:\\windows";
67 /* system directory with trailing backslash */
68 const WCHAR system_dir
[] = L
"C:\\windows\\system32\\";
69 const WCHAR syswow64_dir
[] = L
"C:\\windows\\syswow64\\";
71 static const BOOL is_win64
= (sizeof(void *) > sizeof(int));
72 BOOL is_wow64
= FALSE
;
74 /* system search path */
75 static const WCHAR system_path
[] = L
"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
77 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
78 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
79 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
80 static ULONG path_safe_mode
; /* path mode set by RtlSetSearchPathMode */
81 static ULONG dll_safe_mode
= 1; /* dll search mode */
82 static UNICODE_STRING dll_directory
; /* extra path for LdrSetDllDirectory */
83 static DWORD default_search_flags
; /* default flags set by LdrSetDefaultDllDirectories */
91 static struct list dll_dir_list
= LIST_INIT( dll_dir_list
); /* extra dirs from LdrAddDllDirectory */
93 struct ldr_notification
96 PLDR_DLL_NOTIFICATION_FUNCTION callback
;
100 static struct list ldr_notifications
= LIST_INIT( ldr_notifications
);
102 static const char * const reason_names
[] =
108 NULL
, NULL
, NULL
, NULL
,
117 /* internal representation of loaded modules */
118 typedef struct _wine_modref
120 LDR_DATA_TABLE_ENTRY ldr
;
125 struct _wine_modref
**deps
;
128 static UINT tls_module_count
; /* number of modules with TLS directory */
129 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
130 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
132 static RTL_CRITICAL_SECTION loader_section
;
133 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
135 0, 0, &loader_section
,
136 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
137 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
139 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
141 static CRITICAL_SECTION dlldir_section
;
142 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug
=
144 0, 0, &dlldir_section
,
145 { &dlldir_critsect_debug
.ProcessLocksList
, &dlldir_critsect_debug
.ProcessLocksList
},
146 0, 0, { (DWORD_PTR
)(__FILE__
": dlldir_section") }
148 static CRITICAL_SECTION dlldir_section
= { &dlldir_critsect_debug
, -1, 0, 0, 0, 0 };
150 static RTL_CRITICAL_SECTION peb_lock
;
151 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug
=
154 { &peb_critsect_debug
.ProcessLocksList
, &peb_critsect_debug
.ProcessLocksList
},
155 0, 0, { (DWORD_PTR
)(__FILE__
": peb_lock") }
157 static RTL_CRITICAL_SECTION peb_lock
= { &peb_critsect_debug
, -1, 0, 0, 0, 0 };
159 static PEB_LDR_DATA ldr
= { sizeof(ldr
), TRUE
};
160 static RTL_BITMAP tls_bitmap
;
161 static RTL_BITMAP tls_expansion_bitmap
;
163 static WINE_MODREF
*cached_modref
;
164 static WINE_MODREF
*current_modref
;
165 static WINE_MODREF
*last_failed_modref
;
167 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
168 DWORD flags
, WINE_MODREF
** pwm
);
169 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
170 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
171 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
172 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
173 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
175 /* convert PE image VirtualAddress to Real Address */
176 static inline void *get_rva( HMODULE module
, DWORD va
)
178 return (void *)((char *)module
+ va
);
181 /* check whether the file name contains a path */
182 static inline BOOL
contains_path( LPCWSTR name
)
184 return ((*name
&& (name
[1] == ':')) || wcschr(name
, '/') || wcschr(name
, '\\'));
187 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
189 typedef struct _RTL_UNLOAD_EVENT_TRACE
197 } RTL_UNLOAD_EVENT_TRACE
, *PRTL_UNLOAD_EVENT_TRACE
;
199 static RTL_UNLOAD_EVENT_TRACE unload_traces
[RTL_UNLOAD_EVENT_TRACE_NUMBER
];
200 static RTL_UNLOAD_EVENT_TRACE
*unload_trace_ptr
;
201 static unsigned int unload_trace_seq
;
203 static void module_push_unload_trace( const LDR_DATA_TABLE_ENTRY
*ldr
)
205 RTL_UNLOAD_EVENT_TRACE
*ptr
= &unload_traces
[unload_trace_seq
];
206 unsigned int len
= min(sizeof(ptr
->ImageName
) - sizeof(WCHAR
), ldr
->BaseDllName
.Length
);
208 ptr
->BaseAddress
= ldr
->DllBase
;
209 ptr
->SizeOfImage
= ldr
->SizeOfImage
;
210 ptr
->Sequence
= unload_trace_seq
;
211 ptr
->TimeDateStamp
= ldr
->TimeDateStamp
;
212 ptr
->CheckSum
= ldr
->CheckSum
;
213 memcpy(ptr
->ImageName
, ldr
->BaseDllName
.Buffer
, len
);
214 ptr
->ImageName
[len
/ sizeof(*ptr
->ImageName
)] = 0;
216 unload_trace_seq
= (unload_trace_seq
+ 1) % ARRAY_SIZE(unload_traces
);
217 unload_trace_ptr
= unload_traces
;
220 /*********************************************************************
221 * RtlGetUnloadEventTrace [NTDLL.@]
223 RTL_UNLOAD_EVENT_TRACE
* WINAPI
RtlGetUnloadEventTrace(void)
225 return unload_traces
;
228 /*********************************************************************
229 * RtlGetUnloadEventTraceEx [NTDLL.@]
231 void WINAPI
RtlGetUnloadEventTraceEx(ULONG
**size
, ULONG
**count
, void **trace
)
233 static unsigned int element_size
= sizeof(*unload_traces
);
234 static unsigned int element_count
= ARRAY_SIZE(unload_traces
);
236 *size
= &element_size
;
237 *count
= &element_count
;
238 *trace
= &unload_trace_ptr
;
241 /*************************************************************************
242 * call_dll_entry_point
244 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
245 * their entry point, so we need a small asm wrapper. Testing indicates
246 * that only modifying esi leads to a crash, so use this one to backup
247 * ebp while running the dll entry proc.
250 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
251 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
253 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
254 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
256 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
258 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
260 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
262 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
264 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
268 "movl 8(%ebp),%eax\n\t"
271 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
272 "leal -12(%ebp),%esp\n\t"
274 __ASM_CFI(".cfi_same_value %edi\n\t")
276 __ASM_CFI(".cfi_same_value %esi\n\t")
278 __ASM_CFI(".cfi_same_value %ebx\n\t")
280 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
281 __ASM_CFI(".cfi_same_value %ebp\n\t")
284 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
285 UINT reason
, void *reserved
)
287 return proc( module
, reason
, reserved
);
289 #endif /* __i386__ */
292 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
293 /*************************************************************************
296 * Entry point for stub functions.
298 static void WINAPI
stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
300 EXCEPTION_RECORD rec
;
302 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
303 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
304 rec
.ExceptionRecord
= NULL
;
305 rec
.ExceptionAddress
= ret_addr
;
306 rec
.NumberParameters
= 2;
307 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
308 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
309 for (;;) RtlRaiseException( &rec
);
313 #include "pshpack1.h"
317 BYTE pushl1
; /* pushl $name */
319 BYTE pushl2
; /* pushl $dll */
321 BYTE call
; /* call stub_entry_point */
324 #elif defined(__arm__)
327 DWORD ldr_r0
; /* ldr r0, $dll */
328 DWORD ldr_r1
; /* ldr r1, $name */
329 DWORD mov_r2_lr
; /* mov r2, lr */
330 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
335 #elif defined(__aarch64__)
338 DWORD ldr_x0
; /* ldr x0, $dll */
339 DWORD ldr_x1
; /* ldr x1, $name */
340 DWORD mov_x2_lr
; /* mov x2, lr */
341 DWORD ldr_x16
; /* ldr x16, $entry */
342 DWORD br_x16
; /* br x16 */
350 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
352 BYTE movq_rsi
[2]; /* movq $name,%rsi */
354 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
355 BYTE movq_rax
[2]; /* movq $entry, %rax */
357 BYTE jmpq_rax
[2]; /* jmp %rax */
362 /*************************************************************************
365 * Allocate a stub entry point.
367 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
369 #define MAX_SIZE 65536
370 static struct stub
*stubs
;
371 static unsigned int nb_stubs
;
374 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
378 SIZE_T size
= MAX_SIZE
;
379 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
380 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
383 stub
= &stubs
[nb_stubs
++];
385 stub
->pushl1
= 0x68; /* pushl $name */
387 stub
->pushl2
= 0x68; /* pushl $dll */
389 stub
->call
= 0xe8; /* call stub_entry_point */
390 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
391 #elif defined(__arm__)
392 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
393 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
394 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
395 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
398 stub
->entry
= stub_entry_point
;
399 #elif defined(__aarch64__)
400 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
401 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
402 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
403 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
404 stub
->br_x16
= 0xd61f0200; /* br x16 */
407 stub
->entry
= stub_entry_point
;
409 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rcx */
410 stub
->movq_rdi
[1] = 0xb9;
412 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rdx */
413 stub
->movq_rsi
[1] = 0xba;
415 stub
->movq_rsp_rdx
[0] = 0x4c; /* movq (%rsp),%r8 */
416 stub
->movq_rsp_rdx
[1] = 0x8b;
417 stub
->movq_rsp_rdx
[2] = 0x04;
418 stub
->movq_rsp_rdx
[3] = 0x24;
419 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
420 stub
->movq_rax
[1] = 0xb8;
421 stub
->entry
= stub_entry_point
;
422 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
423 stub
->jmpq_rax
[1] = 0xe0;
425 return (ULONG_PTR
)stub
;
429 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
430 #endif /* __i386__ */
432 /* call ldr notifications */
433 static void call_ldr_notifications( ULONG reason
, LDR_DATA_TABLE_ENTRY
*module
)
435 struct ldr_notification
*notify
, *notify_next
;
436 LDR_DLL_NOTIFICATION_DATA data
;
438 data
.Loaded
.Flags
= 0;
439 data
.Loaded
.FullDllName
= &module
->FullDllName
;
440 data
.Loaded
.BaseDllName
= &module
->BaseDllName
;
441 data
.Loaded
.DllBase
= module
->DllBase
;
442 data
.Loaded
.SizeOfImage
= module
->SizeOfImage
;
444 LIST_FOR_EACH_ENTRY_SAFE( notify
, notify_next
, &ldr_notifications
, struct ldr_notification
, entry
)
446 TRACE_(relay
)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
447 notify
->callback
, reason
, &data
, notify
->context
);
449 notify
->callback(reason
, &data
, notify
->context
);
451 TRACE_(relay
)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
452 notify
->callback
, reason
, &data
, notify
->context
);
456 /*************************************************************************
459 * Looks for the referenced HMODULE in the current process
460 * The loader_section must be locked while calling this function.
462 static WINE_MODREF
*get_modref( HMODULE hmod
)
464 PLIST_ENTRY mark
, entry
;
465 PLDR_DATA_TABLE_ENTRY mod
;
467 if (cached_modref
&& cached_modref
->ldr
.DllBase
== hmod
) return cached_modref
;
469 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
470 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
472 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
473 if (mod
->DllBase
== hmod
)
474 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
480 /**********************************************************************
481 * find_basename_module
483 * Find a module from its base name.
484 * The loader_section must be locked while calling this function
486 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
488 PLIST_ENTRY mark
, entry
;
489 UNICODE_STRING name_str
;
491 RtlInitUnicodeString( &name_str
, name
);
493 if (cached_modref
&& RtlEqualUnicodeString( &name_str
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
494 return cached_modref
;
496 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
497 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
499 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
500 if (RtlEqualUnicodeString( &name_str
, &mod
->BaseDllName
, TRUE
))
502 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
503 return cached_modref
;
510 /**********************************************************************
511 * find_fullname_module
513 * Find a module from its full path name.
514 * The loader_section must be locked while calling this function
516 static WINE_MODREF
*find_fullname_module( const UNICODE_STRING
*nt_name
)
518 PLIST_ENTRY mark
, entry
;
519 UNICODE_STRING name
= *nt_name
;
521 if (name
.Length
<= 4 * sizeof(WCHAR
)) return NULL
;
522 name
.Length
-= 4 * sizeof(WCHAR
); /* for \??\ prefix */
525 if (cached_modref
&& RtlEqualUnicodeString( &name
, &cached_modref
->ldr
.FullDllName
, TRUE
))
526 return cached_modref
;
528 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
529 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
531 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
532 if (RtlEqualUnicodeString( &name
, &mod
->FullDllName
, TRUE
))
534 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
535 return cached_modref
;
542 /**********************************************************************
545 * Find a module from its file id.
546 * The loader_section must be locked while calling this function
548 static WINE_MODREF
*find_fileid_module( const struct file_id
*id
)
550 LIST_ENTRY
*mark
, *entry
;
552 if (cached_modref
&& !memcmp( &cached_modref
->id
, id
, sizeof(*id
) )) return cached_modref
;
554 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
555 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
557 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
558 WINE_MODREF
*wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
560 if (!memcmp( &wm
->id
, id
, sizeof(*id
) ))
570 /*************************************************************************
573 static WINE_MODREF
**grow_module_deps( WINE_MODREF
*wm
, int count
)
578 deps
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, wm
->deps
,
579 (wm
->alloc_deps
+ count
) * sizeof(*deps
) );
581 deps
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, count
* sizeof(*deps
) );
586 wm
->alloc_deps
+= count
;
591 /*************************************************************************
592 * find_forwarded_export
594 * Find the final function pointer for a forwarded function.
595 * The loader_section must be locked while calling this function.
597 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
599 const IMAGE_EXPORT_DIRECTORY
*exports
;
602 WCHAR buffer
[32], *mod_name
= buffer
;
603 const char *end
= strrchr(forward
, '.');
606 if (!end
) return NULL
;
607 if ((end
- forward
) * sizeof(WCHAR
) > sizeof(buffer
) - sizeof(L
".dll"))
609 if (!(mod_name
= RtlAllocateHeap( GetProcessHeap(), 0,
610 (end
- forward
+ sizeof(L
".dll")) * sizeof(WCHAR
) )))
613 ascii_to_unicode( mod_name
, forward
, end
- forward
);
614 mod_name
[end
- forward
] = 0;
615 if (!wcschr( mod_name
, '.' ))
616 memcpy( mod_name
+ (end
- forward
), L
".dll", sizeof(L
".dll") );
618 if (!(wm
= find_basename_module( mod_name
)))
620 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
621 if (load_dll( load_path
, mod_name
, L
".dll", 0, &wm
) == STATUS_SUCCESS
&&
622 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
624 if (!imports_fixup_done
&& current_modref
)
626 WINE_MODREF
**deps
= grow_module_deps( current_modref
, 1 );
627 if (deps
) deps
[current_modref
->nDeps
++] = wm
;
629 else if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
631 LdrUnloadDll( wm
->ldr
.DllBase
);
638 if (mod_name
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, mod_name
);
639 ERR( "module not found for forward '%s' used by %s\n",
640 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
644 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
645 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
647 const char *name
= end
+ 1;
648 if (*name
== '#') /* ordinal */
649 proc
= find_ordinal_export( wm
->ldr
.DllBase
, exports
, exp_size
, atoi(name
+1), load_path
);
651 proc
= find_named_export( wm
->ldr
.DllBase
, exports
, exp_size
, name
, -1, load_path
);
656 ERR("function not found for forward '%s' used by %s."
657 " If you are using builtin %s, try using the native one instead.\n",
658 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
659 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
661 if (mod_name
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, mod_name
);
666 /*************************************************************************
667 * find_ordinal_export
669 * Find an exported function by ordinal.
670 * The exports base must have been subtracted from the ordinal already.
671 * The loader_section must be locked while calling this function.
673 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
674 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
677 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
679 if (ordinal
>= exports
->NumberOfFunctions
)
681 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
684 if (!functions
[ordinal
]) return NULL
;
686 proc
= get_rva( module
, functions
[ordinal
] );
688 /* if the address falls into the export dir, it's a forward */
689 if (((const char *)proc
>= (const char *)exports
) &&
690 ((const char *)proc
< (const char *)exports
+ exp_size
))
691 return find_forwarded_export( module
, (const char *)proc
, load_path
);
695 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
696 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
700 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
701 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
707 /*************************************************************************
710 * Find an exported function by name.
711 * The loader_section must be locked while calling this function.
713 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
714 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
716 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
717 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
718 int min
= 0, max
= exports
->NumberOfNames
- 1;
720 /* first check the hint */
721 if (hint
>= 0 && hint
<= max
)
723 char *ename
= get_rva( module
, names
[hint
] );
724 if (!strcmp( ename
, name
))
725 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
728 /* then do a binary search */
731 int res
, pos
= (min
+ max
) / 2;
732 char *ename
= get_rva( module
, names
[pos
] );
733 if (!(res
= strcmp( ename
, name
)))
734 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
735 if (res
> 0) max
= pos
- 1;
743 /*************************************************************************
746 * Import the dll specified by the given import descriptor.
747 * The loader_section must be locked while calling this function.
749 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
754 const IMAGE_EXPORT_DIRECTORY
*exports
;
756 const IMAGE_THUNK_DATA
*import_list
;
757 IMAGE_THUNK_DATA
*thunk_list
;
759 const char *name
= get_rva( module
, descr
->Name
);
760 DWORD len
= strlen(name
);
762 SIZE_T protect_size
= 0;
765 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
766 if (descr
->u
.OriginalFirstThunk
)
767 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
769 import_list
= thunk_list
;
771 if (!import_list
->u1
.Ordinal
)
773 WARN( "Skipping unused import %s\n", name
);
778 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
780 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
782 ascii_to_unicode( buffer
, name
, len
);
784 status
= load_dll( load_path
, buffer
, L
".dll", 0, &wmImp
);
786 else /* need to allocate a larger buffer */
788 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
789 if (!ptr
) return FALSE
;
790 ascii_to_unicode( ptr
, name
, len
);
792 status
= load_dll( load_path
, ptr
, L
".dll", 0, &wmImp
);
793 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
798 if (status
== STATUS_DLL_NOT_FOUND
)
799 ERR("Library %s (which is needed by %s) not found\n",
800 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
802 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
803 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
807 /* unprotect the import address table since it can be located in
808 * readonly section */
809 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
810 protect_base
= thunk_list
;
811 protect_size
*= sizeof(*thunk_list
);
812 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
813 &protect_size
, PAGE_READWRITE
, &protect_old
);
815 imp_mod
= wmImp
->ldr
.DllBase
;
816 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
820 /* set all imported function to deadbeef */
821 while (import_list
->u1
.Ordinal
)
823 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
825 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
826 WARN("No implementation for %s.%d", name
, ordinal
);
827 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
831 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
832 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
833 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
835 WARN(" imported from %s, allocating stub %p\n",
836 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
837 (void *)thunk_list
->u1
.Function
);
844 while (import_list
->u1
.Ordinal
)
846 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
848 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
850 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
851 ordinal
- exports
->Base
, load_path
);
852 if (!thunk_list
->u1
.Function
)
854 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
855 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
856 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
857 (void *)thunk_list
->u1
.Function
);
859 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
861 else /* import by name */
863 IMAGE_IMPORT_BY_NAME
*pe_name
;
864 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
865 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
866 (const char*)pe_name
->Name
,
867 pe_name
->Hint
, load_path
);
868 if (!thunk_list
->u1
.Function
)
870 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
871 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
872 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
873 (void *)thunk_list
->u1
.Function
);
875 TRACE_(imports
)("--- %s %s.%d = %p\n",
876 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
883 /* restore old protection of the import address table */
884 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
890 /***********************************************************************
891 * create_module_activation_context
893 static NTSTATUS
create_module_activation_context( LDR_DATA_TABLE_ENTRY
*module
)
896 LDR_RESOURCE_INFO info
;
897 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
899 info
.Type
= RT_MANIFEST
;
900 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
902 if (!(status
= LdrFindResource_U( module
->DllBase
, &info
, 3, &entry
)))
905 ctx
.cbSize
= sizeof(ctx
);
907 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
908 ctx
.hModule
= module
->DllBase
;
909 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
910 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
916 /*************************************************************************
917 * is_dll_native_subsystem
919 * Check if dll is a proper native driver.
920 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
921 * while being perfectly normal DLLs. This heuristic should catch such breakages.
923 static BOOL
is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY
*mod
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
925 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
929 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
930 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
931 if (mod
->Flags
& LDR_WINE_INTERNAL
) return TRUE
;
933 if ((imports
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
,
934 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
936 for (i
= 0; imports
[i
].Name
; i
++)
938 const char *name
= get_rva( mod
->DllBase
, imports
[i
].Name
);
939 DWORD len
= strlen(name
);
940 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
941 ascii_to_unicode( buffer
, name
, len
+ 1 );
942 if (!wcsicmp( buffer
, L
"ntdll.dll" ) || !wcsicmp( buffer
, L
"kernel32.dll" ))
944 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
952 /*************************************************************************
955 * Allocate a TLS slot for a newly-loaded module.
956 * The loader_section must be locked while calling this function.
958 static SHORT
alloc_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
960 const IMAGE_TLS_DIRECTORY
*dir
;
965 if (!(dir
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
968 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
969 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
971 for (i
= 0; i
< tls_module_count
; i
++)
973 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
974 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
978 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->DllBase
,
979 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
980 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
982 if (i
== tls_module_count
)
984 UINT new_count
= max( 32, tls_module_count
* 2 );
987 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
989 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
990 new_count
* sizeof(*tls_dirs
) );
991 if (!new_ptr
) return -1;
993 /* resize the pointer block in all running threads */
994 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
996 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
997 void **old
= teb
->ThreadLocalStoragePointer
;
998 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
1000 if (!new) return -1;
1001 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
1002 teb
->ThreadLocalStoragePointer
= new;
1003 #ifdef __x86_64__ /* macOS-specific hack */
1004 if (teb
->Reserved5
[0]) ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
1006 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
1007 /* FIXME: can't free old block here, should be freed at thread exit */
1011 tls_module_count
= new_count
;
1014 /* allocate the data block in all running threads */
1015 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1017 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
1019 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
1020 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
1021 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
1023 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1024 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
1026 RtlFreeHeap( GetProcessHeap(), 0,
1027 InterlockedExchangePointer( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
1030 *(DWORD
*)dir
->AddressOfIndex
= i
;
1036 /*************************************************************************
1039 * Free the module TLS slot on unload.
1040 * The loader_section must be locked while calling this function.
1042 static void free_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
1044 ULONG i
= (USHORT
)mod
->TlsIndex
;
1046 if (mod
->TlsIndex
== -1) return;
1047 assert( i
< tls_module_count
);
1048 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
1052 /****************************************************************
1053 * fixup_imports_ilonly
1055 * Fixup imports for an IL-only module. All we do is import mscoree.
1056 * The loader_section must be locked while calling this function.
1058 static NTSTATUS
fixup_imports_ilonly( WINE_MODREF
*wm
, LPCWSTR load_path
, void **entry
)
1060 IMAGE_EXPORT_DIRECTORY
*exports
;
1064 WINE_MODREF
*prev
, *imp
;
1066 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1067 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1069 if (!grow_module_deps( wm
, 1 )) return STATUS_NO_MEMORY
;
1072 prev
= current_modref
;
1073 current_modref
= wm
;
1074 if (!(status
= load_dll( load_path
, L
"mscoree.dll", NULL
, 0, &imp
))) wm
->deps
[0] = imp
;
1075 current_modref
= prev
;
1078 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1079 debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1083 TRACE( "loaded mscoree for %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1085 if ((exports
= RtlImageDirectoryEntryToData( imp
->ldr
.DllBase
, TRUE
,
1086 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1088 const char *name
= (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) ? "_CorDllMain" : "_CorExeMain";
1089 proc
= find_named_export( imp
->ldr
.DllBase
, exports
, exp_size
, name
, -1, load_path
);
1091 if (!proc
) return STATUS_PROCEDURE_NOT_FOUND
;
1093 return STATUS_SUCCESS
;
1097 /****************************************************************
1100 * Fixup all imports of a given module.
1101 * The loader_section must be locked while calling this function.
1103 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
1105 int i
, dep
, nb_imports
;
1106 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1107 WINE_MODREF
*prev
, *imp
;
1112 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1113 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1115 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
1117 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
1118 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1119 return STATUS_SUCCESS
;
1122 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
1124 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
1125 if (!grow_module_deps( wm
, nb_imports
)) return STATUS_NO_MEMORY
;
1127 if (!create_module_activation_context( &wm
->ldr
))
1128 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1130 /* load the imported modules. They are automatically
1131 * added to the modref list of the process.
1133 prev
= current_modref
;
1134 current_modref
= wm
;
1135 status
= STATUS_SUCCESS
;
1136 for (i
= 0; i
< nb_imports
; i
++)
1140 if (!import_dll( wm
->ldr
.DllBase
, &imports
[i
], load_path
, &imp
))
1143 status
= STATUS_DLL_NOT_FOUND
;
1145 wm
->deps
[dep
] = imp
;
1147 current_modref
= prev
;
1148 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1153 /*************************************************************************
1156 * Allocate a WINE_MODREF structure and add it to the process list
1157 * The loader_section must be locked while calling this function.
1159 static WINE_MODREF
*alloc_module( HMODULE hModule
, const UNICODE_STRING
*nt_name
, BOOL builtin
)
1164 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
1166 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) ))) return NULL
;
1168 wm
->ldr
.DllBase
= hModule
;
1169 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
1170 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
| (builtin
? LDR_WINE_INTERNAL
: 0);
1171 wm
->ldr
.TlsIndex
= -1;
1172 wm
->ldr
.LoadCount
= 1;
1174 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, nt_name
->Length
- 3 * sizeof(WCHAR
) )))
1176 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1179 memcpy( buffer
, nt_name
->Buffer
+ 4 /* \??\ prefix */, nt_name
->Length
- 4 * sizeof(WCHAR
) );
1180 buffer
[nt_name
->Length
/sizeof(WCHAR
) - 4] = 0;
1181 if ((p
= wcsrchr( buffer
, '\\' ))) p
++;
1183 RtlInitUnicodeString( &wm
->ldr
.FullDllName
, buffer
);
1184 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
1186 if (!is_dll_native_subsystem( &wm
->ldr
, nt
, p
))
1188 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
1189 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
1190 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
1191 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1194 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
1195 &wm
->ldr
.InLoadOrderLinks
);
1196 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
1197 &wm
->ldr
.InMemoryOrderLinks
);
1198 /* wait until init is called for inserting into InInitializationOrderModuleList */
1200 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
1202 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
1203 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1204 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1210 /*************************************************************************
1213 * Allocate the per-thread structure for module TLS storage.
1215 static NTSTATUS
alloc_thread_tls(void)
1220 if (!tls_module_count
) return STATUS_SUCCESS
;
1222 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1223 tls_module_count
* sizeof(*pointers
) )))
1224 return STATUS_NO_MEMORY
;
1226 for (i
= 0; i
< tls_module_count
; i
++)
1228 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1231 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1232 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1234 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1236 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1237 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1238 return STATUS_NO_MEMORY
;
1240 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1241 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1243 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1244 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1246 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1247 #ifdef __x86_64__ /* macOS-specific hack */
1248 if (NtCurrentTeb()->Reserved5
[0])
1249 ((TEB
*)NtCurrentTeb()->Reserved5
[0])->ThreadLocalStoragePointer
= pointers
;
1251 return STATUS_SUCCESS
;
1255 /*************************************************************************
1256 * call_tls_callbacks
1258 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1260 const IMAGE_TLS_DIRECTORY
*dir
;
1261 const PIMAGE_TLS_CALLBACK
*callback
;
1264 if (reason
== DLL_WINE_PREATTACH
) return;
1266 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1267 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1269 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1271 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1272 *callback
, module
, reason_names
[reason
] );
1275 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1279 TRACE_(relay
)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1280 GetExceptionCode(), callback
, module
, reason_names
[reason
] );
1284 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1285 *callback
, module
, reason_names
[reason
] );
1289 /*************************************************************************
1292 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1295 NTSTATUS status
= STATUS_SUCCESS
;
1296 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1297 void *module
= wm
->ldr
.DllBase
;
1300 /* Skip calls for modules loaded with special load flags */
1302 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1303 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, reason
);
1304 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
&& reason
== DLL_PROCESS_ATTACH
)
1305 unix_funcs
->init_builtin_dll( wm
->ldr
.DllBase
);
1306 if (!entry
) return STATUS_SUCCESS
;
1308 if (TRACE_ON(relay
))
1310 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1311 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1312 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1313 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1314 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1316 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1317 reason_names
[reason
], lpReserved
);
1321 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1323 status
= STATUS_DLL_INIT_FAILED
;
1327 status
= GetExceptionCode();
1328 TRACE_(relay
)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1329 status
, entry
, module
, reason_names
[reason
], lpReserved
);
1333 /* The state of the module list may have changed due to the call
1334 to the dll. We cannot assume that this module has not been
1336 if (TRACE_ON(relay
))
1337 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1338 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1340 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1346 /*************************************************************************
1349 * Send the process attach notification to all DLLs the given module
1350 * depends on (recursively). This is somewhat complicated due to the fact that
1352 * - we have to respect the module dependencies, i.e. modules implicitly
1353 * referenced by another module have to be initialized before the module
1354 * itself can be initialized
1356 * - the initialization routine of a DLL can itself call LoadLibrary,
1357 * thereby introducing a whole new set of dependencies (even involving
1358 * the 'old' modules) at any time during the whole process
1360 * (Note that this routine can be recursively entered not only directly
1361 * from itself, but also via LoadLibrary from one of the called initialization
1364 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1365 * the process *detach* notifications to be sent in the correct order.
1366 * This must not only take into account module dependencies, but also
1367 * 'hidden' dependencies created by modules calling LoadLibrary in their
1368 * attach notification routine.
1370 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1371 * list after the attach notification has returned. This implies that the
1372 * detach notifications are called in the reverse of the sequence the attach
1373 * notifications *returned*.
1375 * The loader_section must be locked while calling this function.
1377 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1379 NTSTATUS status
= STATUS_SUCCESS
;
1383 if (process_detaching
) return status
;
1385 /* prevent infinite recursion in case of cyclical dependencies */
1386 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1387 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1390 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1392 /* Tag current MODREF to prevent recursive loop */
1393 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1394 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1395 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1397 /* Recursively attach all DLLs this one depends on */
1398 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1400 if (!wm
->deps
[i
]) continue;
1401 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1404 if (!wm
->ldr
.InInitializationOrderLinks
.Flink
)
1405 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1406 &wm
->ldr
.InInitializationOrderLinks
);
1408 /* Call DLL entry point */
1409 if (status
== STATUS_SUCCESS
)
1411 WINE_MODREF
*prev
= current_modref
;
1412 current_modref
= wm
;
1414 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED
, &wm
->ldr
);
1415 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1416 if (status
== STATUS_SUCCESS
)
1418 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1422 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1423 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, &wm
->ldr
);
1425 /* point to the name so LdrInitializeThunk can print it */
1426 last_failed_modref
= wm
;
1427 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1429 current_modref
= prev
;
1432 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1433 /* Remove recursion flag */
1434 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1436 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1441 /**********************************************************************
1442 * attach_implicitly_loaded_dlls
1444 * Attach to the (builtin) dlls that have been implicitly loaded because
1445 * of a dependency at the Unix level, but not imported at the Win32 level.
1447 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1451 PLIST_ENTRY mark
, entry
;
1453 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1454 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1456 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1458 if (!(mod
->Flags
& LDR_IMAGE_IS_DLL
)) continue;
1459 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1460 TRACE( "found implicitly loaded %s, attaching to it\n",
1461 debugstr_w(mod
->BaseDllName
.Buffer
));
1462 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1463 break; /* restart the search from the start */
1465 if (entry
== mark
) break; /* nothing found */
1470 /*************************************************************************
1473 * Send DLL process detach notifications. See the comment about calling
1474 * sequence at process_attach.
1476 static void process_detach(void)
1478 PLIST_ENTRY mark
, entry
;
1479 PLDR_DATA_TABLE_ENTRY mod
;
1481 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1484 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1486 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1487 InInitializationOrderLinks
);
1488 /* Check whether to detach this DLL */
1489 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1491 if ( mod
->LoadCount
&& !process_detaching
)
1494 /* Call detach notification */
1495 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1496 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1497 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1498 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, mod
);
1500 /* Restart at head of WINE_MODREF list, as entries might have
1501 been added and/or removed while performing the call ... */
1504 } while (entry
!= mark
);
1507 /*************************************************************************
1510 * Send DLL thread attach notifications. These are sent in the
1511 * reverse sequence of process detach notification.
1512 * The loader_section must be locked while calling this function.
1514 static void thread_attach(void)
1516 PLIST_ENTRY mark
, entry
;
1517 PLDR_DATA_TABLE_ENTRY mod
;
1519 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1520 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1522 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1523 InInitializationOrderLinks
);
1524 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1526 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1529 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1533 /******************************************************************
1534 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1537 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1540 NTSTATUS ret
= STATUS_SUCCESS
;
1542 RtlEnterCriticalSection( &loader_section
);
1544 wm
= get_modref( hModule
);
1545 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1546 ret
= STATUS_DLL_NOT_FOUND
;
1548 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1550 RtlLeaveCriticalSection( &loader_section
);
1555 /******************************************************************
1556 * LdrFindEntryForAddress (NTDLL.@)
1558 * The loader_section must be locked while calling this function
1560 NTSTATUS WINAPI
LdrFindEntryForAddress( const void *addr
, PLDR_DATA_TABLE_ENTRY
*pmod
)
1562 PLIST_ENTRY mark
, entry
;
1563 PLDR_DATA_TABLE_ENTRY mod
;
1565 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1566 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1568 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1569 if (mod
->DllBase
<= addr
&&
1570 (const char *)addr
< (char*)mod
->DllBase
+ mod
->SizeOfImage
)
1573 return STATUS_SUCCESS
;
1576 return STATUS_NO_MORE_ENTRIES
;
1579 /******************************************************************
1580 * LdrEnumerateLoadedModules (NTDLL.@)
1582 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1584 LIST_ENTRY
*mark
, *entry
;
1585 LDR_DATA_TABLE_ENTRY
*mod
;
1586 BOOLEAN stop
= FALSE
;
1588 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1590 if (unknown
|| !callback
)
1591 return STATUS_INVALID_PARAMETER
;
1593 RtlEnterCriticalSection( &loader_section
);
1595 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1596 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1598 mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1599 callback( mod
, context
, &stop
);
1603 RtlLeaveCriticalSection( &loader_section
);
1604 return STATUS_SUCCESS
;
1607 /******************************************************************
1608 * LdrRegisterDllNotification (NTDLL.@)
1610 NTSTATUS WINAPI
LdrRegisterDllNotification(ULONG flags
, PLDR_DLL_NOTIFICATION_FUNCTION callback
,
1611 void *context
, void **cookie
)
1613 struct ldr_notification
*notify
;
1615 TRACE( "(%x, %p, %p, %p)\n", flags
, callback
, context
, cookie
);
1617 if (!callback
|| !cookie
)
1618 return STATUS_INVALID_PARAMETER
;
1621 FIXME( "ignoring flags %x\n", flags
);
1623 notify
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify
) );
1624 if (!notify
) return STATUS_NO_MEMORY
;
1625 notify
->callback
= callback
;
1626 notify
->context
= context
;
1628 RtlEnterCriticalSection( &loader_section
);
1629 list_add_tail( &ldr_notifications
, ¬ify
->entry
);
1630 RtlLeaveCriticalSection( &loader_section
);
1633 return STATUS_SUCCESS
;
1636 /******************************************************************
1637 * LdrUnregisterDllNotification (NTDLL.@)
1639 NTSTATUS WINAPI
LdrUnregisterDllNotification( void *cookie
)
1641 struct ldr_notification
*notify
= cookie
;
1643 TRACE( "(%p)\n", cookie
);
1645 if (!notify
) return STATUS_INVALID_PARAMETER
;
1647 RtlEnterCriticalSection( &loader_section
);
1648 list_remove( ¬ify
->entry
);
1649 RtlLeaveCriticalSection( &loader_section
);
1651 RtlFreeHeap( GetProcessHeap(), 0, notify
);
1652 return STATUS_SUCCESS
;
1655 /******************************************************************
1656 * LdrLockLoaderLock (NTDLL.@)
1658 * Note: some flags are not implemented.
1659 * Flag 0x01 is used to raise exceptions on errors.
1661 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1663 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1665 if (result
) *result
= 0;
1666 if (magic
) *magic
= 0;
1667 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1668 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1669 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1673 if (!RtlTryEnterCriticalSection( &loader_section
))
1676 return STATUS_SUCCESS
;
1682 RtlEnterCriticalSection( &loader_section
);
1683 if (result
) *result
= 1;
1685 *magic
= GetCurrentThreadId();
1686 return STATUS_SUCCESS
;
1690 /******************************************************************
1691 * LdrUnlockLoaderUnlock (NTDLL.@)
1693 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1697 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1698 RtlLeaveCriticalSection( &loader_section
);
1700 return STATUS_SUCCESS
;
1704 /******************************************************************
1705 * LdrGetProcedureAddress (NTDLL.@)
1707 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1708 ULONG ord
, PVOID
*address
)
1710 IMAGE_EXPORT_DIRECTORY
*exports
;
1712 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1714 RtlEnterCriticalSection( &loader_section
);
1716 /* check if the module itself is invalid to return the proper error */
1717 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1718 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1719 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1721 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1722 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1723 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1727 ret
= STATUS_SUCCESS
;
1731 RtlLeaveCriticalSection( &loader_section
);
1736 /***********************************************************************
1737 * set_security_cookie
1739 * Create a random security cookie for buffer overflow protection. Make
1740 * sure it does not accidentally match the default cookie value.
1742 static void set_security_cookie( void *module
, SIZE_T len
)
1745 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1749 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1750 if (!loadcfg
) return;
1751 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1752 if (!loadcfg
->SecurityCookie
) return;
1753 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1754 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1756 WARN( "security cookie %p outside of image %p-%p\n",
1757 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1761 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1762 TRACE( "initializing security cookie %p\n", cookie
);
1764 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1767 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1768 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1769 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1770 *cookie
= RtlRandom( &seed
);
1771 #ifdef DEFAULT_SECURITY_COOKIE_64
1772 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1774 *cookie
= RtlRandom( &seed
);
1775 /* fill up, but keep the highest word clear */
1776 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1784 static NTSTATUS
perform_relocations( void *module
, IMAGE_NT_HEADERS
*nt
, SIZE_T len
)
1787 IMAGE_BASE_RELOCATION
*rel
, *end
;
1788 const IMAGE_DATA_DIRECTORY
*relocs
;
1789 const IMAGE_SECTION_HEADER
*sec
;
1791 ULONG protect_old
[96], i
;
1793 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1794 if (module
== base
) return STATUS_SUCCESS
; /* nothing to do */
1796 /* no relocations are performed on non page-aligned binaries */
1797 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1798 return STATUS_SUCCESS
;
1800 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1801 return STATUS_SUCCESS
;
1803 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1805 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1807 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1809 return STATUS_CONFLICTING_ADDRESSES
;
1812 if (!relocs
->Size
) return STATUS_SUCCESS
;
1813 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1815 if (nt
->FileHeader
.NumberOfSections
> ARRAY_SIZE( protect_old
))
1816 return STATUS_INVALID_IMAGE_FORMAT
;
1818 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1819 nt
->FileHeader
.SizeOfOptionalHeader
);
1820 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1822 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1823 SIZE_T size
= sec
[i
].SizeOfRawData
;
1824 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1825 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1828 TRACE( "relocating from %p-%p to %p-%p\n",
1829 base
, base
+ len
, module
, (char *)module
+ len
);
1831 rel
= get_rva( module
, relocs
->VirtualAddress
);
1832 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1833 delta
= (char *)module
- base
;
1835 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1837 if (rel
->VirtualAddress
>= len
)
1839 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1840 return STATUS_ACCESS_VIOLATION
;
1842 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1843 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1844 (USHORT
*)(rel
+ 1), delta
);
1845 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1848 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1850 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1851 SIZE_T size
= sec
[i
].SizeOfRawData
;
1852 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1853 &size
, protect_old
[i
], &protect_old
[i
] );
1856 return STATUS_SUCCESS
;
1860 /*************************************************************************
1863 * Build the module data for a mapped dll.
1865 static NTSTATUS
build_module( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, void **module
,
1866 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
1867 DWORD flags
, WINE_MODREF
**pwm
)
1869 IMAGE_NT_HEADERS
*nt
;
1874 if (!(nt
= RtlImageNtHeader( *module
))) return STATUS_INVALID_IMAGE_FORMAT
;
1876 map_size
= (nt
->OptionalHeader
.SizeOfImage
+ page_size
- 1) & ~(page_size
- 1);
1877 if ((status
= perform_relocations( *module
, nt
, map_size
))) return status
;
1879 /* create the MODREF */
1881 if (!(wm
= alloc_module( *module
, nt_name
, (image_info
->u
.ImageFlags
& IMAGE_FLAGS_WineBuiltin
) )))
1882 return STATUS_NO_MEMORY
;
1884 if (id
) wm
->id
= *id
;
1885 if (image_info
->LoaderFlags
) wm
->ldr
.Flags
|= LDR_COR_IMAGE
;
1886 if (image_info
->u
.ImageFlags
& IMAGE_FLAGS_ComPlusILOnly
) wm
->ldr
.Flags
|= LDR_COR_ILONLY
;
1888 set_security_cookie( *module
, map_size
);
1892 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1893 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1894 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1896 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
1897 status
= fixup_imports_ilonly( wm
, load_path
, &wm
->ldr
.EntryPoint
);
1899 status
= fixup_imports( wm
, load_path
);
1900 if (status
!= STATUS_SUCCESS
)
1902 /* the module has only be inserted in the load & memory order lists */
1903 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
1904 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
1906 /* FIXME: there are several more dangling references
1907 * left. Including dlls loaded by this dll before the
1908 * failed one. Unrolling is rather difficult with the
1909 * current structure and we can leave them lying
1910 * around with no problems, so we don't care.
1911 * As these might reference our wm, we don't free it.
1918 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name
), wm
, *module
);
1920 /* send DLL load event */
1922 SERVER_START_REQ( load_dll
)
1924 req
->base
= wine_server_client_ptr( *module
);
1925 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1926 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1927 wine_server_call( req
);
1931 if (image_info
->u
.ImageFlags
& IMAGE_FLAGS_WineBuiltin
)
1933 if (TRACE_ON(relay
)) RELAY_SetupDLL( *module
);
1937 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( *module
);
1940 TRACE_(loaddll
)( "Loaded %s at %p: %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), *module
,
1941 (image_info
->u
.ImageFlags
& IMAGE_FLAGS_WineBuiltin
) ? "builtin" : "native" );
1943 wm
->ldr
.LoadCount
= 1;
1946 return STATUS_SUCCESS
;
1950 /*************************************************************************
1951 * build_builtin_module
1953 * Build the module for a builtin library.
1955 static NTSTATUS
build_builtin_module( const WCHAR
*load_path
, const UNICODE_STRING
*nt_name
,
1956 void *module
, DWORD flags
, WINE_MODREF
**pwm
)
1959 SECTION_IMAGE_INFORMATION image_info
= { 0 };
1961 image_info
.u
.ImageFlags
= IMAGE_FLAGS_WineBuiltin
;
1962 status
= build_module( load_path
, nt_name
, &module
, &image_info
, NULL
, flags
, pwm
);
1963 if (status
&& module
) unix_funcs
->unload_builtin_dll( module
);
1969 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1970 static BOOL
convert_to_pe64( HMODULE module
, const SECTION_IMAGE_INFORMATION
*info
)
1972 static const ULONG copy_dirs
[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE
,
1973 IMAGE_DIRECTORY_ENTRY_SECURITY
,
1974 IMAGE_DIRECTORY_ENTRY_BASERELOC
,
1975 IMAGE_DIRECTORY_ENTRY_DEBUG
,
1976 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
};
1977 IMAGE_OPTIONAL_HEADER32 hdr32
= { IMAGE_NT_OPTIONAL_HDR32_MAGIC
};
1978 IMAGE_OPTIONAL_HEADER64 hdr64
= { IMAGE_NT_OPTIONAL_HDR64_MAGIC
};
1979 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
1980 SIZE_T hdr_size
= min( sizeof(hdr32
), nt
->FileHeader
.SizeOfOptionalHeader
);
1981 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char *)&nt
->OptionalHeader
+ hdr_size
);
1982 SIZE_T size
= min( nt
->OptionalHeader
.SizeOfHeaders
, nt
->OptionalHeader
.SizeOfImage
);
1983 void *addr
= module
;
1986 if (nt
->OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return TRUE
; /* already 64-bit */
1988 TRACE( "%p\n", module
);
1990 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, PAGE_READWRITE
, &old_prot
))
1993 if ((char *)module
+ size
< (char *)(nt
+ 1) + nt
->FileHeader
.NumberOfSections
* sizeof(*sec
))
1995 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
1999 memcpy( &hdr32
, &nt
->OptionalHeader
, hdr_size
);
2000 memcpy( &hdr64
, &hdr32
, offsetof( IMAGE_OPTIONAL_HEADER64
, SizeOfStackReserve
));
2001 hdr64
.Magic
= IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
2002 hdr64
.AddressOfEntryPoint
= 0;
2003 hdr64
.ImageBase
= hdr32
.ImageBase
;
2004 hdr64
.SizeOfStackReserve
= hdr32
.SizeOfStackReserve
;
2005 hdr64
.SizeOfStackCommit
= hdr32
.SizeOfStackCommit
;
2006 hdr64
.SizeOfHeapReserve
= hdr32
.SizeOfHeapReserve
;
2007 hdr64
.SizeOfHeapCommit
= hdr32
.SizeOfHeapCommit
;
2008 hdr64
.LoaderFlags
= hdr32
.LoaderFlags
;
2009 hdr64
.NumberOfRvaAndSizes
= hdr32
.NumberOfRvaAndSizes
;
2010 for (i
= 0; i
< ARRAY_SIZE( copy_dirs
); i
++)
2011 hdr64
.DataDirectory
[copy_dirs
[i
]] = hdr32
.DataDirectory
[copy_dirs
[i
]];
2013 memmove( nt
+ 1, sec
, nt
->FileHeader
.NumberOfSections
* sizeof(*sec
) );
2014 nt
->FileHeader
.SizeOfOptionalHeader
= sizeof(hdr64
);
2015 nt
->OptionalHeader
= hdr64
;
2016 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
2020 /* check COM header for ILONLY flag, ignoring runtime version */
2021 static BOOL
get_cor_header( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
, IMAGE_COR20_HEADER
*cor
)
2023 IMAGE_DOS_HEADER mz
;
2024 IMAGE_NT_HEADERS32 nt
;
2026 LARGE_INTEGER offset
;
2027 IMAGE_SECTION_HEADER sec
[96];
2028 unsigned int i
, count
;
2031 offset
.QuadPart
= 0;
2032 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &mz
, sizeof(mz
), &offset
, NULL
)) return FALSE
;
2033 if (io
.Information
!= sizeof(mz
)) return FALSE
;
2034 if (mz
.e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
2035 offset
.QuadPart
= mz
.e_lfanew
;
2036 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &nt
, sizeof(nt
), &offset
, NULL
)) return FALSE
;
2037 if (io
.Information
!= sizeof(nt
)) return FALSE
;
2038 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) return FALSE
;
2039 if (nt
.OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return FALSE
;
2040 va
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].VirtualAddress
;
2041 size
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].Size
;
2042 if (!va
|| size
< sizeof(*cor
)) return FALSE
;
2043 offset
.QuadPart
= offsetof( IMAGE_NT_HEADERS32
, OptionalHeader
) + nt
.FileHeader
.SizeOfOptionalHeader
;
2044 count
= min( 96, nt
.FileHeader
.NumberOfSections
);
2045 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &sec
, count
* sizeof(*sec
), &offset
, NULL
)) return FALSE
;
2046 if (io
.Information
!= count
* sizeof(*sec
)) return FALSE
;
2047 for (i
= 0; i
< count
; i
++)
2049 if (va
< sec
[i
].VirtualAddress
) continue;
2050 if (sec
[i
].Misc
.VirtualSize
&& va
- sec
[i
].VirtualAddress
>= sec
[i
].Misc
.VirtualSize
) continue;
2051 offset
.QuadPart
= sec
->PointerToRawData
+ va
- sec
[i
].VirtualAddress
;
2052 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, cor
, sizeof(*cor
), &offset
, NULL
)) return FALSE
;
2053 return (io
.Information
== sizeof(*cor
));
2059 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2060 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2061 static BOOL
is_valid_binary( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
)
2064 return info
->Machine
== IMAGE_FILE_MACHINE_I386
;
2065 #elif defined(__arm__)
2066 return info
->Machine
== IMAGE_FILE_MACHINE_ARM
||
2067 info
->Machine
== IMAGE_FILE_MACHINE_THUMB
||
2068 info
->Machine
== IMAGE_FILE_MACHINE_ARMNT
;
2069 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2071 if (info
->Machine
== IMAGE_FILE_MACHINE_AMD64
) return TRUE
;
2073 if (info
->Machine
== IMAGE_FILE_MACHINE_ARM64
) return TRUE
;
2075 if (!info
->ImageContainsCode
) return TRUE
;
2076 if (!(info
->u
.ImageFlags
& IMAGE_FLAGS_ComPlusNativeReady
))
2078 IMAGE_COR20_HEADER cor_header
;
2079 if (!get_cor_header( file
, info
, &cor_header
)) return FALSE
;
2080 if (!(cor_header
.Flags
& COMIMAGE_FLAGS_ILONLY
)) return FALSE
;
2084 return FALSE
; /* no wow64 support on other platforms */
2089 /******************************************************************
2090 * get_module_path_end
2092 * Returns the end of the directory component of the module path.
2094 static inline const WCHAR
*get_module_path_end( const WCHAR
*module
)
2097 const WCHAR
*mod_end
= module
;
2099 if ((p
= wcsrchr( mod_end
, '\\' ))) mod_end
= p
;
2100 if ((p
= wcsrchr( mod_end
, '/' ))) mod_end
= p
;
2101 if (mod_end
== module
+ 2 && module
[1] == ':') mod_end
++;
2102 if (mod_end
== module
&& module
[0] && module
[1] == ':') mod_end
+= 2;
2107 /******************************************************************
2110 * Append a counted string to the load path. Helper for get_dll_load_path.
2112 static inline WCHAR
*append_path( WCHAR
*p
, const WCHAR
*str
, int len
)
2114 if (len
== -1) len
= wcslen(str
);
2116 memcpy( p
, str
, len
* sizeof(WCHAR
) );
2122 /******************************************************************
2125 static NTSTATUS
get_dll_load_path( LPCWSTR module
, LPCWSTR dll_dir
, ULONG safe_mode
, WCHAR
**path
)
2127 const WCHAR
*mod_end
= module
;
2128 UNICODE_STRING name
, value
;
2130 int len
= ARRAY_SIZE(system_path
) + 1, path_len
= 0;
2134 mod_end
= get_module_path_end( module
);
2135 len
+= (mod_end
- module
) + 1;
2138 RtlInitUnicodeString( &name
, L
"PATH" );
2140 value
.MaximumLength
= 0;
2141 value
.Buffer
= NULL
;
2142 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2143 path_len
= value
.Length
;
2145 if (dll_dir
) len
+= wcslen( dll_dir
) + 1;
2146 else len
+= 2; /* current directory */
2147 if (!(p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, path_len
+ len
* sizeof(WCHAR
) )))
2148 return STATUS_NO_MEMORY
;
2150 p
= append_path( p
, module
, mod_end
- module
);
2151 if (dll_dir
) p
= append_path( p
, dll_dir
, -1 );
2152 else if (!safe_mode
) p
= append_path( p
, L
".", -1 );
2153 p
= append_path( p
, system_path
, -1 );
2154 if (!dll_dir
&& safe_mode
) p
= append_path( p
, L
".", -1 );
2157 value
.MaximumLength
= path_len
;
2159 while (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2163 /* grow the buffer and retry */
2164 path_len
= value
.Length
;
2165 if (!(new_ptr
= RtlReAllocateHeap( GetProcessHeap(), 0, ret
, path_len
+ len
* sizeof(WCHAR
) )))
2167 RtlFreeHeap( GetProcessHeap(), 0, ret
);
2168 return STATUS_NO_MEMORY
;
2170 value
.Buffer
= new_ptr
+ (value
.Buffer
- ret
);
2171 value
.MaximumLength
= path_len
;
2174 value
.Buffer
[value
.Length
/ sizeof(WCHAR
)] = 0;
2176 return STATUS_SUCCESS
;
2180 /******************************************************************
2181 * get_dll_load_path_search_flags
2183 static NTSTATUS
get_dll_load_path_search_flags( LPCWSTR module
, DWORD flags
, WCHAR
**path
)
2185 const WCHAR
*image
= NULL
, *mod_end
, *image_end
;
2186 struct dll_dir_entry
*dir
;
2190 if (flags
& LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
)
2191 flags
|= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
2192 LOAD_LIBRARY_SEARCH_USER_DIRS
|
2193 LOAD_LIBRARY_SEARCH_SYSTEM32
);
2195 if (flags
& LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
)
2197 DWORD type
= RtlDetermineDosPathNameType_U( module
);
2198 if (type
!= ABSOLUTE_DRIVE_PATH
&& type
!= ABSOLUTE_PATH
&& type
!= DEVICE_PATH
)
2199 return STATUS_INVALID_PARAMETER
;
2200 mod_end
= get_module_path_end( module
);
2201 len
+= (mod_end
- module
) + 1;
2205 if (flags
& LOAD_LIBRARY_SEARCH_APPLICATION_DIR
)
2207 image
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
2208 image_end
= get_module_path_end( image
);
2209 len
+= (image_end
- image
) + 1;
2212 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2214 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2215 len
+= wcslen( dir
->dir
+ 4 /* \??\ */ ) + 1;
2216 if (dll_directory
.Length
) len
+= dll_directory
.Length
/ sizeof(WCHAR
) + 1;
2219 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) len
+= wcslen( system_dir
);
2221 if ((p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2223 if (module
) p
= append_path( p
, module
, mod_end
- module
);
2224 if (image
) p
= append_path( p
, image
, image_end
- image
);
2225 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2227 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2228 p
= append_path( p
, dir
->dir
+ 4 /* \??\ */, -1 );
2229 p
= append_path( p
, dll_directory
.Buffer
, dll_directory
.Length
/ sizeof(WCHAR
) );
2231 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) wcscpy( p
, system_dir
);
2239 return STATUS_SUCCESS
;
2243 /***********************************************************************
2246 * Open a file for a new dll. Helper for find_dll_file.
2248 static NTSTATUS
open_dll_file( UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2249 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2251 FILE_BASIC_INFORMATION info
;
2252 OBJECT_ATTRIBUTES attr
;
2255 FILE_OBJECTID_BUFFER fid
;
2259 if ((*pwm
= find_fullname_module( nt_name
))) return STATUS_SUCCESS
;
2261 attr
.Length
= sizeof(attr
);
2262 attr
.RootDirectory
= 0;
2263 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2264 attr
.ObjectName
= nt_name
;
2265 attr
.SecurityDescriptor
= NULL
;
2266 attr
.SecurityQualityOfService
= NULL
;
2267 if ((status
= NtOpenFile( &handle
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
,
2268 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2269 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
2271 if (status
!= STATUS_OBJECT_PATH_NOT_FOUND
&&
2272 status
!= STATUS_OBJECT_NAME_NOT_FOUND
&&
2273 !NtQueryAttributesFile( &attr
, &info
))
2275 /* if the file exists but failed to open, report the error */
2278 /* otherwise continue searching */
2279 return STATUS_DLL_NOT_FOUND
;
2282 if (!NtFsControlFile( handle
, 0, NULL
, NULL
, &io
, FSCTL_GET_OBJECT_ID
, NULL
, 0, &fid
, sizeof(fid
) ))
2284 memcpy( id
, fid
.ObjectId
, sizeof(*id
) );
2285 if ((*pwm
= find_fileid_module( id
)))
2287 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name
->Buffer
),
2288 (*pwm
)->ldr
.DllBase
, debugstr_w( (*pwm
)->ldr
.FullDllName
.Buffer
));
2290 return STATUS_SUCCESS
;
2295 status
= NtCreateSection( mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
2296 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
2297 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, handle
);
2300 NtQuerySection( *mapping
, SectionImageInformation
, image_info
, sizeof(*image_info
), NULL
);
2301 if (!is_valid_binary( handle
, image_info
))
2303 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name
), image_info
->Machine
);
2304 status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2305 NtClose( *mapping
);
2313 /******************************************************************************
2314 * load_native_dll (internal)
2316 static NTSTATUS
load_native_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, HANDLE mapping
,
2317 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
2318 DWORD flags
, WINE_MODREF
** pwm
)
2320 void *module
= NULL
;
2322 NTSTATUS status
= NtMapViewOfSection( mapping
, NtCurrentProcess(), &module
, 0, 0, NULL
, &len
,
2323 ViewShare
, 0, PAGE_EXECUTE_READ
);
2325 if (status
== STATUS_IMAGE_NOT_AT_BASE
) status
= STATUS_SUCCESS
;
2327 if (!status
&& !convert_to_pe64( module
, image_info
)) status
= STATUS_INVALID_IMAGE_FORMAT
;
2329 if (!status
) status
= build_module( load_path
, nt_name
, &module
, image_info
, id
, flags
, pwm
);
2330 if (status
&& module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2335 /***********************************************************************
2338 static NTSTATUS
load_so_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
,
2339 DWORD flags
, WINE_MODREF
**pwm
)
2344 UNICODE_STRING win_name
= *nt_name
;
2346 TRACE( "trying %s as so lib\n", debugstr_us(&win_name
) );
2347 if (unix_funcs
->load_so_dll( &win_name
, &module
))
2349 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name
) );
2350 return STATUS_INVALID_IMAGE_FORMAT
;
2353 if ((wm
= get_modref( module
))) /* already loaded */
2355 TRACE( "Found %s at %p for builtin %s\n",
2356 debugstr_w(wm
->ldr
.FullDllName
.Buffer
), wm
->ldr
.DllBase
, debugstr_us(nt_name
) );
2357 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2361 if ((status
= build_builtin_module( load_path
, &win_name
, module
, flags
, &wm
))) return status
;
2362 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name
), module
);
2365 return STATUS_SUCCESS
;
2369 /***********************************************************************
2372 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
,
2373 DWORD flags
, WINE_MODREF
** pwm
)
2375 const WCHAR
*name
, *p
;
2377 void *module
, *unix_entry
= NULL
;
2378 SECTION_IMAGE_INFORMATION image_info
;
2380 /* Fix the name in case we have a full path and extension */
2381 name
= nt_name
->Buffer
;
2382 if ((p
= wcsrchr( name
, '\\' ))) name
= p
+ 1;
2383 if ((p
= wcsrchr( name
, '/' ))) name
= p
+ 1;
2385 TRACE("Trying built-in %s\n", debugstr_w(name
));
2387 status
= unix_funcs
->load_builtin_dll( name
, &module
, &unix_entry
, &image_info
);
2388 if (status
) return status
;
2390 if ((*pwm
= get_modref( module
))) /* already loaded */
2392 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2393 TRACE( "Found %s for %s at %p, count=%d\n",
2394 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(name
),
2395 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2396 return STATUS_SUCCESS
;
2399 TRACE( "loading %s from %s\n", debugstr_w(name
), debugstr_us(nt_name
) );
2400 status
= build_module( load_path
, nt_name
, &module
, &image_info
, NULL
, flags
, pwm
);
2401 if (!status
) (*pwm
)->unix_entry
= unix_entry
;
2402 else if (module
) unix_funcs
->unload_builtin_dll( module
);
2407 /***********************************************************************
2410 * Find the full path (if any) of the dll from the activation context.
2412 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2414 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2416 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2417 ACTCTX_SECTION_KEYED_DATA data
;
2418 UNICODE_STRING nameW
;
2420 SIZE_T needed
, size
= 1024;
2423 RtlInitUnicodeString( &nameW
, libname
);
2424 data
.cbSize
= sizeof(data
);
2425 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2426 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2428 if (status
!= STATUS_SUCCESS
) return status
;
2432 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2434 status
= STATUS_NO_MEMORY
;
2437 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2438 AssemblyDetailedInformationInActivationContext
,
2439 info
, size
, &needed
);
2440 if (status
== STATUS_SUCCESS
) break;
2441 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2442 RtlFreeHeap( GetProcessHeap(), 0, info
);
2444 /* restart with larger buffer */
2447 if (!info
->lpAssemblyManifestPath
)
2449 status
= STATUS_SXS_KEY_NOT_FOUND
;
2453 if ((p
= wcsrchr( info
->lpAssemblyManifestPath
, '\\' )))
2455 DWORD len
, dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2458 if (!dirlen
|| len
<= dirlen
||
2459 RtlCompareUnicodeStrings( p
, dirlen
, info
->lpAssemblyDirectoryName
, dirlen
, TRUE
) ||
2460 wcsicmp( p
+ dirlen
, L
".manifest" ))
2462 /* manifest name does not match directory name, so it's not a global
2463 * windows/winsxs manifest; use the manifest directory name instead */
2464 dirlen
= p
- info
->lpAssemblyManifestPath
;
2465 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2466 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2468 status
= STATUS_NO_MEMORY
;
2471 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2473 wcscpy( p
, libname
);
2478 if (!info
->lpAssemblyDirectoryName
)
2480 status
= STATUS_SXS_KEY_NOT_FOUND
;
2484 needed
= (wcslen(windows_dir
) * sizeof(WCHAR
) +
2485 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2487 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2489 status
= STATUS_NO_MEMORY
;
2492 wcscpy( p
, windows_dir
);
2494 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2495 p
+= ARRAY_SIZE( winsxsW
);
2496 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2497 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2499 wcscpy( p
, libname
);
2501 RtlFreeHeap( GetProcessHeap(), 0, info
);
2502 RtlReleaseActivationContext( data
.hActCtx
);
2507 /***********************************************************************
2510 * Search for dll in the specified paths.
2512 static NTSTATUS
search_dll_file( LPCWSTR paths
, LPCWSTR search
, UNICODE_STRING
*nt_name
,
2513 WINE_MODREF
**pwm
, HANDLE
*mapping
, SECTION_IMAGE_INFORMATION
*image_info
,
2514 struct file_id
*id
)
2517 BOOL found_image
= FALSE
;
2518 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
2519 ULONG len
= wcslen( paths
);
2521 if (len
< wcslen( system_dir
)) len
= wcslen( system_dir
);
2522 len
+= wcslen( search
) + 2;
2524 if (!(name
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2525 return STATUS_NO_MEMORY
;
2529 LPCWSTR ptr
= paths
;
2531 while (*ptr
&& *ptr
!= ';') ptr
++;
2533 if (*ptr
== ';') ptr
++;
2534 memcpy( name
, paths
, len
* sizeof(WCHAR
) );
2535 if (len
&& name
[len
- 1] != '\\') name
[len
++] = '\\';
2536 wcscpy( name
+ len
, search
);
2538 nt_name
->Buffer
= NULL
;
2539 if ((status
= RtlDosPathNameToNtPathName_U_WithStatus( name
, nt_name
, NULL
, NULL
))) goto done
;
2541 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
2542 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) found_image
= TRUE
;
2543 else if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2544 RtlFreeUnicodeString( nt_name
);
2550 /* not found, return file in the system dir to be loaded as builtin */
2551 wcscpy( name
, system_dir
);
2552 wcscat( name
, search
);
2553 if (!RtlDosPathNameToNtPathName_U( name
, nt_name
, NULL
, NULL
)) status
= STATUS_NO_MEMORY
;
2555 else status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2558 RtlFreeHeap( GetProcessHeap(), 0, name
);
2563 /***********************************************************************
2566 * Find the file (or already loaded module) for a given dll name.
2568 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
2569 UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2570 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2572 WCHAR
*ext
, *dllname
;
2574 ULONG wow64_old_value
= 0;
2579 if (default_ext
) /* first append default extension */
2581 if (!(ext
= wcsrchr( libname
, '.')) || wcschr( ext
, '/' ) || wcschr( ext
, '\\'))
2583 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2584 (wcslen(libname
)+wcslen(default_ext
)+1) * sizeof(WCHAR
))))
2585 return STATUS_NO_MEMORY
;
2586 wcscpy( dllname
, libname
);
2587 wcscat( dllname
, default_ext
);
2592 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2593 if (is_wow64
) RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value
);
2595 nt_name
->Buffer
= NULL
;
2597 if (!contains_path( libname
))
2599 WCHAR
*fullname
= NULL
;
2601 status
= find_actctx_dll( libname
, &fullname
);
2602 if (status
== STATUS_SUCCESS
)
2604 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2605 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2606 libname
= dllname
= fullname
;
2610 if (status
!= STATUS_SXS_KEY_NOT_FOUND
) goto done
;
2611 if ((*pwm
= find_basename_module( libname
)) != NULL
)
2613 status
= STATUS_SUCCESS
;
2619 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2620 status
= search_dll_file( load_path
, libname
, nt_name
, pwm
, mapping
, image_info
, id
);
2621 else if (!(status
= RtlDosPathNameToNtPathName_U_WithStatus( libname
, nt_name
, NULL
, NULL
)))
2622 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
2624 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) status
= STATUS_INVALID_IMAGE_FORMAT
;
2627 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2628 if (wow64_old_value
) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value
);
2633 /***********************************************************************
2634 * load_dll (internal)
2636 * Load a PE style module according to the load order.
2637 * The loader_section must be locked while calling this function.
2639 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
2640 DWORD flags
, WINE_MODREF
** pwm
)
2642 enum loadorder loadorder
;
2643 WINE_MODREF
*main_exe
;
2644 UNICODE_STRING nt_name
;
2647 SECTION_IMAGE_INFORMATION image_info
;
2650 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2652 nts
= find_dll_file( load_path
, libname
, default_ext
, &nt_name
, pwm
, &mapping
, &image_info
, &id
);
2654 if (*pwm
) /* found already loaded module */
2656 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2658 TRACE("Found %s for %s at %p, count=%d\n",
2659 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2660 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2661 RtlFreeUnicodeString( &nt_name
);
2662 return STATUS_SUCCESS
;
2665 if (nts
&& nts
!= STATUS_DLL_NOT_FOUND
&& nts
!= STATUS_INVALID_IMAGE_NOT_MZ
) goto done
;
2667 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2668 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, &nt_name
);
2672 case STATUS_INVALID_IMAGE_NOT_MZ
: /* not in PE format, maybe it's a .so file */
2676 case LO_NATIVE_BUILTIN
:
2678 case LO_BUILTIN_NATIVE
:
2680 if (!load_so_dll( load_path
, &nt_name
, flags
, pwm
)) nts
= STATUS_SUCCESS
;
2683 nts
= STATUS_DLL_NOT_FOUND
;
2688 case STATUS_SUCCESS
: /* valid PE file */
2689 if (image_info
.u
.ImageFlags
& IMAGE_FLAGS_WineBuiltin
)
2693 case LO_NATIVE_BUILTIN
:
2695 case LO_BUILTIN_NATIVE
:
2697 nts
= load_builtin_dll( load_path
, &nt_name
, flags
, pwm
);
2698 if (nts
== STATUS_DLL_NOT_FOUND
)
2699 nts
= load_native_dll( load_path
, &nt_name
, mapping
, &image_info
, &id
, flags
, pwm
);
2702 nts
= STATUS_DLL_NOT_FOUND
;
2707 if (!(image_info
.u
.ImageFlags
& IMAGE_FLAGS_WineFakeDll
))
2712 case LO_NATIVE_BUILTIN
:
2713 nts
= load_native_dll( load_path
, &nt_name
, mapping
, &image_info
, &id
, flags
, pwm
);
2716 nts
= load_builtin_dll( load_path
, &nt_name
, flags
, pwm
);
2718 case LO_BUILTIN_NATIVE
:
2720 nts
= load_builtin_dll( load_path
, &nt_name
, flags
, pwm
);
2721 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2722 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2724 /* stub-only dll, try native */
2725 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_us(&nt_name
) );
2726 LdrUnloadDll( (*pwm
)->ldr
.DllBase
);
2727 nts
= STATUS_DLL_NOT_FOUND
;
2729 if (nts
== STATUS_DLL_NOT_FOUND
)
2730 nts
= load_native_dll( load_path
, &nt_name
, mapping
, &image_info
, &id
, flags
, pwm
);
2733 nts
= STATUS_DLL_NOT_FOUND
;
2738 TRACE( "%s is a fake Wine dll\n", debugstr_us(&nt_name
) );
2741 case STATUS_DLL_NOT_FOUND
: /* no file found, try builtin */
2744 case LO_NATIVE_BUILTIN
:
2746 case LO_BUILTIN_NATIVE
:
2748 nts
= load_builtin_dll( load_path
, &nt_name
, flags
, pwm
);
2751 nts
= STATUS_DLL_NOT_FOUND
;
2758 if (nts
== STATUS_SUCCESS
)
2759 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name
), (*pwm
)->ldr
.DllBase
);
2761 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2763 if (mapping
) NtClose( mapping
);
2764 RtlFreeUnicodeString( &nt_name
);
2769 /***********************************************************************
2770 * __wine_init_unix_lib
2772 NTSTATUS __cdecl
__wine_init_unix_lib( HMODULE module
, DWORD reason
, const void *ptr_in
, void *ptr_out
)
2775 NTSTATUS ret
= STATUS_DLL_NOT_FOUND
;
2777 RtlEnterCriticalSection( &loader_section
);
2779 if ((wm
= get_modref( module
)))
2781 NTSTATUS (CDECL
*init_func
)( HMODULE
, DWORD
, const void *, void * ) = wm
->unix_entry
;
2782 if (init_func
) ret
= init_func( module
, reason
, ptr_in
, ptr_out
);
2784 else ret
= STATUS_INVALID_HANDLE
;
2786 RtlLeaveCriticalSection( &loader_section
);
2791 /******************************************************************
2792 * LdrLoadDll (NTDLL.@)
2794 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2795 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2800 RtlEnterCriticalSection( &loader_section
);
2802 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2803 nts
= load_dll( path_name
, libname
->Buffer
, L
".dll", flags
, &wm
);
2805 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2807 nts
= process_attach( wm
, NULL
);
2808 if (nts
!= STATUS_SUCCESS
)
2810 LdrUnloadDll(wm
->ldr
.DllBase
);
2814 *hModule
= (wm
) ? wm
->ldr
.DllBase
: NULL
;
2816 RtlLeaveCriticalSection( &loader_section
);
2821 /******************************************************************
2822 * LdrGetDllHandle (NTDLL.@)
2824 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2827 UNICODE_STRING nt_name
;
2830 SECTION_IMAGE_INFORMATION image_info
;
2833 RtlEnterCriticalSection( &loader_section
);
2835 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2837 status
= find_dll_file( load_path
, name
->Buffer
, L
".dll", &nt_name
, &wm
, &mapping
, &image_info
, &id
);
2839 if (wm
) *base
= wm
->ldr
.DllBase
;
2842 if (status
== STATUS_SUCCESS
) NtClose( mapping
);
2843 status
= STATUS_DLL_NOT_FOUND
;
2845 RtlFreeUnicodeString( &nt_name
);
2847 RtlLeaveCriticalSection( &loader_section
);
2848 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2853 /******************************************************************
2854 * LdrAddRefDll (NTDLL.@)
2856 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2858 NTSTATUS ret
= STATUS_SUCCESS
;
2861 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2863 RtlEnterCriticalSection( &loader_section
);
2865 if ((wm
= get_modref( module
)))
2867 if (flags
& LDR_ADDREF_DLL_PIN
)
2868 wm
->ldr
.LoadCount
= -1;
2870 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2871 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2873 else ret
= STATUS_INVALID_PARAMETER
;
2875 RtlLeaveCriticalSection( &loader_section
);
2880 /***********************************************************************
2881 * LdrProcessRelocationBlock (NTDLL.@)
2883 * Apply relocations to a given page of a mapped PE image.
2885 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2886 USHORT
*relocs
, INT_PTR delta
)
2890 USHORT offset
= *relocs
& 0xfff;
2891 int type
= *relocs
>> 12;
2894 case IMAGE_REL_BASED_ABSOLUTE
:
2896 case IMAGE_REL_BASED_HIGH
:
2897 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2899 case IMAGE_REL_BASED_LOW
:
2900 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2902 case IMAGE_REL_BASED_HIGHLOW
:
2903 *(int *)((char *)page
+ offset
) += delta
;
2906 case IMAGE_REL_BASED_DIR64
:
2907 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2909 #elif defined(__arm__)
2910 case IMAGE_REL_BASED_THUMB_MOV32
:
2912 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2913 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2914 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2917 if ((inst
& 0x8000fbf0) != 0x0000f240)
2918 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2920 imm16
+= LOWORD(delta
);
2921 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2922 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2923 ((imm16
>> 12) & 0x000f) +
2924 ((imm16
<< 20) & 0x70000000) +
2925 ((imm16
<< 16) & 0xff0000);
2929 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2930 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2931 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2933 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2934 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2938 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2939 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2940 ((imm16
>> 1) & 0x0400) +
2941 ((imm16
>> 12) & 0x000f) +
2942 ((imm16
<< 20) & 0x70000000) +
2943 ((imm16
<< 16) & 0xff0000);
2949 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2954 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2958 /******************************************************************
2959 * LdrQueryProcessModuleInformation
2962 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2963 ULONG buf_size
, ULONG
* req_size
)
2965 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2966 ULONG size
= sizeof(ULONG
);
2967 NTSTATUS nts
= STATUS_SUCCESS
;
2970 PLIST_ENTRY mark
, entry
;
2971 LDR_DATA_TABLE_ENTRY
*mod
;
2974 smi
->ModulesCount
= 0;
2976 RtlEnterCriticalSection( &loader_section
);
2977 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2978 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2980 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2981 size
+= sizeof(*sm
);
2982 if (size
<= buf_size
)
2984 sm
->Section
= 0; /* FIXME */
2985 sm
->MappedBaseAddress
= mod
->DllBase
;
2986 sm
->ImageBaseAddress
= mod
->DllBase
;
2987 sm
->ImageSize
= mod
->SizeOfImage
;
2988 sm
->Flags
= mod
->Flags
;
2989 sm
->LoadOrderIndex
= id
++;
2990 sm
->InitOrderIndex
= 0; /* FIXME */
2991 sm
->LoadCount
= mod
->LoadCount
;
2993 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2994 str
.Buffer
= (char*)sm
->Name
;
2995 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2996 ptr
= strrchr(str
.Buffer
, '\\');
2997 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2999 smi
->ModulesCount
++;
3002 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
3004 RtlLeaveCriticalSection( &loader_section
);
3006 if (req_size
) *req_size
= size
;
3012 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
3018 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3020 RtlInitUnicodeString( &str
, name
);
3022 size
= sizeof(buffer
) - sizeof(WCHAR
);
3023 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
3026 if (info
->Type
!= REG_DWORD
)
3028 buffer
[size
/ sizeof(WCHAR
)] = 0;
3029 *value
= wcstoul( (WCHAR
*)info
->Data
, 0, 16 );
3031 else memcpy( value
, info
->Data
, sizeof(*value
) );
3035 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
3036 void *data
, ULONG in_size
, ULONG
*out_size
)
3042 KEY_VALUE_PARTIAL_INFORMATION
*info
;
3043 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
3045 RtlInitUnicodeString( &str
, name
);
3047 size
= info_size
+ in_size
;
3048 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
3049 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3050 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
3051 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
3053 if (out_size
) *out_size
= info
->DataLength
;
3054 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
3056 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
3061 /******************************************************************
3062 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3064 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
3065 void *data
, ULONG in_size
, ULONG
*out_size
)
3067 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
3068 'S','o','f','t','w','a','r','e','\\',
3069 'M','i','c','r','o','s','o','f','t','\\',
3070 'W','i','n','d','o','w','s',' ','N','T','\\',
3071 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3072 'I','m','a','g','e',' ','F','i','l','e',' ',
3073 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3074 WCHAR path
[MAX_PATH
+ ARRAY_SIZE( optionsW
)];
3075 OBJECT_ATTRIBUTES attr
;
3076 UNICODE_STRING name_str
;
3082 attr
.Length
= sizeof(attr
);
3083 attr
.RootDirectory
= 0;
3084 attr
.ObjectName
= &name_str
;
3085 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3086 attr
.SecurityDescriptor
= NULL
;
3087 attr
.SecurityQualityOfService
= NULL
;
3089 p
= key
->Buffer
+ key
->Length
/ sizeof(WCHAR
);
3090 while (p
> key
->Buffer
&& p
[-1] != '\\') p
--;
3091 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
3092 name_str
.Buffer
= path
;
3093 name_str
.Length
= sizeof(optionsW
) + len
;
3094 name_str
.MaximumLength
= name_str
.Length
;
3095 memcpy( path
, optionsW
, sizeof(optionsW
) );
3096 memcpy( path
+ ARRAY_SIZE( optionsW
), p
, len
);
3097 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
3099 if (type
== REG_DWORD
)
3101 if (out_size
) *out_size
= sizeof(ULONG
);
3102 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
3103 else status
= STATUS_BUFFER_OVERFLOW
;
3105 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
3112 /******************************************************************
3113 * RtlDllShutdownInProgress (NTDLL.@)
3115 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
3117 return process_detaching
;
3120 /****************************************************************************
3121 * LdrResolveDelayLoadedAPI (NTDLL.@)
3123 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
3124 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
,
3125 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook
,
3126 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
3128 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
3129 DELAYLOAD_INFO delayinfo
;
3137 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
3139 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
3140 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
3141 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
3142 name
= get_rva(base
, desc
->DllNameRVA
);
3147 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
3149 nts
= STATUS_NO_MEMORY
;
3152 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
3153 RtlFreeUnicodeString(&mod
);
3157 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3158 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
3161 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3164 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
3165 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
3169 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
3174 delayinfo
.Size
= sizeof(delayinfo
);
3175 delayinfo
.DelayloadDescriptor
= desc
;
3176 delayinfo
.ThunkAddress
= addr
;
3177 delayinfo
.TargetDllName
= name
;
3178 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
3179 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
3180 delayinfo
.TargetModuleBase
= *phmod
;
3181 delayinfo
.Unused
= NULL
;
3182 delayinfo
.LastError
= nts
;
3185 return dllhook(4, &delayinfo
);
3187 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3189 DWORD_PTR ord
= LOWORD(pINT
[id
].u1
.Ordinal
);
3190 return syshook(name
, (const char *)ord
);
3194 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3195 return syshook(name
, (const char *)iibn
->Name
);
3199 /******************************************************************
3200 * LdrShutdownProcess (NTDLL.@)
3203 void WINAPI
LdrShutdownProcess(void)
3205 BOOL detaching
= process_detaching
;
3209 process_detaching
= TRUE
;
3211 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3217 /******************************************************************
3218 * RtlExitUserProcess (NTDLL.@)
3220 void WINAPI
RtlExitUserProcess( DWORD status
)
3222 RtlEnterCriticalSection( &loader_section
);
3223 RtlAcquirePebLock();
3224 NtTerminateProcess( 0, status
);
3225 LdrShutdownProcess();
3226 for (;;) NtTerminateProcess( GetCurrentProcess(), status
);
3229 /******************************************************************
3230 * LdrShutdownThread (NTDLL.@)
3233 void WINAPI
LdrShutdownThread(void)
3235 PLIST_ENTRY mark
, entry
;
3236 LDR_DATA_TABLE_ENTRY
*mod
;
3243 /* don't do any detach calls if process is exiting */
3244 if (process_detaching
) return;
3246 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3248 RtlEnterCriticalSection( &loader_section
);
3249 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3251 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3252 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
3254 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
3255 InInitializationOrderLinks
);
3256 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
3258 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
3261 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
3262 DLL_THREAD_DETACH
, NULL
);
3265 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_DETACH
);
3267 RtlAcquirePebLock();
3268 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
3269 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
3271 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
3272 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
3274 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 2 );
3275 NtCurrentTeb()->FlsSlots
= NULL
;
3276 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
3277 NtCurrentTeb()->TlsExpansionSlots
= NULL
;
3278 RtlReleasePebLock();
3280 RtlLeaveCriticalSection( &loader_section
);
3284 /***********************************************************************
3288 static void free_modref( WINE_MODREF
*wm
)
3290 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
3291 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
3292 if (wm
->ldr
.InInitializationOrderLinks
.Flink
)
3293 RemoveEntryList(&wm
->ldr
.InInitializationOrderLinks
);
3295 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
3296 if (!TRACE_ON(module
))
3297 TRACE_(loaddll
)("Unloaded module %s : %s\n",
3298 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
3299 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
3301 SERVER_START_REQ( unload_dll
)
3303 req
->base
= wine_server_client_ptr( wm
->ldr
.DllBase
);
3304 wine_server_call( req
);
3308 free_tls_slot( &wm
->ldr
);
3309 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
3310 unix_funcs
->unload_builtin_dll( wm
->ldr
.DllBase
);
3311 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.DllBase
);
3312 if (cached_modref
== wm
) cached_modref
= NULL
;
3313 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
3314 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
3315 RtlFreeHeap( GetProcessHeap(), 0, wm
);
3318 /***********************************************************************
3319 * MODULE_FlushModrefs
3321 * Remove all unused modrefs and call the internal unloading routines
3322 * for the library type.
3324 * The loader_section must be locked while calling this function.
3326 static void MODULE_FlushModrefs(void)
3328 PLIST_ENTRY mark
, entry
, prev
;
3329 LDR_DATA_TABLE_ENTRY
*mod
;
3332 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3333 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3335 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
3336 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3337 prev
= entry
->Blink
;
3338 if (!mod
->LoadCount
) free_modref( wm
);
3341 /* check load order list too for modules that haven't been initialized yet */
3342 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3343 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3345 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3346 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3347 prev
= entry
->Blink
;
3348 if (!mod
->LoadCount
) free_modref( wm
);
3352 /***********************************************************************
3353 * MODULE_DecRefCount
3355 * The loader_section must be locked while calling this function.
3357 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
3361 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
3364 if ( wm
->ldr
.LoadCount
<= 0 )
3367 --wm
->ldr
.LoadCount
;
3368 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3370 if ( wm
->ldr
.LoadCount
== 0 )
3372 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
3374 for ( i
= 0; i
< wm
->nDeps
; i
++ )
3376 MODULE_DecRefCount( wm
->deps
[i
] );
3378 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
3380 module_push_unload_trace( &wm
->ldr
);
3384 /******************************************************************
3385 * LdrUnloadDll (NTDLL.@)
3389 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
3392 NTSTATUS retv
= STATUS_SUCCESS
;
3394 if (process_detaching
) return retv
;
3396 TRACE("(%p)\n", hModule
);
3398 RtlEnterCriticalSection( &loader_section
);
3401 if ((wm
= get_modref( hModule
)) != NULL
)
3403 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
3405 /* Recursively decrement reference counts */
3406 MODULE_DecRefCount( wm
);
3408 /* Call process detach notifications */
3409 if ( free_lib_count
<= 1 )
3412 MODULE_FlushModrefs();
3418 retv
= STATUS_DLL_NOT_FOUND
;
3422 RtlLeaveCriticalSection( &loader_section
);
3427 /***********************************************************************
3428 * RtlImageNtHeader (NTDLL.@)
3430 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
3432 IMAGE_NT_HEADERS
*ret
;
3436 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
3439 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
3441 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
3442 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
3453 /***********************************************************************
3454 * process_breakpoint
3456 * Trigger a debug breakpoint if the process is being debugged.
3458 static void process_breakpoint(void)
3462 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort
, &port
, sizeof(port
), NULL
);
3477 /******************************************************************
3478 * LdrInitializeThunk (NTDLL.@)
3480 * Attach to all the loaded dlls.
3481 * If this is the first time, perform the full process initialization.
3483 void WINAPI
LdrInitializeThunk( CONTEXT
*context
, ULONG_PTR unknown2
, ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3485 static int attach_done
;
3491 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3494 entry
= (void **)&context
->Eax
;
3495 #elif defined(__x86_64__)
3496 entry
= (void **)&context
->Rcx
;
3497 #elif defined(__arm__)
3498 entry
= (void **)&context
->R0
;
3499 #elif defined(__aarch64__)
3500 entry
= (void **)&context
->u
.s
.X0
;
3503 if (process_detaching
) NtTerminateThread( GetCurrentThread(), 0 );
3505 RtlEnterCriticalSection( &loader_section
);
3507 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3510 if (!imports_fixup_done
)
3513 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
3514 status
= fixup_imports_ilonly( wm
, load_path
, entry
);
3516 status
= fixup_imports( wm
, load_path
);
3520 ERR( "Importing dlls for %s failed, status %x\n",
3521 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3522 NtTerminateProcess( GetCurrentProcess(), status
);
3524 imports_fixup_done
= TRUE
;
3527 RtlAcquirePebLock();
3528 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
3529 RtlReleasePebLock();
3531 NtCurrentTeb()->FlsSlots
= fls_alloc_data();
3533 if (!attach_done
) /* first time around */
3536 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3538 ERR( "TLS init failed when loading %s, status %x\n",
3539 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3540 NtTerminateProcess( GetCurrentProcess(), status
);
3542 wm
->ldr
.LoadCount
= -1;
3543 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
; /* don't try to attach again */
3544 if (wm
->ldr
.ActivationContext
)
3545 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
3547 for (i
= 0; i
< wm
->nDeps
; i
++)
3549 if (!wm
->deps
[i
]) continue;
3550 if ((status
= process_attach( wm
->deps
[i
], context
)) != STATUS_SUCCESS
)
3552 if (last_failed_modref
)
3553 ERR( "%s failed to initialize, aborting\n",
3554 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3555 ERR( "Initializing dlls for %s failed, status %x\n",
3556 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3557 NtTerminateProcess( GetCurrentProcess(), status
);
3560 attach_implicitly_loaded_dlls( context
);
3561 unix_funcs
->virtual_release_address_space();
3562 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_PROCESS_ATTACH
);
3563 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) unix_funcs
->init_builtin_dll( wm
->ldr
.DllBase
);
3564 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
3565 process_breakpoint();
3569 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3570 NtTerminateThread( GetCurrentThread(), status
);
3572 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_ATTACH
);
3575 RtlLeaveCriticalSection( &loader_section
);
3576 signal_start_thread( context
);
3580 /***********************************************************************
3581 * load_global_options
3583 static void load_global_options(void)
3585 OBJECT_ATTRIBUTES attr
;
3586 UNICODE_STRING name_str
;
3590 attr
.Length
= sizeof(attr
);
3591 attr
.RootDirectory
= 0;
3592 attr
.ObjectName
= &name_str
;
3593 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3594 attr
.SecurityDescriptor
= NULL
;
3595 attr
.SecurityQualityOfService
= NULL
;
3596 RtlInitUnicodeString( &name_str
, L
"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3598 if (!NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))
3600 query_dword_option( hkey
, L
"GlobalFlag", &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3601 query_dword_option( hkey
, L
"SafeProcessSearchMode", &path_safe_mode
);
3602 query_dword_option( hkey
, L
"SafeDllSearchMode", &dll_safe_mode
);
3604 if (!query_dword_option( hkey
, L
"CriticalSectionTimeout", &value
))
3605 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3607 if (!query_dword_option( hkey
, L
"HeapSegmentReserve", &value
))
3608 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3610 if (!query_dword_option( hkey
, L
"HeapSegmentCommit", &value
))
3611 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3613 if (!query_dword_option( hkey
, L
"HeapDeCommitTotalFreeThreshold", &value
))
3614 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3616 if (!query_dword_option( hkey
, L
"HeapDeCommitFreeBlockThreshold", &value
))
3617 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3621 LdrQueryImageFileExecutionOptions( &NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
,
3622 L
"GlobalFlag", REG_DWORD
, &NtCurrentTeb()->Peb
->NtGlobalFlag
,
3623 sizeof(DWORD
), NULL
);
3624 heap_set_debug_flags( GetProcessHeap() );
3628 /***********************************************************************
3629 * RtlImageDirectoryEntryToData (NTDLL.@)
3631 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3633 const IMAGE_NT_HEADERS
*nt
;
3636 if ((ULONG_PTR
)module
& 1) image
= FALSE
; /* mapped as data file */
3637 module
= (HMODULE
)((ULONG_PTR
)module
& ~3);
3638 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3639 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3641 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3643 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3644 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3645 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3646 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3648 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3650 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3652 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3653 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3654 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3655 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3659 /* not mapped as image, need to find the section containing the virtual address */
3660 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3664 /***********************************************************************
3665 * RtlImageRvaToSection (NTDLL.@)
3667 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3668 HMODULE module
, DWORD rva
)
3671 const IMAGE_SECTION_HEADER
*sec
;
3673 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3674 nt
->FileHeader
.SizeOfOptionalHeader
);
3675 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3677 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3678 return (PIMAGE_SECTION_HEADER
)sec
;
3684 /***********************************************************************
3685 * RtlImageRvaToVa (NTDLL.@)
3687 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3688 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3690 IMAGE_SECTION_HEADER
*sec
;
3692 if (section
&& *section
) /* try this section first */
3695 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3698 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3700 if (section
) *section
= sec
;
3701 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3705 /***********************************************************************
3706 * RtlPcToFileHeader (NTDLL.@)
3708 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3710 LDR_DATA_TABLE_ENTRY
*module
;
3713 RtlEnterCriticalSection( &loader_section
);
3714 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->DllBase
;
3715 RtlLeaveCriticalSection( &loader_section
);
3721 /****************************************************************************
3722 * LdrGetDllDirectory (NTDLL.@)
3724 NTSTATUS WINAPI
LdrGetDllDirectory( UNICODE_STRING
*dir
)
3726 NTSTATUS status
= STATUS_SUCCESS
;
3728 RtlEnterCriticalSection( &dlldir_section
);
3729 dir
->Length
= dll_directory
.Length
+ sizeof(WCHAR
);
3730 if (dir
->MaximumLength
>= dir
->Length
) RtlCopyUnicodeString( dir
, &dll_directory
);
3733 status
= STATUS_BUFFER_TOO_SMALL
;
3734 if (dir
->MaximumLength
) dir
->Buffer
[0] = 0;
3736 RtlLeaveCriticalSection( &dlldir_section
);
3741 /****************************************************************************
3742 * LdrSetDllDirectory (NTDLL.@)
3744 NTSTATUS WINAPI
LdrSetDllDirectory( const UNICODE_STRING
*dir
)
3746 NTSTATUS status
= STATUS_SUCCESS
;
3749 if (!dir
->Buffer
) RtlInitUnicodeString( &new, NULL
);
3750 else if ((status
= RtlDuplicateUnicodeString( 1, dir
, &new ))) return status
;
3752 RtlEnterCriticalSection( &dlldir_section
);
3753 RtlFreeUnicodeString( &dll_directory
);
3754 dll_directory
= new;
3755 RtlLeaveCriticalSection( &dlldir_section
);
3760 /****************************************************************************
3761 * LdrAddDllDirectory (NTDLL.@)
3763 NTSTATUS WINAPI
LdrAddDllDirectory( const UNICODE_STRING
*dir
, void **cookie
)
3765 FILE_BASIC_INFORMATION info
;
3766 UNICODE_STRING nt_name
;
3768 OBJECT_ATTRIBUTES attr
;
3770 struct dll_dir_entry
*ptr
;
3771 DOS_PATHNAME_TYPE type
= RtlDetermineDosPathNameType_U( dir
->Buffer
);
3773 if (type
!= ABSOLUTE_PATH
&& type
!= ABSOLUTE_DRIVE_PATH
)
3774 return STATUS_INVALID_PARAMETER
;
3776 status
= RtlDosPathNameToNtPathName_U_WithStatus( dir
->Buffer
, &nt_name
, NULL
, NULL
);
3777 if (status
) return status
;
3778 len
= nt_name
.Length
/ sizeof(WCHAR
);
3779 if (!(ptr
= RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry
, dir
[++len
] ))))
3780 return STATUS_NO_MEMORY
;
3781 memcpy( ptr
->dir
, nt_name
.Buffer
, len
* sizeof(WCHAR
) );
3783 attr
.Length
= sizeof(attr
);
3784 attr
.RootDirectory
= 0;
3785 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3786 attr
.ObjectName
= &nt_name
;
3787 attr
.SecurityDescriptor
= NULL
;
3788 attr
.SecurityQualityOfService
= NULL
;
3789 status
= NtQueryAttributesFile( &attr
, &info
);
3790 RtlFreeUnicodeString( &nt_name
);
3794 TRACE( "%s\n", debugstr_w( ptr
->dir
));
3795 RtlEnterCriticalSection( &dlldir_section
);
3796 list_add_head( &dll_dir_list
, &ptr
->entry
);
3797 RtlLeaveCriticalSection( &dlldir_section
);
3800 else RtlFreeHeap( GetProcessHeap(), 0, ptr
);
3805 /****************************************************************************
3806 * LdrRemoveDllDirectory (NTDLL.@)
3808 NTSTATUS WINAPI
LdrRemoveDllDirectory( void *cookie
)
3810 struct dll_dir_entry
*ptr
= cookie
;
3812 TRACE( "%s\n", debugstr_w( ptr
->dir
));
3814 RtlEnterCriticalSection( &dlldir_section
);
3815 list_remove( &ptr
->entry
);
3816 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
3817 RtlLeaveCriticalSection( &dlldir_section
);
3818 return STATUS_SUCCESS
;
3822 /*************************************************************************
3823 * LdrSetDefaultDllDirectories (NTDLL.@)
3825 NTSTATUS WINAPI
LdrSetDefaultDllDirectories( ULONG flags
)
3827 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
3828 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
3829 LOAD_LIBRARY_SEARCH_USER_DIRS
|
3830 LOAD_LIBRARY_SEARCH_SYSTEM32
|
3831 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
3833 if (!flags
|| (flags
& ~load_library_search_flags
)) return STATUS_INVALID_PARAMETER
;
3834 default_search_flags
= flags
;
3835 return STATUS_SUCCESS
;
3839 /******************************************************************
3840 * LdrGetDllPath (NTDLL.@)
3842 NTSTATUS WINAPI
LdrGetDllPath( PCWSTR module
, ULONG flags
, PWSTR
*path
, PWSTR
*unknown
)
3845 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
|
3846 LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
3847 LOAD_LIBRARY_SEARCH_USER_DIRS
|
3848 LOAD_LIBRARY_SEARCH_SYSTEM32
|
3849 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
3851 if (flags
& LOAD_WITH_ALTERED_SEARCH_PATH
)
3853 if (flags
& load_library_search_flags
) return STATUS_INVALID_PARAMETER
;
3854 if (default_search_flags
) flags
|= default_search_flags
| LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
;
3856 else if (!(flags
& load_library_search_flags
)) flags
|= default_search_flags
;
3858 RtlEnterCriticalSection( &dlldir_section
);
3860 if (flags
& load_library_search_flags
)
3862 status
= get_dll_load_path_search_flags( module
, flags
, path
);
3866 const WCHAR
*dlldir
= dll_directory
.Length
? dll_directory
.Buffer
: NULL
;
3867 if (!(flags
& LOAD_WITH_ALTERED_SEARCH_PATH
))
3868 module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
3869 status
= get_dll_load_path( module
, dlldir
, dll_safe_mode
, path
);
3872 RtlLeaveCriticalSection( &dlldir_section
);
3878 /*************************************************************************
3879 * RtlSetSearchPathMode (NTDLL.@)
3881 NTSTATUS WINAPI
RtlSetSearchPathMode( ULONG flags
)
3887 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
:
3890 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE
:
3893 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
| BASE_SEARCH_PATH_PERMANENT
:
3894 InterlockedExchange( (int *)&path_safe_mode
, 2 );
3895 return STATUS_SUCCESS
;
3897 return STATUS_INVALID_PARAMETER
;
3902 int prev
= path_safe_mode
;
3903 if (prev
== 2) break; /* permanently set */
3904 if (InterlockedCompareExchange( (int *)&path_safe_mode
, val
, prev
) == prev
) return STATUS_SUCCESS
;
3906 return STATUS_ACCESS_DENIED
;
3910 /******************************************************************
3911 * RtlGetExePath (NTDLL.@)
3913 NTSTATUS WINAPI
RtlGetExePath( PCWSTR name
, PWSTR
*path
)
3915 const WCHAR
*dlldir
= L
".";
3916 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
3918 /* same check as NeedCurrentDirectoryForExePathW */
3919 if (!wcschr( name
, '\\' ))
3921 UNICODE_STRING name
, value
= { 0 };
3923 RtlInitUnicodeString( &name
, L
"NoDefaultCurrentDirectoryInExePath" );
3924 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) != STATUS_VARIABLE_NOT_FOUND
)
3927 return get_dll_load_path( module
, dlldir
, FALSE
, path
);
3931 /******************************************************************
3932 * RtlGetSearchPath (NTDLL.@)
3934 NTSTATUS WINAPI
RtlGetSearchPath( PWSTR
*path
)
3936 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
3937 return get_dll_load_path( module
, NULL
, path_safe_mode
, path
);
3941 /******************************************************************
3942 * RtlReleasePath (NTDLL.@)
3944 void WINAPI
RtlReleasePath( PWSTR path
)
3946 RtlFreeHeap( GetProcessHeap(), 0, path
);
3950 /******************************************************************
3953 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3955 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3960 /***********************************************************************
3963 static void restart_winevdm( RTL_USER_PROCESS_PARAMETERS
*params
)
3966 WCHAR
*appname
, *cmdline
;
3968 len
= wcslen(system_dir
) + wcslen(L
"winevdm.exe") + 1;
3969 appname
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
3970 wcscpy( appname
, (is_win64
|| is_wow64
) ? syswow64_dir
: system_dir
);
3971 wcscat( appname
, L
"winevdm.exe" );
3973 len
+= 16 + wcslen(params
->ImagePathName
.Buffer
) + wcslen(params
->CommandLine
.Buffer
);
3974 cmdline
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
3975 swprintf( cmdline
, len
, L
"%s --app-name \"%s\" %s",
3976 appname
, params
->ImagePathName
.Buffer
, params
->CommandLine
.Buffer
);
3978 RtlInitUnicodeString( ¶ms
->ImagePathName
, appname
);
3979 RtlInitUnicodeString( ¶ms
->CommandLine
, cmdline
);
3983 /***********************************************************************
3986 static NTSTATUS
process_init(void)
3988 RTL_USER_PROCESS_PARAMETERS
*params
;
3991 ANSI_STRING func_name
;
3992 UNICODE_STRING nt_name
;
3993 MEMORY_BASIC_INFORMATION meminfo
;
3995 TEB
*teb
= NtCurrentTeb();
3996 PEB
*peb
= teb
->Peb
;
3998 peb
->LdrData
= &ldr
;
3999 peb
->FastPebLock
= &peb_lock
;
4000 peb
->TlsBitmap
= &tls_bitmap
;
4001 peb
->TlsExpansionBitmap
= &tls_expansion_bitmap
;
4002 peb
->LoaderLock
= &loader_section
;
4003 peb
->OSMajorVersion
= 5;
4004 peb
->OSMinorVersion
= 1;
4005 peb
->OSBuildNumber
= 0xA28;
4006 peb
->OSPlatformId
= VER_PLATFORM_WIN32_NT
;
4008 peb
->ProcessHeap
= RtlCreateHeap( HEAP_GROWABLE
, NULL
, 0, 0, NULL
, NULL
);
4010 RtlInitializeBitMap( &tls_bitmap
, peb
->TlsBitmapBits
, sizeof(peb
->TlsBitmapBits
) * 8 );
4011 RtlInitializeBitMap( &tls_expansion_bitmap
, peb
->TlsExpansionBitmapBits
,
4012 sizeof(peb
->TlsExpansionBitmapBits
) * 8 );
4013 RtlSetBits( peb
->TlsBitmap
, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
4014 init_global_fls_data();
4016 InitializeListHead( &ldr
.InLoadOrderModuleList
);
4017 InitializeListHead( &ldr
.InMemoryOrderModuleList
);
4018 InitializeListHead( &ldr
.InInitializationOrderModuleList
);
4021 is_wow64
= !!NtCurrentTeb64();
4024 init_unix_codepage();
4026 init_user_process_params();
4027 params
= peb
->ProcessParameters
;
4029 load_global_options();
4032 if (!(status
= load_dll( params
->DllPath
.Buffer
, params
->ImagePathName
.Buffer
, NULL
,
4033 DONT_RESOLVE_DLL_REFERENCES
, &wm
)))
4035 peb
->ImageBaseAddress
= wm
->ldr
.DllBase
;
4036 TRACE( "main exe loaded %s at %p\n", debugstr_us(¶ms
->ImagePathName
), peb
->ImageBaseAddress
);
4037 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
4039 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
4040 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT
);
4047 case STATUS_INVALID_IMAGE_NOT_MZ
:
4049 WCHAR
*p
= wcsrchr( params
->ImagePathName
.Buffer
, '.' );
4050 if (p
&& (!wcsicmp( p
, L
".com" ) || !wcsicmp( p
, L
".pif" )))
4052 restart_winevdm( params
);
4053 status
= STATUS_INVALID_IMAGE_WIN_16
;
4057 case STATUS_INVALID_IMAGE_WIN_16
:
4058 case STATUS_INVALID_IMAGE_NE_FORMAT
:
4059 case STATUS_INVALID_IMAGE_PROTECT
:
4060 restart_winevdm( params
);
4062 case STATUS_CONFLICTING_ADDRESSES
:
4063 case STATUS_NO_MEMORY
:
4064 case STATUS_INVALID_IMAGE_FORMAT
:
4066 case STATUS_INVALID_IMAGE_WIN_64
:
4067 ERR( "%s 64-bit application not supported in 32-bit prefix\n",
4068 debugstr_us(¶ms
->ImagePathName
) );
4070 case STATUS_DLL_NOT_FOUND
:
4071 ERR( "%s not found\n", debugstr_us(¶ms
->ImagePathName
) );
4074 ERR( "failed to load %s, error %x\n", debugstr_us(¶ms
->ImagePathName
), status
);
4077 NtTerminateProcess( GetCurrentProcess(), status
);
4081 if (NtCurrentTeb64())
4083 PEB64
*peb64
= UlongToPtr( NtCurrentTeb64()->Peb
);
4084 peb64
->ImageBaseAddress
= PtrToUlong( peb
->ImageBaseAddress
);
4085 peb64
->OSMajorVersion
= peb
->OSMajorVersion
;
4086 peb64
->OSMinorVersion
= peb
->OSMinorVersion
;
4087 peb64
->OSBuildNumber
= peb
->OSBuildNumber
;
4088 peb64
->OSPlatformId
= peb
->OSPlatformId
;
4089 peb64
->SessionId
= peb
->SessionId
;
4093 RtlInitUnicodeString( &nt_name
, L
"\\??\\C:\\windows\\system32\\ntdll.dll" );
4094 NtQueryVirtualMemory( GetCurrentProcess(), process_init
, MemoryBasicInformation
,
4095 &meminfo
, sizeof(meminfo
), NULL
);
4096 status
= build_builtin_module( params
->DllPath
.Buffer
, &nt_name
, meminfo
.AllocationBase
, 0, &wm
);
4099 if ((status
= load_dll( params
->DllPath
.Buffer
, L
"C:\\windows\\system32\\kernel32.dll",
4100 NULL
, 0, &wm
)) != STATUS_SUCCESS
)
4102 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
4103 NtTerminateProcess( GetCurrentProcess(), status
);
4105 RtlInitAnsiString( &func_name
, "BaseThreadInitThunk" );
4106 if ((status
= LdrGetProcedureAddress( wm
->ldr
.DllBase
, &func_name
,
4107 0, (void **)&pBaseThreadInitThunk
)) != STATUS_SUCCESS
)
4109 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status
);
4110 NtTerminateProcess( GetCurrentProcess(), status
);
4113 init_locale( wm
->ldr
.DllBase
);
4115 RtlCreateUserStack( 0, 0, 0, 0x10000, 0x10000, &stack
);
4116 teb
->Tib
.StackBase
= stack
.StackBase
;
4117 teb
->Tib
.StackLimit
= stack
.StackLimit
;
4118 teb
->DeallocationStack
= stack
.DeallocationStack
;
4119 return STATUS_SUCCESS
;
4122 /***********************************************************************
4123 * __wine_set_unix_funcs
4125 NTSTATUS CDECL
__wine_set_unix_funcs( int version
, const struct unix_funcs
*funcs
)
4127 assert( version
== NTDLL_UNIXLIB_VERSION
);
4129 return process_init();