ntdll: Move Wow64 initialization to LdrInitializeThunk().
[wine/zf.git] / dlls / ntdll / loader.c
blob35cef275e9a56d7a315f4e359d77e08b9557e91e
1 /*
2 * Loader functions
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
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30 #include "windef.h"
31 #include "winnt.h"
32 #include "winioctl.h"
33 #include "winternl.h"
34 #include "delayloadhandler.h"
36 #include "wine/exception.h"
37 #include "wine/debug.h"
38 #include "wine/list.h"
39 #include "ntdll_misc.h"
40 #include "ddk/wdm.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);
48 #ifdef _WIN64
49 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
50 #endif
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 HMODULE kernel32_handle = 0;
73 /* system search path */
74 static const WCHAR system_path[] = L"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
76 static BOOL is_prefix_bootstrap; /* are we bootstrapping the prefix? */
77 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
78 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
79 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
80 static ULONG path_safe_mode; /* path mode set by RtlSetSearchPathMode */
81 static ULONG dll_safe_mode = 1; /* dll search mode */
82 static UNICODE_STRING dll_directory; /* extra path for LdrSetDllDirectory */
83 static DWORD default_search_flags; /* default flags set by LdrSetDefaultDllDirectories */
84 static WCHAR *default_load_path; /* default dll search path */
86 struct dll_dir_entry
88 struct list entry;
89 WCHAR dir[1];
92 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from LdrAddDllDirectory */
94 struct ldr_notification
96 struct list entry;
97 PLDR_DLL_NOTIFICATION_FUNCTION callback;
98 void *context;
101 static struct list ldr_notifications = LIST_INIT( ldr_notifications );
103 static const char * const reason_names[] =
105 "PROCESS_DETACH",
106 "PROCESS_ATTACH",
107 "THREAD_ATTACH",
108 "THREAD_DETACH",
111 struct file_id
113 BYTE ObjectId[16];
116 /* internal representation of loaded modules */
117 typedef struct _wine_modref
119 LDR_DATA_TABLE_ENTRY ldr;
120 struct file_id id;
121 int alloc_deps;
122 int nDeps;
123 struct _wine_modref **deps;
124 } WINE_MODREF;
126 static UINT tls_module_count; /* number of modules with TLS directory */
127 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
128 LIST_ENTRY tls_links = { &tls_links, &tls_links };
130 static RTL_CRITICAL_SECTION loader_section;
131 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
133 0, 0, &loader_section,
134 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
135 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
137 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
139 static CRITICAL_SECTION dlldir_section;
140 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug =
142 0, 0, &dlldir_section,
143 { &dlldir_critsect_debug.ProcessLocksList, &dlldir_critsect_debug.ProcessLocksList },
144 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
146 static CRITICAL_SECTION dlldir_section = { &dlldir_critsect_debug, -1, 0, 0, 0, 0 };
148 static RTL_CRITICAL_SECTION peb_lock;
149 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug =
151 0, 0, &peb_lock,
152 { &peb_critsect_debug.ProcessLocksList, &peb_critsect_debug.ProcessLocksList },
153 0, 0, { (DWORD_PTR)(__FILE__ ": peb_lock") }
155 static RTL_CRITICAL_SECTION peb_lock = { &peb_critsect_debug, -1, 0, 0, 0, 0 };
157 static PEB_LDR_DATA ldr = { sizeof(ldr), TRUE };
158 static RTL_BITMAP tls_bitmap;
159 static RTL_BITMAP tls_expansion_bitmap;
161 static WINE_MODREF *cached_modref;
162 static WINE_MODREF *current_modref;
163 static WINE_MODREF *last_failed_modref;
165 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
166 DWORD flags, WINE_MODREF** pwm );
167 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
168 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
169 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
170 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
171 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
173 /* convert PE image VirtualAddress to Real Address */
174 static inline void *get_rva( HMODULE module, DWORD va )
176 return (void *)((char *)module + va);
179 /* check whether the file name contains a path */
180 static inline BOOL contains_path( LPCWSTR name )
182 return ((*name && (name[1] == ':')) || wcschr(name, '/') || wcschr(name, '\\'));
185 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
187 typedef struct _RTL_UNLOAD_EVENT_TRACE
189 void *BaseAddress;
190 SIZE_T SizeOfImage;
191 ULONG Sequence;
192 ULONG TimeDateStamp;
193 ULONG CheckSum;
194 WCHAR ImageName[32];
195 } RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
197 static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
198 static RTL_UNLOAD_EVENT_TRACE *unload_trace_ptr;
199 static unsigned int unload_trace_seq;
201 static void module_push_unload_trace( const LDR_DATA_TABLE_ENTRY *ldr )
203 RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
204 unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
206 ptr->BaseAddress = ldr->DllBase;
207 ptr->SizeOfImage = ldr->SizeOfImage;
208 ptr->Sequence = unload_trace_seq;
209 ptr->TimeDateStamp = ldr->TimeDateStamp;
210 ptr->CheckSum = ldr->CheckSum;
211 memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
212 ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
214 unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
215 unload_trace_ptr = unload_traces;
218 /*********************************************************************
219 * RtlGetUnloadEventTrace [NTDLL.@]
221 RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
223 return unload_traces;
226 /*********************************************************************
227 * RtlGetUnloadEventTraceEx [NTDLL.@]
229 void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
231 static unsigned int element_size = sizeof(*unload_traces);
232 static unsigned int element_count = ARRAY_SIZE(unload_traces);
234 *size = &element_size;
235 *count = &element_count;
236 *trace = &unload_trace_ptr;
239 /*************************************************************************
240 * call_dll_entry_point
242 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
243 * their entry point, so we need a small asm wrapper. Testing indicates
244 * that only modifying esi leads to a crash, so use this one to backup
245 * ebp while running the dll entry proc.
247 #ifdef __i386__
248 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
249 __ASM_GLOBAL_FUNC(call_dll_entry_point,
250 "pushl %ebp\n\t"
251 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
252 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
253 "movl %esp,%ebp\n\t"
254 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
255 "pushl %ebx\n\t"
256 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
257 "pushl %esi\n\t"
258 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
259 "pushl %edi\n\t"
260 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
261 "movl %ebp,%esi\n\t"
262 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
263 "pushl 20(%ebp)\n\t"
264 "pushl 16(%ebp)\n\t"
265 "pushl 12(%ebp)\n\t"
266 "movl 8(%ebp),%eax\n\t"
267 "call *%eax\n\t"
268 "movl %esi,%ebp\n\t"
269 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
270 "leal -12(%ebp),%esp\n\t"
271 "popl %edi\n\t"
272 __ASM_CFI(".cfi_same_value %edi\n\t")
273 "popl %esi\n\t"
274 __ASM_CFI(".cfi_same_value %esi\n\t")
275 "popl %ebx\n\t"
276 __ASM_CFI(".cfi_same_value %ebx\n\t")
277 "popl %ebp\n\t"
278 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
279 __ASM_CFI(".cfi_same_value %ebp\n\t")
280 "ret" )
281 #else /* __i386__ */
282 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
283 UINT reason, void *reserved )
285 return proc( module, reason, reserved );
287 #endif /* __i386__ */
290 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
291 /*************************************************************************
292 * stub_entry_point
294 * Entry point for stub functions.
296 static void WINAPI stub_entry_point( const char *dll, const char *name, void *ret_addr )
298 EXCEPTION_RECORD rec;
300 rec.ExceptionCode = EXCEPTION_WINE_STUB;
301 rec.ExceptionFlags = EH_NONCONTINUABLE;
302 rec.ExceptionRecord = NULL;
303 rec.ExceptionAddress = ret_addr;
304 rec.NumberParameters = 2;
305 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
306 rec.ExceptionInformation[1] = (ULONG_PTR)name;
307 for (;;) RtlRaiseException( &rec );
311 #include "pshpack1.h"
312 #ifdef __i386__
313 struct stub
315 BYTE pushl1; /* pushl $name */
316 const char *name;
317 BYTE pushl2; /* pushl $dll */
318 const char *dll;
319 BYTE call; /* call stub_entry_point */
320 DWORD entry;
322 #elif defined(__arm__)
323 struct stub
325 DWORD ldr_r0; /* ldr r0, $dll */
326 DWORD ldr_r1; /* ldr r1, $name */
327 DWORD mov_r2_lr; /* mov r2, lr */
328 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
329 const char *dll;
330 const char *name;
331 const void* entry;
333 #elif defined(__aarch64__)
334 struct stub
336 DWORD ldr_x0; /* ldr x0, $dll */
337 DWORD ldr_x1; /* ldr x1, $name */
338 DWORD mov_x2_lr; /* mov x2, lr */
339 DWORD ldr_x16; /* ldr x16, $entry */
340 DWORD br_x16; /* br x16 */
341 const char *dll;
342 const char *name;
343 const void *entry;
345 #else
346 struct stub
348 BYTE movq_rdi[2]; /* movq $dll,%rdi */
349 const char *dll;
350 BYTE movq_rsi[2]; /* movq $name,%rsi */
351 const char *name;
352 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
353 BYTE movq_rax[2]; /* movq $entry, %rax */
354 const void* entry;
355 BYTE jmpq_rax[2]; /* jmp %rax */
357 #endif
358 #include "poppack.h"
360 /*************************************************************************
361 * allocate_stub
363 * Allocate a stub entry point.
365 static ULONG_PTR allocate_stub( const char *dll, const char *name )
367 #define MAX_SIZE 65536
368 static struct stub *stubs;
369 static unsigned int nb_stubs;
370 struct stub *stub;
372 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
374 if (!stubs)
376 SIZE_T size = MAX_SIZE;
377 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
378 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
379 return 0xdeadbeef;
381 stub = &stubs[nb_stubs++];
382 #ifdef __i386__
383 stub->pushl1 = 0x68; /* pushl $name */
384 stub->name = name;
385 stub->pushl2 = 0x68; /* pushl $dll */
386 stub->dll = dll;
387 stub->call = 0xe8; /* call stub_entry_point */
388 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
389 #elif defined(__arm__)
390 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
391 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
392 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
393 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
394 stub->dll = dll;
395 stub->name = name;
396 stub->entry = stub_entry_point;
397 #elif defined(__aarch64__)
398 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
399 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
400 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
401 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
402 stub->br_x16 = 0xd61f0200; /* br x16 */
403 stub->dll = dll;
404 stub->name = name;
405 stub->entry = stub_entry_point;
406 #else
407 stub->movq_rdi[0] = 0x48; /* movq $dll,%rcx */
408 stub->movq_rdi[1] = 0xb9;
409 stub->dll = dll;
410 stub->movq_rsi[0] = 0x48; /* movq $name,%rdx */
411 stub->movq_rsi[1] = 0xba;
412 stub->name = name;
413 stub->movq_rsp_rdx[0] = 0x4c; /* movq (%rsp),%r8 */
414 stub->movq_rsp_rdx[1] = 0x8b;
415 stub->movq_rsp_rdx[2] = 0x04;
416 stub->movq_rsp_rdx[3] = 0x24;
417 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
418 stub->movq_rax[1] = 0xb8;
419 stub->entry = stub_entry_point;
420 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
421 stub->jmpq_rax[1] = 0xe0;
422 #endif
423 return (ULONG_PTR)stub;
426 #else /* __i386__ */
427 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
428 #endif /* __i386__ */
430 /* call ldr notifications */
431 static void call_ldr_notifications( ULONG reason, LDR_DATA_TABLE_ENTRY *module )
433 struct ldr_notification *notify, *notify_next;
434 LDR_DLL_NOTIFICATION_DATA data;
436 data.Loaded.Flags = 0;
437 data.Loaded.FullDllName = &module->FullDllName;
438 data.Loaded.BaseDllName = &module->BaseDllName;
439 data.Loaded.DllBase = module->DllBase;
440 data.Loaded.SizeOfImage = module->SizeOfImage;
442 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
444 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
445 notify->callback, reason, &data, notify->context );
447 notify->callback(reason, &data, notify->context);
449 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
450 notify->callback, reason, &data, notify->context );
454 /*************************************************************************
455 * get_modref
457 * Looks for the referenced HMODULE in the current process
458 * The loader_section must be locked while calling this function.
460 static WINE_MODREF *get_modref( HMODULE hmod )
462 PLIST_ENTRY mark, entry;
463 PLDR_DATA_TABLE_ENTRY mod;
465 if (cached_modref && cached_modref->ldr.DllBase == hmod) return cached_modref;
467 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
468 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
470 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
471 if (mod->DllBase == hmod)
472 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
474 return NULL;
478 /**********************************************************************
479 * find_basename_module
481 * Find a module from its base name.
482 * The loader_section must be locked while calling this function
484 static WINE_MODREF *find_basename_module( LPCWSTR name )
486 PLIST_ENTRY mark, entry;
487 UNICODE_STRING name_str;
489 RtlInitUnicodeString( &name_str, name );
491 if (cached_modref && RtlEqualUnicodeString( &name_str, &cached_modref->ldr.BaseDllName, TRUE ))
492 return cached_modref;
494 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
495 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
497 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
498 if (RtlEqualUnicodeString( &name_str, &mod->BaseDllName, TRUE ))
500 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
501 return cached_modref;
504 return NULL;
508 /**********************************************************************
509 * find_fullname_module
511 * Find a module from its full path name.
512 * The loader_section must be locked while calling this function
514 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
516 PLIST_ENTRY mark, entry;
517 UNICODE_STRING name = *nt_name;
519 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
520 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
521 name.Buffer += 4;
523 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
524 return cached_modref;
526 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
527 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
529 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
530 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
532 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
533 return cached_modref;
536 return NULL;
540 /**********************************************************************
541 * find_fileid_module
543 * Find a module from its file id.
544 * The loader_section must be locked while calling this function
546 static WINE_MODREF *find_fileid_module( const struct file_id *id )
548 LIST_ENTRY *mark, *entry;
550 if (cached_modref && !memcmp( &cached_modref->id, id, sizeof(*id) )) return cached_modref;
552 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
553 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
555 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
556 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
558 if (!memcmp( &wm->id, id, sizeof(*id) ))
560 cached_modref = wm;
561 return wm;
564 return NULL;
568 /*************************************************************************
569 * grow_module_deps
571 static WINE_MODREF **grow_module_deps( WINE_MODREF *wm, int count )
573 WINE_MODREF **deps;
575 if (wm->alloc_deps)
576 deps = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, wm->deps,
577 (wm->alloc_deps + count) * sizeof(*deps) );
578 else
579 deps = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, count * sizeof(*deps) );
581 if (deps)
583 wm->deps = deps;
584 wm->alloc_deps += count;
586 return deps;
589 /*************************************************************************
590 * find_forwarded_export
592 * Find the final function pointer for a forwarded function.
593 * The loader_section must be locked while calling this function.
595 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
597 const IMAGE_EXPORT_DIRECTORY *exports;
598 DWORD exp_size;
599 WINE_MODREF *wm;
600 WCHAR buffer[32], *mod_name = buffer;
601 const char *end = strrchr(forward, '.');
602 FARPROC proc = NULL;
604 if (!end) return NULL;
605 if ((end - forward) * sizeof(WCHAR) > sizeof(buffer) - sizeof(L".dll"))
607 if (!(mod_name = RtlAllocateHeap( GetProcessHeap(), 0,
608 (end - forward + sizeof(L".dll")) * sizeof(WCHAR) )))
609 return NULL;
611 ascii_to_unicode( mod_name, forward, end - forward );
612 mod_name[end - forward] = 0;
613 if (!wcschr( mod_name, '.' ))
614 memcpy( mod_name + (end - forward), L".dll", sizeof(L".dll") );
616 if (!(wm = find_basename_module( mod_name )))
618 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
619 if (load_dll( load_path, mod_name, L".dll", 0, &wm ) == STATUS_SUCCESS &&
620 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
622 if (!imports_fixup_done && current_modref)
624 WINE_MODREF **deps = grow_module_deps( current_modref, 1 );
625 if (deps) deps[current_modref->nDeps++] = wm;
627 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
629 LdrUnloadDll( wm->ldr.DllBase );
630 wm = NULL;
634 if (!wm)
636 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
637 ERR( "module not found for forward '%s' used by %s\n",
638 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
639 return NULL;
642 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
643 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
645 const char *name = end + 1;
647 if (*name == '#') { /* ordinal */
648 proc = find_ordinal_export( wm->ldr.DllBase, exports, exp_size,
649 atoi(name+1) - exports->Base, load_path );
650 } else
651 proc = find_named_export( wm->ldr.DllBase, exports, exp_size, name, -1, load_path );
654 if (!proc)
656 ERR("function not found for forward '%s' used by %s."
657 " If you are using builtin %s, try using the native one instead.\n",
658 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
659 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
661 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
662 return proc;
666 /*************************************************************************
667 * find_ordinal_export
669 * Find an exported function by ordinal.
670 * The exports base must have been subtracted from the ordinal already.
671 * The loader_section must be locked while calling this function.
673 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
674 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
676 FARPROC proc;
677 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
679 if (ordinal >= exports->NumberOfFunctions)
681 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
682 return NULL;
684 if (!functions[ordinal]) return NULL;
686 proc = get_rva( module, functions[ordinal] );
688 /* if the address falls into the export dir, it's a forward */
689 if (((const char *)proc >= (const char *)exports) &&
690 ((const char *)proc < (const char *)exports + exp_size))
691 return find_forwarded_export( module, (const char *)proc, load_path );
693 if (TRACE_ON(snoop))
695 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
696 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
698 if (TRACE_ON(relay))
700 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
701 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
703 return proc;
707 /*************************************************************************
708 * find_named_export
710 * Find an exported function by name.
711 * The loader_section must be locked while calling this function.
713 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
714 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
716 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
717 const DWORD *names = get_rva( module, exports->AddressOfNames );
718 int min = 0, max = exports->NumberOfNames - 1;
720 /* first check the hint */
721 if (hint >= 0 && hint <= max)
723 char *ename = get_rva( module, names[hint] );
724 if (!strcmp( ename, name ))
725 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
728 /* then do a binary search */
729 while (min <= max)
731 int res, pos = (min + max) / 2;
732 char *ename = get_rva( module, names[pos] );
733 if (!(res = strcmp( ename, name )))
734 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
735 if (res > 0) max = pos - 1;
736 else min = pos + 1;
738 return NULL;
743 /*************************************************************************
744 * import_dll
746 * Import the dll specified by the given import descriptor.
747 * The loader_section must be locked while calling this function.
749 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
751 NTSTATUS status;
752 WINE_MODREF *wmImp;
753 HMODULE imp_mod;
754 const IMAGE_EXPORT_DIRECTORY *exports;
755 DWORD exp_size;
756 const IMAGE_THUNK_DATA *import_list;
757 IMAGE_THUNK_DATA *thunk_list;
758 WCHAR buffer[32];
759 const char *name = get_rva( module, descr->Name );
760 DWORD len = strlen(name);
761 PVOID protect_base;
762 SIZE_T protect_size = 0;
763 DWORD protect_old;
765 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
766 if (descr->u.OriginalFirstThunk)
767 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
768 else
769 import_list = thunk_list;
771 if (!import_list->u1.Ordinal)
773 WARN( "Skipping unused import %s\n", name );
774 *pwm = NULL;
775 return TRUE;
778 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
780 if (len * sizeof(WCHAR) < sizeof(buffer))
782 ascii_to_unicode( buffer, name, len );
783 buffer[len] = 0;
784 status = load_dll( load_path, buffer, L".dll", 0, &wmImp );
786 else /* need to allocate a larger buffer */
788 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
789 if (!ptr) return FALSE;
790 ascii_to_unicode( ptr, name, len );
791 ptr[len] = 0;
792 status = load_dll( load_path, ptr, L".dll", 0, &wmImp );
793 RtlFreeHeap( GetProcessHeap(), 0, ptr );
796 if (status)
798 if (status == STATUS_DLL_NOT_FOUND)
799 ERR("Library %s (which is needed by %s) not found\n",
800 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
801 else
802 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
803 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
804 return FALSE;
807 /* unprotect the import address table since it can be located in
808 * readonly section */
809 while (import_list[protect_size].u1.Ordinal) protect_size++;
810 protect_base = thunk_list;
811 protect_size *= sizeof(*thunk_list);
812 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
813 &protect_size, PAGE_READWRITE, &protect_old );
815 imp_mod = wmImp->ldr.DllBase;
816 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
818 if (!exports)
820 /* set all imported function to deadbeef */
821 while (import_list->u1.Ordinal)
823 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
825 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
826 WARN("No implementation for %s.%d", name, ordinal );
827 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
829 else
831 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
832 WARN("No implementation for %s.%s", name, pe_name->Name );
833 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
835 WARN(" imported from %s, allocating stub %p\n",
836 debugstr_w(current_modref->ldr.FullDllName.Buffer),
837 (void *)thunk_list->u1.Function );
838 import_list++;
839 thunk_list++;
841 goto done;
844 while (import_list->u1.Ordinal)
846 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
848 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
850 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
851 ordinal - exports->Base, load_path );
852 if (!thunk_list->u1.Function)
854 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
855 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
856 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
857 (void *)thunk_list->u1.Function );
859 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
861 else /* import by name */
863 IMAGE_IMPORT_BY_NAME *pe_name;
864 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
865 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
866 (const char*)pe_name->Name,
867 pe_name->Hint, load_path );
868 if (!thunk_list->u1.Function)
870 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
871 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
872 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
873 (void *)thunk_list->u1.Function );
875 TRACE_(imports)("--- %s %s.%d = %p\n",
876 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
878 import_list++;
879 thunk_list++;
882 done:
883 /* restore old protection of the import address table */
884 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
885 *pwm = wmImp;
886 return TRUE;
890 /***********************************************************************
891 * create_module_activation_context
893 static NTSTATUS create_module_activation_context( LDR_DATA_TABLE_ENTRY *module )
895 NTSTATUS status;
896 LDR_RESOURCE_INFO info;
897 const IMAGE_RESOURCE_DATA_ENTRY *entry;
899 info.Type = RT_MANIFEST;
900 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
901 info.Language = 0;
902 if (!(status = LdrFindResource_U( module->DllBase, &info, 3, &entry )))
904 ACTCTXW ctx;
905 ctx.cbSize = sizeof(ctx);
906 ctx.lpSource = NULL;
907 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
908 ctx.hModule = module->DllBase;
909 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
910 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
912 return status;
916 /*************************************************************************
917 * is_dll_native_subsystem
919 * Check if dll is a proper native driver.
920 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
921 * while being perfectly normal DLLs. This heuristic should catch such breakages.
923 static BOOL is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
925 const IMAGE_IMPORT_DESCRIPTOR *imports;
926 DWORD i, size;
927 WCHAR buffer[16];
929 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
930 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
931 if (mod->Flags & LDR_WINE_INTERNAL) return TRUE;
933 if ((imports = RtlImageDirectoryEntryToData( mod->DllBase, TRUE,
934 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
936 for (i = 0; imports[i].Name; i++)
938 const char *name = get_rva( mod->DllBase, imports[i].Name );
939 DWORD len = strlen(name);
940 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
941 ascii_to_unicode( buffer, name, len + 1 );
942 if (!wcsicmp( buffer, L"ntdll.dll" ) || !wcsicmp( buffer, L"kernel32.dll" ))
944 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
945 return FALSE;
949 return TRUE;
952 /*************************************************************************
953 * alloc_tls_slot
955 * Allocate a TLS slot for a newly-loaded module.
956 * The loader_section must be locked while calling this function.
958 static SHORT alloc_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
960 const IMAGE_TLS_DIRECTORY *dir;
961 ULONG i, size;
962 void *new_ptr;
963 LIST_ENTRY *entry;
965 if (!(dir = RtlImageDirectoryEntryToData( mod->DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
966 return -1;
968 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
969 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
971 for (i = 0; i < tls_module_count; i++)
973 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
974 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
975 break;
978 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->DllBase,
979 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
980 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
982 if (i == tls_module_count)
984 UINT new_count = max( 32, tls_module_count * 2 );
986 if (!tls_dirs)
987 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
988 else
989 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
990 new_count * sizeof(*tls_dirs) );
991 if (!new_ptr) return -1;
993 /* resize the pointer block in all running threads */
994 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
996 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
997 void **old = teb->ThreadLocalStoragePointer;
998 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
1000 if (!new) return -1;
1001 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
1002 teb->ThreadLocalStoragePointer = new;
1003 #ifdef __x86_64__ /* macOS-specific hack */
1004 if (teb->Reserved5[0]) ((TEB *)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
1005 #endif
1006 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
1007 /* FIXME: can't free old block here, should be freed at thread exit */
1010 tls_dirs = new_ptr;
1011 tls_module_count = new_count;
1014 /* allocate the data block in all running threads */
1015 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1017 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1019 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
1020 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
1021 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
1023 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1024 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
1026 RtlFreeHeap( GetProcessHeap(), 0,
1027 InterlockedExchangePointer( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
1030 *(DWORD *)dir->AddressOfIndex = i;
1031 tls_dirs[i] = *dir;
1032 return i;
1036 /*************************************************************************
1037 * free_tls_slot
1039 * Free the module TLS slot on unload.
1040 * The loader_section must be locked while calling this function.
1042 static void free_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1044 ULONG i = (USHORT)mod->TlsIndex;
1046 if (mod->TlsIndex == -1) return;
1047 assert( i < tls_module_count );
1048 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
1052 /****************************************************************
1053 * fixup_imports_ilonly
1055 * Fixup imports for an IL-only module. All we do is import mscoree.
1056 * The loader_section must be locked while calling this function.
1058 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
1060 IMAGE_EXPORT_DIRECTORY *exports;
1061 DWORD exp_size;
1062 NTSTATUS status;
1063 void *proc = NULL;
1064 WINE_MODREF *prev, *imp;
1066 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1067 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1069 if (!grow_module_deps( wm, 1 )) return STATUS_NO_MEMORY;
1070 wm->nDeps = 1;
1072 prev = current_modref;
1073 current_modref = wm;
1074 if (!(status = load_dll( load_path, L"mscoree.dll", NULL, 0, &imp ))) wm->deps[0] = imp;
1075 current_modref = prev;
1076 if (status)
1078 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1079 debugstr_w(wm->ldr.BaseDllName.Buffer) );
1080 return status;
1083 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1085 if ((exports = RtlImageDirectoryEntryToData( imp->ldr.DllBase, TRUE,
1086 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1088 const char *name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
1089 proc = find_named_export( imp->ldr.DllBase, exports, exp_size, name, -1, load_path );
1091 if (!proc) return STATUS_PROCEDURE_NOT_FOUND;
1092 *entry = proc;
1093 return STATUS_SUCCESS;
1097 /****************************************************************
1098 * fixup_imports
1100 * Fixup all imports of a given module.
1101 * The loader_section must be locked while calling this function.
1103 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1105 int i, dep, nb_imports;
1106 const IMAGE_IMPORT_DESCRIPTOR *imports;
1107 WINE_MODREF *prev, *imp;
1108 DWORD size;
1109 NTSTATUS status;
1110 ULONG_PTR cookie;
1112 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1113 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1115 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
1117 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
1118 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1119 return STATUS_SUCCESS;
1121 nb_imports = 0;
1122 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1124 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1125 if (!grow_module_deps( wm, nb_imports )) return STATUS_NO_MEMORY;
1127 if (!create_module_activation_context( &wm->ldr ))
1128 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1130 /* load the imported modules. They are automatically
1131 * added to the modref list of the process.
1133 prev = current_modref;
1134 current_modref = wm;
1135 status = STATUS_SUCCESS;
1136 for (i = 0; i < nb_imports; i++)
1138 dep = wm->nDeps++;
1140 if (!import_dll( wm->ldr.DllBase, &imports[i], load_path, &imp ))
1142 imp = NULL;
1143 status = STATUS_DLL_NOT_FOUND;
1145 wm->deps[dep] = imp;
1147 current_modref = prev;
1148 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1149 return status;
1153 /*************************************************************************
1154 * alloc_module
1156 * Allocate a WINE_MODREF structure and add it to the process list
1157 * The loader_section must be locked while calling this function.
1159 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name, BOOL builtin )
1161 WCHAR *buffer;
1162 WINE_MODREF *wm;
1163 const WCHAR *p;
1164 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1166 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1168 wm->ldr.DllBase = hModule;
1169 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1170 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS | (builtin ? LDR_WINE_INTERNAL : 0);
1171 wm->ldr.TlsIndex = -1;
1172 wm->ldr.LoadCount = 1;
1173 wm->ldr.CheckSum = nt->OptionalHeader.CheckSum;
1174 wm->ldr.TimeDateStamp = nt->FileHeader.TimeDateStamp;
1176 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, nt_name->Length - 3 * sizeof(WCHAR) )))
1178 RtlFreeHeap( GetProcessHeap(), 0, wm );
1179 return NULL;
1181 memcpy( buffer, nt_name->Buffer + 4 /* \??\ prefix */, nt_name->Length - 4 * sizeof(WCHAR) );
1182 buffer[nt_name->Length/sizeof(WCHAR) - 4] = 0;
1183 if ((p = wcsrchr( buffer, '\\' ))) p++;
1184 else p = buffer;
1185 RtlInitUnicodeString( &wm->ldr.FullDllName, buffer );
1186 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1188 if (!is_dll_native_subsystem( &wm->ldr, nt, p ))
1190 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1191 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1192 if (nt->OptionalHeader.AddressOfEntryPoint)
1193 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1196 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1197 &wm->ldr.InLoadOrderLinks);
1198 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1199 &wm->ldr.InMemoryOrderLinks);
1200 /* wait until init is called for inserting into InInitializationOrderModuleList */
1202 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1204 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1205 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1206 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1208 return wm;
1212 /*************************************************************************
1213 * alloc_thread_tls
1215 * Allocate the per-thread structure for module TLS storage.
1217 static NTSTATUS alloc_thread_tls(void)
1219 void **pointers;
1220 UINT i, size;
1222 if (!tls_module_count) return STATUS_SUCCESS;
1224 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1225 tls_module_count * sizeof(*pointers) )))
1226 return STATUS_NO_MEMORY;
1228 for (i = 0; i < tls_module_count; i++)
1230 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1232 if (!dir) continue;
1233 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1234 if (!size && !dir->SizeOfZeroFill) continue;
1236 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1238 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1239 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1240 return STATUS_NO_MEMORY;
1242 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1243 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1245 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1246 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1248 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1249 #ifdef __x86_64__ /* macOS-specific hack */
1250 if (NtCurrentTeb()->Reserved5[0])
1251 ((TEB *)NtCurrentTeb()->Reserved5[0])->ThreadLocalStoragePointer = pointers;
1252 #endif
1253 return STATUS_SUCCESS;
1257 /*************************************************************************
1258 * call_tls_callbacks
1260 static void call_tls_callbacks( HMODULE module, UINT reason )
1262 const IMAGE_TLS_DIRECTORY *dir;
1263 const PIMAGE_TLS_CALLBACK *callback;
1264 ULONG dirsize;
1266 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1267 if (!dir || !dir->AddressOfCallBacks) return;
1269 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1271 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1272 *callback, module, reason_names[reason] );
1273 __TRY
1275 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1277 __EXCEPT_ALL
1279 TRACE_(relay)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1280 GetExceptionCode(), callback, module, reason_names[reason] );
1281 return;
1283 __ENDTRY
1284 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1285 *callback, module, reason_names[reason] );
1289 /*************************************************************************
1290 * MODULE_InitDLL
1292 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1294 WCHAR mod_name[32];
1295 NTSTATUS status = STATUS_SUCCESS;
1296 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1297 void *module = wm->ldr.DllBase;
1298 BOOL retv = FALSE;
1300 /* Skip calls for modules loaded with special load flags */
1302 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1303 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, reason );
1304 if (wm->ldr.Flags & LDR_WINE_INTERNAL && reason == DLL_PROCESS_ATTACH)
1305 unix_funcs->init_builtin_dll( wm->ldr.DllBase );
1306 if (!entry) return STATUS_SUCCESS;
1308 if (TRACE_ON(relay))
1310 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1311 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1312 mod_name[len / sizeof(WCHAR)] = 0;
1313 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1314 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1316 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1317 reason_names[reason], lpReserved );
1319 __TRY
1321 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1322 if (!retv)
1323 status = STATUS_DLL_INIT_FAILED;
1325 __EXCEPT_ALL
1327 status = GetExceptionCode();
1328 TRACE_(relay)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1329 status, entry, module, reason_names[reason], lpReserved );
1331 __ENDTRY
1333 /* The state of the module list may have changed due to the call
1334 to the dll. We cannot assume that this module has not been
1335 deleted. */
1336 if (TRACE_ON(relay))
1337 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1338 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1339 else
1340 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1342 return status;
1346 /*************************************************************************
1347 * process_attach
1349 * Send the process attach notification to all DLLs the given module
1350 * depends on (recursively). This is somewhat complicated due to the fact that
1352 * - we have to respect the module dependencies, i.e. modules implicitly
1353 * referenced by another module have to be initialized before the module
1354 * itself can be initialized
1356 * - the initialization routine of a DLL can itself call LoadLibrary,
1357 * thereby introducing a whole new set of dependencies (even involving
1358 * the 'old' modules) at any time during the whole process
1360 * (Note that this routine can be recursively entered not only directly
1361 * from itself, but also via LoadLibrary from one of the called initialization
1362 * routines.)
1364 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1365 * the process *detach* notifications to be sent in the correct order.
1366 * This must not only take into account module dependencies, but also
1367 * 'hidden' dependencies created by modules calling LoadLibrary in their
1368 * attach notification routine.
1370 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1371 * list after the attach notification has returned. This implies that the
1372 * detach notifications are called in the reverse of the sequence the attach
1373 * notifications *returned*.
1375 * The loader_section must be locked while calling this function.
1377 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1379 NTSTATUS status = STATUS_SUCCESS;
1380 ULONG_PTR cookie;
1381 int i;
1383 if (process_detaching) return status;
1385 /* prevent infinite recursion in case of cyclical dependencies */
1386 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1387 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1388 return status;
1390 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1392 /* Tag current MODREF to prevent recursive loop */
1393 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1394 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1395 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1397 /* Recursively attach all DLLs this one depends on */
1398 for ( i = 0; i < wm->nDeps; i++ )
1400 if (!wm->deps[i]) continue;
1401 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1404 if (!wm->ldr.InInitializationOrderLinks.Flink)
1405 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1406 &wm->ldr.InInitializationOrderLinks);
1408 /* Call DLL entry point */
1409 if (status == STATUS_SUCCESS)
1411 WINE_MODREF *prev = current_modref;
1412 current_modref = wm;
1414 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1415 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1416 if (status == STATUS_SUCCESS)
1418 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1420 else
1422 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1423 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1425 /* point to the name so LdrInitializeThunk can print it */
1426 last_failed_modref = wm;
1427 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1429 current_modref = prev;
1432 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1433 /* Remove recursion flag */
1434 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1436 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1437 return status;
1441 /*************************************************************************
1442 * process_detach
1444 * Send DLL process detach notifications. See the comment about calling
1445 * sequence at process_attach.
1447 static void process_detach(void)
1449 PLIST_ENTRY mark, entry;
1450 PLDR_DATA_TABLE_ENTRY mod;
1452 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1455 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1457 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1458 InInitializationOrderLinks);
1459 /* Check whether to detach this DLL */
1460 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1461 continue;
1462 if ( mod->LoadCount && !process_detaching )
1463 continue;
1465 /* Call detach notification */
1466 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1467 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1468 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1469 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1471 /* Restart at head of WINE_MODREF list, as entries might have
1472 been added and/or removed while performing the call ... */
1473 break;
1475 } while (entry != mark);
1478 /*************************************************************************
1479 * thread_attach
1481 * Send DLL thread attach notifications. These are sent in the
1482 * reverse sequence of process detach notification.
1483 * The loader_section must be locked while calling this function.
1485 static void thread_attach(void)
1487 PLIST_ENTRY mark, entry;
1488 PLDR_DATA_TABLE_ENTRY mod;
1490 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1491 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1493 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1494 InInitializationOrderLinks);
1495 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1496 continue;
1497 if ( mod->Flags & LDR_NO_DLL_CALLS )
1498 continue;
1500 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1504 /******************************************************************
1505 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1508 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1510 WINE_MODREF *wm;
1511 NTSTATUS ret = STATUS_SUCCESS;
1513 RtlEnterCriticalSection( &loader_section );
1515 wm = get_modref( hModule );
1516 if (!wm || wm->ldr.TlsIndex != -1)
1517 ret = STATUS_DLL_NOT_FOUND;
1518 else
1519 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1521 RtlLeaveCriticalSection( &loader_section );
1523 return ret;
1526 /******************************************************************
1527 * LdrFindEntryForAddress (NTDLL.@)
1529 * The loader_section must be locked while calling this function
1531 NTSTATUS WINAPI LdrFindEntryForAddress( const void *addr, PLDR_DATA_TABLE_ENTRY *pmod )
1533 PLIST_ENTRY mark, entry;
1534 PLDR_DATA_TABLE_ENTRY mod;
1536 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1537 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1539 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
1540 if (mod->DllBase <= addr &&
1541 (const char *)addr < (char*)mod->DllBase + mod->SizeOfImage)
1543 *pmod = mod;
1544 return STATUS_SUCCESS;
1547 return STATUS_NO_MORE_ENTRIES;
1550 /******************************************************************
1551 * LdrEnumerateLoadedModules (NTDLL.@)
1553 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1555 LIST_ENTRY *mark, *entry;
1556 LDR_DATA_TABLE_ENTRY *mod;
1557 BOOLEAN stop = FALSE;
1559 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1561 if (unknown || !callback)
1562 return STATUS_INVALID_PARAMETER;
1564 RtlEnterCriticalSection( &loader_section );
1566 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1567 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1569 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
1570 callback( mod, context, &stop );
1571 if (stop) break;
1574 RtlLeaveCriticalSection( &loader_section );
1575 return STATUS_SUCCESS;
1578 /******************************************************************
1579 * LdrRegisterDllNotification (NTDLL.@)
1581 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1582 void *context, void **cookie)
1584 struct ldr_notification *notify;
1586 TRACE( "(%x, %p, %p, %p)\n", flags, callback, context, cookie );
1588 if (!callback || !cookie)
1589 return STATUS_INVALID_PARAMETER;
1591 if (flags)
1592 FIXME( "ignoring flags %x\n", flags );
1594 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1595 if (!notify) return STATUS_NO_MEMORY;
1596 notify->callback = callback;
1597 notify->context = context;
1599 RtlEnterCriticalSection( &loader_section );
1600 list_add_tail( &ldr_notifications, &notify->entry );
1601 RtlLeaveCriticalSection( &loader_section );
1603 *cookie = notify;
1604 return STATUS_SUCCESS;
1607 /******************************************************************
1608 * LdrUnregisterDllNotification (NTDLL.@)
1610 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1612 struct ldr_notification *notify = cookie;
1614 TRACE( "(%p)\n", cookie );
1616 if (!notify) return STATUS_INVALID_PARAMETER;
1618 RtlEnterCriticalSection( &loader_section );
1619 list_remove( &notify->entry );
1620 RtlLeaveCriticalSection( &loader_section );
1622 RtlFreeHeap( GetProcessHeap(), 0, notify );
1623 return STATUS_SUCCESS;
1626 /******************************************************************
1627 * LdrLockLoaderLock (NTDLL.@)
1629 * Note: some flags are not implemented.
1630 * Flag 0x01 is used to raise exceptions on errors.
1632 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1634 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1636 if (result) *result = 0;
1637 if (magic) *magic = 0;
1638 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1639 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1640 if (!magic) return STATUS_INVALID_PARAMETER_3;
1642 if (flags & 0x2)
1644 if (!RtlTryEnterCriticalSection( &loader_section ))
1646 *result = 2;
1647 return STATUS_SUCCESS;
1649 *result = 1;
1651 else
1653 RtlEnterCriticalSection( &loader_section );
1654 if (result) *result = 1;
1656 *magic = GetCurrentThreadId();
1657 return STATUS_SUCCESS;
1661 /******************************************************************
1662 * LdrUnlockLoaderUnlock (NTDLL.@)
1664 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1666 if (magic)
1668 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1669 RtlLeaveCriticalSection( &loader_section );
1671 return STATUS_SUCCESS;
1675 /******************************************************************
1676 * LdrGetProcedureAddress (NTDLL.@)
1678 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1679 ULONG ord, PVOID *address)
1681 IMAGE_EXPORT_DIRECTORY *exports;
1682 DWORD exp_size;
1683 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1685 RtlEnterCriticalSection( &loader_section );
1687 /* check if the module itself is invalid to return the proper error */
1688 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1689 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1690 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1692 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, NULL )
1693 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, NULL );
1694 if (proc)
1696 *address = proc;
1697 ret = STATUS_SUCCESS;
1701 RtlLeaveCriticalSection( &loader_section );
1702 return ret;
1706 /***********************************************************************
1707 * set_security_cookie
1709 * Create a random security cookie for buffer overflow protection. Make
1710 * sure it does not accidentally match the default cookie value.
1712 static void set_security_cookie( void *module, SIZE_T len )
1714 static ULONG seed;
1715 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1716 ULONG loadcfg_size;
1717 ULONG_PTR *cookie;
1719 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1720 if (!loadcfg) return;
1721 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1722 if (!loadcfg->SecurityCookie) return;
1723 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1724 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1726 WARN( "security cookie %p outside of image %p-%p\n",
1727 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1728 return;
1731 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1732 TRACE( "initializing security cookie %p\n", cookie );
1734 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1735 for (;;)
1737 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1738 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1739 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1740 *cookie = RtlRandom( &seed );
1741 #ifdef DEFAULT_SECURITY_COOKIE_64
1742 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1744 *cookie = RtlRandom( &seed );
1745 /* fill up, but keep the highest word clear */
1746 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1748 #endif
1749 else
1750 break;
1754 static NTSTATUS perform_relocations( void *module, IMAGE_NT_HEADERS *nt, SIZE_T len )
1756 char *base;
1757 IMAGE_BASE_RELOCATION *rel, *end;
1758 const IMAGE_DATA_DIRECTORY *relocs;
1759 const IMAGE_SECTION_HEADER *sec;
1760 INT_PTR delta;
1761 ULONG protect_old[96], i;
1763 base = (char *)nt->OptionalHeader.ImageBase;
1764 if (module == base) return STATUS_SUCCESS; /* nothing to do */
1766 /* no relocations are performed on non page-aligned binaries */
1767 if (nt->OptionalHeader.SectionAlignment < page_size)
1768 return STATUS_SUCCESS;
1770 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1771 return STATUS_SUCCESS;
1773 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1775 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1777 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1778 base, module );
1779 return STATUS_CONFLICTING_ADDRESSES;
1782 if (!relocs->Size) return STATUS_SUCCESS;
1783 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1785 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
1786 return STATUS_INVALID_IMAGE_FORMAT;
1788 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1789 nt->FileHeader.SizeOfOptionalHeader);
1790 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1792 void *addr = get_rva( module, sec[i].VirtualAddress );
1793 SIZE_T size = sec[i].SizeOfRawData;
1794 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1795 &size, PAGE_READWRITE, &protect_old[i] );
1798 TRACE( "relocating from %p-%p to %p-%p\n",
1799 base, base + len, module, (char *)module + len );
1801 rel = get_rva( module, relocs->VirtualAddress );
1802 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1803 delta = (char *)module - base;
1805 while (rel < end - 1 && rel->SizeOfBlock)
1807 if (rel->VirtualAddress >= len)
1809 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1810 return STATUS_ACCESS_VIOLATION;
1812 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1813 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1814 (USHORT *)(rel + 1), delta );
1815 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1818 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1820 void *addr = get_rva( module, sec[i].VirtualAddress );
1821 SIZE_T size = sec[i].SizeOfRawData;
1822 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1823 &size, protect_old[i], &protect_old[i] );
1826 return STATUS_SUCCESS;
1830 /*************************************************************************
1831 * build_module
1833 * Build the module data for a mapped dll.
1835 static NTSTATUS build_module( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module,
1836 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
1837 DWORD flags, WINE_MODREF **pwm )
1839 static const char builtin_signature[] = "Wine builtin DLL";
1840 char *signature = (char *)((IMAGE_DOS_HEADER *)*module + 1);
1841 BOOL is_builtin;
1842 IMAGE_NT_HEADERS *nt;
1843 WINE_MODREF *wm;
1844 NTSTATUS status;
1845 SIZE_T map_size;
1847 if (!(nt = RtlImageNtHeader( *module ))) return STATUS_INVALID_IMAGE_FORMAT;
1849 map_size = (nt->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
1850 if ((status = perform_relocations( *module, nt, map_size ))) return status;
1852 is_builtin = ((char *)nt - signature >= sizeof(builtin_signature) &&
1853 !memcmp( signature, builtin_signature, sizeof(builtin_signature) ));
1855 /* create the MODREF */
1857 if (!(wm = alloc_module( *module, nt_name, is_builtin ))) return STATUS_NO_MEMORY;
1859 if (id) wm->id = *id;
1860 if (image_info->LoaderFlags) wm->ldr.Flags |= LDR_COR_IMAGE;
1861 if (image_info->u.s.ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
1863 set_security_cookie( *module, map_size );
1865 /* fixup imports */
1867 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1868 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1869 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1871 if (wm->ldr.Flags & LDR_COR_ILONLY)
1872 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
1873 else
1874 status = fixup_imports( wm, load_path );
1875 if (status != STATUS_SUCCESS)
1877 /* the module has only be inserted in the load & memory order lists */
1878 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
1879 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
1881 /* FIXME: there are several more dangling references
1882 * left. Including dlls loaded by this dll before the
1883 * failed one. Unrolling is rather difficult with the
1884 * current structure and we can leave them lying
1885 * around with no problems, so we don't care.
1886 * As these might reference our wm, we don't free it.
1888 *module = NULL;
1889 return status;
1893 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name), wm, *module );
1895 if (is_builtin)
1897 if (TRACE_ON(relay)) RELAY_SetupDLL( *module );
1899 else
1901 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( *module );
1904 TRACE_(loaddll)( "Loaded %s at %p: %s\n", debugstr_w(wm->ldr.FullDllName.Buffer), *module,
1905 is_builtin ? "builtin" : "native" );
1907 wm->ldr.LoadCount = 1;
1908 *pwm = wm;
1909 *module = NULL;
1910 return STATUS_SUCCESS;
1914 /*************************************************************************
1915 * build_ntdll_module
1917 * Build the module data for the initially-loaded ntdll.
1919 static void build_ntdll_module(void)
1921 MEMORY_BASIC_INFORMATION meminfo;
1922 FILE_BASIC_INFORMATION basic_info;
1923 UNICODE_STRING nt_name;
1924 OBJECT_ATTRIBUTES attr;
1925 WINE_MODREF *wm;
1927 RtlInitUnicodeString( &nt_name, L"\\??\\C:\\windows\\system32\\ntdll.dll" );
1928 InitializeObjectAttributes( &attr, &nt_name, OBJ_CASE_INSENSITIVE, 0, NULL );
1929 is_prefix_bootstrap = NtQueryAttributesFile( &attr, &basic_info) != STATUS_SUCCESS;
1930 NtQueryVirtualMemory( GetCurrentProcess(), build_ntdll_module, MemoryBasicInformation,
1931 &meminfo, sizeof(meminfo), NULL );
1932 wm = alloc_module( meminfo.AllocationBase, &nt_name, TRUE );
1933 assert( wm );
1934 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1935 if (TRACE_ON(relay)) RELAY_SetupDLL( meminfo.AllocationBase );
1939 #ifdef _WIN64
1940 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1941 static BOOL convert_to_pe64( HMODULE module, const SECTION_IMAGE_INFORMATION *info )
1943 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
1944 IMAGE_DIRECTORY_ENTRY_SECURITY,
1945 IMAGE_DIRECTORY_ENTRY_BASERELOC,
1946 IMAGE_DIRECTORY_ENTRY_DEBUG,
1947 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
1948 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
1949 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
1950 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1951 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
1952 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
1953 SIZE_T size = min( nt->OptionalHeader.SizeOfHeaders, nt->OptionalHeader.SizeOfImage );
1954 void *addr = module;
1955 ULONG i, old_prot;
1957 if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return TRUE; /* already 64-bit */
1958 if (!info->ImageContainsCode) return TRUE; /* no need to convert */
1960 TRACE( "%p\n", module );
1962 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
1963 return FALSE;
1965 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
1967 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1968 return FALSE;
1971 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
1972 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
1973 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1974 hdr64.AddressOfEntryPoint = 0;
1975 hdr64.ImageBase = hdr32.ImageBase;
1976 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
1977 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
1978 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
1979 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
1980 hdr64.LoaderFlags = hdr32.LoaderFlags;
1981 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
1982 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
1983 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
1985 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
1986 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
1987 nt->OptionalHeader = hdr64;
1988 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1989 return TRUE;
1992 /* check COM header for ILONLY flag, ignoring runtime version */
1993 static BOOL get_cor_header( HANDLE file, const SECTION_IMAGE_INFORMATION *info, IMAGE_COR20_HEADER *cor )
1995 IMAGE_DOS_HEADER mz;
1996 IMAGE_NT_HEADERS32 nt;
1997 IO_STATUS_BLOCK io;
1998 LARGE_INTEGER offset;
1999 IMAGE_SECTION_HEADER sec[96];
2000 unsigned int i, count;
2001 DWORD va, size;
2003 offset.QuadPart = 0;
2004 if (NtReadFile( file, 0, NULL, NULL, &io, &mz, sizeof(mz), &offset, NULL )) return FALSE;
2005 if (io.Information != sizeof(mz)) return FALSE;
2006 if (mz.e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
2007 offset.QuadPart = mz.e_lfanew;
2008 if (NtReadFile( file, 0, NULL, NULL, &io, &nt, sizeof(nt), &offset, NULL )) return FALSE;
2009 if (io.Information != sizeof(nt)) return FALSE;
2010 if (nt.Signature != IMAGE_NT_SIGNATURE) return FALSE;
2011 if (nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return FALSE;
2012 va = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress;
2013 size = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size;
2014 if (!va || size < sizeof(*cor)) return FALSE;
2015 offset.QuadPart += offsetof( IMAGE_NT_HEADERS32, OptionalHeader ) + nt.FileHeader.SizeOfOptionalHeader;
2016 count = min( 96, nt.FileHeader.NumberOfSections );
2017 if (NtReadFile( file, 0, NULL, NULL, &io, &sec, count * sizeof(*sec), &offset, NULL )) return FALSE;
2018 if (io.Information != count * sizeof(*sec)) return FALSE;
2019 for (i = 0; i < count; i++)
2021 if (va < sec[i].VirtualAddress) continue;
2022 if (sec[i].Misc.VirtualSize && va - sec[i].VirtualAddress >= sec[i].Misc.VirtualSize) continue;
2023 offset.QuadPart = sec->PointerToRawData + va - sec[i].VirtualAddress;
2024 if (NtReadFile( file, 0, NULL, NULL, &io, cor, sizeof(*cor), &offset, NULL )) return FALSE;
2025 return (io.Information == sizeof(*cor));
2027 return FALSE;
2029 #endif
2031 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2032 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2033 static BOOL is_valid_binary( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2035 #ifdef __i386__
2036 return info->Machine == IMAGE_FILE_MACHINE_I386;
2037 #elif defined(__arm__)
2038 return info->Machine == IMAGE_FILE_MACHINE_ARM ||
2039 info->Machine == IMAGE_FILE_MACHINE_THUMB ||
2040 info->Machine == IMAGE_FILE_MACHINE_ARMNT;
2041 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2042 #ifdef __x86_64__
2043 if (info->Machine == IMAGE_FILE_MACHINE_AMD64) return TRUE;
2044 #else
2045 if (info->Machine == IMAGE_FILE_MACHINE_ARM64) return TRUE;
2046 #endif
2047 if (!info->ImageContainsCode) return TRUE;
2048 if (!(info->u.s.ComPlusNativeReady))
2050 IMAGE_COR20_HEADER cor_header;
2051 if (!get_cor_header( file, info, &cor_header )) return FALSE;
2052 if (!(cor_header.Flags & COMIMAGE_FLAGS_ILONLY)) return FALSE;
2054 return TRUE;
2055 #else
2056 return FALSE; /* no wow64 support on other platforms */
2057 #endif
2061 /******************************************************************
2062 * get_module_path_end
2064 * Returns the end of the directory component of the module path.
2066 static inline const WCHAR *get_module_path_end( const WCHAR *module )
2068 const WCHAR *p;
2069 const WCHAR *mod_end = module;
2071 if ((p = wcsrchr( mod_end, '\\' ))) mod_end = p;
2072 if ((p = wcsrchr( mod_end, '/' ))) mod_end = p;
2073 if (mod_end == module + 2 && module[1] == ':') mod_end++;
2074 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
2075 return mod_end;
2079 /******************************************************************
2080 * append_path
2082 * Append a counted string to the load path. Helper for get_dll_load_path.
2084 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str, int len )
2086 if (len == -1) len = wcslen(str);
2087 if (!len) return p;
2088 memcpy( p, str, len * sizeof(WCHAR) );
2089 p[len] = ';';
2090 return p + len + 1;
2094 /******************************************************************
2095 * get_dll_load_path
2097 static NTSTATUS get_dll_load_path( LPCWSTR module, LPCWSTR dll_dir, ULONG safe_mode, WCHAR **path )
2099 const WCHAR *mod_end = module;
2100 UNICODE_STRING name, value;
2101 WCHAR *p, *ret;
2102 int len = ARRAY_SIZE(system_path) + 1, path_len = 0;
2104 if (module)
2106 mod_end = get_module_path_end( module );
2107 len += (mod_end - module) + 1;
2110 RtlInitUnicodeString( &name, L"PATH" );
2111 value.Length = 0;
2112 value.MaximumLength = 0;
2113 value.Buffer = NULL;
2114 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2115 path_len = value.Length;
2117 if (dll_dir) len += wcslen( dll_dir ) + 1;
2118 else len += 2; /* current directory */
2119 if (!(p = ret = RtlAllocateHeap( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
2120 return STATUS_NO_MEMORY;
2122 p = append_path( p, module, mod_end - module );
2123 if (dll_dir) p = append_path( p, dll_dir, -1 );
2124 else if (!safe_mode) p = append_path( p, L".", -1 );
2125 p = append_path( p, system_path, -1 );
2126 if (!dll_dir && safe_mode) p = append_path( p, L".", -1 );
2128 value.Buffer = p;
2129 value.MaximumLength = path_len;
2131 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2133 WCHAR *new_ptr;
2135 /* grow the buffer and retry */
2136 path_len = value.Length;
2137 if (!(new_ptr = RtlReAllocateHeap( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
2139 RtlFreeHeap( GetProcessHeap(), 0, ret );
2140 return STATUS_NO_MEMORY;
2142 value.Buffer = new_ptr + (value.Buffer - ret);
2143 value.MaximumLength = path_len;
2144 ret = new_ptr;
2146 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
2147 *path = ret;
2148 return STATUS_SUCCESS;
2152 /******************************************************************
2153 * get_dll_load_path_search_flags
2155 static NTSTATUS get_dll_load_path_search_flags( LPCWSTR module, DWORD flags, WCHAR **path )
2157 const WCHAR *image = NULL, *mod_end, *image_end;
2158 struct dll_dir_entry *dir;
2159 WCHAR *p, *ret;
2160 int len = 1;
2162 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
2163 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
2164 LOAD_LIBRARY_SEARCH_USER_DIRS |
2165 LOAD_LIBRARY_SEARCH_SYSTEM32);
2167 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
2169 DWORD type = RtlDetermineDosPathNameType_U( module );
2170 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH && type != DEVICE_PATH)
2171 return STATUS_INVALID_PARAMETER;
2172 mod_end = get_module_path_end( module );
2173 len += (mod_end - module) + 1;
2175 else module = NULL;
2177 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
2179 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
2180 image_end = get_module_path_end( image );
2181 len += (image_end - image) + 1;
2184 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2186 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2187 len += wcslen( dir->dir + 4 /* \??\ */ ) + 1;
2188 if (dll_directory.Length) len += dll_directory.Length / sizeof(WCHAR) + 1;
2191 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += wcslen( system_dir );
2193 if ((p = ret = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2195 if (module) p = append_path( p, module, mod_end - module );
2196 if (image) p = append_path( p, image, image_end - image );
2197 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2199 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2200 p = append_path( p, dir->dir + 4 /* \??\ */, -1 );
2201 p = append_path( p, dll_directory.Buffer, dll_directory.Length / sizeof(WCHAR) );
2203 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) wcscpy( p, system_dir );
2204 else
2206 if (p > ret) p--;
2207 *p = 0;
2210 *path = ret;
2211 return STATUS_SUCCESS;
2215 /***********************************************************************
2216 * open_dll_file
2218 * Open a file for a new dll. Helper for find_dll_file.
2220 static NTSTATUS open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2221 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2223 FILE_BASIC_INFORMATION info;
2224 OBJECT_ATTRIBUTES attr;
2225 IO_STATUS_BLOCK io;
2226 LARGE_INTEGER size;
2227 FILE_OBJECTID_BUFFER fid;
2228 NTSTATUS status;
2229 HANDLE handle;
2231 if ((*pwm = find_fullname_module( nt_name ))) return STATUS_SUCCESS;
2233 attr.Length = sizeof(attr);
2234 attr.RootDirectory = 0;
2235 attr.Attributes = OBJ_CASE_INSENSITIVE;
2236 attr.ObjectName = nt_name;
2237 attr.SecurityDescriptor = NULL;
2238 attr.SecurityQualityOfService = NULL;
2239 if ((status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2240 FILE_SHARE_READ | FILE_SHARE_DELETE,
2241 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
2243 if (status != STATUS_OBJECT_PATH_NOT_FOUND &&
2244 status != STATUS_OBJECT_NAME_NOT_FOUND &&
2245 !NtQueryAttributesFile( &attr, &info ))
2247 /* if the file exists but failed to open, report the error */
2248 return status;
2250 /* otherwise continue searching */
2251 return STATUS_DLL_NOT_FOUND;
2254 if (!NtFsControlFile( handle, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &fid, sizeof(fid) ))
2256 memcpy( id, fid.ObjectId, sizeof(*id) );
2257 if ((*pwm = find_fileid_module( id )))
2259 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2260 (*pwm)->ldr.DllBase, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2261 NtClose( handle );
2262 return STATUS_SUCCESS;
2266 size.QuadPart = 0;
2267 status = NtCreateSection( mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2268 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2269 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, handle );
2270 if (!status)
2272 NtQuerySection( *mapping, SectionImageInformation, image_info, sizeof(*image_info), NULL );
2273 if (!is_valid_binary( handle, image_info ))
2275 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name), image_info->Machine );
2276 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2277 NtClose( *mapping );
2280 NtClose( handle );
2281 return status;
2285 /******************************************************************************
2286 * find_existing_module
2288 * Find an existing module that is the same mapping as the new module.
2290 static WINE_MODREF *find_existing_module( HMODULE module )
2292 WINE_MODREF *wm;
2293 LIST_ENTRY *mark, *entry;
2294 LDR_DATA_TABLE_ENTRY *mod;
2295 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
2297 if ((wm = get_modref( module ))) return wm;
2299 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
2300 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2302 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
2303 if (mod->TimeDateStamp != nt->FileHeader.TimeDateStamp) continue;
2304 if (mod->CheckSum != nt->OptionalHeader.CheckSum) continue;
2305 if (NtAreMappedFilesTheSame( mod->DllBase, module ) != STATUS_SUCCESS) continue;
2306 return CONTAINING_RECORD( mod, WINE_MODREF, ldr );
2308 return NULL;
2312 /******************************************************************************
2313 * load_native_dll (internal)
2315 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, HANDLE mapping,
2316 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
2317 DWORD flags, WINE_MODREF** pwm )
2319 void *module = NULL;
2320 SIZE_T len = 0;
2321 NTSTATUS status = NtMapViewOfSection( mapping, NtCurrentProcess(), &module, 0, 0, NULL, &len,
2322 ViewShare, 0, PAGE_EXECUTE_READ );
2324 if (status == STATUS_IMAGE_NOT_AT_BASE) status = STATUS_SUCCESS;
2325 if (status) return status;
2327 if ((*pwm = find_existing_module( module ))) /* already loaded */
2329 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2330 TRACE( "found %s for %s at %p, count=%d\n",
2331 debugstr_us(&(*pwm)->ldr.FullDllName), debugstr_us(nt_name),
2332 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2333 if (module != (*pwm)->ldr.DllBase) NtUnmapViewOfSection( NtCurrentProcess(), module );
2334 return STATUS_SUCCESS;
2336 #ifdef _WIN64
2337 if (!convert_to_pe64( module, image_info )) status = STATUS_INVALID_IMAGE_FORMAT;
2338 #endif
2339 if (!status) status = build_module( load_path, nt_name, &module, image_info, id, flags, pwm );
2340 if (status && module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2341 return status;
2345 /***********************************************************************
2346 * load_so_dll
2348 static NTSTATUS load_so_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name,
2349 DWORD flags, WINE_MODREF **pwm )
2351 void *module;
2352 NTSTATUS status;
2353 WINE_MODREF *wm;
2354 UNICODE_STRING win_name = *nt_name;
2356 TRACE( "trying %s as so lib\n", debugstr_us(&win_name) );
2357 if ((status = unix_funcs->load_so_dll( &win_name, &module )))
2359 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name) );
2360 if (status == STATUS_INVALID_IMAGE_FORMAT) status = STATUS_INVALID_IMAGE_NOT_MZ;
2361 return status;
2364 if ((wm = get_modref( module ))) /* already loaded */
2366 TRACE( "Found %s at %p for builtin %s\n",
2367 debugstr_w(wm->ldr.FullDllName.Buffer), wm->ldr.DllBase, debugstr_us(nt_name) );
2368 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2370 else
2372 SECTION_IMAGE_INFORMATION image_info = { 0 };
2374 if ((status = build_module( load_path, &win_name, &module, &image_info, NULL, flags, &wm )))
2376 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2377 return status;
2379 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name), module );
2381 *pwm = wm;
2382 return STATUS_SUCCESS;
2386 /*************************************************************************
2387 * build_main_module
2389 * Build the module data for the main image.
2391 static WINE_MODREF *build_main_module(void)
2393 SECTION_IMAGE_INFORMATION info;
2394 UNICODE_STRING nt_name;
2395 WINE_MODREF *wm;
2396 NTSTATUS status;
2397 RTL_USER_PROCESS_PARAMETERS *params = NtCurrentTeb()->Peb->ProcessParameters;
2398 void *module = NtCurrentTeb()->Peb->ImageBaseAddress;
2400 default_load_path = params->DllPath.Buffer;
2401 if (!default_load_path)
2402 get_dll_load_path( params->ImagePathName.Buffer, NULL, dll_safe_mode, &default_load_path );
2404 NtQueryInformationProcess( GetCurrentProcess(), ProcessImageInformation, &info, sizeof(info), NULL );
2405 if (info.ImageCharacteristics & IMAGE_FILE_DLL)
2407 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_us(&params->ImagePathName) );
2408 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT );
2410 #ifdef _WIN64
2411 if (!convert_to_pe64( module, &info ))
2413 status = STATUS_INVALID_IMAGE_FORMAT;
2414 goto failed;
2416 #endif
2417 status = RtlDosPathNameToNtPathName_U_WithStatus( params->ImagePathName.Buffer, &nt_name, NULL, NULL );
2418 if (status) goto failed;
2419 status = build_module( NULL, &nt_name, &module, &info, NULL, DONT_RESOLVE_DLL_REFERENCES, &wm );
2420 RtlFreeUnicodeString( &nt_name );
2421 if (!status) return wm;
2422 failed:
2423 MESSAGE( "wine: failed to create main module for %s, status %x\n",
2424 debugstr_us(&params->ImagePathName), status );
2425 NtTerminateProcess( GetCurrentProcess(), status );
2426 return NULL; /* unreached */
2430 /***********************************************************************
2431 * find_actctx_dll
2433 * Find the full path (if any) of the dll from the activation context.
2435 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2437 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2439 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2440 ACTCTX_SECTION_KEYED_DATA data;
2441 UNICODE_STRING nameW;
2442 NTSTATUS status;
2443 SIZE_T needed, size = 1024;
2444 WCHAR *p;
2446 RtlInitUnicodeString( &nameW, libname );
2447 data.cbSize = sizeof(data);
2448 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2449 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2450 &nameW, &data );
2451 if (status != STATUS_SUCCESS) return status;
2453 for (;;)
2455 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2457 status = STATUS_NO_MEMORY;
2458 goto done;
2460 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2461 AssemblyDetailedInformationInActivationContext,
2462 info, size, &needed );
2463 if (status == STATUS_SUCCESS) break;
2464 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2465 RtlFreeHeap( GetProcessHeap(), 0, info );
2466 size = needed;
2467 /* restart with larger buffer */
2470 if (!info->lpAssemblyManifestPath)
2472 status = STATUS_SXS_KEY_NOT_FOUND;
2473 goto done;
2476 if ((p = wcsrchr( info->lpAssemblyManifestPath, '\\' )))
2478 DWORD len, dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2479 p++;
2480 len = wcslen( p );
2481 if (!dirlen || len <= dirlen ||
2482 RtlCompareUnicodeStrings( p, dirlen, info->lpAssemblyDirectoryName, dirlen, TRUE ) ||
2483 wcsicmp( p + dirlen, L".manifest" ))
2485 /* manifest name does not match directory name, so it's not a global
2486 * windows/winsxs manifest; use the manifest directory name instead */
2487 dirlen = p - info->lpAssemblyManifestPath;
2488 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2489 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2491 status = STATUS_NO_MEMORY;
2492 goto done;
2494 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2495 p += dirlen;
2496 wcscpy( p, libname );
2497 goto done;
2501 if (!info->lpAssemblyDirectoryName)
2503 status = STATUS_SXS_KEY_NOT_FOUND;
2504 goto done;
2507 needed = (wcslen(windows_dir) * sizeof(WCHAR) +
2508 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2510 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2512 status = STATUS_NO_MEMORY;
2513 goto done;
2515 wcscpy( p, windows_dir );
2516 p += wcslen(p);
2517 memcpy( p, winsxsW, sizeof(winsxsW) );
2518 p += ARRAY_SIZE( winsxsW );
2519 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2520 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2521 *p++ = '\\';
2522 wcscpy( p, libname );
2523 done:
2524 RtlFreeHeap( GetProcessHeap(), 0, info );
2525 RtlReleaseActivationContext( data.hActCtx );
2526 return status;
2530 /***********************************************************************
2531 * get_env_var
2533 static NTSTATUS get_env_var( const WCHAR *name, SIZE_T extra, UNICODE_STRING *ret )
2535 NTSTATUS status;
2536 SIZE_T len, size = 1024 + extra;
2538 for (;;)
2540 ret->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, size );
2541 status = RtlQueryEnvironmentVariable( NULL, name, wcslen(name),
2542 ret->Buffer, size - extra - 1, &len );
2543 if (!status)
2545 ret->Buffer[len] = 0;
2546 ret->Length = len * sizeof(WCHAR);
2547 ret->MaximumLength = size * sizeof(WCHAR);
2548 return status;
2550 RtlFreeHeap( GetProcessHeap(), 0, ret->Buffer );
2551 if (status != STATUS_BUFFER_TOO_SMALL) return status;
2552 size = len + 1 + extra;
2557 /***********************************************************************
2558 * find_builtin_without_file
2560 * Find a builtin dll when the corresponding file cannot be found in the prefix.
2561 * This is used during prefix bootstrap.
2563 static NTSTATUS find_builtin_without_file( const WCHAR *name, UNICODE_STRING *new_name,
2564 WINE_MODREF **pwm, HANDLE *mapping,
2565 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2567 const WCHAR *ext;
2568 WCHAR dllpath[32];
2569 DWORD i, len;
2570 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2571 BOOL found_image = FALSE;
2573 if (!get_env_var( L"WINEBUILDDIR", 20 + 2 * wcslen(name), new_name ))
2575 RtlAppendUnicodeToString( new_name, L"\\dlls\\" );
2576 RtlAppendUnicodeToString( new_name, name );
2577 if ((ext = wcsrchr( name, '.' )) && !wcscmp( ext, L".dll" )) new_name->Length -= 4 * sizeof(WCHAR);
2578 RtlAppendUnicodeToString( new_name, L"\\" );
2579 RtlAppendUnicodeToString( new_name, name );
2580 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2581 if (status != STATUS_DLL_NOT_FOUND) goto done;
2582 RtlAppendUnicodeToString( new_name, L".fake" );
2583 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2584 if (status != STATUS_DLL_NOT_FOUND) goto done;
2585 RtlFreeUnicodeString( new_name );
2587 for (i = 0; ; i++)
2589 swprintf( dllpath, ARRAY_SIZE(dllpath), L"WINEDLLDIR%u", i );
2590 if (get_env_var( dllpath, 20 + wcslen(name), new_name )) break;
2591 len = new_name->Length;
2592 RtlAppendUnicodeToString( new_name, L"\\" );
2593 RtlAppendUnicodeToString( new_name, name );
2594 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2595 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2596 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2597 new_name->Length = len;
2598 RtlAppendUnicodeToString( new_name, L"\\fakedlls\\" );
2599 RtlAppendUnicodeToString( new_name, name );
2600 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2601 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2602 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2603 RtlFreeUnicodeString( new_name );
2605 if (found_image) status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2607 done:
2608 RtlFreeUnicodeString( new_name );
2609 if (!status)
2611 new_name->Length = (4 + wcslen(system_dir) + wcslen(name)) * sizeof(WCHAR);
2612 new_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, new_name->Length + sizeof(WCHAR) );
2613 wcscpy( new_name->Buffer, L"\\??\\" );
2614 wcscat( new_name->Buffer, system_dir );
2615 wcscat( new_name->Buffer, name );
2617 return status;
2621 /***********************************************************************
2622 * search_dll_file
2624 * Search for dll in the specified paths.
2626 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name,
2627 WINE_MODREF **pwm, HANDLE *mapping, SECTION_IMAGE_INFORMATION *image_info,
2628 struct file_id *id )
2630 WCHAR *name;
2631 BOOL found_image = FALSE;
2632 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2633 ULONG len;
2635 if (!paths) paths = default_load_path;
2636 len = wcslen( paths );
2638 if (len < wcslen( system_dir )) len = wcslen( system_dir );
2639 len += wcslen( search ) + 2;
2641 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2642 return STATUS_NO_MEMORY;
2644 while (*paths)
2646 LPCWSTR ptr = paths;
2648 while (*ptr && *ptr != ';') ptr++;
2649 len = ptr - paths;
2650 if (*ptr == ';') ptr++;
2651 memcpy( name, paths, len * sizeof(WCHAR) );
2652 if (len && name[len - 1] != '\\') name[len++] = '\\';
2653 wcscpy( name + len, search );
2655 nt_name->Buffer = NULL;
2656 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( name, nt_name, NULL, NULL ))) goto done;
2658 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
2659 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2660 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2661 RtlFreeUnicodeString( nt_name );
2662 paths = ptr;
2665 if (found_image)
2666 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2667 else if (is_prefix_bootstrap && !wcspbrk( search, L":/\\" ))
2668 status = find_builtin_without_file( search, nt_name, pwm, mapping, image_info, id );
2670 done:
2671 RtlFreeHeap( GetProcessHeap(), 0, name );
2672 return status;
2676 /***********************************************************************
2677 * find_dll_file
2679 * Find the file (or already loaded module) for a given dll name.
2681 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2682 UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2683 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2685 WCHAR *ext, *dllname;
2686 NTSTATUS status;
2687 ULONG wow64_old_value = 0;
2689 *pwm = NULL;
2690 dllname = NULL;
2692 if (default_ext) /* first append default extension */
2694 if (!(ext = wcsrchr( libname, '.')) || wcschr( ext, '/' ) || wcschr( ext, '\\'))
2696 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2697 (wcslen(libname)+wcslen(default_ext)+1) * sizeof(WCHAR))))
2698 return STATUS_NO_MEMORY;
2699 wcscpy( dllname, libname );
2700 wcscat( dllname, default_ext );
2701 libname = dllname;
2705 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2706 RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value );
2708 nt_name->Buffer = NULL;
2710 if (!contains_path( libname ))
2712 WCHAR *fullname = NULL;
2714 status = find_actctx_dll( libname, &fullname );
2715 if (status == STATUS_SUCCESS)
2717 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2718 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2719 libname = dllname = fullname;
2721 else
2723 if (status != STATUS_SXS_KEY_NOT_FOUND) goto done;
2724 if ((*pwm = find_basename_module( libname )) != NULL)
2726 status = STATUS_SUCCESS;
2727 goto done;
2732 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2733 status = search_dll_file( load_path, libname, nt_name, pwm, mapping, image_info, id );
2734 else if (!(status = RtlDosPathNameToNtPathName_U_WithStatus( libname, nt_name, NULL, NULL )))
2735 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
2737 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) status = STATUS_INVALID_IMAGE_FORMAT;
2739 done:
2740 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2741 if (wow64_old_value) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value );
2742 return status;
2746 /***********************************************************************
2747 * load_dll (internal)
2749 * Load a PE style module according to the load order.
2750 * The loader_section must be locked while calling this function.
2752 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2753 DWORD flags, WINE_MODREF** pwm )
2755 UNICODE_STRING nt_name;
2756 struct file_id id;
2757 HANDLE mapping = 0;
2758 SECTION_IMAGE_INFORMATION image_info;
2759 NTSTATUS nts;
2760 void *prev;
2762 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2764 nts = find_dll_file( load_path, libname, default_ext, &nt_name, pwm, &mapping, &image_info, &id );
2766 if (*pwm) /* found already loaded module */
2768 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2770 TRACE("Found %s for %s at %p, count=%d\n",
2771 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2772 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2773 RtlFreeUnicodeString( &nt_name );
2774 return STATUS_SUCCESS;
2777 if (nts && nts != STATUS_INVALID_IMAGE_NOT_MZ) goto done;
2779 prev = NtCurrentTeb()->Tib.ArbitraryUserPointer;
2780 NtCurrentTeb()->Tib.ArbitraryUserPointer = nt_name.Buffer + 4;
2782 switch (nts)
2784 case STATUS_INVALID_IMAGE_NOT_MZ: /* not in PE format, maybe it's a .so file */
2785 nts = load_so_dll( load_path, &nt_name, flags, pwm );
2786 break;
2788 case STATUS_SUCCESS: /* valid PE file */
2789 nts = load_native_dll( load_path, &nt_name, mapping, &image_info, &id, flags, pwm );
2790 break;
2792 NtCurrentTeb()->Tib.ArbitraryUserPointer = prev;
2794 done:
2795 if (nts == STATUS_SUCCESS)
2796 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name), (*pwm)->ldr.DllBase);
2797 else
2798 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2800 if (mapping) NtClose( mapping );
2801 RtlFreeUnicodeString( &nt_name );
2802 return nts;
2806 /***********************************************************************
2807 * __wine_init_unix_lib
2809 NTSTATUS __cdecl __wine_init_unix_lib( HMODULE module, DWORD reason, const void *ptr_in, void *ptr_out )
2811 WINE_MODREF *wm;
2812 NTSTATUS ret;
2814 RtlEnterCriticalSection( &loader_section );
2816 if ((wm = get_modref( module ))) ret = unix_funcs->init_unix_lib( module, reason, ptr_in, ptr_out );
2817 else ret = STATUS_INVALID_HANDLE;
2819 RtlLeaveCriticalSection( &loader_section );
2820 return ret;
2824 /******************************************************************
2825 * LdrLoadDll (NTDLL.@)
2827 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2828 const UNICODE_STRING *libname, HMODULE* hModule)
2830 WINE_MODREF *wm;
2831 NTSTATUS nts;
2833 RtlEnterCriticalSection( &loader_section );
2835 nts = load_dll( path_name, libname->Buffer, L".dll", flags, &wm );
2837 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2839 nts = process_attach( wm, NULL );
2840 if (nts != STATUS_SUCCESS)
2842 LdrUnloadDll(wm->ldr.DllBase);
2843 wm = NULL;
2846 *hModule = (wm) ? wm->ldr.DllBase : NULL;
2848 RtlLeaveCriticalSection( &loader_section );
2849 return nts;
2853 /******************************************************************
2854 * LdrGetDllHandle (NTDLL.@)
2856 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2858 NTSTATUS status;
2859 UNICODE_STRING nt_name;
2860 WINE_MODREF *wm;
2861 HANDLE mapping;
2862 SECTION_IMAGE_INFORMATION image_info;
2863 struct file_id id;
2865 RtlEnterCriticalSection( &loader_section );
2867 status = find_dll_file( load_path, name->Buffer, L".dll", &nt_name, &wm, &mapping, &image_info, &id );
2869 if (wm) *base = wm->ldr.DllBase;
2870 else
2872 if (status == STATUS_SUCCESS) NtClose( mapping );
2873 status = STATUS_DLL_NOT_FOUND;
2875 RtlFreeUnicodeString( &nt_name );
2877 RtlLeaveCriticalSection( &loader_section );
2878 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2879 return status;
2883 /******************************************************************
2884 * LdrAddRefDll (NTDLL.@)
2886 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2888 NTSTATUS ret = STATUS_SUCCESS;
2889 WINE_MODREF *wm;
2891 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2893 RtlEnterCriticalSection( &loader_section );
2895 if ((wm = get_modref( module )))
2897 if (flags & LDR_ADDREF_DLL_PIN)
2898 wm->ldr.LoadCount = -1;
2899 else
2900 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2901 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2903 else ret = STATUS_INVALID_PARAMETER;
2905 RtlLeaveCriticalSection( &loader_section );
2906 return ret;
2910 /***********************************************************************
2911 * LdrProcessRelocationBlock (NTDLL.@)
2913 * Apply relocations to a given page of a mapped PE image.
2915 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2916 USHORT *relocs, INT_PTR delta )
2918 while (count--)
2920 USHORT offset = *relocs & 0xfff;
2921 int type = *relocs >> 12;
2922 switch(type)
2924 case IMAGE_REL_BASED_ABSOLUTE:
2925 break;
2926 case IMAGE_REL_BASED_HIGH:
2927 *(short *)((char *)page + offset) += HIWORD(delta);
2928 break;
2929 case IMAGE_REL_BASED_LOW:
2930 *(short *)((char *)page + offset) += LOWORD(delta);
2931 break;
2932 case IMAGE_REL_BASED_HIGHLOW:
2933 *(int *)((char *)page + offset) += delta;
2934 break;
2935 #ifdef _WIN64
2936 case IMAGE_REL_BASED_DIR64:
2937 *(INT_PTR *)((char *)page + offset) += delta;
2938 break;
2939 #elif defined(__arm__)
2940 case IMAGE_REL_BASED_THUMB_MOV32:
2942 DWORD *inst = (DWORD *)((char *)page + offset);
2943 WORD lo = ((inst[0] << 1) & 0x0800) + ((inst[0] << 12) & 0xf000) +
2944 ((inst[0] >> 20) & 0x0700) + ((inst[0] >> 16) & 0x00ff);
2945 WORD hi = ((inst[1] << 1) & 0x0800) + ((inst[1] << 12) & 0xf000) +
2946 ((inst[1] >> 20) & 0x0700) + ((inst[1] >> 16) & 0x00ff);
2947 DWORD imm = MAKELONG( lo, hi ) + delta;
2949 lo = LOWORD( imm );
2950 hi = HIWORD( imm );
2952 if ((inst[0] & 0x8000fbf0) != 0x0000f240 || (inst[1] & 0x8000fbf0) != 0x0000f2c0)
2953 ERR("wrong Thumb2 instruction @%p %08x:%08x, expected MOVW/MOVT\n",
2954 inst, inst[0], inst[1] );
2956 inst[0] = (inst[0] & 0x8f00fbf0) + ((lo >> 1) & 0x0400) + ((lo >> 12) & 0x000f) +
2957 ((lo << 20) & 0x70000000) + ((lo << 16) & 0xff0000);
2958 inst[1] = (inst[1] & 0x8f00fbf0) + ((hi >> 1) & 0x0400) + ((hi >> 12) & 0x000f) +
2959 ((hi << 20) & 0x70000000) + ((hi << 16) & 0xff0000);
2960 break;
2962 #endif
2963 default:
2964 FIXME("Unknown/unsupported fixup type %x.\n", type);
2965 return NULL;
2967 relocs++;
2969 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2973 /******************************************************************
2974 * LdrQueryProcessModuleInformation
2977 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2978 ULONG buf_size, ULONG* req_size)
2980 SYSTEM_MODULE* sm = &smi->Modules[0];
2981 ULONG size = sizeof(ULONG);
2982 NTSTATUS nts = STATUS_SUCCESS;
2983 ANSI_STRING str;
2984 char* ptr;
2985 PLIST_ENTRY mark, entry;
2986 LDR_DATA_TABLE_ENTRY *mod;
2987 WORD id = 0;
2989 smi->ModulesCount = 0;
2991 RtlEnterCriticalSection( &loader_section );
2992 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2993 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2995 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2996 size += sizeof(*sm);
2997 if (size <= buf_size)
2999 sm->Section = 0; /* FIXME */
3000 sm->MappedBaseAddress = mod->DllBase;
3001 sm->ImageBaseAddress = mod->DllBase;
3002 sm->ImageSize = mod->SizeOfImage;
3003 sm->Flags = mod->Flags;
3004 sm->LoadOrderIndex = id++;
3005 sm->InitOrderIndex = 0; /* FIXME */
3006 sm->LoadCount = mod->LoadCount;
3007 str.Length = 0;
3008 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
3009 str.Buffer = (char*)sm->Name;
3010 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
3011 ptr = strrchr(str.Buffer, '\\');
3012 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
3014 smi->ModulesCount++;
3015 sm++;
3017 else nts = STATUS_INFO_LENGTH_MISMATCH;
3019 RtlLeaveCriticalSection( &loader_section );
3021 if (req_size) *req_size = size;
3023 return nts;
3027 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
3029 NTSTATUS status;
3030 UNICODE_STRING str;
3031 ULONG size;
3032 WCHAR buffer[64];
3033 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3035 RtlInitUnicodeString( &str, name );
3037 size = sizeof(buffer) - sizeof(WCHAR);
3038 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
3039 return status;
3041 if (info->Type != REG_DWORD)
3043 buffer[size / sizeof(WCHAR)] = 0;
3044 *value = wcstoul( (WCHAR *)info->Data, 0, 16 );
3046 else memcpy( value, info->Data, sizeof(*value) );
3047 return status;
3050 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
3051 void *data, ULONG in_size, ULONG *out_size )
3053 NTSTATUS status;
3054 UNICODE_STRING str;
3055 ULONG size;
3056 char *buffer;
3057 KEY_VALUE_PARTIAL_INFORMATION *info;
3058 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
3060 RtlInitUnicodeString( &str, name );
3062 size = info_size + in_size;
3063 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
3064 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3065 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
3066 if (!status || status == STATUS_BUFFER_OVERFLOW)
3068 if (out_size) *out_size = info->DataLength;
3069 if (data && !status) memcpy( data, info->Data, info->DataLength );
3071 RtlFreeHeap( GetProcessHeap(), 0, buffer );
3072 return status;
3076 /******************************************************************
3077 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3079 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
3080 void *data, ULONG in_size, ULONG *out_size )
3082 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
3083 'S','o','f','t','w','a','r','e','\\',
3084 'M','i','c','r','o','s','o','f','t','\\',
3085 'W','i','n','d','o','w','s',' ','N','T','\\',
3086 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3087 'I','m','a','g','e',' ','F','i','l','e',' ',
3088 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3089 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
3090 OBJECT_ATTRIBUTES attr;
3091 UNICODE_STRING name_str;
3092 HANDLE hkey;
3093 NTSTATUS status;
3094 ULONG len;
3095 WCHAR *p;
3097 attr.Length = sizeof(attr);
3098 attr.RootDirectory = 0;
3099 attr.ObjectName = &name_str;
3100 attr.Attributes = OBJ_CASE_INSENSITIVE;
3101 attr.SecurityDescriptor = NULL;
3102 attr.SecurityQualityOfService = NULL;
3104 p = key->Buffer + key->Length / sizeof(WCHAR);
3105 while (p > key->Buffer && p[-1] != '\\') p--;
3106 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
3107 name_str.Buffer = path;
3108 name_str.Length = sizeof(optionsW) + len;
3109 name_str.MaximumLength = name_str.Length;
3110 memcpy( path, optionsW, sizeof(optionsW) );
3111 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
3112 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
3114 if (type == REG_DWORD)
3116 if (out_size) *out_size = sizeof(ULONG);
3117 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
3118 else status = STATUS_BUFFER_OVERFLOW;
3120 else status = query_string_option( hkey, value, type, data, in_size, out_size );
3122 NtClose( hkey );
3123 return status;
3127 /******************************************************************
3128 * RtlDllShutdownInProgress (NTDLL.@)
3130 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
3132 return process_detaching;
3135 /****************************************************************************
3136 * LdrResolveDelayLoadedAPI (NTDLL.@)
3138 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
3139 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
3140 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
3141 IMAGE_THUNK_DATA* addr, ULONG flags )
3143 IMAGE_THUNK_DATA *pIAT, *pINT;
3144 DELAYLOAD_INFO delayinfo;
3145 UNICODE_STRING mod;
3146 const CHAR* name;
3147 HMODULE *phmod;
3148 NTSTATUS nts;
3149 FARPROC fp;
3150 DWORD id;
3152 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base, desc, dllhook, syshook, addr, flags );
3154 phmod = get_rva(base, desc->ModuleHandleRVA);
3155 pIAT = get_rva(base, desc->ImportAddressTableRVA);
3156 pINT = get_rva(base, desc->ImportNameTableRVA);
3157 name = get_rva(base, desc->DllNameRVA);
3158 id = addr - pIAT;
3160 if (!*phmod)
3162 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
3164 nts = STATUS_NO_MEMORY;
3165 goto fail;
3167 nts = LdrLoadDll(NULL, 0, &mod, phmod);
3168 RtlFreeUnicodeString(&mod);
3169 if (nts) goto fail;
3172 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3173 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
3174 else
3176 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3177 ANSI_STRING fnc;
3179 RtlInitAnsiString(&fnc, (char*)iibn->Name);
3180 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
3182 if (!nts)
3184 pIAT[id].u1.Function = (ULONG_PTR)fp;
3185 return fp;
3188 fail:
3189 delayinfo.Size = sizeof(delayinfo);
3190 delayinfo.DelayloadDescriptor = desc;
3191 delayinfo.ThunkAddress = addr;
3192 delayinfo.TargetDllName = name;
3193 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
3194 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
3195 delayinfo.TargetModuleBase = *phmod;
3196 delayinfo.Unused = NULL;
3197 delayinfo.LastError = nts;
3199 if (dllhook)
3200 return dllhook(4, &delayinfo);
3202 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3204 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3205 return syshook(name, (const char *)ord);
3207 else
3209 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3210 return syshook(name, (const char *)iibn->Name);
3214 /******************************************************************
3215 * LdrShutdownProcess (NTDLL.@)
3218 void WINAPI LdrShutdownProcess(void)
3220 BOOL detaching = process_detaching;
3222 TRACE("()\n");
3224 process_detaching = TRUE;
3225 if (!detaching)
3226 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3228 process_detach();
3232 /******************************************************************
3233 * RtlExitUserProcess (NTDLL.@)
3235 void WINAPI RtlExitUserProcess( DWORD status )
3237 RtlEnterCriticalSection( &loader_section );
3238 RtlAcquirePebLock();
3239 NtTerminateProcess( 0, status );
3240 LdrShutdownProcess();
3241 for (;;) NtTerminateProcess( GetCurrentProcess(), status );
3244 /******************************************************************
3245 * LdrShutdownThread (NTDLL.@)
3248 void WINAPI LdrShutdownThread(void)
3250 PLIST_ENTRY mark, entry;
3251 LDR_DATA_TABLE_ENTRY *mod;
3252 WINE_MODREF *wm;
3253 UINT i;
3254 void **pointers;
3256 TRACE("()\n");
3258 /* don't do any detach calls if process is exiting */
3259 if (process_detaching) return;
3261 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3263 RtlEnterCriticalSection( &loader_section );
3264 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3266 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3267 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3269 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
3270 InInitializationOrderLinks);
3271 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3272 continue;
3273 if ( mod->Flags & LDR_NO_DLL_CALLS )
3274 continue;
3276 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3277 DLL_THREAD_DETACH, NULL );
3280 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_DETACH );
3282 RtlAcquirePebLock();
3283 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3284 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3286 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3287 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3289 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 2 );
3290 NtCurrentTeb()->FlsSlots = NULL;
3291 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3292 NtCurrentTeb()->TlsExpansionSlots = NULL;
3293 RtlReleasePebLock();
3295 RtlLeaveCriticalSection( &loader_section );
3296 /* don't call DbgUiGetThreadDebugObject as some apps hook it and terminate if called */
3297 if (NtCurrentTeb()->DbgSsReserved[1]) NtClose( NtCurrentTeb()->DbgSsReserved[1] );
3298 RtlFreeThreadActivationContextStack();
3302 /***********************************************************************
3303 * free_modref
3306 static void free_modref( WINE_MODREF *wm )
3308 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
3309 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
3310 if (wm->ldr.InInitializationOrderLinks.Flink)
3311 RemoveEntryList(&wm->ldr.InInitializationOrderLinks);
3313 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3314 if (!TRACE_ON(module))
3315 TRACE_(loaddll)("Unloaded module %s : %s\n",
3316 debugstr_w(wm->ldr.FullDllName.Buffer),
3317 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3319 free_tls_slot( &wm->ldr );
3320 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3321 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.DllBase );
3322 if (cached_modref == wm) cached_modref = NULL;
3323 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3324 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
3325 RtlFreeHeap( GetProcessHeap(), 0, wm );
3328 /***********************************************************************
3329 * MODULE_FlushModrefs
3331 * Remove all unused modrefs and call the internal unloading routines
3332 * for the library type.
3334 * The loader_section must be locked while calling this function.
3336 static void MODULE_FlushModrefs(void)
3338 PLIST_ENTRY mark, entry, prev;
3339 LDR_DATA_TABLE_ENTRY *mod;
3340 WINE_MODREF*wm;
3342 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3343 for (entry = mark->Blink; entry != mark; entry = prev)
3345 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
3346 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3347 prev = entry->Blink;
3348 if (!mod->LoadCount) free_modref( wm );
3351 /* check load order list too for modules that haven't been initialized yet */
3352 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3353 for (entry = mark->Blink; entry != mark; entry = prev)
3355 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3356 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3357 prev = entry->Blink;
3358 if (!mod->LoadCount) free_modref( wm );
3362 /***********************************************************************
3363 * MODULE_DecRefCount
3365 * The loader_section must be locked while calling this function.
3367 static void MODULE_DecRefCount( WINE_MODREF *wm )
3369 int i;
3371 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3372 return;
3374 if ( wm->ldr.LoadCount <= 0 )
3375 return;
3377 --wm->ldr.LoadCount;
3378 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3380 if ( wm->ldr.LoadCount == 0 )
3382 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3384 for ( i = 0; i < wm->nDeps; i++ )
3385 if ( wm->deps[i] )
3386 MODULE_DecRefCount( wm->deps[i] );
3388 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3390 module_push_unload_trace( &wm->ldr );
3394 /******************************************************************
3395 * LdrUnloadDll (NTDLL.@)
3399 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3401 WINE_MODREF *wm;
3402 NTSTATUS retv = STATUS_SUCCESS;
3404 if (process_detaching) return retv;
3406 TRACE("(%p)\n", hModule);
3408 RtlEnterCriticalSection( &loader_section );
3410 free_lib_count++;
3411 if ((wm = get_modref( hModule )) != NULL)
3413 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3415 /* Recursively decrement reference counts */
3416 MODULE_DecRefCount( wm );
3418 /* Call process detach notifications */
3419 if ( free_lib_count <= 1 )
3421 process_detach();
3422 MODULE_FlushModrefs();
3425 TRACE("END\n");
3427 else
3428 retv = STATUS_DLL_NOT_FOUND;
3430 free_lib_count--;
3432 RtlLeaveCriticalSection( &loader_section );
3434 return retv;
3437 /***********************************************************************
3438 * RtlImageNtHeader (NTDLL.@)
3440 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3442 IMAGE_NT_HEADERS *ret;
3444 __TRY
3446 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3448 ret = NULL;
3449 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3451 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3452 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3455 __EXCEPT_PAGE_FAULT
3457 return NULL;
3459 __ENDTRY
3460 return ret;
3463 /***********************************************************************
3464 * process_breakpoint
3466 * Trigger a debug breakpoint if the process is being debugged.
3468 static void process_breakpoint(void)
3470 DWORD_PTR port = 0;
3472 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort, &port, sizeof(port), NULL );
3473 if (!port) return;
3475 __TRY
3477 DbgBreakPoint();
3479 __EXCEPT_ALL
3481 /* do nothing */
3483 __ENDTRY
3487 #ifndef _WIN64
3488 void *Wow64Transition = NULL;
3490 static void map_wow64cpu(void)
3492 SIZE_T size = 0;
3493 OBJECT_ATTRIBUTES attr;
3494 UNICODE_STRING string;
3495 HANDLE file, section;
3496 IO_STATUS_BLOCK io;
3497 NTSTATUS status;
3499 RtlInitUnicodeString( &string, L"\\??\\C:\\windows\\sysnative\\wow64cpu.dll" );
3500 InitializeObjectAttributes( &attr, &string, 0, NULL, NULL );
3501 if ((status = NtOpenFile( &file, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ,
3502 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
3504 WARN("failed to open wow64cpu, status %#x\n", status);
3505 return;
3507 if (!NtCreateSection( &section, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
3508 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
3509 NULL, NULL, PAGE_EXECUTE_READ, SEC_COMMIT, file ))
3511 NtMapViewOfSection( section, NtCurrentProcess(), &Wow64Transition, 0,
3512 0, NULL, &size, ViewShare, 0, PAGE_EXECUTE_READ );
3513 NtClose( section );
3515 NtClose( file );
3518 static void init_wow64(void)
3520 PEB *peb = NtCurrentTeb()->Peb;
3521 PEB64 *peb64;
3523 if (!NtCurrentTeb64()) return;
3524 peb64 = UlongToPtr( NtCurrentTeb64()->Peb );
3525 peb64->ImageBaseAddress = PtrToUlong( peb->ImageBaseAddress );
3526 peb64->OSMajorVersion = peb->OSMajorVersion;
3527 peb64->OSMinorVersion = peb->OSMinorVersion;
3528 peb64->OSBuildNumber = peb->OSBuildNumber;
3529 peb64->OSPlatformId = peb->OSPlatformId;
3530 peb64->SessionId = peb->SessionId;
3532 map_wow64cpu();
3534 #endif
3537 /******************************************************************
3538 * LdrInitializeThunk (NTDLL.@)
3540 * Attach to all the loaded dlls.
3541 * If this is the first time, perform the full process initialization.
3543 void WINAPI LdrInitializeThunk( CONTEXT *context, ULONG_PTR unknown2, ULONG_PTR unknown3, ULONG_PTR unknown4 )
3545 static int attach_done;
3546 int i;
3547 NTSTATUS status;
3548 ULONG_PTR cookie;
3549 WINE_MODREF *wm;
3550 void **entry;
3552 #ifdef __i386__
3553 entry = (void **)&context->Eax;
3554 #elif defined(__x86_64__)
3555 entry = (void **)&context->Rcx;
3556 #elif defined(__arm__)
3557 entry = (void **)&context->R0;
3558 #elif defined(__aarch64__)
3559 entry = (void **)&context->u.s.X0;
3560 #endif
3562 if (process_detaching) NtTerminateThread( GetCurrentThread(), 0 );
3564 RtlEnterCriticalSection( &loader_section );
3566 if (!imports_fixup_done)
3568 ANSI_STRING func_name;
3569 WINE_MODREF *kernel32;
3571 #ifndef _WIN64
3572 init_wow64();
3573 #endif
3574 wm = build_main_module();
3575 wm->ldr.LoadCount = -1;
3577 build_ntdll_module();
3579 if ((status = load_dll( NULL, L"kernel32.dll", NULL, 0, &kernel32 )) != STATUS_SUCCESS)
3581 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3582 NtTerminateProcess( GetCurrentProcess(), status );
3584 kernel32_handle = kernel32->ldr.DllBase;
3585 RtlInitAnsiString( &func_name, "BaseThreadInitThunk" );
3586 if ((status = LdrGetProcedureAddress( kernel32_handle, &func_name,
3587 0, (void **)&pBaseThreadInitThunk )) != STATUS_SUCCESS)
3589 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status );
3590 NtTerminateProcess( GetCurrentProcess(), status );
3593 actctx_init();
3594 if (wm->ldr.Flags & LDR_COR_ILONLY)
3595 status = fixup_imports_ilonly( wm, NULL, entry );
3596 else
3597 status = fixup_imports( wm, NULL );
3599 if (status)
3601 ERR( "Importing dlls for %s failed, status %x\n",
3602 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3603 NtTerminateProcess( GetCurrentProcess(), status );
3605 imports_fixup_done = TRUE;
3607 else wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3609 RtlAcquirePebLock();
3610 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3611 RtlReleasePebLock();
3613 NtCurrentTeb()->FlsSlots = fls_alloc_data();
3615 if (!attach_done) /* first time around */
3617 attach_done = 1;
3618 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3620 ERR( "TLS init failed when loading %s, status %x\n",
3621 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3622 NtTerminateProcess( GetCurrentProcess(), status );
3624 wm->ldr.Flags |= LDR_PROCESS_ATTACHED; /* don't try to attach again */
3625 if (wm->ldr.ActivationContext)
3626 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
3628 for (i = 0; i < wm->nDeps; i++)
3630 if (!wm->deps[i]) continue;
3631 if ((status = process_attach( wm->deps[i], context )) != STATUS_SUCCESS)
3633 if (last_failed_modref)
3634 ERR( "%s failed to initialize, aborting\n",
3635 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3636 ERR( "Initializing dlls for %s failed, status %x\n",
3637 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3638 NtTerminateProcess( GetCurrentProcess(), status );
3641 unix_funcs->virtual_release_address_space();
3642 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_PROCESS_ATTACH );
3643 if (wm->ldr.Flags & LDR_WINE_INTERNAL) unix_funcs->init_builtin_dll( wm->ldr.DllBase );
3644 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
3645 process_breakpoint();
3647 else
3649 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3650 NtTerminateThread( GetCurrentThread(), status );
3651 thread_attach();
3652 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_ATTACH );
3655 RtlLeaveCriticalSection( &loader_section );
3656 signal_start_thread( context );
3660 /***********************************************************************
3661 * load_global_options
3663 static void load_global_options(void)
3665 OBJECT_ATTRIBUTES attr;
3666 UNICODE_STRING name_str;
3667 HANDLE hkey;
3668 ULONG value;
3670 attr.Length = sizeof(attr);
3671 attr.RootDirectory = 0;
3672 attr.ObjectName = &name_str;
3673 attr.Attributes = OBJ_CASE_INSENSITIVE;
3674 attr.SecurityDescriptor = NULL;
3675 attr.SecurityQualityOfService = NULL;
3676 RtlInitUnicodeString( &name_str, L"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3678 if (!NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))
3680 query_dword_option( hkey, L"GlobalFlag", &NtCurrentTeb()->Peb->NtGlobalFlag );
3681 query_dword_option( hkey, L"SafeProcessSearchMode", &path_safe_mode );
3682 query_dword_option( hkey, L"SafeDllSearchMode", &dll_safe_mode );
3684 if (!query_dword_option( hkey, L"CriticalSectionTimeout", &value ))
3685 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3687 if (!query_dword_option( hkey, L"HeapSegmentReserve", &value ))
3688 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3690 if (!query_dword_option( hkey, L"HeapSegmentCommit", &value ))
3691 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3693 if (!query_dword_option( hkey, L"HeapDeCommitTotalFreeThreshold", &value ))
3694 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3696 if (!query_dword_option( hkey, L"HeapDeCommitFreeBlockThreshold", &value ))
3697 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3699 NtClose( hkey );
3701 LdrQueryImageFileExecutionOptions( &NtCurrentTeb()->Peb->ProcessParameters->ImagePathName,
3702 L"GlobalFlag", REG_DWORD, &NtCurrentTeb()->Peb->NtGlobalFlag,
3703 sizeof(DWORD), NULL );
3704 heap_set_debug_flags( GetProcessHeap() );
3708 /***********************************************************************
3709 * RtlImageDirectoryEntryToData (NTDLL.@)
3711 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3713 const IMAGE_NT_HEADERS *nt;
3714 DWORD addr;
3716 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
3717 module = (HMODULE)((ULONG_PTR)module & ~3);
3718 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3719 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3721 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3723 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3724 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3725 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3726 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3728 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3730 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3732 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3733 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3734 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3735 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3737 else return NULL;
3739 /* not mapped as image, need to find the section containing the virtual address */
3740 return RtlImageRvaToVa( nt, module, addr, NULL );
3744 /***********************************************************************
3745 * RtlImageRvaToSection (NTDLL.@)
3747 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3748 HMODULE module, DWORD rva )
3750 int i;
3751 const IMAGE_SECTION_HEADER *sec;
3753 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3754 nt->FileHeader.SizeOfOptionalHeader);
3755 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3757 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3758 return (PIMAGE_SECTION_HEADER)sec;
3760 return NULL;
3764 /***********************************************************************
3765 * RtlImageRvaToVa (NTDLL.@)
3767 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3768 DWORD rva, IMAGE_SECTION_HEADER **section )
3770 IMAGE_SECTION_HEADER *sec;
3772 if (section && *section) /* try this section first */
3774 sec = *section;
3775 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3776 goto found;
3778 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3779 found:
3780 if (section) *section = sec;
3781 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3785 /***********************************************************************
3786 * RtlPcToFileHeader (NTDLL.@)
3788 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3790 LDR_DATA_TABLE_ENTRY *module;
3791 PVOID ret = NULL;
3793 RtlEnterCriticalSection( &loader_section );
3794 if (!LdrFindEntryForAddress( pc, &module )) ret = module->DllBase;
3795 RtlLeaveCriticalSection( &loader_section );
3796 *address = ret;
3797 return ret;
3801 /****************************************************************************
3802 * LdrGetDllDirectory (NTDLL.@)
3804 NTSTATUS WINAPI LdrGetDllDirectory( UNICODE_STRING *dir )
3806 NTSTATUS status = STATUS_SUCCESS;
3808 RtlEnterCriticalSection( &dlldir_section );
3809 dir->Length = dll_directory.Length + sizeof(WCHAR);
3810 if (dir->MaximumLength >= dir->Length) RtlCopyUnicodeString( dir, &dll_directory );
3811 else
3813 status = STATUS_BUFFER_TOO_SMALL;
3814 if (dir->MaximumLength) dir->Buffer[0] = 0;
3816 RtlLeaveCriticalSection( &dlldir_section );
3817 return status;
3821 /****************************************************************************
3822 * LdrSetDllDirectory (NTDLL.@)
3824 NTSTATUS WINAPI LdrSetDllDirectory( const UNICODE_STRING *dir )
3826 NTSTATUS status = STATUS_SUCCESS;
3827 UNICODE_STRING new;
3829 if (!dir->Buffer) RtlInitUnicodeString( &new, NULL );
3830 else if ((status = RtlDuplicateUnicodeString( 1, dir, &new ))) return status;
3832 RtlEnterCriticalSection( &dlldir_section );
3833 RtlFreeUnicodeString( &dll_directory );
3834 dll_directory = new;
3835 RtlLeaveCriticalSection( &dlldir_section );
3836 return status;
3840 /****************************************************************************
3841 * LdrAddDllDirectory (NTDLL.@)
3843 NTSTATUS WINAPI LdrAddDllDirectory( const UNICODE_STRING *dir, void **cookie )
3845 FILE_BASIC_INFORMATION info;
3846 UNICODE_STRING nt_name;
3847 NTSTATUS status;
3848 OBJECT_ATTRIBUTES attr;
3849 DWORD len;
3850 struct dll_dir_entry *ptr;
3851 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir->Buffer );
3853 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
3854 return STATUS_INVALID_PARAMETER;
3856 status = RtlDosPathNameToNtPathName_U_WithStatus( dir->Buffer, &nt_name, NULL, NULL );
3857 if (status) return status;
3858 len = nt_name.Length / sizeof(WCHAR);
3859 if (!(ptr = RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] ))))
3860 return STATUS_NO_MEMORY;
3861 memcpy( ptr->dir, nt_name.Buffer, len * sizeof(WCHAR) );
3863 attr.Length = sizeof(attr);
3864 attr.RootDirectory = 0;
3865 attr.Attributes = OBJ_CASE_INSENSITIVE;
3866 attr.ObjectName = &nt_name;
3867 attr.SecurityDescriptor = NULL;
3868 attr.SecurityQualityOfService = NULL;
3869 status = NtQueryAttributesFile( &attr, &info );
3870 RtlFreeUnicodeString( &nt_name );
3872 if (!status)
3874 TRACE( "%s\n", debugstr_w( ptr->dir ));
3875 RtlEnterCriticalSection( &dlldir_section );
3876 list_add_head( &dll_dir_list, &ptr->entry );
3877 RtlLeaveCriticalSection( &dlldir_section );
3878 *cookie = ptr;
3880 else RtlFreeHeap( GetProcessHeap(), 0, ptr );
3881 return status;
3885 /****************************************************************************
3886 * LdrRemoveDllDirectory (NTDLL.@)
3888 NTSTATUS WINAPI LdrRemoveDllDirectory( void *cookie )
3890 struct dll_dir_entry *ptr = cookie;
3892 TRACE( "%s\n", debugstr_w( ptr->dir ));
3894 RtlEnterCriticalSection( &dlldir_section );
3895 list_remove( &ptr->entry );
3896 RtlFreeHeap( GetProcessHeap(), 0, ptr );
3897 RtlLeaveCriticalSection( &dlldir_section );
3898 return STATUS_SUCCESS;
3902 /*************************************************************************
3903 * LdrSetDefaultDllDirectories (NTDLL.@)
3905 NTSTATUS WINAPI LdrSetDefaultDllDirectories( ULONG flags )
3907 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
3908 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
3909 LOAD_LIBRARY_SEARCH_USER_DIRS |
3910 LOAD_LIBRARY_SEARCH_SYSTEM32 |
3911 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
3913 if (!flags || (flags & ~load_library_search_flags)) return STATUS_INVALID_PARAMETER;
3914 default_search_flags = flags;
3915 return STATUS_SUCCESS;
3919 /******************************************************************
3920 * LdrGetDllPath (NTDLL.@)
3922 NTSTATUS WINAPI LdrGetDllPath( PCWSTR module, ULONG flags, PWSTR *path, PWSTR *unknown )
3924 NTSTATUS status;
3925 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
3926 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
3927 LOAD_LIBRARY_SEARCH_USER_DIRS |
3928 LOAD_LIBRARY_SEARCH_SYSTEM32 |
3929 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
3931 if (flags & LOAD_WITH_ALTERED_SEARCH_PATH)
3933 if (flags & load_library_search_flags) return STATUS_INVALID_PARAMETER;
3934 if (default_search_flags) flags |= default_search_flags | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
3936 else if (!(flags & load_library_search_flags)) flags |= default_search_flags;
3938 RtlEnterCriticalSection( &dlldir_section );
3940 if (flags & load_library_search_flags)
3942 status = get_dll_load_path_search_flags( module, flags, path );
3944 else
3946 const WCHAR *dlldir = dll_directory.Length ? dll_directory.Buffer : NULL;
3947 if (!(flags & LOAD_WITH_ALTERED_SEARCH_PATH))
3948 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3949 status = get_dll_load_path( module, dlldir, dll_safe_mode, path );
3952 RtlLeaveCriticalSection( &dlldir_section );
3953 *unknown = NULL;
3954 return status;
3958 /*************************************************************************
3959 * RtlSetSearchPathMode (NTDLL.@)
3961 NTSTATUS WINAPI RtlSetSearchPathMode( ULONG flags )
3963 int val;
3965 switch (flags)
3967 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE:
3968 val = 1;
3969 break;
3970 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE:
3971 val = 0;
3972 break;
3973 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT:
3974 InterlockedExchange( (int *)&path_safe_mode, 2 );
3975 return STATUS_SUCCESS;
3976 default:
3977 return STATUS_INVALID_PARAMETER;
3980 for (;;)
3982 int prev = path_safe_mode;
3983 if (prev == 2) break; /* permanently set */
3984 if (InterlockedCompareExchange( (int *)&path_safe_mode, val, prev ) == prev) return STATUS_SUCCESS;
3986 return STATUS_ACCESS_DENIED;
3990 /******************************************************************
3991 * RtlGetExePath (NTDLL.@)
3993 NTSTATUS WINAPI RtlGetExePath( PCWSTR name, PWSTR *path )
3995 const WCHAR *dlldir = L".";
3996 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3998 /* same check as NeedCurrentDirectoryForExePathW */
3999 if (!wcschr( name, '\\' ))
4001 UNICODE_STRING name, value = { 0 };
4003 RtlInitUnicodeString( &name, L"NoDefaultCurrentDirectoryInExePath" );
4004 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) != STATUS_VARIABLE_NOT_FOUND)
4005 dlldir = L"";
4007 return get_dll_load_path( module, dlldir, FALSE, path );
4011 /******************************************************************
4012 * RtlGetSearchPath (NTDLL.@)
4014 NTSTATUS WINAPI RtlGetSearchPath( PWSTR *path )
4016 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4017 return get_dll_load_path( module, NULL, path_safe_mode, path );
4021 /******************************************************************
4022 * RtlReleasePath (NTDLL.@)
4024 void WINAPI RtlReleasePath( PWSTR path )
4026 RtlFreeHeap( GetProcessHeap(), 0, path );
4030 /******************************************************************
4031 * DllMain (NTDLL.@)
4033 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
4035 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
4036 return TRUE;
4040 /***********************************************************************
4041 * process_init
4043 static NTSTATUS process_init(void)
4045 TEB *teb = NtCurrentTeb();
4046 PEB *peb = teb->Peb;
4048 peb->LdrData = &ldr;
4049 peb->FastPebLock = &peb_lock;
4050 peb->TlsBitmap = &tls_bitmap;
4051 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
4052 peb->LoaderLock = &loader_section;
4053 peb->OSMajorVersion = 5;
4054 peb->OSMinorVersion = 1;
4055 peb->OSBuildNumber = 0xA28;
4056 peb->OSPlatformId = VER_PLATFORM_WIN32_NT;
4057 peb->SessionId = 1;
4058 peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
4060 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
4061 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
4062 sizeof(peb->TlsExpansionBitmapBits) * 8 );
4063 RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
4064 init_global_fls_data();
4066 InitializeListHead( &ldr.InLoadOrderModuleList );
4067 InitializeListHead( &ldr.InMemoryOrderModuleList );
4068 InitializeListHead( &ldr.InInitializationOrderModuleList );
4070 init_user_process_params();
4071 load_global_options();
4072 version_init();
4073 return STATUS_SUCCESS;
4076 /***********************************************************************
4077 * __wine_set_unix_funcs
4079 NTSTATUS CDECL __wine_set_unix_funcs( int version, const struct unix_funcs *funcs )
4081 if (version != NTDLL_UNIXLIB_VERSION) return STATUS_REVISION_MISMATCH;
4082 unix_funcs = funcs;
4083 return process_init();