wined3d: Use glFinish() for synchronisation when cleaning up a destroyed context...
[wine.git] / dlls / ntdll / loader.c
blob3f43062f9f882d54dd884cbfcad5e2d51dcacd5e
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>
25 #include "ntstatus.h"
26 #define WIN32_NO_STATUS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29 #include "windef.h"
30 #include "winnt.h"
31 #include "winioctl.h"
32 #include "winternl.h"
33 #include "delayloadhandler.h"
35 #include "wine/exception.h"
36 #include "wine/debug.h"
37 #include "wine/list.h"
38 #include "wine/server.h"
39 #include "ntdll_misc.h"
40 #include "ddk/wdm.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(module);
43 WINE_DECLARE_DEBUG_CHANNEL(relay);
44 WINE_DECLARE_DEBUG_CHANNEL(snoop);
45 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
46 WINE_DECLARE_DEBUG_CHANNEL(imports);
48 #ifdef _WIN64
49 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
50 #endif
51 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
52 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
59 typedef void (CALLBACK *LDRENUMPROC)(LDR_DATA_TABLE_ENTRY *, void *, BOOLEAN *);
61 void (FASTCALL *pBaseThreadInitThunk)(DWORD,LPTHREAD_START_ROUTINE,void *) = NULL;
63 const struct unix_funcs *unix_funcs = NULL;
65 /* windows directory */
66 const WCHAR windows_dir[] = L"C:\\windows";
67 /* system directory with trailing backslash */
68 const WCHAR system_dir[] = L"C:\\windows\\system32\\";
69 const WCHAR syswow64_dir[] = L"C:\\windows\\syswow64\\";
71 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
72 BOOL is_wow64 = FALSE;
74 /* system search path */
75 static const WCHAR system_path[] = L"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
77 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
78 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
79 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
80 static ULONG path_safe_mode; /* path mode set by RtlSetSearchPathMode */
81 static ULONG dll_safe_mode = 1; /* dll search mode */
82 static UNICODE_STRING dll_directory; /* extra path for LdrSetDllDirectory */
83 static DWORD default_search_flags; /* default flags set by LdrSetDefaultDllDirectories */
85 struct dll_dir_entry
87 struct list entry;
88 WCHAR dir[1];
91 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from LdrAddDllDirectory */
93 struct ldr_notification
95 struct list entry;
96 PLDR_DLL_NOTIFICATION_FUNCTION callback;
97 void *context;
100 static struct list ldr_notifications = LIST_INIT( ldr_notifications );
102 static const char * const reason_names[] =
104 "PROCESS_DETACH",
105 "PROCESS_ATTACH",
106 "THREAD_ATTACH",
107 "THREAD_DETACH",
108 NULL, NULL, NULL, NULL,
109 "WINE_PREATTACH"
112 struct file_id
114 BYTE ObjectId[16];
117 /* internal representation of loaded modules */
118 typedef struct _wine_modref
120 LDR_DATA_TABLE_ENTRY ldr;
121 struct file_id id;
122 void *unix_entry;
123 int alloc_deps;
124 int nDeps;
125 struct _wine_modref **deps;
126 } WINE_MODREF;
128 static UINT tls_module_count; /* number of modules with TLS directory */
129 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
130 LIST_ENTRY tls_links = { &tls_links, &tls_links };
132 static RTL_CRITICAL_SECTION loader_section;
133 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
135 0, 0, &loader_section,
136 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
137 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
139 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
141 static CRITICAL_SECTION dlldir_section;
142 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug =
144 0, 0, &dlldir_section,
145 { &dlldir_critsect_debug.ProcessLocksList, &dlldir_critsect_debug.ProcessLocksList },
146 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
148 static CRITICAL_SECTION dlldir_section = { &dlldir_critsect_debug, -1, 0, 0, 0, 0 };
150 static RTL_CRITICAL_SECTION peb_lock;
151 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug =
153 0, 0, &peb_lock,
154 { &peb_critsect_debug.ProcessLocksList, &peb_critsect_debug.ProcessLocksList },
155 0, 0, { (DWORD_PTR)(__FILE__ ": peb_lock") }
157 static RTL_CRITICAL_SECTION peb_lock = { &peb_critsect_debug, -1, 0, 0, 0, 0 };
159 static PEB_LDR_DATA ldr = { sizeof(ldr), TRUE };
160 static RTL_BITMAP tls_bitmap;
161 static RTL_BITMAP tls_expansion_bitmap;
163 static WINE_MODREF *cached_modref;
164 static WINE_MODREF *current_modref;
165 static WINE_MODREF *last_failed_modref;
167 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
168 DWORD flags, WINE_MODREF** pwm );
169 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
170 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
171 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
172 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
173 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
175 /* convert PE image VirtualAddress to Real Address */
176 static inline void *get_rva( HMODULE module, DWORD va )
178 return (void *)((char *)module + va);
181 /* check whether the file name contains a path */
182 static inline BOOL contains_path( LPCWSTR name )
184 return ((*name && (name[1] == ':')) || wcschr(name, '/') || wcschr(name, '\\'));
187 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
189 typedef struct _RTL_UNLOAD_EVENT_TRACE
191 void *BaseAddress;
192 SIZE_T SizeOfImage;
193 ULONG Sequence;
194 ULONG TimeDateStamp;
195 ULONG CheckSum;
196 WCHAR ImageName[32];
197 } RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
199 static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
200 static RTL_UNLOAD_EVENT_TRACE *unload_trace_ptr;
201 static unsigned int unload_trace_seq;
203 static void module_push_unload_trace( const LDR_DATA_TABLE_ENTRY *ldr )
205 RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
206 unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
208 ptr->BaseAddress = ldr->DllBase;
209 ptr->SizeOfImage = ldr->SizeOfImage;
210 ptr->Sequence = unload_trace_seq;
211 ptr->TimeDateStamp = ldr->TimeDateStamp;
212 ptr->CheckSum = ldr->CheckSum;
213 memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
214 ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
216 unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
217 unload_trace_ptr = unload_traces;
220 /*********************************************************************
221 * RtlGetUnloadEventTrace [NTDLL.@]
223 RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
225 return unload_traces;
228 /*********************************************************************
229 * RtlGetUnloadEventTraceEx [NTDLL.@]
231 void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
233 static unsigned int element_size = sizeof(*unload_traces);
234 static unsigned int element_count = ARRAY_SIZE(unload_traces);
236 *size = &element_size;
237 *count = &element_count;
238 *trace = &unload_trace_ptr;
241 /*************************************************************************
242 * call_dll_entry_point
244 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
245 * their entry point, so we need a small asm wrapper. Testing indicates
246 * that only modifying esi leads to a crash, so use this one to backup
247 * ebp while running the dll entry proc.
249 #ifdef __i386__
250 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
251 __ASM_GLOBAL_FUNC(call_dll_entry_point,
252 "pushl %ebp\n\t"
253 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
254 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
255 "movl %esp,%ebp\n\t"
256 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
257 "pushl %ebx\n\t"
258 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
259 "pushl %esi\n\t"
260 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
261 "pushl %edi\n\t"
262 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
263 "movl %ebp,%esi\n\t"
264 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
265 "pushl 20(%ebp)\n\t"
266 "pushl 16(%ebp)\n\t"
267 "pushl 12(%ebp)\n\t"
268 "movl 8(%ebp),%eax\n\t"
269 "call *%eax\n\t"
270 "movl %esi,%ebp\n\t"
271 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
272 "leal -12(%ebp),%esp\n\t"
273 "popl %edi\n\t"
274 __ASM_CFI(".cfi_same_value %edi\n\t")
275 "popl %esi\n\t"
276 __ASM_CFI(".cfi_same_value %esi\n\t")
277 "popl %ebx\n\t"
278 __ASM_CFI(".cfi_same_value %ebx\n\t")
279 "popl %ebp\n\t"
280 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
281 __ASM_CFI(".cfi_same_value %ebp\n\t")
282 "ret" )
283 #else /* __i386__ */
284 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
285 UINT reason, void *reserved )
287 return proc( module, reason, reserved );
289 #endif /* __i386__ */
292 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
293 /*************************************************************************
294 * stub_entry_point
296 * Entry point for stub functions.
298 static void WINAPI stub_entry_point( const char *dll, const char *name, void *ret_addr )
300 EXCEPTION_RECORD rec;
302 rec.ExceptionCode = EXCEPTION_WINE_STUB;
303 rec.ExceptionFlags = EH_NONCONTINUABLE;
304 rec.ExceptionRecord = NULL;
305 rec.ExceptionAddress = ret_addr;
306 rec.NumberParameters = 2;
307 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
308 rec.ExceptionInformation[1] = (ULONG_PTR)name;
309 for (;;) RtlRaiseException( &rec );
313 #include "pshpack1.h"
314 #ifdef __i386__
315 struct stub
317 BYTE pushl1; /* pushl $name */
318 const char *name;
319 BYTE pushl2; /* pushl $dll */
320 const char *dll;
321 BYTE call; /* call stub_entry_point */
322 DWORD entry;
324 #elif defined(__arm__)
325 struct stub
327 DWORD ldr_r0; /* ldr r0, $dll */
328 DWORD ldr_r1; /* ldr r1, $name */
329 DWORD mov_r2_lr; /* mov r2, lr */
330 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
331 const char *dll;
332 const char *name;
333 const void* entry;
335 #elif defined(__aarch64__)
336 struct stub
338 DWORD ldr_x0; /* ldr x0, $dll */
339 DWORD ldr_x1; /* ldr x1, $name */
340 DWORD mov_x2_lr; /* mov x2, lr */
341 DWORD ldr_x16; /* ldr x16, $entry */
342 DWORD br_x16; /* br x16 */
343 const char *dll;
344 const char *name;
345 const void *entry;
347 #else
348 struct stub
350 BYTE movq_rdi[2]; /* movq $dll,%rdi */
351 const char *dll;
352 BYTE movq_rsi[2]; /* movq $name,%rsi */
353 const char *name;
354 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
355 BYTE movq_rax[2]; /* movq $entry, %rax */
356 const void* entry;
357 BYTE jmpq_rax[2]; /* jmp %rax */
359 #endif
360 #include "poppack.h"
362 /*************************************************************************
363 * allocate_stub
365 * Allocate a stub entry point.
367 static ULONG_PTR allocate_stub( const char *dll, const char *name )
369 #define MAX_SIZE 65536
370 static struct stub *stubs;
371 static unsigned int nb_stubs;
372 struct stub *stub;
374 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
376 if (!stubs)
378 SIZE_T size = MAX_SIZE;
379 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
380 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
381 return 0xdeadbeef;
383 stub = &stubs[nb_stubs++];
384 #ifdef __i386__
385 stub->pushl1 = 0x68; /* pushl $name */
386 stub->name = name;
387 stub->pushl2 = 0x68; /* pushl $dll */
388 stub->dll = dll;
389 stub->call = 0xe8; /* call stub_entry_point */
390 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
391 #elif defined(__arm__)
392 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
393 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
394 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
395 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
396 stub->dll = dll;
397 stub->name = name;
398 stub->entry = stub_entry_point;
399 #elif defined(__aarch64__)
400 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
401 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
402 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
403 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
404 stub->br_x16 = 0xd61f0200; /* br x16 */
405 stub->dll = dll;
406 stub->name = name;
407 stub->entry = stub_entry_point;
408 #else
409 stub->movq_rdi[0] = 0x48; /* movq $dll,%rcx */
410 stub->movq_rdi[1] = 0xb9;
411 stub->dll = dll;
412 stub->movq_rsi[0] = 0x48; /* movq $name,%rdx */
413 stub->movq_rsi[1] = 0xba;
414 stub->name = name;
415 stub->movq_rsp_rdx[0] = 0x4c; /* movq (%rsp),%r8 */
416 stub->movq_rsp_rdx[1] = 0x8b;
417 stub->movq_rsp_rdx[2] = 0x04;
418 stub->movq_rsp_rdx[3] = 0x24;
419 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
420 stub->movq_rax[1] = 0xb8;
421 stub->entry = stub_entry_point;
422 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
423 stub->jmpq_rax[1] = 0xe0;
424 #endif
425 return (ULONG_PTR)stub;
428 #else /* __i386__ */
429 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
430 #endif /* __i386__ */
432 /* call ldr notifications */
433 static void call_ldr_notifications( ULONG reason, LDR_DATA_TABLE_ENTRY *module )
435 struct ldr_notification *notify, *notify_next;
436 LDR_DLL_NOTIFICATION_DATA data;
438 data.Loaded.Flags = 0;
439 data.Loaded.FullDllName = &module->FullDllName;
440 data.Loaded.BaseDllName = &module->BaseDllName;
441 data.Loaded.DllBase = module->DllBase;
442 data.Loaded.SizeOfImage = module->SizeOfImage;
444 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
446 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
447 notify->callback, reason, &data, notify->context );
449 notify->callback(reason, &data, notify->context);
451 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
452 notify->callback, reason, &data, notify->context );
456 /*************************************************************************
457 * get_modref
459 * Looks for the referenced HMODULE in the current process
460 * The loader_section must be locked while calling this function.
462 static WINE_MODREF *get_modref( HMODULE hmod )
464 PLIST_ENTRY mark, entry;
465 PLDR_DATA_TABLE_ENTRY mod;
467 if (cached_modref && cached_modref->ldr.DllBase == hmod) return cached_modref;
469 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
470 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
472 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
473 if (mod->DllBase == hmod)
474 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
476 return NULL;
480 /**********************************************************************
481 * find_basename_module
483 * Find a module from its base name.
484 * The loader_section must be locked while calling this function
486 static WINE_MODREF *find_basename_module( LPCWSTR name )
488 PLIST_ENTRY mark, entry;
489 UNICODE_STRING name_str;
491 RtlInitUnicodeString( &name_str, name );
493 if (cached_modref && RtlEqualUnicodeString( &name_str, &cached_modref->ldr.BaseDllName, TRUE ))
494 return cached_modref;
496 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
497 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
499 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
500 if (RtlEqualUnicodeString( &name_str, &mod->BaseDllName, TRUE ))
502 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
503 return cached_modref;
506 return NULL;
510 /**********************************************************************
511 * find_fullname_module
513 * Find a module from its full path name.
514 * The loader_section must be locked while calling this function
516 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
518 PLIST_ENTRY mark, entry;
519 UNICODE_STRING name = *nt_name;
521 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
522 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
523 name.Buffer += 4;
525 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
526 return cached_modref;
528 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
529 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
531 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
532 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
534 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
535 return cached_modref;
538 return NULL;
542 /**********************************************************************
543 * find_fileid_module
545 * Find a module from its file id.
546 * The loader_section must be locked while calling this function
548 static WINE_MODREF *find_fileid_module( const struct file_id *id )
550 LIST_ENTRY *mark, *entry;
552 if (cached_modref && !memcmp( &cached_modref->id, id, sizeof(*id) )) return cached_modref;
554 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
555 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
557 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
558 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
560 if (!memcmp( &wm->id, id, sizeof(*id) ))
562 cached_modref = wm;
563 return wm;
566 return NULL;
570 /*************************************************************************
571 * grow_module_deps
573 static WINE_MODREF **grow_module_deps( WINE_MODREF *wm, int count )
575 WINE_MODREF **deps;
577 if (wm->alloc_deps)
578 deps = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, wm->deps,
579 (wm->alloc_deps + count) * sizeof(*deps) );
580 else
581 deps = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, count * sizeof(*deps) );
583 if (deps)
585 wm->deps = deps;
586 wm->alloc_deps += count;
588 return deps;
591 /*************************************************************************
592 * find_forwarded_export
594 * Find the final function pointer for a forwarded function.
595 * The loader_section must be locked while calling this function.
597 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
599 const IMAGE_EXPORT_DIRECTORY *exports;
600 DWORD exp_size;
601 WINE_MODREF *wm;
602 WCHAR buffer[32], *mod_name = buffer;
603 const char *end = strrchr(forward, '.');
604 FARPROC proc = NULL;
606 if (!end) return NULL;
607 if ((end - forward) * sizeof(WCHAR) > sizeof(buffer) - sizeof(L".dll"))
609 if (!(mod_name = RtlAllocateHeap( GetProcessHeap(), 0,
610 (end - forward + sizeof(L".dll")) * sizeof(WCHAR) )))
611 return NULL;
613 ascii_to_unicode( mod_name, forward, end - forward );
614 mod_name[end - forward] = 0;
615 if (!wcschr( mod_name, '.' ))
616 memcpy( mod_name + (end - forward), L".dll", sizeof(L".dll") );
618 if (!(wm = find_basename_module( mod_name )))
620 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
621 if (load_dll( load_path, mod_name, L".dll", 0, &wm ) == STATUS_SUCCESS &&
622 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
624 if (!imports_fixup_done && current_modref)
626 WINE_MODREF **deps = grow_module_deps( current_modref, 1 );
627 if (deps) deps[current_modref->nDeps++] = wm;
629 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
631 LdrUnloadDll( wm->ldr.DllBase );
632 wm = NULL;
636 if (!wm)
638 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
639 ERR( "module not found for forward '%s' used by %s\n",
640 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
641 return NULL;
644 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
645 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
647 const char *name = end + 1;
648 if (*name == '#') /* ordinal */
649 proc = find_ordinal_export( wm->ldr.DllBase, exports, exp_size, atoi(name+1), load_path );
650 else
651 proc = find_named_export( wm->ldr.DllBase, exports, exp_size, name, -1, load_path );
654 if (!proc)
656 ERR("function not found for forward '%s' used by %s."
657 " If you are using builtin %s, try using the native one instead.\n",
658 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
659 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
661 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
662 return proc;
666 /*************************************************************************
667 * find_ordinal_export
669 * Find an exported function by ordinal.
670 * The exports base must have been subtracted from the ordinal already.
671 * The loader_section must be locked while calling this function.
673 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
674 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
676 FARPROC proc;
677 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
679 if (ordinal >= exports->NumberOfFunctions)
681 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
682 return NULL;
684 if (!functions[ordinal]) return NULL;
686 proc = get_rva( module, functions[ordinal] );
688 /* if the address falls into the export dir, it's a forward */
689 if (((const char *)proc >= (const char *)exports) &&
690 ((const char *)proc < (const char *)exports + exp_size))
691 return find_forwarded_export( module, (const char *)proc, load_path );
693 if (TRACE_ON(snoop))
695 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
696 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
698 if (TRACE_ON(relay))
700 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
701 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
703 return proc;
707 /*************************************************************************
708 * find_named_export
710 * Find an exported function by name.
711 * The loader_section must be locked while calling this function.
713 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
714 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
716 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
717 const DWORD *names = get_rva( module, exports->AddressOfNames );
718 int min = 0, max = exports->NumberOfNames - 1;
720 /* first check the hint */
721 if (hint >= 0 && hint <= max)
723 char *ename = get_rva( module, names[hint] );
724 if (!strcmp( ename, name ))
725 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
728 /* then do a binary search */
729 while (min <= max)
731 int res, pos = (min + max) / 2;
732 char *ename = get_rva( module, names[pos] );
733 if (!(res = strcmp( ename, name )))
734 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
735 if (res > 0) max = pos - 1;
736 else min = pos + 1;
738 return NULL;
743 /*************************************************************************
744 * import_dll
746 * Import the dll specified by the given import descriptor.
747 * The loader_section must be locked while calling this function.
749 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
751 NTSTATUS status;
752 WINE_MODREF *wmImp;
753 HMODULE imp_mod;
754 const IMAGE_EXPORT_DIRECTORY *exports;
755 DWORD exp_size;
756 const IMAGE_THUNK_DATA *import_list;
757 IMAGE_THUNK_DATA *thunk_list;
758 WCHAR buffer[32];
759 const char *name = get_rva( module, descr->Name );
760 DWORD len = strlen(name);
761 PVOID protect_base;
762 SIZE_T protect_size = 0;
763 DWORD protect_old;
765 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
766 if (descr->u.OriginalFirstThunk)
767 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
768 else
769 import_list = thunk_list;
771 if (!import_list->u1.Ordinal)
773 WARN( "Skipping unused import %s\n", name );
774 *pwm = NULL;
775 return TRUE;
778 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
780 if (len * sizeof(WCHAR) < sizeof(buffer))
782 ascii_to_unicode( buffer, name, len );
783 buffer[len] = 0;
784 status = load_dll( load_path, buffer, L".dll", 0, &wmImp );
786 else /* need to allocate a larger buffer */
788 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
789 if (!ptr) return FALSE;
790 ascii_to_unicode( ptr, name, len );
791 ptr[len] = 0;
792 status = load_dll( load_path, ptr, L".dll", 0, &wmImp );
793 RtlFreeHeap( GetProcessHeap(), 0, ptr );
796 if (status)
798 if (status == STATUS_DLL_NOT_FOUND)
799 ERR("Library %s (which is needed by %s) not found\n",
800 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
801 else
802 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
803 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
804 return FALSE;
807 /* unprotect the import address table since it can be located in
808 * readonly section */
809 while (import_list[protect_size].u1.Ordinal) protect_size++;
810 protect_base = thunk_list;
811 protect_size *= sizeof(*thunk_list);
812 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
813 &protect_size, PAGE_READWRITE, &protect_old );
815 imp_mod = wmImp->ldr.DllBase;
816 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
818 if (!exports)
820 /* set all imported function to deadbeef */
821 while (import_list->u1.Ordinal)
823 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
825 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
826 WARN("No implementation for %s.%d", name, ordinal );
827 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
829 else
831 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
832 WARN("No implementation for %s.%s", name, pe_name->Name );
833 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
835 WARN(" imported from %s, allocating stub %p\n",
836 debugstr_w(current_modref->ldr.FullDllName.Buffer),
837 (void *)thunk_list->u1.Function );
838 import_list++;
839 thunk_list++;
841 goto done;
844 while (import_list->u1.Ordinal)
846 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
848 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
850 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
851 ordinal - exports->Base, load_path );
852 if (!thunk_list->u1.Function)
854 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
855 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
856 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
857 (void *)thunk_list->u1.Function );
859 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
861 else /* import by name */
863 IMAGE_IMPORT_BY_NAME *pe_name;
864 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
865 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
866 (const char*)pe_name->Name,
867 pe_name->Hint, load_path );
868 if (!thunk_list->u1.Function)
870 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
871 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
872 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
873 (void *)thunk_list->u1.Function );
875 TRACE_(imports)("--- %s %s.%d = %p\n",
876 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
878 import_list++;
879 thunk_list++;
882 done:
883 /* restore old protection of the import address table */
884 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
885 *pwm = wmImp;
886 return TRUE;
890 /***********************************************************************
891 * create_module_activation_context
893 static NTSTATUS create_module_activation_context( LDR_DATA_TABLE_ENTRY *module )
895 NTSTATUS status;
896 LDR_RESOURCE_INFO info;
897 const IMAGE_RESOURCE_DATA_ENTRY *entry;
899 info.Type = RT_MANIFEST;
900 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
901 info.Language = 0;
902 if (!(status = LdrFindResource_U( module->DllBase, &info, 3, &entry )))
904 ACTCTXW ctx;
905 ctx.cbSize = sizeof(ctx);
906 ctx.lpSource = NULL;
907 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
908 ctx.hModule = module->DllBase;
909 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
910 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
912 return status;
916 /*************************************************************************
917 * is_dll_native_subsystem
919 * Check if dll is a proper native driver.
920 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
921 * while being perfectly normal DLLs. This heuristic should catch such breakages.
923 static BOOL is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
925 const IMAGE_IMPORT_DESCRIPTOR *imports;
926 DWORD i, size;
927 WCHAR buffer[16];
929 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
930 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
931 if (mod->Flags & LDR_WINE_INTERNAL) return TRUE;
933 if ((imports = RtlImageDirectoryEntryToData( mod->DllBase, TRUE,
934 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
936 for (i = 0; imports[i].Name; i++)
938 const char *name = get_rva( mod->DllBase, imports[i].Name );
939 DWORD len = strlen(name);
940 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
941 ascii_to_unicode( buffer, name, len + 1 );
942 if (!wcsicmp( buffer, L"ntdll.dll" ) || !wcsicmp( buffer, L"kernel32.dll" ))
944 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
945 return FALSE;
949 return TRUE;
952 /*************************************************************************
953 * alloc_tls_slot
955 * Allocate a TLS slot for a newly-loaded module.
956 * The loader_section must be locked while calling this function.
958 static SHORT alloc_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
960 const IMAGE_TLS_DIRECTORY *dir;
961 ULONG i, size;
962 void *new_ptr;
963 LIST_ENTRY *entry;
965 if (!(dir = RtlImageDirectoryEntryToData( mod->DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
966 return -1;
968 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
969 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
971 for (i = 0; i < tls_module_count; i++)
973 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
974 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
975 break;
978 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->DllBase,
979 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
980 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
982 if (i == tls_module_count)
984 UINT new_count = max( 32, tls_module_count * 2 );
986 if (!tls_dirs)
987 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
988 else
989 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
990 new_count * sizeof(*tls_dirs) );
991 if (!new_ptr) return -1;
993 /* resize the pointer block in all running threads */
994 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
996 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
997 void **old = teb->ThreadLocalStoragePointer;
998 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
1000 if (!new) return -1;
1001 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
1002 teb->ThreadLocalStoragePointer = new;
1003 #ifdef __x86_64__ /* macOS-specific hack */
1004 if (teb->Reserved5[0]) ((TEB *)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
1005 #endif
1006 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
1007 /* FIXME: can't free old block here, should be freed at thread exit */
1010 tls_dirs = new_ptr;
1011 tls_module_count = new_count;
1014 /* allocate the data block in all running threads */
1015 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1017 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1019 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
1020 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
1021 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
1023 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1024 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
1026 RtlFreeHeap( GetProcessHeap(), 0,
1027 InterlockedExchangePointer( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
1030 *(DWORD *)dir->AddressOfIndex = i;
1031 tls_dirs[i] = *dir;
1032 return i;
1036 /*************************************************************************
1037 * free_tls_slot
1039 * Free the module TLS slot on unload.
1040 * The loader_section must be locked while calling this function.
1042 static void free_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1044 ULONG i = (USHORT)mod->TlsIndex;
1046 if (mod->TlsIndex == -1) return;
1047 assert( i < tls_module_count );
1048 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
1052 /****************************************************************
1053 * fixup_imports_ilonly
1055 * Fixup imports for an IL-only module. All we do is import mscoree.
1056 * The loader_section must be locked while calling this function.
1058 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
1060 IMAGE_EXPORT_DIRECTORY *exports;
1061 DWORD exp_size;
1062 NTSTATUS status;
1063 void *proc = NULL;
1064 WINE_MODREF *prev, *imp;
1066 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1067 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1069 if (!grow_module_deps( wm, 1 )) return STATUS_NO_MEMORY;
1070 wm->nDeps = 1;
1072 prev = current_modref;
1073 current_modref = wm;
1074 if (!(status = load_dll( load_path, L"mscoree.dll", NULL, 0, &imp ))) wm->deps[0] = imp;
1075 current_modref = prev;
1076 if (status)
1078 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1079 debugstr_w(wm->ldr.BaseDllName.Buffer) );
1080 return status;
1083 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1085 if ((exports = RtlImageDirectoryEntryToData( imp->ldr.DllBase, TRUE,
1086 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1088 const char *name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
1089 proc = find_named_export( imp->ldr.DllBase, exports, exp_size, name, -1, load_path );
1091 if (!proc) return STATUS_PROCEDURE_NOT_FOUND;
1092 *entry = proc;
1093 return STATUS_SUCCESS;
1097 /****************************************************************
1098 * fixup_imports
1100 * Fixup all imports of a given module.
1101 * The loader_section must be locked while calling this function.
1103 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1105 int i, dep, nb_imports;
1106 const IMAGE_IMPORT_DESCRIPTOR *imports;
1107 WINE_MODREF *prev, *imp;
1108 DWORD size;
1109 NTSTATUS status;
1110 ULONG_PTR cookie;
1112 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1113 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1115 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
1117 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
1118 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1119 return STATUS_SUCCESS;
1121 nb_imports = 0;
1122 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1124 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1125 if (!grow_module_deps( wm, nb_imports )) return STATUS_NO_MEMORY;
1127 if (!create_module_activation_context( &wm->ldr ))
1128 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1130 /* load the imported modules. They are automatically
1131 * added to the modref list of the process.
1133 prev = current_modref;
1134 current_modref = wm;
1135 status = STATUS_SUCCESS;
1136 for (i = 0; i < nb_imports; i++)
1138 dep = wm->nDeps++;
1140 if (!import_dll( wm->ldr.DllBase, &imports[i], load_path, &imp ))
1142 imp = NULL;
1143 status = STATUS_DLL_NOT_FOUND;
1145 wm->deps[dep] = imp;
1147 current_modref = prev;
1148 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1149 return status;
1153 /*************************************************************************
1154 * alloc_module
1156 * Allocate a WINE_MODREF structure and add it to the process list
1157 * The loader_section must be locked while calling this function.
1159 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name, BOOL builtin )
1161 WCHAR *buffer;
1162 WINE_MODREF *wm;
1163 const WCHAR *p;
1164 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1166 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1168 wm->ldr.DllBase = hModule;
1169 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1170 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS | (builtin ? LDR_WINE_INTERNAL : 0);
1171 wm->ldr.TlsIndex = -1;
1172 wm->ldr.LoadCount = 1;
1174 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, nt_name->Length - 3 * sizeof(WCHAR) )))
1176 RtlFreeHeap( GetProcessHeap(), 0, wm );
1177 return NULL;
1179 memcpy( buffer, nt_name->Buffer + 4 /* \??\ prefix */, nt_name->Length - 4 * sizeof(WCHAR) );
1180 buffer[nt_name->Length/sizeof(WCHAR) - 4] = 0;
1181 if ((p = wcsrchr( buffer, '\\' ))) p++;
1182 else p = buffer;
1183 RtlInitUnicodeString( &wm->ldr.FullDllName, buffer );
1184 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1186 if (!is_dll_native_subsystem( &wm->ldr, nt, p ))
1188 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1189 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1190 if (nt->OptionalHeader.AddressOfEntryPoint)
1191 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1194 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1195 &wm->ldr.InLoadOrderLinks);
1196 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1197 &wm->ldr.InMemoryOrderLinks);
1198 /* wait until init is called for inserting into InInitializationOrderModuleList */
1200 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1202 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1203 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1204 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1206 return wm;
1210 /*************************************************************************
1211 * alloc_thread_tls
1213 * Allocate the per-thread structure for module TLS storage.
1215 static NTSTATUS alloc_thread_tls(void)
1217 void **pointers;
1218 UINT i, size;
1220 if (!tls_module_count) return STATUS_SUCCESS;
1222 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1223 tls_module_count * sizeof(*pointers) )))
1224 return STATUS_NO_MEMORY;
1226 for (i = 0; i < tls_module_count; i++)
1228 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1230 if (!dir) continue;
1231 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1232 if (!size && !dir->SizeOfZeroFill) continue;
1234 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1236 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1237 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1238 return STATUS_NO_MEMORY;
1240 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1241 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1243 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1244 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1246 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1247 #ifdef __x86_64__ /* macOS-specific hack */
1248 if (NtCurrentTeb()->Reserved5[0])
1249 ((TEB *)NtCurrentTeb()->Reserved5[0])->ThreadLocalStoragePointer = pointers;
1250 #endif
1251 return STATUS_SUCCESS;
1255 /*************************************************************************
1256 * call_tls_callbacks
1258 static void call_tls_callbacks( HMODULE module, UINT reason )
1260 const IMAGE_TLS_DIRECTORY *dir;
1261 const PIMAGE_TLS_CALLBACK *callback;
1262 ULONG dirsize;
1264 if (reason == DLL_WINE_PREATTACH) return;
1266 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1267 if (!dir || !dir->AddressOfCallBacks) return;
1269 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1271 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1272 *callback, module, reason_names[reason] );
1273 __TRY
1275 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1277 __EXCEPT_ALL
1279 TRACE_(relay)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1280 GetExceptionCode(), callback, module, reason_names[reason] );
1281 return;
1283 __ENDTRY
1284 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1285 *callback, module, reason_names[reason] );
1289 /*************************************************************************
1290 * MODULE_InitDLL
1292 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1294 WCHAR mod_name[32];
1295 NTSTATUS status = STATUS_SUCCESS;
1296 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1297 void *module = wm->ldr.DllBase;
1298 BOOL retv = FALSE;
1300 /* Skip calls for modules loaded with special load flags */
1302 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1303 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, reason );
1304 if (wm->ldr.Flags & LDR_WINE_INTERNAL && reason == DLL_PROCESS_ATTACH)
1305 unix_funcs->init_builtin_dll( wm->ldr.DllBase );
1306 if (!entry) return STATUS_SUCCESS;
1308 if (TRACE_ON(relay))
1310 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1311 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1312 mod_name[len / sizeof(WCHAR)] = 0;
1313 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1314 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1316 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1317 reason_names[reason], lpReserved );
1319 __TRY
1321 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1322 if (!retv)
1323 status = STATUS_DLL_INIT_FAILED;
1325 __EXCEPT_ALL
1327 status = GetExceptionCode();
1328 TRACE_(relay)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1329 status, entry, module, reason_names[reason], lpReserved );
1331 __ENDTRY
1333 /* The state of the module list may have changed due to the call
1334 to the dll. We cannot assume that this module has not been
1335 deleted. */
1336 if (TRACE_ON(relay))
1337 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1338 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1339 else
1340 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1342 return status;
1346 /*************************************************************************
1347 * process_attach
1349 * Send the process attach notification to all DLLs the given module
1350 * depends on (recursively). This is somewhat complicated due to the fact that
1352 * - we have to respect the module dependencies, i.e. modules implicitly
1353 * referenced by another module have to be initialized before the module
1354 * itself can be initialized
1356 * - the initialization routine of a DLL can itself call LoadLibrary,
1357 * thereby introducing a whole new set of dependencies (even involving
1358 * the 'old' modules) at any time during the whole process
1360 * (Note that this routine can be recursively entered not only directly
1361 * from itself, but also via LoadLibrary from one of the called initialization
1362 * routines.)
1364 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1365 * the process *detach* notifications to be sent in the correct order.
1366 * This must not only take into account module dependencies, but also
1367 * 'hidden' dependencies created by modules calling LoadLibrary in their
1368 * attach notification routine.
1370 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1371 * list after the attach notification has returned. This implies that the
1372 * detach notifications are called in the reverse of the sequence the attach
1373 * notifications *returned*.
1375 * The loader_section must be locked while calling this function.
1377 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1379 NTSTATUS status = STATUS_SUCCESS;
1380 ULONG_PTR cookie;
1381 int i;
1383 if (process_detaching) return status;
1385 /* prevent infinite recursion in case of cyclical dependencies */
1386 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1387 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1388 return status;
1390 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1392 /* Tag current MODREF to prevent recursive loop */
1393 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1394 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1395 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1397 /* Recursively attach all DLLs this one depends on */
1398 for ( i = 0; i < wm->nDeps; i++ )
1400 if (!wm->deps[i]) continue;
1401 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1404 if (!wm->ldr.InInitializationOrderLinks.Flink)
1405 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1406 &wm->ldr.InInitializationOrderLinks);
1408 /* Call DLL entry point */
1409 if (status == STATUS_SUCCESS)
1411 WINE_MODREF *prev = current_modref;
1412 current_modref = wm;
1414 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1415 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1416 if (status == STATUS_SUCCESS)
1418 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1420 else
1422 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1423 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1425 /* point to the name so LdrInitializeThunk can print it */
1426 last_failed_modref = wm;
1427 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1429 current_modref = prev;
1432 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1433 /* Remove recursion flag */
1434 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1436 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1437 return status;
1441 /**********************************************************************
1442 * attach_implicitly_loaded_dlls
1444 * Attach to the (builtin) dlls that have been implicitly loaded because
1445 * of a dependency at the Unix level, but not imported at the Win32 level.
1447 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1449 for (;;)
1451 PLIST_ENTRY mark, entry;
1453 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1454 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1456 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
1458 if (!(mod->Flags & LDR_IMAGE_IS_DLL)) continue;
1459 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1460 TRACE( "found implicitly loaded %s, attaching to it\n",
1461 debugstr_w(mod->BaseDllName.Buffer));
1462 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1463 break; /* restart the search from the start */
1465 if (entry == mark) break; /* nothing found */
1470 /*************************************************************************
1471 * process_detach
1473 * Send DLL process detach notifications. See the comment about calling
1474 * sequence at process_attach.
1476 static void process_detach(void)
1478 PLIST_ENTRY mark, entry;
1479 PLDR_DATA_TABLE_ENTRY mod;
1481 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1484 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1486 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1487 InInitializationOrderLinks);
1488 /* Check whether to detach this DLL */
1489 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1490 continue;
1491 if ( mod->LoadCount && !process_detaching )
1492 continue;
1494 /* Call detach notification */
1495 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1496 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1497 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1498 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1500 /* Restart at head of WINE_MODREF list, as entries might have
1501 been added and/or removed while performing the call ... */
1502 break;
1504 } while (entry != mark);
1507 /*************************************************************************
1508 * thread_attach
1510 * Send DLL thread attach notifications. These are sent in the
1511 * reverse sequence of process detach notification.
1512 * The loader_section must be locked while calling this function.
1514 static void thread_attach(void)
1516 PLIST_ENTRY mark, entry;
1517 PLDR_DATA_TABLE_ENTRY mod;
1519 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1520 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1522 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1523 InInitializationOrderLinks);
1524 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1525 continue;
1526 if ( mod->Flags & LDR_NO_DLL_CALLS )
1527 continue;
1529 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1533 /******************************************************************
1534 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1537 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1539 WINE_MODREF *wm;
1540 NTSTATUS ret = STATUS_SUCCESS;
1542 RtlEnterCriticalSection( &loader_section );
1544 wm = get_modref( hModule );
1545 if (!wm || wm->ldr.TlsIndex != -1)
1546 ret = STATUS_DLL_NOT_FOUND;
1547 else
1548 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1550 RtlLeaveCriticalSection( &loader_section );
1552 return ret;
1555 /******************************************************************
1556 * LdrFindEntryForAddress (NTDLL.@)
1558 * The loader_section must be locked while calling this function
1560 NTSTATUS WINAPI LdrFindEntryForAddress( const void *addr, PLDR_DATA_TABLE_ENTRY *pmod )
1562 PLIST_ENTRY mark, entry;
1563 PLDR_DATA_TABLE_ENTRY mod;
1565 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1566 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1568 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
1569 if (mod->DllBase <= addr &&
1570 (const char *)addr < (char*)mod->DllBase + mod->SizeOfImage)
1572 *pmod = mod;
1573 return STATUS_SUCCESS;
1576 return STATUS_NO_MORE_ENTRIES;
1579 /******************************************************************
1580 * LdrEnumerateLoadedModules (NTDLL.@)
1582 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1584 LIST_ENTRY *mark, *entry;
1585 LDR_DATA_TABLE_ENTRY *mod;
1586 BOOLEAN stop = FALSE;
1588 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1590 if (unknown || !callback)
1591 return STATUS_INVALID_PARAMETER;
1593 RtlEnterCriticalSection( &loader_section );
1595 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1596 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1598 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
1599 callback( mod, context, &stop );
1600 if (stop) break;
1603 RtlLeaveCriticalSection( &loader_section );
1604 return STATUS_SUCCESS;
1607 /******************************************************************
1608 * LdrRegisterDllNotification (NTDLL.@)
1610 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1611 void *context, void **cookie)
1613 struct ldr_notification *notify;
1615 TRACE( "(%x, %p, %p, %p)\n", flags, callback, context, cookie );
1617 if (!callback || !cookie)
1618 return STATUS_INVALID_PARAMETER;
1620 if (flags)
1621 FIXME( "ignoring flags %x\n", flags );
1623 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1624 if (!notify) return STATUS_NO_MEMORY;
1625 notify->callback = callback;
1626 notify->context = context;
1628 RtlEnterCriticalSection( &loader_section );
1629 list_add_tail( &ldr_notifications, &notify->entry );
1630 RtlLeaveCriticalSection( &loader_section );
1632 *cookie = notify;
1633 return STATUS_SUCCESS;
1636 /******************************************************************
1637 * LdrUnregisterDllNotification (NTDLL.@)
1639 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1641 struct ldr_notification *notify = cookie;
1643 TRACE( "(%p)\n", cookie );
1645 if (!notify) return STATUS_INVALID_PARAMETER;
1647 RtlEnterCriticalSection( &loader_section );
1648 list_remove( &notify->entry );
1649 RtlLeaveCriticalSection( &loader_section );
1651 RtlFreeHeap( GetProcessHeap(), 0, notify );
1652 return STATUS_SUCCESS;
1655 /******************************************************************
1656 * LdrLockLoaderLock (NTDLL.@)
1658 * Note: some flags are not implemented.
1659 * Flag 0x01 is used to raise exceptions on errors.
1661 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1663 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1665 if (result) *result = 0;
1666 if (magic) *magic = 0;
1667 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1668 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1669 if (!magic) return STATUS_INVALID_PARAMETER_3;
1671 if (flags & 0x2)
1673 if (!RtlTryEnterCriticalSection( &loader_section ))
1675 *result = 2;
1676 return STATUS_SUCCESS;
1678 *result = 1;
1680 else
1682 RtlEnterCriticalSection( &loader_section );
1683 if (result) *result = 1;
1685 *magic = GetCurrentThreadId();
1686 return STATUS_SUCCESS;
1690 /******************************************************************
1691 * LdrUnlockLoaderUnlock (NTDLL.@)
1693 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1695 if (magic)
1697 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1698 RtlLeaveCriticalSection( &loader_section );
1700 return STATUS_SUCCESS;
1704 /******************************************************************
1705 * LdrGetProcedureAddress (NTDLL.@)
1707 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1708 ULONG ord, PVOID *address)
1710 IMAGE_EXPORT_DIRECTORY *exports;
1711 DWORD exp_size;
1712 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1714 RtlEnterCriticalSection( &loader_section );
1716 /* check if the module itself is invalid to return the proper error */
1717 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1718 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1719 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1721 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1722 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1723 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1724 if (proc)
1726 *address = proc;
1727 ret = STATUS_SUCCESS;
1731 RtlLeaveCriticalSection( &loader_section );
1732 return ret;
1736 /***********************************************************************
1737 * set_security_cookie
1739 * Create a random security cookie for buffer overflow protection. Make
1740 * sure it does not accidentally match the default cookie value.
1742 static void set_security_cookie( void *module, SIZE_T len )
1744 static ULONG seed;
1745 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1746 ULONG loadcfg_size;
1747 ULONG_PTR *cookie;
1749 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1750 if (!loadcfg) return;
1751 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1752 if (!loadcfg->SecurityCookie) return;
1753 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1754 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1756 WARN( "security cookie %p outside of image %p-%p\n",
1757 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1758 return;
1761 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1762 TRACE( "initializing security cookie %p\n", cookie );
1764 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1765 for (;;)
1767 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1768 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1769 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1770 *cookie = RtlRandom( &seed );
1771 #ifdef DEFAULT_SECURITY_COOKIE_64
1772 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1774 *cookie = RtlRandom( &seed );
1775 /* fill up, but keep the highest word clear */
1776 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1778 #endif
1779 else
1780 break;
1784 static NTSTATUS perform_relocations( void *module, IMAGE_NT_HEADERS *nt, SIZE_T len )
1786 char *base;
1787 IMAGE_BASE_RELOCATION *rel, *end;
1788 const IMAGE_DATA_DIRECTORY *relocs;
1789 const IMAGE_SECTION_HEADER *sec;
1790 INT_PTR delta;
1791 ULONG protect_old[96], i;
1793 base = (char *)nt->OptionalHeader.ImageBase;
1794 if (module == base) return STATUS_SUCCESS; /* nothing to do */
1796 /* no relocations are performed on non page-aligned binaries */
1797 if (nt->OptionalHeader.SectionAlignment < page_size)
1798 return STATUS_SUCCESS;
1800 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1801 return STATUS_SUCCESS;
1803 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1805 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1807 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1808 base, module );
1809 return STATUS_CONFLICTING_ADDRESSES;
1812 if (!relocs->Size) return STATUS_SUCCESS;
1813 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1815 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
1816 return STATUS_INVALID_IMAGE_FORMAT;
1818 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1819 nt->FileHeader.SizeOfOptionalHeader);
1820 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1822 void *addr = get_rva( module, sec[i].VirtualAddress );
1823 SIZE_T size = sec[i].SizeOfRawData;
1824 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1825 &size, PAGE_READWRITE, &protect_old[i] );
1828 TRACE( "relocating from %p-%p to %p-%p\n",
1829 base, base + len, module, (char *)module + len );
1831 rel = get_rva( module, relocs->VirtualAddress );
1832 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1833 delta = (char *)module - base;
1835 while (rel < end - 1 && rel->SizeOfBlock)
1837 if (rel->VirtualAddress >= len)
1839 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1840 return STATUS_ACCESS_VIOLATION;
1842 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1843 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1844 (USHORT *)(rel + 1), delta );
1845 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1848 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1850 void *addr = get_rva( module, sec[i].VirtualAddress );
1851 SIZE_T size = sec[i].SizeOfRawData;
1852 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1853 &size, protect_old[i], &protect_old[i] );
1856 return STATUS_SUCCESS;
1860 /*************************************************************************
1861 * build_module
1863 * Build the module data for a mapped dll.
1865 static NTSTATUS build_module( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module,
1866 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
1867 DWORD flags, WINE_MODREF **pwm )
1869 IMAGE_NT_HEADERS *nt;
1870 WINE_MODREF *wm;
1871 NTSTATUS status;
1872 SIZE_T map_size;
1874 if (!(nt = RtlImageNtHeader( *module ))) return STATUS_INVALID_IMAGE_FORMAT;
1876 map_size = (nt->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
1877 if ((status = perform_relocations( *module, nt, map_size ))) return status;
1879 /* create the MODREF */
1881 if (!(wm = alloc_module( *module, nt_name, (image_info->u.ImageFlags & IMAGE_FLAGS_WineBuiltin) )))
1882 return STATUS_NO_MEMORY;
1884 if (id) wm->id = *id;
1885 if (image_info->LoaderFlags) wm->ldr.Flags |= LDR_COR_IMAGE;
1886 if (image_info->u.ImageFlags & IMAGE_FLAGS_ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
1888 set_security_cookie( *module, map_size );
1890 /* fixup imports */
1892 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1893 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1894 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1896 if (wm->ldr.Flags & LDR_COR_ILONLY)
1897 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
1898 else
1899 status = fixup_imports( wm, load_path );
1900 if (status != STATUS_SUCCESS)
1902 /* the module has only be inserted in the load & memory order lists */
1903 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
1904 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
1906 /* FIXME: there are several more dangling references
1907 * left. Including dlls loaded by this dll before the
1908 * failed one. Unrolling is rather difficult with the
1909 * current structure and we can leave them lying
1910 * around with no problems, so we don't care.
1911 * As these might reference our wm, we don't free it.
1913 *module = NULL;
1914 return status;
1918 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name), wm, module );
1920 /* send DLL load event */
1922 SERVER_START_REQ( load_dll )
1924 req->base = wine_server_client_ptr( *module );
1925 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1926 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1927 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1928 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1929 wine_server_call( req );
1931 SERVER_END_REQ;
1933 if (image_info->u.ImageFlags & IMAGE_FLAGS_WineBuiltin)
1935 if (TRACE_ON(relay)) RELAY_SetupDLL( *module );
1937 else
1939 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( *module );
1942 TRACE_(loaddll)( "Loaded %s at %p: %s\n", debugstr_w(wm->ldr.FullDllName.Buffer), *module,
1943 (image_info->u.ImageFlags & IMAGE_FLAGS_WineBuiltin) ? "builtin" : "native" );
1945 wm->ldr.LoadCount = 1;
1946 *pwm = wm;
1947 *module = NULL;
1948 return STATUS_SUCCESS;
1952 /*************************************************************************
1953 * build_builtin_module
1955 * Build the module for a builtin library.
1957 static NTSTATUS build_builtin_module( const WCHAR *load_path, const UNICODE_STRING *nt_name,
1958 void *module, DWORD flags, WINE_MODREF **pwm )
1960 NTSTATUS status;
1961 SECTION_IMAGE_INFORMATION image_info = { 0 };
1963 image_info.u.ImageFlags = IMAGE_FLAGS_WineBuiltin;
1964 status = build_module( load_path, nt_name, &module, &image_info, NULL, flags, pwm );
1965 if (status && module) unix_funcs->unload_builtin_dll( module );
1966 return status;
1970 #ifdef _WIN64
1971 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1972 static BOOL convert_to_pe64( HMODULE module, const SECTION_IMAGE_INFORMATION *info )
1974 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
1975 IMAGE_DIRECTORY_ENTRY_SECURITY,
1976 IMAGE_DIRECTORY_ENTRY_BASERELOC,
1977 IMAGE_DIRECTORY_ENTRY_DEBUG,
1978 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
1979 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
1980 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
1981 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1982 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
1983 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
1984 SIZE_T size = min( nt->OptionalHeader.SizeOfHeaders, nt->OptionalHeader.SizeOfImage );
1985 void *addr = module;
1986 ULONG i, old_prot;
1988 TRACE( "%p\n", module );
1990 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
1991 return FALSE;
1993 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
1995 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1996 return FALSE;
1999 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
2000 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
2001 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
2002 hdr64.AddressOfEntryPoint = 0;
2003 hdr64.ImageBase = hdr32.ImageBase;
2004 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
2005 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
2006 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
2007 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
2008 hdr64.LoaderFlags = hdr32.LoaderFlags;
2009 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
2010 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
2011 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
2013 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
2014 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
2015 nt->OptionalHeader = hdr64;
2016 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2017 return TRUE;
2019 #endif
2021 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2022 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2023 static BOOL is_valid_binary( HMODULE module, const SECTION_IMAGE_INFORMATION *info )
2025 #ifdef __i386__
2026 return info->Machine == IMAGE_FILE_MACHINE_I386;
2027 #elif defined(__arm__)
2028 return info->Machine == IMAGE_FILE_MACHINE_ARM ||
2029 info->Machine == IMAGE_FILE_MACHINE_THUMB ||
2030 info->Machine == IMAGE_FILE_MACHINE_ARMNT;
2031 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2032 #ifdef __x86_64__
2033 if (info->Machine == IMAGE_FILE_MACHINE_AMD64) return TRUE;
2034 #else
2035 if (info->Machine == IMAGE_FILE_MACHINE_ARM64) return TRUE;
2036 #endif
2037 if (!info->ImageContainsCode) return TRUE;
2038 if (!(info->u.ImageFlags & IMAGE_FLAGS_ComPlusNativeReady))
2040 /* check COM header directly, ignoring runtime version */
2041 DWORD size;
2042 const IMAGE_COR20_HEADER *cor_header = RtlImageDirectoryEntryToData( module, TRUE,
2043 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size );
2044 if (!cor_header || !(cor_header->Flags & COMIMAGE_FLAGS_ILONLY)) return FALSE;
2046 return convert_to_pe64( module, info );
2047 #else
2048 return FALSE; /* no wow64 support on other platforms */
2049 #endif
2053 /******************************************************************
2054 * get_module_path_end
2056 * Returns the end of the directory component of the module path.
2058 static inline const WCHAR *get_module_path_end( const WCHAR *module )
2060 const WCHAR *p;
2061 const WCHAR *mod_end = module;
2063 if ((p = wcsrchr( mod_end, '\\' ))) mod_end = p;
2064 if ((p = wcsrchr( mod_end, '/' ))) mod_end = p;
2065 if (mod_end == module + 2 && module[1] == ':') mod_end++;
2066 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
2067 return mod_end;
2071 /******************************************************************
2072 * append_path
2074 * Append a counted string to the load path. Helper for get_dll_load_path.
2076 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str, int len )
2078 if (len == -1) len = wcslen(str);
2079 if (!len) return p;
2080 memcpy( p, str, len * sizeof(WCHAR) );
2081 p[len] = ';';
2082 return p + len + 1;
2086 /******************************************************************
2087 * get_dll_load_path
2089 static NTSTATUS get_dll_load_path( LPCWSTR module, LPCWSTR dll_dir, ULONG safe_mode, WCHAR **path )
2091 const WCHAR *mod_end = module;
2092 UNICODE_STRING name, value;
2093 WCHAR *p, *ret;
2094 int len = ARRAY_SIZE(system_path) + 1, path_len = 0;
2096 if (module)
2098 mod_end = get_module_path_end( module );
2099 len += (mod_end - module) + 1;
2102 RtlInitUnicodeString( &name, L"PATH" );
2103 value.Length = 0;
2104 value.MaximumLength = 0;
2105 value.Buffer = NULL;
2106 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2107 path_len = value.Length;
2109 if (dll_dir) len += wcslen( dll_dir ) + 1;
2110 else len += 2; /* current directory */
2111 if (!(p = ret = RtlAllocateHeap( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
2112 return STATUS_NO_MEMORY;
2114 p = append_path( p, module, mod_end - module );
2115 if (dll_dir) p = append_path( p, dll_dir, -1 );
2116 else if (!safe_mode) p = append_path( p, L".", -1 );
2117 p = append_path( p, system_path, -1 );
2118 if (!dll_dir && safe_mode) p = append_path( p, L".", -1 );
2120 value.Buffer = p;
2121 value.MaximumLength = path_len;
2123 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2125 WCHAR *new_ptr;
2127 /* grow the buffer and retry */
2128 path_len = value.Length;
2129 if (!(new_ptr = RtlReAllocateHeap( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
2131 RtlFreeHeap( GetProcessHeap(), 0, ret );
2132 return STATUS_NO_MEMORY;
2134 value.Buffer = new_ptr + (value.Buffer - ret);
2135 value.MaximumLength = path_len;
2136 ret = new_ptr;
2138 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
2139 *path = ret;
2140 return STATUS_SUCCESS;
2144 /******************************************************************
2145 * get_dll_load_path_search_flags
2147 static NTSTATUS get_dll_load_path_search_flags( LPCWSTR module, DWORD flags, WCHAR **path )
2149 const WCHAR *image = NULL, *mod_end, *image_end;
2150 struct dll_dir_entry *dir;
2151 WCHAR *p, *ret;
2152 int len = 1;
2154 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
2155 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
2156 LOAD_LIBRARY_SEARCH_USER_DIRS |
2157 LOAD_LIBRARY_SEARCH_SYSTEM32);
2159 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
2161 DWORD type = RtlDetermineDosPathNameType_U( module );
2162 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH && type != DEVICE_PATH)
2163 return STATUS_INVALID_PARAMETER;
2164 mod_end = get_module_path_end( module );
2165 len += (mod_end - module) + 1;
2167 else module = NULL;
2169 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
2171 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
2172 image_end = get_module_path_end( image );
2173 len += (image_end - image) + 1;
2176 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2178 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2179 len += wcslen( dir->dir + 4 /* \??\ */ ) + 1;
2180 if (dll_directory.Length) len += dll_directory.Length / sizeof(WCHAR) + 1;
2183 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += wcslen( system_dir );
2185 if ((p = ret = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2187 if (module) p = append_path( p, module, mod_end - module );
2188 if (image) p = append_path( p, image, image_end - image );
2189 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2191 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2192 p = append_path( p, dir->dir + 4 /* \??\ */, -1 );
2193 p = append_path( p, dll_directory.Buffer, dll_directory.Length / sizeof(WCHAR) );
2195 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) wcscpy( p, system_dir );
2196 else
2198 if (p > ret) p--;
2199 *p = 0;
2202 *path = ret;
2203 return STATUS_SUCCESS;
2207 /***********************************************************************
2208 * open_dll_file
2210 * Open a file for a new dll. Helper for find_dll_file.
2212 static NTSTATUS open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm, void **module,
2213 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2215 FILE_BASIC_INFORMATION info;
2216 OBJECT_ATTRIBUTES attr;
2217 IO_STATUS_BLOCK io;
2218 LARGE_INTEGER size;
2219 FILE_OBJECTID_BUFFER fid;
2220 SIZE_T len = 0;
2221 NTSTATUS status;
2222 HANDLE handle, mapping;
2224 if ((*pwm = find_fullname_module( nt_name )))
2226 NtUnmapViewOfSection( NtCurrentProcess(), *module );
2227 *module = NULL;
2228 return STATUS_SUCCESS;
2231 attr.Length = sizeof(attr);
2232 attr.RootDirectory = 0;
2233 attr.Attributes = OBJ_CASE_INSENSITIVE;
2234 attr.ObjectName = nt_name;
2235 attr.SecurityDescriptor = NULL;
2236 attr.SecurityQualityOfService = NULL;
2237 if ((status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2238 FILE_SHARE_READ | FILE_SHARE_DELETE,
2239 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
2241 if (status != STATUS_OBJECT_PATH_NOT_FOUND &&
2242 status != STATUS_OBJECT_NAME_NOT_FOUND &&
2243 !NtQueryAttributesFile( &attr, &info ))
2245 /* if the file exists but failed to open, report the error */
2246 return status;
2248 /* otherwise continue searching */
2249 return STATUS_DLL_NOT_FOUND;
2252 if (!NtFsControlFile( handle, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &fid, sizeof(fid) ))
2254 memcpy( id, fid.ObjectId, sizeof(*id) );
2255 if ((*pwm = find_fileid_module( id )))
2257 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2258 (*pwm)->ldr.DllBase, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2259 NtClose( handle );
2260 NtUnmapViewOfSection( NtCurrentProcess(), *module );
2261 *module = NULL;
2262 return STATUS_SUCCESS;
2266 size.QuadPart = 0;
2267 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2268 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2269 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, handle );
2270 NtClose( handle );
2272 if (!status)
2274 if (*module)
2276 NtUnmapViewOfSection( NtCurrentProcess(), *module );
2277 *module = NULL;
2279 NtQuerySection( mapping, SectionImageInformation, image_info, sizeof(*image_info), NULL );
2280 status = NtMapViewOfSection( mapping, NtCurrentProcess(), module, 0, 0, NULL, &len,
2281 ViewShare, 0, PAGE_EXECUTE_READ );
2282 if (status == STATUS_IMAGE_NOT_AT_BASE) status = STATUS_SUCCESS;
2283 NtClose( mapping );
2285 if (!status && !is_valid_binary( *module, image_info ))
2287 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name), image_info->Machine );
2288 NtUnmapViewOfSection( NtCurrentProcess(), *module );
2289 *module = NULL;
2290 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2292 return status;
2296 /******************************************************************************
2297 * load_native_dll (internal)
2299 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module,
2300 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
2301 DWORD flags, WINE_MODREF** pwm )
2303 return build_module( load_path, nt_name, module, image_info, id, flags, pwm );
2307 /***********************************************************************
2308 * load_so_dll
2310 static NTSTATUS load_so_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name,
2311 DWORD flags, WINE_MODREF **pwm )
2313 void *module;
2314 NTSTATUS status;
2315 WINE_MODREF *wm;
2316 UNICODE_STRING win_name = *nt_name;
2318 TRACE( "trying %s as so lib\n", debugstr_us(&win_name) );
2319 if (unix_funcs->load_so_dll( &win_name, &module ))
2321 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name) );
2322 return STATUS_INVALID_IMAGE_FORMAT;
2325 if ((wm = get_modref( module ))) /* already loaded */
2327 TRACE( "Found %s at %p for builtin %s\n",
2328 debugstr_w(wm->ldr.FullDllName.Buffer), wm->ldr.DllBase, debugstr_us(nt_name) );
2329 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2331 else
2333 if ((status = build_builtin_module( load_path, &win_name, module, flags, &wm ))) return status;
2334 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name), module );
2336 *pwm = wm;
2337 return STATUS_SUCCESS;
2341 /***********************************************************************
2342 * load_builtin_dll
2344 static NTSTATUS load_builtin_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module_ptr,
2345 DWORD flags, WINE_MODREF** pwm )
2347 const WCHAR *name, *p;
2348 NTSTATUS status;
2349 void *module = NULL, *unix_entry = NULL;
2350 SECTION_IMAGE_INFORMATION image_info;
2352 /* Fix the name in case we have a full path and extension */
2353 name = nt_name->Buffer;
2354 if ((p = wcsrchr( name, '\\' ))) name = p + 1;
2355 if ((p = wcsrchr( name, '/' ))) name = p + 1;
2357 TRACE("Trying built-in %s\n", debugstr_w(name));
2359 if (!module_ptr) module_ptr = &module;
2361 status = unix_funcs->load_builtin_dll( name, module_ptr, &unix_entry, &image_info );
2362 if (status) return status;
2364 if ((*pwm = get_modref( *module_ptr ))) /* already loaded */
2366 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2367 TRACE( "Found %s for %s at %p, count=%d\n",
2368 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(name),
2369 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2370 *module_ptr = NULL;
2371 return STATUS_SUCCESS;
2374 TRACE( "loading %s from %s\n", debugstr_w(name), debugstr_us(nt_name) );
2375 status = build_module( load_path, nt_name, module_ptr, &image_info, NULL, flags, pwm );
2376 if (!status) (*pwm)->unix_entry = unix_entry;
2377 else if (*module_ptr) unix_funcs->unload_builtin_dll( *module_ptr );
2378 return status;
2382 /***********************************************************************
2383 * find_actctx_dll
2385 * Find the full path (if any) of the dll from the activation context.
2387 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2389 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2391 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2392 ACTCTX_SECTION_KEYED_DATA data;
2393 UNICODE_STRING nameW;
2394 NTSTATUS status;
2395 SIZE_T needed, size = 1024;
2396 WCHAR *p;
2398 RtlInitUnicodeString( &nameW, libname );
2399 data.cbSize = sizeof(data);
2400 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2401 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2402 &nameW, &data );
2403 if (status != STATUS_SUCCESS) return status;
2405 for (;;)
2407 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2409 status = STATUS_NO_MEMORY;
2410 goto done;
2412 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2413 AssemblyDetailedInformationInActivationContext,
2414 info, size, &needed );
2415 if (status == STATUS_SUCCESS) break;
2416 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2417 RtlFreeHeap( GetProcessHeap(), 0, info );
2418 size = needed;
2419 /* restart with larger buffer */
2422 if (!info->lpAssemblyManifestPath)
2424 status = STATUS_SXS_KEY_NOT_FOUND;
2425 goto done;
2428 if ((p = wcsrchr( info->lpAssemblyManifestPath, '\\' )))
2430 DWORD len, dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2431 p++;
2432 len = wcslen( p );
2433 if (!dirlen || len <= dirlen ||
2434 RtlCompareUnicodeStrings( p, dirlen, info->lpAssemblyDirectoryName, dirlen, TRUE ) ||
2435 wcsicmp( p + dirlen, L".manifest" ))
2437 /* manifest name does not match directory name, so it's not a global
2438 * windows/winsxs manifest; use the manifest directory name instead */
2439 dirlen = p - info->lpAssemblyManifestPath;
2440 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2441 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2443 status = STATUS_NO_MEMORY;
2444 goto done;
2446 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2447 p += dirlen;
2448 wcscpy( p, libname );
2449 goto done;
2453 if (!info->lpAssemblyDirectoryName)
2455 status = STATUS_SXS_KEY_NOT_FOUND;
2456 goto done;
2459 needed = (wcslen(windows_dir) * sizeof(WCHAR) +
2460 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2462 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2464 status = STATUS_NO_MEMORY;
2465 goto done;
2467 wcscpy( p, windows_dir );
2468 p += wcslen(p);
2469 memcpy( p, winsxsW, sizeof(winsxsW) );
2470 p += ARRAY_SIZE( winsxsW );
2471 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2472 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2473 *p++ = '\\';
2474 wcscpy( p, libname );
2475 done:
2476 RtlFreeHeap( GetProcessHeap(), 0, info );
2477 RtlReleaseActivationContext( data.hActCtx );
2478 return status;
2482 /***********************************************************************
2483 * search_dll_file
2485 * Search for dll in the specified paths.
2487 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name,
2488 WINE_MODREF **pwm, void **module, SECTION_IMAGE_INFORMATION *image_info,
2489 struct file_id *id )
2491 WCHAR *name;
2492 BOOL found_image = FALSE;
2493 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2494 ULONG len = wcslen( paths );
2496 if (len < wcslen( system_dir )) len = wcslen( system_dir );
2497 len += wcslen( search ) + 2;
2499 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2500 return STATUS_NO_MEMORY;
2502 while (*paths)
2504 LPCWSTR ptr = paths;
2506 while (*ptr && *ptr != ';') ptr++;
2507 len = ptr - paths;
2508 if (*ptr == ';') ptr++;
2509 memcpy( name, paths, len * sizeof(WCHAR) );
2510 if (len && name[len - 1] != '\\') name[len++] = '\\';
2511 wcscpy( name + len, search );
2513 nt_name->Buffer = NULL;
2514 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( name, nt_name, NULL, NULL ))) goto done;
2516 status = open_dll_file( nt_name, pwm, module, image_info, id );
2517 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2518 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2519 RtlFreeUnicodeString( nt_name );
2520 paths = ptr;
2523 if (!found_image)
2525 /* not found, return file in the system dir to be loaded as builtin */
2526 wcscpy( name, system_dir );
2527 wcscat( name, search );
2528 if (!RtlDosPathNameToNtPathName_U( name, nt_name, NULL, NULL )) status = STATUS_NO_MEMORY;
2530 else status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2532 done:
2533 RtlFreeHeap( GetProcessHeap(), 0, name );
2534 return status;
2538 /***********************************************************************
2539 * find_dll_file
2541 * Find the file (or already loaded module) for a given dll name.
2543 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2544 UNICODE_STRING *nt_name, WINE_MODREF **pwm, void **module,
2545 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2547 WCHAR *ext, *dllname;
2548 NTSTATUS status;
2549 ULONG wow64_old_value = 0;
2551 *pwm = NULL;
2552 *module = NULL;
2553 dllname = NULL;
2555 if (default_ext) /* first append default extension */
2557 if (!(ext = wcsrchr( libname, '.')) || wcschr( ext, '/' ) || wcschr( ext, '\\'))
2559 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2560 (wcslen(libname)+wcslen(default_ext)+1) * sizeof(WCHAR))))
2561 return STATUS_NO_MEMORY;
2562 wcscpy( dllname, libname );
2563 wcscat( dllname, default_ext );
2564 libname = dllname;
2568 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2569 if (is_wow64) RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value );
2571 nt_name->Buffer = NULL;
2573 if (!contains_path( libname ))
2575 WCHAR *fullname = NULL;
2577 status = find_actctx_dll( libname, &fullname );
2578 if (status == STATUS_SUCCESS)
2580 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2581 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2582 libname = dllname = fullname;
2584 else
2586 if (status != STATUS_SXS_KEY_NOT_FOUND) goto done;
2587 if ((*pwm = find_basename_module( libname )) != NULL)
2589 status = STATUS_SUCCESS;
2590 goto done;
2595 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2596 status = search_dll_file( load_path, libname, nt_name, pwm, module, image_info, id );
2597 else if (!(status = RtlDosPathNameToNtPathName_U_WithStatus( libname, nt_name, NULL, NULL )))
2598 status = open_dll_file( nt_name, pwm, module, image_info, id );
2600 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) status = STATUS_INVALID_IMAGE_FORMAT;
2602 done:
2603 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2604 if (wow64_old_value) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value );
2605 return status;
2609 /***********************************************************************
2610 * load_dll (internal)
2612 * Load a PE style module according to the load order.
2613 * The loader_section must be locked while calling this function.
2615 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2616 DWORD flags, WINE_MODREF** pwm )
2618 enum loadorder loadorder;
2619 WINE_MODREF *main_exe;
2620 UNICODE_STRING nt_name;
2621 struct file_id id;
2622 void *module;
2623 SECTION_IMAGE_INFORMATION image_info;
2624 NTSTATUS nts;
2626 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2628 nts = find_dll_file( load_path, libname, default_ext, &nt_name, pwm, &module, &image_info, &id );
2630 if (*pwm) /* found already loaded module */
2632 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2634 TRACE("Found %s for %s at %p, count=%d\n",
2635 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2636 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2637 RtlFreeUnicodeString( &nt_name );
2638 return STATUS_SUCCESS;
2641 if (nts && nts != STATUS_DLL_NOT_FOUND && nts != STATUS_INVALID_IMAGE_NOT_MZ) goto done;
2643 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2644 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, &nt_name );
2646 switch (nts)
2648 case STATUS_INVALID_IMAGE_NOT_MZ: /* not in PE format, maybe it's a .so file */
2649 switch (loadorder)
2651 case LO_NATIVE:
2652 case LO_NATIVE_BUILTIN:
2653 case LO_BUILTIN:
2654 case LO_BUILTIN_NATIVE:
2655 case LO_DEFAULT:
2656 if (!load_so_dll( load_path, &nt_name, flags, pwm )) nts = STATUS_SUCCESS;
2657 break;
2658 default:
2659 nts = STATUS_DLL_NOT_FOUND;
2660 break;
2662 break;
2664 case STATUS_SUCCESS: /* valid PE file */
2665 if (image_info.u.ImageFlags & IMAGE_FLAGS_WineBuiltin)
2667 switch (loadorder)
2669 case LO_NATIVE_BUILTIN:
2670 case LO_BUILTIN:
2671 case LO_BUILTIN_NATIVE:
2672 case LO_DEFAULT:
2673 nts = load_builtin_dll( load_path, &nt_name, &module, flags, pwm );
2674 if (nts == STATUS_DLL_NOT_FOUND)
2675 nts = load_native_dll( load_path, &nt_name, &module, &image_info, &id, flags, pwm );
2676 break;
2677 default:
2678 nts = STATUS_DLL_NOT_FOUND;
2679 break;
2681 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2682 break;
2684 if (!(image_info.u.ImageFlags & IMAGE_FLAGS_WineFakeDll))
2686 switch (loadorder)
2688 case LO_NATIVE:
2689 case LO_NATIVE_BUILTIN:
2690 nts = load_native_dll( load_path, &nt_name, &module, &image_info, &id, flags, pwm );
2691 break;
2692 case LO_BUILTIN:
2693 nts = load_builtin_dll( load_path, &nt_name, &module, flags, pwm );
2694 break;
2695 case LO_BUILTIN_NATIVE:
2696 case LO_DEFAULT:
2697 nts = load_builtin_dll( load_path, &nt_name, &module, flags, pwm );
2698 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2699 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2701 /* stub-only dll, try native */
2702 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_us(&nt_name) );
2703 LdrUnloadDll( (*pwm)->ldr.DllBase );
2704 nts = STATUS_DLL_NOT_FOUND;
2705 /* map the dll again if it was unmapped */
2706 if (!module && open_dll_file( &nt_name, pwm, &module, &image_info, &id )) break;
2708 if (nts == STATUS_DLL_NOT_FOUND)
2709 nts = load_native_dll( load_path, &nt_name, &module, &image_info, &id, flags, pwm );
2710 break;
2711 default:
2712 nts = STATUS_DLL_NOT_FOUND;
2713 break;
2715 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2716 break;
2718 TRACE( "%s is a fake Wine dll\n", debugstr_us(&nt_name) );
2719 NtUnmapViewOfSection( NtCurrentProcess(), module );
2720 /* fall through */
2722 case STATUS_DLL_NOT_FOUND: /* no file found, try builtin */
2723 switch (loadorder)
2725 case LO_NATIVE_BUILTIN:
2726 case LO_BUILTIN:
2727 case LO_BUILTIN_NATIVE:
2728 case LO_DEFAULT:
2729 nts = load_builtin_dll( load_path, &nt_name, NULL, flags, pwm );
2730 break;
2731 default:
2732 nts = STATUS_DLL_NOT_FOUND;
2733 break;
2735 break;
2738 done:
2739 if (nts == STATUS_SUCCESS)
2740 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name), (*pwm)->ldr.DllBase);
2741 else
2742 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2744 RtlFreeUnicodeString( &nt_name );
2745 return nts;
2749 /***********************************************************************
2750 * __wine_init_unix_lib
2752 NTSTATUS __cdecl __wine_init_unix_lib( HMODULE module, DWORD reason, const void *ptr_in, void *ptr_out )
2754 WINE_MODREF *wm;
2755 NTSTATUS ret = STATUS_DLL_NOT_FOUND;
2757 RtlEnterCriticalSection( &loader_section );
2759 if ((wm = get_modref( module )))
2761 NTSTATUS (CDECL *init_func)( HMODULE, DWORD, const void *, void * ) = wm->unix_entry;
2762 if (init_func) ret = init_func( module, reason, ptr_in, ptr_out );
2764 else ret = STATUS_INVALID_HANDLE;
2766 RtlLeaveCriticalSection( &loader_section );
2767 return ret;
2771 /******************************************************************
2772 * LdrLoadDll (NTDLL.@)
2774 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2775 const UNICODE_STRING *libname, HMODULE* hModule)
2777 WINE_MODREF *wm;
2778 NTSTATUS nts;
2780 RtlEnterCriticalSection( &loader_section );
2782 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2783 nts = load_dll( path_name, libname->Buffer, L".dll", flags, &wm );
2785 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2787 nts = process_attach( wm, NULL );
2788 if (nts != STATUS_SUCCESS)
2790 LdrUnloadDll(wm->ldr.DllBase);
2791 wm = NULL;
2794 *hModule = (wm) ? wm->ldr.DllBase : NULL;
2796 RtlLeaveCriticalSection( &loader_section );
2797 return nts;
2801 /******************************************************************
2802 * LdrGetDllHandle (NTDLL.@)
2804 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2806 NTSTATUS status;
2807 UNICODE_STRING nt_name;
2808 WINE_MODREF *wm;
2809 void *module;
2810 SECTION_IMAGE_INFORMATION image_info;
2811 struct file_id id;
2813 RtlEnterCriticalSection( &loader_section );
2815 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2817 status = find_dll_file( load_path, name->Buffer, L".dll", &nt_name, &wm, &module, &image_info, &id );
2819 if (wm) *base = wm->ldr.DllBase;
2820 else
2822 if (status == STATUS_SUCCESS) NtUnmapViewOfSection( NtCurrentProcess(), module );
2823 status = STATUS_DLL_NOT_FOUND;
2825 RtlFreeUnicodeString( &nt_name );
2827 RtlLeaveCriticalSection( &loader_section );
2828 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2829 return status;
2833 /******************************************************************
2834 * LdrAddRefDll (NTDLL.@)
2836 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2838 NTSTATUS ret = STATUS_SUCCESS;
2839 WINE_MODREF *wm;
2841 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2843 RtlEnterCriticalSection( &loader_section );
2845 if ((wm = get_modref( module )))
2847 if (flags & LDR_ADDREF_DLL_PIN)
2848 wm->ldr.LoadCount = -1;
2849 else
2850 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2851 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2853 else ret = STATUS_INVALID_PARAMETER;
2855 RtlLeaveCriticalSection( &loader_section );
2856 return ret;
2860 /***********************************************************************
2861 * LdrProcessRelocationBlock (NTDLL.@)
2863 * Apply relocations to a given page of a mapped PE image.
2865 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2866 USHORT *relocs, INT_PTR delta )
2868 while (count--)
2870 USHORT offset = *relocs & 0xfff;
2871 int type = *relocs >> 12;
2872 switch(type)
2874 case IMAGE_REL_BASED_ABSOLUTE:
2875 break;
2876 case IMAGE_REL_BASED_HIGH:
2877 *(short *)((char *)page + offset) += HIWORD(delta);
2878 break;
2879 case IMAGE_REL_BASED_LOW:
2880 *(short *)((char *)page + offset) += LOWORD(delta);
2881 break;
2882 case IMAGE_REL_BASED_HIGHLOW:
2883 *(int *)((char *)page + offset) += delta;
2884 break;
2885 #ifdef _WIN64
2886 case IMAGE_REL_BASED_DIR64:
2887 *(INT_PTR *)((char *)page + offset) += delta;
2888 break;
2889 #elif defined(__arm__)
2890 case IMAGE_REL_BASED_THUMB_MOV32:
2892 DWORD inst = *(INT_PTR *)((char *)page + offset);
2893 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2894 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2895 DWORD hi_delta;
2897 if ((inst & 0x8000fbf0) != 0x0000f240)
2898 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2900 imm16 += LOWORD(delta);
2901 hi_delta = HIWORD(delta) + HIWORD(imm16);
2902 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2903 ((imm16 >> 12) & 0x000f) +
2904 ((imm16 << 20) & 0x70000000) +
2905 ((imm16 << 16) & 0xff0000);
2907 if (hi_delta != 0)
2909 inst = *(INT_PTR *)((char *)page + offset + 4);
2910 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2911 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2913 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2914 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2916 imm16 += hi_delta;
2917 if (imm16 > 0xffff)
2918 ERR("resulting immediate value won't fit: %08x\n", imm16);
2919 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2920 ((imm16 >> 1) & 0x0400) +
2921 ((imm16 >> 12) & 0x000f) +
2922 ((imm16 << 20) & 0x70000000) +
2923 ((imm16 << 16) & 0xff0000);
2926 break;
2927 #endif
2928 default:
2929 FIXME("Unknown/unsupported fixup type %x.\n", type);
2930 return NULL;
2932 relocs++;
2934 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2938 /******************************************************************
2939 * LdrQueryProcessModuleInformation
2942 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2943 ULONG buf_size, ULONG* req_size)
2945 SYSTEM_MODULE* sm = &smi->Modules[0];
2946 ULONG size = sizeof(ULONG);
2947 NTSTATUS nts = STATUS_SUCCESS;
2948 ANSI_STRING str;
2949 char* ptr;
2950 PLIST_ENTRY mark, entry;
2951 LDR_DATA_TABLE_ENTRY *mod;
2952 WORD id = 0;
2954 smi->ModulesCount = 0;
2956 RtlEnterCriticalSection( &loader_section );
2957 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2958 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2960 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2961 size += sizeof(*sm);
2962 if (size <= buf_size)
2964 sm->Section = 0; /* FIXME */
2965 sm->MappedBaseAddress = mod->DllBase;
2966 sm->ImageBaseAddress = mod->DllBase;
2967 sm->ImageSize = mod->SizeOfImage;
2968 sm->Flags = mod->Flags;
2969 sm->LoadOrderIndex = id++;
2970 sm->InitOrderIndex = 0; /* FIXME */
2971 sm->LoadCount = mod->LoadCount;
2972 str.Length = 0;
2973 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2974 str.Buffer = (char*)sm->Name;
2975 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2976 ptr = strrchr(str.Buffer, '\\');
2977 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2979 smi->ModulesCount++;
2980 sm++;
2982 else nts = STATUS_INFO_LENGTH_MISMATCH;
2984 RtlLeaveCriticalSection( &loader_section );
2986 if (req_size) *req_size = size;
2988 return nts;
2992 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2994 NTSTATUS status;
2995 UNICODE_STRING str;
2996 ULONG size;
2997 WCHAR buffer[64];
2998 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3000 RtlInitUnicodeString( &str, name );
3002 size = sizeof(buffer) - sizeof(WCHAR);
3003 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
3004 return status;
3006 if (info->Type != REG_DWORD)
3008 buffer[size / sizeof(WCHAR)] = 0;
3009 *value = wcstoul( (WCHAR *)info->Data, 0, 16 );
3011 else memcpy( value, info->Data, sizeof(*value) );
3012 return status;
3015 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
3016 void *data, ULONG in_size, ULONG *out_size )
3018 NTSTATUS status;
3019 UNICODE_STRING str;
3020 ULONG size;
3021 char *buffer;
3022 KEY_VALUE_PARTIAL_INFORMATION *info;
3023 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
3025 RtlInitUnicodeString( &str, name );
3027 size = info_size + in_size;
3028 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
3029 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3030 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
3031 if (!status || status == STATUS_BUFFER_OVERFLOW)
3033 if (out_size) *out_size = info->DataLength;
3034 if (data && !status) memcpy( data, info->Data, info->DataLength );
3036 RtlFreeHeap( GetProcessHeap(), 0, buffer );
3037 return status;
3041 /******************************************************************
3042 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3044 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
3045 void *data, ULONG in_size, ULONG *out_size )
3047 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
3048 'S','o','f','t','w','a','r','e','\\',
3049 'M','i','c','r','o','s','o','f','t','\\',
3050 'W','i','n','d','o','w','s',' ','N','T','\\',
3051 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3052 'I','m','a','g','e',' ','F','i','l','e',' ',
3053 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3054 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
3055 OBJECT_ATTRIBUTES attr;
3056 UNICODE_STRING name_str;
3057 HANDLE hkey;
3058 NTSTATUS status;
3059 ULONG len;
3060 WCHAR *p;
3062 attr.Length = sizeof(attr);
3063 attr.RootDirectory = 0;
3064 attr.ObjectName = &name_str;
3065 attr.Attributes = OBJ_CASE_INSENSITIVE;
3066 attr.SecurityDescriptor = NULL;
3067 attr.SecurityQualityOfService = NULL;
3069 p = key->Buffer + key->Length / sizeof(WCHAR);
3070 while (p > key->Buffer && p[-1] != '\\') p--;
3071 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
3072 name_str.Buffer = path;
3073 name_str.Length = sizeof(optionsW) + len;
3074 name_str.MaximumLength = name_str.Length;
3075 memcpy( path, optionsW, sizeof(optionsW) );
3076 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
3077 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
3079 if (type == REG_DWORD)
3081 if (out_size) *out_size = sizeof(ULONG);
3082 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
3083 else status = STATUS_BUFFER_OVERFLOW;
3085 else status = query_string_option( hkey, value, type, data, in_size, out_size );
3087 NtClose( hkey );
3088 return status;
3092 /******************************************************************
3093 * RtlDllShutdownInProgress (NTDLL.@)
3095 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
3097 return process_detaching;
3100 /****************************************************************************
3101 * LdrResolveDelayLoadedAPI (NTDLL.@)
3103 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
3104 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
3105 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
3106 IMAGE_THUNK_DATA* addr, ULONG flags )
3108 IMAGE_THUNK_DATA *pIAT, *pINT;
3109 DELAYLOAD_INFO delayinfo;
3110 UNICODE_STRING mod;
3111 const CHAR* name;
3112 HMODULE *phmod;
3113 NTSTATUS nts;
3114 FARPROC fp;
3115 DWORD id;
3117 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base, desc, dllhook, syshook, addr, flags );
3119 phmod = get_rva(base, desc->ModuleHandleRVA);
3120 pIAT = get_rva(base, desc->ImportAddressTableRVA);
3121 pINT = get_rva(base, desc->ImportNameTableRVA);
3122 name = get_rva(base, desc->DllNameRVA);
3123 id = addr - pIAT;
3125 if (!*phmod)
3127 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
3129 nts = STATUS_NO_MEMORY;
3130 goto fail;
3132 nts = LdrLoadDll(NULL, 0, &mod, phmod);
3133 RtlFreeUnicodeString(&mod);
3134 if (nts) goto fail;
3137 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3138 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
3139 else
3141 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3142 ANSI_STRING fnc;
3144 RtlInitAnsiString(&fnc, (char*)iibn->Name);
3145 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
3147 if (!nts)
3149 pIAT[id].u1.Function = (ULONG_PTR)fp;
3150 return fp;
3153 fail:
3154 delayinfo.Size = sizeof(delayinfo);
3155 delayinfo.DelayloadDescriptor = desc;
3156 delayinfo.ThunkAddress = addr;
3157 delayinfo.TargetDllName = name;
3158 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
3159 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
3160 delayinfo.TargetModuleBase = *phmod;
3161 delayinfo.Unused = NULL;
3162 delayinfo.LastError = nts;
3164 if (dllhook)
3165 return dllhook(4, &delayinfo);
3167 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3169 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3170 return syshook(name, (const char *)ord);
3172 else
3174 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3175 return syshook(name, (const char *)iibn->Name);
3179 /******************************************************************
3180 * LdrShutdownProcess (NTDLL.@)
3183 void WINAPI LdrShutdownProcess(void)
3185 BOOL detaching = process_detaching;
3187 TRACE("()\n");
3189 process_detaching = TRUE;
3190 if (!detaching)
3191 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3193 process_detach();
3197 /******************************************************************
3198 * RtlExitUserProcess (NTDLL.@)
3200 void WINAPI RtlExitUserProcess( DWORD status )
3202 RtlEnterCriticalSection( &loader_section );
3203 RtlAcquirePebLock();
3204 NtTerminateProcess( 0, status );
3205 LdrShutdownProcess();
3206 for (;;) NtTerminateProcess( GetCurrentProcess(), status );
3209 /******************************************************************
3210 * LdrShutdownThread (NTDLL.@)
3213 void WINAPI LdrShutdownThread(void)
3215 PLIST_ENTRY mark, entry;
3216 LDR_DATA_TABLE_ENTRY *mod;
3217 WINE_MODREF *wm;
3218 UINT i;
3219 void **pointers;
3221 TRACE("()\n");
3223 /* don't do any detach calls if process is exiting */
3224 if (process_detaching) return;
3226 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3228 RtlEnterCriticalSection( &loader_section );
3229 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3231 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3232 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3234 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
3235 InInitializationOrderLinks);
3236 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3237 continue;
3238 if ( mod->Flags & LDR_NO_DLL_CALLS )
3239 continue;
3241 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3242 DLL_THREAD_DETACH, NULL );
3245 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_DETACH );
3247 RtlAcquirePebLock();
3248 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3249 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3251 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3252 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3254 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 2 );
3255 NtCurrentTeb()->FlsSlots = NULL;
3256 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3257 NtCurrentTeb()->TlsExpansionSlots = NULL;
3258 RtlReleasePebLock();
3260 RtlLeaveCriticalSection( &loader_section );
3264 /***********************************************************************
3265 * free_modref
3268 static void free_modref( WINE_MODREF *wm )
3270 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
3271 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
3272 if (wm->ldr.InInitializationOrderLinks.Flink)
3273 RemoveEntryList(&wm->ldr.InInitializationOrderLinks);
3275 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3276 if (!TRACE_ON(module))
3277 TRACE_(loaddll)("Unloaded module %s : %s\n",
3278 debugstr_w(wm->ldr.FullDllName.Buffer),
3279 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3281 SERVER_START_REQ( unload_dll )
3283 req->base = wine_server_client_ptr( wm->ldr.DllBase );
3284 wine_server_call( req );
3286 SERVER_END_REQ;
3288 free_tls_slot( &wm->ldr );
3289 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3290 unix_funcs->unload_builtin_dll( wm->ldr.DllBase );
3291 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.DllBase );
3292 if (cached_modref == wm) cached_modref = NULL;
3293 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3294 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
3295 RtlFreeHeap( GetProcessHeap(), 0, wm );
3298 /***********************************************************************
3299 * MODULE_FlushModrefs
3301 * Remove all unused modrefs and call the internal unloading routines
3302 * for the library type.
3304 * The loader_section must be locked while calling this function.
3306 static void MODULE_FlushModrefs(void)
3308 PLIST_ENTRY mark, entry, prev;
3309 LDR_DATA_TABLE_ENTRY *mod;
3310 WINE_MODREF*wm;
3312 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3313 for (entry = mark->Blink; entry != mark; entry = prev)
3315 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
3316 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3317 prev = entry->Blink;
3318 if (!mod->LoadCount) free_modref( wm );
3321 /* check load order list too for modules that haven't been initialized yet */
3322 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3323 for (entry = mark->Blink; entry != mark; entry = prev)
3325 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3326 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3327 prev = entry->Blink;
3328 if (!mod->LoadCount) free_modref( wm );
3332 /***********************************************************************
3333 * MODULE_DecRefCount
3335 * The loader_section must be locked while calling this function.
3337 static void MODULE_DecRefCount( WINE_MODREF *wm )
3339 int i;
3341 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3342 return;
3344 if ( wm->ldr.LoadCount <= 0 )
3345 return;
3347 --wm->ldr.LoadCount;
3348 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3350 if ( wm->ldr.LoadCount == 0 )
3352 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3354 for ( i = 0; i < wm->nDeps; i++ )
3355 if ( wm->deps[i] )
3356 MODULE_DecRefCount( wm->deps[i] );
3358 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3360 module_push_unload_trace( &wm->ldr );
3364 /******************************************************************
3365 * LdrUnloadDll (NTDLL.@)
3369 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3371 WINE_MODREF *wm;
3372 NTSTATUS retv = STATUS_SUCCESS;
3374 if (process_detaching) return retv;
3376 TRACE("(%p)\n", hModule);
3378 RtlEnterCriticalSection( &loader_section );
3380 free_lib_count++;
3381 if ((wm = get_modref( hModule )) != NULL)
3383 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3385 /* Recursively decrement reference counts */
3386 MODULE_DecRefCount( wm );
3388 /* Call process detach notifications */
3389 if ( free_lib_count <= 1 )
3391 process_detach();
3392 MODULE_FlushModrefs();
3395 TRACE("END\n");
3397 else
3398 retv = STATUS_DLL_NOT_FOUND;
3400 free_lib_count--;
3402 RtlLeaveCriticalSection( &loader_section );
3404 return retv;
3407 /***********************************************************************
3408 * RtlImageNtHeader (NTDLL.@)
3410 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3412 IMAGE_NT_HEADERS *ret;
3414 __TRY
3416 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3418 ret = NULL;
3419 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3421 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3422 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3425 __EXCEPT_PAGE_FAULT
3427 return NULL;
3429 __ENDTRY
3430 return ret;
3433 /***********************************************************************
3434 * process_breakpoint
3436 * Trigger a debug breakpoint if the process is being debugged.
3438 static void process_breakpoint(void)
3440 DWORD_PTR port = 0;
3442 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort, &port, sizeof(port), NULL );
3443 if (!port) return;
3445 __TRY
3447 DbgBreakPoint();
3449 __EXCEPT_ALL
3451 /* do nothing */
3453 __ENDTRY
3457 /******************************************************************
3458 * LdrInitializeThunk (NTDLL.@)
3460 * Attach to all the loaded dlls.
3461 * If this is the first time, perform the full process initialization.
3463 void WINAPI LdrInitializeThunk( CONTEXT *context, ULONG_PTR unknown2, ULONG_PTR unknown3, ULONG_PTR unknown4 )
3465 static int attach_done;
3466 int i;
3467 NTSTATUS status;
3468 ULONG_PTR cookie;
3469 WINE_MODREF *wm;
3470 void **entry;
3471 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3473 #ifdef __i386__
3474 entry = (void **)&context->Eax;
3475 #elif defined(__x86_64__)
3476 entry = (void **)&context->Rcx;
3477 #elif defined(__arm__)
3478 entry = (void **)&context->R0;
3479 #elif defined(__aarch64__)
3480 entry = (void **)&context->u.s.X0;
3481 #endif
3483 if (process_detaching) NtTerminateThread( GetCurrentThread(), 0 );
3485 RtlEnterCriticalSection( &loader_section );
3487 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3488 assert( wm );
3490 if (!imports_fixup_done)
3492 actctx_init();
3493 if (wm->ldr.Flags & LDR_COR_ILONLY)
3494 status = fixup_imports_ilonly( wm, load_path, entry );
3495 else
3496 status = fixup_imports( wm, load_path );
3498 if (status)
3500 ERR( "Importing dlls for %s failed, status %x\n",
3501 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3502 NtTerminateProcess( GetCurrentProcess(), status );
3504 imports_fixup_done = TRUE;
3507 RtlAcquirePebLock();
3508 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3509 RtlReleasePebLock();
3511 NtCurrentTeb()->FlsSlots = fls_alloc_data();
3513 if (!attach_done) /* first time around */
3515 attach_done = 1;
3516 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3518 ERR( "TLS init failed when loading %s, status %x\n",
3519 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3520 NtTerminateProcess( GetCurrentProcess(), status );
3522 wm->ldr.LoadCount = -1;
3523 wm->ldr.Flags |= LDR_PROCESS_ATTACHED; /* don't try to attach again */
3524 if (wm->ldr.ActivationContext)
3525 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
3527 for (i = 0; i < wm->nDeps; i++)
3529 if (!wm->deps[i]) continue;
3530 if ((status = process_attach( wm->deps[i], context )) != STATUS_SUCCESS)
3532 if (last_failed_modref)
3533 ERR( "%s failed to initialize, aborting\n",
3534 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3535 ERR( "Initializing dlls for %s failed, status %x\n",
3536 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3537 NtTerminateProcess( GetCurrentProcess(), status );
3540 attach_implicitly_loaded_dlls( context );
3541 unix_funcs->virtual_release_address_space();
3542 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_PROCESS_ATTACH );
3543 if (wm->ldr.Flags & LDR_WINE_INTERNAL) unix_funcs->init_builtin_dll( wm->ldr.DllBase );
3544 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
3545 process_breakpoint();
3547 else
3549 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3550 NtTerminateThread( GetCurrentThread(), status );
3551 thread_attach();
3552 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_ATTACH );
3555 RtlLeaveCriticalSection( &loader_section );
3556 signal_start_thread( context );
3560 /***********************************************************************
3561 * load_global_options
3563 static void load_global_options(void)
3565 OBJECT_ATTRIBUTES attr;
3566 UNICODE_STRING name_str;
3567 HANDLE hkey;
3568 ULONG value;
3570 attr.Length = sizeof(attr);
3571 attr.RootDirectory = 0;
3572 attr.ObjectName = &name_str;
3573 attr.Attributes = OBJ_CASE_INSENSITIVE;
3574 attr.SecurityDescriptor = NULL;
3575 attr.SecurityQualityOfService = NULL;
3576 RtlInitUnicodeString( &name_str, L"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3578 if (!NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))
3580 query_dword_option( hkey, L"GlobalFlag", &NtCurrentTeb()->Peb->NtGlobalFlag );
3581 query_dword_option( hkey, L"SafeProcessSearchMode", &path_safe_mode );
3582 query_dword_option( hkey, L"SafeDllSearchMode", &dll_safe_mode );
3584 if (!query_dword_option( hkey, L"CriticalSectionTimeout", &value ))
3585 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3587 if (!query_dword_option( hkey, L"HeapSegmentReserve", &value ))
3588 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3590 if (!query_dword_option( hkey, L"HeapSegmentCommit", &value ))
3591 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3593 if (!query_dword_option( hkey, L"HeapDeCommitTotalFreeThreshold", &value ))
3594 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3596 if (!query_dword_option( hkey, L"HeapDeCommitFreeBlockThreshold", &value ))
3597 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3599 NtClose( hkey );
3601 LdrQueryImageFileExecutionOptions( &NtCurrentTeb()->Peb->ProcessParameters->ImagePathName,
3602 L"GlobalFlag", REG_DWORD, &NtCurrentTeb()->Peb->NtGlobalFlag,
3603 sizeof(DWORD), NULL );
3604 heap_set_debug_flags( GetProcessHeap() );
3608 /***********************************************************************
3609 * RtlImageDirectoryEntryToData (NTDLL.@)
3611 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3613 const IMAGE_NT_HEADERS *nt;
3614 DWORD addr;
3616 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
3617 module = (HMODULE)((ULONG_PTR)module & ~3);
3618 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3619 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3621 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3623 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3624 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3625 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3626 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3628 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3630 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3632 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3633 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3634 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3635 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3637 else return NULL;
3639 /* not mapped as image, need to find the section containing the virtual address */
3640 return RtlImageRvaToVa( nt, module, addr, NULL );
3644 /***********************************************************************
3645 * RtlImageRvaToSection (NTDLL.@)
3647 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3648 HMODULE module, DWORD rva )
3650 int i;
3651 const IMAGE_SECTION_HEADER *sec;
3653 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3654 nt->FileHeader.SizeOfOptionalHeader);
3655 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3657 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3658 return (PIMAGE_SECTION_HEADER)sec;
3660 return NULL;
3664 /***********************************************************************
3665 * RtlImageRvaToVa (NTDLL.@)
3667 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3668 DWORD rva, IMAGE_SECTION_HEADER **section )
3670 IMAGE_SECTION_HEADER *sec;
3672 if (section && *section) /* try this section first */
3674 sec = *section;
3675 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3676 goto found;
3678 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3679 found:
3680 if (section) *section = sec;
3681 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3685 /***********************************************************************
3686 * RtlPcToFileHeader (NTDLL.@)
3688 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3690 LDR_DATA_TABLE_ENTRY *module;
3691 PVOID ret = NULL;
3693 RtlEnterCriticalSection( &loader_section );
3694 if (!LdrFindEntryForAddress( pc, &module )) ret = module->DllBase;
3695 RtlLeaveCriticalSection( &loader_section );
3696 *address = ret;
3697 return ret;
3701 /****************************************************************************
3702 * LdrGetDllDirectory (NTDLL.@)
3704 NTSTATUS WINAPI LdrGetDllDirectory( UNICODE_STRING *dir )
3706 NTSTATUS status = STATUS_SUCCESS;
3708 RtlEnterCriticalSection( &dlldir_section );
3709 dir->Length = dll_directory.Length + sizeof(WCHAR);
3710 if (dir->MaximumLength >= dir->Length) RtlCopyUnicodeString( dir, &dll_directory );
3711 else
3713 status = STATUS_BUFFER_TOO_SMALL;
3714 if (dir->MaximumLength) dir->Buffer[0] = 0;
3716 RtlLeaveCriticalSection( &dlldir_section );
3717 return status;
3721 /****************************************************************************
3722 * LdrSetDllDirectory (NTDLL.@)
3724 NTSTATUS WINAPI LdrSetDllDirectory( const UNICODE_STRING *dir )
3726 NTSTATUS status = STATUS_SUCCESS;
3727 UNICODE_STRING new;
3729 if (!dir->Buffer) RtlInitUnicodeString( &new, NULL );
3730 else if ((status = RtlDuplicateUnicodeString( 1, dir, &new ))) return status;
3732 RtlEnterCriticalSection( &dlldir_section );
3733 RtlFreeUnicodeString( &dll_directory );
3734 dll_directory = new;
3735 RtlLeaveCriticalSection( &dlldir_section );
3736 return status;
3740 /****************************************************************************
3741 * LdrAddDllDirectory (NTDLL.@)
3743 NTSTATUS WINAPI LdrAddDllDirectory( const UNICODE_STRING *dir, void **cookie )
3745 FILE_BASIC_INFORMATION info;
3746 UNICODE_STRING nt_name;
3747 NTSTATUS status;
3748 OBJECT_ATTRIBUTES attr;
3749 DWORD len;
3750 struct dll_dir_entry *ptr;
3751 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir->Buffer );
3753 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
3754 return STATUS_INVALID_PARAMETER;
3756 status = RtlDosPathNameToNtPathName_U_WithStatus( dir->Buffer, &nt_name, NULL, NULL );
3757 if (status) return status;
3758 len = nt_name.Length / sizeof(WCHAR);
3759 if (!(ptr = RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] ))))
3760 return STATUS_NO_MEMORY;
3761 memcpy( ptr->dir, nt_name.Buffer, len * sizeof(WCHAR) );
3763 attr.Length = sizeof(attr);
3764 attr.RootDirectory = 0;
3765 attr.Attributes = OBJ_CASE_INSENSITIVE;
3766 attr.ObjectName = &nt_name;
3767 attr.SecurityDescriptor = NULL;
3768 attr.SecurityQualityOfService = NULL;
3769 status = NtQueryAttributesFile( &attr, &info );
3770 RtlFreeUnicodeString( &nt_name );
3772 if (!status)
3774 TRACE( "%s\n", debugstr_w( ptr->dir ));
3775 RtlEnterCriticalSection( &dlldir_section );
3776 list_add_head( &dll_dir_list, &ptr->entry );
3777 RtlLeaveCriticalSection( &dlldir_section );
3778 *cookie = ptr;
3780 else RtlFreeHeap( GetProcessHeap(), 0, ptr );
3781 return status;
3785 /****************************************************************************
3786 * LdrRemoveDllDirectory (NTDLL.@)
3788 NTSTATUS WINAPI LdrRemoveDllDirectory( void *cookie )
3790 struct dll_dir_entry *ptr = cookie;
3792 TRACE( "%s\n", debugstr_w( ptr->dir ));
3794 RtlEnterCriticalSection( &dlldir_section );
3795 list_remove( &ptr->entry );
3796 RtlFreeHeap( GetProcessHeap(), 0, ptr );
3797 RtlLeaveCriticalSection( &dlldir_section );
3798 return STATUS_SUCCESS;
3802 /*************************************************************************
3803 * LdrSetDefaultDllDirectories (NTDLL.@)
3805 NTSTATUS WINAPI LdrSetDefaultDllDirectories( ULONG flags )
3807 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
3808 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
3809 LOAD_LIBRARY_SEARCH_USER_DIRS |
3810 LOAD_LIBRARY_SEARCH_SYSTEM32 |
3811 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
3813 if (!flags || (flags & ~load_library_search_flags)) return STATUS_INVALID_PARAMETER;
3814 default_search_flags = flags;
3815 return STATUS_SUCCESS;
3819 /******************************************************************
3820 * LdrGetDllPath (NTDLL.@)
3822 NTSTATUS WINAPI LdrGetDllPath( PCWSTR module, ULONG flags, PWSTR *path, PWSTR *unknown )
3824 NTSTATUS status;
3825 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
3826 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
3827 LOAD_LIBRARY_SEARCH_USER_DIRS |
3828 LOAD_LIBRARY_SEARCH_SYSTEM32 |
3829 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
3831 if (flags & LOAD_WITH_ALTERED_SEARCH_PATH)
3833 if (flags & load_library_search_flags) return STATUS_INVALID_PARAMETER;
3834 if (default_search_flags) flags |= default_search_flags | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
3836 else if (!(flags & load_library_search_flags)) flags |= default_search_flags;
3838 RtlEnterCriticalSection( &dlldir_section );
3840 if (flags & load_library_search_flags)
3842 status = get_dll_load_path_search_flags( module, flags, path );
3844 else
3846 const WCHAR *dlldir = dll_directory.Length ? dll_directory.Buffer : NULL;
3847 if (!(flags & LOAD_WITH_ALTERED_SEARCH_PATH))
3848 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3849 status = get_dll_load_path( module, dlldir, dll_safe_mode, path );
3852 RtlLeaveCriticalSection( &dlldir_section );
3853 *unknown = NULL;
3854 return status;
3858 /*************************************************************************
3859 * RtlSetSearchPathMode (NTDLL.@)
3861 NTSTATUS WINAPI RtlSetSearchPathMode( ULONG flags )
3863 int val;
3865 switch (flags)
3867 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE:
3868 val = 1;
3869 break;
3870 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE:
3871 val = 0;
3872 break;
3873 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT:
3874 InterlockedExchange( (int *)&path_safe_mode, 2 );
3875 return STATUS_SUCCESS;
3876 default:
3877 return STATUS_INVALID_PARAMETER;
3880 for (;;)
3882 int prev = path_safe_mode;
3883 if (prev == 2) break; /* permanently set */
3884 if (InterlockedCompareExchange( (int *)&path_safe_mode, val, prev ) == prev) return STATUS_SUCCESS;
3886 return STATUS_ACCESS_DENIED;
3890 /******************************************************************
3891 * RtlGetExePath (NTDLL.@)
3893 NTSTATUS WINAPI RtlGetExePath( PCWSTR name, PWSTR *path )
3895 const WCHAR *dlldir = L".";
3896 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3898 /* same check as NeedCurrentDirectoryForExePathW */
3899 if (!wcschr( name, '\\' ))
3901 UNICODE_STRING name, value = { 0 };
3903 RtlInitUnicodeString( &name, L"NoDefaultCurrentDirectoryInExePath" );
3904 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) != STATUS_VARIABLE_NOT_FOUND)
3905 dlldir = L"";
3907 return get_dll_load_path( module, dlldir, FALSE, path );
3911 /******************************************************************
3912 * RtlGetSearchPath (NTDLL.@)
3914 NTSTATUS WINAPI RtlGetSearchPath( PWSTR *path )
3916 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3917 return get_dll_load_path( module, NULL, path_safe_mode, path );
3921 /******************************************************************
3922 * RtlReleasePath (NTDLL.@)
3924 void WINAPI RtlReleasePath( PWSTR path )
3926 RtlFreeHeap( GetProcessHeap(), 0, path );
3930 /******************************************************************
3931 * DllMain (NTDLL.@)
3933 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3935 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3936 return TRUE;
3940 /***********************************************************************
3941 * restart_winevdm
3943 static void restart_winevdm( RTL_USER_PROCESS_PARAMETERS *params )
3945 DWORD len;
3946 WCHAR *appname, *cmdline;
3948 len = wcslen(system_dir) + wcslen(L"winevdm.exe") + 1;
3949 appname = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
3950 wcscpy( appname, (is_win64 || is_wow64) ? syswow64_dir : system_dir );
3951 wcscat( appname, L"winevdm.exe" );
3953 len += 16 + wcslen(params->ImagePathName.Buffer) + wcslen(params->CommandLine.Buffer);
3954 cmdline = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
3955 swprintf( cmdline, len, L"%s --app-name \"%s\" %s",
3956 appname, params->ImagePathName.Buffer, params->CommandLine.Buffer );
3958 RtlInitUnicodeString( &params->ImagePathName, appname );
3959 RtlInitUnicodeString( &params->CommandLine, cmdline );
3963 /***********************************************************************
3964 * process_init
3966 static NTSTATUS process_init(void)
3968 RTL_USER_PROCESS_PARAMETERS *params;
3969 WINE_MODREF *wm;
3970 NTSTATUS status;
3971 ANSI_STRING func_name;
3972 UNICODE_STRING nt_name;
3973 MEMORY_BASIC_INFORMATION meminfo;
3974 INITIAL_TEB stack;
3975 TEB *teb = NtCurrentTeb();
3976 PEB *peb = teb->Peb;
3978 peb->LdrData = &ldr;
3979 peb->FastPebLock = &peb_lock;
3980 peb->TlsBitmap = &tls_bitmap;
3981 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
3982 peb->LoaderLock = &loader_section;
3983 peb->OSMajorVersion = 5;
3984 peb->OSMinorVersion = 1;
3985 peb->OSBuildNumber = 0xA28;
3986 peb->OSPlatformId = VER_PLATFORM_WIN32_NT;
3987 peb->SessionId = 1;
3988 peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
3990 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
3991 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
3992 sizeof(peb->TlsExpansionBitmapBits) * 8 );
3993 RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
3994 init_global_fls_data();
3996 InitializeListHead( &ldr.InLoadOrderModuleList );
3997 InitializeListHead( &ldr.InMemoryOrderModuleList );
3998 InitializeListHead( &ldr.InInitializationOrderModuleList );
4000 #ifndef _WIN64
4001 is_wow64 = !!NtCurrentTeb64();
4002 #endif
4004 init_unix_codepage();
4005 init_directories();
4006 init_user_process_params();
4007 params = peb->ProcessParameters;
4009 load_global_options();
4010 version_init();
4012 /* setup the load callback and create ntdll modref */
4013 RtlInitUnicodeString( &nt_name, L"\\??\\C:\\windows\\system32\\ntdll.dll" );
4014 NtQueryVirtualMemory( GetCurrentProcess(), process_init, MemoryBasicInformation,
4015 &meminfo, sizeof(meminfo), NULL );
4016 status = build_builtin_module( params->DllPath.Buffer, &nt_name, meminfo.AllocationBase, 0, &wm );
4017 assert( !status );
4019 if ((status = load_dll( params->DllPath.Buffer, L"C:\\windows\\system32\\kernel32.dll",
4020 NULL, 0, &wm )) != STATUS_SUCCESS)
4022 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
4023 NtTerminateProcess( GetCurrentProcess(), status );
4025 RtlInitAnsiString( &func_name, "BaseThreadInitThunk" );
4026 if ((status = LdrGetProcedureAddress( wm->ldr.DllBase, &func_name,
4027 0, (void **)&pBaseThreadInitThunk )) != STATUS_SUCCESS)
4029 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status );
4030 NtTerminateProcess( GetCurrentProcess(), status );
4033 init_locale( wm->ldr.DllBase );
4035 if (!(status = load_dll( params->DllPath.Buffer, params->ImagePathName.Buffer, NULL,
4036 DONT_RESOLVE_DLL_REFERENCES, &wm )))
4038 peb->ImageBaseAddress = wm->ldr.DllBase;
4039 TRACE( "main exe loaded %s at %p\n", debugstr_us(&params->ImagePathName), peb->ImageBaseAddress );
4040 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
4042 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
4043 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT );
4046 else
4048 switch (status)
4050 case STATUS_INVALID_IMAGE_NOT_MZ:
4052 WCHAR *p = wcsrchr( params->ImagePathName.Buffer, '.' );
4053 if (p && (!wcsicmp( p, L".com" ) || !wcsicmp( p, L".pif" )))
4055 restart_winevdm( params );
4056 status = STATUS_INVALID_IMAGE_WIN_16;
4058 return status;
4060 case STATUS_INVALID_IMAGE_WIN_16:
4061 case STATUS_INVALID_IMAGE_NE_FORMAT:
4062 case STATUS_INVALID_IMAGE_PROTECT:
4063 restart_winevdm( params );
4064 return status;
4065 case STATUS_CONFLICTING_ADDRESSES:
4066 case STATUS_NO_MEMORY:
4067 case STATUS_INVALID_IMAGE_FORMAT:
4068 return status;
4069 case STATUS_INVALID_IMAGE_WIN_64:
4070 ERR( "%s 64-bit application not supported in 32-bit prefix\n",
4071 debugstr_us(&params->ImagePathName) );
4072 break;
4073 case STATUS_DLL_NOT_FOUND:
4074 ERR( "%s not found\n", debugstr_us(&params->ImagePathName) );
4075 break;
4076 default:
4077 ERR( "failed to load %s, error %x\n", debugstr_us(&params->ImagePathName), status );
4078 break;
4080 NtTerminateProcess( GetCurrentProcess(), status );
4083 #ifndef _WIN64
4084 if (NtCurrentTeb64())
4086 PEB64 *peb64 = UlongToPtr( NtCurrentTeb64()->Peb );
4087 peb64->ImageBaseAddress = PtrToUlong( peb->ImageBaseAddress );
4088 peb64->OSMajorVersion = peb->OSMajorVersion;
4089 peb64->OSMinorVersion = peb->OSMinorVersion;
4090 peb64->OSBuildNumber = peb->OSBuildNumber;
4091 peb64->OSPlatformId = peb->OSPlatformId;
4092 peb64->SessionId = peb->SessionId;
4094 #endif
4096 /* the main exe needs to be the first in the load order list */
4097 RemoveEntryList( &wm->ldr.InLoadOrderLinks );
4098 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderLinks );
4099 RemoveEntryList( &wm->ldr.InMemoryOrderLinks );
4100 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderLinks );
4102 RtlCreateUserStack( 0, 0, 0, 0x10000, 0x10000, &stack );
4103 teb->Tib.StackBase = stack.StackBase;
4104 teb->Tib.StackLimit = stack.StackLimit;
4105 teb->DeallocationStack = stack.DeallocationStack;
4106 return STATUS_SUCCESS;
4109 /***********************************************************************
4110 * __wine_set_unix_funcs
4112 NTSTATUS CDECL __wine_set_unix_funcs( int version, const struct unix_funcs *funcs )
4114 assert( version == NTDLL_UNIXLIB_VERSION );
4115 unix_funcs = funcs;
4116 return process_init();