ws2_32/tests: Add some tests for opening the Afd device.
[wine.git] / dlls / ntdll / loader.c
blob02220d7808b7d0f9f8349c650f3668aa47bdde3d
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 #ifdef __i386__
55 static const WCHAR pe_dir[] = L"\\i386-windows";
56 #elif defined __x86_64__
57 static const WCHAR pe_dir[] = L"\\x86_64-windows";
58 #elif defined __arm__
59 static const WCHAR pe_dir[] = L"\\arm-windows";
60 #elif defined __aarch64__
61 static const WCHAR pe_dir[] = L"\\aarch64-windows";
62 #else
63 static const WCHAR pe_dir[] = L"";
64 #endif
66 /* we don't want to include winuser.h */
67 #define RT_MANIFEST ((ULONG_PTR)24)
68 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
70 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
71 typedef void (CALLBACK *LDRENUMPROC)(LDR_DATA_TABLE_ENTRY *, void *, BOOLEAN *);
73 void (FASTCALL *pBaseThreadInitThunk)(DWORD,LPTHREAD_START_ROUTINE,void *) = NULL;
75 const struct unix_funcs *unix_funcs = NULL;
77 /* windows directory */
78 const WCHAR windows_dir[] = L"C:\\windows";
79 /* system directory with trailing backslash */
80 const WCHAR system_dir[] = L"C:\\windows\\system32\\";
81 const WCHAR syswow64_dir[] = L"C:\\windows\\syswow64\\";
83 HMODULE kernel32_handle = 0;
85 /* system search path */
86 static const WCHAR system_path[] = L"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
88 static BOOL is_prefix_bootstrap; /* are we bootstrapping the prefix? */
89 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
90 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
91 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
92 static ULONG path_safe_mode; /* path mode set by RtlSetSearchPathMode */
93 static ULONG dll_safe_mode = 1; /* dll search mode */
94 static UNICODE_STRING dll_directory; /* extra path for LdrSetDllDirectory */
95 static DWORD default_search_flags; /* default flags set by LdrSetDefaultDllDirectories */
96 static WCHAR *default_load_path; /* default dll search path */
98 struct dll_dir_entry
100 struct list entry;
101 WCHAR dir[1];
104 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from LdrAddDllDirectory */
106 struct ldr_notification
108 struct list entry;
109 PLDR_DLL_NOTIFICATION_FUNCTION callback;
110 void *context;
113 static struct list ldr_notifications = LIST_INIT( ldr_notifications );
115 static const char * const reason_names[] =
117 "PROCESS_DETACH",
118 "PROCESS_ATTACH",
119 "THREAD_ATTACH",
120 "THREAD_DETACH",
123 struct file_id
125 BYTE ObjectId[16];
128 /* internal representation of loaded modules */
129 typedef struct _wine_modref
131 LDR_DATA_TABLE_ENTRY ldr;
132 struct file_id id;
133 int alloc_deps;
134 int nDeps;
135 struct _wine_modref **deps;
136 } WINE_MODREF;
138 static UINT tls_module_count; /* number of modules with TLS directory */
139 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
140 LIST_ENTRY tls_links = { &tls_links, &tls_links };
142 static RTL_CRITICAL_SECTION loader_section;
143 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
145 0, 0, &loader_section,
146 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
147 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
149 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
151 static CRITICAL_SECTION dlldir_section;
152 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug =
154 0, 0, &dlldir_section,
155 { &dlldir_critsect_debug.ProcessLocksList, &dlldir_critsect_debug.ProcessLocksList },
156 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
158 static CRITICAL_SECTION dlldir_section = { &dlldir_critsect_debug, -1, 0, 0, 0, 0 };
160 static RTL_CRITICAL_SECTION peb_lock;
161 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug =
163 0, 0, &peb_lock,
164 { &peb_critsect_debug.ProcessLocksList, &peb_critsect_debug.ProcessLocksList },
165 0, 0, { (DWORD_PTR)(__FILE__ ": peb_lock") }
167 static RTL_CRITICAL_SECTION peb_lock = { &peb_critsect_debug, -1, 0, 0, 0, 0 };
169 static PEB_LDR_DATA ldr =
171 sizeof(ldr), TRUE, NULL,
172 { &ldr.InLoadOrderModuleList, &ldr.InLoadOrderModuleList },
173 { &ldr.InMemoryOrderModuleList, &ldr.InMemoryOrderModuleList },
174 { &ldr.InInitializationOrderModuleList, &ldr.InInitializationOrderModuleList }
177 static RTL_BITMAP tls_bitmap;
178 static RTL_BITMAP tls_expansion_bitmap;
180 static WINE_MODREF *cached_modref;
181 static WINE_MODREF *current_modref;
182 static WINE_MODREF *last_failed_modref;
184 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
185 DWORD flags, WINE_MODREF** pwm );
186 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
187 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
188 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
189 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
190 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
192 /* convert PE image VirtualAddress to Real Address */
193 static inline void *get_rva( HMODULE module, DWORD va )
195 return (void *)((char *)module + va);
198 /* check whether the file name contains a path */
199 static inline BOOL contains_path( LPCWSTR name )
201 return ((*name && (name[1] == ':')) || wcschr(name, '/') || wcschr(name, '\\'));
204 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
206 typedef struct _RTL_UNLOAD_EVENT_TRACE
208 void *BaseAddress;
209 SIZE_T SizeOfImage;
210 ULONG Sequence;
211 ULONG TimeDateStamp;
212 ULONG CheckSum;
213 WCHAR ImageName[32];
214 } RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
216 static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
217 static RTL_UNLOAD_EVENT_TRACE *unload_trace_ptr;
218 static unsigned int unload_trace_seq;
220 static void module_push_unload_trace( const LDR_DATA_TABLE_ENTRY *ldr )
222 RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
223 unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
225 ptr->BaseAddress = ldr->DllBase;
226 ptr->SizeOfImage = ldr->SizeOfImage;
227 ptr->Sequence = unload_trace_seq;
228 ptr->TimeDateStamp = ldr->TimeDateStamp;
229 ptr->CheckSum = ldr->CheckSum;
230 memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
231 ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
233 unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
234 unload_trace_ptr = unload_traces;
237 /*********************************************************************
238 * RtlGetUnloadEventTrace [NTDLL.@]
240 RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
242 return unload_traces;
245 /*********************************************************************
246 * RtlGetUnloadEventTraceEx [NTDLL.@]
248 void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
250 static unsigned int element_size = sizeof(*unload_traces);
251 static unsigned int element_count = ARRAY_SIZE(unload_traces);
253 *size = &element_size;
254 *count = &element_count;
255 *trace = &unload_trace_ptr;
258 /*************************************************************************
259 * call_dll_entry_point
261 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
262 * their entry point, so we need a small asm wrapper. Testing indicates
263 * that only modifying esi leads to a crash, so use this one to backup
264 * ebp while running the dll entry proc.
266 #ifdef __i386__
267 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
268 __ASM_GLOBAL_FUNC(call_dll_entry_point,
269 "pushl %ebp\n\t"
270 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
271 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
272 "movl %esp,%ebp\n\t"
273 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
274 "pushl %ebx\n\t"
275 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
276 "pushl %esi\n\t"
277 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
278 "pushl %edi\n\t"
279 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
280 "movl %ebp,%esi\n\t"
281 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
282 "pushl 20(%ebp)\n\t"
283 "pushl 16(%ebp)\n\t"
284 "pushl 12(%ebp)\n\t"
285 "movl 8(%ebp),%eax\n\t"
286 "call *%eax\n\t"
287 "movl %esi,%ebp\n\t"
288 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
289 "leal -12(%ebp),%esp\n\t"
290 "popl %edi\n\t"
291 __ASM_CFI(".cfi_same_value %edi\n\t")
292 "popl %esi\n\t"
293 __ASM_CFI(".cfi_same_value %esi\n\t")
294 "popl %ebx\n\t"
295 __ASM_CFI(".cfi_same_value %ebx\n\t")
296 "popl %ebp\n\t"
297 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
298 __ASM_CFI(".cfi_same_value %ebp\n\t")
299 "ret" )
300 #else /* __i386__ */
301 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
302 UINT reason, void *reserved )
304 return proc( module, reason, reserved );
306 #endif /* __i386__ */
309 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
310 /*************************************************************************
311 * stub_entry_point
313 * Entry point for stub functions.
315 static void WINAPI stub_entry_point( const char *dll, const char *name, void *ret_addr )
317 EXCEPTION_RECORD rec;
319 rec.ExceptionCode = EXCEPTION_WINE_STUB;
320 rec.ExceptionFlags = EH_NONCONTINUABLE;
321 rec.ExceptionRecord = NULL;
322 rec.ExceptionAddress = ret_addr;
323 rec.NumberParameters = 2;
324 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
325 rec.ExceptionInformation[1] = (ULONG_PTR)name;
326 for (;;) RtlRaiseException( &rec );
330 #include "pshpack1.h"
331 #ifdef __i386__
332 struct stub
334 BYTE pushl1; /* pushl $name */
335 const char *name;
336 BYTE pushl2; /* pushl $dll */
337 const char *dll;
338 BYTE call; /* call stub_entry_point */
339 DWORD entry;
341 #elif defined(__arm__)
342 struct stub
344 DWORD ldr_r0; /* ldr r0, $dll */
345 DWORD ldr_r1; /* ldr r1, $name */
346 DWORD mov_r2_lr; /* mov r2, lr */
347 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
348 const char *dll;
349 const char *name;
350 const void* entry;
352 #elif defined(__aarch64__)
353 struct stub
355 DWORD ldr_x0; /* ldr x0, $dll */
356 DWORD ldr_x1; /* ldr x1, $name */
357 DWORD mov_x2_lr; /* mov x2, lr */
358 DWORD ldr_x16; /* ldr x16, $entry */
359 DWORD br_x16; /* br x16 */
360 const char *dll;
361 const char *name;
362 const void *entry;
364 #else
365 struct stub
367 BYTE movq_rdi[2]; /* movq $dll,%rdi */
368 const char *dll;
369 BYTE movq_rsi[2]; /* movq $name,%rsi */
370 const char *name;
371 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
372 BYTE movq_rax[2]; /* movq $entry, %rax */
373 const void* entry;
374 BYTE jmpq_rax[2]; /* jmp %rax */
376 #endif
377 #include "poppack.h"
379 /*************************************************************************
380 * allocate_stub
382 * Allocate a stub entry point.
384 static ULONG_PTR allocate_stub( const char *dll, const char *name )
386 #define MAX_SIZE 65536
387 static struct stub *stubs;
388 static unsigned int nb_stubs;
389 struct stub *stub;
391 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
393 if (!stubs)
395 SIZE_T size = MAX_SIZE;
396 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
397 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
398 return 0xdeadbeef;
400 stub = &stubs[nb_stubs++];
401 #ifdef __i386__
402 stub->pushl1 = 0x68; /* pushl $name */
403 stub->name = name;
404 stub->pushl2 = 0x68; /* pushl $dll */
405 stub->dll = dll;
406 stub->call = 0xe8; /* call stub_entry_point */
407 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
408 #elif defined(__arm__)
409 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
410 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
411 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
412 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
413 stub->dll = dll;
414 stub->name = name;
415 stub->entry = stub_entry_point;
416 #elif defined(__aarch64__)
417 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
418 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
419 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
420 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
421 stub->br_x16 = 0xd61f0200; /* br x16 */
422 stub->dll = dll;
423 stub->name = name;
424 stub->entry = stub_entry_point;
425 #else
426 stub->movq_rdi[0] = 0x48; /* movq $dll,%rcx */
427 stub->movq_rdi[1] = 0xb9;
428 stub->dll = dll;
429 stub->movq_rsi[0] = 0x48; /* movq $name,%rdx */
430 stub->movq_rsi[1] = 0xba;
431 stub->name = name;
432 stub->movq_rsp_rdx[0] = 0x4c; /* movq (%rsp),%r8 */
433 stub->movq_rsp_rdx[1] = 0x8b;
434 stub->movq_rsp_rdx[2] = 0x04;
435 stub->movq_rsp_rdx[3] = 0x24;
436 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
437 stub->movq_rax[1] = 0xb8;
438 stub->entry = stub_entry_point;
439 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
440 stub->jmpq_rax[1] = 0xe0;
441 #endif
442 return (ULONG_PTR)stub;
445 #else /* __i386__ */
446 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
447 #endif /* __i386__ */
449 /* call ldr notifications */
450 static void call_ldr_notifications( ULONG reason, LDR_DATA_TABLE_ENTRY *module )
452 struct ldr_notification *notify, *notify_next;
453 LDR_DLL_NOTIFICATION_DATA data;
455 data.Loaded.Flags = 0;
456 data.Loaded.FullDllName = &module->FullDllName;
457 data.Loaded.BaseDllName = &module->BaseDllName;
458 data.Loaded.DllBase = module->DllBase;
459 data.Loaded.SizeOfImage = module->SizeOfImage;
461 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
463 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
464 notify->callback, reason, &data, notify->context );
466 notify->callback(reason, &data, notify->context);
468 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
469 notify->callback, reason, &data, notify->context );
473 /*************************************************************************
474 * get_modref
476 * Looks for the referenced HMODULE in the current process
477 * The loader_section must be locked while calling this function.
479 static WINE_MODREF *get_modref( HMODULE hmod )
481 PLIST_ENTRY mark, entry;
482 PLDR_DATA_TABLE_ENTRY mod;
484 if (cached_modref && cached_modref->ldr.DllBase == hmod) return cached_modref;
486 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
487 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
489 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
490 if (mod->DllBase == hmod)
491 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
493 return NULL;
497 /**********************************************************************
498 * find_basename_module
500 * Find a module from its base name.
501 * The loader_section must be locked while calling this function
503 static WINE_MODREF *find_basename_module( LPCWSTR name )
505 PLIST_ENTRY mark, entry;
506 UNICODE_STRING name_str;
508 RtlInitUnicodeString( &name_str, name );
510 if (cached_modref && RtlEqualUnicodeString( &name_str, &cached_modref->ldr.BaseDllName, TRUE ))
511 return cached_modref;
513 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
514 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
516 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
517 if (RtlEqualUnicodeString( &name_str, &mod->BaseDllName, TRUE ))
519 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
520 return cached_modref;
523 return NULL;
527 /**********************************************************************
528 * find_fullname_module
530 * Find a module from its full path name.
531 * The loader_section must be locked while calling this function
533 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
535 PLIST_ENTRY mark, entry;
536 UNICODE_STRING name = *nt_name;
538 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
539 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
540 name.Buffer += 4;
542 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
543 return cached_modref;
545 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
546 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
548 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
549 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
551 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
552 return cached_modref;
555 return NULL;
559 /**********************************************************************
560 * find_fileid_module
562 * Find a module from its file id.
563 * The loader_section must be locked while calling this function
565 static WINE_MODREF *find_fileid_module( const struct file_id *id )
567 LIST_ENTRY *mark, *entry;
569 if (cached_modref && !memcmp( &cached_modref->id, id, sizeof(*id) )) return cached_modref;
571 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
572 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
574 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
575 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
577 if (!memcmp( &wm->id, id, sizeof(*id) ))
579 cached_modref = wm;
580 return wm;
583 return NULL;
587 /*************************************************************************
588 * grow_module_deps
590 static WINE_MODREF **grow_module_deps( WINE_MODREF *wm, int count )
592 WINE_MODREF **deps;
594 if (wm->alloc_deps)
595 deps = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, wm->deps,
596 (wm->alloc_deps + count) * sizeof(*deps) );
597 else
598 deps = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, count * sizeof(*deps) );
600 if (deps)
602 wm->deps = deps;
603 wm->alloc_deps += count;
605 return deps;
608 /*************************************************************************
609 * find_forwarded_export
611 * Find the final function pointer for a forwarded function.
612 * The loader_section must be locked while calling this function.
614 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
616 const IMAGE_EXPORT_DIRECTORY *exports;
617 DWORD exp_size;
618 WINE_MODREF *wm;
619 WCHAR buffer[32], *mod_name = buffer;
620 const char *end = strrchr(forward, '.');
621 FARPROC proc = NULL;
623 if (!end) return NULL;
624 if ((end - forward) * sizeof(WCHAR) > sizeof(buffer) - sizeof(L".dll"))
626 if (!(mod_name = RtlAllocateHeap( GetProcessHeap(), 0,
627 (end - forward + sizeof(L".dll")) * sizeof(WCHAR) )))
628 return NULL;
630 ascii_to_unicode( mod_name, forward, end - forward );
631 mod_name[end - forward] = 0;
632 if (!wcschr( mod_name, '.' ))
633 memcpy( mod_name + (end - forward), L".dll", sizeof(L".dll") );
635 if (!(wm = find_basename_module( mod_name )))
637 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
638 if (load_dll( load_path, mod_name, L".dll", 0, &wm ) == STATUS_SUCCESS &&
639 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
641 if (!imports_fixup_done && current_modref)
643 WINE_MODREF **deps = grow_module_deps( current_modref, 1 );
644 if (deps) deps[current_modref->nDeps++] = wm;
646 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
648 LdrUnloadDll( wm->ldr.DllBase );
649 wm = NULL;
653 if (!wm)
655 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
656 ERR( "module not found for forward '%s' used by %s\n",
657 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
658 return NULL;
661 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
662 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
664 const char *name = end + 1;
666 if (*name == '#') { /* ordinal */
667 proc = find_ordinal_export( wm->ldr.DllBase, exports, exp_size,
668 atoi(name+1) - exports->Base, load_path );
669 } else
670 proc = find_named_export( wm->ldr.DllBase, exports, exp_size, name, -1, load_path );
673 if (!proc)
675 ERR("function not found for forward '%s' used by %s."
676 " If you are using builtin %s, try using the native one instead.\n",
677 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
678 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
680 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
681 return proc;
685 /*************************************************************************
686 * find_ordinal_export
688 * Find an exported function by ordinal.
689 * The exports base must have been subtracted from the ordinal already.
690 * The loader_section must be locked while calling this function.
692 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
693 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
695 FARPROC proc;
696 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
698 if (ordinal >= exports->NumberOfFunctions)
700 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
701 return NULL;
703 if (!functions[ordinal]) return NULL;
705 proc = get_rva( module, functions[ordinal] );
707 /* if the address falls into the export dir, it's a forward */
708 if (((const char *)proc >= (const char *)exports) &&
709 ((const char *)proc < (const char *)exports + exp_size))
710 return find_forwarded_export( module, (const char *)proc, load_path );
712 if (TRACE_ON(snoop))
714 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
715 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
717 if (TRACE_ON(relay))
719 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
720 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
722 return proc;
726 /*************************************************************************
727 * find_name_in_exports
729 * Helper for find_named_export.
731 static int find_name_in_exports( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports, const char *name )
733 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
734 const DWORD *names = get_rva( module, exports->AddressOfNames );
735 int min = 0, max = exports->NumberOfNames - 1;
737 while (min <= max)
739 int res, pos = (min + max) / 2;
740 char *ename = get_rva( module, names[pos] );
741 if (!(res = strcmp( ename, name ))) return ordinals[pos];
742 if (res > 0) max = pos - 1;
743 else min = pos + 1;
745 return -1;
749 /*************************************************************************
750 * find_named_export
752 * Find an exported function by name.
753 * The loader_section must be locked while calling this function.
755 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
756 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
758 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
759 const DWORD *names = get_rva( module, exports->AddressOfNames );
760 int ordinal;
762 /* first check the hint */
763 if (hint >= 0 && hint < exports->NumberOfNames)
765 char *ename = get_rva( module, names[hint] );
766 if (!strcmp( ename, name ))
767 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
770 /* then do a binary search */
771 if ((ordinal = find_name_in_exports( module, exports, name )) == -1) return NULL;
772 return find_ordinal_export( module, exports, exp_size, ordinal, load_path );
777 /*************************************************************************
778 * RtlFindExportedRoutineByName
780 void * WINAPI RtlFindExportedRoutineByName( HMODULE module, const char *name )
782 const IMAGE_EXPORT_DIRECTORY *exports;
783 const DWORD *functions;
784 DWORD exp_size;
785 int ordinal;
787 exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
788 if (!exports || exp_size < sizeof(*exports)) return NULL;
790 if ((ordinal = find_name_in_exports( module, exports, name )) == -1) return NULL;
791 if (ordinal >= exports->NumberOfFunctions) return NULL;
792 functions = get_rva( module, exports->AddressOfFunctions );
793 if (!functions[ordinal]) return NULL;
794 return get_rva( module, functions[ordinal] );
798 /*************************************************************************
799 * import_dll
801 * Import the dll specified by the given import descriptor.
802 * The loader_section must be locked while calling this function.
804 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
806 NTSTATUS status;
807 WINE_MODREF *wmImp;
808 HMODULE imp_mod;
809 const IMAGE_EXPORT_DIRECTORY *exports;
810 DWORD exp_size;
811 const IMAGE_THUNK_DATA *import_list;
812 IMAGE_THUNK_DATA *thunk_list;
813 WCHAR buffer[32];
814 const char *name = get_rva( module, descr->Name );
815 DWORD len = strlen(name);
816 PVOID protect_base;
817 SIZE_T protect_size = 0;
818 DWORD protect_old;
820 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
821 if (descr->u.OriginalFirstThunk)
822 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
823 else
824 import_list = thunk_list;
826 if (!import_list->u1.Ordinal)
828 WARN( "Skipping unused import %s\n", name );
829 *pwm = NULL;
830 return TRUE;
833 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
835 if (len * sizeof(WCHAR) < sizeof(buffer))
837 ascii_to_unicode( buffer, name, len );
838 buffer[len] = 0;
839 status = load_dll( load_path, buffer, L".dll", 0, &wmImp );
841 else /* need to allocate a larger buffer */
843 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
844 if (!ptr) return FALSE;
845 ascii_to_unicode( ptr, name, len );
846 ptr[len] = 0;
847 status = load_dll( load_path, ptr, L".dll", 0, &wmImp );
848 RtlFreeHeap( GetProcessHeap(), 0, ptr );
851 if (status)
853 if (status == STATUS_DLL_NOT_FOUND)
854 ERR("Library %s (which is needed by %s) not found\n",
855 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
856 else
857 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
858 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
859 return FALSE;
862 /* unprotect the import address table since it can be located in
863 * readonly section */
864 while (import_list[protect_size].u1.Ordinal) protect_size++;
865 protect_base = thunk_list;
866 protect_size *= sizeof(*thunk_list);
867 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
868 &protect_size, PAGE_READWRITE, &protect_old );
870 imp_mod = wmImp->ldr.DllBase;
871 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
873 if (!exports)
875 /* set all imported function to deadbeef */
876 while (import_list->u1.Ordinal)
878 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
880 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
881 WARN("No implementation for %s.%d", name, ordinal );
882 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
884 else
886 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
887 WARN("No implementation for %s.%s", name, pe_name->Name );
888 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
890 WARN(" imported from %s, allocating stub %p\n",
891 debugstr_w(current_modref->ldr.FullDllName.Buffer),
892 (void *)thunk_list->u1.Function );
893 import_list++;
894 thunk_list++;
896 goto done;
899 while (import_list->u1.Ordinal)
901 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
903 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
905 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
906 ordinal - exports->Base, load_path );
907 if (!thunk_list->u1.Function)
909 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
910 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
911 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
912 (void *)thunk_list->u1.Function );
914 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
916 else /* import by name */
918 IMAGE_IMPORT_BY_NAME *pe_name;
919 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
920 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
921 (const char*)pe_name->Name,
922 pe_name->Hint, load_path );
923 if (!thunk_list->u1.Function)
925 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
926 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
927 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
928 (void *)thunk_list->u1.Function );
930 TRACE_(imports)("--- %s %s.%d = %p\n",
931 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
933 import_list++;
934 thunk_list++;
937 done:
938 /* restore old protection of the import address table */
939 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
940 *pwm = wmImp;
941 return TRUE;
945 /***********************************************************************
946 * create_module_activation_context
948 static NTSTATUS create_module_activation_context( LDR_DATA_TABLE_ENTRY *module )
950 NTSTATUS status;
951 LDR_RESOURCE_INFO info;
952 const IMAGE_RESOURCE_DATA_ENTRY *entry;
954 info.Type = RT_MANIFEST;
955 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
956 info.Language = 0;
957 if (!(status = LdrFindResource_U( module->DllBase, &info, 3, &entry )))
959 ACTCTXW ctx;
960 ctx.cbSize = sizeof(ctx);
961 ctx.lpSource = NULL;
962 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
963 ctx.hModule = module->DllBase;
964 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
965 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
967 return status;
971 /*************************************************************************
972 * is_dll_native_subsystem
974 * Check if dll is a proper native driver.
975 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
976 * while being perfectly normal DLLs. This heuristic should catch such breakages.
978 static BOOL is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
980 const IMAGE_IMPORT_DESCRIPTOR *imports;
981 DWORD i, size;
982 WCHAR buffer[16];
984 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
985 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
986 if (mod->Flags & LDR_WINE_INTERNAL) return TRUE;
988 if ((imports = RtlImageDirectoryEntryToData( mod->DllBase, TRUE,
989 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
991 for (i = 0; imports[i].Name; i++)
993 const char *name = get_rva( mod->DllBase, imports[i].Name );
994 DWORD len = strlen(name);
995 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
996 ascii_to_unicode( buffer, name, len + 1 );
997 if (!wcsicmp( buffer, L"ntdll.dll" ) || !wcsicmp( buffer, L"kernel32.dll" ))
999 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
1000 return FALSE;
1004 return TRUE;
1007 /*************************************************************************
1008 * alloc_tls_slot
1010 * Allocate a TLS slot for a newly-loaded module.
1011 * The loader_section must be locked while calling this function.
1013 static SHORT alloc_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1015 const IMAGE_TLS_DIRECTORY *dir;
1016 ULONG i, size;
1017 void *new_ptr;
1018 LIST_ENTRY *entry;
1020 if (!(dir = RtlImageDirectoryEntryToData( mod->DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
1021 return -1;
1023 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1024 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
1026 for (i = 0; i < tls_module_count; i++)
1028 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
1029 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
1030 break;
1033 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->DllBase,
1034 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
1035 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
1037 if (i == tls_module_count)
1039 UINT new_count = max( 32, tls_module_count * 2 );
1041 if (!tls_dirs)
1042 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
1043 else
1044 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
1045 new_count * sizeof(*tls_dirs) );
1046 if (!new_ptr) return -1;
1048 /* resize the pointer block in all running threads */
1049 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1051 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1052 void **old = teb->ThreadLocalStoragePointer;
1053 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
1055 if (!new) return -1;
1056 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
1057 teb->ThreadLocalStoragePointer = new;
1058 #ifdef __x86_64__ /* macOS-specific hack */
1059 if (teb->Reserved5[0]) ((TEB *)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
1060 #endif
1061 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
1062 /* FIXME: can't free old block here, should be freed at thread exit */
1065 tls_dirs = new_ptr;
1066 tls_module_count = new_count;
1069 /* allocate the data block in all running threads */
1070 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1072 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1074 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
1075 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
1076 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
1078 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1079 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
1081 RtlFreeHeap( GetProcessHeap(), 0,
1082 InterlockedExchangePointer( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
1085 *(DWORD *)dir->AddressOfIndex = i;
1086 tls_dirs[i] = *dir;
1087 return i;
1091 /*************************************************************************
1092 * free_tls_slot
1094 * Free the module TLS slot on unload.
1095 * The loader_section must be locked while calling this function.
1097 static void free_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1099 ULONG i = (USHORT)mod->TlsIndex;
1101 if (mod->TlsIndex == -1) return;
1102 assert( i < tls_module_count );
1103 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
1107 /****************************************************************
1108 * fixup_imports_ilonly
1110 * Fixup imports for an IL-only module. All we do is import mscoree.
1111 * The loader_section must be locked while calling this function.
1113 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
1115 NTSTATUS status;
1116 void *proc;
1117 const char *name;
1118 WINE_MODREF *prev, *imp;
1120 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1121 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1123 if (!grow_module_deps( wm, 1 )) return STATUS_NO_MEMORY;
1124 wm->nDeps = 1;
1126 prev = current_modref;
1127 current_modref = wm;
1128 if (!(status = load_dll( load_path, L"mscoree.dll", NULL, 0, &imp ))) wm->deps[0] = imp;
1129 current_modref = prev;
1130 if (status)
1132 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1133 debugstr_w(wm->ldr.BaseDllName.Buffer) );
1134 return status;
1137 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1139 name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
1140 if (!(proc = RtlFindExportedRoutineByName( imp->ldr.DllBase, name ))) return STATUS_PROCEDURE_NOT_FOUND;
1141 *entry = proc;
1142 return STATUS_SUCCESS;
1146 /****************************************************************
1147 * fixup_imports
1149 * Fixup all imports of a given module.
1150 * The loader_section must be locked while calling this function.
1152 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1154 int i, dep, nb_imports;
1155 const IMAGE_IMPORT_DESCRIPTOR *imports;
1156 WINE_MODREF *prev, *imp;
1157 DWORD size;
1158 NTSTATUS status;
1159 ULONG_PTR cookie;
1161 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1162 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1164 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
1166 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
1167 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1168 return STATUS_SUCCESS;
1170 nb_imports = 0;
1171 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1173 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1174 if (!grow_module_deps( wm, nb_imports )) return STATUS_NO_MEMORY;
1176 if (!create_module_activation_context( &wm->ldr ))
1177 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1179 /* load the imported modules. They are automatically
1180 * added to the modref list of the process.
1182 prev = current_modref;
1183 current_modref = wm;
1184 status = STATUS_SUCCESS;
1185 for (i = 0; i < nb_imports; i++)
1187 dep = wm->nDeps++;
1189 if (!import_dll( wm->ldr.DllBase, &imports[i], load_path, &imp ))
1191 imp = NULL;
1192 status = STATUS_DLL_NOT_FOUND;
1194 wm->deps[dep] = imp;
1196 current_modref = prev;
1197 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1198 return status;
1202 /*************************************************************************
1203 * alloc_module
1205 * Allocate a WINE_MODREF structure and add it to the process list
1206 * The loader_section must be locked while calling this function.
1208 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name, BOOL builtin )
1210 WCHAR *buffer;
1211 WINE_MODREF *wm;
1212 const WCHAR *p;
1213 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1215 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1217 wm->ldr.DllBase = hModule;
1218 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1219 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS | (builtin ? LDR_WINE_INTERNAL : 0);
1220 wm->ldr.TlsIndex = -1;
1221 wm->ldr.LoadCount = 1;
1222 wm->ldr.CheckSum = nt->OptionalHeader.CheckSum;
1223 wm->ldr.TimeDateStamp = nt->FileHeader.TimeDateStamp;
1225 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, nt_name->Length - 3 * sizeof(WCHAR) )))
1227 RtlFreeHeap( GetProcessHeap(), 0, wm );
1228 return NULL;
1230 memcpy( buffer, nt_name->Buffer + 4 /* \??\ prefix */, nt_name->Length - 4 * sizeof(WCHAR) );
1231 buffer[nt_name->Length/sizeof(WCHAR) - 4] = 0;
1232 if ((p = wcsrchr( buffer, '\\' ))) p++;
1233 else p = buffer;
1234 RtlInitUnicodeString( &wm->ldr.FullDllName, buffer );
1235 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1237 if (!is_dll_native_subsystem( &wm->ldr, nt, p ))
1239 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1240 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1241 if (nt->OptionalHeader.AddressOfEntryPoint)
1242 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1245 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1246 &wm->ldr.InLoadOrderLinks);
1247 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1248 &wm->ldr.InMemoryOrderLinks);
1249 /* wait until init is called for inserting into InInitializationOrderModuleList */
1251 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1253 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1254 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1255 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1257 return wm;
1261 /*************************************************************************
1262 * alloc_thread_tls
1264 * Allocate the per-thread structure for module TLS storage.
1266 static NTSTATUS alloc_thread_tls(void)
1268 void **pointers;
1269 UINT i, size;
1271 if (!tls_module_count) return STATUS_SUCCESS;
1273 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1274 tls_module_count * sizeof(*pointers) )))
1275 return STATUS_NO_MEMORY;
1277 for (i = 0; i < tls_module_count; i++)
1279 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1281 if (!dir) continue;
1282 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1283 if (!size && !dir->SizeOfZeroFill) continue;
1285 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1287 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1288 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1289 return STATUS_NO_MEMORY;
1291 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1292 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1294 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1295 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1297 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1298 #ifdef __x86_64__ /* macOS-specific hack */
1299 if (NtCurrentTeb()->Reserved5[0])
1300 ((TEB *)NtCurrentTeb()->Reserved5[0])->ThreadLocalStoragePointer = pointers;
1301 #endif
1302 return STATUS_SUCCESS;
1306 /*************************************************************************
1307 * call_tls_callbacks
1309 static void call_tls_callbacks( HMODULE module, UINT reason )
1311 const IMAGE_TLS_DIRECTORY *dir;
1312 const PIMAGE_TLS_CALLBACK *callback;
1313 ULONG dirsize;
1315 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1316 if (!dir || !dir->AddressOfCallBacks) return;
1318 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1320 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1321 *callback, module, reason_names[reason] );
1322 __TRY
1324 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1326 __EXCEPT_ALL
1328 TRACE_(relay)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1329 GetExceptionCode(), callback, module, reason_names[reason] );
1330 return;
1332 __ENDTRY
1333 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1334 *callback, module, reason_names[reason] );
1338 /*************************************************************************
1339 * MODULE_InitDLL
1341 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1343 WCHAR mod_name[32];
1344 NTSTATUS status = STATUS_SUCCESS;
1345 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1346 void *module = wm->ldr.DllBase;
1347 BOOL retv = FALSE;
1349 /* Skip calls for modules loaded with special load flags */
1351 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1352 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, reason );
1353 if (wm->ldr.Flags & LDR_WINE_INTERNAL && reason == DLL_PROCESS_ATTACH)
1354 unix_funcs->init_builtin_dll( wm->ldr.DllBase );
1355 if (!entry) return STATUS_SUCCESS;
1357 if (TRACE_ON(relay))
1359 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1360 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1361 mod_name[len / sizeof(WCHAR)] = 0;
1362 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1363 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1365 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1366 reason_names[reason], lpReserved );
1368 __TRY
1370 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1371 if (!retv)
1372 status = STATUS_DLL_INIT_FAILED;
1374 __EXCEPT_ALL
1376 status = GetExceptionCode();
1377 TRACE_(relay)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1378 status, entry, module, reason_names[reason], lpReserved );
1380 __ENDTRY
1382 /* The state of the module list may have changed due to the call
1383 to the dll. We cannot assume that this module has not been
1384 deleted. */
1385 if (TRACE_ON(relay))
1386 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1387 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1388 else
1389 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1391 return status;
1395 /*************************************************************************
1396 * process_attach
1398 * Send the process attach notification to all DLLs the given module
1399 * depends on (recursively). This is somewhat complicated due to the fact that
1401 * - we have to respect the module dependencies, i.e. modules implicitly
1402 * referenced by another module have to be initialized before the module
1403 * itself can be initialized
1405 * - the initialization routine of a DLL can itself call LoadLibrary,
1406 * thereby introducing a whole new set of dependencies (even involving
1407 * the 'old' modules) at any time during the whole process
1409 * (Note that this routine can be recursively entered not only directly
1410 * from itself, but also via LoadLibrary from one of the called initialization
1411 * routines.)
1413 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1414 * the process *detach* notifications to be sent in the correct order.
1415 * This must not only take into account module dependencies, but also
1416 * 'hidden' dependencies created by modules calling LoadLibrary in their
1417 * attach notification routine.
1419 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1420 * list after the attach notification has returned. This implies that the
1421 * detach notifications are called in the reverse of the sequence the attach
1422 * notifications *returned*.
1424 * The loader_section must be locked while calling this function.
1426 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1428 NTSTATUS status = STATUS_SUCCESS;
1429 ULONG_PTR cookie;
1430 int i;
1432 if (process_detaching) return status;
1434 /* prevent infinite recursion in case of cyclical dependencies */
1435 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1436 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1437 return status;
1439 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1441 /* Tag current MODREF to prevent recursive loop */
1442 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1443 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1444 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1446 /* Recursively attach all DLLs this one depends on */
1447 for ( i = 0; i < wm->nDeps; i++ )
1449 if (!wm->deps[i]) continue;
1450 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1453 if (!wm->ldr.InInitializationOrderLinks.Flink)
1454 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1455 &wm->ldr.InInitializationOrderLinks);
1457 /* Call DLL entry point */
1458 if (status == STATUS_SUCCESS)
1460 WINE_MODREF *prev = current_modref;
1461 current_modref = wm;
1463 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1464 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1465 if (status == STATUS_SUCCESS)
1467 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1469 else
1471 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1472 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1474 /* point to the name so LdrInitializeThunk can print it */
1475 last_failed_modref = wm;
1476 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1478 current_modref = prev;
1481 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1482 /* Remove recursion flag */
1483 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1485 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1486 return status;
1490 /*************************************************************************
1491 * process_detach
1493 * Send DLL process detach notifications. See the comment about calling
1494 * sequence at process_attach.
1496 static void process_detach(void)
1498 PLIST_ENTRY mark, entry;
1499 PLDR_DATA_TABLE_ENTRY mod;
1501 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1504 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1506 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1507 InInitializationOrderLinks);
1508 /* Check whether to detach this DLL */
1509 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1510 continue;
1511 if ( mod->LoadCount && !process_detaching )
1512 continue;
1514 /* Call detach notification */
1515 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1516 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1517 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1518 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1520 /* Restart at head of WINE_MODREF list, as entries might have
1521 been added and/or removed while performing the call ... */
1522 break;
1524 } while (entry != mark);
1527 /*************************************************************************
1528 * thread_attach
1530 * Send DLL thread attach notifications. These are sent in the
1531 * reverse sequence of process detach notification.
1532 * The loader_section must be locked while calling this function.
1534 static void thread_attach(void)
1536 PLIST_ENTRY mark, entry;
1537 PLDR_DATA_TABLE_ENTRY mod;
1539 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1540 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1542 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1543 InInitializationOrderLinks);
1544 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1545 continue;
1546 if ( mod->Flags & LDR_NO_DLL_CALLS )
1547 continue;
1549 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1553 /******************************************************************
1554 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1557 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1559 WINE_MODREF *wm;
1560 NTSTATUS ret = STATUS_SUCCESS;
1562 RtlEnterCriticalSection( &loader_section );
1564 wm = get_modref( hModule );
1565 if (!wm || wm->ldr.TlsIndex != -1)
1566 ret = STATUS_DLL_NOT_FOUND;
1567 else
1568 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1570 RtlLeaveCriticalSection( &loader_section );
1572 return ret;
1575 /******************************************************************
1576 * LdrFindEntryForAddress (NTDLL.@)
1578 * The loader_section must be locked while calling this function
1580 NTSTATUS WINAPI LdrFindEntryForAddress( const void *addr, PLDR_DATA_TABLE_ENTRY *pmod )
1582 PLIST_ENTRY mark, entry;
1583 PLDR_DATA_TABLE_ENTRY mod;
1585 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1586 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1588 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
1589 if (mod->DllBase <= addr &&
1590 (const char *)addr < (char*)mod->DllBase + mod->SizeOfImage)
1592 *pmod = mod;
1593 return STATUS_SUCCESS;
1596 return STATUS_NO_MORE_ENTRIES;
1599 /******************************************************************
1600 * LdrEnumerateLoadedModules (NTDLL.@)
1602 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1604 LIST_ENTRY *mark, *entry;
1605 LDR_DATA_TABLE_ENTRY *mod;
1606 BOOLEAN stop = FALSE;
1608 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1610 if (unknown || !callback)
1611 return STATUS_INVALID_PARAMETER;
1613 RtlEnterCriticalSection( &loader_section );
1615 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1616 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1618 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
1619 callback( mod, context, &stop );
1620 if (stop) break;
1623 RtlLeaveCriticalSection( &loader_section );
1624 return STATUS_SUCCESS;
1627 /******************************************************************
1628 * LdrRegisterDllNotification (NTDLL.@)
1630 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1631 void *context, void **cookie)
1633 struct ldr_notification *notify;
1635 TRACE( "(%x, %p, %p, %p)\n", flags, callback, context, cookie );
1637 if (!callback || !cookie)
1638 return STATUS_INVALID_PARAMETER;
1640 if (flags)
1641 FIXME( "ignoring flags %x\n", flags );
1643 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1644 if (!notify) return STATUS_NO_MEMORY;
1645 notify->callback = callback;
1646 notify->context = context;
1648 RtlEnterCriticalSection( &loader_section );
1649 list_add_tail( &ldr_notifications, &notify->entry );
1650 RtlLeaveCriticalSection( &loader_section );
1652 *cookie = notify;
1653 return STATUS_SUCCESS;
1656 /******************************************************************
1657 * LdrUnregisterDllNotification (NTDLL.@)
1659 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1661 struct ldr_notification *notify = cookie;
1663 TRACE( "(%p)\n", cookie );
1665 if (!notify) return STATUS_INVALID_PARAMETER;
1667 RtlEnterCriticalSection( &loader_section );
1668 list_remove( &notify->entry );
1669 RtlLeaveCriticalSection( &loader_section );
1671 RtlFreeHeap( GetProcessHeap(), 0, notify );
1672 return STATUS_SUCCESS;
1675 /******************************************************************
1676 * LdrLockLoaderLock (NTDLL.@)
1678 * Note: some flags are not implemented.
1679 * Flag 0x01 is used to raise exceptions on errors.
1681 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1683 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1685 if (result) *result = 0;
1686 if (magic) *magic = 0;
1687 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1688 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1689 if (!magic) return STATUS_INVALID_PARAMETER_3;
1691 if (flags & 0x2)
1693 if (!RtlTryEnterCriticalSection( &loader_section ))
1695 *result = 2;
1696 return STATUS_SUCCESS;
1698 *result = 1;
1700 else
1702 RtlEnterCriticalSection( &loader_section );
1703 if (result) *result = 1;
1705 *magic = GetCurrentThreadId();
1706 return STATUS_SUCCESS;
1710 /******************************************************************
1711 * LdrUnlockLoaderUnlock (NTDLL.@)
1713 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1715 if (magic)
1717 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1718 RtlLeaveCriticalSection( &loader_section );
1720 return STATUS_SUCCESS;
1724 /******************************************************************
1725 * LdrGetProcedureAddress (NTDLL.@)
1727 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1728 ULONG ord, PVOID *address)
1730 IMAGE_EXPORT_DIRECTORY *exports;
1731 DWORD exp_size;
1732 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1734 RtlEnterCriticalSection( &loader_section );
1736 /* check if the module itself is invalid to return the proper error */
1737 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1738 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1739 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1741 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, NULL )
1742 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, NULL );
1743 if (proc)
1745 *address = proc;
1746 ret = STATUS_SUCCESS;
1750 RtlLeaveCriticalSection( &loader_section );
1751 return ret;
1755 /***********************************************************************
1756 * set_security_cookie
1758 * Create a random security cookie for buffer overflow protection. Make
1759 * sure it does not accidentally match the default cookie value.
1761 static void set_security_cookie( void *module, SIZE_T len )
1763 static ULONG seed;
1764 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1765 ULONG loadcfg_size;
1766 ULONG_PTR *cookie;
1768 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1769 if (!loadcfg) return;
1770 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1771 if (!loadcfg->SecurityCookie) return;
1772 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1773 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1775 WARN( "security cookie %p outside of image %p-%p\n",
1776 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1777 return;
1780 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1781 TRACE( "initializing security cookie %p\n", cookie );
1783 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1784 for (;;)
1786 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1787 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1788 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1789 *cookie = RtlRandom( &seed );
1790 #ifdef DEFAULT_SECURITY_COOKIE_64
1791 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1793 *cookie = RtlRandom( &seed );
1794 /* fill up, but keep the highest word clear */
1795 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1797 #endif
1798 else
1799 break;
1803 static NTSTATUS perform_relocations( void *module, IMAGE_NT_HEADERS *nt, SIZE_T len )
1805 char *base;
1806 IMAGE_BASE_RELOCATION *rel, *end;
1807 const IMAGE_DATA_DIRECTORY *relocs;
1808 const IMAGE_SECTION_HEADER *sec;
1809 INT_PTR delta;
1810 ULONG protect_old[96], i;
1812 base = (char *)nt->OptionalHeader.ImageBase;
1813 if (module == base) return STATUS_SUCCESS; /* nothing to do */
1815 /* no relocations are performed on non page-aligned binaries */
1816 if (nt->OptionalHeader.SectionAlignment < page_size)
1817 return STATUS_SUCCESS;
1819 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1820 return STATUS_SUCCESS;
1822 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1824 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1826 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1827 base, module );
1828 return STATUS_CONFLICTING_ADDRESSES;
1831 if (!relocs->Size) return STATUS_SUCCESS;
1832 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1834 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
1835 return STATUS_INVALID_IMAGE_FORMAT;
1837 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1838 nt->FileHeader.SizeOfOptionalHeader);
1839 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1841 void *addr = get_rva( module, sec[i].VirtualAddress );
1842 SIZE_T size = sec[i].SizeOfRawData;
1843 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1844 &size, PAGE_READWRITE, &protect_old[i] );
1847 TRACE( "relocating from %p-%p to %p-%p\n",
1848 base, base + len, module, (char *)module + len );
1850 rel = get_rva( module, relocs->VirtualAddress );
1851 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1852 delta = (char *)module - base;
1854 while (rel < end - 1 && rel->SizeOfBlock)
1856 if (rel->VirtualAddress >= len)
1858 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1859 return STATUS_ACCESS_VIOLATION;
1861 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1862 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1863 (USHORT *)(rel + 1), delta );
1864 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1867 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1869 void *addr = get_rva( module, sec[i].VirtualAddress );
1870 SIZE_T size = sec[i].SizeOfRawData;
1871 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1872 &size, protect_old[i], &protect_old[i] );
1875 return STATUS_SUCCESS;
1879 /*************************************************************************
1880 * build_module
1882 * Build the module data for a mapped dll.
1884 static NTSTATUS build_module( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module,
1885 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
1886 DWORD flags, WINE_MODREF **pwm )
1888 static const char builtin_signature[] = "Wine builtin DLL";
1889 char *signature = (char *)((IMAGE_DOS_HEADER *)*module + 1);
1890 BOOL is_builtin;
1891 IMAGE_NT_HEADERS *nt;
1892 WINE_MODREF *wm;
1893 NTSTATUS status;
1894 SIZE_T map_size;
1896 if (!(nt = RtlImageNtHeader( *module ))) return STATUS_INVALID_IMAGE_FORMAT;
1898 map_size = (nt->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
1899 if ((status = perform_relocations( *module, nt, map_size ))) return status;
1901 is_builtin = ((char *)nt - signature >= sizeof(builtin_signature) &&
1902 !memcmp( signature, builtin_signature, sizeof(builtin_signature) ));
1904 /* create the MODREF */
1906 if (!(wm = alloc_module( *module, nt_name, is_builtin ))) return STATUS_NO_MEMORY;
1908 if (id) wm->id = *id;
1909 if (image_info->LoaderFlags) wm->ldr.Flags |= LDR_COR_IMAGE;
1910 if (image_info->u.s.ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
1912 set_security_cookie( *module, map_size );
1914 /* fixup imports */
1916 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1917 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1918 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1920 if (wm->ldr.Flags & LDR_COR_ILONLY)
1921 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
1922 else
1923 status = fixup_imports( wm, load_path );
1924 if (status != STATUS_SUCCESS)
1926 /* the module has only be inserted in the load & memory order lists */
1927 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
1928 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
1930 /* FIXME: there are several more dangling references
1931 * left. Including dlls loaded by this dll before the
1932 * failed one. Unrolling is rather difficult with the
1933 * current structure and we can leave them lying
1934 * around with no problems, so we don't care.
1935 * As these might reference our wm, we don't free it.
1937 *module = NULL;
1938 return status;
1942 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name), wm, *module );
1944 if (is_builtin)
1946 if (TRACE_ON(relay)) RELAY_SetupDLL( *module );
1948 else
1950 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( *module );
1953 TRACE_(loaddll)( "Loaded %s at %p: %s\n", debugstr_w(wm->ldr.FullDllName.Buffer), *module,
1954 is_builtin ? "builtin" : "native" );
1956 wm->ldr.LoadCount = 1;
1957 *pwm = wm;
1958 *module = NULL;
1959 return STATUS_SUCCESS;
1963 /*************************************************************************
1964 * build_ntdll_module
1966 * Build the module data for the initially-loaded ntdll.
1968 static void build_ntdll_module(void)
1970 MEMORY_BASIC_INFORMATION meminfo;
1971 UNICODE_STRING nt_name;
1972 WINE_MODREF *wm;
1974 RtlInitUnicodeString( &nt_name, L"\\??\\C:\\windows\\system32\\ntdll.dll" );
1975 NtQueryVirtualMemory( GetCurrentProcess(), build_ntdll_module, MemoryBasicInformation,
1976 &meminfo, sizeof(meminfo), NULL );
1977 wm = alloc_module( meminfo.AllocationBase, &nt_name, TRUE );
1978 assert( wm );
1979 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1980 if (TRACE_ON(relay)) RELAY_SetupDLL( meminfo.AllocationBase );
1984 #ifdef _WIN64
1985 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1986 static BOOL convert_to_pe64( HMODULE module, const SECTION_IMAGE_INFORMATION *info )
1988 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
1989 IMAGE_DIRECTORY_ENTRY_SECURITY,
1990 IMAGE_DIRECTORY_ENTRY_BASERELOC,
1991 IMAGE_DIRECTORY_ENTRY_DEBUG,
1992 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
1993 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
1994 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
1995 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1996 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
1997 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
1998 SIZE_T size = min( nt->OptionalHeader.SizeOfHeaders, nt->OptionalHeader.SizeOfImage );
1999 void *addr = module;
2000 ULONG i, old_prot;
2002 if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return TRUE; /* already 64-bit */
2003 if (!info->ImageContainsCode) return TRUE; /* no need to convert */
2005 TRACE( "%p\n", module );
2007 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
2008 return FALSE;
2010 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
2012 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2013 return FALSE;
2016 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
2017 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
2018 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
2019 hdr64.AddressOfEntryPoint = 0;
2020 hdr64.ImageBase = hdr32.ImageBase;
2021 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
2022 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
2023 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
2024 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
2025 hdr64.LoaderFlags = hdr32.LoaderFlags;
2026 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
2027 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
2028 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
2030 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
2031 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
2032 nt->OptionalHeader = hdr64;
2033 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2034 return TRUE;
2037 /* check COM header for ILONLY flag, ignoring runtime version */
2038 static BOOL get_cor_header( HANDLE file, const SECTION_IMAGE_INFORMATION *info, IMAGE_COR20_HEADER *cor )
2040 IMAGE_DOS_HEADER mz;
2041 IMAGE_NT_HEADERS32 nt;
2042 IO_STATUS_BLOCK io;
2043 LARGE_INTEGER offset;
2044 IMAGE_SECTION_HEADER sec[96];
2045 unsigned int i, count;
2046 DWORD va, size;
2048 offset.QuadPart = 0;
2049 if (NtReadFile( file, 0, NULL, NULL, &io, &mz, sizeof(mz), &offset, NULL )) return FALSE;
2050 if (io.Information != sizeof(mz)) return FALSE;
2051 if (mz.e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
2052 offset.QuadPart = mz.e_lfanew;
2053 if (NtReadFile( file, 0, NULL, NULL, &io, &nt, sizeof(nt), &offset, NULL )) return FALSE;
2054 if (io.Information != sizeof(nt)) return FALSE;
2055 if (nt.Signature != IMAGE_NT_SIGNATURE) return FALSE;
2056 if (nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return FALSE;
2057 va = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress;
2058 size = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size;
2059 if (!va || size < sizeof(*cor)) return FALSE;
2060 offset.QuadPart += offsetof( IMAGE_NT_HEADERS32, OptionalHeader ) + nt.FileHeader.SizeOfOptionalHeader;
2061 count = min( 96, nt.FileHeader.NumberOfSections );
2062 if (NtReadFile( file, 0, NULL, NULL, &io, &sec, count * sizeof(*sec), &offset, NULL )) return FALSE;
2063 if (io.Information != count * sizeof(*sec)) return FALSE;
2064 for (i = 0; i < count; i++)
2066 if (va < sec[i].VirtualAddress) continue;
2067 if (sec[i].Misc.VirtualSize && va - sec[i].VirtualAddress >= sec[i].Misc.VirtualSize) continue;
2068 offset.QuadPart = sec->PointerToRawData + va - sec[i].VirtualAddress;
2069 if (NtReadFile( file, 0, NULL, NULL, &io, cor, sizeof(*cor), &offset, NULL )) return FALSE;
2070 return (io.Information == sizeof(*cor));
2072 return FALSE;
2074 #endif
2076 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2077 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2078 static BOOL is_valid_binary( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2080 #ifdef __i386__
2081 return info->Machine == IMAGE_FILE_MACHINE_I386;
2082 #elif defined(__arm__)
2083 return info->Machine == IMAGE_FILE_MACHINE_ARM ||
2084 info->Machine == IMAGE_FILE_MACHINE_THUMB ||
2085 info->Machine == IMAGE_FILE_MACHINE_ARMNT;
2086 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2087 #ifdef __x86_64__
2088 if (info->Machine == IMAGE_FILE_MACHINE_AMD64) return TRUE;
2089 #else
2090 if (info->Machine == IMAGE_FILE_MACHINE_ARM64) return TRUE;
2091 #endif
2092 if (!info->ImageContainsCode) return TRUE;
2093 if (!(info->u.s.ComPlusNativeReady))
2095 IMAGE_COR20_HEADER cor_header;
2096 if (!get_cor_header( file, info, &cor_header )) return FALSE;
2097 if (!(cor_header.Flags & COMIMAGE_FLAGS_ILONLY)) return FALSE;
2099 return TRUE;
2100 #else
2101 return FALSE; /* no wow64 support on other platforms */
2102 #endif
2106 /******************************************************************
2107 * get_module_path_end
2109 * Returns the end of the directory component of the module path.
2111 static inline const WCHAR *get_module_path_end( const WCHAR *module )
2113 const WCHAR *p;
2114 const WCHAR *mod_end = module;
2116 if ((p = wcsrchr( mod_end, '\\' ))) mod_end = p;
2117 if ((p = wcsrchr( mod_end, '/' ))) mod_end = p;
2118 if (mod_end == module + 2 && module[1] == ':') mod_end++;
2119 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
2120 return mod_end;
2124 /******************************************************************
2125 * append_path
2127 * Append a counted string to the load path. Helper for get_dll_load_path.
2129 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str, int len )
2131 if (len == -1) len = wcslen(str);
2132 if (!len) return p;
2133 memcpy( p, str, len * sizeof(WCHAR) );
2134 p[len] = ';';
2135 return p + len + 1;
2139 /******************************************************************
2140 * get_dll_load_path
2142 static NTSTATUS get_dll_load_path( LPCWSTR module, LPCWSTR dll_dir, ULONG safe_mode, WCHAR **path )
2144 const WCHAR *mod_end = module;
2145 UNICODE_STRING name, value;
2146 WCHAR *p, *ret;
2147 int len = ARRAY_SIZE(system_path) + 1, path_len = 0;
2149 if (module)
2151 mod_end = get_module_path_end( module );
2152 len += (mod_end - module) + 1;
2155 RtlInitUnicodeString( &name, L"PATH" );
2156 value.Length = 0;
2157 value.MaximumLength = 0;
2158 value.Buffer = NULL;
2159 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2160 path_len = value.Length;
2162 if (dll_dir) len += wcslen( dll_dir ) + 1;
2163 else len += 2; /* current directory */
2164 if (!(p = ret = RtlAllocateHeap( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
2165 return STATUS_NO_MEMORY;
2167 p = append_path( p, module, mod_end - module );
2168 if (dll_dir) p = append_path( p, dll_dir, -1 );
2169 else if (!safe_mode) p = append_path( p, L".", -1 );
2170 p = append_path( p, system_path, -1 );
2171 if (!dll_dir && safe_mode) p = append_path( p, L".", -1 );
2173 value.Buffer = p;
2174 value.MaximumLength = path_len;
2176 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2178 WCHAR *new_ptr;
2180 /* grow the buffer and retry */
2181 path_len = value.Length;
2182 if (!(new_ptr = RtlReAllocateHeap( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
2184 RtlFreeHeap( GetProcessHeap(), 0, ret );
2185 return STATUS_NO_MEMORY;
2187 value.Buffer = new_ptr + (value.Buffer - ret);
2188 value.MaximumLength = path_len;
2189 ret = new_ptr;
2191 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
2192 *path = ret;
2193 return STATUS_SUCCESS;
2197 /******************************************************************
2198 * get_dll_load_path_search_flags
2200 static NTSTATUS get_dll_load_path_search_flags( LPCWSTR module, DWORD flags, WCHAR **path )
2202 const WCHAR *image = NULL, *mod_end, *image_end;
2203 struct dll_dir_entry *dir;
2204 WCHAR *p, *ret;
2205 int len = 1;
2207 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
2208 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
2209 LOAD_LIBRARY_SEARCH_USER_DIRS |
2210 LOAD_LIBRARY_SEARCH_SYSTEM32);
2212 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
2214 DWORD type = RtlDetermineDosPathNameType_U( module );
2215 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH && type != DEVICE_PATH)
2216 return STATUS_INVALID_PARAMETER;
2217 mod_end = get_module_path_end( module );
2218 len += (mod_end - module) + 1;
2220 else module = NULL;
2222 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
2224 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
2225 image_end = get_module_path_end( image );
2226 len += (image_end - image) + 1;
2229 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2231 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2232 len += wcslen( dir->dir + 4 /* \??\ */ ) + 1;
2233 if (dll_directory.Length) len += dll_directory.Length / sizeof(WCHAR) + 1;
2236 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += wcslen( system_dir );
2238 if ((p = ret = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2240 if (module) p = append_path( p, module, mod_end - module );
2241 if (image) p = append_path( p, image, image_end - image );
2242 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2244 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2245 p = append_path( p, dir->dir + 4 /* \??\ */, -1 );
2246 p = append_path( p, dll_directory.Buffer, dll_directory.Length / sizeof(WCHAR) );
2248 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) wcscpy( p, system_dir );
2249 else
2251 if (p > ret) p--;
2252 *p = 0;
2255 *path = ret;
2256 return STATUS_SUCCESS;
2260 /***********************************************************************
2261 * open_dll_file
2263 * Open a file for a new dll. Helper for find_dll_file.
2265 static NTSTATUS open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2266 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2268 FILE_BASIC_INFORMATION info;
2269 OBJECT_ATTRIBUTES attr;
2270 IO_STATUS_BLOCK io;
2271 LARGE_INTEGER size;
2272 FILE_OBJECTID_BUFFER fid;
2273 NTSTATUS status;
2274 HANDLE handle;
2276 if ((*pwm = find_fullname_module( nt_name ))) return STATUS_SUCCESS;
2278 attr.Length = sizeof(attr);
2279 attr.RootDirectory = 0;
2280 attr.Attributes = OBJ_CASE_INSENSITIVE;
2281 attr.ObjectName = nt_name;
2282 attr.SecurityDescriptor = NULL;
2283 attr.SecurityQualityOfService = NULL;
2284 if ((status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2285 FILE_SHARE_READ | FILE_SHARE_DELETE,
2286 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
2288 if (status != STATUS_OBJECT_PATH_NOT_FOUND &&
2289 status != STATUS_OBJECT_NAME_NOT_FOUND &&
2290 !NtQueryAttributesFile( &attr, &info ))
2292 /* if the file exists but failed to open, report the error */
2293 return status;
2295 /* otherwise continue searching */
2296 return STATUS_DLL_NOT_FOUND;
2299 if (!NtFsControlFile( handle, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &fid, sizeof(fid) ))
2301 memcpy( id, fid.ObjectId, sizeof(*id) );
2302 if ((*pwm = find_fileid_module( id )))
2304 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2305 (*pwm)->ldr.DllBase, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2306 NtClose( handle );
2307 return STATUS_SUCCESS;
2311 size.QuadPart = 0;
2312 status = NtCreateSection( mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2313 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2314 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, handle );
2315 if (!status)
2317 NtQuerySection( *mapping, SectionImageInformation, image_info, sizeof(*image_info), NULL );
2318 if (!is_valid_binary( handle, image_info ))
2320 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name), image_info->Machine );
2321 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2322 NtClose( *mapping );
2323 *mapping = NULL;
2326 NtClose( handle );
2327 return status;
2331 /******************************************************************************
2332 * find_existing_module
2334 * Find an existing module that is the same mapping as the new module.
2336 static WINE_MODREF *find_existing_module( HMODULE module )
2338 WINE_MODREF *wm;
2339 LIST_ENTRY *mark, *entry;
2340 LDR_DATA_TABLE_ENTRY *mod;
2341 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
2343 if ((wm = get_modref( module ))) return wm;
2345 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
2346 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2348 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
2349 if (mod->TimeDateStamp != nt->FileHeader.TimeDateStamp) continue;
2350 if (mod->CheckSum != nt->OptionalHeader.CheckSum) continue;
2351 if (NtAreMappedFilesTheSame( mod->DllBase, module ) != STATUS_SUCCESS) continue;
2352 return CONTAINING_RECORD( mod, WINE_MODREF, ldr );
2354 return NULL;
2358 /******************************************************************************
2359 * load_native_dll (internal)
2361 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, HANDLE mapping,
2362 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
2363 DWORD flags, WINE_MODREF** pwm )
2365 void *module = NULL;
2366 SIZE_T len = 0;
2367 NTSTATUS status = NtMapViewOfSection( mapping, NtCurrentProcess(), &module, 0, 0, NULL, &len,
2368 ViewShare, 0, PAGE_EXECUTE_READ );
2370 if (status == STATUS_IMAGE_NOT_AT_BASE) status = STATUS_SUCCESS;
2371 if (status) return status;
2373 if ((*pwm = find_existing_module( module ))) /* already loaded */
2375 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2376 TRACE( "found %s for %s at %p, count=%d\n",
2377 debugstr_us(&(*pwm)->ldr.FullDllName), debugstr_us(nt_name),
2378 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2379 if (module != (*pwm)->ldr.DllBase) NtUnmapViewOfSection( NtCurrentProcess(), module );
2380 return STATUS_SUCCESS;
2382 #ifdef _WIN64
2383 if (!convert_to_pe64( module, image_info )) status = STATUS_INVALID_IMAGE_FORMAT;
2384 #endif
2385 if (!status) status = build_module( load_path, nt_name, &module, image_info, id, flags, pwm );
2386 if (status && module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2387 return status;
2391 /***********************************************************************
2392 * load_so_dll
2394 static NTSTATUS load_so_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name,
2395 DWORD flags, WINE_MODREF **pwm )
2397 void *module;
2398 NTSTATUS status;
2399 WINE_MODREF *wm;
2400 UNICODE_STRING win_name = *nt_name;
2402 TRACE( "trying %s as so lib\n", debugstr_us(&win_name) );
2403 if ((status = unix_funcs->load_so_dll( &win_name, &module )))
2405 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name) );
2406 if (status == STATUS_INVALID_IMAGE_FORMAT) status = STATUS_INVALID_IMAGE_NOT_MZ;
2407 return status;
2410 if ((wm = get_modref( module ))) /* already loaded */
2412 TRACE( "Found %s at %p for builtin %s\n",
2413 debugstr_w(wm->ldr.FullDllName.Buffer), wm->ldr.DllBase, debugstr_us(nt_name) );
2414 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2416 else
2418 SECTION_IMAGE_INFORMATION image_info = { 0 };
2420 if ((status = build_module( load_path, &win_name, &module, &image_info, NULL, flags, &wm )))
2422 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2423 return status;
2425 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name), module );
2427 *pwm = wm;
2428 return STATUS_SUCCESS;
2432 /*************************************************************************
2433 * build_main_module
2435 * Build the module data for the main image.
2437 static WINE_MODREF *build_main_module(void)
2439 SECTION_IMAGE_INFORMATION info;
2440 UNICODE_STRING nt_name;
2441 WINE_MODREF *wm;
2442 NTSTATUS status;
2443 RTL_USER_PROCESS_PARAMETERS *params = NtCurrentTeb()->Peb->ProcessParameters;
2444 void *module = NtCurrentTeb()->Peb->ImageBaseAddress;
2446 default_load_path = params->DllPath.Buffer;
2447 if (!default_load_path)
2448 get_dll_load_path( params->ImagePathName.Buffer, NULL, dll_safe_mode, &default_load_path );
2450 NtQueryInformationProcess( GetCurrentProcess(), ProcessImageInformation, &info, sizeof(info), NULL );
2451 if (info.ImageCharacteristics & IMAGE_FILE_DLL)
2453 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_us(&params->ImagePathName) );
2454 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT );
2456 #ifdef _WIN64
2457 if (!convert_to_pe64( module, &info ))
2459 status = STATUS_INVALID_IMAGE_FORMAT;
2460 goto failed;
2462 #endif
2463 status = RtlDosPathNameToNtPathName_U_WithStatus( params->ImagePathName.Buffer, &nt_name, NULL, NULL );
2464 if (status) goto failed;
2465 status = build_module( NULL, &nt_name, &module, &info, NULL, DONT_RESOLVE_DLL_REFERENCES, &wm );
2466 RtlFreeUnicodeString( &nt_name );
2467 if (!status) return wm;
2468 failed:
2469 MESSAGE( "wine: failed to create main module for %s, status %x\n",
2470 debugstr_us(&params->ImagePathName), status );
2471 NtTerminateProcess( GetCurrentProcess(), status );
2472 return NULL; /* unreached */
2476 /***********************************************************************
2477 * build_dlldata_path
2479 * Helper for find_actctx_dll.
2481 static NTSTATUS build_dlldata_path( LPCWSTR libname, ACTCTX_SECTION_KEYED_DATA *data, LPWSTR *fullname )
2483 struct dllredirect_data *dlldata = data->lpData;
2484 char *base = data->lpSectionBase;
2485 SIZE_T total = dlldata->total_len + (wcslen(libname) + 1) * sizeof(WCHAR);
2486 WCHAR *p, *buffer;
2487 NTSTATUS status = STATUS_SUCCESS;
2488 ULONG i;
2490 if (!(p = buffer = RtlAllocateHeap( GetProcessHeap(), 0, total ))) return STATUS_NO_MEMORY;
2491 for (i = 0; i < dlldata->paths_count; i++)
2493 memcpy( p, base + dlldata->paths[i].offset, dlldata->paths[i].len );
2494 p += dlldata->paths[i].len / sizeof(WCHAR);
2496 if (p == buffer || p[-1] == '\\') wcscpy( p, libname );
2497 else *p = 0;
2499 if (dlldata->flags & DLL_REDIRECT_PATH_EXPAND)
2501 RtlExpandEnvironmentStrings( NULL, buffer, wcslen(buffer), NULL, 0, &total );
2502 if ((*fullname = RtlAllocateHeap( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
2503 RtlExpandEnvironmentStrings( NULL, buffer, wcslen(buffer), *fullname, total, NULL );
2504 else
2505 status = STATUS_NO_MEMORY;
2507 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2509 else *fullname = buffer;
2511 return status;
2515 /***********************************************************************
2516 * find_actctx_dll
2518 * Find the full path (if any) of the dll from the activation context.
2520 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2522 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2524 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info = NULL;
2525 ACTCTX_SECTION_KEYED_DATA data;
2526 struct dllredirect_data *dlldata;
2527 UNICODE_STRING nameW;
2528 NTSTATUS status;
2529 SIZE_T needed, size = 1024;
2530 WCHAR *p;
2532 RtlInitUnicodeString( &nameW, libname );
2533 data.cbSize = sizeof(data);
2534 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2535 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2536 &nameW, &data );
2537 if (status != STATUS_SUCCESS) return status;
2539 if (data.ulLength < offsetof( struct dllredirect_data, paths[0] ))
2541 status = STATUS_SXS_KEY_NOT_FOUND;
2542 goto done;
2544 dlldata = data.lpData;
2545 if (!(dlldata->flags & DLL_REDIRECT_PATH_OMITS_ASSEMBLY_ROOT))
2547 status = build_dlldata_path( libname, &data, fullname );
2548 goto done;
2551 for (;;)
2553 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2555 status = STATUS_NO_MEMORY;
2556 goto done;
2558 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2559 AssemblyDetailedInformationInActivationContext,
2560 info, size, &needed );
2561 if (status == STATUS_SUCCESS) break;
2562 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2563 RtlFreeHeap( GetProcessHeap(), 0, info );
2564 size = needed;
2565 /* restart with larger buffer */
2568 if (!info->lpAssemblyManifestPath)
2570 status = STATUS_SXS_KEY_NOT_FOUND;
2571 goto done;
2574 if ((p = wcsrchr( info->lpAssemblyManifestPath, '\\' )))
2576 DWORD len, dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2577 p++;
2578 len = wcslen( p );
2579 if (!dirlen || len <= dirlen ||
2580 RtlCompareUnicodeStrings( p, dirlen, info->lpAssemblyDirectoryName, dirlen, TRUE ) ||
2581 wcsicmp( p + dirlen, L".manifest" ))
2583 /* manifest name does not match directory name, so it's not a global
2584 * windows/winsxs manifest; use the manifest directory name instead */
2585 dirlen = p - info->lpAssemblyManifestPath;
2586 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2587 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2589 status = STATUS_NO_MEMORY;
2590 goto done;
2592 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2593 p += dirlen;
2594 wcscpy( p, libname );
2595 goto done;
2599 if (!info->lpAssemblyDirectoryName)
2601 status = STATUS_SXS_KEY_NOT_FOUND;
2602 goto done;
2605 needed = (wcslen(windows_dir) * sizeof(WCHAR) +
2606 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2608 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2610 status = STATUS_NO_MEMORY;
2611 goto done;
2613 wcscpy( p, windows_dir );
2614 p += wcslen(p);
2615 memcpy( p, winsxsW, sizeof(winsxsW) );
2616 p += ARRAY_SIZE( winsxsW );
2617 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2618 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2619 *p++ = '\\';
2620 wcscpy( p, libname );
2621 done:
2622 RtlFreeHeap( GetProcessHeap(), 0, info );
2623 RtlReleaseActivationContext( data.hActCtx );
2624 return status;
2628 /***********************************************************************
2629 * get_env_var
2631 static NTSTATUS get_env_var( const WCHAR *name, SIZE_T extra, UNICODE_STRING *ret )
2633 NTSTATUS status;
2634 SIZE_T len, size = 1024 + extra;
2636 for (;;)
2638 ret->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, size * sizeof(WCHAR) );
2639 status = RtlQueryEnvironmentVariable( NULL, name, wcslen(name),
2640 ret->Buffer, size - extra - 1, &len );
2641 if (!status)
2643 ret->Buffer[len] = 0;
2644 ret->Length = len * sizeof(WCHAR);
2645 ret->MaximumLength = size * sizeof(WCHAR);
2646 return status;
2648 RtlFreeHeap( GetProcessHeap(), 0, ret->Buffer );
2649 if (status != STATUS_BUFFER_TOO_SMALL)
2651 ret->Buffer = NULL;
2652 return status;
2654 size = len + 1 + extra;
2659 /***********************************************************************
2660 * find_builtin_without_file
2662 * Find a builtin dll when the corresponding file cannot be found in the prefix.
2663 * This is used during prefix bootstrap.
2665 static NTSTATUS find_builtin_without_file( const WCHAR *name, UNICODE_STRING *new_name,
2666 WINE_MODREF **pwm, HANDLE *mapping,
2667 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2669 const WCHAR *ext;
2670 WCHAR dllpath[32];
2671 DWORD i, len;
2672 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2673 BOOL found_image = FALSE;
2675 if (!get_env_var( L"WINEBUILDDIR", 20 + 2 * wcslen(name), new_name ))
2677 RtlAppendUnicodeToString( new_name, L"\\dlls\\" );
2678 RtlAppendUnicodeToString( new_name, name );
2679 if ((ext = wcsrchr( name, '.' )) && !wcscmp( ext, L".dll" )) new_name->Length -= 4 * sizeof(WCHAR);
2680 RtlAppendUnicodeToString( new_name, L"\\" );
2681 RtlAppendUnicodeToString( new_name, name );
2682 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2683 if (status != STATUS_DLL_NOT_FOUND) goto done;
2684 RtlAppendUnicodeToString( new_name, L".fake" );
2685 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2686 if (status != STATUS_DLL_NOT_FOUND) goto done;
2687 RtlFreeUnicodeString( new_name );
2690 for (i = 0; ; i++)
2692 swprintf( dllpath, ARRAY_SIZE(dllpath), L"WINEDLLDIR%u", i );
2693 if (get_env_var( dllpath, wcslen(pe_dir) + wcslen(name) + 1, new_name )) break;
2694 len = new_name->Length;
2695 RtlAppendUnicodeToString( new_name, pe_dir );
2696 RtlAppendUnicodeToString( new_name, L"\\" );
2697 RtlAppendUnicodeToString( new_name, name );
2698 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2699 if (status != STATUS_DLL_NOT_FOUND) goto done;
2700 new_name->Length = len;
2701 RtlAppendUnicodeToString( new_name, L"\\" );
2702 RtlAppendUnicodeToString( new_name, name );
2703 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2704 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2705 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2706 RtlFreeUnicodeString( new_name );
2708 if (found_image) status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2710 done:
2711 RtlFreeUnicodeString( new_name );
2712 if (!status)
2714 new_name->Length = (4 + wcslen(system_dir) + wcslen(name)) * sizeof(WCHAR);
2715 new_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, new_name->Length + sizeof(WCHAR) );
2716 wcscpy( new_name->Buffer, L"\\??\\" );
2717 wcscat( new_name->Buffer, system_dir );
2718 wcscat( new_name->Buffer, name );
2720 return status;
2724 /***********************************************************************
2725 * search_dll_file
2727 * Search for dll in the specified paths.
2729 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name,
2730 WINE_MODREF **pwm, HANDLE *mapping, SECTION_IMAGE_INFORMATION *image_info,
2731 struct file_id *id )
2733 WCHAR *name;
2734 BOOL found_image = FALSE;
2735 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2736 ULONG len;
2738 if (!paths) paths = default_load_path;
2739 len = wcslen( paths );
2741 if (len < wcslen( system_dir )) len = wcslen( system_dir );
2742 len += wcslen( search ) + 2;
2744 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2745 return STATUS_NO_MEMORY;
2747 while (*paths)
2749 LPCWSTR ptr = paths;
2751 while (*ptr && *ptr != ';') ptr++;
2752 len = ptr - paths;
2753 if (*ptr == ';') ptr++;
2754 memcpy( name, paths, len * sizeof(WCHAR) );
2755 if (len && name[len - 1] != '\\') name[len++] = '\\';
2756 wcscpy( name + len, search );
2758 nt_name->Buffer = NULL;
2759 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( name, nt_name, NULL, NULL ))) goto done;
2761 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
2762 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2763 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2764 RtlFreeUnicodeString( nt_name );
2765 paths = ptr;
2768 if (found_image)
2769 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2770 else if (is_prefix_bootstrap && !contains_path( search ))
2771 status = find_builtin_without_file( search, nt_name, pwm, mapping, image_info, id );
2773 done:
2774 RtlFreeHeap( GetProcessHeap(), 0, name );
2775 return status;
2779 /***********************************************************************
2780 * find_dll_file
2782 * Find the file (or already loaded module) for a given dll name.
2784 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2785 UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2786 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2788 WCHAR *ext, *dllname;
2789 NTSTATUS status;
2790 ULONG wow64_old_value = 0;
2792 *pwm = NULL;
2793 dllname = NULL;
2795 if (default_ext) /* first append default extension */
2797 if (!(ext = wcsrchr( libname, '.')) || wcschr( ext, '/' ) || wcschr( ext, '\\'))
2799 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2800 (wcslen(libname)+wcslen(default_ext)+1) * sizeof(WCHAR))))
2801 return STATUS_NO_MEMORY;
2802 wcscpy( dllname, libname );
2803 wcscat( dllname, default_ext );
2804 libname = dllname;
2808 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2809 RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value );
2811 nt_name->Buffer = NULL;
2813 if (!contains_path( libname ))
2815 WCHAR *fullname = NULL;
2817 status = find_actctx_dll( libname, &fullname );
2818 if (status == STATUS_SUCCESS)
2820 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2821 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2822 libname = dllname = fullname;
2824 else
2826 if (status != STATUS_SXS_KEY_NOT_FOUND) goto done;
2827 if ((*pwm = find_basename_module( libname )) != NULL)
2829 status = STATUS_SUCCESS;
2830 goto done;
2832 /* 16-bit files can't be loaded from the prefix */
2833 if (libname[0] && libname[1] && !wcscmp( libname + wcslen(libname) - 2, L"16" ))
2835 status = find_builtin_without_file( libname, nt_name, pwm, mapping, image_info, id );
2836 goto done;
2841 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2842 status = search_dll_file( load_path, libname, nt_name, pwm, mapping, image_info, id );
2843 else if (!(status = RtlDosPathNameToNtPathName_U_WithStatus( libname, nt_name, NULL, NULL )))
2844 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
2846 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) status = STATUS_INVALID_IMAGE_FORMAT;
2848 done:
2849 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2850 if (wow64_old_value) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value );
2851 return status;
2855 /***********************************************************************
2856 * load_dll (internal)
2858 * Load a PE style module according to the load order.
2859 * The loader_section must be locked while calling this function.
2861 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2862 DWORD flags, WINE_MODREF** pwm )
2864 UNICODE_STRING nt_name;
2865 struct file_id id;
2866 HANDLE mapping = 0;
2867 SECTION_IMAGE_INFORMATION image_info;
2868 NTSTATUS nts;
2869 ULONG64 prev;
2871 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2873 nts = find_dll_file( load_path, libname, default_ext, &nt_name, pwm, &mapping, &image_info, &id );
2875 if (*pwm) /* found already loaded module */
2877 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2879 TRACE("Found %s for %s at %p, count=%d\n",
2880 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2881 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2882 RtlFreeUnicodeString( &nt_name );
2883 return STATUS_SUCCESS;
2886 if (nts && nts != STATUS_INVALID_IMAGE_NOT_MZ) goto done;
2888 if (NtCurrentTeb64())
2890 prev = NtCurrentTeb64()->Tib.ArbitraryUserPointer;
2891 NtCurrentTeb64()->Tib.ArbitraryUserPointer = (ULONG_PTR)(nt_name.Buffer + 4);
2893 else
2895 prev = (ULONG_PTR)NtCurrentTeb()->Tib.ArbitraryUserPointer;
2896 NtCurrentTeb()->Tib.ArbitraryUserPointer = nt_name.Buffer + 4;
2899 switch (nts)
2901 case STATUS_INVALID_IMAGE_NOT_MZ: /* not in PE format, maybe it's a .so file */
2902 nts = load_so_dll( load_path, &nt_name, flags, pwm );
2903 break;
2905 case STATUS_SUCCESS: /* valid PE file */
2906 nts = load_native_dll( load_path, &nt_name, mapping, &image_info, &id, flags, pwm );
2907 break;
2910 if (NtCurrentTeb64())
2911 NtCurrentTeb64()->Tib.ArbitraryUserPointer = prev;
2912 else
2913 NtCurrentTeb()->Tib.ArbitraryUserPointer = (void *)(ULONG_PTR)prev;
2915 done:
2916 if (nts == STATUS_SUCCESS)
2917 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name), (*pwm)->ldr.DllBase);
2918 else
2919 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2921 if (mapping) NtClose( mapping );
2922 RtlFreeUnicodeString( &nt_name );
2923 return nts;
2927 /***********************************************************************
2928 * __wine_init_unix_lib
2930 NTSTATUS __cdecl __wine_init_unix_lib( HMODULE module, DWORD reason, const void *ptr_in, void *ptr_out )
2932 WINE_MODREF *wm;
2933 NTSTATUS ret;
2935 RtlEnterCriticalSection( &loader_section );
2937 if ((wm = get_modref( module ))) ret = unix_funcs->init_unix_lib( module, reason, ptr_in, ptr_out );
2938 else ret = STATUS_INVALID_HANDLE;
2940 RtlLeaveCriticalSection( &loader_section );
2941 return ret;
2945 /******************************************************************
2946 * LdrLoadDll (NTDLL.@)
2948 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2949 const UNICODE_STRING *libname, HMODULE* hModule)
2951 WINE_MODREF *wm;
2952 NTSTATUS nts;
2954 RtlEnterCriticalSection( &loader_section );
2956 nts = load_dll( path_name, libname->Buffer, L".dll", flags, &wm );
2958 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2960 nts = process_attach( wm, NULL );
2961 if (nts != STATUS_SUCCESS)
2963 LdrUnloadDll(wm->ldr.DllBase);
2964 wm = NULL;
2967 *hModule = (wm) ? wm->ldr.DllBase : NULL;
2969 RtlLeaveCriticalSection( &loader_section );
2970 return nts;
2974 /******************************************************************
2975 * LdrGetDllHandle (NTDLL.@)
2977 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2979 NTSTATUS status;
2980 UNICODE_STRING nt_name;
2981 WINE_MODREF *wm;
2982 HANDLE mapping;
2983 SECTION_IMAGE_INFORMATION image_info;
2984 struct file_id id;
2986 RtlEnterCriticalSection( &loader_section );
2988 status = find_dll_file( load_path, name->Buffer, L".dll", &nt_name, &wm, &mapping, &image_info, &id );
2990 if (wm) *base = wm->ldr.DllBase;
2991 else
2993 if (status == STATUS_SUCCESS) NtClose( mapping );
2994 status = STATUS_DLL_NOT_FOUND;
2996 RtlFreeUnicodeString( &nt_name );
2998 RtlLeaveCriticalSection( &loader_section );
2999 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
3000 return status;
3004 /******************************************************************
3005 * LdrAddRefDll (NTDLL.@)
3007 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
3009 NTSTATUS ret = STATUS_SUCCESS;
3010 WINE_MODREF *wm;
3012 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
3014 RtlEnterCriticalSection( &loader_section );
3016 if ((wm = get_modref( module )))
3018 if (flags & LDR_ADDREF_DLL_PIN)
3019 wm->ldr.LoadCount = -1;
3020 else
3021 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
3022 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3024 else ret = STATUS_INVALID_PARAMETER;
3026 RtlLeaveCriticalSection( &loader_section );
3027 return ret;
3031 /***********************************************************************
3032 * LdrProcessRelocationBlock (NTDLL.@)
3034 * Apply relocations to a given page of a mapped PE image.
3036 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
3037 USHORT *relocs, INT_PTR delta )
3039 while (count--)
3041 USHORT offset = *relocs & 0xfff;
3042 int type = *relocs >> 12;
3043 switch(type)
3045 case IMAGE_REL_BASED_ABSOLUTE:
3046 break;
3047 case IMAGE_REL_BASED_HIGH:
3048 *(short *)((char *)page + offset) += HIWORD(delta);
3049 break;
3050 case IMAGE_REL_BASED_LOW:
3051 *(short *)((char *)page + offset) += LOWORD(delta);
3052 break;
3053 case IMAGE_REL_BASED_HIGHLOW:
3054 *(int *)((char *)page + offset) += delta;
3055 break;
3056 #ifdef _WIN64
3057 case IMAGE_REL_BASED_DIR64:
3058 *(INT_PTR *)((char *)page + offset) += delta;
3059 break;
3060 #elif defined(__arm__)
3061 case IMAGE_REL_BASED_THUMB_MOV32:
3063 DWORD *inst = (DWORD *)((char *)page + offset);
3064 WORD lo = ((inst[0] << 1) & 0x0800) + ((inst[0] << 12) & 0xf000) +
3065 ((inst[0] >> 20) & 0x0700) + ((inst[0] >> 16) & 0x00ff);
3066 WORD hi = ((inst[1] << 1) & 0x0800) + ((inst[1] << 12) & 0xf000) +
3067 ((inst[1] >> 20) & 0x0700) + ((inst[1] >> 16) & 0x00ff);
3068 DWORD imm = MAKELONG( lo, hi ) + delta;
3070 lo = LOWORD( imm );
3071 hi = HIWORD( imm );
3073 if ((inst[0] & 0x8000fbf0) != 0x0000f240 || (inst[1] & 0x8000fbf0) != 0x0000f2c0)
3074 ERR("wrong Thumb2 instruction @%p %08x:%08x, expected MOVW/MOVT\n",
3075 inst, inst[0], inst[1] );
3077 inst[0] = (inst[0] & 0x8f00fbf0) + ((lo >> 1) & 0x0400) + ((lo >> 12) & 0x000f) +
3078 ((lo << 20) & 0x70000000) + ((lo << 16) & 0xff0000);
3079 inst[1] = (inst[1] & 0x8f00fbf0) + ((hi >> 1) & 0x0400) + ((hi >> 12) & 0x000f) +
3080 ((hi << 20) & 0x70000000) + ((hi << 16) & 0xff0000);
3081 break;
3083 #endif
3084 default:
3085 FIXME("Unknown/unsupported fixup type %x.\n", type);
3086 return NULL;
3088 relocs++;
3090 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
3094 /******************************************************************
3095 * LdrQueryProcessModuleInformation
3098 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
3099 ULONG buf_size, ULONG* req_size)
3101 SYSTEM_MODULE* sm = &smi->Modules[0];
3102 ULONG size = sizeof(ULONG);
3103 NTSTATUS nts = STATUS_SUCCESS;
3104 ANSI_STRING str;
3105 char* ptr;
3106 PLIST_ENTRY mark, entry;
3107 LDR_DATA_TABLE_ENTRY *mod;
3108 WORD id = 0;
3110 smi->ModulesCount = 0;
3112 RtlEnterCriticalSection( &loader_section );
3113 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3114 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3116 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3117 size += sizeof(*sm);
3118 if (size <= buf_size)
3120 sm->Section = 0; /* FIXME */
3121 sm->MappedBaseAddress = mod->DllBase;
3122 sm->ImageBaseAddress = mod->DllBase;
3123 sm->ImageSize = mod->SizeOfImage;
3124 sm->Flags = mod->Flags;
3125 sm->LoadOrderIndex = id++;
3126 sm->InitOrderIndex = 0; /* FIXME */
3127 sm->LoadCount = mod->LoadCount;
3128 str.Length = 0;
3129 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
3130 str.Buffer = (char*)sm->Name;
3131 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
3132 ptr = strrchr(str.Buffer, '\\');
3133 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
3135 smi->ModulesCount++;
3136 sm++;
3138 else nts = STATUS_INFO_LENGTH_MISMATCH;
3140 RtlLeaveCriticalSection( &loader_section );
3142 if (req_size) *req_size = size;
3144 return nts;
3148 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
3150 NTSTATUS status;
3151 UNICODE_STRING str;
3152 ULONG size;
3153 WCHAR buffer[64];
3154 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3156 RtlInitUnicodeString( &str, name );
3158 size = sizeof(buffer) - sizeof(WCHAR);
3159 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
3160 return status;
3162 if (info->Type != REG_DWORD)
3164 buffer[size / sizeof(WCHAR)] = 0;
3165 *value = wcstoul( (WCHAR *)info->Data, 0, 16 );
3167 else memcpy( value, info->Data, sizeof(*value) );
3168 return status;
3171 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
3172 void *data, ULONG in_size, ULONG *out_size )
3174 NTSTATUS status;
3175 UNICODE_STRING str;
3176 ULONG size;
3177 char *buffer;
3178 KEY_VALUE_PARTIAL_INFORMATION *info;
3179 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
3181 RtlInitUnicodeString( &str, name );
3183 size = info_size + in_size;
3184 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
3185 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3186 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
3187 if (!status || status == STATUS_BUFFER_OVERFLOW)
3189 if (out_size) *out_size = info->DataLength;
3190 if (data && !status) memcpy( data, info->Data, info->DataLength );
3192 RtlFreeHeap( GetProcessHeap(), 0, buffer );
3193 return status;
3197 /******************************************************************
3198 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3200 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
3201 void *data, ULONG in_size, ULONG *out_size )
3203 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
3204 'S','o','f','t','w','a','r','e','\\',
3205 'M','i','c','r','o','s','o','f','t','\\',
3206 'W','i','n','d','o','w','s',' ','N','T','\\',
3207 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3208 'I','m','a','g','e',' ','F','i','l','e',' ',
3209 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3210 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
3211 OBJECT_ATTRIBUTES attr;
3212 UNICODE_STRING name_str;
3213 HANDLE hkey;
3214 NTSTATUS status;
3215 ULONG len;
3216 WCHAR *p;
3218 attr.Length = sizeof(attr);
3219 attr.RootDirectory = 0;
3220 attr.ObjectName = &name_str;
3221 attr.Attributes = OBJ_CASE_INSENSITIVE;
3222 attr.SecurityDescriptor = NULL;
3223 attr.SecurityQualityOfService = NULL;
3225 p = key->Buffer + key->Length / sizeof(WCHAR);
3226 while (p > key->Buffer && p[-1] != '\\') p--;
3227 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
3228 name_str.Buffer = path;
3229 name_str.Length = sizeof(optionsW) + len;
3230 name_str.MaximumLength = name_str.Length;
3231 memcpy( path, optionsW, sizeof(optionsW) );
3232 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
3233 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
3235 if (type == REG_DWORD)
3237 if (out_size) *out_size = sizeof(ULONG);
3238 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
3239 else status = STATUS_BUFFER_OVERFLOW;
3241 else status = query_string_option( hkey, value, type, data, in_size, out_size );
3243 NtClose( hkey );
3244 return status;
3248 /******************************************************************
3249 * RtlDllShutdownInProgress (NTDLL.@)
3251 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
3253 return process_detaching;
3256 /****************************************************************************
3257 * LdrResolveDelayLoadedAPI (NTDLL.@)
3259 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
3260 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
3261 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
3262 IMAGE_THUNK_DATA* addr, ULONG flags )
3264 IMAGE_THUNK_DATA *pIAT, *pINT;
3265 DELAYLOAD_INFO delayinfo;
3266 UNICODE_STRING mod;
3267 const CHAR* name;
3268 HMODULE *phmod;
3269 NTSTATUS nts;
3270 FARPROC fp;
3271 DWORD id;
3273 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base, desc, dllhook, syshook, addr, flags );
3275 phmod = get_rva(base, desc->ModuleHandleRVA);
3276 pIAT = get_rva(base, desc->ImportAddressTableRVA);
3277 pINT = get_rva(base, desc->ImportNameTableRVA);
3278 name = get_rva(base, desc->DllNameRVA);
3279 id = addr - pIAT;
3281 if (!*phmod)
3283 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
3285 nts = STATUS_NO_MEMORY;
3286 goto fail;
3288 nts = LdrLoadDll(NULL, 0, &mod, phmod);
3289 RtlFreeUnicodeString(&mod);
3290 if (nts) goto fail;
3293 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3294 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
3295 else
3297 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3298 ANSI_STRING fnc;
3300 RtlInitAnsiString(&fnc, (char*)iibn->Name);
3301 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
3303 if (!nts)
3305 pIAT[id].u1.Function = (ULONG_PTR)fp;
3306 return fp;
3309 fail:
3310 delayinfo.Size = sizeof(delayinfo);
3311 delayinfo.DelayloadDescriptor = desc;
3312 delayinfo.ThunkAddress = addr;
3313 delayinfo.TargetDllName = name;
3314 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
3315 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
3316 delayinfo.TargetModuleBase = *phmod;
3317 delayinfo.Unused = NULL;
3318 delayinfo.LastError = nts;
3320 if (dllhook)
3321 return dllhook(4, &delayinfo);
3323 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3325 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3326 return syshook(name, (const char *)ord);
3328 else
3330 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3331 return syshook(name, (const char *)iibn->Name);
3335 /******************************************************************
3336 * LdrShutdownProcess (NTDLL.@)
3339 void WINAPI LdrShutdownProcess(void)
3341 BOOL detaching = process_detaching;
3343 TRACE("()\n");
3345 process_detaching = TRUE;
3346 if (!detaching)
3347 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3349 process_detach();
3353 /******************************************************************
3354 * RtlExitUserProcess (NTDLL.@)
3356 void WINAPI RtlExitUserProcess( DWORD status )
3358 RtlEnterCriticalSection( &loader_section );
3359 RtlAcquirePebLock();
3360 NtTerminateProcess( 0, status );
3361 LdrShutdownProcess();
3362 for (;;) NtTerminateProcess( GetCurrentProcess(), status );
3365 /******************************************************************
3366 * LdrShutdownThread (NTDLL.@)
3369 void WINAPI LdrShutdownThread(void)
3371 PLIST_ENTRY mark, entry;
3372 LDR_DATA_TABLE_ENTRY *mod;
3373 WINE_MODREF *wm;
3374 UINT i;
3375 void **pointers;
3377 TRACE("()\n");
3379 /* don't do any detach calls if process is exiting */
3380 if (process_detaching) return;
3382 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3384 RtlEnterCriticalSection( &loader_section );
3385 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3387 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3388 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3390 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
3391 InInitializationOrderLinks);
3392 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3393 continue;
3394 if ( mod->Flags & LDR_NO_DLL_CALLS )
3395 continue;
3397 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3398 DLL_THREAD_DETACH, NULL );
3401 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_DETACH );
3403 RtlAcquirePebLock();
3404 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3405 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3407 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3408 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3410 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 2 );
3411 NtCurrentTeb()->FlsSlots = NULL;
3412 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3413 NtCurrentTeb()->TlsExpansionSlots = NULL;
3414 RtlReleasePebLock();
3416 RtlLeaveCriticalSection( &loader_section );
3417 /* don't call DbgUiGetThreadDebugObject as some apps hook it and terminate if called */
3418 if (NtCurrentTeb()->DbgSsReserved[1]) NtClose( NtCurrentTeb()->DbgSsReserved[1] );
3419 RtlFreeThreadActivationContextStack();
3423 /***********************************************************************
3424 * free_modref
3427 static void free_modref( WINE_MODREF *wm )
3429 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
3430 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
3431 if (wm->ldr.InInitializationOrderLinks.Flink)
3432 RemoveEntryList(&wm->ldr.InInitializationOrderLinks);
3434 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3435 if (!TRACE_ON(module))
3436 TRACE_(loaddll)("Unloaded module %s : %s\n",
3437 debugstr_w(wm->ldr.FullDllName.Buffer),
3438 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3440 free_tls_slot( &wm->ldr );
3441 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3442 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.DllBase );
3443 if (cached_modref == wm) cached_modref = NULL;
3444 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3445 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
3446 RtlFreeHeap( GetProcessHeap(), 0, wm );
3449 /***********************************************************************
3450 * MODULE_FlushModrefs
3452 * Remove all unused modrefs and call the internal unloading routines
3453 * for the library type.
3455 * The loader_section must be locked while calling this function.
3457 static void MODULE_FlushModrefs(void)
3459 PLIST_ENTRY mark, entry, prev;
3460 LDR_DATA_TABLE_ENTRY *mod;
3461 WINE_MODREF*wm;
3463 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3464 for (entry = mark->Blink; entry != mark; entry = prev)
3466 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
3467 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3468 prev = entry->Blink;
3469 if (!mod->LoadCount) free_modref( wm );
3472 /* check load order list too for modules that haven't been initialized yet */
3473 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3474 for (entry = mark->Blink; entry != mark; entry = prev)
3476 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3477 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3478 prev = entry->Blink;
3479 if (!mod->LoadCount) free_modref( wm );
3483 /***********************************************************************
3484 * MODULE_DecRefCount
3486 * The loader_section must be locked while calling this function.
3488 static void MODULE_DecRefCount( WINE_MODREF *wm )
3490 int i;
3492 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3493 return;
3495 if ( wm->ldr.LoadCount <= 0 )
3496 return;
3498 --wm->ldr.LoadCount;
3499 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3501 if ( wm->ldr.LoadCount == 0 )
3503 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3505 for ( i = 0; i < wm->nDeps; i++ )
3506 if ( wm->deps[i] )
3507 MODULE_DecRefCount( wm->deps[i] );
3509 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3511 module_push_unload_trace( &wm->ldr );
3515 /******************************************************************
3516 * LdrUnloadDll (NTDLL.@)
3520 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3522 WINE_MODREF *wm;
3523 NTSTATUS retv = STATUS_SUCCESS;
3525 if (process_detaching) return retv;
3527 TRACE("(%p)\n", hModule);
3529 RtlEnterCriticalSection( &loader_section );
3531 free_lib_count++;
3532 if ((wm = get_modref( hModule )) != NULL)
3534 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3536 /* Recursively decrement reference counts */
3537 MODULE_DecRefCount( wm );
3539 /* Call process detach notifications */
3540 if ( free_lib_count <= 1 )
3542 process_detach();
3543 MODULE_FlushModrefs();
3546 TRACE("END\n");
3548 else
3549 retv = STATUS_DLL_NOT_FOUND;
3551 free_lib_count--;
3553 RtlLeaveCriticalSection( &loader_section );
3555 return retv;
3558 /***********************************************************************
3559 * RtlImageNtHeader (NTDLL.@)
3561 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3563 IMAGE_NT_HEADERS *ret;
3565 __TRY
3567 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3569 ret = NULL;
3570 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3572 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3573 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3576 __EXCEPT_PAGE_FAULT
3578 return NULL;
3580 __ENDTRY
3581 return ret;
3584 /***********************************************************************
3585 * process_breakpoint
3587 * Trigger a debug breakpoint if the process is being debugged.
3589 static void process_breakpoint(void)
3591 DWORD_PTR port = 0;
3593 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort, &port, sizeof(port), NULL );
3594 if (!port) return;
3596 __TRY
3598 DbgBreakPoint();
3600 __EXCEPT_ALL
3602 /* do nothing */
3604 __ENDTRY
3608 /***********************************************************************
3609 * load_global_options
3611 static void load_global_options(void)
3613 OBJECT_ATTRIBUTES attr;
3614 UNICODE_STRING name_str, val_str;
3615 HANDLE hkey;
3616 ULONG value;
3618 RtlInitUnicodeString( &name_str, L"WINEBOOTSTRAPMODE" );
3619 val_str.MaximumLength = 0;
3620 is_prefix_bootstrap = RtlQueryEnvironmentVariable_U( NULL, &name_str, &val_str ) != STATUS_VARIABLE_NOT_FOUND;
3622 attr.Length = sizeof(attr);
3623 attr.RootDirectory = 0;
3624 attr.ObjectName = &name_str;
3625 attr.Attributes = OBJ_CASE_INSENSITIVE;
3626 attr.SecurityDescriptor = NULL;
3627 attr.SecurityQualityOfService = NULL;
3628 RtlInitUnicodeString( &name_str, L"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3630 if (!NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))
3632 query_dword_option( hkey, L"GlobalFlag", &NtCurrentTeb()->Peb->NtGlobalFlag );
3633 query_dword_option( hkey, L"SafeProcessSearchMode", &path_safe_mode );
3634 query_dword_option( hkey, L"SafeDllSearchMode", &dll_safe_mode );
3636 if (!query_dword_option( hkey, L"CriticalSectionTimeout", &value ))
3637 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3639 if (!query_dword_option( hkey, L"HeapSegmentReserve", &value ))
3640 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3642 if (!query_dword_option( hkey, L"HeapSegmentCommit", &value ))
3643 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3645 if (!query_dword_option( hkey, L"HeapDeCommitTotalFreeThreshold", &value ))
3646 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3648 if (!query_dword_option( hkey, L"HeapDeCommitFreeBlockThreshold", &value ))
3649 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3651 NtClose( hkey );
3653 LdrQueryImageFileExecutionOptions( &NtCurrentTeb()->Peb->ProcessParameters->ImagePathName,
3654 L"GlobalFlag", REG_DWORD, &NtCurrentTeb()->Peb->NtGlobalFlag,
3655 sizeof(DWORD), NULL );
3656 heap_set_debug_flags( GetProcessHeap() );
3660 #ifndef _WIN64
3661 void *Wow64Transition = NULL;
3663 static void map_wow64cpu(void)
3665 SIZE_T size = 0;
3666 OBJECT_ATTRIBUTES attr;
3667 UNICODE_STRING string;
3668 HANDLE file, section;
3669 IO_STATUS_BLOCK io;
3670 NTSTATUS status;
3672 RtlInitUnicodeString( &string, L"\\??\\C:\\windows\\sysnative\\wow64cpu.dll" );
3673 InitializeObjectAttributes( &attr, &string, 0, NULL, NULL );
3674 if ((status = NtOpenFile( &file, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ,
3675 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
3677 WARN("failed to open wow64cpu, status %#x\n", status);
3678 return;
3680 if (!NtCreateSection( &section, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
3681 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
3682 NULL, NULL, PAGE_EXECUTE_READ, SEC_COMMIT, file ))
3684 NtMapViewOfSection( section, NtCurrentProcess(), &Wow64Transition, 0,
3685 0, NULL, &size, ViewShare, 0, PAGE_EXECUTE_READ );
3686 NtClose( section );
3688 NtClose( file );
3691 static void init_wow64(void)
3693 PEB *peb = NtCurrentTeb()->Peb;
3694 PEB64 *peb64;
3696 if (!NtCurrentTeb64()) return;
3697 peb64 = UlongToPtr( NtCurrentTeb64()->Peb );
3698 peb64->ImageBaseAddress = PtrToUlong( peb->ImageBaseAddress );
3699 peb64->OSMajorVersion = peb->OSMajorVersion;
3700 peb64->OSMinorVersion = peb->OSMinorVersion;
3701 peb64->OSBuildNumber = peb->OSBuildNumber;
3702 peb64->OSPlatformId = peb->OSPlatformId;
3703 peb64->SessionId = peb->SessionId;
3705 map_wow64cpu();
3707 #endif
3710 /******************************************************************
3711 * LdrInitializeThunk (NTDLL.@)
3713 * Attach to all the loaded dlls.
3714 * If this is the first time, perform the full process initialization.
3716 void WINAPI LdrInitializeThunk( CONTEXT *context, ULONG_PTR unknown2, ULONG_PTR unknown3, ULONG_PTR unknown4 )
3718 static int attach_done;
3719 int i;
3720 NTSTATUS status;
3721 ULONG_PTR cookie;
3722 WINE_MODREF *wm;
3723 void **entry;
3725 #ifdef __i386__
3726 entry = (void **)&context->Eax;
3727 #elif defined(__x86_64__)
3728 entry = (void **)&context->Rcx;
3729 #elif defined(__arm__)
3730 entry = (void **)&context->R0;
3731 #elif defined(__aarch64__)
3732 entry = (void **)&context->u.s.X0;
3733 #endif
3735 if (process_detaching) NtTerminateThread( GetCurrentThread(), 0 );
3737 RtlEnterCriticalSection( &loader_section );
3739 if (!imports_fixup_done)
3741 ANSI_STRING func_name;
3742 WINE_MODREF *kernel32;
3743 PEB *peb = NtCurrentTeb()->Peb;
3745 peb->LdrData = &ldr;
3746 peb->FastPebLock = &peb_lock;
3747 peb->TlsBitmap = &tls_bitmap;
3748 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
3749 peb->LoaderLock = &loader_section;
3750 peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
3752 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
3753 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
3754 sizeof(peb->TlsExpansionBitmapBits) * 8 );
3755 RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
3757 init_user_process_params();
3758 load_global_options();
3759 version_init();
3760 #ifndef _WIN64
3761 init_wow64();
3762 #endif
3763 wm = build_main_module();
3764 wm->ldr.LoadCount = -1;
3766 build_ntdll_module();
3768 if ((status = load_dll( NULL, L"kernel32.dll", NULL, 0, &kernel32 )) != STATUS_SUCCESS)
3770 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3771 NtTerminateProcess( GetCurrentProcess(), status );
3773 kernel32_handle = kernel32->ldr.DllBase;
3774 RtlInitAnsiString( &func_name, "BaseThreadInitThunk" );
3775 if ((status = LdrGetProcedureAddress( kernel32_handle, &func_name,
3776 0, (void **)&pBaseThreadInitThunk )) != STATUS_SUCCESS)
3778 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status );
3779 NtTerminateProcess( GetCurrentProcess(), status );
3782 actctx_init();
3783 if (wm->ldr.Flags & LDR_COR_ILONLY)
3784 status = fixup_imports_ilonly( wm, NULL, entry );
3785 else
3786 status = fixup_imports( wm, NULL );
3788 if (status)
3790 ERR( "Importing dlls for %s failed, status %x\n",
3791 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3792 NtTerminateProcess( GetCurrentProcess(), status );
3794 imports_fixup_done = TRUE;
3796 else wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3798 RtlAcquirePebLock();
3799 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3800 RtlReleasePebLock();
3802 NtCurrentTeb()->FlsSlots = fls_alloc_data();
3804 if (!attach_done) /* first time around */
3806 attach_done = 1;
3807 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3809 ERR( "TLS init failed when loading %s, status %x\n",
3810 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3811 NtTerminateProcess( GetCurrentProcess(), status );
3813 wm->ldr.Flags |= LDR_PROCESS_ATTACHED; /* don't try to attach again */
3814 if (wm->ldr.ActivationContext)
3815 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
3817 for (i = 0; i < wm->nDeps; i++)
3819 if (!wm->deps[i]) continue;
3820 if ((status = process_attach( wm->deps[i], context )) != STATUS_SUCCESS)
3822 if (last_failed_modref)
3823 ERR( "%s failed to initialize, aborting\n",
3824 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3825 ERR( "Initializing dlls for %s failed, status %x\n",
3826 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3827 NtTerminateProcess( GetCurrentProcess(), status );
3830 unix_funcs->virtual_release_address_space();
3831 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_PROCESS_ATTACH );
3832 if (wm->ldr.Flags & LDR_WINE_INTERNAL) unix_funcs->init_builtin_dll( wm->ldr.DllBase );
3833 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
3834 process_breakpoint();
3836 else
3838 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3839 NtTerminateThread( GetCurrentThread(), status );
3840 thread_attach();
3841 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_ATTACH );
3844 RtlLeaveCriticalSection( &loader_section );
3845 signal_start_thread( context );
3849 /***********************************************************************
3850 * RtlImageDirectoryEntryToData (NTDLL.@)
3852 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3854 const IMAGE_NT_HEADERS *nt;
3855 DWORD addr;
3857 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
3858 module = (HMODULE)((ULONG_PTR)module & ~3);
3859 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3860 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3862 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3864 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3865 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3866 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3867 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3869 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3871 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3873 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3874 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3875 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3876 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3878 else return NULL;
3880 /* not mapped as image, need to find the section containing the virtual address */
3881 return RtlImageRvaToVa( nt, module, addr, NULL );
3885 /***********************************************************************
3886 * RtlImageRvaToSection (NTDLL.@)
3888 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3889 HMODULE module, DWORD rva )
3891 int i;
3892 const IMAGE_SECTION_HEADER *sec;
3894 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3895 nt->FileHeader.SizeOfOptionalHeader);
3896 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3898 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3899 return (PIMAGE_SECTION_HEADER)sec;
3901 return NULL;
3905 /***********************************************************************
3906 * RtlImageRvaToVa (NTDLL.@)
3908 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3909 DWORD rva, IMAGE_SECTION_HEADER **section )
3911 IMAGE_SECTION_HEADER *sec;
3913 if (section && *section) /* try this section first */
3915 sec = *section;
3916 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3917 goto found;
3919 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3920 found:
3921 if (section) *section = sec;
3922 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3926 /***********************************************************************
3927 * RtlPcToFileHeader (NTDLL.@)
3929 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3931 LDR_DATA_TABLE_ENTRY *module;
3932 PVOID ret = NULL;
3934 RtlEnterCriticalSection( &loader_section );
3935 if (!LdrFindEntryForAddress( pc, &module )) ret = module->DllBase;
3936 RtlLeaveCriticalSection( &loader_section );
3937 *address = ret;
3938 return ret;
3942 /****************************************************************************
3943 * LdrGetDllDirectory (NTDLL.@)
3945 NTSTATUS WINAPI LdrGetDllDirectory( UNICODE_STRING *dir )
3947 NTSTATUS status = STATUS_SUCCESS;
3949 RtlEnterCriticalSection( &dlldir_section );
3950 dir->Length = dll_directory.Length + sizeof(WCHAR);
3951 if (dir->MaximumLength >= dir->Length) RtlCopyUnicodeString( dir, &dll_directory );
3952 else
3954 status = STATUS_BUFFER_TOO_SMALL;
3955 if (dir->MaximumLength) dir->Buffer[0] = 0;
3957 RtlLeaveCriticalSection( &dlldir_section );
3958 return status;
3962 /****************************************************************************
3963 * LdrSetDllDirectory (NTDLL.@)
3965 NTSTATUS WINAPI LdrSetDllDirectory( const UNICODE_STRING *dir )
3967 NTSTATUS status = STATUS_SUCCESS;
3968 UNICODE_STRING new;
3970 if (!dir->Buffer) RtlInitUnicodeString( &new, NULL );
3971 else if ((status = RtlDuplicateUnicodeString( 1, dir, &new ))) return status;
3973 RtlEnterCriticalSection( &dlldir_section );
3974 RtlFreeUnicodeString( &dll_directory );
3975 dll_directory = new;
3976 RtlLeaveCriticalSection( &dlldir_section );
3977 return status;
3981 /****************************************************************************
3982 * LdrAddDllDirectory (NTDLL.@)
3984 NTSTATUS WINAPI LdrAddDllDirectory( const UNICODE_STRING *dir, void **cookie )
3986 FILE_BASIC_INFORMATION info;
3987 UNICODE_STRING nt_name;
3988 NTSTATUS status;
3989 OBJECT_ATTRIBUTES attr;
3990 DWORD len;
3991 struct dll_dir_entry *ptr;
3992 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir->Buffer );
3994 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
3995 return STATUS_INVALID_PARAMETER;
3997 status = RtlDosPathNameToNtPathName_U_WithStatus( dir->Buffer, &nt_name, NULL, NULL );
3998 if (status) return status;
3999 len = nt_name.Length / sizeof(WCHAR);
4000 if (!(ptr = RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] ))))
4001 return STATUS_NO_MEMORY;
4002 memcpy( ptr->dir, nt_name.Buffer, len * sizeof(WCHAR) );
4004 attr.Length = sizeof(attr);
4005 attr.RootDirectory = 0;
4006 attr.Attributes = OBJ_CASE_INSENSITIVE;
4007 attr.ObjectName = &nt_name;
4008 attr.SecurityDescriptor = NULL;
4009 attr.SecurityQualityOfService = NULL;
4010 status = NtQueryAttributesFile( &attr, &info );
4011 RtlFreeUnicodeString( &nt_name );
4013 if (!status)
4015 TRACE( "%s\n", debugstr_w( ptr->dir ));
4016 RtlEnterCriticalSection( &dlldir_section );
4017 list_add_head( &dll_dir_list, &ptr->entry );
4018 RtlLeaveCriticalSection( &dlldir_section );
4019 *cookie = ptr;
4021 else RtlFreeHeap( GetProcessHeap(), 0, ptr );
4022 return status;
4026 /****************************************************************************
4027 * LdrRemoveDllDirectory (NTDLL.@)
4029 NTSTATUS WINAPI LdrRemoveDllDirectory( void *cookie )
4031 struct dll_dir_entry *ptr = cookie;
4033 TRACE( "%s\n", debugstr_w( ptr->dir ));
4035 RtlEnterCriticalSection( &dlldir_section );
4036 list_remove( &ptr->entry );
4037 RtlFreeHeap( GetProcessHeap(), 0, ptr );
4038 RtlLeaveCriticalSection( &dlldir_section );
4039 return STATUS_SUCCESS;
4043 /*************************************************************************
4044 * LdrSetDefaultDllDirectories (NTDLL.@)
4046 NTSTATUS WINAPI LdrSetDefaultDllDirectories( ULONG flags )
4048 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
4049 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
4050 LOAD_LIBRARY_SEARCH_USER_DIRS |
4051 LOAD_LIBRARY_SEARCH_SYSTEM32 |
4052 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
4054 if (!flags || (flags & ~load_library_search_flags)) return STATUS_INVALID_PARAMETER;
4055 default_search_flags = flags;
4056 return STATUS_SUCCESS;
4060 /******************************************************************
4061 * LdrGetDllPath (NTDLL.@)
4063 NTSTATUS WINAPI LdrGetDllPath( PCWSTR module, ULONG flags, PWSTR *path, PWSTR *unknown )
4065 NTSTATUS status;
4066 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
4067 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
4068 LOAD_LIBRARY_SEARCH_USER_DIRS |
4069 LOAD_LIBRARY_SEARCH_SYSTEM32 |
4070 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
4072 if (flags & LOAD_WITH_ALTERED_SEARCH_PATH)
4074 if (flags & load_library_search_flags) return STATUS_INVALID_PARAMETER;
4075 if (default_search_flags) flags |= default_search_flags | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
4077 else if (!(flags & load_library_search_flags)) flags |= default_search_flags;
4079 RtlEnterCriticalSection( &dlldir_section );
4081 if (flags & load_library_search_flags)
4083 status = get_dll_load_path_search_flags( module, flags, path );
4085 else
4087 const WCHAR *dlldir = dll_directory.Length ? dll_directory.Buffer : NULL;
4088 if (!(flags & LOAD_WITH_ALTERED_SEARCH_PATH))
4089 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4090 status = get_dll_load_path( module, dlldir, dll_safe_mode, path );
4093 RtlLeaveCriticalSection( &dlldir_section );
4094 *unknown = NULL;
4095 return status;
4099 /*************************************************************************
4100 * RtlSetSearchPathMode (NTDLL.@)
4102 NTSTATUS WINAPI RtlSetSearchPathMode( ULONG flags )
4104 int val;
4106 switch (flags)
4108 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE:
4109 val = 1;
4110 break;
4111 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE:
4112 val = 0;
4113 break;
4114 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT:
4115 InterlockedExchange( (int *)&path_safe_mode, 2 );
4116 return STATUS_SUCCESS;
4117 default:
4118 return STATUS_INVALID_PARAMETER;
4121 for (;;)
4123 int prev = path_safe_mode;
4124 if (prev == 2) break; /* permanently set */
4125 if (InterlockedCompareExchange( (int *)&path_safe_mode, val, prev ) == prev) return STATUS_SUCCESS;
4127 return STATUS_ACCESS_DENIED;
4131 /******************************************************************
4132 * RtlGetExePath (NTDLL.@)
4134 NTSTATUS WINAPI RtlGetExePath( PCWSTR name, PWSTR *path )
4136 const WCHAR *dlldir = L".";
4137 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4139 /* same check as NeedCurrentDirectoryForExePathW */
4140 if (!wcschr( name, '\\' ))
4142 UNICODE_STRING name, value = { 0 };
4144 RtlInitUnicodeString( &name, L"NoDefaultCurrentDirectoryInExePath" );
4145 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) != STATUS_VARIABLE_NOT_FOUND)
4146 dlldir = L"";
4148 return get_dll_load_path( module, dlldir, FALSE, path );
4152 /******************************************************************
4153 * RtlGetSearchPath (NTDLL.@)
4155 NTSTATUS WINAPI RtlGetSearchPath( PWSTR *path )
4157 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4158 return get_dll_load_path( module, NULL, path_safe_mode, path );
4162 /******************************************************************
4163 * RtlReleasePath (NTDLL.@)
4165 void WINAPI RtlReleasePath( PWSTR path )
4167 RtlFreeHeap( GetProcessHeap(), 0, path );
4171 /******************************************************************
4172 * DllMain (NTDLL.@)
4174 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
4176 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
4177 return TRUE;
4181 /***********************************************************************
4182 * __wine_set_unix_funcs
4184 NTSTATUS CDECL __wine_set_unix_funcs( int version, const struct unix_funcs *funcs )
4186 if (version != NTDLL_UNIXLIB_VERSION) return STATUS_REVISION_MISMATCH;
4187 unix_funcs = funcs;
4188 return STATUS_SUCCESS;