ntdll: Use STATUS_NOT_SUPPORTED for internal machine mismatch errors.
[wine.git] / dlls / ntdll / loader.c
blobfeaacea83e7521cf1c9a636459caf0ebe17a7576
1 /*
2 * Loader functions
4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
26 #include "ntstatus.h"
27 #define WIN32_NO_STATUS
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30 #include "windef.h"
31 #include "winnt.h"
32 #include "winioctl.h"
33 #include "winternl.h"
34 #include "delayloadhandler.h"
36 #include "wine/exception.h"
37 #include "wine/debug.h"
38 #include "wine/list.h"
39 #include "ntdll_misc.h"
40 #include "ddk/wdm.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(module);
43 WINE_DECLARE_DEBUG_CHANNEL(relay);
44 WINE_DECLARE_DEBUG_CHANNEL(snoop);
45 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
46 WINE_DECLARE_DEBUG_CHANNEL(imports);
48 #ifdef _WIN64
49 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
50 #endif
51 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
52 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
54 #ifdef __i386__
55 static const WCHAR pe_dir[] = L"\\i386-windows";
56 static const USHORT current_machine = IMAGE_FILE_MACHINE_I386;
57 #elif defined __x86_64__
58 static const WCHAR pe_dir[] = L"\\x86_64-windows";
59 static const USHORT current_machine = IMAGE_FILE_MACHINE_AMD64;
60 #elif defined __arm__
61 static const WCHAR pe_dir[] = L"\\arm-windows";
62 static const USHORT current_machine = IMAGE_FILE_MACHINE_ARMNT;
63 #elif defined __aarch64__
64 static const WCHAR pe_dir[] = L"\\aarch64-windows";
65 static const USHORT current_machine = IMAGE_FILE_MACHINE_ARM64;
66 #else
67 static const WCHAR pe_dir[] = L"";
68 static const USHORT current_machine = IMAGE_FILE_MACHINE_UNKNOWN;
69 #endif
71 /* we don't want to include winuser.h */
72 #define RT_MANIFEST ((ULONG_PTR)24)
73 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
75 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
76 typedef void (CALLBACK *LDRENUMPROC)(LDR_DATA_TABLE_ENTRY *, void *, BOOLEAN *);
78 void (FASTCALL *pBaseThreadInitThunk)(DWORD,LPTHREAD_START_ROUTINE,void *) = NULL;
79 NTSTATUS (WINAPI *__wine_unix_call_dispatcher)( unixlib_handle_t, unsigned int, void * ) = __wine_unix_call;
81 static DWORD (WINAPI *pCtrlRoutine)(void *);
83 SYSTEM_DLL_INIT_BLOCK LdrSystemDllInitBlock = { 0xf0 };
85 unixlib_handle_t __wine_unixlib_handle = 0;
87 /* windows directory */
88 const WCHAR windows_dir[] = L"C:\\windows";
89 /* system directory with trailing backslash */
90 const WCHAR system_dir[] = L"C:\\windows\\system32\\";
92 /* system search path */
93 static const WCHAR system_path[] = L"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
95 static BOOL is_prefix_bootstrap; /* are we bootstrapping the prefix? */
96 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
97 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
98 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
99 static LONG path_safe_mode; /* path mode set by RtlSetSearchPathMode */
100 static LONG dll_safe_mode = 1; /* dll search mode */
101 static UNICODE_STRING dll_directory; /* extra path for LdrSetDllDirectory */
102 static UNICODE_STRING system_dll_path; /* path to search for system dependency dlls */
103 static DWORD default_search_flags; /* default flags set by LdrSetDefaultDllDirectories */
104 static WCHAR *default_load_path; /* default dll search path */
106 struct dll_dir_entry
108 struct list entry;
109 WCHAR dir[1];
112 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from LdrAddDllDirectory */
114 struct ldr_notification
116 struct list entry;
117 PLDR_DLL_NOTIFICATION_FUNCTION callback;
118 void *context;
121 static struct list ldr_notifications = LIST_INIT( ldr_notifications );
123 static const char * const reason_names[] =
125 "PROCESS_DETACH",
126 "PROCESS_ATTACH",
127 "THREAD_ATTACH",
128 "THREAD_DETACH",
131 struct file_id
133 BYTE ObjectId[16];
136 /* internal representation of loaded modules */
137 typedef struct _wine_modref
139 LDR_DATA_TABLE_ENTRY ldr;
140 struct file_id id;
141 ULONG CheckSum;
142 BOOL system;
143 } WINE_MODREF;
145 static UINT tls_module_count; /* number of modules with TLS directory */
146 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
147 LIST_ENTRY tls_links = { &tls_links, &tls_links };
149 static RTL_CRITICAL_SECTION loader_section;
150 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
152 0, 0, &loader_section,
153 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
154 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
156 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
158 static CRITICAL_SECTION dlldir_section;
159 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug =
161 0, 0, &dlldir_section,
162 { &dlldir_critsect_debug.ProcessLocksList, &dlldir_critsect_debug.ProcessLocksList },
163 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
165 static CRITICAL_SECTION dlldir_section = { &dlldir_critsect_debug, -1, 0, 0, 0, 0 };
167 static RTL_CRITICAL_SECTION peb_lock;
168 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug =
170 0, 0, &peb_lock,
171 { &peb_critsect_debug.ProcessLocksList, &peb_critsect_debug.ProcessLocksList },
172 0, 0, { (DWORD_PTR)(__FILE__ ": peb_lock") }
174 static RTL_CRITICAL_SECTION peb_lock = { &peb_critsect_debug, -1, 0, 0, 0, 0 };
176 static PEB_LDR_DATA ldr =
178 sizeof(ldr), TRUE, NULL,
179 { &ldr.InLoadOrderModuleList, &ldr.InLoadOrderModuleList },
180 { &ldr.InMemoryOrderModuleList, &ldr.InMemoryOrderModuleList },
181 { &ldr.InInitializationOrderModuleList, &ldr.InInitializationOrderModuleList }
184 static RTL_BITMAP tls_bitmap;
185 static RTL_BITMAP tls_expansion_bitmap;
187 static WINE_MODREF *cached_modref;
188 static WINE_MODREF *current_modref;
189 static WINE_MODREF *last_failed_modref;
191 static LDR_DDAG_NODE *node_ntdll, *node_kernel32;
193 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, DWORD flags, WINE_MODREF** pwm, BOOL system );
194 static NTSTATUS process_attach( LDR_DDAG_NODE *node, LPVOID lpReserved );
195 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
196 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
197 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
198 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
200 /* convert PE image VirtualAddress to Real Address */
201 static inline void *get_rva( HMODULE module, DWORD va )
203 return (void *)((char *)module + va);
206 /* check whether the file name contains a path */
207 static inline BOOL contains_path( LPCWSTR name )
209 return ((*name && (name[1] == ':')) || wcschr(name, '/') || wcschr(name, '\\'));
212 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
214 typedef struct _RTL_UNLOAD_EVENT_TRACE
216 void *BaseAddress;
217 SIZE_T SizeOfImage;
218 ULONG Sequence;
219 ULONG TimeDateStamp;
220 ULONG CheckSum;
221 WCHAR ImageName[32];
222 } RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
224 static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
225 static RTL_UNLOAD_EVENT_TRACE *unload_trace_ptr;
226 static unsigned int unload_trace_seq;
228 static void module_push_unload_trace( const WINE_MODREF *wm )
230 RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
231 const LDR_DATA_TABLE_ENTRY *ldr = &wm->ldr;
232 unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
234 ptr->BaseAddress = ldr->DllBase;
235 ptr->SizeOfImage = ldr->SizeOfImage;
236 ptr->Sequence = unload_trace_seq;
237 ptr->TimeDateStamp = ldr->TimeDateStamp;
238 ptr->CheckSum = wm->CheckSum;
239 memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
240 ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
242 unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
243 unload_trace_ptr = unload_traces;
246 /*********************************************************************
247 * RtlGetUnloadEventTrace [NTDLL.@]
249 RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
251 return unload_traces;
254 /*********************************************************************
255 * RtlGetUnloadEventTraceEx [NTDLL.@]
257 void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
259 static ULONG element_size = sizeof(*unload_traces);
260 static ULONG element_count = ARRAY_SIZE(unload_traces);
262 *size = &element_size;
263 *count = &element_count;
264 *trace = &unload_trace_ptr;
267 /*************************************************************************
268 * call_dll_entry_point
270 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
271 * their entry point, so we need a small asm wrapper. Testing indicates
272 * that only modifying esi leads to a crash, so use this one to backup
273 * ebp while running the dll entry proc.
275 #if defined(__i386__)
276 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
277 __ASM_GLOBAL_FUNC(call_dll_entry_point,
278 "pushl %ebp\n\t"
279 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
280 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
281 "movl %esp,%ebp\n\t"
282 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
283 "pushl %ebx\n\t"
284 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
285 "pushl %esi\n\t"
286 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
287 "pushl %edi\n\t"
288 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
289 "movl %ebp,%esi\n\t"
290 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
291 "pushl 20(%ebp)\n\t"
292 "pushl 16(%ebp)\n\t"
293 "pushl 12(%ebp)\n\t"
294 "movl 8(%ebp),%eax\n\t"
295 "call *%eax\n\t"
296 "movl %esi,%ebp\n\t"
297 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
298 "leal -12(%ebp),%esp\n\t"
299 "popl %edi\n\t"
300 __ASM_CFI(".cfi_same_value %edi\n\t")
301 "popl %esi\n\t"
302 __ASM_CFI(".cfi_same_value %esi\n\t")
303 "popl %ebx\n\t"
304 __ASM_CFI(".cfi_same_value %ebx\n\t")
305 "popl %ebp\n\t"
306 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
307 __ASM_CFI(".cfi_same_value %ebp\n\t")
308 "ret" )
309 #elif defined(__x86_64__)
310 extern BOOL CDECL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
311 /* Some apps modify rbx in TLS entry point. */
312 __ASM_GLOBAL_FUNC(call_dll_entry_point,
313 "pushq %rbx\n\t"
314 __ASM_SEH(".seh_pushreg %rbx\n\t")
315 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
316 __ASM_CFI(".cfi_rel_offset %rbx,0\n\t")
317 "subq $48,%rsp\n\t"
318 __ASM_SEH(".seh_stackalloc 48\n\t")
319 __ASM_SEH(".seh_endprologue\n\t")
320 __ASM_CFI(".cfi_adjust_cfa_offset 48\n\t")
321 "mov %rcx,%r10\n\t"
322 "mov %rdx,%rcx\n\t"
323 "mov %r8d,%edx\n\t"
324 "mov %r9,%r8\n\t"
325 "call *%r10\n\t"
326 "addq $48,%rsp\n\t"
327 __ASM_CFI(".cfi_adjust_cfa_offset -48\n\t")
328 "popq %rbx\n\t"
329 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
330 __ASM_CFI(".cfi_same_value %rbx\n\t")
331 "ret" )
332 #else
333 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
334 UINT reason, void *reserved )
336 return proc( module, reason, reserved );
338 #endif
341 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
342 /*************************************************************************
343 * stub_entry_point
345 * Entry point for stub functions.
347 static void WINAPI stub_entry_point( const char *dll, const char *name, void *ret_addr )
349 EXCEPTION_RECORD rec;
351 rec.ExceptionCode = EXCEPTION_WINE_STUB;
352 rec.ExceptionFlags = EH_NONCONTINUABLE;
353 rec.ExceptionRecord = NULL;
354 rec.ExceptionAddress = ret_addr;
355 rec.NumberParameters = 2;
356 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
357 rec.ExceptionInformation[1] = (ULONG_PTR)name;
358 for (;;) RtlRaiseException( &rec );
362 #include "pshpack1.h"
363 #ifdef __i386__
364 struct stub
366 BYTE pushl1; /* pushl $name */
367 const char *name;
368 BYTE pushl2; /* pushl $dll */
369 const char *dll;
370 BYTE call; /* call stub_entry_point */
371 DWORD entry;
373 #elif defined(__arm__)
374 struct stub
376 DWORD ldr_r0; /* ldr r0, $dll */
377 DWORD ldr_r1; /* ldr r1, $name */
378 DWORD mov_r2_lr; /* mov r2, lr */
379 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
380 const char *dll;
381 const char *name;
382 const void* entry;
384 #elif defined(__aarch64__)
385 struct stub
387 DWORD ldr_x0; /* ldr x0, $dll */
388 DWORD ldr_x1; /* ldr x1, $name */
389 DWORD mov_x2_lr; /* mov x2, lr */
390 DWORD ldr_x16; /* ldr x16, $entry */
391 DWORD br_x16; /* br x16 */
392 const char *dll;
393 const char *name;
394 const void *entry;
396 #else
397 struct stub
399 BYTE movq_rdi[2]; /* movq $dll,%rdi */
400 const char *dll;
401 BYTE movq_rsi[2]; /* movq $name,%rsi */
402 const char *name;
403 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
404 BYTE movq_rax[2]; /* movq $entry, %rax */
405 const void* entry;
406 BYTE jmpq_rax[2]; /* jmp %rax */
408 #endif
409 #include "poppack.h"
411 /*************************************************************************
412 * allocate_stub
414 * Allocate a stub entry point.
416 static ULONG_PTR allocate_stub( const char *dll, const char *name )
418 #define MAX_SIZE 65536
419 static struct stub *stubs;
420 static unsigned int nb_stubs;
421 struct stub *stub;
423 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
425 if (!stubs)
427 SIZE_T size = MAX_SIZE;
428 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
429 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
430 return 0xdeadbeef;
432 stub = &stubs[nb_stubs++];
433 #ifdef __i386__
434 stub->pushl1 = 0x68; /* pushl $name */
435 stub->name = name;
436 stub->pushl2 = 0x68; /* pushl $dll */
437 stub->dll = dll;
438 stub->call = 0xe8; /* call stub_entry_point */
439 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
440 #elif defined(__arm__)
441 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
442 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
443 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
444 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
445 stub->dll = dll;
446 stub->name = name;
447 stub->entry = stub_entry_point;
448 #elif defined(__aarch64__)
449 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
450 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
451 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
452 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
453 stub->br_x16 = 0xd61f0200; /* br x16 */
454 stub->dll = dll;
455 stub->name = name;
456 stub->entry = stub_entry_point;
457 #else
458 stub->movq_rdi[0] = 0x48; /* movq $dll,%rcx */
459 stub->movq_rdi[1] = 0xb9;
460 stub->dll = dll;
461 stub->movq_rsi[0] = 0x48; /* movq $name,%rdx */
462 stub->movq_rsi[1] = 0xba;
463 stub->name = name;
464 stub->movq_rsp_rdx[0] = 0x4c; /* movq (%rsp),%r8 */
465 stub->movq_rsp_rdx[1] = 0x8b;
466 stub->movq_rsp_rdx[2] = 0x04;
467 stub->movq_rsp_rdx[3] = 0x24;
468 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
469 stub->movq_rax[1] = 0xb8;
470 stub->entry = stub_entry_point;
471 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
472 stub->jmpq_rax[1] = 0xe0;
473 #endif
474 return (ULONG_PTR)stub;
477 #else /* __i386__ */
478 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
479 #endif /* __i386__ */
481 /* call ldr notifications */
482 static void call_ldr_notifications( ULONG reason, LDR_DATA_TABLE_ENTRY *module )
484 struct ldr_notification *notify, *notify_next;
485 LDR_DLL_NOTIFICATION_DATA data;
487 data.Loaded.Flags = 0;
488 data.Loaded.FullDllName = &module->FullDllName;
489 data.Loaded.BaseDllName = &module->BaseDllName;
490 data.Loaded.DllBase = module->DllBase;
491 data.Loaded.SizeOfImage = module->SizeOfImage;
493 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
495 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%lu,data=%p,context=%p)\n",
496 notify->callback, reason, &data, notify->context );
498 notify->callback(reason, &data, notify->context);
500 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%lu,data=%p,context=%p)\n",
501 notify->callback, reason, &data, notify->context );
505 /*************************************************************************
506 * get_modref
508 * Looks for the referenced HMODULE in the current process
509 * The loader_section must be locked while calling this function.
511 static WINE_MODREF *get_modref( HMODULE hmod )
513 PLIST_ENTRY mark, entry;
514 PLDR_DATA_TABLE_ENTRY mod;
516 if (cached_modref && cached_modref->ldr.DllBase == hmod) return cached_modref;
518 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
519 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
521 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
522 if (mod->DllBase == hmod)
523 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
525 return NULL;
529 /**********************************************************************
530 * find_basename_module
532 * Find a module from its base name.
533 * The loader_section must be locked while calling this function
535 static WINE_MODREF *find_basename_module( LPCWSTR name )
537 PLIST_ENTRY mark, entry;
538 UNICODE_STRING name_str;
540 RtlInitUnicodeString( &name_str, name );
542 if (cached_modref && RtlEqualUnicodeString( &name_str, &cached_modref->ldr.BaseDllName, TRUE ))
543 return cached_modref;
545 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
546 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
548 WINE_MODREF *mod = CONTAINING_RECORD(entry, WINE_MODREF, ldr.InLoadOrderLinks);
549 if (RtlEqualUnicodeString( &name_str, &mod->ldr.BaseDllName, TRUE ) && !mod->system)
551 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
552 return cached_modref;
555 return NULL;
559 /**********************************************************************
560 * find_fullname_module
562 * Find a module from its full path name.
563 * The loader_section must be locked while calling this function
565 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
567 PLIST_ENTRY mark, entry;
568 UNICODE_STRING name = *nt_name;
570 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
571 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
572 name.Buffer += 4;
574 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
575 return cached_modref;
577 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
578 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
580 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
581 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
583 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
584 return cached_modref;
587 return NULL;
591 /**********************************************************************
592 * find_fileid_module
594 * Find a module from its file id.
595 * The loader_section must be locked while calling this function
597 static WINE_MODREF *find_fileid_module( const struct file_id *id )
599 LIST_ENTRY *mark, *entry;
601 if (cached_modref && !memcmp( &cached_modref->id, id, sizeof(*id) )) return cached_modref;
603 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
604 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
606 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
607 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
609 if (!memcmp( &wm->id, id, sizeof(*id) ))
611 cached_modref = wm;
612 return wm;
615 return NULL;
619 /******************************************************************************
620 * get_apiset_entry
622 static NTSTATUS get_apiset_entry( const API_SET_NAMESPACE *map, const WCHAR *name, ULONG len,
623 const API_SET_NAMESPACE_ENTRY **entry )
625 const API_SET_HASH_ENTRY *hash_entry;
626 ULONG hash, i, hash_len;
627 int min, max;
629 if (len <= 4) return STATUS_INVALID_PARAMETER;
630 if (wcsnicmp( name, L"api-", 4 ) && wcsnicmp( name, L"ext-", 4 )) return STATUS_INVALID_PARAMETER;
631 if (!map) return STATUS_APISET_NOT_PRESENT;
633 for (i = hash_len = 0; i < len; i++)
635 if (name[i] == '.') break;
636 if (name[i] == '-') hash_len = i;
638 for (i = hash = 0; i < hash_len; i++)
639 hash = hash * map->HashFactor + ((name[i] >= 'A' && name[i] <= 'Z') ? name[i] + 32 : name[i]);
641 hash_entry = (API_SET_HASH_ENTRY *)((char *)map + map->HashOffset);
642 min = 0;
643 max = map->Count - 1;
644 while (min <= max)
646 int pos = (min + max) / 2;
647 if (hash_entry[pos].Hash < hash) min = pos + 1;
648 else if (hash_entry[pos].Hash > hash) max = pos - 1;
649 else
651 *entry = (API_SET_NAMESPACE_ENTRY *)((char *)map + map->EntryOffset) + hash_entry[pos].Index;
652 if ((*entry)->HashedLength != hash_len * sizeof(WCHAR)) break;
653 if (wcsnicmp( (WCHAR *)((char *)map + (*entry)->NameOffset), name, hash_len )) break;
654 return STATUS_SUCCESS;
657 return STATUS_APISET_NOT_PRESENT;
661 /******************************************************************************
662 * get_apiset_target
664 static NTSTATUS get_apiset_target( const API_SET_NAMESPACE *map, const API_SET_NAMESPACE_ENTRY *entry,
665 const WCHAR *host, UNICODE_STRING *ret )
667 const API_SET_VALUE_ENTRY *value = (API_SET_VALUE_ENTRY *)((char *)map + entry->ValueOffset);
668 ULONG i, len;
670 if (!entry->ValueCount) return STATUS_DLL_NOT_FOUND;
671 if (host)
673 /* look for specific host in entries 1..n, entry 0 is the default */
674 for (i = 1; i < entry->ValueCount; i++)
676 len = value[i].NameLength / sizeof(WCHAR);
677 if (!wcsnicmp( host, (WCHAR *)((char *)map + value[i].NameOffset), len ) && !host[len])
679 value += i;
680 break;
684 if (!value->ValueOffset) return STATUS_DLL_NOT_FOUND;
685 ret->Buffer = (WCHAR *)((char *)map + value->ValueOffset);
686 ret->Length = value->ValueLength;
687 return STATUS_SUCCESS;
691 /**********************************************************************
692 * build_import_name
694 static NTSTATUS build_import_name( WCHAR buffer[256], const char *import, int len )
696 const API_SET_NAMESPACE *map = NtCurrentTeb()->Peb->ApiSetMap;
697 const API_SET_NAMESPACE_ENTRY *entry;
698 const WCHAR *host = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
699 UNICODE_STRING str;
701 while (len && import[len-1] == ' ') len--; /* remove trailing spaces */
702 if (len + sizeof(".dll") > 256) return STATUS_DLL_NOT_FOUND;
703 ascii_to_unicode( buffer, import, len );
704 buffer[len] = 0;
705 if (!wcschr( buffer, '.' )) wcscpy( buffer + len, L".dll" );
707 if (get_apiset_entry( map, buffer, wcslen(buffer), &entry )) return STATUS_SUCCESS;
709 if (get_apiset_target( map, entry, host, &str )) return STATUS_DLL_NOT_FOUND;
710 if (str.Length >= 256 * sizeof(WCHAR)) return STATUS_DLL_NOT_FOUND;
712 TRACE( "found %s for %s\n", debugstr_us(&str), debugstr_w(buffer));
713 memcpy( buffer, str.Buffer, str.Length );
714 buffer[str.Length / sizeof(WCHAR)] = 0;
715 return STATUS_SUCCESS;
719 /**********************************************************************
720 * append_dll_ext
722 static WCHAR *append_dll_ext( const WCHAR *name )
724 const WCHAR *ext = wcsrchr( name, '.' );
726 if (!ext || wcschr( ext, '/' ) || wcschr( ext, '\\'))
728 WCHAR *ret = RtlAllocateHeap( GetProcessHeap(), 0,
729 wcslen(name) * sizeof(WCHAR) + sizeof(L".dll") );
730 if (!ret) return NULL;
731 wcscpy( ret, name );
732 wcscat( ret, L".dll" );
733 return ret;
735 return NULL;
739 /***********************************************************************
740 * is_import_dll_system
742 static BOOL is_import_dll_system( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_IMPORT_DESCRIPTOR *import )
744 const char *name = get_rva( mod->DllBase, import->Name );
746 return !_stricmp( name, "ntdll.dll" ) || !_stricmp( name, "kernel32.dll" );
749 /**********************************************************************
750 * insert_single_list_tail
752 static void insert_single_list_after( LDRP_CSLIST *list, SINGLE_LIST_ENTRY *prev, SINGLE_LIST_ENTRY *entry )
754 if (!list->Tail)
756 assert( !prev );
757 entry->Next = entry;
758 list->Tail = entry;
759 return;
761 if (!prev)
763 /* Insert at head. */
764 entry->Next = list->Tail->Next;
765 list->Tail->Next = entry;
766 return;
768 entry->Next = prev->Next;
769 prev->Next = entry;
770 if (prev == list->Tail) list->Tail = entry;
773 /**********************************************************************
774 * remove_single_list_entry
776 static void remove_single_list_entry( LDRP_CSLIST *list, SINGLE_LIST_ENTRY *entry )
778 SINGLE_LIST_ENTRY *prev;
780 assert( list->Tail );
782 if (entry->Next == entry)
784 assert( list->Tail == entry );
785 list->Tail = NULL;
786 return;
789 prev = list->Tail->Next;
790 while (prev->Next != entry && prev != list->Tail)
791 prev = prev->Next;
792 assert( prev->Next == entry );
793 prev->Next = entry->Next;
794 if (list->Tail == entry) list->Tail = prev;
795 entry->Next = NULL;
798 /**********************************************************************
799 * add_module_dependency_after
801 static BOOL add_module_dependency_after( LDR_DDAG_NODE *from, LDR_DDAG_NODE *to,
802 SINGLE_LIST_ENTRY *dep_after )
804 LDR_DEPENDENCY *dep;
806 if (!(dep = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*dep) ))) return FALSE;
808 dep->dependency_from = from;
809 insert_single_list_after( &from->Dependencies, dep_after, &dep->dependency_to_entry );
810 dep->dependency_to = to;
811 insert_single_list_after( &to->IncomingDependencies, NULL, &dep->dependency_from_entry );
813 return TRUE;
816 /**********************************************************************
817 * add_module_dependency
819 static BOOL add_module_dependency( LDR_DDAG_NODE *from, LDR_DDAG_NODE *to )
821 return add_module_dependency_after( from, to, from->Dependencies.Tail );
824 /**********************************************************************
825 * remove_module_dependency
827 static void remove_module_dependency( LDR_DEPENDENCY *dep )
829 remove_single_list_entry( &dep->dependency_to->IncomingDependencies, &dep->dependency_from_entry );
830 remove_single_list_entry( &dep->dependency_from->Dependencies, &dep->dependency_to_entry );
831 RtlFreeHeap( GetProcessHeap(), 0, dep );
834 /**********************************************************************
835 * walk_node_dependencies
837 static NTSTATUS walk_node_dependencies( LDR_DDAG_NODE *node, void *context,
838 NTSTATUS (*callback)( LDR_DDAG_NODE *, void * ))
840 SINGLE_LIST_ENTRY *entry;
841 LDR_DEPENDENCY *dep;
842 NTSTATUS status;
844 if (!(entry = node->Dependencies.Tail)) return STATUS_SUCCESS;
848 entry = entry->Next;
849 dep = CONTAINING_RECORD( entry, LDR_DEPENDENCY, dependency_to_entry );
850 assert( dep->dependency_from == node );
851 if ((status = callback( dep->dependency_to, context ))) break;
852 } while (entry != node->Dependencies.Tail);
854 return status;
857 /*************************************************************************
858 * find_forwarded_export
860 * Find the final function pointer for a forwarded function.
861 * The loader_section must be locked while calling this function.
863 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
865 const IMAGE_EXPORT_DIRECTORY *exports;
866 DWORD exp_size;
867 WINE_MODREF *wm;
868 WCHAR mod_name[256];
869 const char *end = strrchr(forward, '.');
870 FARPROC proc = NULL;
872 if (!end) return NULL;
873 if (build_import_name( mod_name, forward, end - forward )) return NULL;
875 if (!(wm = find_basename_module( mod_name )))
877 WINE_MODREF *imp = get_modref( module );
878 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
879 if (load_dll( load_path, mod_name, 0, &wm, imp->system ) == STATUS_SUCCESS &&
880 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
882 if (!imports_fixup_done && current_modref)
884 add_module_dependency( current_modref->ldr.DdagNode, wm->ldr.DdagNode );
886 else if (process_attach( wm->ldr.DdagNode, NULL ) != STATUS_SUCCESS)
888 LdrUnloadDll( wm->ldr.DllBase );
889 wm = NULL;
893 if (!wm)
895 ERR( "module not found for forward '%s' used by %s\n",
896 forward, debugstr_w(imp->ldr.FullDllName.Buffer) );
897 return NULL;
900 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
901 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
903 const char *name = end + 1;
905 if (*name == '#') { /* ordinal */
906 proc = find_ordinal_export( wm->ldr.DllBase, exports, exp_size,
907 atoi(name+1) - exports->Base, load_path );
908 } else
909 proc = find_named_export( wm->ldr.DllBase, exports, exp_size, name, -1, load_path );
912 if (!proc)
914 ERR("function not found for forward '%s' used by %s."
915 " If you are using builtin %s, try using the native one instead.\n",
916 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
917 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
919 return proc;
923 /*************************************************************************
924 * find_ordinal_export
926 * Find an exported function by ordinal.
927 * The exports base must have been subtracted from the ordinal already.
928 * The loader_section must be locked while calling this function.
930 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
931 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
933 FARPROC proc;
934 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
936 if (ordinal >= exports->NumberOfFunctions)
938 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
939 return NULL;
941 if (!functions[ordinal]) return NULL;
943 proc = get_rva( module, functions[ordinal] );
945 /* if the address falls into the export dir, it's a forward */
946 if (((const char *)proc >= (const char *)exports) &&
947 ((const char *)proc < (const char *)exports + exp_size))
948 return find_forwarded_export( module, (const char *)proc, load_path );
950 if (TRACE_ON(snoop))
952 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
953 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
955 if (TRACE_ON(relay))
957 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
958 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
960 return proc;
964 /*************************************************************************
965 * find_name_in_exports
967 * Helper for find_named_export.
969 static int find_name_in_exports( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports, const char *name )
971 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
972 const DWORD *names = get_rva( module, exports->AddressOfNames );
973 int min = 0, max = exports->NumberOfNames - 1;
975 while (min <= max)
977 int res, pos = (min + max) / 2;
978 char *ename = get_rva( module, names[pos] );
979 if (!(res = strcmp( ename, name ))) return ordinals[pos];
980 if (res > 0) max = pos - 1;
981 else min = pos + 1;
983 return -1;
987 /*************************************************************************
988 * find_named_export
990 * Find an exported function by name.
991 * The loader_section must be locked while calling this function.
993 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
994 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
996 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
997 const DWORD *names = get_rva( module, exports->AddressOfNames );
998 int ordinal;
1000 /* first check the hint */
1001 if (hint >= 0 && hint < exports->NumberOfNames)
1003 char *ename = get_rva( module, names[hint] );
1004 if (!strcmp( ename, name ))
1005 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
1008 /* then do a binary search */
1009 if ((ordinal = find_name_in_exports( module, exports, name )) == -1) return NULL;
1010 return find_ordinal_export( module, exports, exp_size, ordinal, load_path );
1015 /*************************************************************************
1016 * RtlFindExportedRoutineByName
1018 void * WINAPI RtlFindExportedRoutineByName( HMODULE module, const char *name )
1020 const IMAGE_EXPORT_DIRECTORY *exports;
1021 const DWORD *functions;
1022 DWORD exp_size;
1023 int ordinal;
1025 exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
1026 if (!exports || exp_size < sizeof(*exports)) return NULL;
1028 if ((ordinal = find_name_in_exports( module, exports, name )) == -1) return NULL;
1029 if (ordinal >= exports->NumberOfFunctions) return NULL;
1030 functions = get_rva( module, exports->AddressOfFunctions );
1031 if (!functions[ordinal]) return NULL;
1032 return get_rva( module, functions[ordinal] );
1036 /*************************************************************************
1037 * import_dll
1039 * Import the dll specified by the given import descriptor.
1040 * The loader_section must be locked while calling this function.
1042 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
1044 BOOL system = current_modref->system || (current_modref->ldr.Flags & LDR_WINE_INTERNAL);
1045 NTSTATUS status;
1046 WINE_MODREF *wmImp;
1047 HMODULE imp_mod;
1048 const IMAGE_EXPORT_DIRECTORY *exports;
1049 DWORD exp_size;
1050 const IMAGE_THUNK_DATA *import_list;
1051 IMAGE_THUNK_DATA *thunk_list;
1052 WCHAR buffer[256];
1053 const char *name = get_rva( module, descr->Name );
1054 DWORD len = strlen(name);
1055 PVOID protect_base;
1056 SIZE_T protect_size = 0;
1057 DWORD protect_old;
1059 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
1060 if (descr->u.OriginalFirstThunk)
1061 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
1062 else
1063 import_list = thunk_list;
1065 if (!import_list->u1.Ordinal)
1067 WARN( "Skipping unused import %s\n", name );
1068 *pwm = NULL;
1069 return TRUE;
1072 status = build_import_name( buffer, name, len );
1073 if (!status) status = load_dll( load_path, buffer, 0, &wmImp, system );
1075 if (status)
1077 if (status == STATUS_DLL_NOT_FOUND)
1078 ERR("Library %s (which is needed by %s) not found\n",
1079 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
1080 else
1081 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
1082 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
1083 return FALSE;
1086 /* unprotect the import address table since it can be located in
1087 * readonly section */
1088 while (import_list[protect_size].u1.Ordinal) protect_size++;
1089 protect_base = thunk_list;
1090 protect_size *= sizeof(*thunk_list);
1091 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
1092 &protect_size, PAGE_READWRITE, &protect_old );
1094 imp_mod = wmImp->ldr.DllBase;
1095 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
1097 if (!exports)
1099 /* set all imported function to deadbeef */
1100 while (import_list->u1.Ordinal)
1102 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
1104 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
1105 WARN("No implementation for %s.%d", name, ordinal );
1106 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
1108 else
1110 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
1111 WARN("No implementation for %s.%s", name, pe_name->Name );
1112 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
1114 WARN(" imported from %s, allocating stub %p\n",
1115 debugstr_w(current_modref->ldr.FullDllName.Buffer),
1116 (void *)thunk_list->u1.Function );
1117 import_list++;
1118 thunk_list++;
1120 goto done;
1123 while (import_list->u1.Ordinal)
1125 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
1127 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
1129 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
1130 ordinal - exports->Base, load_path );
1131 if (!thunk_list->u1.Function)
1133 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
1134 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
1135 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
1136 (void *)thunk_list->u1.Function );
1138 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
1140 else /* import by name */
1142 IMAGE_IMPORT_BY_NAME *pe_name;
1143 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
1144 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
1145 (const char*)pe_name->Name,
1146 pe_name->Hint, load_path );
1147 if (!thunk_list->u1.Function)
1149 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
1150 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
1151 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
1152 (void *)thunk_list->u1.Function );
1154 TRACE_(imports)("--- %s %s.%d = %p\n",
1155 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
1157 import_list++;
1158 thunk_list++;
1161 done:
1162 /* restore old protection of the import address table */
1163 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
1164 *pwm = wmImp;
1165 return TRUE;
1169 /***********************************************************************
1170 * create_module_activation_context
1172 static NTSTATUS create_module_activation_context( LDR_DATA_TABLE_ENTRY *module )
1174 NTSTATUS status;
1175 LDR_RESOURCE_INFO info;
1176 const IMAGE_RESOURCE_DATA_ENTRY *entry;
1178 info.Type = RT_MANIFEST;
1179 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
1180 info.Language = 0;
1181 if (!(status = LdrFindResource_U( module->DllBase, &info, 3, &entry )))
1183 ACTCTXW ctx;
1184 ctx.cbSize = sizeof(ctx);
1185 ctx.lpSource = NULL;
1186 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
1187 ctx.hModule = module->DllBase;
1188 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
1189 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
1191 return status;
1195 /*************************************************************************
1196 * is_dll_native_subsystem
1198 * Check if dll is a proper native driver.
1199 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
1200 * while being perfectly normal DLLs. This heuristic should catch such breakages.
1202 static BOOL is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
1204 const IMAGE_IMPORT_DESCRIPTOR *imports;
1205 DWORD i, size;
1207 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
1208 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
1209 if (mod->Flags & LDR_WINE_INTERNAL) return TRUE;
1211 if ((imports = RtlImageDirectoryEntryToData( mod->DllBase, TRUE,
1212 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1214 for (i = 0; imports[i].Name; i++)
1215 if (is_import_dll_system( mod, &imports[i] ))
1217 TRACE( "%s imports system dll, assuming not native\n", debugstr_w(filename) );
1218 return FALSE;
1221 return TRUE;
1224 /*************************************************************************
1225 * alloc_tls_slot
1227 * Allocate a TLS slot for a newly-loaded module.
1228 * The loader_section must be locked while calling this function.
1230 static BOOL alloc_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1232 const IMAGE_TLS_DIRECTORY *dir;
1233 ULONG i, size;
1234 void *new_ptr;
1235 LIST_ENTRY *entry;
1237 if (!(dir = RtlImageDirectoryEntryToData( mod->DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
1238 return FALSE;
1240 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1241 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return FALSE;
1243 for (i = 0; i < tls_module_count; i++)
1245 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
1246 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
1247 break;
1250 TRACE( "module %p data %p-%p zerofill %lu index %p callback %p flags %lx -> slot %lu\n", mod->DllBase,
1251 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
1252 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
1254 if (i == tls_module_count)
1256 UINT new_count = max( 32, tls_module_count * 2 );
1258 if (!tls_dirs)
1259 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
1260 else
1261 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
1262 new_count * sizeof(*tls_dirs) );
1263 if (!new_ptr) return FALSE;
1265 /* resize the pointer block in all running threads */
1266 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1268 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1269 void **old = teb->ThreadLocalStoragePointer;
1270 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
1272 if (!new) return FALSE;
1273 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
1274 teb->ThreadLocalStoragePointer = new;
1275 #ifdef __x86_64__ /* macOS-specific hack */
1276 if (teb->Instrumentation[0]) ((TEB *)teb->Instrumentation[0])->ThreadLocalStoragePointer = new;
1277 #endif
1278 TRACE( "thread %04lx tls block %p -> %p\n", HandleToULong(teb->ClientId.UniqueThread), old, new );
1279 /* FIXME: can't free old block here, should be freed at thread exit */
1282 tls_dirs = new_ptr;
1283 tls_module_count = new_count;
1286 /* allocate the data block in all running threads */
1287 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1289 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1291 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
1292 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
1293 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
1295 TRACE( "thread %04lx slot %lu: %lu/%lu bytes at %p\n",
1296 HandleToULong(teb->ClientId.UniqueThread), i, size, dir->SizeOfZeroFill, new_ptr );
1298 RtlFreeHeap( GetProcessHeap(), 0,
1299 InterlockedExchangePointer( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
1302 *(DWORD *)dir->AddressOfIndex = i;
1303 tls_dirs[i] = *dir;
1304 return TRUE;
1308 /*************************************************************************
1309 * free_tls_slot
1311 * Free the module TLS slot on unload.
1312 * The loader_section must be locked while calling this function.
1314 static void free_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1316 const IMAGE_TLS_DIRECTORY *dir;
1317 ULONG i, size;
1319 if (mod->TlsIndex != -1)
1320 return;
1321 if (!(dir = RtlImageDirectoryEntryToData( mod->DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
1322 return;
1324 i = *(ULONG*)dir->AddressOfIndex;
1325 assert( i < tls_module_count );
1326 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
1330 /****************************************************************
1331 * fixup_imports_ilonly
1333 * Fixup imports for an IL-only module. All we do is import mscoree.
1334 * The loader_section must be locked while calling this function.
1336 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
1338 NTSTATUS status;
1339 void *proc;
1340 const char *name;
1341 WINE_MODREF *prev, *imp;
1343 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1344 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1346 prev = current_modref;
1347 current_modref = wm;
1348 assert( !wm->ldr.DdagNode->Dependencies.Tail );
1349 if (!(status = load_dll( load_path, L"mscoree.dll", 0, &imp, FALSE ))
1350 && !add_module_dependency_after( wm->ldr.DdagNode, imp->ldr.DdagNode, NULL ))
1351 status = STATUS_NO_MEMORY;
1352 current_modref = prev;
1353 if (status)
1355 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1356 debugstr_w(wm->ldr.BaseDllName.Buffer) );
1357 return status;
1360 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1362 name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
1363 if (!(proc = RtlFindExportedRoutineByName( imp->ldr.DllBase, name ))) return STATUS_PROCEDURE_NOT_FOUND;
1364 *entry = proc;
1365 return STATUS_SUCCESS;
1369 /****************************************************************
1370 * fixup_imports
1372 * Fixup all imports of a given module.
1373 * The loader_section must be locked while calling this function.
1375 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1377 const IMAGE_IMPORT_DESCRIPTOR *imports;
1378 SINGLE_LIST_ENTRY *dep_after;
1379 WINE_MODREF *prev, *imp;
1380 int i, nb_imports;
1381 DWORD size;
1382 NTSTATUS status;
1383 ULONG_PTR cookie;
1385 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1386 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1388 if (alloc_tls_slot( &wm->ldr )) wm->ldr.TlsIndex = -1;
1390 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
1391 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1392 return STATUS_SUCCESS;
1394 nb_imports = 0;
1395 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1397 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1399 if (!create_module_activation_context( &wm->ldr ))
1400 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1402 /* load the imported modules. They are automatically
1403 * added to the modref list of the process.
1405 prev = current_modref;
1406 current_modref = wm;
1407 status = STATUS_SUCCESS;
1408 for (i = 0; i < nb_imports; i++)
1410 dep_after = wm->ldr.DdagNode->Dependencies.Tail;
1411 if (!import_dll( wm->ldr.DllBase, &imports[i], load_path, &imp ))
1412 status = STATUS_DLL_NOT_FOUND;
1413 else if (imp && imp->ldr.DdagNode != node_ntdll && imp->ldr.DdagNode != node_kernel32)
1414 add_module_dependency_after( wm->ldr.DdagNode, imp->ldr.DdagNode, dep_after );
1416 current_modref = prev;
1417 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1418 return status;
1422 /*************************************************************************
1423 * alloc_module
1425 * Allocate a WINE_MODREF structure and add it to the process list
1426 * The loader_section must be locked while calling this function.
1428 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name, BOOL builtin )
1430 WCHAR *buffer;
1431 WINE_MODREF *wm;
1432 const WCHAR *p;
1433 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1435 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1437 wm->ldr.DllBase = hModule;
1438 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1439 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS | (builtin ? LDR_WINE_INTERNAL : 0);
1440 wm->ldr.TlsIndex = 0;
1441 wm->ldr.LoadCount = 1;
1442 wm->CheckSum = nt->OptionalHeader.CheckSum;
1443 wm->ldr.TimeDateStamp = nt->FileHeader.TimeDateStamp;
1445 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, nt_name->Length - 3 * sizeof(WCHAR) )))
1447 RtlFreeHeap( GetProcessHeap(), 0, wm );
1448 return NULL;
1451 if (!(wm->ldr.DdagNode = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm->ldr.DdagNode) )))
1453 RtlFreeHeap( GetProcessHeap(), 0, buffer );
1454 RtlFreeHeap( GetProcessHeap(), 0, wm );
1455 return NULL;
1457 InitializeListHead(&wm->ldr.DdagNode->Modules);
1458 InsertTailList(&wm->ldr.DdagNode->Modules, &wm->ldr.NodeModuleLink);
1460 memcpy( buffer, nt_name->Buffer + 4 /* \??\ prefix */, nt_name->Length - 4 * sizeof(WCHAR) );
1461 buffer[nt_name->Length/sizeof(WCHAR) - 4] = 0;
1462 if ((p = wcsrchr( buffer, '\\' ))) p++;
1463 else p = buffer;
1464 RtlInitUnicodeString( &wm->ldr.FullDllName, buffer );
1465 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1467 if (!is_dll_native_subsystem( &wm->ldr, nt, p ))
1469 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1470 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1471 if (nt->OptionalHeader.AddressOfEntryPoint)
1472 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1475 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1476 &wm->ldr.InLoadOrderLinks);
1477 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1478 &wm->ldr.InMemoryOrderLinks);
1479 /* wait until init is called for inserting into InInitializationOrderModuleList */
1481 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1483 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1484 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1485 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1487 return wm;
1491 /*************************************************************************
1492 * alloc_thread_tls
1494 * Allocate the per-thread structure for module TLS storage.
1496 static NTSTATUS alloc_thread_tls(void)
1498 void **pointers;
1499 UINT i, size;
1501 if (!tls_module_count) return STATUS_SUCCESS;
1503 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1504 tls_module_count * sizeof(*pointers) )))
1505 return STATUS_NO_MEMORY;
1507 for (i = 0; i < tls_module_count; i++)
1509 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1511 if (!dir) continue;
1512 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1513 if (!size && !dir->SizeOfZeroFill) continue;
1515 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1517 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1518 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1519 return STATUS_NO_MEMORY;
1521 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1522 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1524 TRACE( "slot %u: %u/%lu bytes at %p\n", i, size, dir->SizeOfZeroFill, pointers[i] );
1526 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1527 #ifdef __x86_64__ /* macOS-specific hack */
1528 if (NtCurrentTeb()->Instrumentation[0])
1529 ((TEB *)NtCurrentTeb()->Instrumentation[0])->ThreadLocalStoragePointer = pointers;
1530 #endif
1531 return STATUS_SUCCESS;
1535 /*************************************************************************
1536 * call_tls_callbacks
1538 static void call_tls_callbacks( HMODULE module, UINT reason )
1540 const IMAGE_TLS_DIRECTORY *dir;
1541 const PIMAGE_TLS_CALLBACK *callback;
1542 ULONG dirsize;
1544 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1545 if (!dir || !dir->AddressOfCallBacks) return;
1547 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1549 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1550 *callback, module, reason_names[reason] );
1551 __TRY
1553 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1555 __EXCEPT_ALL
1557 TRACE_(relay)("\1exception %08lx in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1558 GetExceptionCode(), callback, module, reason_names[reason] );
1559 return;
1561 __ENDTRY
1562 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1563 *callback, module, reason_names[reason] );
1567 /*************************************************************************
1568 * MODULE_InitDLL
1570 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1572 WCHAR mod_name[64];
1573 NTSTATUS status = STATUS_SUCCESS;
1574 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1575 void *module = wm->ldr.DllBase;
1576 BOOL retv = FALSE;
1578 /* Skip calls for modules loaded with special load flags */
1580 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1581 if (wm->ldr.TlsIndex == -1) call_tls_callbacks( wm->ldr.DllBase, reason );
1582 if (!entry) return STATUS_SUCCESS;
1584 if (TRACE_ON(relay))
1586 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1587 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1588 mod_name[len / sizeof(WCHAR)] = 0;
1589 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1590 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1592 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1593 reason_names[reason], lpReserved );
1595 __TRY
1597 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1598 if (!retv)
1599 status = STATUS_DLL_INIT_FAILED;
1601 __EXCEPT_ALL
1603 status = GetExceptionCode();
1604 TRACE_(relay)("\1exception %08lx in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1605 status, entry, module, reason_names[reason], lpReserved );
1607 __ENDTRY
1609 /* The state of the module list may have changed due to the call
1610 to the dll. We cannot assume that this module has not been
1611 deleted. */
1612 if (TRACE_ON(relay))
1613 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1614 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1615 else
1616 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1618 return status;
1622 /*************************************************************************
1623 * process_attach
1625 * Send the process attach notification to all DLLs the given module
1626 * depends on (recursively). This is somewhat complicated due to the fact that
1628 * - we have to respect the module dependencies, i.e. modules implicitly
1629 * referenced by another module have to be initialized before the module
1630 * itself can be initialized
1632 * - the initialization routine of a DLL can itself call LoadLibrary,
1633 * thereby introducing a whole new set of dependencies (even involving
1634 * the 'old' modules) at any time during the whole process
1636 * (Note that this routine can be recursively entered not only directly
1637 * from itself, but also via LoadLibrary from one of the called initialization
1638 * routines.)
1640 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1641 * the process *detach* notifications to be sent in the correct order.
1642 * This must not only take into account module dependencies, but also
1643 * 'hidden' dependencies created by modules calling LoadLibrary in their
1644 * attach notification routine.
1646 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1647 * list after the attach notification has returned. This implies that the
1648 * detach notifications are called in the reverse of the sequence the attach
1649 * notifications *returned*.
1651 * The loader_section must be locked while calling this function.
1653 static NTSTATUS process_attach( LDR_DDAG_NODE *node, LPVOID lpReserved )
1655 NTSTATUS status = STATUS_SUCCESS;
1656 LDR_DATA_TABLE_ENTRY *mod;
1657 ULONG_PTR cookie;
1658 WINE_MODREF *wm;
1660 if (process_detaching) return status;
1662 mod = CONTAINING_RECORD( node->Modules.Flink, LDR_DATA_TABLE_ENTRY, NodeModuleLink );
1663 wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
1665 /* prevent infinite recursion in case of cyclical dependencies */
1666 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1667 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1668 return status;
1670 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1672 /* Tag current MODREF to prevent recursive loop */
1673 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1674 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1675 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1677 /* Recursively attach all DLLs this one depends on */
1678 status = walk_node_dependencies( node, lpReserved, process_attach );
1680 if (!wm->ldr.InInitializationOrderLinks.Flink)
1681 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1682 &wm->ldr.InInitializationOrderLinks);
1684 /* Call DLL entry point */
1685 if (status == STATUS_SUCCESS)
1687 WINE_MODREF *prev = current_modref;
1688 current_modref = wm;
1690 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1691 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1692 if (status == STATUS_SUCCESS)
1694 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1696 else
1698 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1699 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1701 /* point to the name so LdrInitializeThunk can print it */
1702 last_failed_modref = wm;
1703 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1705 current_modref = prev;
1708 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1709 /* Remove recursion flag */
1710 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1712 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1713 return status;
1717 /*************************************************************************
1718 * process_detach
1720 * Send DLL process detach notifications. See the comment about calling
1721 * sequence at process_attach.
1723 static void process_detach(void)
1725 PLIST_ENTRY mark, entry;
1726 PLDR_DATA_TABLE_ENTRY mod;
1728 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1731 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1733 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1734 InInitializationOrderLinks);
1735 /* Check whether to detach this DLL */
1736 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1737 continue;
1738 if ( mod->LoadCount && !process_detaching )
1739 continue;
1741 /* Call detach notification */
1742 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1743 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1744 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1745 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1747 /* Restart at head of WINE_MODREF list, as entries might have
1748 been added and/or removed while performing the call ... */
1749 break;
1751 } while (entry != mark);
1754 /*************************************************************************
1755 * thread_attach
1757 * Send DLL thread attach notifications. These are sent in the
1758 * reverse sequence of process detach notification.
1759 * The loader_section must be locked while calling this function.
1761 static void thread_attach(void)
1763 PLIST_ENTRY mark, entry;
1764 PLDR_DATA_TABLE_ENTRY mod;
1766 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1767 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1769 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1770 InInitializationOrderLinks);
1771 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1772 continue;
1773 if ( mod->Flags & LDR_NO_DLL_CALLS )
1774 continue;
1776 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1780 /******************************************************************
1781 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1784 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1786 WINE_MODREF *wm;
1787 NTSTATUS ret = STATUS_SUCCESS;
1789 RtlEnterCriticalSection( &loader_section );
1791 wm = get_modref( hModule );
1792 if (!wm || wm->ldr.TlsIndex == -1)
1793 ret = STATUS_DLL_NOT_FOUND;
1794 else
1795 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1797 RtlLeaveCriticalSection( &loader_section );
1799 return ret;
1802 /******************************************************************
1803 * LdrFindEntryForAddress (NTDLL.@)
1805 * The loader_section must be locked while calling this function
1807 NTSTATUS WINAPI LdrFindEntryForAddress( const void *addr, PLDR_DATA_TABLE_ENTRY *pmod )
1809 PLIST_ENTRY mark, entry;
1810 PLDR_DATA_TABLE_ENTRY mod;
1812 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1813 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1815 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
1816 if (mod->DllBase <= addr &&
1817 (const char *)addr < (char*)mod->DllBase + mod->SizeOfImage)
1819 *pmod = mod;
1820 return STATUS_SUCCESS;
1823 return STATUS_NO_MORE_ENTRIES;
1826 /******************************************************************
1827 * LdrEnumerateLoadedModules (NTDLL.@)
1829 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1831 LIST_ENTRY *mark, *entry;
1832 LDR_DATA_TABLE_ENTRY *mod;
1833 BOOLEAN stop = FALSE;
1835 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1837 if (unknown || !callback)
1838 return STATUS_INVALID_PARAMETER;
1840 RtlEnterCriticalSection( &loader_section );
1842 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1843 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1845 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
1846 callback( mod, context, &stop );
1847 if (stop) break;
1850 RtlLeaveCriticalSection( &loader_section );
1851 return STATUS_SUCCESS;
1854 /******************************************************************
1855 * LdrRegisterDllNotification (NTDLL.@)
1857 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1858 void *context, void **cookie)
1860 struct ldr_notification *notify;
1862 TRACE( "(%lx, %p, %p, %p)\n", flags, callback, context, cookie );
1864 if (!callback || !cookie)
1865 return STATUS_INVALID_PARAMETER;
1867 if (flags)
1868 FIXME( "ignoring flags %lx\n", flags );
1870 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1871 if (!notify) return STATUS_NO_MEMORY;
1872 notify->callback = callback;
1873 notify->context = context;
1875 RtlEnterCriticalSection( &loader_section );
1876 list_add_tail( &ldr_notifications, &notify->entry );
1877 RtlLeaveCriticalSection( &loader_section );
1879 *cookie = notify;
1880 return STATUS_SUCCESS;
1883 /******************************************************************
1884 * LdrUnregisterDllNotification (NTDLL.@)
1886 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1888 struct ldr_notification *notify = cookie;
1890 TRACE( "(%p)\n", cookie );
1892 if (!notify) return STATUS_INVALID_PARAMETER;
1894 RtlEnterCriticalSection( &loader_section );
1895 list_remove( &notify->entry );
1896 RtlLeaveCriticalSection( &loader_section );
1898 RtlFreeHeap( GetProcessHeap(), 0, notify );
1899 return STATUS_SUCCESS;
1902 /******************************************************************
1903 * LdrLockLoaderLock (NTDLL.@)
1905 * Note: some flags are not implemented.
1906 * Flag 0x01 is used to raise exceptions on errors.
1908 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1910 if (flags & ~0x2) FIXME( "flags %lx not supported\n", flags );
1912 if (result) *result = 0;
1913 if (magic) *magic = 0;
1914 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1915 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1916 if (!magic) return STATUS_INVALID_PARAMETER_3;
1918 if (flags & 0x2)
1920 if (!RtlTryEnterCriticalSection( &loader_section ))
1922 *result = 2;
1923 return STATUS_SUCCESS;
1925 *result = 1;
1927 else
1929 RtlEnterCriticalSection( &loader_section );
1930 if (result) *result = 1;
1932 *magic = GetCurrentThreadId();
1933 return STATUS_SUCCESS;
1937 /******************************************************************
1938 * LdrUnlockLoaderUnlock (NTDLL.@)
1940 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1942 if (magic)
1944 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1945 RtlLeaveCriticalSection( &loader_section );
1947 return STATUS_SUCCESS;
1951 /******************************************************************
1952 * LdrGetProcedureAddress (NTDLL.@)
1954 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1955 ULONG ord, PVOID *address)
1957 IMAGE_EXPORT_DIRECTORY *exports;
1958 DWORD exp_size;
1959 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1961 RtlEnterCriticalSection( &loader_section );
1963 /* check if the module itself is invalid to return the proper error */
1964 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1965 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1966 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1968 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, NULL )
1969 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, NULL );
1970 if (proc)
1972 *address = proc;
1973 ret = STATUS_SUCCESS;
1977 RtlLeaveCriticalSection( &loader_section );
1978 return ret;
1982 /***********************************************************************
1983 * set_security_cookie
1985 * Create a random security cookie for buffer overflow protection. Make
1986 * sure it does not accidentally match the default cookie value.
1988 static void set_security_cookie( void *module, SIZE_T len )
1990 static ULONG seed;
1991 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1992 ULONG loadcfg_size;
1993 ULONG_PTR *cookie;
1995 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1996 if (!loadcfg) return;
1997 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1998 if (!loadcfg->SecurityCookie) return;
1999 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
2000 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
2002 WARN( "security cookie %p outside of image %p-%p\n",
2003 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
2004 return;
2007 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
2008 TRACE( "initializing security cookie %p\n", cookie );
2010 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
2011 for (;;)
2013 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
2014 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
2015 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
2016 *cookie = RtlRandom( &seed );
2017 #ifdef DEFAULT_SECURITY_COOKIE_64
2018 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
2020 *cookie = RtlRandom( &seed );
2021 /* fill up, but keep the highest word clear */
2022 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
2024 #endif
2025 else
2026 break;
2030 static NTSTATUS perform_relocations( void *module, IMAGE_NT_HEADERS *nt, SIZE_T len )
2032 char *base;
2033 IMAGE_BASE_RELOCATION *rel, *end;
2034 const IMAGE_DATA_DIRECTORY *relocs;
2035 const IMAGE_SECTION_HEADER *sec;
2036 INT_PTR delta;
2037 ULONG protect_old[96], i;
2039 base = (char *)nt->OptionalHeader.ImageBase;
2040 if (module == base) return STATUS_SUCCESS; /* nothing to do */
2042 /* no relocations are performed on non page-aligned binaries */
2043 if (nt->OptionalHeader.SectionAlignment < page_size)
2044 return STATUS_SUCCESS;
2046 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
2047 return STATUS_SUCCESS;
2049 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
2051 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
2053 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
2054 base, module );
2055 return STATUS_CONFLICTING_ADDRESSES;
2058 if (!relocs->Size) return STATUS_SUCCESS;
2059 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
2061 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
2062 return STATUS_INVALID_IMAGE_FORMAT;
2064 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
2065 nt->FileHeader.SizeOfOptionalHeader);
2066 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
2068 void *addr = get_rva( module, sec[i].VirtualAddress );
2069 SIZE_T size = sec[i].SizeOfRawData;
2070 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
2071 &size, PAGE_READWRITE, &protect_old[i] );
2074 TRACE( "relocating from %p-%p to %p-%p\n",
2075 base, base + len, module, (char *)module + len );
2077 rel = get_rva( module, relocs->VirtualAddress );
2078 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
2079 delta = (char *)module - base;
2081 while (rel < end - 1 && rel->SizeOfBlock)
2083 if (rel->VirtualAddress >= len)
2085 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
2086 return STATUS_ACCESS_VIOLATION;
2088 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
2089 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
2090 (USHORT *)(rel + 1), delta );
2091 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
2094 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
2096 void *addr = get_rva( module, sec[i].VirtualAddress );
2097 SIZE_T size = sec[i].SizeOfRawData;
2098 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
2099 &size, protect_old[i], &protect_old[i] );
2102 return STATUS_SUCCESS;
2106 /*************************************************************************
2107 * build_module
2109 * Build the module data for a mapped dll.
2111 static NTSTATUS build_module( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module,
2112 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
2113 DWORD flags, BOOL system, WINE_MODREF **pwm )
2115 static const char builtin_signature[] = "Wine builtin DLL";
2116 char *signature = (char *)((IMAGE_DOS_HEADER *)*module + 1);
2117 BOOL is_builtin;
2118 IMAGE_NT_HEADERS *nt;
2119 WINE_MODREF *wm;
2120 NTSTATUS status;
2121 SIZE_T map_size;
2123 if (!(nt = RtlImageNtHeader( *module ))) return STATUS_INVALID_IMAGE_FORMAT;
2125 map_size = (nt->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
2126 if ((status = perform_relocations( *module, nt, map_size ))) return status;
2128 is_builtin = ((char *)nt - signature >= sizeof(builtin_signature) &&
2129 !memcmp( signature, builtin_signature, sizeof(builtin_signature) ));
2131 /* create the MODREF */
2133 if (!(wm = alloc_module( *module, nt_name, is_builtin ))) return STATUS_NO_MEMORY;
2135 if (id) wm->id = *id;
2136 if (image_info->LoaderFlags) wm->ldr.Flags |= LDR_COR_IMAGE;
2137 if (image_info->u.s.ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
2138 wm->system = system;
2140 set_security_cookie( *module, map_size );
2142 /* fixup imports */
2144 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
2145 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
2146 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
2148 if (wm->ldr.Flags & LDR_COR_ILONLY)
2149 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
2150 else
2151 status = fixup_imports( wm, load_path );
2152 if (status != STATUS_SUCCESS)
2154 /* the module has only be inserted in the load & memory order lists */
2155 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
2156 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
2158 /* FIXME: there are several more dangling references
2159 * left. Including dlls loaded by this dll before the
2160 * failed one. Unrolling is rather difficult with the
2161 * current structure and we can leave them lying
2162 * around with no problems, so we don't care.
2163 * As these might reference our wm, we don't free it.
2165 *module = NULL;
2166 return status;
2170 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name), wm, *module );
2172 if (is_builtin)
2174 if (TRACE_ON(relay)) RELAY_SetupDLL( *module );
2176 else
2178 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( *module );
2181 TRACE_(loaddll)( "Loaded %s at %p: %s\n", debugstr_w(wm->ldr.FullDllName.Buffer), *module,
2182 is_builtin ? "builtin" : "native" );
2184 wm->ldr.LoadCount = 1;
2185 *pwm = wm;
2186 *module = NULL;
2187 return STATUS_SUCCESS;
2191 /*************************************************************************
2192 * build_ntdll_module
2194 * Build the module data for the initially-loaded ntdll.
2196 static void build_ntdll_module( HMODULE module )
2198 UNICODE_STRING nt_name = RTL_CONSTANT_STRING( L"\\??\\C:\\windows\\system32\\ntdll.dll" );
2199 WINE_MODREF *wm;
2201 wm = alloc_module( module, &nt_name, TRUE );
2202 assert( wm );
2203 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
2204 node_ntdll = wm->ldr.DdagNode;
2205 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
2209 #ifdef _WIN64
2210 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
2211 static BOOL convert_to_pe64( HMODULE module, const SECTION_IMAGE_INFORMATION *info )
2213 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
2214 IMAGE_DIRECTORY_ENTRY_SECURITY,
2215 IMAGE_DIRECTORY_ENTRY_BASERELOC,
2216 IMAGE_DIRECTORY_ENTRY_DEBUG,
2217 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
2218 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
2219 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
2220 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
2221 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
2222 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
2223 SIZE_T size = min( nt->OptionalHeader.SizeOfHeaders, nt->OptionalHeader.SizeOfImage );
2224 void *addr = module;
2225 ULONG i, old_prot;
2227 if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return TRUE; /* already 64-bit */
2228 if (NtCurrentTeb()->WowTebOffset) return TRUE; /* no need to convert */
2229 if (!info->ImageContainsCode) return TRUE; /* no need to convert */
2231 TRACE( "%p\n", module );
2233 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
2234 return FALSE;
2236 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
2238 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2239 return FALSE;
2242 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
2243 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
2244 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
2245 hdr64.AddressOfEntryPoint = 0;
2246 hdr64.ImageBase = hdr32.ImageBase;
2247 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
2248 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
2249 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
2250 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
2251 hdr64.LoaderFlags = hdr32.LoaderFlags;
2252 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
2253 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
2254 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
2256 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
2257 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
2258 nt->OptionalHeader = hdr64;
2259 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2260 return TRUE;
2263 /* read data out of a PE image directory */
2264 static ULONG read_image_directory( HANDLE file, const SECTION_IMAGE_INFORMATION *info,
2265 ULONG dir, void *buffer, ULONG maxlen, USHORT *magic )
2267 IMAGE_DOS_HEADER mz;
2268 IO_STATUS_BLOCK io;
2269 LARGE_INTEGER offset;
2270 IMAGE_SECTION_HEADER sec[96];
2271 unsigned int i, count;
2272 DWORD va, size;
2273 union
2275 IMAGE_NT_HEADERS32 nt32;
2276 IMAGE_NT_HEADERS64 nt64;
2277 } nt;
2279 offset.QuadPart = 0;
2280 if (NtReadFile( file, 0, NULL, NULL, &io, &mz, sizeof(mz), &offset, NULL )) return 0;
2281 if (io.Information != sizeof(mz)) return 0;
2282 if (mz.e_magic != IMAGE_DOS_SIGNATURE) return 0;
2283 offset.QuadPart = mz.e_lfanew;
2284 if (NtReadFile( file, 0, NULL, NULL, &io, &nt, sizeof(nt), &offset, NULL )) return 0;
2285 if (io.Information != sizeof(nt)) return 0;
2286 if (nt.nt32.Signature != IMAGE_NT_SIGNATURE) return 0;
2287 *magic = nt.nt32.OptionalHeader.Magic;
2288 switch (nt.nt32.OptionalHeader.Magic)
2290 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
2291 va = nt.nt32.OptionalHeader.DataDirectory[dir].VirtualAddress;
2292 size = nt.nt32.OptionalHeader.DataDirectory[dir].Size;
2293 break;
2294 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
2295 va = nt.nt64.OptionalHeader.DataDirectory[dir].VirtualAddress;
2296 size = nt.nt64.OptionalHeader.DataDirectory[dir].Size;
2297 break;
2298 default:
2299 return 0;
2301 if (!va) return 0;
2302 offset.QuadPart += offsetof( IMAGE_NT_HEADERS32, OptionalHeader ) + nt.nt32.FileHeader.SizeOfOptionalHeader;
2303 count = min( 96, nt.nt32.FileHeader.NumberOfSections );
2304 if (NtReadFile( file, 0, NULL, NULL, &io, &sec, count * sizeof(*sec), &offset, NULL )) return 0;
2305 if (io.Information != count * sizeof(*sec)) return 0;
2306 for (i = 0; i < count; i++)
2308 if (va < sec[i].VirtualAddress) continue;
2309 if (sec[i].Misc.VirtualSize && va - sec[i].VirtualAddress >= sec[i].Misc.VirtualSize) continue;
2310 offset.QuadPart = sec[i].PointerToRawData + va - sec[i].VirtualAddress;
2311 if (NtReadFile( file, 0, NULL, NULL, &io, buffer, min( maxlen, size ), &offset, NULL )) return 0;
2312 return io.Information;
2314 return 0;
2317 /* check COM header for ILONLY flag, ignoring runtime version */
2318 static BOOL is_com_ilonly( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2320 USHORT magic;
2321 IMAGE_COR20_HEADER cor_header;
2322 ULONG len = read_image_directory( file, info, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR,
2323 &cor_header, sizeof(cor_header), &magic );
2325 if (len != sizeof(cor_header)) return FALSE;
2326 if (magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return FALSE;
2327 return !!(cor_header.Flags & COMIMAGE_FLAGS_ILONLY);
2330 /* check LOAD_CONFIG header for CHPE metadata */
2331 static BOOL has_chpe_metadata( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2333 USHORT magic;
2334 IMAGE_LOAD_CONFIG_DIRECTORY64 loadcfg;
2335 ULONG len = read_image_directory( file, info, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
2336 &loadcfg, sizeof(loadcfg), &magic );
2338 if (!len) return FALSE;
2339 if (magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return FALSE;
2340 len = min( len, loadcfg.Size );
2341 if (len <= offsetof( IMAGE_LOAD_CONFIG_DIRECTORY64, CHPEMetadataPointer )) return FALSE;
2342 return !!loadcfg.CHPEMetadataPointer;
2345 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2346 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2347 static BOOL is_valid_binary( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2349 if (info->Machine == current_machine) return TRUE;
2350 if (NtCurrentTeb()->WowTebOffset) return TRUE;
2351 /* support ARM64EC binaries on x86-64 */
2352 if (current_machine == IMAGE_FILE_MACHINE_AMD64 && has_chpe_metadata( file, info )) return TRUE;
2353 /* support 32-bit IL-only images on 64-bit */
2354 if (!info->ImageContainsCode) return TRUE;
2355 if (info->u.s.ComPlusNativeReady) return TRUE;
2356 return is_com_ilonly( file, info );
2359 #else /* _WIN64 */
2361 static BOOL is_valid_binary( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2363 return (info->Machine == current_machine);
2366 #endif /* _WIN64 */
2369 /******************************************************************
2370 * get_module_path_end
2372 * Returns the end of the directory component of the module path.
2374 static inline const WCHAR *get_module_path_end( const WCHAR *module )
2376 const WCHAR *p;
2377 const WCHAR *mod_end = module;
2379 if ((p = wcsrchr( mod_end, '\\' ))) mod_end = p;
2380 if ((p = wcsrchr( mod_end, '/' ))) mod_end = p;
2381 if (mod_end == module + 2 && module[1] == ':') mod_end++;
2382 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
2383 return mod_end;
2387 /******************************************************************
2388 * append_path
2390 * Append a counted string to the load path. Helper for get_dll_load_path.
2392 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str, int len )
2394 if (len == -1) len = wcslen(str);
2395 if (!len) return p;
2396 memcpy( p, str, len * sizeof(WCHAR) );
2397 p[len] = ';';
2398 return p + len + 1;
2402 /******************************************************************
2403 * get_dll_load_path
2405 static NTSTATUS get_dll_load_path( LPCWSTR module, LPCWSTR dll_dir, ULONG safe_mode, WCHAR **path )
2407 const WCHAR *mod_end = module;
2408 UNICODE_STRING name = RTL_CONSTANT_STRING( L"PATH" ), value;
2409 WCHAR *p, *ret;
2410 int len = ARRAY_SIZE(system_path) + 1, path_len = 0;
2412 if (module)
2414 mod_end = get_module_path_end( module );
2415 len += (mod_end - module) + 1;
2418 value.Length = 0;
2419 value.MaximumLength = 0;
2420 value.Buffer = NULL;
2421 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2422 path_len = value.Length;
2424 if (dll_dir) len += wcslen( dll_dir ) + 1;
2425 else len += 2; /* current directory */
2426 if (!(p = ret = RtlAllocateHeap( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
2427 return STATUS_NO_MEMORY;
2429 p = append_path( p, module, mod_end - module );
2430 if (dll_dir) p = append_path( p, dll_dir, -1 );
2431 else if (!safe_mode) p = append_path( p, L".", -1 );
2432 p = append_path( p, system_path, -1 );
2433 if (!dll_dir && safe_mode) p = append_path( p, L".", -1 );
2435 value.Buffer = p;
2436 value.MaximumLength = path_len;
2438 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2440 WCHAR *new_ptr;
2442 /* grow the buffer and retry */
2443 path_len = value.Length;
2444 if (!(new_ptr = RtlReAllocateHeap( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
2446 RtlFreeHeap( GetProcessHeap(), 0, ret );
2447 return STATUS_NO_MEMORY;
2449 value.Buffer = new_ptr + (value.Buffer - ret);
2450 value.MaximumLength = path_len;
2451 ret = new_ptr;
2453 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
2454 *path = ret;
2455 return STATUS_SUCCESS;
2459 /******************************************************************
2460 * get_dll_load_path_search_flags
2462 static NTSTATUS get_dll_load_path_search_flags( LPCWSTR module, DWORD flags, WCHAR **path )
2464 const WCHAR *image = NULL, *mod_end, *image_end;
2465 struct dll_dir_entry *dir;
2466 WCHAR *p, *ret;
2467 int len = 1;
2469 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
2470 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
2471 LOAD_LIBRARY_SEARCH_USER_DIRS |
2472 LOAD_LIBRARY_SEARCH_SYSTEM32);
2474 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
2476 DWORD type = RtlDetermineDosPathNameType_U( module );
2477 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH && type != DEVICE_PATH)
2478 return STATUS_INVALID_PARAMETER;
2479 mod_end = get_module_path_end( module );
2480 len += (mod_end - module) + 1;
2482 else module = NULL;
2484 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
2486 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
2487 image_end = get_module_path_end( image );
2488 len += (image_end - image) + 1;
2491 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2493 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2494 len += wcslen( dir->dir + 4 /* \??\ */ ) + 1;
2495 if (dll_directory.Length) len += dll_directory.Length / sizeof(WCHAR) + 1;
2498 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += wcslen( system_dir );
2500 if ((p = ret = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2502 if (module) p = append_path( p, module, mod_end - module );
2503 if (image) p = append_path( p, image, image_end - image );
2504 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2506 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2507 p = append_path( p, dir->dir + 4 /* \??\ */, -1 );
2508 p = append_path( p, dll_directory.Buffer, dll_directory.Length / sizeof(WCHAR) );
2510 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) wcscpy( p, system_dir );
2511 else
2513 if (p > ret) p--;
2514 *p = 0;
2517 *path = ret;
2518 return STATUS_SUCCESS;
2522 /***********************************************************************
2523 * open_dll_file
2525 * Open a file for a new dll. Helper for find_dll_file.
2527 static NTSTATUS open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2528 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2530 FILE_BASIC_INFORMATION info;
2531 OBJECT_ATTRIBUTES attr;
2532 IO_STATUS_BLOCK io;
2533 LARGE_INTEGER size;
2534 FILE_OBJECTID_BUFFER fid;
2535 NTSTATUS status;
2536 HANDLE handle;
2538 if ((*pwm = find_fullname_module( nt_name ))) return STATUS_SUCCESS;
2540 attr.Length = sizeof(attr);
2541 attr.RootDirectory = 0;
2542 attr.Attributes = OBJ_CASE_INSENSITIVE;
2543 attr.ObjectName = nt_name;
2544 attr.SecurityDescriptor = NULL;
2545 attr.SecurityQualityOfService = NULL;
2546 if ((status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2547 FILE_SHARE_READ | FILE_SHARE_DELETE,
2548 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
2550 if (status != STATUS_OBJECT_PATH_NOT_FOUND &&
2551 status != STATUS_OBJECT_NAME_NOT_FOUND &&
2552 !NtQueryAttributesFile( &attr, &info ))
2554 /* if the file exists but failed to open, report the error */
2555 return status;
2557 /* otherwise continue searching */
2558 return STATUS_DLL_NOT_FOUND;
2561 if (!NtFsControlFile( handle, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &fid, sizeof(fid) ))
2563 memcpy( id, fid.ObjectId, sizeof(*id) );
2564 if ((*pwm = find_fileid_module( id )))
2566 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2567 (*pwm)->ldr.DllBase, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2568 NtClose( handle );
2569 return STATUS_SUCCESS;
2573 size.QuadPart = 0;
2574 status = NtCreateSection( mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2575 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2576 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, handle );
2577 if (!status)
2579 NtQuerySection( *mapping, SectionImageInformation, image_info, sizeof(*image_info), NULL );
2580 if (!is_valid_binary( handle, image_info ))
2582 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name), image_info->Machine );
2583 status = STATUS_NOT_SUPPORTED;
2584 NtClose( *mapping );
2585 *mapping = NULL;
2588 NtClose( handle );
2589 return status;
2593 /******************************************************************************
2594 * find_existing_module
2596 * Find an existing module that is the same mapping as the new module.
2598 static WINE_MODREF *find_existing_module( HMODULE module )
2600 WINE_MODREF *wm;
2601 LIST_ENTRY *mark, *entry;
2602 LDR_DATA_TABLE_ENTRY *mod;
2603 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
2605 if ((wm = get_modref( module ))) return wm;
2607 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
2608 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2610 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
2611 if (mod->TimeDateStamp != nt->FileHeader.TimeDateStamp) continue;
2612 wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
2613 if (wm->CheckSum != nt->OptionalHeader.CheckSum) continue;
2614 if (NtAreMappedFilesTheSame( mod->DllBase, module ) != STATUS_SUCCESS) continue;
2615 return CONTAINING_RECORD( mod, WINE_MODREF, ldr );
2617 return NULL;
2621 /******************************************************************************
2622 * load_native_dll (internal)
2624 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, HANDLE mapping,
2625 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
2626 DWORD flags, BOOL system, WINE_MODREF** pwm )
2628 void *module = NULL;
2629 SIZE_T len = 0;
2630 NTSTATUS status = NtMapViewOfSection( mapping, NtCurrentProcess(), &module, 0, 0, NULL, &len,
2631 ViewShare, 0, PAGE_EXECUTE_READ );
2633 if (status == STATUS_IMAGE_NOT_AT_BASE) status = STATUS_SUCCESS;
2634 if (status) return status;
2636 if ((*pwm = find_existing_module( module ))) /* already loaded */
2638 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2639 TRACE( "found %s for %s at %p, count=%d\n",
2640 debugstr_us(&(*pwm)->ldr.FullDllName), debugstr_us(nt_name),
2641 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2642 if (module != (*pwm)->ldr.DllBase) NtUnmapViewOfSection( NtCurrentProcess(), module );
2643 return STATUS_SUCCESS;
2645 #ifdef _WIN64
2646 if (!convert_to_pe64( module, image_info )) status = STATUS_INVALID_IMAGE_FORMAT;
2647 #endif
2648 if (!status) status = build_module( load_path, nt_name, &module, image_info, id, flags, system, pwm );
2649 if (status && module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2650 return status;
2654 /***********************************************************************
2655 * load_so_dll
2657 static NTSTATUS load_so_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name,
2658 DWORD flags, WINE_MODREF **pwm )
2660 void *module;
2661 NTSTATUS status;
2662 WINE_MODREF *wm;
2663 struct load_so_dll_params params = { *nt_name, &module };
2665 TRACE( "trying %s as so lib\n", debugstr_us(nt_name) );
2666 if ((status = WINE_UNIX_CALL( unix_load_so_dll, &params )))
2668 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name) );
2669 if (status == STATUS_INVALID_IMAGE_FORMAT) status = STATUS_INVALID_IMAGE_NOT_MZ;
2670 return status;
2673 if ((wm = get_modref( module ))) /* already loaded */
2675 TRACE( "Found %s at %p for builtin %s\n",
2676 debugstr_w(wm->ldr.FullDllName.Buffer), wm->ldr.DllBase, debugstr_us(nt_name) );
2677 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2679 else
2681 SECTION_IMAGE_INFORMATION image_info = { 0 };
2683 if ((status = build_module( load_path, &params.nt_name, &module, &image_info, NULL, flags, FALSE, &wm )))
2685 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2686 return status;
2688 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name), module );
2690 *pwm = wm;
2691 return STATUS_SUCCESS;
2695 /*************************************************************************
2696 * build_main_module
2698 * Build the module data for the main image.
2700 static WINE_MODREF *build_main_module(void)
2702 SECTION_IMAGE_INFORMATION info;
2703 UNICODE_STRING nt_name;
2704 WINE_MODREF *wm;
2705 NTSTATUS status;
2706 RTL_USER_PROCESS_PARAMETERS *params = NtCurrentTeb()->Peb->ProcessParameters;
2707 void *module = NtCurrentTeb()->Peb->ImageBaseAddress;
2709 default_load_path = params->DllPath.Buffer;
2710 if (!default_load_path)
2711 get_dll_load_path( params->ImagePathName.Buffer, NULL, dll_safe_mode, &default_load_path );
2713 NtQueryInformationProcess( GetCurrentProcess(), ProcessImageInformation, &info, sizeof(info), NULL );
2714 if (info.ImageCharacteristics & IMAGE_FILE_DLL)
2716 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_us(&params->ImagePathName) );
2717 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT );
2719 #ifdef _WIN64
2720 if (!convert_to_pe64( module, &info ))
2722 status = STATUS_INVALID_IMAGE_FORMAT;
2723 goto failed;
2725 #endif
2726 status = RtlDosPathNameToNtPathName_U_WithStatus( params->ImagePathName.Buffer, &nt_name, NULL, NULL );
2727 if (status) goto failed;
2728 status = build_module( NULL, &nt_name, &module, &info, NULL, DONT_RESOLVE_DLL_REFERENCES, FALSE, &wm );
2729 RtlFreeUnicodeString( &nt_name );
2730 if (!status) return wm;
2731 failed:
2732 MESSAGE( "wine: failed to create main module for %s, status %lx\n",
2733 debugstr_us(&params->ImagePathName), status );
2734 NtTerminateProcess( GetCurrentProcess(), status );
2735 return NULL; /* unreached */
2739 /***********************************************************************
2740 * build_dlldata_path
2742 * Helper for find_actctx_dll.
2744 static NTSTATUS build_dlldata_path( LPCWSTR libname, ACTCTX_SECTION_KEYED_DATA *data, LPWSTR *fullname )
2746 struct dllredirect_data *dlldata = data->lpData;
2747 char *base = data->lpSectionBase;
2748 SIZE_T total = dlldata->total_len + (wcslen(libname) + 1) * sizeof(WCHAR);
2749 WCHAR *p, *buffer;
2750 NTSTATUS status = STATUS_SUCCESS;
2751 ULONG i;
2753 if (!(p = buffer = RtlAllocateHeap( GetProcessHeap(), 0, total ))) return STATUS_NO_MEMORY;
2754 for (i = 0; i < dlldata->paths_count; i++)
2756 memcpy( p, base + dlldata->paths[i].offset, dlldata->paths[i].len );
2757 p += dlldata->paths[i].len / sizeof(WCHAR);
2759 if (p == buffer || p[-1] == '\\') wcscpy( p, libname );
2760 else *p = 0;
2762 if (dlldata->flags & DLL_REDIRECT_PATH_EXPAND)
2764 RtlExpandEnvironmentStrings( NULL, buffer, wcslen(buffer), NULL, 0, &total );
2765 if ((*fullname = RtlAllocateHeap( GetProcessHeap(), 0, total * sizeof(WCHAR) )))
2766 RtlExpandEnvironmentStrings( NULL, buffer, wcslen(buffer), *fullname, total, NULL );
2767 else
2768 status = STATUS_NO_MEMORY;
2770 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2772 else *fullname = buffer;
2774 return status;
2778 /***********************************************************************
2779 * find_actctx_dll
2781 * Find the full path (if any) of the dll from the activation context.
2783 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2785 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2787 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info = NULL;
2788 ACTCTX_SECTION_KEYED_DATA data;
2789 struct dllredirect_data *dlldata;
2790 UNICODE_STRING nameW;
2791 NTSTATUS status;
2792 SIZE_T needed, size = 1024;
2793 WCHAR *p;
2795 RtlInitUnicodeString( &nameW, libname );
2796 data.cbSize = sizeof(data);
2797 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2798 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2799 &nameW, &data );
2800 if (status != STATUS_SUCCESS) return status;
2802 if (data.ulLength < offsetof( struct dllredirect_data, paths[0] ))
2804 status = STATUS_SXS_KEY_NOT_FOUND;
2805 goto done;
2807 dlldata = data.lpData;
2808 if (!(dlldata->flags & DLL_REDIRECT_PATH_OMITS_ASSEMBLY_ROOT))
2810 status = build_dlldata_path( libname, &data, fullname );
2811 goto done;
2814 for (;;)
2816 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2818 status = STATUS_NO_MEMORY;
2819 goto done;
2821 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2822 AssemblyDetailedInformationInActivationContext,
2823 info, size, &needed );
2824 if (status == STATUS_SUCCESS) break;
2825 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2826 RtlFreeHeap( GetProcessHeap(), 0, info );
2827 size = needed;
2828 /* restart with larger buffer */
2831 if (!info->lpAssemblyManifestPath)
2833 status = STATUS_SXS_KEY_NOT_FOUND;
2834 goto done;
2837 if ((p = wcsrchr( info->lpAssemblyManifestPath, '\\' )))
2839 DWORD len, dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2840 p++;
2841 len = wcslen( p );
2842 if (!dirlen || len <= dirlen ||
2843 RtlCompareUnicodeStrings( p, dirlen, info->lpAssemblyDirectoryName, dirlen, TRUE ) ||
2844 wcsicmp( p + dirlen, L".manifest" ))
2846 /* manifest name does not match directory name, so it's not a global
2847 * windows/winsxs manifest; use the manifest directory name instead */
2848 dirlen = p - info->lpAssemblyManifestPath;
2849 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2850 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2852 status = STATUS_NO_MEMORY;
2853 goto done;
2855 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2856 p += dirlen;
2857 wcscpy( p, libname );
2858 goto done;
2862 if (!info->lpAssemblyDirectoryName)
2864 status = STATUS_SXS_KEY_NOT_FOUND;
2865 goto done;
2868 needed = (wcslen(windows_dir) * sizeof(WCHAR) +
2869 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2871 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2873 status = STATUS_NO_MEMORY;
2874 goto done;
2876 wcscpy( p, windows_dir );
2877 p += wcslen(p);
2878 memcpy( p, winsxsW, sizeof(winsxsW) );
2879 p += ARRAY_SIZE( winsxsW );
2880 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2881 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2882 *p++ = '\\';
2883 wcscpy( p, libname );
2884 done:
2885 RtlFreeHeap( GetProcessHeap(), 0, info );
2886 RtlReleaseActivationContext( data.hActCtx );
2887 return status;
2892 /******************************************************************************
2893 * find_apiset_dll
2895 static NTSTATUS find_apiset_dll( const WCHAR *name, WCHAR **fullname )
2897 const API_SET_NAMESPACE *map = NtCurrentTeb()->Peb->ApiSetMap;
2898 const API_SET_NAMESPACE_ENTRY *entry;
2899 UNICODE_STRING str;
2900 ULONG len;
2902 if (get_apiset_entry( map, name, wcslen(name), &entry )) return STATUS_APISET_NOT_PRESENT;
2903 if (get_apiset_target( map, entry, NULL, &str )) return STATUS_DLL_NOT_FOUND;
2905 len = wcslen( system_dir ) + str.Length / sizeof(WCHAR);
2906 if (!(*fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
2907 return STATUS_NO_MEMORY;
2908 wcscpy( *fullname, system_dir );
2909 memcpy( *fullname + wcslen( system_dir ), str.Buffer, str.Length );
2910 (*fullname)[len] = 0;
2911 return STATUS_SUCCESS;
2915 /***********************************************************************
2916 * get_env_var
2918 static NTSTATUS get_env_var( const WCHAR *name, SIZE_T extra, UNICODE_STRING *ret )
2920 NTSTATUS status;
2921 SIZE_T len, size = 1024 + extra;
2923 for (;;)
2925 ret->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, size * sizeof(WCHAR) );
2926 status = RtlQueryEnvironmentVariable( NULL, name, wcslen(name),
2927 ret->Buffer, size - extra - 1, &len );
2928 if (!status)
2930 ret->Buffer[len] = 0;
2931 ret->Length = len * sizeof(WCHAR);
2932 ret->MaximumLength = size * sizeof(WCHAR);
2933 return status;
2935 RtlFreeHeap( GetProcessHeap(), 0, ret->Buffer );
2936 if (status != STATUS_BUFFER_TOO_SMALL)
2938 ret->Buffer = NULL;
2939 return status;
2941 size = len + 1 + extra;
2946 /***********************************************************************
2947 * find_builtin_without_file
2949 * Find a builtin dll when the corresponding file cannot be found in the prefix.
2950 * This is used during prefix bootstrap.
2952 static NTSTATUS find_builtin_without_file( const WCHAR *name, UNICODE_STRING *new_name,
2953 WINE_MODREF **pwm, HANDLE *mapping,
2954 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2956 const WCHAR *ext;
2957 WCHAR dllpath[32];
2958 DWORD i, len;
2959 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2960 BOOL found_image = FALSE;
2962 if (contains_path( name )) return status;
2964 if (!is_prefix_bootstrap)
2966 /* 16-bit files can't be loaded from the prefix */
2967 if (!name[1] || wcscmp( name + wcslen(name) - 2, L"16" )) return status;
2970 if (!get_env_var( L"WINEBUILDDIR", 20 + 2 * wcslen(name) + wcslen(pe_dir), new_name ))
2972 len = new_name->Length;
2973 RtlAppendUnicodeToString( new_name, L"\\dlls\\" );
2974 RtlAppendUnicodeToString( new_name, name );
2975 if ((ext = wcsrchr( name, '.' )) && !wcscmp( ext, L".dll" )) new_name->Length -= 4 * sizeof(WCHAR);
2976 RtlAppendUnicodeToString( new_name, pe_dir );
2977 RtlAppendUnicodeToString( new_name, L"\\" );
2978 RtlAppendUnicodeToString( new_name, name );
2979 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2980 if (status != STATUS_DLL_NOT_FOUND) goto done;
2982 new_name->Length = len;
2983 RtlAppendUnicodeToString( new_name, L"\\programs\\" );
2984 RtlAppendUnicodeToString( new_name, name );
2985 RtlAppendUnicodeToString( new_name, pe_dir );
2986 RtlAppendUnicodeToString( new_name, L"\\" );
2987 RtlAppendUnicodeToString( new_name, name );
2988 status = open_dll_file( new_name, pwm, mapping, image_info, id );
2989 if (status != STATUS_DLL_NOT_FOUND) goto done;
2990 RtlFreeUnicodeString( new_name );
2993 for (i = 0; ; i++)
2995 swprintf( dllpath, ARRAY_SIZE(dllpath), L"WINEDLLDIR%u", i );
2996 if (get_env_var( dllpath, wcslen(pe_dir) + wcslen(name) + 1, new_name )) break;
2997 len = new_name->Length;
2998 RtlAppendUnicodeToString( new_name, pe_dir );
2999 RtlAppendUnicodeToString( new_name, L"\\" );
3000 RtlAppendUnicodeToString( new_name, name );
3001 status = open_dll_file( new_name, pwm, mapping, image_info, id );
3002 if (status != STATUS_DLL_NOT_FOUND) goto done;
3003 new_name->Length = len;
3004 RtlAppendUnicodeToString( new_name, L"\\" );
3005 RtlAppendUnicodeToString( new_name, name );
3006 status = open_dll_file( new_name, pwm, mapping, image_info, id );
3007 if (status == STATUS_NOT_SUPPORTED) found_image = TRUE;
3008 else if (status != STATUS_DLL_NOT_FOUND) goto done;
3009 RtlFreeUnicodeString( new_name );
3011 if (found_image) status = STATUS_NOT_SUPPORTED;
3013 done:
3014 RtlFreeUnicodeString( new_name );
3015 if (!status)
3017 new_name->Length = (4 + wcslen(system_dir) + wcslen(name)) * sizeof(WCHAR);
3018 new_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, new_name->Length + sizeof(WCHAR) );
3019 wcscpy( new_name->Buffer, L"\\??\\" );
3020 wcscat( new_name->Buffer, system_dir );
3021 wcscat( new_name->Buffer, name );
3023 return status;
3027 /***********************************************************************
3028 * search_dll_file
3030 * Search for dll in the specified paths.
3032 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name,
3033 WINE_MODREF **pwm, HANDLE *mapping, SECTION_IMAGE_INFORMATION *image_info,
3034 struct file_id *id )
3036 WCHAR *name;
3037 BOOL found_image = FALSE;
3038 NTSTATUS status = STATUS_DLL_NOT_FOUND;
3039 ULONG len;
3041 if (!paths) paths = default_load_path;
3042 len = wcslen( paths );
3044 if (len < wcslen( system_dir )) len = wcslen( system_dir );
3045 len += wcslen( search ) + 2;
3047 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
3048 return STATUS_NO_MEMORY;
3050 while (*paths)
3052 LPCWSTR ptr = paths;
3054 while (*ptr && *ptr != ';') ptr++;
3055 len = ptr - paths;
3056 if (*ptr == ';') ptr++;
3057 memcpy( name, paths, len * sizeof(WCHAR) );
3058 if (len && name[len - 1] != '\\') name[len++] = '\\';
3059 wcscpy( name + len, search );
3061 nt_name->Buffer = NULL;
3062 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( name, nt_name, NULL, NULL ))) goto done;
3064 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
3065 if (status == STATUS_NOT_SUPPORTED) found_image = TRUE;
3066 else if (status != STATUS_DLL_NOT_FOUND) goto done;
3067 RtlFreeUnicodeString( nt_name );
3068 paths = ptr;
3071 if (found_image) status = STATUS_NOT_SUPPORTED;
3073 done:
3074 RtlFreeHeap( GetProcessHeap(), 0, name );
3075 return status;
3078 /***********************************************************************
3079 * find_dll_file
3081 * Find the file (or already loaded module) for a given dll name.
3083 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname, UNICODE_STRING *nt_name,
3084 WINE_MODREF **pwm, HANDLE *mapping, SECTION_IMAGE_INFORMATION *image_info,
3085 struct file_id *id )
3087 WCHAR *fullname = NULL;
3088 NTSTATUS status;
3089 ULONG wow64_old_value = 0;
3091 *pwm = NULL;
3093 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
3094 RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value );
3096 nt_name->Buffer = NULL;
3098 if (!contains_path( libname ))
3100 status = find_apiset_dll( libname, &fullname );
3101 if (status == STATUS_DLL_NOT_FOUND) goto done;
3103 if (status) status = find_actctx_dll( libname, &fullname );
3105 if (status == STATUS_SUCCESS)
3107 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
3108 libname = fullname;
3110 else
3112 if (status != STATUS_SXS_KEY_NOT_FOUND) goto done;
3113 if ((*pwm = find_basename_module( libname )) != NULL)
3115 status = STATUS_SUCCESS;
3116 goto done;
3121 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
3123 status = search_dll_file( load_path, libname, nt_name, pwm, mapping, image_info, id );
3124 if (status == STATUS_DLL_NOT_FOUND)
3125 status = find_builtin_without_file( libname, nt_name, pwm, mapping, image_info, id );
3127 else if (!(status = RtlDosPathNameToNtPathName_U_WithStatus( libname, nt_name, NULL, NULL )))
3128 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
3130 if (status == STATUS_NOT_SUPPORTED) status = STATUS_INVALID_IMAGE_FORMAT;
3132 done:
3133 RtlFreeHeap( GetProcessHeap(), 0, fullname );
3134 if (wow64_old_value) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value );
3135 return status;
3139 /***********************************************************************
3140 * load_dll (internal)
3142 * Load a PE style module according to the load order.
3143 * The loader_section must be locked while calling this function.
3145 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, DWORD flags, WINE_MODREF** pwm, BOOL system )
3147 UNICODE_STRING nt_name;
3148 struct file_id id;
3149 HANDLE mapping = 0;
3150 SECTION_IMAGE_INFORMATION image_info;
3151 NTSTATUS nts = STATUS_DLL_NOT_FOUND;
3152 ULONG64 prev;
3154 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
3156 if (system && system_dll_path.Buffer)
3157 nts = search_dll_file( system_dll_path.Buffer, libname, &nt_name, pwm, &mapping, &image_info, &id );
3159 if (nts)
3161 nts = find_dll_file( load_path, libname, &nt_name, pwm, &mapping, &image_info, &id );
3162 system = FALSE;
3165 if (*pwm) /* found already loaded module */
3167 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
3169 TRACE("Found %s for %s at %p, count=%d\n",
3170 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
3171 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
3172 RtlFreeUnicodeString( &nt_name );
3173 return STATUS_SUCCESS;
3176 if (nts && nts != STATUS_INVALID_IMAGE_NOT_MZ) goto done;
3178 if (NtCurrentTeb64())
3180 prev = NtCurrentTeb64()->Tib.ArbitraryUserPointer;
3181 NtCurrentTeb64()->Tib.ArbitraryUserPointer = (ULONG_PTR)(nt_name.Buffer + 4);
3183 else
3185 prev = (ULONG_PTR)NtCurrentTeb()->Tib.ArbitraryUserPointer;
3186 NtCurrentTeb()->Tib.ArbitraryUserPointer = nt_name.Buffer + 4;
3189 switch (nts)
3191 case STATUS_INVALID_IMAGE_NOT_MZ: /* not in PE format, maybe it's a .so file */
3192 if (__wine_unixlib_handle) nts = load_so_dll( load_path, &nt_name, flags, pwm );
3193 break;
3195 case STATUS_SUCCESS: /* valid PE file */
3196 nts = load_native_dll( load_path, &nt_name, mapping, &image_info, &id, flags, system, pwm );
3197 break;
3200 if (NtCurrentTeb64())
3201 NtCurrentTeb64()->Tib.ArbitraryUserPointer = prev;
3202 else
3203 NtCurrentTeb()->Tib.ArbitraryUserPointer = (void *)(ULONG_PTR)prev;
3205 done:
3206 if (nts == STATUS_SUCCESS)
3207 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name), (*pwm)->ldr.DllBase);
3208 else
3209 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
3211 if (mapping) NtClose( mapping );
3212 RtlFreeUnicodeString( &nt_name );
3213 return nts;
3217 /***********************************************************************
3218 * __wine_ctrl_routine
3220 NTSTATUS WINAPI __wine_ctrl_routine( void *arg )
3222 DWORD ret = 0;
3224 if (pCtrlRoutine && NtCurrentTeb()->Peb->ProcessParameters->ConsoleHandle) ret = pCtrlRoutine( arg );
3225 RtlExitUserThread( ret );
3229 /***********************************************************************
3230 * __wine_unix_call
3232 NTSTATUS WINAPI __wine_unix_call( unixlib_handle_t handle, unsigned int code, void *args )
3234 return __wine_unix_call_dispatcher( handle, code, args );
3238 /***********************************************************************
3239 * __wine_unix_spawnvp
3241 NTSTATUS WINAPI __wine_unix_spawnvp( char * const argv[], int wait )
3243 struct wine_spawnvp_params params = { (char **)argv, wait };
3245 return WINE_UNIX_CALL( unix_wine_spawnvp, &params );
3249 /***********************************************************************
3250 * wine_server_call
3252 unsigned int CDECL wine_server_call( void *req_ptr )
3254 return WINE_UNIX_CALL( unix_wine_server_call, req_ptr );
3258 /***********************************************************************
3259 * wine_server_fd_to_handle
3261 NTSTATUS CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes,
3262 HANDLE *handle )
3264 struct wine_server_fd_to_handle_params params = { fd, access, attributes, handle };
3266 return WINE_UNIX_CALL( unix_wine_server_fd_to_handle, &params );
3270 /***********************************************************************
3271 * wine_server_handle_to_fd (NTDLL.@)
3273 NTSTATUS CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
3274 unsigned int *options )
3276 struct wine_server_handle_to_fd_params params = { handle, access, unix_fd, options };
3278 return WINE_UNIX_CALL( unix_wine_server_handle_to_fd, &params );
3281 /******************************************************************
3282 * LdrLoadDll (NTDLL.@)
3284 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
3285 const UNICODE_STRING *libname, HMODULE* hModule)
3287 WINE_MODREF *wm;
3288 NTSTATUS nts;
3289 WCHAR *dllname = append_dll_ext( libname->Buffer );
3291 RtlEnterCriticalSection( &loader_section );
3293 nts = load_dll( path_name, dllname ? dllname : libname->Buffer, flags, &wm, FALSE );
3295 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
3297 nts = process_attach( wm->ldr.DdagNode, NULL );
3298 if (nts != STATUS_SUCCESS)
3300 LdrUnloadDll(wm->ldr.DllBase);
3301 wm = NULL;
3304 *hModule = (wm) ? wm->ldr.DllBase : NULL;
3306 RtlLeaveCriticalSection( &loader_section );
3307 RtlFreeHeap( GetProcessHeap(), 0, dllname );
3308 return nts;
3312 /******************************************************************
3313 * LdrGetDllFullName (NTDLL.@)
3315 NTSTATUS WINAPI LdrGetDllFullName( HMODULE module, UNICODE_STRING *name )
3317 WINE_MODREF *wm;
3318 NTSTATUS status;
3320 TRACE( "module %p, name %p.\n", module, name );
3322 if (!module) module = NtCurrentTeb()->Peb->ImageBaseAddress;
3324 RtlEnterCriticalSection( &loader_section );
3325 wm = get_modref( module );
3326 if (wm)
3328 RtlCopyUnicodeString( name, &wm->ldr.FullDllName );
3329 if (name->MaximumLength < wm->ldr.FullDllName.Length + sizeof(WCHAR)) status = STATUS_BUFFER_TOO_SMALL;
3330 else status = STATUS_SUCCESS;
3331 } else status = STATUS_DLL_NOT_FOUND;
3332 RtlLeaveCriticalSection( &loader_section );
3334 return status;
3338 /******************************************************************
3339 * LdrGetDllHandleEx (NTDLL.@)
3341 NTSTATUS WINAPI LdrGetDllHandleEx( ULONG flags, LPCWSTR load_path, ULONG *dll_characteristics,
3342 const UNICODE_STRING *name, HMODULE *base )
3344 static const ULONG supported_flags = LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
3345 | LDR_GET_DLL_HANDLE_EX_FLAG_PIN;
3346 static const ULONG valid_flags = LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
3347 | LDR_GET_DLL_HANDLE_EX_FLAG_PIN | 4;
3348 SECTION_IMAGE_INFORMATION image_info;
3349 UNICODE_STRING nt_name;
3350 struct file_id id;
3351 NTSTATUS status;
3352 WINE_MODREF *wm;
3353 WCHAR *dllname;
3354 HANDLE mapping;
3356 TRACE( "flags %#lx, load_path %p, dll_characteristics %p, name %p, base %p.\n",
3357 flags, load_path, dll_characteristics, name, base );
3359 if (flags & ~valid_flags) return STATUS_INVALID_PARAMETER;
3361 if ((flags & (LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | LDR_GET_DLL_HANDLE_EX_FLAG_PIN))
3362 == (LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | LDR_GET_DLL_HANDLE_EX_FLAG_PIN))
3363 return STATUS_INVALID_PARAMETER;
3365 if (flags & ~supported_flags) FIXME( "Unsupported flags %#lx.\n", flags );
3366 if (dll_characteristics) FIXME( "dll_characteristics unsupported.\n" );
3368 dllname = append_dll_ext( name->Buffer );
3370 RtlEnterCriticalSection( &loader_section );
3372 status = find_dll_file( load_path, dllname ? dllname : name->Buffer,
3373 &nt_name, &wm, &mapping, &image_info, &id );
3375 if (wm) *base = wm->ldr.DllBase;
3376 else
3378 if (status == STATUS_SUCCESS) NtClose( mapping );
3379 status = STATUS_DLL_NOT_FOUND;
3381 RtlFreeUnicodeString( &nt_name );
3383 if (!status)
3385 if (flags & LDR_GET_DLL_HANDLE_EX_FLAG_PIN)
3386 LdrAddRefDll( LDR_ADDREF_DLL_PIN, *base );
3387 else if (!(flags & LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
3388 LdrAddRefDll( 0, *base );
3391 RtlLeaveCriticalSection( &loader_section );
3392 RtlFreeHeap( GetProcessHeap(), 0, dllname );
3393 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
3394 return status;
3398 /******************************************************************
3399 * LdrGetDllHandle (NTDLL.@)
3401 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
3403 return LdrGetDllHandleEx( LDR_GET_DLL_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, load_path, NULL, name, base );
3407 /******************************************************************
3408 * LdrAddRefDll (NTDLL.@)
3410 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
3412 NTSTATUS ret = STATUS_SUCCESS;
3413 WINE_MODREF *wm;
3415 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %lx not implemented\n", module, flags );
3417 RtlEnterCriticalSection( &loader_section );
3419 if ((wm = get_modref( module )))
3421 if (flags & LDR_ADDREF_DLL_PIN)
3422 wm->ldr.LoadCount = -1;
3423 else
3424 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
3425 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3427 else ret = STATUS_INVALID_PARAMETER;
3429 RtlLeaveCriticalSection( &loader_section );
3430 return ret;
3434 /***********************************************************************
3435 * LdrProcessRelocationBlock (NTDLL.@)
3437 * Apply relocations to a given page of a mapped PE image.
3439 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
3440 USHORT *relocs, INT_PTR delta )
3442 while (count--)
3444 USHORT offset = *relocs & 0xfff;
3445 int type = *relocs >> 12;
3446 switch(type)
3448 case IMAGE_REL_BASED_ABSOLUTE:
3449 break;
3450 case IMAGE_REL_BASED_HIGH:
3451 *(short *)((char *)page + offset) += HIWORD(delta);
3452 break;
3453 case IMAGE_REL_BASED_LOW:
3454 *(short *)((char *)page + offset) += LOWORD(delta);
3455 break;
3456 case IMAGE_REL_BASED_HIGHLOW:
3457 *(int *)((char *)page + offset) += delta;
3458 break;
3459 #ifdef _WIN64
3460 case IMAGE_REL_BASED_DIR64:
3461 *(INT_PTR *)((char *)page + offset) += delta;
3462 break;
3463 #elif defined(__arm__)
3464 case IMAGE_REL_BASED_THUMB_MOV32:
3466 UINT *inst = (UINT *)((char *)page + offset);
3467 WORD lo = ((inst[0] << 1) & 0x0800) + ((inst[0] << 12) & 0xf000) +
3468 ((inst[0] >> 20) & 0x0700) + ((inst[0] >> 16) & 0x00ff);
3469 WORD hi = ((inst[1] << 1) & 0x0800) + ((inst[1] << 12) & 0xf000) +
3470 ((inst[1] >> 20) & 0x0700) + ((inst[1] >> 16) & 0x00ff);
3471 DWORD imm = MAKELONG( lo, hi ) + delta;
3473 lo = LOWORD( imm );
3474 hi = HIWORD( imm );
3476 if ((inst[0] & 0x8000fbf0) != 0x0000f240 || (inst[1] & 0x8000fbf0) != 0x0000f2c0)
3477 ERR("wrong Thumb2 instruction @%p %08x:%08x, expected MOVW/MOVT\n",
3478 inst, inst[0], inst[1] );
3480 inst[0] = (inst[0] & 0x8f00fbf0) + ((lo >> 1) & 0x0400) + ((lo >> 12) & 0x000f) +
3481 ((lo << 20) & 0x70000000) + ((lo << 16) & 0xff0000);
3482 inst[1] = (inst[1] & 0x8f00fbf0) + ((hi >> 1) & 0x0400) + ((hi >> 12) & 0x000f) +
3483 ((hi << 20) & 0x70000000) + ((hi << 16) & 0xff0000);
3484 break;
3486 #endif
3487 default:
3488 FIXME("Unknown/unsupported fixup type %x.\n", type);
3489 return NULL;
3491 relocs++;
3493 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
3497 /******************************************************************
3498 * LdrQueryProcessModuleInformation
3501 NTSTATUS WINAPI LdrQueryProcessModuleInformation(RTL_PROCESS_MODULES *smi,
3502 ULONG buf_size, ULONG* req_size)
3504 RTL_PROCESS_MODULE_INFORMATION *sm = &smi->Modules[0];
3505 ULONG size = sizeof(ULONG);
3506 NTSTATUS nts = STATUS_SUCCESS;
3507 ANSI_STRING str;
3508 char* ptr;
3509 PLIST_ENTRY mark, entry;
3510 LDR_DATA_TABLE_ENTRY *mod;
3511 WORD id = 0;
3513 smi->ModulesCount = 0;
3515 RtlEnterCriticalSection( &loader_section );
3516 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3517 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3519 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3520 size += sizeof(*sm);
3521 if (size <= buf_size)
3523 sm->Section = 0; /* FIXME */
3524 sm->MappedBaseAddress = mod->DllBase;
3525 sm->ImageBaseAddress = mod->DllBase;
3526 sm->ImageSize = mod->SizeOfImage;
3527 sm->Flags = mod->Flags;
3528 sm->LoadOrderIndex = id++;
3529 sm->InitOrderIndex = 0; /* FIXME */
3530 sm->LoadCount = mod->LoadCount;
3531 str.Length = 0;
3532 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
3533 str.Buffer = (char*)sm->Name;
3534 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
3535 ptr = strrchr(str.Buffer, '\\');
3536 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
3538 smi->ModulesCount++;
3539 sm++;
3541 else nts = STATUS_INFO_LENGTH_MISMATCH;
3543 RtlLeaveCriticalSection( &loader_section );
3545 if (req_size) *req_size = size;
3547 return nts;
3551 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, LONG *value )
3553 NTSTATUS status;
3554 UNICODE_STRING str;
3555 ULONG size;
3556 WCHAR buffer[64];
3557 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3559 RtlInitUnicodeString( &str, name );
3561 size = sizeof(buffer) - sizeof(WCHAR);
3562 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
3563 return status;
3565 if (info->Type != REG_DWORD)
3567 buffer[size / sizeof(WCHAR)] = 0;
3568 *value = wcstoul( (WCHAR *)info->Data, 0, 16 );
3570 else memcpy( value, info->Data, sizeof(*value) );
3571 return status;
3574 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
3575 void *data, ULONG in_size, ULONG *out_size )
3577 NTSTATUS status;
3578 UNICODE_STRING str;
3579 ULONG size;
3580 char *buffer;
3581 KEY_VALUE_PARTIAL_INFORMATION *info;
3582 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
3584 RtlInitUnicodeString( &str, name );
3586 size = info_size + in_size;
3587 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
3588 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3589 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
3590 if (!status || status == STATUS_BUFFER_OVERFLOW)
3592 if (out_size) *out_size = info->DataLength;
3593 if (data && !status) memcpy( data, info->Data, info->DataLength );
3595 RtlFreeHeap( GetProcessHeap(), 0, buffer );
3596 return status;
3600 /******************************************************************
3601 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3603 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
3604 void *data, ULONG in_size, ULONG *out_size )
3606 static const WCHAR optionsW[] = L"\\Registry\\Machine\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options";
3607 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
3608 OBJECT_ATTRIBUTES attr;
3609 UNICODE_STRING name_str;
3610 HANDLE hkey;
3611 NTSTATUS status;
3612 ULONG len;
3613 WCHAR *p;
3615 attr.Length = sizeof(attr);
3616 attr.RootDirectory = 0;
3617 attr.ObjectName = &name_str;
3618 attr.Attributes = OBJ_CASE_INSENSITIVE;
3619 attr.SecurityDescriptor = NULL;
3620 attr.SecurityQualityOfService = NULL;
3622 p = key->Buffer + key->Length / sizeof(WCHAR);
3623 while (p > key->Buffer && p[-1] != '\\') p--;
3624 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
3625 name_str.Buffer = path;
3626 name_str.Length = sizeof(optionsW) + len;
3627 name_str.MaximumLength = name_str.Length;
3628 memcpy( path, optionsW, sizeof(optionsW) );
3629 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
3630 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
3632 if (type == REG_DWORD)
3634 if (out_size) *out_size = sizeof(ULONG);
3635 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
3636 else status = STATUS_BUFFER_OVERFLOW;
3638 else status = query_string_option( hkey, value, type, data, in_size, out_size );
3640 NtClose( hkey );
3641 return status;
3645 /******************************************************************
3646 * RtlDllShutdownInProgress (NTDLL.@)
3648 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
3650 return process_detaching;
3653 /****************************************************************************
3654 * LdrResolveDelayLoadedAPI (NTDLL.@)
3656 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
3657 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
3658 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
3659 IMAGE_THUNK_DATA* addr, ULONG flags )
3661 IMAGE_THUNK_DATA *pIAT, *pINT;
3662 DELAYLOAD_INFO delayinfo;
3663 UNICODE_STRING mod;
3664 const CHAR* name;
3665 HMODULE *phmod;
3666 NTSTATUS nts;
3667 FARPROC fp;
3668 DWORD id;
3670 TRACE( "(%p, %p, %p, %p, %p, 0x%08lx)\n", base, desc, dllhook, syshook, addr, flags );
3672 phmod = get_rva(base, desc->ModuleHandleRVA);
3673 pIAT = get_rva(base, desc->ImportAddressTableRVA);
3674 pINT = get_rva(base, desc->ImportNameTableRVA);
3675 name = get_rva(base, desc->DllNameRVA);
3676 id = addr - pIAT;
3678 if (!*phmod)
3680 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
3682 nts = STATUS_NO_MEMORY;
3683 goto fail;
3685 nts = LdrLoadDll(NULL, 0, &mod, phmod);
3686 RtlFreeUnicodeString(&mod);
3687 if (nts) goto fail;
3690 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3691 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
3692 else
3694 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3695 ANSI_STRING fnc;
3697 RtlInitAnsiString(&fnc, (char*)iibn->Name);
3698 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
3700 if (!nts)
3702 pIAT[id].u1.Function = (ULONG_PTR)fp;
3703 return fp;
3706 fail:
3707 delayinfo.Size = sizeof(delayinfo);
3708 delayinfo.DelayloadDescriptor = desc;
3709 delayinfo.ThunkAddress = addr;
3710 delayinfo.TargetDllName = name;
3711 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
3712 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
3713 delayinfo.TargetModuleBase = *phmod;
3714 delayinfo.Unused = NULL;
3715 delayinfo.LastError = nts;
3717 if (dllhook)
3718 return dllhook(4, &delayinfo);
3720 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3722 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3723 return syshook(name, (const char *)ord);
3725 else
3727 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3728 return syshook(name, (const char *)iibn->Name);
3732 /******************************************************************
3733 * LdrShutdownProcess (NTDLL.@)
3736 void WINAPI LdrShutdownProcess(void)
3738 BOOL detaching = process_detaching;
3740 TRACE("()\n");
3742 process_detaching = TRUE;
3743 if (!detaching)
3744 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3746 process_detach();
3750 /******************************************************************
3751 * RtlExitUserProcess (NTDLL.@)
3753 void WINAPI RtlExitUserProcess( DWORD status )
3755 RtlEnterCriticalSection( &loader_section );
3756 RtlAcquirePebLock();
3757 NtTerminateProcess( 0, status );
3758 LdrShutdownProcess();
3759 for (;;) NtTerminateProcess( GetCurrentProcess(), status );
3762 /******************************************************************
3763 * LdrShutdownThread (NTDLL.@)
3766 void WINAPI LdrShutdownThread(void)
3768 PLIST_ENTRY mark, entry;
3769 LDR_DATA_TABLE_ENTRY *mod;
3770 WINE_MODREF *wm;
3771 UINT i;
3772 void **pointers;
3774 TRACE("()\n");
3776 /* don't do any detach calls if process is exiting */
3777 if (process_detaching) return;
3779 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3781 RtlEnterCriticalSection( &loader_section );
3782 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3784 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3785 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3787 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
3788 InInitializationOrderLinks);
3789 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3790 continue;
3791 if ( mod->Flags & LDR_NO_DLL_CALLS )
3792 continue;
3794 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3795 DLL_THREAD_DETACH, NULL );
3798 if (wm->ldr.TlsIndex == -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_DETACH );
3800 RtlAcquirePebLock();
3801 if (NtCurrentTeb()->TlsLinks.Flink) RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3802 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3804 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3805 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3807 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 2 );
3808 NtCurrentTeb()->FlsSlots = NULL;
3809 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3810 NtCurrentTeb()->TlsExpansionSlots = NULL;
3811 RtlReleasePebLock();
3813 RtlLeaveCriticalSection( &loader_section );
3814 /* don't call DbgUiGetThreadDebugObject as some apps hook it and terminate if called */
3815 if (NtCurrentTeb()->DbgSsReserved[1]) NtClose( NtCurrentTeb()->DbgSsReserved[1] );
3816 RtlFreeThreadActivationContextStack();
3818 heap_thread_detach();
3822 /***********************************************************************
3823 * free_modref
3826 static void free_modref( WINE_MODREF *wm )
3828 SINGLE_LIST_ENTRY *entry;
3829 LDR_DEPENDENCY *dep;
3831 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
3832 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
3833 if (wm->ldr.InInitializationOrderLinks.Flink)
3834 RemoveEntryList(&wm->ldr.InInitializationOrderLinks);
3836 while ((entry = wm->ldr.DdagNode->Dependencies.Tail))
3838 dep = CONTAINING_RECORD( entry, LDR_DEPENDENCY, dependency_to_entry );
3839 assert( dep->dependency_from == wm->ldr.DdagNode );
3840 remove_module_dependency( dep );
3843 while ((entry = wm->ldr.DdagNode->IncomingDependencies.Tail))
3845 dep = CONTAINING_RECORD( entry, LDR_DEPENDENCY, dependency_from_entry );
3846 assert( dep->dependency_to == wm->ldr.DdagNode );
3847 remove_module_dependency( dep );
3850 RemoveEntryList(&wm->ldr.NodeModuleLink);
3851 if (IsListEmpty(&wm->ldr.DdagNode->Modules))
3852 RtlFreeHeap( GetProcessHeap(), 0, wm->ldr.DdagNode );
3854 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3855 if (!TRACE_ON(module))
3856 TRACE_(loaddll)("Unloaded module %s : %s\n",
3857 debugstr_w(wm->ldr.FullDllName.Buffer),
3858 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3860 free_tls_slot( &wm->ldr );
3861 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3862 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.DllBase );
3863 if (cached_modref == wm) cached_modref = NULL;
3864 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3865 RtlFreeHeap( GetProcessHeap(), 0, wm );
3868 /***********************************************************************
3869 * MODULE_FlushModrefs
3871 * Remove all unused modrefs and call the internal unloading routines
3872 * for the library type.
3874 * The loader_section must be locked while calling this function.
3876 static void MODULE_FlushModrefs(void)
3878 PLIST_ENTRY mark, entry, prev;
3879 LDR_DATA_TABLE_ENTRY *mod;
3880 WINE_MODREF*wm;
3882 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3883 for (entry = mark->Blink; entry != mark; entry = prev)
3885 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
3886 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3887 prev = entry->Blink;
3888 if (!mod->LoadCount) free_modref( wm );
3891 /* check load order list too for modules that haven't been initialized yet */
3892 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3893 for (entry = mark->Blink; entry != mark; entry = prev)
3895 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3896 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3897 prev = entry->Blink;
3898 if (!mod->LoadCount) free_modref( wm );
3902 /***********************************************************************
3903 * MODULE_DecRefCount
3905 * The loader_section must be locked while calling this function.
3907 static NTSTATUS MODULE_DecRefCount( LDR_DDAG_NODE *node, void *context )
3909 LDR_DATA_TABLE_ENTRY *mod;
3910 WINE_MODREF *wm;
3912 mod = CONTAINING_RECORD( node->Modules.Flink, LDR_DATA_TABLE_ENTRY, NodeModuleLink );
3913 wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
3915 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3916 return STATUS_SUCCESS;
3918 if ( wm->ldr.LoadCount <= 0 )
3919 return STATUS_SUCCESS;
3921 --wm->ldr.LoadCount;
3922 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3924 if ( wm->ldr.LoadCount == 0 )
3926 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3927 walk_node_dependencies( node, context, MODULE_DecRefCount );
3928 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3929 module_push_unload_trace( wm );
3931 return STATUS_SUCCESS;
3934 /******************************************************************
3935 * LdrUnloadDll (NTDLL.@)
3939 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3941 WINE_MODREF *wm;
3942 NTSTATUS retv = STATUS_SUCCESS;
3944 if (process_detaching) return retv;
3946 TRACE("(%p)\n", hModule);
3948 RtlEnterCriticalSection( &loader_section );
3950 free_lib_count++;
3951 if ((wm = get_modref( hModule )) != NULL)
3953 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3955 /* Recursively decrement reference counts */
3956 MODULE_DecRefCount( wm->ldr.DdagNode, NULL );
3958 /* Call process detach notifications */
3959 if ( free_lib_count <= 1 )
3961 process_detach();
3962 MODULE_FlushModrefs();
3965 TRACE("END\n");
3967 else
3968 retv = STATUS_DLL_NOT_FOUND;
3970 free_lib_count--;
3972 RtlLeaveCriticalSection( &loader_section );
3974 return retv;
3977 /***********************************************************************
3978 * RtlImageNtHeader (NTDLL.@)
3980 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3982 IMAGE_NT_HEADERS *ret;
3984 __TRY
3986 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3988 ret = NULL;
3989 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3991 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3992 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3995 __EXCEPT_PAGE_FAULT
3997 return NULL;
3999 __ENDTRY
4000 return ret;
4003 /***********************************************************************
4004 * process_breakpoint
4006 * Trigger a debug breakpoint if the process is being debugged.
4008 static void process_breakpoint(void)
4010 DWORD_PTR port = 0;
4012 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort, &port, sizeof(port), NULL );
4013 if (!port) return;
4015 __TRY
4017 DbgBreakPoint();
4019 __EXCEPT_ALL
4021 /* do nothing */
4023 __ENDTRY
4027 /***********************************************************************
4028 * load_global_options
4030 static void load_global_options(void)
4032 OBJECT_ATTRIBUTES attr;
4033 UNICODE_STRING bootstrap_mode_str = RTL_CONSTANT_STRING( L"WINEBOOTSTRAPMODE" );
4034 UNICODE_STRING session_manager_str =
4035 RTL_CONSTANT_STRING( L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
4036 UNICODE_STRING val_str;
4037 HANDLE hkey;
4039 val_str.MaximumLength = 0;
4040 is_prefix_bootstrap =
4041 RtlQueryEnvironmentVariable_U( NULL, &bootstrap_mode_str, &val_str ) != STATUS_VARIABLE_NOT_FOUND;
4043 attr.Length = sizeof(attr);
4044 attr.RootDirectory = 0;
4045 attr.ObjectName = &session_manager_str;
4046 attr.Attributes = OBJ_CASE_INSENSITIVE;
4047 attr.SecurityDescriptor = NULL;
4048 attr.SecurityQualityOfService = NULL;
4050 if (!NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))
4052 query_dword_option( hkey, L"SafeProcessSearchMode", &path_safe_mode );
4053 query_dword_option( hkey, L"SafeDllSearchMode", &dll_safe_mode );
4054 NtClose( hkey );
4060 #ifdef _WIN64
4062 static void (WINAPI *pWow64LdrpInitialize)( CONTEXT *ctx );
4064 void (WINAPI *pWow64PrepareForException)( EXCEPTION_RECORD *rec, CONTEXT *context ) = NULL;
4066 static void init_wow64( CONTEXT *context )
4068 if (!imports_fixup_done)
4070 HMODULE wow64;
4071 WINE_MODREF *wm;
4072 NTSTATUS status;
4073 static const WCHAR wow64_path[] = L"C:\\windows\\system32\\wow64.dll";
4075 if ((status = load_dll( NULL, wow64_path, 0, &wm, FALSE )))
4077 ERR( "could not load %s, status %lx\n", debugstr_w(wow64_path), status );
4078 NtTerminateProcess( GetCurrentProcess(), status );
4080 wow64 = wm->ldr.DllBase;
4081 #define GET_PTR(name) \
4082 if (!(p ## name = RtlFindExportedRoutineByName( wow64, #name ))) ERR( "failed to load %s\n", #name )
4084 GET_PTR( Wow64LdrpInitialize );
4085 GET_PTR( Wow64PrepareForException );
4086 #undef GET_PTR
4087 imports_fixup_done = TRUE;
4090 RtlAcquirePebLock();
4091 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
4092 RtlReleasePebLock();
4094 RtlLeaveCriticalSection( &loader_section );
4095 pWow64LdrpInitialize( context );
4099 #else
4101 void *Wow64Transition = NULL;
4103 static void map_wow64cpu(void)
4105 SIZE_T size = 0;
4106 OBJECT_ATTRIBUTES attr;
4107 UNICODE_STRING string = RTL_CONSTANT_STRING( L"\\??\\C:\\windows\\sysnative\\wow64cpu.dll" );
4108 HANDLE file, section;
4109 IO_STATUS_BLOCK io;
4110 NTSTATUS status;
4112 InitializeObjectAttributes( &attr, &string, 0, NULL, NULL );
4113 if ((status = NtOpenFile( &file, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ,
4114 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
4116 WARN("failed to open wow64cpu, status %#lx\n", status);
4117 return;
4119 if (!NtCreateSection( &section, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
4120 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
4121 NULL, NULL, PAGE_EXECUTE_READ, SEC_COMMIT, file ))
4123 NtMapViewOfSection( section, NtCurrentProcess(), &Wow64Transition, 0,
4124 0, NULL, &size, ViewShare, 0, PAGE_EXECUTE_READ );
4125 NtClose( section );
4127 NtClose( file );
4130 static void init_wow64( CONTEXT *context )
4132 PEB *peb = NtCurrentTeb()->Peb;
4133 PEB64 *peb64 = UlongToPtr( NtCurrentTeb64()->Peb );
4135 if (Wow64Transition) return; /* already initialized */
4137 peb64->OSMajorVersion = peb->OSMajorVersion;
4138 peb64->OSMinorVersion = peb->OSMinorVersion;
4139 peb64->OSBuildNumber = peb->OSBuildNumber;
4140 peb64->OSPlatformId = peb->OSPlatformId;
4142 #define SET_INIT_BLOCK(func) LdrSystemDllInitBlock.p ## func = PtrToUlong( &func )
4143 SET_INIT_BLOCK( KiUserApcDispatcher );
4144 SET_INIT_BLOCK( KiUserExceptionDispatcher );
4145 SET_INIT_BLOCK( LdrInitializeThunk );
4146 SET_INIT_BLOCK( LdrSystemDllInitBlock );
4147 SET_INIT_BLOCK( RtlUserThreadStart );
4148 SET_INIT_BLOCK( KiUserCallbackDispatcher );
4149 /* SET_INIT_BLOCK( RtlpQueryProcessDebugInformationRemote ); */
4150 /* SET_INIT_BLOCK( RtlpFreezeTimeBias ); */
4151 /* LdrSystemDllInitBlock.ntdll_handle */
4152 #undef SET_INIT_BLOCK
4154 map_wow64cpu();
4156 #endif
4159 /* release some address space once dlls are loaded*/
4160 static void release_address_space(void)
4162 #ifndef _WIN64
4163 void *addr = (void *)1;
4164 SIZE_T size = 0;
4166 NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
4167 #endif
4170 /******************************************************************
4171 * LdrInitializeThunk (NTDLL.@)
4173 * Attach to all the loaded dlls.
4174 * If this is the first time, perform the full process initialization.
4176 void WINAPI LdrInitializeThunk( CONTEXT *context, ULONG_PTR unknown2, ULONG_PTR unknown3, ULONG_PTR unknown4 )
4178 static int attach_done;
4179 NTSTATUS status;
4180 ULONG_PTR cookie;
4181 WINE_MODREF *wm;
4182 void **entry;
4184 #ifdef __i386__
4185 entry = (void **)&context->Eax;
4186 #elif defined(__x86_64__)
4187 entry = (void **)&context->Rcx;
4188 #elif defined(__arm__)
4189 entry = (void **)&context->R0;
4190 #elif defined(__aarch64__)
4191 entry = (void **)&context->u.s.X0;
4192 #endif
4194 if (process_detaching) NtTerminateThread( GetCurrentThread(), 0 );
4196 RtlEnterCriticalSection( &loader_section );
4198 if (!imports_fixup_done)
4200 MEMORY_BASIC_INFORMATION meminfo;
4201 ANSI_STRING base_thread_init_thunk = RTL_CONSTANT_STRING( "BaseThreadInitThunk" );
4202 ANSI_STRING ctrl_routine = RTL_CONSTANT_STRING( "CtrlRoutine" );
4203 WINE_MODREF *kernel32;
4204 PEB *peb = NtCurrentTeb()->Peb;
4206 NtQueryVirtualMemory( GetCurrentProcess(), LdrInitializeThunk, MemoryBasicInformation,
4207 &meminfo, sizeof(meminfo), NULL );
4209 peb->LdrData = &ldr;
4210 peb->FastPebLock = &peb_lock;
4211 peb->TlsBitmap = &tls_bitmap;
4212 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
4213 peb->LoaderLock = &loader_section;
4214 peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
4216 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
4217 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
4218 sizeof(peb->TlsExpansionBitmapBits) * 8 );
4219 /* TLS index 0 is always reserved, and wow64 reserves extra TLS entries */
4220 RtlSetBits( peb->TlsBitmap, 0, NtCurrentTeb()->WowTebOffset ? WOW64_TLS_MAX_NUMBER : 1 );
4222 init_user_process_params();
4223 load_global_options();
4224 version_init();
4226 get_env_var( L"WINESYSTEMDLLPATH", 0, &system_dll_path );
4228 wm = build_main_module();
4229 wm->ldr.LoadCount = -1;
4231 build_ntdll_module( meminfo.AllocationBase );
4233 if (NtCurrentTeb()->WowTebOffset) init_wow64( context );
4235 if ((status = load_dll( NULL, L"kernel32.dll", 0, &kernel32, FALSE )) != STATUS_SUCCESS)
4237 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
4238 NtTerminateProcess( GetCurrentProcess(), status );
4240 node_kernel32 = kernel32->ldr.DdagNode;
4241 if ((status = LdrGetProcedureAddress( kernel32->ldr.DllBase, &base_thread_init_thunk,
4242 0, (void **)&pBaseThreadInitThunk )) != STATUS_SUCCESS)
4244 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %lx\n", status );
4245 NtTerminateProcess( GetCurrentProcess(), status );
4247 LdrGetProcedureAddress( kernel32->ldr.DllBase, &ctrl_routine, 0, (void **)&pCtrlRoutine );
4249 actctx_init();
4250 locale_init();
4251 if (wm->ldr.Flags & LDR_COR_ILONLY)
4252 status = fixup_imports_ilonly( wm, NULL, entry );
4253 else
4254 status = fixup_imports( wm, NULL );
4256 if (status)
4258 ERR( "Importing dlls for %s failed, status %lx\n",
4259 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
4260 NtTerminateProcess( GetCurrentProcess(), status );
4262 imports_fixup_done = TRUE;
4264 else wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
4266 #ifdef _WIN64
4267 if (NtCurrentTeb()->WowTebOffset) init_wow64( context );
4268 #endif
4270 RtlAcquirePebLock();
4271 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
4272 RtlReleasePebLock();
4274 NtCurrentTeb()->FlsSlots = fls_alloc_data();
4276 if (!attach_done) /* first time around */
4278 attach_done = 1;
4279 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
4281 ERR( "TLS init failed when loading %s, status %lx\n",
4282 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
4283 NtTerminateProcess( GetCurrentProcess(), status );
4285 wm->ldr.Flags |= LDR_PROCESS_ATTACHED; /* don't try to attach again */
4286 if (wm->ldr.ActivationContext)
4287 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
4289 if ((status = process_attach( node_ntdll, context ))
4290 || (status = process_attach( node_kernel32, context )))
4292 ERR( "Initializing system dll for %s failed, status %lx\n",
4293 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
4294 NtTerminateProcess( GetCurrentProcess(), status );
4297 if ((status = walk_node_dependencies( wm->ldr.DdagNode, context, process_attach )))
4299 if (last_failed_modref)
4300 ERR( "%s failed to initialize, aborting\n",
4301 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
4302 ERR( "Initializing dlls for %s failed, status %lx\n",
4303 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
4304 NtTerminateProcess( GetCurrentProcess(), status );
4306 release_address_space();
4307 if (wm->ldr.TlsIndex == -1) call_tls_callbacks( wm->ldr.DllBase, DLL_PROCESS_ATTACH );
4308 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
4309 process_breakpoint();
4311 else
4313 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
4314 NtTerminateThread( GetCurrentThread(), status );
4315 thread_attach();
4316 if (wm->ldr.TlsIndex == -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_ATTACH );
4319 RtlLeaveCriticalSection( &loader_section );
4320 signal_start_thread( context );
4324 /***********************************************************************
4325 * RtlImageDirectoryEntryToData (NTDLL.@)
4327 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
4329 const IMAGE_NT_HEADERS *nt;
4330 DWORD addr;
4332 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
4333 module = (HMODULE)((ULONG_PTR)module & ~3);
4334 if (!(nt = RtlImageNtHeader( module ))) return NULL;
4335 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
4337 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
4339 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
4340 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
4341 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
4342 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
4344 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
4346 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
4348 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
4349 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
4350 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
4351 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
4353 else return NULL;
4355 /* not mapped as image, need to find the section containing the virtual address */
4356 return RtlImageRvaToVa( nt, module, addr, NULL );
4360 /***********************************************************************
4361 * RtlImageRvaToSection (NTDLL.@)
4363 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
4364 HMODULE module, DWORD rva )
4366 int i;
4367 const IMAGE_SECTION_HEADER *sec;
4369 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
4370 nt->FileHeader.SizeOfOptionalHeader);
4371 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
4373 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
4374 return (PIMAGE_SECTION_HEADER)sec;
4376 return NULL;
4380 /***********************************************************************
4381 * RtlImageRvaToVa (NTDLL.@)
4383 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
4384 DWORD rva, IMAGE_SECTION_HEADER **section )
4386 IMAGE_SECTION_HEADER *sec;
4388 if (section && *section) /* try this section first */
4390 sec = *section;
4391 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
4392 goto found;
4394 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
4395 found:
4396 if (section) *section = sec;
4397 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
4401 /***********************************************************************
4402 * RtlAddressInSectionTable (NTDLL.@)
4404 PVOID WINAPI RtlAddressInSectionTable( const IMAGE_NT_HEADERS *nt, HMODULE module,
4405 DWORD rva )
4407 return RtlImageRvaToVa( nt, module, rva, NULL );
4410 /***********************************************************************
4411 * RtlPcToFileHeader (NTDLL.@)
4413 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
4415 LDR_DATA_TABLE_ENTRY *module;
4416 PVOID ret = NULL;
4418 RtlEnterCriticalSection( &loader_section );
4419 if (!LdrFindEntryForAddress( pc, &module )) ret = module->DllBase;
4420 RtlLeaveCriticalSection( &loader_section );
4421 *address = ret;
4422 return ret;
4426 /****************************************************************************
4427 * LdrGetDllDirectory (NTDLL.@)
4429 NTSTATUS WINAPI LdrGetDllDirectory( UNICODE_STRING *dir )
4431 NTSTATUS status = STATUS_SUCCESS;
4433 RtlEnterCriticalSection( &dlldir_section );
4434 dir->Length = dll_directory.Length + sizeof(WCHAR);
4435 if (dir->MaximumLength >= dir->Length) RtlCopyUnicodeString( dir, &dll_directory );
4436 else
4438 status = STATUS_BUFFER_TOO_SMALL;
4439 if (dir->MaximumLength) dir->Buffer[0] = 0;
4441 RtlLeaveCriticalSection( &dlldir_section );
4442 return status;
4446 /****************************************************************************
4447 * LdrSetDllDirectory (NTDLL.@)
4449 NTSTATUS WINAPI LdrSetDllDirectory( const UNICODE_STRING *dir )
4451 NTSTATUS status = STATUS_SUCCESS;
4452 UNICODE_STRING new;
4454 if (!dir->Buffer) RtlInitUnicodeString( &new, NULL );
4455 else if ((status = RtlDuplicateUnicodeString( 1, dir, &new ))) return status;
4457 RtlEnterCriticalSection( &dlldir_section );
4458 RtlFreeUnicodeString( &dll_directory );
4459 dll_directory = new;
4460 RtlLeaveCriticalSection( &dlldir_section );
4461 return status;
4465 /****************************************************************************
4466 * LdrAddDllDirectory (NTDLL.@)
4468 NTSTATUS WINAPI LdrAddDllDirectory( const UNICODE_STRING *dir, void **cookie )
4470 FILE_BASIC_INFORMATION info;
4471 UNICODE_STRING nt_name;
4472 NTSTATUS status;
4473 OBJECT_ATTRIBUTES attr;
4474 DWORD len;
4475 struct dll_dir_entry *ptr;
4476 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir->Buffer );
4478 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
4479 return STATUS_INVALID_PARAMETER;
4481 status = RtlDosPathNameToNtPathName_U_WithStatus( dir->Buffer, &nt_name, NULL, NULL );
4482 if (status) return status;
4483 len = nt_name.Length / sizeof(WCHAR);
4484 if (!(ptr = RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] ))))
4485 return STATUS_NO_MEMORY;
4486 memcpy( ptr->dir, nt_name.Buffer, len * sizeof(WCHAR) );
4488 attr.Length = sizeof(attr);
4489 attr.RootDirectory = 0;
4490 attr.Attributes = OBJ_CASE_INSENSITIVE;
4491 attr.ObjectName = &nt_name;
4492 attr.SecurityDescriptor = NULL;
4493 attr.SecurityQualityOfService = NULL;
4494 status = NtQueryAttributesFile( &attr, &info );
4495 RtlFreeUnicodeString( &nt_name );
4497 if (!status)
4499 TRACE( "%s\n", debugstr_w( ptr->dir ));
4500 RtlEnterCriticalSection( &dlldir_section );
4501 list_add_head( &dll_dir_list, &ptr->entry );
4502 RtlLeaveCriticalSection( &dlldir_section );
4503 *cookie = ptr;
4505 else RtlFreeHeap( GetProcessHeap(), 0, ptr );
4506 return status;
4510 /****************************************************************************
4511 * LdrRemoveDllDirectory (NTDLL.@)
4513 NTSTATUS WINAPI LdrRemoveDllDirectory( void *cookie )
4515 struct dll_dir_entry *ptr = cookie;
4517 TRACE( "%s\n", debugstr_w( ptr->dir ));
4519 RtlEnterCriticalSection( &dlldir_section );
4520 list_remove( &ptr->entry );
4521 RtlFreeHeap( GetProcessHeap(), 0, ptr );
4522 RtlLeaveCriticalSection( &dlldir_section );
4523 return STATUS_SUCCESS;
4527 /*************************************************************************
4528 * LdrSetDefaultDllDirectories (NTDLL.@)
4530 NTSTATUS WINAPI LdrSetDefaultDllDirectories( ULONG flags )
4532 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
4533 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
4534 LOAD_LIBRARY_SEARCH_USER_DIRS |
4535 LOAD_LIBRARY_SEARCH_SYSTEM32 |
4536 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
4538 if (!flags || (flags & ~load_library_search_flags)) return STATUS_INVALID_PARAMETER;
4539 default_search_flags = flags;
4540 return STATUS_SUCCESS;
4544 /******************************************************************
4545 * LdrGetDllPath (NTDLL.@)
4547 NTSTATUS WINAPI LdrGetDllPath( PCWSTR module, ULONG flags, PWSTR *path, PWSTR *unknown )
4549 NTSTATUS status;
4550 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
4551 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
4552 LOAD_LIBRARY_SEARCH_USER_DIRS |
4553 LOAD_LIBRARY_SEARCH_SYSTEM32 |
4554 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
4556 if (flags & LOAD_WITH_ALTERED_SEARCH_PATH)
4558 if (flags & load_library_search_flags) return STATUS_INVALID_PARAMETER;
4559 if (default_search_flags) flags |= default_search_flags | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
4561 else if (!(flags & load_library_search_flags)) flags |= default_search_flags;
4563 RtlEnterCriticalSection( &dlldir_section );
4565 if (flags & load_library_search_flags)
4567 status = get_dll_load_path_search_flags( module, flags, path );
4569 else
4571 const WCHAR *dlldir = dll_directory.Length ? dll_directory.Buffer : NULL;
4572 if (!(flags & LOAD_WITH_ALTERED_SEARCH_PATH) || !wcschr( module, L'\\' ))
4573 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4574 status = get_dll_load_path( module, dlldir, dll_safe_mode, path );
4577 RtlLeaveCriticalSection( &dlldir_section );
4578 *unknown = NULL;
4579 return status;
4583 /*************************************************************************
4584 * RtlSetSearchPathMode (NTDLL.@)
4586 NTSTATUS WINAPI RtlSetSearchPathMode( ULONG flags )
4588 int val;
4590 switch (flags)
4592 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE:
4593 val = 1;
4594 break;
4595 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE:
4596 val = 0;
4597 break;
4598 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT:
4599 InterlockedExchange( &path_safe_mode, 2 );
4600 return STATUS_SUCCESS;
4601 default:
4602 return STATUS_INVALID_PARAMETER;
4605 for (;;)
4607 LONG prev = path_safe_mode;
4608 if (prev == 2) break; /* permanently set */
4609 if (InterlockedCompareExchange( &path_safe_mode, val, prev ) == prev) return STATUS_SUCCESS;
4611 return STATUS_ACCESS_DENIED;
4615 /******************************************************************
4616 * RtlGetExePath (NTDLL.@)
4618 NTSTATUS WINAPI RtlGetExePath( PCWSTR name, PWSTR *path )
4620 const WCHAR *dlldir = L".";
4621 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4623 /* same check as NeedCurrentDirectoryForExePathW */
4624 if (!wcschr( name, '\\' ))
4626 UNICODE_STRING name = RTL_CONSTANT_STRING( L"NoDefaultCurrentDirectoryInExePath" ), value = { 0 };
4628 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) != STATUS_VARIABLE_NOT_FOUND)
4629 dlldir = L"";
4631 return get_dll_load_path( module, dlldir, FALSE, path );
4635 /******************************************************************
4636 * RtlGetSearchPath (NTDLL.@)
4638 NTSTATUS WINAPI RtlGetSearchPath( PWSTR *path )
4640 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
4641 return get_dll_load_path( module, NULL, path_safe_mode, path );
4645 /******************************************************************
4646 * RtlReleasePath (NTDLL.@)
4648 void WINAPI RtlReleasePath( PWSTR path )
4650 RtlFreeHeap( GetProcessHeap(), 0, path );
4654 /*********************************************************************
4655 * ApiSetQueryApiSetPresence (NTDLL.@)
4657 NTSTATUS WINAPI ApiSetQueryApiSetPresence( const UNICODE_STRING *name, BOOLEAN *present )
4659 const API_SET_NAMESPACE *map = NtCurrentTeb()->Peb->ApiSetMap;
4660 const API_SET_NAMESPACE_ENTRY *entry;
4661 UNICODE_STRING str;
4663 *present = (!get_apiset_entry( map, name->Buffer, name->Length / sizeof(WCHAR), &entry ) &&
4664 !get_apiset_target( map, entry, NULL, &str ));
4665 return STATUS_SUCCESS;
4669 /*********************************************************************
4670 * ApiSetQueryApiSetPresenceEx (NTDLL.@)
4672 NTSTATUS WINAPI ApiSetQueryApiSetPresenceEx( const UNICODE_STRING *name, BOOLEAN *in_schema, BOOLEAN *present )
4674 const API_SET_NAMESPACE *map = NtCurrentTeb()->Peb->ApiSetMap;
4675 const API_SET_NAMESPACE_ENTRY *entry;
4676 NTSTATUS status;
4677 UNICODE_STRING str;
4678 ULONG i, len = name->Length / sizeof(WCHAR);
4680 /* extension not allowed */
4681 for (i = 0; i < len; i++) if (name->Buffer[i] == '.') return STATUS_INVALID_PARAMETER;
4683 status = get_apiset_entry( map, name->Buffer, len, &entry );
4684 if (status == STATUS_APISET_NOT_PRESENT)
4686 *in_schema = *present = FALSE;
4687 return STATUS_SUCCESS;
4689 if (status) return status;
4691 /* the name must match exactly */
4692 *in_schema = (entry->NameLength == name->Length &&
4693 !wcsnicmp( (WCHAR *)((char *)map + entry->NameOffset), name->Buffer, len ));
4694 *present = *in_schema && !get_apiset_target( map, entry, NULL, &str );
4695 return STATUS_SUCCESS;
4699 /******************************************************************
4700 * DllMain (NTDLL.@)
4702 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
4704 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
4705 return TRUE;