4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
27 #define WIN32_NO_STATUS
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
34 #include "delayloadhandler.h"
36 #include "wine/exception.h"
37 #include "wine/debug.h"
38 #include "wine/list.h"
39 #include "ntdll_misc.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(module
);
43 WINE_DECLARE_DEBUG_CHANNEL(relay
);
44 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
45 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
46 WINE_DECLARE_DEBUG_CHANNEL(imports
);
49 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
51 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
52 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
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 BOOL is_wow64
= FALSE
;
73 /* system search path */
74 static const WCHAR system_path
[] = L
"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
76 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
77 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
78 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
79 static ULONG path_safe_mode
; /* path mode set by RtlSetSearchPathMode */
80 static ULONG dll_safe_mode
= 1; /* dll search mode */
81 static UNICODE_STRING dll_directory
; /* extra path for LdrSetDllDirectory */
82 static DWORD default_search_flags
; /* default flags set by LdrSetDefaultDllDirectories */
83 static WCHAR
*default_load_path
; /* default dll search path */
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
[] =
115 /* internal representation of loaded modules */
116 typedef struct _wine_modref
118 LDR_DATA_TABLE_ENTRY ldr
;
122 struct _wine_modref
**deps
;
125 static UINT tls_module_count
; /* number of modules with TLS directory */
126 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
127 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
129 static RTL_CRITICAL_SECTION loader_section
;
130 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
132 0, 0, &loader_section
,
133 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
134 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
136 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
138 static CRITICAL_SECTION dlldir_section
;
139 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug
=
141 0, 0, &dlldir_section
,
142 { &dlldir_critsect_debug
.ProcessLocksList
, &dlldir_critsect_debug
.ProcessLocksList
},
143 0, 0, { (DWORD_PTR
)(__FILE__
": dlldir_section") }
145 static CRITICAL_SECTION dlldir_section
= { &dlldir_critsect_debug
, -1, 0, 0, 0, 0 };
147 static RTL_CRITICAL_SECTION peb_lock
;
148 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug
=
151 { &peb_critsect_debug
.ProcessLocksList
, &peb_critsect_debug
.ProcessLocksList
},
152 0, 0, { (DWORD_PTR
)(__FILE__
": peb_lock") }
154 static RTL_CRITICAL_SECTION peb_lock
= { &peb_critsect_debug
, -1, 0, 0, 0, 0 };
156 static PEB_LDR_DATA ldr
= { sizeof(ldr
), TRUE
};
157 static RTL_BITMAP tls_bitmap
;
158 static RTL_BITMAP tls_expansion_bitmap
;
160 static WINE_MODREF
*cached_modref
;
161 static WINE_MODREF
*current_modref
;
162 static WINE_MODREF
*last_failed_modref
;
164 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
165 DWORD flags
, WINE_MODREF
** pwm
);
166 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
167 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
168 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
169 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
170 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
172 /* convert PE image VirtualAddress to Real Address */
173 static inline void *get_rva( HMODULE module
, DWORD va
)
175 return (void *)((char *)module
+ va
);
178 /* check whether the file name contains a path */
179 static inline BOOL
contains_path( LPCWSTR name
)
181 return ((*name
&& (name
[1] == ':')) || wcschr(name
, '/') || wcschr(name
, '\\'));
184 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
186 typedef struct _RTL_UNLOAD_EVENT_TRACE
194 } RTL_UNLOAD_EVENT_TRACE
, *PRTL_UNLOAD_EVENT_TRACE
;
196 static RTL_UNLOAD_EVENT_TRACE unload_traces
[RTL_UNLOAD_EVENT_TRACE_NUMBER
];
197 static RTL_UNLOAD_EVENT_TRACE
*unload_trace_ptr
;
198 static unsigned int unload_trace_seq
;
200 static void module_push_unload_trace( const LDR_DATA_TABLE_ENTRY
*ldr
)
202 RTL_UNLOAD_EVENT_TRACE
*ptr
= &unload_traces
[unload_trace_seq
];
203 unsigned int len
= min(sizeof(ptr
->ImageName
) - sizeof(WCHAR
), ldr
->BaseDllName
.Length
);
205 ptr
->BaseAddress
= ldr
->DllBase
;
206 ptr
->SizeOfImage
= ldr
->SizeOfImage
;
207 ptr
->Sequence
= unload_trace_seq
;
208 ptr
->TimeDateStamp
= ldr
->TimeDateStamp
;
209 ptr
->CheckSum
= ldr
->CheckSum
;
210 memcpy(ptr
->ImageName
, ldr
->BaseDllName
.Buffer
, len
);
211 ptr
->ImageName
[len
/ sizeof(*ptr
->ImageName
)] = 0;
213 unload_trace_seq
= (unload_trace_seq
+ 1) % ARRAY_SIZE(unload_traces
);
214 unload_trace_ptr
= unload_traces
;
217 /*********************************************************************
218 * RtlGetUnloadEventTrace [NTDLL.@]
220 RTL_UNLOAD_EVENT_TRACE
* WINAPI
RtlGetUnloadEventTrace(void)
222 return unload_traces
;
225 /*********************************************************************
226 * RtlGetUnloadEventTraceEx [NTDLL.@]
228 void WINAPI
RtlGetUnloadEventTraceEx(ULONG
**size
, ULONG
**count
, void **trace
)
230 static unsigned int element_size
= sizeof(*unload_traces
);
231 static unsigned int element_count
= ARRAY_SIZE(unload_traces
);
233 *size
= &element_size
;
234 *count
= &element_count
;
235 *trace
= &unload_trace_ptr
;
238 /*************************************************************************
239 * call_dll_entry_point
241 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
242 * their entry point, so we need a small asm wrapper. Testing indicates
243 * that only modifying esi leads to a crash, so use this one to backup
244 * ebp while running the dll entry proc.
247 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
248 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
250 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
251 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
253 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
255 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
257 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
259 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
261 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
265 "movl 8(%ebp),%eax\n\t"
268 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
269 "leal -12(%ebp),%esp\n\t"
271 __ASM_CFI(".cfi_same_value %edi\n\t")
273 __ASM_CFI(".cfi_same_value %esi\n\t")
275 __ASM_CFI(".cfi_same_value %ebx\n\t")
277 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
278 __ASM_CFI(".cfi_same_value %ebp\n\t")
281 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
282 UINT reason
, void *reserved
)
284 return proc( module
, reason
, reserved
);
286 #endif /* __i386__ */
289 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
290 /*************************************************************************
293 * Entry point for stub functions.
295 static void WINAPI
stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
297 EXCEPTION_RECORD rec
;
299 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
300 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
301 rec
.ExceptionRecord
= NULL
;
302 rec
.ExceptionAddress
= ret_addr
;
303 rec
.NumberParameters
= 2;
304 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
305 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
306 for (;;) RtlRaiseException( &rec
);
310 #include "pshpack1.h"
314 BYTE pushl1
; /* pushl $name */
316 BYTE pushl2
; /* pushl $dll */
318 BYTE call
; /* call stub_entry_point */
321 #elif defined(__arm__)
324 DWORD ldr_r0
; /* ldr r0, $dll */
325 DWORD ldr_r1
; /* ldr r1, $name */
326 DWORD mov_r2_lr
; /* mov r2, lr */
327 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
332 #elif defined(__aarch64__)
335 DWORD ldr_x0
; /* ldr x0, $dll */
336 DWORD ldr_x1
; /* ldr x1, $name */
337 DWORD mov_x2_lr
; /* mov x2, lr */
338 DWORD ldr_x16
; /* ldr x16, $entry */
339 DWORD br_x16
; /* br x16 */
347 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
349 BYTE movq_rsi
[2]; /* movq $name,%rsi */
351 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
352 BYTE movq_rax
[2]; /* movq $entry, %rax */
354 BYTE jmpq_rax
[2]; /* jmp %rax */
359 /*************************************************************************
362 * Allocate a stub entry point.
364 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
366 #define MAX_SIZE 65536
367 static struct stub
*stubs
;
368 static unsigned int nb_stubs
;
371 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
375 SIZE_T size
= MAX_SIZE
;
376 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
377 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
380 stub
= &stubs
[nb_stubs
++];
382 stub
->pushl1
= 0x68; /* pushl $name */
384 stub
->pushl2
= 0x68; /* pushl $dll */
386 stub
->call
= 0xe8; /* call stub_entry_point */
387 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
388 #elif defined(__arm__)
389 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
390 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
391 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
392 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
395 stub
->entry
= stub_entry_point
;
396 #elif defined(__aarch64__)
397 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
398 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
399 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
400 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
401 stub
->br_x16
= 0xd61f0200; /* br x16 */
404 stub
->entry
= stub_entry_point
;
406 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rcx */
407 stub
->movq_rdi
[1] = 0xb9;
409 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rdx */
410 stub
->movq_rsi
[1] = 0xba;
412 stub
->movq_rsp_rdx
[0] = 0x4c; /* movq (%rsp),%r8 */
413 stub
->movq_rsp_rdx
[1] = 0x8b;
414 stub
->movq_rsp_rdx
[2] = 0x04;
415 stub
->movq_rsp_rdx
[3] = 0x24;
416 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
417 stub
->movq_rax
[1] = 0xb8;
418 stub
->entry
= stub_entry_point
;
419 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
420 stub
->jmpq_rax
[1] = 0xe0;
422 return (ULONG_PTR
)stub
;
426 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
427 #endif /* __i386__ */
429 /* call ldr notifications */
430 static void call_ldr_notifications( ULONG reason
, LDR_DATA_TABLE_ENTRY
*module
)
432 struct ldr_notification
*notify
, *notify_next
;
433 LDR_DLL_NOTIFICATION_DATA data
;
435 data
.Loaded
.Flags
= 0;
436 data
.Loaded
.FullDllName
= &module
->FullDllName
;
437 data
.Loaded
.BaseDllName
= &module
->BaseDllName
;
438 data
.Loaded
.DllBase
= module
->DllBase
;
439 data
.Loaded
.SizeOfImage
= module
->SizeOfImage
;
441 LIST_FOR_EACH_ENTRY_SAFE( notify
, notify_next
, &ldr_notifications
, struct ldr_notification
, entry
)
443 TRACE_(relay
)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
444 notify
->callback
, reason
, &data
, notify
->context
);
446 notify
->callback(reason
, &data
, notify
->context
);
448 TRACE_(relay
)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
449 notify
->callback
, reason
, &data
, notify
->context
);
453 /*************************************************************************
456 * Looks for the referenced HMODULE in the current process
457 * The loader_section must be locked while calling this function.
459 static WINE_MODREF
*get_modref( HMODULE hmod
)
461 PLIST_ENTRY mark
, entry
;
462 PLDR_DATA_TABLE_ENTRY mod
;
464 if (cached_modref
&& cached_modref
->ldr
.DllBase
== hmod
) return cached_modref
;
466 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
467 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
469 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
470 if (mod
->DllBase
== hmod
)
471 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
477 /**********************************************************************
478 * find_basename_module
480 * Find a module from its base name.
481 * The loader_section must be locked while calling this function
483 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
485 PLIST_ENTRY mark
, entry
;
486 UNICODE_STRING name_str
;
488 RtlInitUnicodeString( &name_str
, name
);
490 if (cached_modref
&& RtlEqualUnicodeString( &name_str
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
491 return cached_modref
;
493 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
494 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
496 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
497 if (RtlEqualUnicodeString( &name_str
, &mod
->BaseDllName
, TRUE
))
499 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
500 return cached_modref
;
507 /**********************************************************************
508 * find_fullname_module
510 * Find a module from its full path name.
511 * The loader_section must be locked while calling this function
513 static WINE_MODREF
*find_fullname_module( const UNICODE_STRING
*nt_name
)
515 PLIST_ENTRY mark
, entry
;
516 UNICODE_STRING name
= *nt_name
;
518 if (name
.Length
<= 4 * sizeof(WCHAR
)) return NULL
;
519 name
.Length
-= 4 * sizeof(WCHAR
); /* for \??\ prefix */
522 if (cached_modref
&& RtlEqualUnicodeString( &name
, &cached_modref
->ldr
.FullDllName
, TRUE
))
523 return cached_modref
;
525 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
526 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
528 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
529 if (RtlEqualUnicodeString( &name
, &mod
->FullDllName
, TRUE
))
531 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
532 return cached_modref
;
539 /**********************************************************************
542 * Find a module from its file id.
543 * The loader_section must be locked while calling this function
545 static WINE_MODREF
*find_fileid_module( const struct file_id
*id
)
547 LIST_ENTRY
*mark
, *entry
;
549 if (cached_modref
&& !memcmp( &cached_modref
->id
, id
, sizeof(*id
) )) return cached_modref
;
551 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
552 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
554 LDR_DATA_TABLE_ENTRY
*mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
555 WINE_MODREF
*wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
557 if (!memcmp( &wm
->id
, id
, sizeof(*id
) ))
567 /*************************************************************************
570 static WINE_MODREF
**grow_module_deps( WINE_MODREF
*wm
, int count
)
575 deps
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, wm
->deps
,
576 (wm
->alloc_deps
+ count
) * sizeof(*deps
) );
578 deps
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, count
* sizeof(*deps
) );
583 wm
->alloc_deps
+= count
;
588 /*************************************************************************
589 * find_forwarded_export
591 * Find the final function pointer for a forwarded function.
592 * The loader_section must be locked while calling this function.
594 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
596 const IMAGE_EXPORT_DIRECTORY
*exports
;
599 WCHAR buffer
[32], *mod_name
= buffer
;
600 const char *end
= strrchr(forward
, '.');
603 if (!end
) return NULL
;
604 if ((end
- forward
) * sizeof(WCHAR
) > sizeof(buffer
) - sizeof(L
".dll"))
606 if (!(mod_name
= RtlAllocateHeap( GetProcessHeap(), 0,
607 (end
- forward
+ sizeof(L
".dll")) * sizeof(WCHAR
) )))
610 ascii_to_unicode( mod_name
, forward
, end
- forward
);
611 mod_name
[end
- forward
] = 0;
612 if (!wcschr( mod_name
, '.' ))
613 memcpy( mod_name
+ (end
- forward
), L
".dll", sizeof(L
".dll") );
615 if (!(wm
= find_basename_module( mod_name
)))
617 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
618 if (load_dll( load_path
, mod_name
, L
".dll", 0, &wm
) == STATUS_SUCCESS
&&
619 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
621 if (!imports_fixup_done
&& current_modref
)
623 WINE_MODREF
**deps
= grow_module_deps( current_modref
, 1 );
624 if (deps
) deps
[current_modref
->nDeps
++] = wm
;
626 else if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
628 LdrUnloadDll( wm
->ldr
.DllBase
);
635 if (mod_name
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, mod_name
);
636 ERR( "module not found for forward '%s' used by %s\n",
637 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
641 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
642 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
644 const char *name
= end
+ 1;
646 if (*name
== '#') { /* ordinal */
647 proc
= find_ordinal_export( wm
->ldr
.DllBase
, exports
, exp_size
,
648 atoi(name
+1) - exports
->Base
, load_path
);
650 proc
= find_named_export( wm
->ldr
.DllBase
, exports
, exp_size
, name
, -1, load_path
);
655 ERR("function not found for forward '%s' used by %s."
656 " If you are using builtin %s, try using the native one instead.\n",
657 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
658 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
660 if (mod_name
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, mod_name
);
665 /*************************************************************************
666 * find_ordinal_export
668 * Find an exported function by ordinal.
669 * The exports base must have been subtracted from the ordinal already.
670 * The loader_section must be locked while calling this function.
672 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
673 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
676 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
678 if (ordinal
>= exports
->NumberOfFunctions
)
680 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
683 if (!functions
[ordinal
]) return NULL
;
685 proc
= get_rva( module
, functions
[ordinal
] );
687 /* if the address falls into the export dir, it's a forward */
688 if (((const char *)proc
>= (const char *)exports
) &&
689 ((const char *)proc
< (const char *)exports
+ exp_size
))
690 return find_forwarded_export( module
, (const char *)proc
, load_path
);
694 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
695 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
699 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
700 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
706 /*************************************************************************
709 * Find an exported function by name.
710 * The loader_section must be locked while calling this function.
712 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
713 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
715 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
716 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
717 int min
= 0, max
= exports
->NumberOfNames
- 1;
719 /* first check the hint */
720 if (hint
>= 0 && hint
<= max
)
722 char *ename
= get_rva( module
, names
[hint
] );
723 if (!strcmp( ename
, name
))
724 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
727 /* then do a binary search */
730 int res
, pos
= (min
+ max
) / 2;
731 char *ename
= get_rva( module
, names
[pos
] );
732 if (!(res
= strcmp( ename
, name
)))
733 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
734 if (res
> 0) max
= pos
- 1;
742 /*************************************************************************
745 * Import the dll specified by the given import descriptor.
746 * The loader_section must be locked while calling this function.
748 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
753 const IMAGE_EXPORT_DIRECTORY
*exports
;
755 const IMAGE_THUNK_DATA
*import_list
;
756 IMAGE_THUNK_DATA
*thunk_list
;
758 const char *name
= get_rva( module
, descr
->Name
);
759 DWORD len
= strlen(name
);
761 SIZE_T protect_size
= 0;
764 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
765 if (descr
->u
.OriginalFirstThunk
)
766 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
768 import_list
= thunk_list
;
770 if (!import_list
->u1
.Ordinal
)
772 WARN( "Skipping unused import %s\n", name
);
777 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
779 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
781 ascii_to_unicode( buffer
, name
, len
);
783 status
= load_dll( load_path
, buffer
, L
".dll", 0, &wmImp
);
785 else /* need to allocate a larger buffer */
787 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
788 if (!ptr
) return FALSE
;
789 ascii_to_unicode( ptr
, name
, len
);
791 status
= load_dll( load_path
, ptr
, L
".dll", 0, &wmImp
);
792 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
797 if (status
== STATUS_DLL_NOT_FOUND
)
798 ERR("Library %s (which is needed by %s) not found\n",
799 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
801 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
802 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
806 /* unprotect the import address table since it can be located in
807 * readonly section */
808 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
809 protect_base
= thunk_list
;
810 protect_size
*= sizeof(*thunk_list
);
811 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
812 &protect_size
, PAGE_READWRITE
, &protect_old
);
814 imp_mod
= wmImp
->ldr
.DllBase
;
815 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
819 /* set all imported function to deadbeef */
820 while (import_list
->u1
.Ordinal
)
822 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
824 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
825 WARN("No implementation for %s.%d", name
, ordinal
);
826 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
830 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
831 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
832 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
834 WARN(" imported from %s, allocating stub %p\n",
835 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
836 (void *)thunk_list
->u1
.Function
);
843 while (import_list
->u1
.Ordinal
)
845 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
847 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
849 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
850 ordinal
- exports
->Base
, load_path
);
851 if (!thunk_list
->u1
.Function
)
853 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
854 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
855 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
856 (void *)thunk_list
->u1
.Function
);
858 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
860 else /* import by name */
862 IMAGE_IMPORT_BY_NAME
*pe_name
;
863 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
864 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
865 (const char*)pe_name
->Name
,
866 pe_name
->Hint
, load_path
);
867 if (!thunk_list
->u1
.Function
)
869 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
870 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
871 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
872 (void *)thunk_list
->u1
.Function
);
874 TRACE_(imports
)("--- %s %s.%d = %p\n",
875 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
882 /* restore old protection of the import address table */
883 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
889 /***********************************************************************
890 * create_module_activation_context
892 static NTSTATUS
create_module_activation_context( LDR_DATA_TABLE_ENTRY
*module
)
895 LDR_RESOURCE_INFO info
;
896 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
898 info
.Type
= RT_MANIFEST
;
899 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
901 if (!(status
= LdrFindResource_U( module
->DllBase
, &info
, 3, &entry
)))
904 ctx
.cbSize
= sizeof(ctx
);
906 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
907 ctx
.hModule
= module
->DllBase
;
908 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
909 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
915 /*************************************************************************
916 * is_dll_native_subsystem
918 * Check if dll is a proper native driver.
919 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
920 * while being perfectly normal DLLs. This heuristic should catch such breakages.
922 static BOOL
is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY
*mod
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
924 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
928 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
929 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
930 if (mod
->Flags
& LDR_WINE_INTERNAL
) return TRUE
;
932 if ((imports
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
,
933 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
935 for (i
= 0; imports
[i
].Name
; i
++)
937 const char *name
= get_rva( mod
->DllBase
, imports
[i
].Name
);
938 DWORD len
= strlen(name
);
939 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
940 ascii_to_unicode( buffer
, name
, len
+ 1 );
941 if (!wcsicmp( buffer
, L
"ntdll.dll" ) || !wcsicmp( buffer
, L
"kernel32.dll" ))
943 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
951 /*************************************************************************
954 * Allocate a TLS slot for a newly-loaded module.
955 * The loader_section must be locked while calling this function.
957 static SHORT
alloc_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
959 const IMAGE_TLS_DIRECTORY
*dir
;
964 if (!(dir
= RtlImageDirectoryEntryToData( mod
->DllBase
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
967 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
968 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
970 for (i
= 0; i
< tls_module_count
; i
++)
972 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
973 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
977 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->DllBase
,
978 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
979 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
981 if (i
== tls_module_count
)
983 UINT new_count
= max( 32, tls_module_count
* 2 );
986 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
988 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
989 new_count
* sizeof(*tls_dirs
) );
990 if (!new_ptr
) return -1;
992 /* resize the pointer block in all running threads */
993 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
995 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
996 void **old
= teb
->ThreadLocalStoragePointer
;
997 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
1000 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
1001 teb
->ThreadLocalStoragePointer
= new;
1002 #ifdef __x86_64__ /* macOS-specific hack */
1003 if (teb
->Reserved5
[0]) ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
1005 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
1006 /* FIXME: can't free old block here, should be freed at thread exit */
1010 tls_module_count
= new_count
;
1013 /* allocate the data block in all running threads */
1014 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1016 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
1018 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
1019 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
1020 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
1022 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1023 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
1025 RtlFreeHeap( GetProcessHeap(), 0,
1026 InterlockedExchangePointer( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
1029 *(DWORD
*)dir
->AddressOfIndex
= i
;
1035 /*************************************************************************
1038 * Free the module TLS slot on unload.
1039 * The loader_section must be locked while calling this function.
1041 static void free_tls_slot( LDR_DATA_TABLE_ENTRY
*mod
)
1043 ULONG i
= (USHORT
)mod
->TlsIndex
;
1045 if (mod
->TlsIndex
== -1) return;
1046 assert( i
< tls_module_count
);
1047 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
1051 /****************************************************************
1052 * fixup_imports_ilonly
1054 * Fixup imports for an IL-only module. All we do is import mscoree.
1055 * The loader_section must be locked while calling this function.
1057 static NTSTATUS
fixup_imports_ilonly( WINE_MODREF
*wm
, LPCWSTR load_path
, void **entry
)
1059 IMAGE_EXPORT_DIRECTORY
*exports
;
1063 WINE_MODREF
*prev
, *imp
;
1065 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1066 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1068 if (!grow_module_deps( wm
, 1 )) return STATUS_NO_MEMORY
;
1071 prev
= current_modref
;
1072 current_modref
= wm
;
1073 if (!(status
= load_dll( load_path
, L
"mscoree.dll", NULL
, 0, &imp
))) wm
->deps
[0] = imp
;
1074 current_modref
= prev
;
1077 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1078 debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1082 TRACE( "loaded mscoree for %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1084 if ((exports
= RtlImageDirectoryEntryToData( imp
->ldr
.DllBase
, TRUE
,
1085 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1087 const char *name
= (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) ? "_CorDllMain" : "_CorExeMain";
1088 proc
= find_named_export( imp
->ldr
.DllBase
, exports
, exp_size
, name
, -1, load_path
);
1090 if (!proc
) return STATUS_PROCEDURE_NOT_FOUND
;
1092 return STATUS_SUCCESS
;
1096 /****************************************************************
1099 * Fixup all imports of a given module.
1100 * The loader_section must be locked while calling this function.
1102 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
1104 int i
, dep
, nb_imports
;
1105 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1106 WINE_MODREF
*prev
, *imp
;
1111 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1112 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1114 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
1116 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.DllBase
, TRUE
,
1117 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1118 return STATUS_SUCCESS
;
1121 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
1123 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
1124 if (!grow_module_deps( wm
, nb_imports
)) return STATUS_NO_MEMORY
;
1126 if (!create_module_activation_context( &wm
->ldr
))
1127 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1129 /* load the imported modules. They are automatically
1130 * added to the modref list of the process.
1132 prev
= current_modref
;
1133 current_modref
= wm
;
1134 status
= STATUS_SUCCESS
;
1135 for (i
= 0; i
< nb_imports
; i
++)
1139 if (!import_dll( wm
->ldr
.DllBase
, &imports
[i
], load_path
, &imp
))
1142 status
= STATUS_DLL_NOT_FOUND
;
1144 wm
->deps
[dep
] = imp
;
1146 current_modref
= prev
;
1147 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1152 /*************************************************************************
1155 * Allocate a WINE_MODREF structure and add it to the process list
1156 * The loader_section must be locked while calling this function.
1158 static WINE_MODREF
*alloc_module( HMODULE hModule
, const UNICODE_STRING
*nt_name
, BOOL builtin
)
1163 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
1165 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) ))) return NULL
;
1167 wm
->ldr
.DllBase
= hModule
;
1168 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
1169 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
| (builtin
? LDR_WINE_INTERNAL
: 0);
1170 wm
->ldr
.TlsIndex
= -1;
1171 wm
->ldr
.LoadCount
= 1;
1172 wm
->ldr
.CheckSum
= nt
->OptionalHeader
.CheckSum
;
1173 wm
->ldr
.TimeDateStamp
= nt
->FileHeader
.TimeDateStamp
;
1175 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, nt_name
->Length
- 3 * sizeof(WCHAR
) )))
1177 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1180 memcpy( buffer
, nt_name
->Buffer
+ 4 /* \??\ prefix */, nt_name
->Length
- 4 * sizeof(WCHAR
) );
1181 buffer
[nt_name
->Length
/sizeof(WCHAR
) - 4] = 0;
1182 if ((p
= wcsrchr( buffer
, '\\' ))) p
++;
1184 RtlInitUnicodeString( &wm
->ldr
.FullDllName
, buffer
);
1185 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
1187 if (!is_dll_native_subsystem( &wm
->ldr
, nt
, p
))
1189 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
1190 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
1191 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
1192 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1195 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
1196 &wm
->ldr
.InLoadOrderLinks
);
1197 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
1198 &wm
->ldr
.InMemoryOrderLinks
);
1199 /* wait until init is called for inserting into InInitializationOrderModuleList */
1201 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
1203 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
1204 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1205 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1211 /*************************************************************************
1214 * Allocate the per-thread structure for module TLS storage.
1216 static NTSTATUS
alloc_thread_tls(void)
1221 if (!tls_module_count
) return STATUS_SUCCESS
;
1223 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1224 tls_module_count
* sizeof(*pointers
) )))
1225 return STATUS_NO_MEMORY
;
1227 for (i
= 0; i
< tls_module_count
; i
++)
1229 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1232 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1233 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1235 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1237 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1238 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1239 return STATUS_NO_MEMORY
;
1241 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1242 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1244 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1245 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1247 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1248 #ifdef __x86_64__ /* macOS-specific hack */
1249 if (NtCurrentTeb()->Reserved5
[0])
1250 ((TEB
*)NtCurrentTeb()->Reserved5
[0])->ThreadLocalStoragePointer
= pointers
;
1252 return STATUS_SUCCESS
;
1256 /*************************************************************************
1257 * call_tls_callbacks
1259 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1261 const IMAGE_TLS_DIRECTORY
*dir
;
1262 const PIMAGE_TLS_CALLBACK
*callback
;
1265 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1266 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1268 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1270 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1271 *callback
, module
, reason_names
[reason
] );
1274 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1278 TRACE_(relay
)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1279 GetExceptionCode(), callback
, module
, reason_names
[reason
] );
1283 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1284 *callback
, module
, reason_names
[reason
] );
1288 /*************************************************************************
1291 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1294 NTSTATUS status
= STATUS_SUCCESS
;
1295 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1296 void *module
= wm
->ldr
.DllBase
;
1299 /* Skip calls for modules loaded with special load flags */
1301 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1302 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, reason
);
1303 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
&& reason
== DLL_PROCESS_ATTACH
)
1304 unix_funcs
->init_builtin_dll( wm
->ldr
.DllBase
);
1305 if (!entry
) return STATUS_SUCCESS
;
1307 if (TRACE_ON(relay
))
1309 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1310 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1311 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1312 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1313 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1315 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1316 reason_names
[reason
], lpReserved
);
1320 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1322 status
= STATUS_DLL_INIT_FAILED
;
1326 status
= GetExceptionCode();
1327 TRACE_(relay
)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1328 status
, entry
, module
, reason_names
[reason
], lpReserved
);
1332 /* The state of the module list may have changed due to the call
1333 to the dll. We cannot assume that this module has not been
1335 if (TRACE_ON(relay
))
1336 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1337 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1339 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1345 /*************************************************************************
1348 * Send the process attach notification to all DLLs the given module
1349 * depends on (recursively). This is somewhat complicated due to the fact that
1351 * - we have to respect the module dependencies, i.e. modules implicitly
1352 * referenced by another module have to be initialized before the module
1353 * itself can be initialized
1355 * - the initialization routine of a DLL can itself call LoadLibrary,
1356 * thereby introducing a whole new set of dependencies (even involving
1357 * the 'old' modules) at any time during the whole process
1359 * (Note that this routine can be recursively entered not only directly
1360 * from itself, but also via LoadLibrary from one of the called initialization
1363 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1364 * the process *detach* notifications to be sent in the correct order.
1365 * This must not only take into account module dependencies, but also
1366 * 'hidden' dependencies created by modules calling LoadLibrary in their
1367 * attach notification routine.
1369 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1370 * list after the attach notification has returned. This implies that the
1371 * detach notifications are called in the reverse of the sequence the attach
1372 * notifications *returned*.
1374 * The loader_section must be locked while calling this function.
1376 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1378 NTSTATUS status
= STATUS_SUCCESS
;
1382 if (process_detaching
) return status
;
1384 /* prevent infinite recursion in case of cyclical dependencies */
1385 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1386 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1389 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1391 /* Tag current MODREF to prevent recursive loop */
1392 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1393 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1394 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1396 /* Recursively attach all DLLs this one depends on */
1397 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1399 if (!wm
->deps
[i
]) continue;
1400 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1403 if (!wm
->ldr
.InInitializationOrderLinks
.Flink
)
1404 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1405 &wm
->ldr
.InInitializationOrderLinks
);
1407 /* Call DLL entry point */
1408 if (status
== STATUS_SUCCESS
)
1410 WINE_MODREF
*prev
= current_modref
;
1411 current_modref
= wm
;
1413 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED
, &wm
->ldr
);
1414 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1415 if (status
== STATUS_SUCCESS
)
1417 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1421 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1422 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, &wm
->ldr
);
1424 /* point to the name so LdrInitializeThunk can print it */
1425 last_failed_modref
= wm
;
1426 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1428 current_modref
= prev
;
1431 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1432 /* Remove recursion flag */
1433 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1435 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1440 /*************************************************************************
1443 * Send DLL process detach notifications. See the comment about calling
1444 * sequence at process_attach.
1446 static void process_detach(void)
1448 PLIST_ENTRY mark
, entry
;
1449 PLDR_DATA_TABLE_ENTRY mod
;
1451 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1454 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1456 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1457 InInitializationOrderLinks
);
1458 /* Check whether to detach this DLL */
1459 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1461 if ( mod
->LoadCount
&& !process_detaching
)
1464 /* Call detach notification */
1465 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1466 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1467 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1468 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, mod
);
1470 /* Restart at head of WINE_MODREF list, as entries might have
1471 been added and/or removed while performing the call ... */
1474 } while (entry
!= mark
);
1477 /*************************************************************************
1480 * Send DLL thread attach notifications. These are sent in the
1481 * reverse sequence of process detach notification.
1482 * The loader_section must be locked while calling this function.
1484 static void thread_attach(void)
1486 PLIST_ENTRY mark
, entry
;
1487 PLDR_DATA_TABLE_ENTRY mod
;
1489 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1490 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1492 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
1493 InInitializationOrderLinks
);
1494 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1496 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1499 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1503 /******************************************************************
1504 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1507 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1510 NTSTATUS ret
= STATUS_SUCCESS
;
1512 RtlEnterCriticalSection( &loader_section
);
1514 wm
= get_modref( hModule
);
1515 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1516 ret
= STATUS_DLL_NOT_FOUND
;
1518 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1520 RtlLeaveCriticalSection( &loader_section
);
1525 /******************************************************************
1526 * LdrFindEntryForAddress (NTDLL.@)
1528 * The loader_section must be locked while calling this function
1530 NTSTATUS WINAPI
LdrFindEntryForAddress( const void *addr
, PLDR_DATA_TABLE_ENTRY
*pmod
)
1532 PLIST_ENTRY mark
, entry
;
1533 PLDR_DATA_TABLE_ENTRY mod
;
1535 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1536 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1538 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
1539 if (mod
->DllBase
<= addr
&&
1540 (const char *)addr
< (char*)mod
->DllBase
+ mod
->SizeOfImage
)
1543 return STATUS_SUCCESS
;
1546 return STATUS_NO_MORE_ENTRIES
;
1549 /******************************************************************
1550 * LdrEnumerateLoadedModules (NTDLL.@)
1552 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1554 LIST_ENTRY
*mark
, *entry
;
1555 LDR_DATA_TABLE_ENTRY
*mod
;
1556 BOOLEAN stop
= FALSE
;
1558 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1560 if (unknown
|| !callback
)
1561 return STATUS_INVALID_PARAMETER
;
1563 RtlEnterCriticalSection( &loader_section
);
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 callback( mod
, context
, &stop
);
1573 RtlLeaveCriticalSection( &loader_section
);
1574 return STATUS_SUCCESS
;
1577 /******************************************************************
1578 * LdrRegisterDllNotification (NTDLL.@)
1580 NTSTATUS WINAPI
LdrRegisterDllNotification(ULONG flags
, PLDR_DLL_NOTIFICATION_FUNCTION callback
,
1581 void *context
, void **cookie
)
1583 struct ldr_notification
*notify
;
1585 TRACE( "(%x, %p, %p, %p)\n", flags
, callback
, context
, cookie
);
1587 if (!callback
|| !cookie
)
1588 return STATUS_INVALID_PARAMETER
;
1591 FIXME( "ignoring flags %x\n", flags
);
1593 notify
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify
) );
1594 if (!notify
) return STATUS_NO_MEMORY
;
1595 notify
->callback
= callback
;
1596 notify
->context
= context
;
1598 RtlEnterCriticalSection( &loader_section
);
1599 list_add_tail( &ldr_notifications
, ¬ify
->entry
);
1600 RtlLeaveCriticalSection( &loader_section
);
1603 return STATUS_SUCCESS
;
1606 /******************************************************************
1607 * LdrUnregisterDllNotification (NTDLL.@)
1609 NTSTATUS WINAPI
LdrUnregisterDllNotification( void *cookie
)
1611 struct ldr_notification
*notify
= cookie
;
1613 TRACE( "(%p)\n", cookie
);
1615 if (!notify
) return STATUS_INVALID_PARAMETER
;
1617 RtlEnterCriticalSection( &loader_section
);
1618 list_remove( ¬ify
->entry
);
1619 RtlLeaveCriticalSection( &loader_section
);
1621 RtlFreeHeap( GetProcessHeap(), 0, notify
);
1622 return STATUS_SUCCESS
;
1625 /******************************************************************
1626 * LdrLockLoaderLock (NTDLL.@)
1628 * Note: some flags are not implemented.
1629 * Flag 0x01 is used to raise exceptions on errors.
1631 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1633 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1635 if (result
) *result
= 0;
1636 if (magic
) *magic
= 0;
1637 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1638 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1639 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1643 if (!RtlTryEnterCriticalSection( &loader_section
))
1646 return STATUS_SUCCESS
;
1652 RtlEnterCriticalSection( &loader_section
);
1653 if (result
) *result
= 1;
1655 *magic
= GetCurrentThreadId();
1656 return STATUS_SUCCESS
;
1660 /******************************************************************
1661 * LdrUnlockLoaderUnlock (NTDLL.@)
1663 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1667 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1668 RtlLeaveCriticalSection( &loader_section
);
1670 return STATUS_SUCCESS
;
1674 /******************************************************************
1675 * LdrGetProcedureAddress (NTDLL.@)
1677 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1678 ULONG ord
, PVOID
*address
)
1680 IMAGE_EXPORT_DIRECTORY
*exports
;
1682 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1684 RtlEnterCriticalSection( &loader_section
);
1686 /* check if the module itself is invalid to return the proper error */
1687 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1688 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1689 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1691 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, NULL
)
1692 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, NULL
);
1696 ret
= STATUS_SUCCESS
;
1700 RtlLeaveCriticalSection( &loader_section
);
1705 /***********************************************************************
1706 * set_security_cookie
1708 * Create a random security cookie for buffer overflow protection. Make
1709 * sure it does not accidentally match the default cookie value.
1711 static void set_security_cookie( void *module
, SIZE_T len
)
1714 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1718 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1719 if (!loadcfg
) return;
1720 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1721 if (!loadcfg
->SecurityCookie
) return;
1722 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1723 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1725 WARN( "security cookie %p outside of image %p-%p\n",
1726 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1730 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1731 TRACE( "initializing security cookie %p\n", cookie
);
1733 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1736 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1737 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1738 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1739 *cookie
= RtlRandom( &seed
);
1740 #ifdef DEFAULT_SECURITY_COOKIE_64
1741 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1743 *cookie
= RtlRandom( &seed
);
1744 /* fill up, but keep the highest word clear */
1745 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1753 static NTSTATUS
perform_relocations( void *module
, IMAGE_NT_HEADERS
*nt
, SIZE_T len
)
1756 IMAGE_BASE_RELOCATION
*rel
, *end
;
1757 const IMAGE_DATA_DIRECTORY
*relocs
;
1758 const IMAGE_SECTION_HEADER
*sec
;
1760 ULONG protect_old
[96], i
;
1762 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1763 if (module
== base
) return STATUS_SUCCESS
; /* nothing to do */
1765 /* no relocations are performed on non page-aligned binaries */
1766 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1767 return STATUS_SUCCESS
;
1769 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1770 return STATUS_SUCCESS
;
1772 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1774 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1776 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1778 return STATUS_CONFLICTING_ADDRESSES
;
1781 if (!relocs
->Size
) return STATUS_SUCCESS
;
1782 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1784 if (nt
->FileHeader
.NumberOfSections
> ARRAY_SIZE( protect_old
))
1785 return STATUS_INVALID_IMAGE_FORMAT
;
1787 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1788 nt
->FileHeader
.SizeOfOptionalHeader
);
1789 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1791 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1792 SIZE_T size
= sec
[i
].SizeOfRawData
;
1793 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1794 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1797 TRACE( "relocating from %p-%p to %p-%p\n",
1798 base
, base
+ len
, module
, (char *)module
+ len
);
1800 rel
= get_rva( module
, relocs
->VirtualAddress
);
1801 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1802 delta
= (char *)module
- base
;
1804 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1806 if (rel
->VirtualAddress
>= len
)
1808 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1809 return STATUS_ACCESS_VIOLATION
;
1811 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1812 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1813 (USHORT
*)(rel
+ 1), delta
);
1814 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1817 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1819 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1820 SIZE_T size
= sec
[i
].SizeOfRawData
;
1821 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1822 &size
, protect_old
[i
], &protect_old
[i
] );
1825 return STATUS_SUCCESS
;
1829 /*************************************************************************
1832 * Build the module data for a mapped dll.
1834 static NTSTATUS
build_module( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, void **module
,
1835 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
1836 DWORD flags
, WINE_MODREF
**pwm
)
1838 static const char builtin_signature
[] = "Wine builtin DLL";
1839 char *signature
= (char *)((IMAGE_DOS_HEADER
*)*module
+ 1);
1841 IMAGE_NT_HEADERS
*nt
;
1846 if (!(nt
= RtlImageNtHeader( *module
))) return STATUS_INVALID_IMAGE_FORMAT
;
1848 map_size
= (nt
->OptionalHeader
.SizeOfImage
+ page_size
- 1) & ~(page_size
- 1);
1849 if ((status
= perform_relocations( *module
, nt
, map_size
))) return status
;
1851 is_builtin
= ((char *)nt
- signature
>= sizeof(builtin_signature
) &&
1852 !memcmp( signature
, builtin_signature
, sizeof(builtin_signature
) ));
1854 /* create the MODREF */
1856 if (!(wm
= alloc_module( *module
, nt_name
, is_builtin
))) return STATUS_NO_MEMORY
;
1858 if (id
) wm
->id
= *id
;
1859 if (image_info
->LoaderFlags
) wm
->ldr
.Flags
|= LDR_COR_IMAGE
;
1860 if (image_info
->u
.s
.ComPlusILOnly
) wm
->ldr
.Flags
|= LDR_COR_ILONLY
;
1862 set_security_cookie( *module
, map_size
);
1866 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1867 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1868 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1870 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
1871 status
= fixup_imports_ilonly( wm
, load_path
, &wm
->ldr
.EntryPoint
);
1873 status
= fixup_imports( wm
, load_path
);
1874 if (status
!= STATUS_SUCCESS
)
1876 /* the module has only be inserted in the load & memory order lists */
1877 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
1878 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
1880 /* FIXME: there are several more dangling references
1881 * left. Including dlls loaded by this dll before the
1882 * failed one. Unrolling is rather difficult with the
1883 * current structure and we can leave them lying
1884 * around with no problems, so we don't care.
1885 * As these might reference our wm, we don't free it.
1892 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name
), wm
, *module
);
1896 if (TRACE_ON(relay
)) RELAY_SetupDLL( *module
);
1900 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( *module
);
1903 TRACE_(loaddll
)( "Loaded %s at %p: %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), *module
,
1904 is_builtin
? "builtin" : "native" );
1906 wm
->ldr
.LoadCount
= 1;
1909 return STATUS_SUCCESS
;
1913 /*************************************************************************
1914 * build_ntdll_module
1916 * Build the module data for the initially-loaded ntdll.
1918 static void build_ntdll_module(void)
1920 MEMORY_BASIC_INFORMATION meminfo
;
1921 UNICODE_STRING nt_name
;
1924 RtlInitUnicodeString( &nt_name
, L
"\\??\\C:\\windows\\system32\\ntdll.dll" );
1925 NtQueryVirtualMemory( GetCurrentProcess(), build_ntdll_module
, MemoryBasicInformation
,
1926 &meminfo
, sizeof(meminfo
), NULL
);
1927 wm
= alloc_module( meminfo
.AllocationBase
, &nt_name
, TRUE
);
1929 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1930 if (TRACE_ON(relay
)) RELAY_SetupDLL( meminfo
.AllocationBase
);
1935 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1936 static BOOL
convert_to_pe64( HMODULE module
, const SECTION_IMAGE_INFORMATION
*info
)
1938 static const ULONG copy_dirs
[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE
,
1939 IMAGE_DIRECTORY_ENTRY_SECURITY
,
1940 IMAGE_DIRECTORY_ENTRY_BASERELOC
,
1941 IMAGE_DIRECTORY_ENTRY_DEBUG
,
1942 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
};
1943 IMAGE_OPTIONAL_HEADER32 hdr32
= { IMAGE_NT_OPTIONAL_HDR32_MAGIC
};
1944 IMAGE_OPTIONAL_HEADER64 hdr64
= { IMAGE_NT_OPTIONAL_HDR64_MAGIC
};
1945 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
1946 SIZE_T hdr_size
= min( sizeof(hdr32
), nt
->FileHeader
.SizeOfOptionalHeader
);
1947 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char *)&nt
->OptionalHeader
+ hdr_size
);
1948 SIZE_T size
= min( nt
->OptionalHeader
.SizeOfHeaders
, nt
->OptionalHeader
.SizeOfImage
);
1949 void *addr
= module
;
1952 if (nt
->OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return TRUE
; /* already 64-bit */
1953 if (!info
->ImageContainsCode
) return TRUE
; /* no need to convert */
1955 TRACE( "%p\n", module
);
1957 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, PAGE_READWRITE
, &old_prot
))
1960 if ((char *)module
+ size
< (char *)(nt
+ 1) + nt
->FileHeader
.NumberOfSections
* sizeof(*sec
))
1962 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
1966 memcpy( &hdr32
, &nt
->OptionalHeader
, hdr_size
);
1967 memcpy( &hdr64
, &hdr32
, offsetof( IMAGE_OPTIONAL_HEADER64
, SizeOfStackReserve
));
1968 hdr64
.Magic
= IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1969 hdr64
.AddressOfEntryPoint
= 0;
1970 hdr64
.ImageBase
= hdr32
.ImageBase
;
1971 hdr64
.SizeOfStackReserve
= hdr32
.SizeOfStackReserve
;
1972 hdr64
.SizeOfStackCommit
= hdr32
.SizeOfStackCommit
;
1973 hdr64
.SizeOfHeapReserve
= hdr32
.SizeOfHeapReserve
;
1974 hdr64
.SizeOfHeapCommit
= hdr32
.SizeOfHeapCommit
;
1975 hdr64
.LoaderFlags
= hdr32
.LoaderFlags
;
1976 hdr64
.NumberOfRvaAndSizes
= hdr32
.NumberOfRvaAndSizes
;
1977 for (i
= 0; i
< ARRAY_SIZE( copy_dirs
); i
++)
1978 hdr64
.DataDirectory
[copy_dirs
[i
]] = hdr32
.DataDirectory
[copy_dirs
[i
]];
1980 memmove( nt
+ 1, sec
, nt
->FileHeader
.NumberOfSections
* sizeof(*sec
) );
1981 nt
->FileHeader
.SizeOfOptionalHeader
= sizeof(hdr64
);
1982 nt
->OptionalHeader
= hdr64
;
1983 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
1987 /* check COM header for ILONLY flag, ignoring runtime version */
1988 static BOOL
get_cor_header( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
, IMAGE_COR20_HEADER
*cor
)
1990 IMAGE_DOS_HEADER mz
;
1991 IMAGE_NT_HEADERS32 nt
;
1993 LARGE_INTEGER offset
;
1994 IMAGE_SECTION_HEADER sec
[96];
1995 unsigned int i
, count
;
1998 offset
.QuadPart
= 0;
1999 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &mz
, sizeof(mz
), &offset
, NULL
)) return FALSE
;
2000 if (io
.Information
!= sizeof(mz
)) return FALSE
;
2001 if (mz
.e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
2002 offset
.QuadPart
= mz
.e_lfanew
;
2003 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &nt
, sizeof(nt
), &offset
, NULL
)) return FALSE
;
2004 if (io
.Information
!= sizeof(nt
)) return FALSE
;
2005 if (nt
.Signature
!= IMAGE_NT_SIGNATURE
) return FALSE
;
2006 if (nt
.OptionalHeader
.Magic
!= IMAGE_NT_OPTIONAL_HDR32_MAGIC
) return FALSE
;
2007 va
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].VirtualAddress
;
2008 size
= nt
.OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
].Size
;
2009 if (!va
|| size
< sizeof(*cor
)) return FALSE
;
2010 offset
.QuadPart
+= offsetof( IMAGE_NT_HEADERS32
, OptionalHeader
) + nt
.FileHeader
.SizeOfOptionalHeader
;
2011 count
= min( 96, nt
.FileHeader
.NumberOfSections
);
2012 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, &sec
, count
* sizeof(*sec
), &offset
, NULL
)) return FALSE
;
2013 if (io
.Information
!= count
* sizeof(*sec
)) return FALSE
;
2014 for (i
= 0; i
< count
; i
++)
2016 if (va
< sec
[i
].VirtualAddress
) continue;
2017 if (sec
[i
].Misc
.VirtualSize
&& va
- sec
[i
].VirtualAddress
>= sec
[i
].Misc
.VirtualSize
) continue;
2018 offset
.QuadPart
= sec
->PointerToRawData
+ va
- sec
[i
].VirtualAddress
;
2019 if (NtReadFile( file
, 0, NULL
, NULL
, &io
, cor
, sizeof(*cor
), &offset
, NULL
)) return FALSE
;
2020 return (io
.Information
== sizeof(*cor
));
2026 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2027 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2028 static BOOL
is_valid_binary( HANDLE file
, const SECTION_IMAGE_INFORMATION
*info
)
2031 return info
->Machine
== IMAGE_FILE_MACHINE_I386
;
2032 #elif defined(__arm__)
2033 return info
->Machine
== IMAGE_FILE_MACHINE_ARM
||
2034 info
->Machine
== IMAGE_FILE_MACHINE_THUMB
||
2035 info
->Machine
== IMAGE_FILE_MACHINE_ARMNT
;
2036 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2038 if (info
->Machine
== IMAGE_FILE_MACHINE_AMD64
) return TRUE
;
2040 if (info
->Machine
== IMAGE_FILE_MACHINE_ARM64
) return TRUE
;
2042 if (!info
->ImageContainsCode
) return TRUE
;
2043 if (!(info
->u
.s
.ComPlusNativeReady
))
2045 IMAGE_COR20_HEADER cor_header
;
2046 if (!get_cor_header( file
, info
, &cor_header
)) return FALSE
;
2047 if (!(cor_header
.Flags
& COMIMAGE_FLAGS_ILONLY
)) return FALSE
;
2051 return FALSE
; /* no wow64 support on other platforms */
2056 /******************************************************************
2057 * get_module_path_end
2059 * Returns the end of the directory component of the module path.
2061 static inline const WCHAR
*get_module_path_end( const WCHAR
*module
)
2064 const WCHAR
*mod_end
= module
;
2066 if ((p
= wcsrchr( mod_end
, '\\' ))) mod_end
= p
;
2067 if ((p
= wcsrchr( mod_end
, '/' ))) mod_end
= p
;
2068 if (mod_end
== module
+ 2 && module
[1] == ':') mod_end
++;
2069 if (mod_end
== module
&& module
[0] && module
[1] == ':') mod_end
+= 2;
2074 /******************************************************************
2077 * Append a counted string to the load path. Helper for get_dll_load_path.
2079 static inline WCHAR
*append_path( WCHAR
*p
, const WCHAR
*str
, int len
)
2081 if (len
== -1) len
= wcslen(str
);
2083 memcpy( p
, str
, len
* sizeof(WCHAR
) );
2089 /******************************************************************
2092 static NTSTATUS
get_dll_load_path( LPCWSTR module
, LPCWSTR dll_dir
, ULONG safe_mode
, WCHAR
**path
)
2094 const WCHAR
*mod_end
= module
;
2095 UNICODE_STRING name
, value
;
2097 int len
= ARRAY_SIZE(system_path
) + 1, path_len
= 0;
2101 mod_end
= get_module_path_end( module
);
2102 len
+= (mod_end
- module
) + 1;
2105 RtlInitUnicodeString( &name
, L
"PATH" );
2107 value
.MaximumLength
= 0;
2108 value
.Buffer
= NULL
;
2109 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2110 path_len
= value
.Length
;
2112 if (dll_dir
) len
+= wcslen( dll_dir
) + 1;
2113 else len
+= 2; /* current directory */
2114 if (!(p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, path_len
+ len
* sizeof(WCHAR
) )))
2115 return STATUS_NO_MEMORY
;
2117 p
= append_path( p
, module
, mod_end
- module
);
2118 if (dll_dir
) p
= append_path( p
, dll_dir
, -1 );
2119 else if (!safe_mode
) p
= append_path( p
, L
".", -1 );
2120 p
= append_path( p
, system_path
, -1 );
2121 if (!dll_dir
&& safe_mode
) p
= append_path( p
, L
".", -1 );
2124 value
.MaximumLength
= path_len
;
2126 while (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) == STATUS_BUFFER_TOO_SMALL
)
2130 /* grow the buffer and retry */
2131 path_len
= value
.Length
;
2132 if (!(new_ptr
= RtlReAllocateHeap( GetProcessHeap(), 0, ret
, path_len
+ len
* sizeof(WCHAR
) )))
2134 RtlFreeHeap( GetProcessHeap(), 0, ret
);
2135 return STATUS_NO_MEMORY
;
2137 value
.Buffer
= new_ptr
+ (value
.Buffer
- ret
);
2138 value
.MaximumLength
= path_len
;
2141 value
.Buffer
[value
.Length
/ sizeof(WCHAR
)] = 0;
2143 return STATUS_SUCCESS
;
2147 /******************************************************************
2148 * get_dll_load_path_search_flags
2150 static NTSTATUS
get_dll_load_path_search_flags( LPCWSTR module
, DWORD flags
, WCHAR
**path
)
2152 const WCHAR
*image
= NULL
, *mod_end
, *image_end
;
2153 struct dll_dir_entry
*dir
;
2157 if (flags
& LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
)
2158 flags
|= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
2159 LOAD_LIBRARY_SEARCH_USER_DIRS
|
2160 LOAD_LIBRARY_SEARCH_SYSTEM32
);
2162 if (flags
& LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
)
2164 DWORD type
= RtlDetermineDosPathNameType_U( module
);
2165 if (type
!= ABSOLUTE_DRIVE_PATH
&& type
!= ABSOLUTE_PATH
&& type
!= DEVICE_PATH
)
2166 return STATUS_INVALID_PARAMETER
;
2167 mod_end
= get_module_path_end( module
);
2168 len
+= (mod_end
- module
) + 1;
2172 if (flags
& LOAD_LIBRARY_SEARCH_APPLICATION_DIR
)
2174 image
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
2175 image_end
= get_module_path_end( image
);
2176 len
+= (image_end
- image
) + 1;
2179 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2181 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2182 len
+= wcslen( dir
->dir
+ 4 /* \??\ */ ) + 1;
2183 if (dll_directory
.Length
) len
+= dll_directory
.Length
/ sizeof(WCHAR
) + 1;
2186 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) len
+= wcslen( system_dir
);
2188 if ((p
= ret
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2190 if (module
) p
= append_path( p
, module
, mod_end
- module
);
2191 if (image
) p
= append_path( p
, image
, image_end
- image
);
2192 if (flags
& LOAD_LIBRARY_SEARCH_USER_DIRS
)
2194 LIST_FOR_EACH_ENTRY( dir
, &dll_dir_list
, struct dll_dir_entry
, entry
)
2195 p
= append_path( p
, dir
->dir
+ 4 /* \??\ */, -1 );
2196 p
= append_path( p
, dll_directory
.Buffer
, dll_directory
.Length
/ sizeof(WCHAR
) );
2198 if (flags
& LOAD_LIBRARY_SEARCH_SYSTEM32
) wcscpy( p
, system_dir
);
2206 return STATUS_SUCCESS
;
2210 /***********************************************************************
2213 * Open a file for a new dll. Helper for find_dll_file.
2215 static NTSTATUS
open_dll_file( UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2216 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2218 FILE_BASIC_INFORMATION info
;
2219 OBJECT_ATTRIBUTES attr
;
2222 FILE_OBJECTID_BUFFER fid
;
2226 if ((*pwm
= find_fullname_module( nt_name
))) return STATUS_SUCCESS
;
2228 attr
.Length
= sizeof(attr
);
2229 attr
.RootDirectory
= 0;
2230 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2231 attr
.ObjectName
= nt_name
;
2232 attr
.SecurityDescriptor
= NULL
;
2233 attr
.SecurityQualityOfService
= NULL
;
2234 if ((status
= NtOpenFile( &handle
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
,
2235 FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2236 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
2238 if (status
!= STATUS_OBJECT_PATH_NOT_FOUND
&&
2239 status
!= STATUS_OBJECT_NAME_NOT_FOUND
&&
2240 !NtQueryAttributesFile( &attr
, &info
))
2242 /* if the file exists but failed to open, report the error */
2245 /* otherwise continue searching */
2246 return STATUS_DLL_NOT_FOUND
;
2249 if (!NtFsControlFile( handle
, 0, NULL
, NULL
, &io
, FSCTL_GET_OBJECT_ID
, NULL
, 0, &fid
, sizeof(fid
) ))
2251 memcpy( id
, fid
.ObjectId
, sizeof(*id
) );
2252 if ((*pwm
= find_fileid_module( id
)))
2254 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name
->Buffer
),
2255 (*pwm
)->ldr
.DllBase
, debugstr_w( (*pwm
)->ldr
.FullDllName
.Buffer
));
2257 return STATUS_SUCCESS
;
2262 status
= NtCreateSection( mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
2263 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
2264 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, handle
);
2267 NtQuerySection( *mapping
, SectionImageInformation
, image_info
, sizeof(*image_info
), NULL
);
2268 if (!is_valid_binary( handle
, image_info
))
2270 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name
), image_info
->Machine
);
2271 status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2272 NtClose( *mapping
);
2280 /******************************************************************************
2281 * find_existing_module
2283 * Find an existing module that is the same mapping as the new module.
2285 static WINE_MODREF
*find_existing_module( HMODULE module
)
2288 LIST_ENTRY
*mark
, *entry
;
2289 LDR_DATA_TABLE_ENTRY
*mod
;
2290 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
2292 if ((wm
= get_modref( module
))) return wm
;
2294 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
2295 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2297 mod
= CONTAINING_RECORD( entry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderLinks
);
2298 if (mod
->TimeDateStamp
!= nt
->FileHeader
.TimeDateStamp
) continue;
2299 if (mod
->CheckSum
!= nt
->OptionalHeader
.CheckSum
) continue;
2300 if (NtAreMappedFilesTheSame( mod
->DllBase
, module
) != STATUS_SUCCESS
) continue;
2301 return CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
2307 /******************************************************************************
2308 * load_native_dll (internal)
2310 static NTSTATUS
load_native_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
, HANDLE mapping
,
2311 const SECTION_IMAGE_INFORMATION
*image_info
, const struct file_id
*id
,
2312 DWORD flags
, WINE_MODREF
** pwm
)
2314 void *module
= NULL
;
2316 NTSTATUS status
= NtMapViewOfSection( mapping
, NtCurrentProcess(), &module
, 0, 0, NULL
, &len
,
2317 ViewShare
, 0, PAGE_EXECUTE_READ
);
2319 if (status
== STATUS_IMAGE_NOT_AT_BASE
) status
= STATUS_SUCCESS
;
2320 if (status
) return status
;
2322 if ((*pwm
= find_existing_module( module
))) /* already loaded */
2324 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2325 TRACE( "found %s for %s at %p, count=%d\n",
2326 debugstr_us(&(*pwm
)->ldr
.FullDllName
), debugstr_us(nt_name
),
2327 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2328 if (module
!= (*pwm
)->ldr
.DllBase
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2329 return STATUS_SUCCESS
;
2332 if (!convert_to_pe64( module
, image_info
)) status
= STATUS_INVALID_IMAGE_FORMAT
;
2334 if (!status
) status
= build_module( load_path
, nt_name
, &module
, image_info
, id
, flags
, pwm
);
2335 if (status
&& module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2340 /***********************************************************************
2343 static NTSTATUS
load_so_dll( LPCWSTR load_path
, const UNICODE_STRING
*nt_name
,
2344 DWORD flags
, WINE_MODREF
**pwm
)
2349 UNICODE_STRING win_name
= *nt_name
;
2351 TRACE( "trying %s as so lib\n", debugstr_us(&win_name
) );
2352 if ((status
= unix_funcs
->load_so_dll( &win_name
, &module
)))
2354 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name
) );
2355 if (status
== STATUS_INVALID_IMAGE_FORMAT
) status
= STATUS_INVALID_IMAGE_NOT_MZ
;
2359 if ((wm
= get_modref( module
))) /* already loaded */
2361 TRACE( "Found %s at %p for builtin %s\n",
2362 debugstr_w(wm
->ldr
.FullDllName
.Buffer
), wm
->ldr
.DllBase
, debugstr_us(nt_name
) );
2363 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2367 SECTION_IMAGE_INFORMATION image_info
= { 0 };
2369 if ((status
= build_module( load_path
, &win_name
, &module
, &image_info
, NULL
, flags
, &wm
)))
2371 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2374 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name
), module
);
2377 return STATUS_SUCCESS
;
2381 /***********************************************************************
2384 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, UNICODE_STRING
*nt_name
,
2385 DWORD flags
, WINE_MODREF
** pwm
, BOOL prefer_native
)
2389 SECTION_IMAGE_INFORMATION image_info
;
2391 TRACE("Trying built-in %s\n", debugstr_us(nt_name
));
2393 status
= unix_funcs
->load_builtin_dll( nt_name
, &module
, &image_info
, prefer_native
);
2394 if (status
) return status
;
2396 if ((*pwm
= find_existing_module( module
))) /* already loaded */
2398 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2399 TRACE( "Found %s for %s at %p, count=%d\n",
2400 debugstr_us(&(*pwm
)->ldr
.FullDllName
), debugstr_us(nt_name
),
2401 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2402 if (module
!= (*pwm
)->ldr
.DllBase
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2403 return STATUS_SUCCESS
;
2406 TRACE( "loading %s\n", debugstr_us(nt_name
) );
2407 status
= build_module( load_path
, nt_name
, &module
, &image_info
, NULL
, flags
, pwm
);
2408 if (status
&& module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2413 /*************************************************************************
2416 * Build the module data for the main image.
2418 static void build_main_module(void)
2420 SECTION_IMAGE_INFORMATION info
;
2421 UNICODE_STRING nt_name
;
2424 RTL_USER_PROCESS_PARAMETERS
*params
= NtCurrentTeb()->Peb
->ProcessParameters
;
2425 void *module
= NtCurrentTeb()->Peb
->ImageBaseAddress
;
2427 default_load_path
= params
->DllPath
.Buffer
;
2428 if (!default_load_path
)
2429 get_dll_load_path( params
->ImagePathName
.Buffer
, NULL
, dll_safe_mode
, &default_load_path
);
2431 NtQueryInformationProcess( GetCurrentProcess(), ProcessImageInformation
, &info
, sizeof(info
), NULL
);
2432 if (info
.ImageCharacteristics
& IMAGE_FILE_DLL
)
2434 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_us(¶ms
->ImagePathName
) );
2435 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT
);
2438 if (!convert_to_pe64( module
, &info
))
2440 status
= STATUS_INVALID_IMAGE_FORMAT
;
2444 status
= RtlDosPathNameToNtPathName_U_WithStatus( params
->ImagePathName
.Buffer
, &nt_name
, NULL
, NULL
);
2445 if (status
) goto failed
;
2446 status
= build_module( NULL
, &nt_name
, &module
, &info
, NULL
, DONT_RESOLVE_DLL_REFERENCES
, &wm
);
2447 RtlFreeUnicodeString( &nt_name
);
2448 if (!status
) return;
2450 MESSAGE( "wine: failed to create main module for %s, status %x\n",
2451 debugstr_us(¶ms
->ImagePathName
), status
);
2452 NtTerminateProcess( GetCurrentProcess(), status
);
2456 /***********************************************************************
2459 * Find the full path (if any) of the dll from the activation context.
2461 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2463 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2465 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2466 ACTCTX_SECTION_KEYED_DATA data
;
2467 UNICODE_STRING nameW
;
2469 SIZE_T needed
, size
= 1024;
2472 RtlInitUnicodeString( &nameW
, libname
);
2473 data
.cbSize
= sizeof(data
);
2474 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2475 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2477 if (status
!= STATUS_SUCCESS
) return status
;
2481 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2483 status
= STATUS_NO_MEMORY
;
2486 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2487 AssemblyDetailedInformationInActivationContext
,
2488 info
, size
, &needed
);
2489 if (status
== STATUS_SUCCESS
) break;
2490 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2491 RtlFreeHeap( GetProcessHeap(), 0, info
);
2493 /* restart with larger buffer */
2496 if (!info
->lpAssemblyManifestPath
)
2498 status
= STATUS_SXS_KEY_NOT_FOUND
;
2502 if ((p
= wcsrchr( info
->lpAssemblyManifestPath
, '\\' )))
2504 DWORD len
, dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2507 if (!dirlen
|| len
<= dirlen
||
2508 RtlCompareUnicodeStrings( p
, dirlen
, info
->lpAssemblyDirectoryName
, dirlen
, TRUE
) ||
2509 wcsicmp( p
+ dirlen
, L
".manifest" ))
2511 /* manifest name does not match directory name, so it's not a global
2512 * windows/winsxs manifest; use the manifest directory name instead */
2513 dirlen
= p
- info
->lpAssemblyManifestPath
;
2514 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2515 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2517 status
= STATUS_NO_MEMORY
;
2520 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2522 wcscpy( p
, libname
);
2527 if (!info
->lpAssemblyDirectoryName
)
2529 status
= STATUS_SXS_KEY_NOT_FOUND
;
2533 needed
= (wcslen(windows_dir
) * sizeof(WCHAR
) +
2534 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2536 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2538 status
= STATUS_NO_MEMORY
;
2541 wcscpy( p
, windows_dir
);
2543 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2544 p
+= ARRAY_SIZE( winsxsW
);
2545 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2546 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2548 wcscpy( p
, libname
);
2550 RtlFreeHeap( GetProcessHeap(), 0, info
);
2551 RtlReleaseActivationContext( data
.hActCtx
);
2556 /***********************************************************************
2559 * Search for dll in the specified paths.
2561 static NTSTATUS
search_dll_file( LPCWSTR paths
, LPCWSTR search
, UNICODE_STRING
*nt_name
,
2562 WINE_MODREF
**pwm
, HANDLE
*mapping
, SECTION_IMAGE_INFORMATION
*image_info
,
2563 struct file_id
*id
)
2566 BOOL found_image
= FALSE
;
2567 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
2570 if (!paths
) paths
= default_load_path
;
2571 len
= wcslen( paths
);
2573 if (len
< wcslen( system_dir
)) len
= wcslen( system_dir
);
2574 len
+= wcslen( search
) + 2;
2576 if (!(name
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) )))
2577 return STATUS_NO_MEMORY
;
2581 LPCWSTR ptr
= paths
;
2583 while (*ptr
&& *ptr
!= ';') ptr
++;
2585 if (*ptr
== ';') ptr
++;
2586 memcpy( name
, paths
, len
* sizeof(WCHAR
) );
2587 if (len
&& name
[len
- 1] != '\\') name
[len
++] = '\\';
2588 wcscpy( name
+ len
, search
);
2590 nt_name
->Buffer
= NULL
;
2591 if ((status
= RtlDosPathNameToNtPathName_U_WithStatus( name
, nt_name
, NULL
, NULL
))) goto done
;
2593 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
2594 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) found_image
= TRUE
;
2595 else if (status
!= STATUS_DLL_NOT_FOUND
) goto done
;
2596 RtlFreeUnicodeString( nt_name
);
2602 /* not found, return file in the system dir to be loaded as builtin */
2603 wcscpy( name
, system_dir
);
2604 wcscat( name
, search
);
2605 if (!RtlDosPathNameToNtPathName_U( name
, nt_name
, NULL
, NULL
)) status
= STATUS_NO_MEMORY
;
2607 else status
= STATUS_IMAGE_MACHINE_TYPE_MISMATCH
;
2610 RtlFreeHeap( GetProcessHeap(), 0, name
);
2615 /***********************************************************************
2618 * Find the file (or already loaded module) for a given dll name.
2620 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
2621 UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, HANDLE
*mapping
,
2622 SECTION_IMAGE_INFORMATION
*image_info
, struct file_id
*id
)
2624 WCHAR
*ext
, *dllname
;
2626 ULONG wow64_old_value
= 0;
2631 if (default_ext
) /* first append default extension */
2633 if (!(ext
= wcsrchr( libname
, '.')) || wcschr( ext
, '/' ) || wcschr( ext
, '\\'))
2635 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2636 (wcslen(libname
)+wcslen(default_ext
)+1) * sizeof(WCHAR
))))
2637 return STATUS_NO_MEMORY
;
2638 wcscpy( dllname
, libname
);
2639 wcscat( dllname
, default_ext
);
2644 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2645 if (is_wow64
) RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value
);
2647 nt_name
->Buffer
= NULL
;
2649 if (!contains_path( libname
))
2651 WCHAR
*fullname
= NULL
;
2653 status
= find_actctx_dll( libname
, &fullname
);
2654 if (status
== STATUS_SUCCESS
)
2656 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2657 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2658 libname
= dllname
= fullname
;
2662 if (status
!= STATUS_SXS_KEY_NOT_FOUND
) goto done
;
2663 if ((*pwm
= find_basename_module( libname
)) != NULL
)
2665 status
= STATUS_SUCCESS
;
2671 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2672 status
= search_dll_file( load_path
, libname
, nt_name
, pwm
, mapping
, image_info
, id
);
2673 else if (!(status
= RtlDosPathNameToNtPathName_U_WithStatus( libname
, nt_name
, NULL
, NULL
)))
2674 status
= open_dll_file( nt_name
, pwm
, mapping
, image_info
, id
);
2676 if (status
== STATUS_IMAGE_MACHINE_TYPE_MISMATCH
) status
= STATUS_INVALID_IMAGE_FORMAT
;
2679 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2680 if (wow64_old_value
) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value
);
2685 /***********************************************************************
2686 * load_dll (internal)
2688 * Load a PE style module according to the load order.
2689 * The loader_section must be locked while calling this function.
2691 static NTSTATUS
load_dll( const WCHAR
*load_path
, const WCHAR
*libname
, const WCHAR
*default_ext
,
2692 DWORD flags
, WINE_MODREF
** pwm
)
2694 UNICODE_STRING nt_name
;
2697 SECTION_IMAGE_INFORMATION image_info
;
2701 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2703 nts
= find_dll_file( load_path
, libname
, default_ext
, &nt_name
, pwm
, &mapping
, &image_info
, &id
);
2705 if (*pwm
) /* found already loaded module */
2707 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2709 TRACE("Found %s for %s at %p, count=%d\n",
2710 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2711 (*pwm
)->ldr
.DllBase
, (*pwm
)->ldr
.LoadCount
);
2712 RtlFreeUnicodeString( &nt_name
);
2713 return STATUS_SUCCESS
;
2716 if (nts
&& nts
!= STATUS_DLL_NOT_FOUND
&& nts
!= STATUS_INVALID_IMAGE_NOT_MZ
) goto done
;
2718 prev
= NtCurrentTeb()->Tib
.ArbitraryUserPointer
;
2719 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= nt_name
.Buffer
+ 4;
2723 case STATUS_INVALID_IMAGE_NOT_MZ
: /* not in PE format, maybe it's a .so file */
2724 nts
= load_so_dll( load_path
, &nt_name
, flags
, pwm
);
2727 case STATUS_SUCCESS
: /* valid PE file */
2728 nts
= load_native_dll( load_path
, &nt_name
, mapping
, &image_info
, &id
, flags
, pwm
);
2731 case STATUS_DLL_NOT_FOUND
: /* no file found, try builtin */
2732 switch (unix_funcs
->get_load_order( &nt_name
))
2734 case LO_NATIVE_BUILTIN
:
2736 case LO_BUILTIN_NATIVE
:
2738 nts
= load_builtin_dll( load_path
, &nt_name
, flags
, pwm
, FALSE
);
2741 nts
= STATUS_DLL_NOT_FOUND
;
2746 NtCurrentTeb()->Tib
.ArbitraryUserPointer
= prev
;
2749 if (nts
== STATUS_SUCCESS
)
2750 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name
), (*pwm
)->ldr
.DllBase
);
2752 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2754 if (mapping
) NtClose( mapping
);
2755 RtlFreeUnicodeString( &nt_name
);
2760 /***********************************************************************
2761 * __wine_init_unix_lib
2763 NTSTATUS __cdecl
__wine_init_unix_lib( HMODULE module
, DWORD reason
, const void *ptr_in
, void *ptr_out
)
2768 RtlEnterCriticalSection( &loader_section
);
2770 if ((wm
= get_modref( module
))) ret
= unix_funcs
->init_unix_lib( module
, reason
, ptr_in
, ptr_out
);
2771 else ret
= STATUS_INVALID_HANDLE
;
2773 RtlLeaveCriticalSection( &loader_section
);
2778 /******************************************************************
2779 * LdrLoadDll (NTDLL.@)
2781 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2782 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2787 RtlEnterCriticalSection( &loader_section
);
2789 nts
= load_dll( path_name
, libname
->Buffer
, L
".dll", flags
, &wm
);
2791 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2793 nts
= process_attach( wm
, NULL
);
2794 if (nts
!= STATUS_SUCCESS
)
2796 LdrUnloadDll(wm
->ldr
.DllBase
);
2800 *hModule
= (wm
) ? wm
->ldr
.DllBase
: NULL
;
2802 RtlLeaveCriticalSection( &loader_section
);
2807 /******************************************************************
2808 * LdrGetDllHandle (NTDLL.@)
2810 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2813 UNICODE_STRING nt_name
;
2816 SECTION_IMAGE_INFORMATION image_info
;
2819 RtlEnterCriticalSection( &loader_section
);
2821 status
= find_dll_file( load_path
, name
->Buffer
, L
".dll", &nt_name
, &wm
, &mapping
, &image_info
, &id
);
2823 if (wm
) *base
= wm
->ldr
.DllBase
;
2826 if (status
== STATUS_SUCCESS
) NtClose( mapping
);
2827 status
= STATUS_DLL_NOT_FOUND
;
2829 RtlFreeUnicodeString( &nt_name
);
2831 RtlLeaveCriticalSection( &loader_section
);
2832 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2837 /******************************************************************
2838 * LdrAddRefDll (NTDLL.@)
2840 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2842 NTSTATUS ret
= STATUS_SUCCESS
;
2845 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2847 RtlEnterCriticalSection( &loader_section
);
2849 if ((wm
= get_modref( module
)))
2851 if (flags
& LDR_ADDREF_DLL_PIN
)
2852 wm
->ldr
.LoadCount
= -1;
2854 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2855 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2857 else ret
= STATUS_INVALID_PARAMETER
;
2859 RtlLeaveCriticalSection( &loader_section
);
2864 /***********************************************************************
2865 * LdrProcessRelocationBlock (NTDLL.@)
2867 * Apply relocations to a given page of a mapped PE image.
2869 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2870 USHORT
*relocs
, INT_PTR delta
)
2874 USHORT offset
= *relocs
& 0xfff;
2875 int type
= *relocs
>> 12;
2878 case IMAGE_REL_BASED_ABSOLUTE
:
2880 case IMAGE_REL_BASED_HIGH
:
2881 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2883 case IMAGE_REL_BASED_LOW
:
2884 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2886 case IMAGE_REL_BASED_HIGHLOW
:
2887 *(int *)((char *)page
+ offset
) += delta
;
2890 case IMAGE_REL_BASED_DIR64
:
2891 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2893 #elif defined(__arm__)
2894 case IMAGE_REL_BASED_THUMB_MOV32
:
2896 DWORD
*inst
= (DWORD
*)((char *)page
+ offset
);
2897 WORD lo
= ((inst
[0] << 1) & 0x0800) + ((inst
[0] << 12) & 0xf000) +
2898 ((inst
[0] >> 20) & 0x0700) + ((inst
[0] >> 16) & 0x00ff);
2899 WORD hi
= ((inst
[1] << 1) & 0x0800) + ((inst
[1] << 12) & 0xf000) +
2900 ((inst
[1] >> 20) & 0x0700) + ((inst
[1] >> 16) & 0x00ff);
2901 DWORD imm
= MAKELONG( lo
, hi
) + delta
;
2906 if ((inst
[0] & 0x8000fbf0) != 0x0000f240 || (inst
[1] & 0x8000fbf0) != 0x0000f2c0)
2907 ERR("wrong Thumb2 instruction @%p %08x:%08x, expected MOVW/MOVT\n",
2908 inst
, inst
[0], inst
[1] );
2910 inst
[0] = (inst
[0] & 0x8f00fbf0) + ((lo
>> 1) & 0x0400) + ((lo
>> 12) & 0x000f) +
2911 ((lo
<< 20) & 0x70000000) + ((lo
<< 16) & 0xff0000);
2912 inst
[1] = (inst
[1] & 0x8f00fbf0) + ((hi
>> 1) & 0x0400) + ((hi
>> 12) & 0x000f) +
2913 ((hi
<< 20) & 0x70000000) + ((hi
<< 16) & 0xff0000);
2918 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2923 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2927 /******************************************************************
2928 * LdrQueryProcessModuleInformation
2931 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2932 ULONG buf_size
, ULONG
* req_size
)
2934 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2935 ULONG size
= sizeof(ULONG
);
2936 NTSTATUS nts
= STATUS_SUCCESS
;
2939 PLIST_ENTRY mark
, entry
;
2940 LDR_DATA_TABLE_ENTRY
*mod
;
2943 smi
->ModulesCount
= 0;
2945 RtlEnterCriticalSection( &loader_section
);
2946 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2947 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2949 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
2950 size
+= sizeof(*sm
);
2951 if (size
<= buf_size
)
2953 sm
->Section
= 0; /* FIXME */
2954 sm
->MappedBaseAddress
= mod
->DllBase
;
2955 sm
->ImageBaseAddress
= mod
->DllBase
;
2956 sm
->ImageSize
= mod
->SizeOfImage
;
2957 sm
->Flags
= mod
->Flags
;
2958 sm
->LoadOrderIndex
= id
++;
2959 sm
->InitOrderIndex
= 0; /* FIXME */
2960 sm
->LoadCount
= mod
->LoadCount
;
2962 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2963 str
.Buffer
= (char*)sm
->Name
;
2964 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2965 ptr
= strrchr(str
.Buffer
, '\\');
2966 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2968 smi
->ModulesCount
++;
2971 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2973 RtlLeaveCriticalSection( &loader_section
);
2975 if (req_size
) *req_size
= size
;
2981 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2987 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2989 RtlInitUnicodeString( &str
, name
);
2991 size
= sizeof(buffer
) - sizeof(WCHAR
);
2992 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2995 if (info
->Type
!= REG_DWORD
)
2997 buffer
[size
/ sizeof(WCHAR
)] = 0;
2998 *value
= wcstoul( (WCHAR
*)info
->Data
, 0, 16 );
3000 else memcpy( value
, info
->Data
, sizeof(*value
) );
3004 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
3005 void *data
, ULONG in_size
, ULONG
*out_size
)
3011 KEY_VALUE_PARTIAL_INFORMATION
*info
;
3012 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
3014 RtlInitUnicodeString( &str
, name
);
3016 size
= info_size
+ in_size
;
3017 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
3018 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
3019 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
3020 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
3022 if (out_size
) *out_size
= info
->DataLength
;
3023 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
3025 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
3030 /******************************************************************
3031 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3033 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
3034 void *data
, ULONG in_size
, ULONG
*out_size
)
3036 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
3037 'S','o','f','t','w','a','r','e','\\',
3038 'M','i','c','r','o','s','o','f','t','\\',
3039 'W','i','n','d','o','w','s',' ','N','T','\\',
3040 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3041 'I','m','a','g','e',' ','F','i','l','e',' ',
3042 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3043 WCHAR path
[MAX_PATH
+ ARRAY_SIZE( optionsW
)];
3044 OBJECT_ATTRIBUTES attr
;
3045 UNICODE_STRING name_str
;
3051 attr
.Length
= sizeof(attr
);
3052 attr
.RootDirectory
= 0;
3053 attr
.ObjectName
= &name_str
;
3054 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3055 attr
.SecurityDescriptor
= NULL
;
3056 attr
.SecurityQualityOfService
= NULL
;
3058 p
= key
->Buffer
+ key
->Length
/ sizeof(WCHAR
);
3059 while (p
> key
->Buffer
&& p
[-1] != '\\') p
--;
3060 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
3061 name_str
.Buffer
= path
;
3062 name_str
.Length
= sizeof(optionsW
) + len
;
3063 name_str
.MaximumLength
= name_str
.Length
;
3064 memcpy( path
, optionsW
, sizeof(optionsW
) );
3065 memcpy( path
+ ARRAY_SIZE( optionsW
), p
, len
);
3066 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
3068 if (type
== REG_DWORD
)
3070 if (out_size
) *out_size
= sizeof(ULONG
);
3071 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
3072 else status
= STATUS_BUFFER_OVERFLOW
;
3074 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
3081 /******************************************************************
3082 * RtlDllShutdownInProgress (NTDLL.@)
3084 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
3086 return process_detaching
;
3089 /****************************************************************************
3090 * LdrResolveDelayLoadedAPI (NTDLL.@)
3092 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
3093 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
,
3094 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook
,
3095 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
3097 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
3098 DELAYLOAD_INFO delayinfo
;
3106 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
3108 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
3109 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
3110 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
3111 name
= get_rva(base
, desc
->DllNameRVA
);
3116 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
3118 nts
= STATUS_NO_MEMORY
;
3121 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
3122 RtlFreeUnicodeString(&mod
);
3126 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3127 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
3130 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3133 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
3134 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
3138 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
3143 delayinfo
.Size
= sizeof(delayinfo
);
3144 delayinfo
.DelayloadDescriptor
= desc
;
3145 delayinfo
.ThunkAddress
= addr
;
3146 delayinfo
.TargetDllName
= name
;
3147 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
3148 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
3149 delayinfo
.TargetModuleBase
= *phmod
;
3150 delayinfo
.Unused
= NULL
;
3151 delayinfo
.LastError
= nts
;
3154 return dllhook(4, &delayinfo
);
3156 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
3158 DWORD_PTR ord
= LOWORD(pINT
[id
].u1
.Ordinal
);
3159 return syshook(name
, (const char *)ord
);
3163 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
3164 return syshook(name
, (const char *)iibn
->Name
);
3168 /******************************************************************
3169 * LdrShutdownProcess (NTDLL.@)
3172 void WINAPI
LdrShutdownProcess(void)
3174 BOOL detaching
= process_detaching
;
3178 process_detaching
= TRUE
;
3180 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3186 /******************************************************************
3187 * RtlExitUserProcess (NTDLL.@)
3189 void WINAPI
RtlExitUserProcess( DWORD status
)
3191 RtlEnterCriticalSection( &loader_section
);
3192 RtlAcquirePebLock();
3193 NtTerminateProcess( 0, status
);
3194 LdrShutdownProcess();
3195 for (;;) NtTerminateProcess( GetCurrentProcess(), status
);
3198 /******************************************************************
3199 * LdrShutdownThread (NTDLL.@)
3202 void WINAPI
LdrShutdownThread(void)
3204 PLIST_ENTRY mark
, entry
;
3205 LDR_DATA_TABLE_ENTRY
*mod
;
3212 /* don't do any detach calls if process is exiting */
3213 if (process_detaching
) return;
3215 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 1 );
3217 RtlEnterCriticalSection( &loader_section
);
3218 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3220 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3221 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
3223 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
,
3224 InInitializationOrderLinks
);
3225 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
3227 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
3230 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
3231 DLL_THREAD_DETACH
, NULL
);
3234 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_DETACH
);
3236 RtlAcquirePebLock();
3237 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
3238 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
3240 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
3241 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
3243 RtlProcessFlsData( NtCurrentTeb()->FlsSlots
, 2 );
3244 NtCurrentTeb()->FlsSlots
= NULL
;
3245 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
3246 NtCurrentTeb()->TlsExpansionSlots
= NULL
;
3247 RtlReleasePebLock();
3249 RtlLeaveCriticalSection( &loader_section
);
3250 /* don't call DbgUiGetThreadDebugObject as some apps hook it and terminate if called */
3251 if (NtCurrentTeb()->DbgSsReserved
[1]) NtClose( NtCurrentTeb()->DbgSsReserved
[1] );
3252 RtlFreeThreadActivationContextStack();
3256 /***********************************************************************
3260 static void free_modref( WINE_MODREF
*wm
)
3262 RemoveEntryList(&wm
->ldr
.InLoadOrderLinks
);
3263 RemoveEntryList(&wm
->ldr
.InMemoryOrderLinks
);
3264 if (wm
->ldr
.InInitializationOrderLinks
.Flink
)
3265 RemoveEntryList(&wm
->ldr
.InInitializationOrderLinks
);
3267 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
3268 if (!TRACE_ON(module
))
3269 TRACE_(loaddll
)("Unloaded module %s : %s\n",
3270 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
3271 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
3273 free_tls_slot( &wm
->ldr
);
3274 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
3275 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.DllBase
);
3276 if (cached_modref
== wm
) cached_modref
= NULL
;
3277 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
3278 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
3279 RtlFreeHeap( GetProcessHeap(), 0, wm
);
3282 /***********************************************************************
3283 * MODULE_FlushModrefs
3285 * Remove all unused modrefs and call the internal unloading routines
3286 * for the library type.
3288 * The loader_section must be locked while calling this function.
3290 static void MODULE_FlushModrefs(void)
3292 PLIST_ENTRY mark
, entry
, prev
;
3293 LDR_DATA_TABLE_ENTRY
*mod
;
3296 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3297 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3299 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderLinks
);
3300 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3301 prev
= entry
->Blink
;
3302 if (!mod
->LoadCount
) free_modref( wm
);
3305 /* check load order list too for modules that haven't been initialized yet */
3306 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3307 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3309 mod
= CONTAINING_RECORD(entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
3310 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3311 prev
= entry
->Blink
;
3312 if (!mod
->LoadCount
) free_modref( wm
);
3316 /***********************************************************************
3317 * MODULE_DecRefCount
3319 * The loader_section must be locked while calling this function.
3321 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
3325 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
3328 if ( wm
->ldr
.LoadCount
<= 0 )
3331 --wm
->ldr
.LoadCount
;
3332 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3334 if ( wm
->ldr
.LoadCount
== 0 )
3336 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
3338 for ( i
= 0; i
< wm
->nDeps
; i
++ )
3340 MODULE_DecRefCount( wm
->deps
[i
] );
3342 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
3344 module_push_unload_trace( &wm
->ldr
);
3348 /******************************************************************
3349 * LdrUnloadDll (NTDLL.@)
3353 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
3356 NTSTATUS retv
= STATUS_SUCCESS
;
3358 if (process_detaching
) return retv
;
3360 TRACE("(%p)\n", hModule
);
3362 RtlEnterCriticalSection( &loader_section
);
3365 if ((wm
= get_modref( hModule
)) != NULL
)
3367 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
3369 /* Recursively decrement reference counts */
3370 MODULE_DecRefCount( wm
);
3372 /* Call process detach notifications */
3373 if ( free_lib_count
<= 1 )
3376 MODULE_FlushModrefs();
3382 retv
= STATUS_DLL_NOT_FOUND
;
3386 RtlLeaveCriticalSection( &loader_section
);
3391 /***********************************************************************
3392 * RtlImageNtHeader (NTDLL.@)
3394 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
3396 IMAGE_NT_HEADERS
*ret
;
3400 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
3403 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
3405 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
3406 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
3417 /***********************************************************************
3418 * process_breakpoint
3420 * Trigger a debug breakpoint if the process is being debugged.
3422 static void process_breakpoint(void)
3426 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort
, &port
, sizeof(port
), NULL
);
3441 /******************************************************************
3442 * LdrInitializeThunk (NTDLL.@)
3444 * Attach to all the loaded dlls.
3445 * If this is the first time, perform the full process initialization.
3447 void WINAPI
LdrInitializeThunk( CONTEXT
*context
, ULONG_PTR unknown2
, ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3449 static int attach_done
;
3457 entry
= (void **)&context
->Eax
;
3458 #elif defined(__x86_64__)
3459 entry
= (void **)&context
->Rcx
;
3460 #elif defined(__arm__)
3461 entry
= (void **)&context
->R0
;
3462 #elif defined(__aarch64__)
3463 entry
= (void **)&context
->u
.s
.X0
;
3466 if (process_detaching
) NtTerminateThread( GetCurrentThread(), 0 );
3468 RtlEnterCriticalSection( &loader_section
);
3470 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3473 if (!imports_fixup_done
)
3476 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
3477 status
= fixup_imports_ilonly( wm
, NULL
, entry
);
3479 status
= fixup_imports( wm
, NULL
);
3483 ERR( "Importing dlls for %s failed, status %x\n",
3484 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3485 NtTerminateProcess( GetCurrentProcess(), status
);
3487 imports_fixup_done
= TRUE
;
3490 RtlAcquirePebLock();
3491 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
3492 RtlReleasePebLock();
3494 NtCurrentTeb()->FlsSlots
= fls_alloc_data();
3496 if (!attach_done
) /* first time around */
3499 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3501 ERR( "TLS init failed when loading %s, status %x\n",
3502 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3503 NtTerminateProcess( GetCurrentProcess(), status
);
3505 wm
->ldr
.LoadCount
= -1;
3506 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
; /* don't try to attach again */
3507 if (wm
->ldr
.ActivationContext
)
3508 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
3510 for (i
= 0; i
< wm
->nDeps
; i
++)
3512 if (!wm
->deps
[i
]) continue;
3513 if ((status
= process_attach( wm
->deps
[i
], context
)) != STATUS_SUCCESS
)
3515 if (last_failed_modref
)
3516 ERR( "%s failed to initialize, aborting\n",
3517 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3518 ERR( "Initializing dlls for %s failed, status %x\n",
3519 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3520 NtTerminateProcess( GetCurrentProcess(), status
);
3523 unix_funcs
->virtual_release_address_space();
3524 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_PROCESS_ATTACH
);
3525 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) unix_funcs
->init_builtin_dll( wm
->ldr
.DllBase
);
3526 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
3527 process_breakpoint();
3531 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3532 NtTerminateThread( GetCurrentThread(), status
);
3534 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.DllBase
, DLL_THREAD_ATTACH
);
3537 RtlLeaveCriticalSection( &loader_section
);
3538 signal_start_thread( context
);
3542 /***********************************************************************
3543 * load_global_options
3545 static void load_global_options(void)
3547 OBJECT_ATTRIBUTES attr
;
3548 UNICODE_STRING name_str
;
3552 attr
.Length
= sizeof(attr
);
3553 attr
.RootDirectory
= 0;
3554 attr
.ObjectName
= &name_str
;
3555 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3556 attr
.SecurityDescriptor
= NULL
;
3557 attr
.SecurityQualityOfService
= NULL
;
3558 RtlInitUnicodeString( &name_str
, L
"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3560 if (!NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))
3562 query_dword_option( hkey
, L
"GlobalFlag", &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3563 query_dword_option( hkey
, L
"SafeProcessSearchMode", &path_safe_mode
);
3564 query_dword_option( hkey
, L
"SafeDllSearchMode", &dll_safe_mode
);
3566 if (!query_dword_option( hkey
, L
"CriticalSectionTimeout", &value
))
3567 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3569 if (!query_dword_option( hkey
, L
"HeapSegmentReserve", &value
))
3570 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3572 if (!query_dword_option( hkey
, L
"HeapSegmentCommit", &value
))
3573 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3575 if (!query_dword_option( hkey
, L
"HeapDeCommitTotalFreeThreshold", &value
))
3576 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3578 if (!query_dword_option( hkey
, L
"HeapDeCommitFreeBlockThreshold", &value
))
3579 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3583 LdrQueryImageFileExecutionOptions( &NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
,
3584 L
"GlobalFlag", REG_DWORD
, &NtCurrentTeb()->Peb
->NtGlobalFlag
,
3585 sizeof(DWORD
), NULL
);
3586 heap_set_debug_flags( GetProcessHeap() );
3590 /***********************************************************************
3591 * RtlImageDirectoryEntryToData (NTDLL.@)
3593 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3595 const IMAGE_NT_HEADERS
*nt
;
3598 if ((ULONG_PTR
)module
& 1) image
= FALSE
; /* mapped as data file */
3599 module
= (HMODULE
)((ULONG_PTR
)module
& ~3);
3600 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3601 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3603 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3605 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3606 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3607 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3608 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3610 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3612 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3614 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3615 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3616 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3617 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3621 /* not mapped as image, need to find the section containing the virtual address */
3622 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3626 /***********************************************************************
3627 * RtlImageRvaToSection (NTDLL.@)
3629 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3630 HMODULE module
, DWORD rva
)
3633 const IMAGE_SECTION_HEADER
*sec
;
3635 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3636 nt
->FileHeader
.SizeOfOptionalHeader
);
3637 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3639 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3640 return (PIMAGE_SECTION_HEADER
)sec
;
3646 /***********************************************************************
3647 * RtlImageRvaToVa (NTDLL.@)
3649 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3650 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3652 IMAGE_SECTION_HEADER
*sec
;
3654 if (section
&& *section
) /* try this section first */
3657 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3660 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3662 if (section
) *section
= sec
;
3663 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3667 /***********************************************************************
3668 * RtlPcToFileHeader (NTDLL.@)
3670 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3672 LDR_DATA_TABLE_ENTRY
*module
;
3675 RtlEnterCriticalSection( &loader_section
);
3676 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->DllBase
;
3677 RtlLeaveCriticalSection( &loader_section
);
3683 /****************************************************************************
3684 * LdrGetDllDirectory (NTDLL.@)
3686 NTSTATUS WINAPI
LdrGetDllDirectory( UNICODE_STRING
*dir
)
3688 NTSTATUS status
= STATUS_SUCCESS
;
3690 RtlEnterCriticalSection( &dlldir_section
);
3691 dir
->Length
= dll_directory
.Length
+ sizeof(WCHAR
);
3692 if (dir
->MaximumLength
>= dir
->Length
) RtlCopyUnicodeString( dir
, &dll_directory
);
3695 status
= STATUS_BUFFER_TOO_SMALL
;
3696 if (dir
->MaximumLength
) dir
->Buffer
[0] = 0;
3698 RtlLeaveCriticalSection( &dlldir_section
);
3703 /****************************************************************************
3704 * LdrSetDllDirectory (NTDLL.@)
3706 NTSTATUS WINAPI
LdrSetDllDirectory( const UNICODE_STRING
*dir
)
3708 NTSTATUS status
= STATUS_SUCCESS
;
3711 if (!dir
->Buffer
) RtlInitUnicodeString( &new, NULL
);
3712 else if ((status
= RtlDuplicateUnicodeString( 1, dir
, &new ))) return status
;
3714 RtlEnterCriticalSection( &dlldir_section
);
3715 RtlFreeUnicodeString( &dll_directory
);
3716 dll_directory
= new;
3717 RtlLeaveCriticalSection( &dlldir_section
);
3722 /****************************************************************************
3723 * LdrAddDllDirectory (NTDLL.@)
3725 NTSTATUS WINAPI
LdrAddDllDirectory( const UNICODE_STRING
*dir
, void **cookie
)
3727 FILE_BASIC_INFORMATION info
;
3728 UNICODE_STRING nt_name
;
3730 OBJECT_ATTRIBUTES attr
;
3732 struct dll_dir_entry
*ptr
;
3733 DOS_PATHNAME_TYPE type
= RtlDetermineDosPathNameType_U( dir
->Buffer
);
3735 if (type
!= ABSOLUTE_PATH
&& type
!= ABSOLUTE_DRIVE_PATH
)
3736 return STATUS_INVALID_PARAMETER
;
3738 status
= RtlDosPathNameToNtPathName_U_WithStatus( dir
->Buffer
, &nt_name
, NULL
, NULL
);
3739 if (status
) return status
;
3740 len
= nt_name
.Length
/ sizeof(WCHAR
);
3741 if (!(ptr
= RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry
, dir
[++len
] ))))
3742 return STATUS_NO_MEMORY
;
3743 memcpy( ptr
->dir
, nt_name
.Buffer
, len
* sizeof(WCHAR
) );
3745 attr
.Length
= sizeof(attr
);
3746 attr
.RootDirectory
= 0;
3747 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3748 attr
.ObjectName
= &nt_name
;
3749 attr
.SecurityDescriptor
= NULL
;
3750 attr
.SecurityQualityOfService
= NULL
;
3751 status
= NtQueryAttributesFile( &attr
, &info
);
3752 RtlFreeUnicodeString( &nt_name
);
3756 TRACE( "%s\n", debugstr_w( ptr
->dir
));
3757 RtlEnterCriticalSection( &dlldir_section
);
3758 list_add_head( &dll_dir_list
, &ptr
->entry
);
3759 RtlLeaveCriticalSection( &dlldir_section
);
3762 else RtlFreeHeap( GetProcessHeap(), 0, ptr
);
3767 /****************************************************************************
3768 * LdrRemoveDllDirectory (NTDLL.@)
3770 NTSTATUS WINAPI
LdrRemoveDllDirectory( void *cookie
)
3772 struct dll_dir_entry
*ptr
= cookie
;
3774 TRACE( "%s\n", debugstr_w( ptr
->dir
));
3776 RtlEnterCriticalSection( &dlldir_section
);
3777 list_remove( &ptr
->entry
);
3778 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
3779 RtlLeaveCriticalSection( &dlldir_section
);
3780 return STATUS_SUCCESS
;
3784 /*************************************************************************
3785 * LdrSetDefaultDllDirectories (NTDLL.@)
3787 NTSTATUS WINAPI
LdrSetDefaultDllDirectories( ULONG flags
)
3789 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
3790 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
3791 LOAD_LIBRARY_SEARCH_USER_DIRS
|
3792 LOAD_LIBRARY_SEARCH_SYSTEM32
|
3793 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
3795 if (!flags
|| (flags
& ~load_library_search_flags
)) return STATUS_INVALID_PARAMETER
;
3796 default_search_flags
= flags
;
3797 return STATUS_SUCCESS
;
3801 /******************************************************************
3802 * LdrGetDllPath (NTDLL.@)
3804 NTSTATUS WINAPI
LdrGetDllPath( PCWSTR module
, ULONG flags
, PWSTR
*path
, PWSTR
*unknown
)
3807 const ULONG load_library_search_flags
= (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
|
3808 LOAD_LIBRARY_SEARCH_APPLICATION_DIR
|
3809 LOAD_LIBRARY_SEARCH_USER_DIRS
|
3810 LOAD_LIBRARY_SEARCH_SYSTEM32
|
3811 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
);
3813 if (flags
& LOAD_WITH_ALTERED_SEARCH_PATH
)
3815 if (flags
& load_library_search_flags
) return STATUS_INVALID_PARAMETER
;
3816 if (default_search_flags
) flags
|= default_search_flags
| LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
;
3818 else if (!(flags
& load_library_search_flags
)) flags
|= default_search_flags
;
3820 RtlEnterCriticalSection( &dlldir_section
);
3822 if (flags
& load_library_search_flags
)
3824 status
= get_dll_load_path_search_flags( module
, flags
, path
);
3828 const WCHAR
*dlldir
= dll_directory
.Length
? dll_directory
.Buffer
: NULL
;
3829 if (!(flags
& LOAD_WITH_ALTERED_SEARCH_PATH
))
3830 module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
3831 status
= get_dll_load_path( module
, dlldir
, dll_safe_mode
, path
);
3834 RtlLeaveCriticalSection( &dlldir_section
);
3840 /*************************************************************************
3841 * RtlSetSearchPathMode (NTDLL.@)
3843 NTSTATUS WINAPI
RtlSetSearchPathMode( ULONG flags
)
3849 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
:
3852 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE
:
3855 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE
| BASE_SEARCH_PATH_PERMANENT
:
3856 InterlockedExchange( (int *)&path_safe_mode
, 2 );
3857 return STATUS_SUCCESS
;
3859 return STATUS_INVALID_PARAMETER
;
3864 int prev
= path_safe_mode
;
3865 if (prev
== 2) break; /* permanently set */
3866 if (InterlockedCompareExchange( (int *)&path_safe_mode
, val
, prev
) == prev
) return STATUS_SUCCESS
;
3868 return STATUS_ACCESS_DENIED
;
3872 /******************************************************************
3873 * RtlGetExePath (NTDLL.@)
3875 NTSTATUS WINAPI
RtlGetExePath( PCWSTR name
, PWSTR
*path
)
3877 const WCHAR
*dlldir
= L
".";
3878 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
3880 /* same check as NeedCurrentDirectoryForExePathW */
3881 if (!wcschr( name
, '\\' ))
3883 UNICODE_STRING name
, value
= { 0 };
3885 RtlInitUnicodeString( &name
, L
"NoDefaultCurrentDirectoryInExePath" );
3886 if (RtlQueryEnvironmentVariable_U( NULL
, &name
, &value
) != STATUS_VARIABLE_NOT_FOUND
)
3889 return get_dll_load_path( module
, dlldir
, FALSE
, path
);
3893 /******************************************************************
3894 * RtlGetSearchPath (NTDLL.@)
3896 NTSTATUS WINAPI
RtlGetSearchPath( PWSTR
*path
)
3898 const WCHAR
*module
= NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
;
3899 return get_dll_load_path( module
, NULL
, path_safe_mode
, path
);
3903 /******************************************************************
3904 * RtlReleasePath (NTDLL.@)
3906 void WINAPI
RtlReleasePath( PWSTR path
)
3908 RtlFreeHeap( GetProcessHeap(), 0, path
);
3912 /******************************************************************
3915 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3917 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3923 void *Wow64Transition
= NULL
;
3925 static void map_wow64cpu(void)
3928 OBJECT_ATTRIBUTES attr
;
3929 UNICODE_STRING string
;
3930 HANDLE file
, section
;
3934 RtlInitUnicodeString( &string
, L
"\\??\\C:\\windows\\sysnative\\wow64cpu.dll" );
3935 InitializeObjectAttributes( &attr
, &string
, 0, NULL
, NULL
);
3936 if ((status
= NtOpenFile( &file
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
,
3937 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
)))
3939 WARN("failed to open wow64cpu, status %#x\n", status
);
3942 if (!NtCreateSection( §ion
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
3943 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
3944 NULL
, NULL
, PAGE_EXECUTE_READ
, SEC_COMMIT
, file
))
3946 NtMapViewOfSection( section
, NtCurrentProcess(), &Wow64Transition
, 0,
3947 0, NULL
, &size
, ViewShare
, 0, PAGE_EXECUTE_READ
);
3955 /***********************************************************************
3958 static NTSTATUS
process_init(void)
3962 ANSI_STRING func_name
;
3964 TEB
*teb
= NtCurrentTeb();
3965 PEB
*peb
= teb
->Peb
;
3967 peb
->LdrData
= &ldr
;
3968 peb
->FastPebLock
= &peb_lock
;
3969 peb
->TlsBitmap
= &tls_bitmap
;
3970 peb
->TlsExpansionBitmap
= &tls_expansion_bitmap
;
3971 peb
->LoaderLock
= &loader_section
;
3972 peb
->OSMajorVersion
= 5;
3973 peb
->OSMinorVersion
= 1;
3974 peb
->OSBuildNumber
= 0xA28;
3975 peb
->OSPlatformId
= VER_PLATFORM_WIN32_NT
;
3977 peb
->ProcessHeap
= RtlCreateHeap( HEAP_GROWABLE
, NULL
, 0, 0, NULL
, NULL
);
3979 RtlInitializeBitMap( &tls_bitmap
, peb
->TlsBitmapBits
, sizeof(peb
->TlsBitmapBits
) * 8 );
3980 RtlInitializeBitMap( &tls_expansion_bitmap
, peb
->TlsExpansionBitmapBits
,
3981 sizeof(peb
->TlsExpansionBitmapBits
) * 8 );
3982 RtlSetBits( peb
->TlsBitmap
, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
3983 init_global_fls_data();
3985 InitializeListHead( &ldr
.InLoadOrderModuleList
);
3986 InitializeListHead( &ldr
.InMemoryOrderModuleList
);
3987 InitializeListHead( &ldr
.InInitializationOrderModuleList
);
3990 is_wow64
= !!NtCurrentTeb64();
3993 init_user_process_params();
3994 load_global_options();
3996 build_main_module();
3999 if (NtCurrentTeb64())
4001 PEB64
*peb64
= UlongToPtr( NtCurrentTeb64()->Peb
);
4002 peb64
->ImageBaseAddress
= PtrToUlong( peb
->ImageBaseAddress
);
4003 peb64
->OSMajorVersion
= peb
->OSMajorVersion
;
4004 peb64
->OSMinorVersion
= peb
->OSMinorVersion
;
4005 peb64
->OSBuildNumber
= peb
->OSBuildNumber
;
4006 peb64
->OSPlatformId
= peb
->OSPlatformId
;
4007 peb64
->SessionId
= peb
->SessionId
;
4011 build_ntdll_module();
4018 if ((status
= load_dll( NULL
, L
"C:\\windows\\system32\\kernel32.dll", NULL
, 0, &wm
)) != STATUS_SUCCESS
)
4020 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
4021 NtTerminateProcess( GetCurrentProcess(), status
);
4023 RtlInitAnsiString( &func_name
, "BaseThreadInitThunk" );
4024 if ((status
= LdrGetProcedureAddress( wm
->ldr
.DllBase
, &func_name
,
4025 0, (void **)&pBaseThreadInitThunk
)) != STATUS_SUCCESS
)
4027 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status
);
4028 NtTerminateProcess( GetCurrentProcess(), status
);
4031 init_locale( wm
->ldr
.DllBase
);
4033 RtlCreateUserStack( 0, 0, 0, 0x10000, 0x10000, &stack
);
4034 teb
->Tib
.StackBase
= stack
.StackBase
;
4035 teb
->Tib
.StackLimit
= stack
.StackLimit
;
4036 teb
->DeallocationStack
= stack
.DeallocationStack
;
4037 return STATUS_SUCCESS
;
4040 /***********************************************************************
4041 * __wine_set_unix_funcs
4043 NTSTATUS CDECL
__wine_set_unix_funcs( int version
, const struct unix_funcs
*funcs
)
4045 if (version
!= NTDLL_UNIXLIB_VERSION
) return STATUS_REVISION_MISMATCH
;
4047 return process_init();