ntdll: Delay mapping a module until we have found the final one to load.
[wine.git] / dlls / ntdll / loader.c
blob6a90770b3b44645745ca5522a8524268835e83c6
1 /*
2 * Loader functions
4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include <assert.h>
23 #include <stdarg.h>
25 #include "ntstatus.h"
26 #define WIN32_NO_STATUS
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29 #include "windef.h"
30 #include "winnt.h"
31 #include "winioctl.h"
32 #include "winternl.h"
33 #include "delayloadhandler.h"
35 #include "wine/exception.h"
36 #include "wine/debug.h"
37 #include "wine/list.h"
38 #include "wine/server.h"
39 #include "ntdll_misc.h"
40 #include "ddk/wdm.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(module);
43 WINE_DECLARE_DEBUG_CHANNEL(relay);
44 WINE_DECLARE_DEBUG_CHANNEL(snoop);
45 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
46 WINE_DECLARE_DEBUG_CHANNEL(imports);
48 #ifdef _WIN64
49 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
50 #endif
51 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
52 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
59 typedef void (CALLBACK *LDRENUMPROC)(LDR_DATA_TABLE_ENTRY *, void *, BOOLEAN *);
61 void (FASTCALL *pBaseThreadInitThunk)(DWORD,LPTHREAD_START_ROUTINE,void *) = NULL;
63 const struct unix_funcs *unix_funcs = NULL;
65 /* windows directory */
66 const WCHAR windows_dir[] = L"C:\\windows";
67 /* system directory with trailing backslash */
68 const WCHAR system_dir[] = L"C:\\windows\\system32\\";
69 const WCHAR syswow64_dir[] = L"C:\\windows\\syswow64\\";
71 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
72 BOOL is_wow64 = FALSE;
74 /* system search path */
75 static const WCHAR system_path[] = L"C:\\windows\\system32;C:\\windows\\system;C:\\windows";
77 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
78 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
79 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
80 static ULONG path_safe_mode; /* path mode set by RtlSetSearchPathMode */
81 static ULONG dll_safe_mode = 1; /* dll search mode */
82 static UNICODE_STRING dll_directory; /* extra path for LdrSetDllDirectory */
83 static DWORD default_search_flags; /* default flags set by LdrSetDefaultDllDirectories */
85 struct dll_dir_entry
87 struct list entry;
88 WCHAR dir[1];
91 static struct list dll_dir_list = LIST_INIT( dll_dir_list ); /* extra dirs from LdrAddDllDirectory */
93 struct ldr_notification
95 struct list entry;
96 PLDR_DLL_NOTIFICATION_FUNCTION callback;
97 void *context;
100 static struct list ldr_notifications = LIST_INIT( ldr_notifications );
102 static const char * const reason_names[] =
104 "PROCESS_DETACH",
105 "PROCESS_ATTACH",
106 "THREAD_ATTACH",
107 "THREAD_DETACH",
108 NULL, NULL, NULL, NULL,
109 "WINE_PREATTACH"
112 struct file_id
114 BYTE ObjectId[16];
117 /* internal representation of loaded modules */
118 typedef struct _wine_modref
120 LDR_DATA_TABLE_ENTRY ldr;
121 struct file_id id;
122 void *unix_entry;
123 int alloc_deps;
124 int nDeps;
125 struct _wine_modref **deps;
126 } WINE_MODREF;
128 static UINT tls_module_count; /* number of modules with TLS directory */
129 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
130 LIST_ENTRY tls_links = { &tls_links, &tls_links };
132 static RTL_CRITICAL_SECTION loader_section;
133 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
135 0, 0, &loader_section,
136 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
137 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
139 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
141 static CRITICAL_SECTION dlldir_section;
142 static CRITICAL_SECTION_DEBUG dlldir_critsect_debug =
144 0, 0, &dlldir_section,
145 { &dlldir_critsect_debug.ProcessLocksList, &dlldir_critsect_debug.ProcessLocksList },
146 0, 0, { (DWORD_PTR)(__FILE__ ": dlldir_section") }
148 static CRITICAL_SECTION dlldir_section = { &dlldir_critsect_debug, -1, 0, 0, 0, 0 };
150 static RTL_CRITICAL_SECTION peb_lock;
151 static RTL_CRITICAL_SECTION_DEBUG peb_critsect_debug =
153 0, 0, &peb_lock,
154 { &peb_critsect_debug.ProcessLocksList, &peb_critsect_debug.ProcessLocksList },
155 0, 0, { (DWORD_PTR)(__FILE__ ": peb_lock") }
157 static RTL_CRITICAL_SECTION peb_lock = { &peb_critsect_debug, -1, 0, 0, 0, 0 };
159 static PEB_LDR_DATA ldr = { sizeof(ldr), TRUE };
160 static RTL_BITMAP tls_bitmap;
161 static RTL_BITMAP tls_expansion_bitmap;
163 static WINE_MODREF *cached_modref;
164 static WINE_MODREF *current_modref;
165 static WINE_MODREF *last_failed_modref;
167 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
168 DWORD flags, WINE_MODREF** pwm );
169 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
170 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
171 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
172 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
173 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
175 /* convert PE image VirtualAddress to Real Address */
176 static inline void *get_rva( HMODULE module, DWORD va )
178 return (void *)((char *)module + va);
181 /* check whether the file name contains a path */
182 static inline BOOL contains_path( LPCWSTR name )
184 return ((*name && (name[1] == ':')) || wcschr(name, '/') || wcschr(name, '\\'));
187 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
189 typedef struct _RTL_UNLOAD_EVENT_TRACE
191 void *BaseAddress;
192 SIZE_T SizeOfImage;
193 ULONG Sequence;
194 ULONG TimeDateStamp;
195 ULONG CheckSum;
196 WCHAR ImageName[32];
197 } RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
199 static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
200 static RTL_UNLOAD_EVENT_TRACE *unload_trace_ptr;
201 static unsigned int unload_trace_seq;
203 static void module_push_unload_trace( const LDR_DATA_TABLE_ENTRY *ldr )
205 RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
206 unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
208 ptr->BaseAddress = ldr->DllBase;
209 ptr->SizeOfImage = ldr->SizeOfImage;
210 ptr->Sequence = unload_trace_seq;
211 ptr->TimeDateStamp = ldr->TimeDateStamp;
212 ptr->CheckSum = ldr->CheckSum;
213 memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
214 ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
216 unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
217 unload_trace_ptr = unload_traces;
220 /*********************************************************************
221 * RtlGetUnloadEventTrace [NTDLL.@]
223 RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
225 return unload_traces;
228 /*********************************************************************
229 * RtlGetUnloadEventTraceEx [NTDLL.@]
231 void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
233 static unsigned int element_size = sizeof(*unload_traces);
234 static unsigned int element_count = ARRAY_SIZE(unload_traces);
236 *size = &element_size;
237 *count = &element_count;
238 *trace = &unload_trace_ptr;
241 /*************************************************************************
242 * call_dll_entry_point
244 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
245 * their entry point, so we need a small asm wrapper. Testing indicates
246 * that only modifying esi leads to a crash, so use this one to backup
247 * ebp while running the dll entry proc.
249 #ifdef __i386__
250 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
251 __ASM_GLOBAL_FUNC(call_dll_entry_point,
252 "pushl %ebp\n\t"
253 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
254 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
255 "movl %esp,%ebp\n\t"
256 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
257 "pushl %ebx\n\t"
258 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
259 "pushl %esi\n\t"
260 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
261 "pushl %edi\n\t"
262 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
263 "movl %ebp,%esi\n\t"
264 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
265 "pushl 20(%ebp)\n\t"
266 "pushl 16(%ebp)\n\t"
267 "pushl 12(%ebp)\n\t"
268 "movl 8(%ebp),%eax\n\t"
269 "call *%eax\n\t"
270 "movl %esi,%ebp\n\t"
271 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
272 "leal -12(%ebp),%esp\n\t"
273 "popl %edi\n\t"
274 __ASM_CFI(".cfi_same_value %edi\n\t")
275 "popl %esi\n\t"
276 __ASM_CFI(".cfi_same_value %esi\n\t")
277 "popl %ebx\n\t"
278 __ASM_CFI(".cfi_same_value %ebx\n\t")
279 "popl %ebp\n\t"
280 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
281 __ASM_CFI(".cfi_same_value %ebp\n\t")
282 "ret" )
283 #else /* __i386__ */
284 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
285 UINT reason, void *reserved )
287 return proc( module, reason, reserved );
289 #endif /* __i386__ */
292 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
293 /*************************************************************************
294 * stub_entry_point
296 * Entry point for stub functions.
298 static void WINAPI stub_entry_point( const char *dll, const char *name, void *ret_addr )
300 EXCEPTION_RECORD rec;
302 rec.ExceptionCode = EXCEPTION_WINE_STUB;
303 rec.ExceptionFlags = EH_NONCONTINUABLE;
304 rec.ExceptionRecord = NULL;
305 rec.ExceptionAddress = ret_addr;
306 rec.NumberParameters = 2;
307 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
308 rec.ExceptionInformation[1] = (ULONG_PTR)name;
309 for (;;) RtlRaiseException( &rec );
313 #include "pshpack1.h"
314 #ifdef __i386__
315 struct stub
317 BYTE pushl1; /* pushl $name */
318 const char *name;
319 BYTE pushl2; /* pushl $dll */
320 const char *dll;
321 BYTE call; /* call stub_entry_point */
322 DWORD entry;
324 #elif defined(__arm__)
325 struct stub
327 DWORD ldr_r0; /* ldr r0, $dll */
328 DWORD ldr_r1; /* ldr r1, $name */
329 DWORD mov_r2_lr; /* mov r2, lr */
330 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
331 const char *dll;
332 const char *name;
333 const void* entry;
335 #elif defined(__aarch64__)
336 struct stub
338 DWORD ldr_x0; /* ldr x0, $dll */
339 DWORD ldr_x1; /* ldr x1, $name */
340 DWORD mov_x2_lr; /* mov x2, lr */
341 DWORD ldr_x16; /* ldr x16, $entry */
342 DWORD br_x16; /* br x16 */
343 const char *dll;
344 const char *name;
345 const void *entry;
347 #else
348 struct stub
350 BYTE movq_rdi[2]; /* movq $dll,%rdi */
351 const char *dll;
352 BYTE movq_rsi[2]; /* movq $name,%rsi */
353 const char *name;
354 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
355 BYTE movq_rax[2]; /* movq $entry, %rax */
356 const void* entry;
357 BYTE jmpq_rax[2]; /* jmp %rax */
359 #endif
360 #include "poppack.h"
362 /*************************************************************************
363 * allocate_stub
365 * Allocate a stub entry point.
367 static ULONG_PTR allocate_stub( const char *dll, const char *name )
369 #define MAX_SIZE 65536
370 static struct stub *stubs;
371 static unsigned int nb_stubs;
372 struct stub *stub;
374 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
376 if (!stubs)
378 SIZE_T size = MAX_SIZE;
379 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
380 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
381 return 0xdeadbeef;
383 stub = &stubs[nb_stubs++];
384 #ifdef __i386__
385 stub->pushl1 = 0x68; /* pushl $name */
386 stub->name = name;
387 stub->pushl2 = 0x68; /* pushl $dll */
388 stub->dll = dll;
389 stub->call = 0xe8; /* call stub_entry_point */
390 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
391 #elif defined(__arm__)
392 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
393 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
394 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
395 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
396 stub->dll = dll;
397 stub->name = name;
398 stub->entry = stub_entry_point;
399 #elif defined(__aarch64__)
400 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
401 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
402 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
403 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
404 stub->br_x16 = 0xd61f0200; /* br x16 */
405 stub->dll = dll;
406 stub->name = name;
407 stub->entry = stub_entry_point;
408 #else
409 stub->movq_rdi[0] = 0x48; /* movq $dll,%rcx */
410 stub->movq_rdi[1] = 0xb9;
411 stub->dll = dll;
412 stub->movq_rsi[0] = 0x48; /* movq $name,%rdx */
413 stub->movq_rsi[1] = 0xba;
414 stub->name = name;
415 stub->movq_rsp_rdx[0] = 0x4c; /* movq (%rsp),%r8 */
416 stub->movq_rsp_rdx[1] = 0x8b;
417 stub->movq_rsp_rdx[2] = 0x04;
418 stub->movq_rsp_rdx[3] = 0x24;
419 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
420 stub->movq_rax[1] = 0xb8;
421 stub->entry = stub_entry_point;
422 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
423 stub->jmpq_rax[1] = 0xe0;
424 #endif
425 return (ULONG_PTR)stub;
428 #else /* __i386__ */
429 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
430 #endif /* __i386__ */
432 /* call ldr notifications */
433 static void call_ldr_notifications( ULONG reason, LDR_DATA_TABLE_ENTRY *module )
435 struct ldr_notification *notify, *notify_next;
436 LDR_DLL_NOTIFICATION_DATA data;
438 data.Loaded.Flags = 0;
439 data.Loaded.FullDllName = &module->FullDllName;
440 data.Loaded.BaseDllName = &module->BaseDllName;
441 data.Loaded.DllBase = module->DllBase;
442 data.Loaded.SizeOfImage = module->SizeOfImage;
444 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
446 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
447 notify->callback, reason, &data, notify->context );
449 notify->callback(reason, &data, notify->context);
451 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
452 notify->callback, reason, &data, notify->context );
456 /*************************************************************************
457 * get_modref
459 * Looks for the referenced HMODULE in the current process
460 * The loader_section must be locked while calling this function.
462 static WINE_MODREF *get_modref( HMODULE hmod )
464 PLIST_ENTRY mark, entry;
465 PLDR_DATA_TABLE_ENTRY mod;
467 if (cached_modref && cached_modref->ldr.DllBase == hmod) return cached_modref;
469 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
470 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
472 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
473 if (mod->DllBase == hmod)
474 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
476 return NULL;
480 /**********************************************************************
481 * find_basename_module
483 * Find a module from its base name.
484 * The loader_section must be locked while calling this function
486 static WINE_MODREF *find_basename_module( LPCWSTR name )
488 PLIST_ENTRY mark, entry;
489 UNICODE_STRING name_str;
491 RtlInitUnicodeString( &name_str, name );
493 if (cached_modref && RtlEqualUnicodeString( &name_str, &cached_modref->ldr.BaseDllName, TRUE ))
494 return cached_modref;
496 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
497 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
499 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
500 if (RtlEqualUnicodeString( &name_str, &mod->BaseDllName, TRUE ))
502 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
503 return cached_modref;
506 return NULL;
510 /**********************************************************************
511 * find_fullname_module
513 * Find a module from its full path name.
514 * The loader_section must be locked while calling this function
516 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
518 PLIST_ENTRY mark, entry;
519 UNICODE_STRING name = *nt_name;
521 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
522 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
523 name.Buffer += 4;
525 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
526 return cached_modref;
528 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
529 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
531 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
532 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
534 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
535 return cached_modref;
538 return NULL;
542 /**********************************************************************
543 * find_fileid_module
545 * Find a module from its file id.
546 * The loader_section must be locked while calling this function
548 static WINE_MODREF *find_fileid_module( const struct file_id *id )
550 LIST_ENTRY *mark, *entry;
552 if (cached_modref && !memcmp( &cached_modref->id, id, sizeof(*id) )) return cached_modref;
554 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
555 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
557 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks );
558 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
560 if (!memcmp( &wm->id, id, sizeof(*id) ))
562 cached_modref = wm;
563 return wm;
566 return NULL;
570 /*************************************************************************
571 * grow_module_deps
573 static WINE_MODREF **grow_module_deps( WINE_MODREF *wm, int count )
575 WINE_MODREF **deps;
577 if (wm->alloc_deps)
578 deps = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, wm->deps,
579 (wm->alloc_deps + count) * sizeof(*deps) );
580 else
581 deps = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, count * sizeof(*deps) );
583 if (deps)
585 wm->deps = deps;
586 wm->alloc_deps += count;
588 return deps;
591 /*************************************************************************
592 * find_forwarded_export
594 * Find the final function pointer for a forwarded function.
595 * The loader_section must be locked while calling this function.
597 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
599 const IMAGE_EXPORT_DIRECTORY *exports;
600 DWORD exp_size;
601 WINE_MODREF *wm;
602 WCHAR buffer[32], *mod_name = buffer;
603 const char *end = strrchr(forward, '.');
604 FARPROC proc = NULL;
606 if (!end) return NULL;
607 if ((end - forward) * sizeof(WCHAR) > sizeof(buffer) - sizeof(L".dll"))
609 if (!(mod_name = RtlAllocateHeap( GetProcessHeap(), 0,
610 (end - forward + sizeof(L".dll")) * sizeof(WCHAR) )))
611 return NULL;
613 ascii_to_unicode( mod_name, forward, end - forward );
614 mod_name[end - forward] = 0;
615 if (!wcschr( mod_name, '.' ))
616 memcpy( mod_name + (end - forward), L".dll", sizeof(L".dll") );
618 if (!(wm = find_basename_module( mod_name )))
620 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
621 if (load_dll( load_path, mod_name, L".dll", 0, &wm ) == STATUS_SUCCESS &&
622 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
624 if (!imports_fixup_done && current_modref)
626 WINE_MODREF **deps = grow_module_deps( current_modref, 1 );
627 if (deps) deps[current_modref->nDeps++] = wm;
629 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
631 LdrUnloadDll( wm->ldr.DllBase );
632 wm = NULL;
636 if (!wm)
638 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
639 ERR( "module not found for forward '%s' used by %s\n",
640 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
641 return NULL;
644 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
645 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
647 const char *name = end + 1;
648 if (*name == '#') /* ordinal */
649 proc = find_ordinal_export( wm->ldr.DllBase, exports, exp_size, atoi(name+1), load_path );
650 else
651 proc = find_named_export( wm->ldr.DllBase, exports, exp_size, name, -1, load_path );
654 if (!proc)
656 ERR("function not found for forward '%s' used by %s."
657 " If you are using builtin %s, try using the native one instead.\n",
658 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
659 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
661 if (mod_name != buffer) RtlFreeHeap( GetProcessHeap(), 0, mod_name );
662 return proc;
666 /*************************************************************************
667 * find_ordinal_export
669 * Find an exported function by ordinal.
670 * The exports base must have been subtracted from the ordinal already.
671 * The loader_section must be locked while calling this function.
673 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
674 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
676 FARPROC proc;
677 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
679 if (ordinal >= exports->NumberOfFunctions)
681 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
682 return NULL;
684 if (!functions[ordinal]) return NULL;
686 proc = get_rva( module, functions[ordinal] );
688 /* if the address falls into the export dir, it's a forward */
689 if (((const char *)proc >= (const char *)exports) &&
690 ((const char *)proc < (const char *)exports + exp_size))
691 return find_forwarded_export( module, (const char *)proc, load_path );
693 if (TRACE_ON(snoop))
695 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
696 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
698 if (TRACE_ON(relay))
700 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
701 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
703 return proc;
707 /*************************************************************************
708 * find_named_export
710 * Find an exported function by name.
711 * The loader_section must be locked while calling this function.
713 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
714 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
716 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
717 const DWORD *names = get_rva( module, exports->AddressOfNames );
718 int min = 0, max = exports->NumberOfNames - 1;
720 /* first check the hint */
721 if (hint >= 0 && hint <= max)
723 char *ename = get_rva( module, names[hint] );
724 if (!strcmp( ename, name ))
725 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
728 /* then do a binary search */
729 while (min <= max)
731 int res, pos = (min + max) / 2;
732 char *ename = get_rva( module, names[pos] );
733 if (!(res = strcmp( ename, name )))
734 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
735 if (res > 0) max = pos - 1;
736 else min = pos + 1;
738 return NULL;
743 /*************************************************************************
744 * import_dll
746 * Import the dll specified by the given import descriptor.
747 * The loader_section must be locked while calling this function.
749 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
751 NTSTATUS status;
752 WINE_MODREF *wmImp;
753 HMODULE imp_mod;
754 const IMAGE_EXPORT_DIRECTORY *exports;
755 DWORD exp_size;
756 const IMAGE_THUNK_DATA *import_list;
757 IMAGE_THUNK_DATA *thunk_list;
758 WCHAR buffer[32];
759 const char *name = get_rva( module, descr->Name );
760 DWORD len = strlen(name);
761 PVOID protect_base;
762 SIZE_T protect_size = 0;
763 DWORD protect_old;
765 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
766 if (descr->u.OriginalFirstThunk)
767 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
768 else
769 import_list = thunk_list;
771 if (!import_list->u1.Ordinal)
773 WARN( "Skipping unused import %s\n", name );
774 *pwm = NULL;
775 return TRUE;
778 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
780 if (len * sizeof(WCHAR) < sizeof(buffer))
782 ascii_to_unicode( buffer, name, len );
783 buffer[len] = 0;
784 status = load_dll( load_path, buffer, L".dll", 0, &wmImp );
786 else /* need to allocate a larger buffer */
788 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
789 if (!ptr) return FALSE;
790 ascii_to_unicode( ptr, name, len );
791 ptr[len] = 0;
792 status = load_dll( load_path, ptr, L".dll", 0, &wmImp );
793 RtlFreeHeap( GetProcessHeap(), 0, ptr );
796 if (status)
798 if (status == STATUS_DLL_NOT_FOUND)
799 ERR("Library %s (which is needed by %s) not found\n",
800 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
801 else
802 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
803 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
804 return FALSE;
807 /* unprotect the import address table since it can be located in
808 * readonly section */
809 while (import_list[protect_size].u1.Ordinal) protect_size++;
810 protect_base = thunk_list;
811 protect_size *= sizeof(*thunk_list);
812 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
813 &protect_size, PAGE_READWRITE, &protect_old );
815 imp_mod = wmImp->ldr.DllBase;
816 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
818 if (!exports)
820 /* set all imported function to deadbeef */
821 while (import_list->u1.Ordinal)
823 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
825 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
826 WARN("No implementation for %s.%d", name, ordinal );
827 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
829 else
831 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
832 WARN("No implementation for %s.%s", name, pe_name->Name );
833 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
835 WARN(" imported from %s, allocating stub %p\n",
836 debugstr_w(current_modref->ldr.FullDllName.Buffer),
837 (void *)thunk_list->u1.Function );
838 import_list++;
839 thunk_list++;
841 goto done;
844 while (import_list->u1.Ordinal)
846 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
848 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
850 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
851 ordinal - exports->Base, load_path );
852 if (!thunk_list->u1.Function)
854 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
855 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
856 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
857 (void *)thunk_list->u1.Function );
859 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
861 else /* import by name */
863 IMAGE_IMPORT_BY_NAME *pe_name;
864 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
865 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
866 (const char*)pe_name->Name,
867 pe_name->Hint, load_path );
868 if (!thunk_list->u1.Function)
870 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
871 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
872 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
873 (void *)thunk_list->u1.Function );
875 TRACE_(imports)("--- %s %s.%d = %p\n",
876 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
878 import_list++;
879 thunk_list++;
882 done:
883 /* restore old protection of the import address table */
884 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
885 *pwm = wmImp;
886 return TRUE;
890 /***********************************************************************
891 * create_module_activation_context
893 static NTSTATUS create_module_activation_context( LDR_DATA_TABLE_ENTRY *module )
895 NTSTATUS status;
896 LDR_RESOURCE_INFO info;
897 const IMAGE_RESOURCE_DATA_ENTRY *entry;
899 info.Type = RT_MANIFEST;
900 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
901 info.Language = 0;
902 if (!(status = LdrFindResource_U( module->DllBase, &info, 3, &entry )))
904 ACTCTXW ctx;
905 ctx.cbSize = sizeof(ctx);
906 ctx.lpSource = NULL;
907 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
908 ctx.hModule = module->DllBase;
909 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
910 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
912 return status;
916 /*************************************************************************
917 * is_dll_native_subsystem
919 * Check if dll is a proper native driver.
920 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
921 * while being perfectly normal DLLs. This heuristic should catch such breakages.
923 static BOOL is_dll_native_subsystem( LDR_DATA_TABLE_ENTRY *mod, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
925 const IMAGE_IMPORT_DESCRIPTOR *imports;
926 DWORD i, size;
927 WCHAR buffer[16];
929 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
930 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
931 if (mod->Flags & LDR_WINE_INTERNAL) return TRUE;
933 if ((imports = RtlImageDirectoryEntryToData( mod->DllBase, TRUE,
934 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
936 for (i = 0; imports[i].Name; i++)
938 const char *name = get_rva( mod->DllBase, imports[i].Name );
939 DWORD len = strlen(name);
940 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
941 ascii_to_unicode( buffer, name, len + 1 );
942 if (!wcsicmp( buffer, L"ntdll.dll" ) || !wcsicmp( buffer, L"kernel32.dll" ))
944 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
945 return FALSE;
949 return TRUE;
952 /*************************************************************************
953 * alloc_tls_slot
955 * Allocate a TLS slot for a newly-loaded module.
956 * The loader_section must be locked while calling this function.
958 static SHORT alloc_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
960 const IMAGE_TLS_DIRECTORY *dir;
961 ULONG i, size;
962 void *new_ptr;
963 LIST_ENTRY *entry;
965 if (!(dir = RtlImageDirectoryEntryToData( mod->DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
966 return -1;
968 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
969 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
971 for (i = 0; i < tls_module_count; i++)
973 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
974 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
975 break;
978 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->DllBase,
979 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
980 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
982 if (i == tls_module_count)
984 UINT new_count = max( 32, tls_module_count * 2 );
986 if (!tls_dirs)
987 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
988 else
989 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
990 new_count * sizeof(*tls_dirs) );
991 if (!new_ptr) return -1;
993 /* resize the pointer block in all running threads */
994 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
996 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
997 void **old = teb->ThreadLocalStoragePointer;
998 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
1000 if (!new) return -1;
1001 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
1002 teb->ThreadLocalStoragePointer = new;
1003 #ifdef __x86_64__ /* macOS-specific hack */
1004 if (teb->Reserved5[0]) ((TEB *)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
1005 #endif
1006 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
1007 /* FIXME: can't free old block here, should be freed at thread exit */
1010 tls_dirs = new_ptr;
1011 tls_module_count = new_count;
1014 /* allocate the data block in all running threads */
1015 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1017 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
1019 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
1020 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
1021 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
1023 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
1024 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
1026 RtlFreeHeap( GetProcessHeap(), 0,
1027 InterlockedExchangePointer( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
1030 *(DWORD *)dir->AddressOfIndex = i;
1031 tls_dirs[i] = *dir;
1032 return i;
1036 /*************************************************************************
1037 * free_tls_slot
1039 * Free the module TLS slot on unload.
1040 * The loader_section must be locked while calling this function.
1042 static void free_tls_slot( LDR_DATA_TABLE_ENTRY *mod )
1044 ULONG i = (USHORT)mod->TlsIndex;
1046 if (mod->TlsIndex == -1) return;
1047 assert( i < tls_module_count );
1048 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
1052 /****************************************************************
1053 * fixup_imports_ilonly
1055 * Fixup imports for an IL-only module. All we do is import mscoree.
1056 * The loader_section must be locked while calling this function.
1058 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
1060 IMAGE_EXPORT_DIRECTORY *exports;
1061 DWORD exp_size;
1062 NTSTATUS status;
1063 void *proc = NULL;
1064 WINE_MODREF *prev, *imp;
1066 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1067 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1069 if (!grow_module_deps( wm, 1 )) return STATUS_NO_MEMORY;
1070 wm->nDeps = 1;
1072 prev = current_modref;
1073 current_modref = wm;
1074 if (!(status = load_dll( load_path, L"mscoree.dll", NULL, 0, &imp ))) wm->deps[0] = imp;
1075 current_modref = prev;
1076 if (status)
1078 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1079 debugstr_w(wm->ldr.BaseDllName.Buffer) );
1080 return status;
1083 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1085 if ((exports = RtlImageDirectoryEntryToData( imp->ldr.DllBase, TRUE,
1086 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1088 const char *name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
1089 proc = find_named_export( imp->ldr.DllBase, exports, exp_size, name, -1, load_path );
1091 if (!proc) return STATUS_PROCEDURE_NOT_FOUND;
1092 *entry = proc;
1093 return STATUS_SUCCESS;
1097 /****************************************************************
1098 * fixup_imports
1100 * Fixup all imports of a given module.
1101 * The loader_section must be locked while calling this function.
1103 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1105 int i, dep, nb_imports;
1106 const IMAGE_IMPORT_DESCRIPTOR *imports;
1107 WINE_MODREF *prev, *imp;
1108 DWORD size;
1109 NTSTATUS status;
1110 ULONG_PTR cookie;
1112 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1113 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1115 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
1117 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.DllBase, TRUE,
1118 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1119 return STATUS_SUCCESS;
1121 nb_imports = 0;
1122 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1124 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1125 if (!grow_module_deps( wm, nb_imports )) return STATUS_NO_MEMORY;
1127 if (!create_module_activation_context( &wm->ldr ))
1128 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1130 /* load the imported modules. They are automatically
1131 * added to the modref list of the process.
1133 prev = current_modref;
1134 current_modref = wm;
1135 status = STATUS_SUCCESS;
1136 for (i = 0; i < nb_imports; i++)
1138 dep = wm->nDeps++;
1140 if (!import_dll( wm->ldr.DllBase, &imports[i], load_path, &imp ))
1142 imp = NULL;
1143 status = STATUS_DLL_NOT_FOUND;
1145 wm->deps[dep] = imp;
1147 current_modref = prev;
1148 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1149 return status;
1153 /*************************************************************************
1154 * alloc_module
1156 * Allocate a WINE_MODREF structure and add it to the process list
1157 * The loader_section must be locked while calling this function.
1159 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name, BOOL builtin )
1161 WCHAR *buffer;
1162 WINE_MODREF *wm;
1163 const WCHAR *p;
1164 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1166 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1168 wm->ldr.DllBase = hModule;
1169 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1170 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS | (builtin ? LDR_WINE_INTERNAL : 0);
1171 wm->ldr.TlsIndex = -1;
1172 wm->ldr.LoadCount = 1;
1174 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, nt_name->Length - 3 * sizeof(WCHAR) )))
1176 RtlFreeHeap( GetProcessHeap(), 0, wm );
1177 return NULL;
1179 memcpy( buffer, nt_name->Buffer + 4 /* \??\ prefix */, nt_name->Length - 4 * sizeof(WCHAR) );
1180 buffer[nt_name->Length/sizeof(WCHAR) - 4] = 0;
1181 if ((p = wcsrchr( buffer, '\\' ))) p++;
1182 else p = buffer;
1183 RtlInitUnicodeString( &wm->ldr.FullDllName, buffer );
1184 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1186 if (!is_dll_native_subsystem( &wm->ldr, nt, p ))
1188 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1189 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1190 if (nt->OptionalHeader.AddressOfEntryPoint)
1191 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1194 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1195 &wm->ldr.InLoadOrderLinks);
1196 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1197 &wm->ldr.InMemoryOrderLinks);
1198 /* wait until init is called for inserting into InInitializationOrderModuleList */
1200 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1202 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1203 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1204 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1206 return wm;
1210 /*************************************************************************
1211 * alloc_thread_tls
1213 * Allocate the per-thread structure for module TLS storage.
1215 static NTSTATUS alloc_thread_tls(void)
1217 void **pointers;
1218 UINT i, size;
1220 if (!tls_module_count) return STATUS_SUCCESS;
1222 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1223 tls_module_count * sizeof(*pointers) )))
1224 return STATUS_NO_MEMORY;
1226 for (i = 0; i < tls_module_count; i++)
1228 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1230 if (!dir) continue;
1231 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1232 if (!size && !dir->SizeOfZeroFill) continue;
1234 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1236 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1237 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1238 return STATUS_NO_MEMORY;
1240 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1241 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1243 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1244 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1246 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1247 #ifdef __x86_64__ /* macOS-specific hack */
1248 if (NtCurrentTeb()->Reserved5[0])
1249 ((TEB *)NtCurrentTeb()->Reserved5[0])->ThreadLocalStoragePointer = pointers;
1250 #endif
1251 return STATUS_SUCCESS;
1255 /*************************************************************************
1256 * call_tls_callbacks
1258 static void call_tls_callbacks( HMODULE module, UINT reason )
1260 const IMAGE_TLS_DIRECTORY *dir;
1261 const PIMAGE_TLS_CALLBACK *callback;
1262 ULONG dirsize;
1264 if (reason == DLL_WINE_PREATTACH) return;
1266 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1267 if (!dir || !dir->AddressOfCallBacks) return;
1269 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1271 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1272 *callback, module, reason_names[reason] );
1273 __TRY
1275 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1277 __EXCEPT_ALL
1279 TRACE_(relay)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1280 GetExceptionCode(), callback, module, reason_names[reason] );
1281 return;
1283 __ENDTRY
1284 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1285 *callback, module, reason_names[reason] );
1289 /*************************************************************************
1290 * MODULE_InitDLL
1292 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1294 WCHAR mod_name[32];
1295 NTSTATUS status = STATUS_SUCCESS;
1296 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1297 void *module = wm->ldr.DllBase;
1298 BOOL retv = FALSE;
1300 /* Skip calls for modules loaded with special load flags */
1302 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1303 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, reason );
1304 if (wm->ldr.Flags & LDR_WINE_INTERNAL && reason == DLL_PROCESS_ATTACH)
1305 unix_funcs->init_builtin_dll( wm->ldr.DllBase );
1306 if (!entry) return STATUS_SUCCESS;
1308 if (TRACE_ON(relay))
1310 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1311 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1312 mod_name[len / sizeof(WCHAR)] = 0;
1313 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1314 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1316 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1317 reason_names[reason], lpReserved );
1319 __TRY
1321 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1322 if (!retv)
1323 status = STATUS_DLL_INIT_FAILED;
1325 __EXCEPT_ALL
1327 status = GetExceptionCode();
1328 TRACE_(relay)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1329 status, entry, module, reason_names[reason], lpReserved );
1331 __ENDTRY
1333 /* The state of the module list may have changed due to the call
1334 to the dll. We cannot assume that this module has not been
1335 deleted. */
1336 if (TRACE_ON(relay))
1337 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1338 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1339 else
1340 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1342 return status;
1346 /*************************************************************************
1347 * process_attach
1349 * Send the process attach notification to all DLLs the given module
1350 * depends on (recursively). This is somewhat complicated due to the fact that
1352 * - we have to respect the module dependencies, i.e. modules implicitly
1353 * referenced by another module have to be initialized before the module
1354 * itself can be initialized
1356 * - the initialization routine of a DLL can itself call LoadLibrary,
1357 * thereby introducing a whole new set of dependencies (even involving
1358 * the 'old' modules) at any time during the whole process
1360 * (Note that this routine can be recursively entered not only directly
1361 * from itself, but also via LoadLibrary from one of the called initialization
1362 * routines.)
1364 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1365 * the process *detach* notifications to be sent in the correct order.
1366 * This must not only take into account module dependencies, but also
1367 * 'hidden' dependencies created by modules calling LoadLibrary in their
1368 * attach notification routine.
1370 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1371 * list after the attach notification has returned. This implies that the
1372 * detach notifications are called in the reverse of the sequence the attach
1373 * notifications *returned*.
1375 * The loader_section must be locked while calling this function.
1377 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1379 NTSTATUS status = STATUS_SUCCESS;
1380 ULONG_PTR cookie;
1381 int i;
1383 if (process_detaching) return status;
1385 /* prevent infinite recursion in case of cyclical dependencies */
1386 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1387 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1388 return status;
1390 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1392 /* Tag current MODREF to prevent recursive loop */
1393 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1394 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1395 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1397 /* Recursively attach all DLLs this one depends on */
1398 for ( i = 0; i < wm->nDeps; i++ )
1400 if (!wm->deps[i]) continue;
1401 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1404 if (!wm->ldr.InInitializationOrderLinks.Flink)
1405 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1406 &wm->ldr.InInitializationOrderLinks);
1408 /* Call DLL entry point */
1409 if (status == STATUS_SUCCESS)
1411 WINE_MODREF *prev = current_modref;
1412 current_modref = wm;
1414 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1415 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1416 if (status == STATUS_SUCCESS)
1418 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1420 else
1422 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1423 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1425 /* point to the name so LdrInitializeThunk can print it */
1426 last_failed_modref = wm;
1427 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1429 current_modref = prev;
1432 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1433 /* Remove recursion flag */
1434 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1436 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1437 return status;
1441 /**********************************************************************
1442 * attach_implicitly_loaded_dlls
1444 * Attach to the (builtin) dlls that have been implicitly loaded because
1445 * of a dependency at the Unix level, but not imported at the Win32 level.
1447 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1449 for (;;)
1451 PLIST_ENTRY mark, entry;
1453 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1454 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1456 LDR_DATA_TABLE_ENTRY *mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
1458 if (!(mod->Flags & LDR_IMAGE_IS_DLL)) continue;
1459 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1460 TRACE( "found implicitly loaded %s, attaching to it\n",
1461 debugstr_w(mod->BaseDllName.Buffer));
1462 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1463 break; /* restart the search from the start */
1465 if (entry == mark) break; /* nothing found */
1470 /*************************************************************************
1471 * process_detach
1473 * Send DLL process detach notifications. See the comment about calling
1474 * sequence at process_attach.
1476 static void process_detach(void)
1478 PLIST_ENTRY mark, entry;
1479 PLDR_DATA_TABLE_ENTRY mod;
1481 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1484 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1486 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1487 InInitializationOrderLinks);
1488 /* Check whether to detach this DLL */
1489 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1490 continue;
1491 if ( mod->LoadCount && !process_detaching )
1492 continue;
1494 /* Call detach notification */
1495 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1496 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1497 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1498 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1500 /* Restart at head of WINE_MODREF list, as entries might have
1501 been added and/or removed while performing the call ... */
1502 break;
1504 } while (entry != mark);
1507 /*************************************************************************
1508 * thread_attach
1510 * Send DLL thread attach notifications. These are sent in the
1511 * reverse sequence of process detach notification.
1512 * The loader_section must be locked while calling this function.
1514 static void thread_attach(void)
1516 PLIST_ENTRY mark, entry;
1517 PLDR_DATA_TABLE_ENTRY mod;
1519 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1520 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1522 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
1523 InInitializationOrderLinks);
1524 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1525 continue;
1526 if ( mod->Flags & LDR_NO_DLL_CALLS )
1527 continue;
1529 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1533 /******************************************************************
1534 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1537 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1539 WINE_MODREF *wm;
1540 NTSTATUS ret = STATUS_SUCCESS;
1542 RtlEnterCriticalSection( &loader_section );
1544 wm = get_modref( hModule );
1545 if (!wm || wm->ldr.TlsIndex != -1)
1546 ret = STATUS_DLL_NOT_FOUND;
1547 else
1548 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1550 RtlLeaveCriticalSection( &loader_section );
1552 return ret;
1555 /******************************************************************
1556 * LdrFindEntryForAddress (NTDLL.@)
1558 * The loader_section must be locked while calling this function
1560 NTSTATUS WINAPI LdrFindEntryForAddress( const void *addr, PLDR_DATA_TABLE_ENTRY *pmod )
1562 PLIST_ENTRY mark, entry;
1563 PLDR_DATA_TABLE_ENTRY mod;
1565 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1566 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1568 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);
1569 if (mod->DllBase <= addr &&
1570 (const char *)addr < (char*)mod->DllBase + mod->SizeOfImage)
1572 *pmod = mod;
1573 return STATUS_SUCCESS;
1576 return STATUS_NO_MORE_ENTRIES;
1579 /******************************************************************
1580 * LdrEnumerateLoadedModules (NTDLL.@)
1582 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1584 LIST_ENTRY *mark, *entry;
1585 LDR_DATA_TABLE_ENTRY *mod;
1586 BOOLEAN stop = FALSE;
1588 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1590 if (unknown || !callback)
1591 return STATUS_INVALID_PARAMETER;
1593 RtlEnterCriticalSection( &loader_section );
1595 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1596 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1598 mod = CONTAINING_RECORD( entry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks );
1599 callback( mod, context, &stop );
1600 if (stop) break;
1603 RtlLeaveCriticalSection( &loader_section );
1604 return STATUS_SUCCESS;
1607 /******************************************************************
1608 * LdrRegisterDllNotification (NTDLL.@)
1610 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1611 void *context, void **cookie)
1613 struct ldr_notification *notify;
1615 TRACE( "(%x, %p, %p, %p)\n", flags, callback, context, cookie );
1617 if (!callback || !cookie)
1618 return STATUS_INVALID_PARAMETER;
1620 if (flags)
1621 FIXME( "ignoring flags %x\n", flags );
1623 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1624 if (!notify) return STATUS_NO_MEMORY;
1625 notify->callback = callback;
1626 notify->context = context;
1628 RtlEnterCriticalSection( &loader_section );
1629 list_add_tail( &ldr_notifications, &notify->entry );
1630 RtlLeaveCriticalSection( &loader_section );
1632 *cookie = notify;
1633 return STATUS_SUCCESS;
1636 /******************************************************************
1637 * LdrUnregisterDllNotification (NTDLL.@)
1639 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1641 struct ldr_notification *notify = cookie;
1643 TRACE( "(%p)\n", cookie );
1645 if (!notify) return STATUS_INVALID_PARAMETER;
1647 RtlEnterCriticalSection( &loader_section );
1648 list_remove( &notify->entry );
1649 RtlLeaveCriticalSection( &loader_section );
1651 RtlFreeHeap( GetProcessHeap(), 0, notify );
1652 return STATUS_SUCCESS;
1655 /******************************************************************
1656 * LdrLockLoaderLock (NTDLL.@)
1658 * Note: some flags are not implemented.
1659 * Flag 0x01 is used to raise exceptions on errors.
1661 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1663 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1665 if (result) *result = 0;
1666 if (magic) *magic = 0;
1667 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1668 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1669 if (!magic) return STATUS_INVALID_PARAMETER_3;
1671 if (flags & 0x2)
1673 if (!RtlTryEnterCriticalSection( &loader_section ))
1675 *result = 2;
1676 return STATUS_SUCCESS;
1678 *result = 1;
1680 else
1682 RtlEnterCriticalSection( &loader_section );
1683 if (result) *result = 1;
1685 *magic = GetCurrentThreadId();
1686 return STATUS_SUCCESS;
1690 /******************************************************************
1691 * LdrUnlockLoaderUnlock (NTDLL.@)
1693 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1695 if (magic)
1697 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1698 RtlLeaveCriticalSection( &loader_section );
1700 return STATUS_SUCCESS;
1704 /******************************************************************
1705 * LdrGetProcedureAddress (NTDLL.@)
1707 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1708 ULONG ord, PVOID *address)
1710 IMAGE_EXPORT_DIRECTORY *exports;
1711 DWORD exp_size;
1712 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1714 RtlEnterCriticalSection( &loader_section );
1716 /* check if the module itself is invalid to return the proper error */
1717 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1718 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1719 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1721 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1722 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1723 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1724 if (proc)
1726 *address = proc;
1727 ret = STATUS_SUCCESS;
1731 RtlLeaveCriticalSection( &loader_section );
1732 return ret;
1736 /***********************************************************************
1737 * set_security_cookie
1739 * Create a random security cookie for buffer overflow protection. Make
1740 * sure it does not accidentally match the default cookie value.
1742 static void set_security_cookie( void *module, SIZE_T len )
1744 static ULONG seed;
1745 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1746 ULONG loadcfg_size;
1747 ULONG_PTR *cookie;
1749 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1750 if (!loadcfg) return;
1751 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1752 if (!loadcfg->SecurityCookie) return;
1753 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1754 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1756 WARN( "security cookie %p outside of image %p-%p\n",
1757 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1758 return;
1761 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1762 TRACE( "initializing security cookie %p\n", cookie );
1764 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1765 for (;;)
1767 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1768 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1769 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1770 *cookie = RtlRandom( &seed );
1771 #ifdef DEFAULT_SECURITY_COOKIE_64
1772 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1774 *cookie = RtlRandom( &seed );
1775 /* fill up, but keep the highest word clear */
1776 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1778 #endif
1779 else
1780 break;
1784 static NTSTATUS perform_relocations( void *module, IMAGE_NT_HEADERS *nt, SIZE_T len )
1786 char *base;
1787 IMAGE_BASE_RELOCATION *rel, *end;
1788 const IMAGE_DATA_DIRECTORY *relocs;
1789 const IMAGE_SECTION_HEADER *sec;
1790 INT_PTR delta;
1791 ULONG protect_old[96], i;
1793 base = (char *)nt->OptionalHeader.ImageBase;
1794 if (module == base) return STATUS_SUCCESS; /* nothing to do */
1796 /* no relocations are performed on non page-aligned binaries */
1797 if (nt->OptionalHeader.SectionAlignment < page_size)
1798 return STATUS_SUCCESS;
1800 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1801 return STATUS_SUCCESS;
1803 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1805 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1807 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1808 base, module );
1809 return STATUS_CONFLICTING_ADDRESSES;
1812 if (!relocs->Size) return STATUS_SUCCESS;
1813 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1815 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
1816 return STATUS_INVALID_IMAGE_FORMAT;
1818 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1819 nt->FileHeader.SizeOfOptionalHeader);
1820 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1822 void *addr = get_rva( module, sec[i].VirtualAddress );
1823 SIZE_T size = sec[i].SizeOfRawData;
1824 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1825 &size, PAGE_READWRITE, &protect_old[i] );
1828 TRACE( "relocating from %p-%p to %p-%p\n",
1829 base, base + len, module, (char *)module + len );
1831 rel = get_rva( module, relocs->VirtualAddress );
1832 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1833 delta = (char *)module - base;
1835 while (rel < end - 1 && rel->SizeOfBlock)
1837 if (rel->VirtualAddress >= len)
1839 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1840 return STATUS_ACCESS_VIOLATION;
1842 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1843 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1844 (USHORT *)(rel + 1), delta );
1845 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1848 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1850 void *addr = get_rva( module, sec[i].VirtualAddress );
1851 SIZE_T size = sec[i].SizeOfRawData;
1852 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1853 &size, protect_old[i], &protect_old[i] );
1856 return STATUS_SUCCESS;
1860 /*************************************************************************
1861 * build_module
1863 * Build the module data for a mapped dll.
1865 static NTSTATUS build_module( LPCWSTR load_path, const UNICODE_STRING *nt_name, void **module,
1866 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
1867 DWORD flags, WINE_MODREF **pwm )
1869 IMAGE_NT_HEADERS *nt;
1870 WINE_MODREF *wm;
1871 NTSTATUS status;
1872 SIZE_T map_size;
1874 if (!(nt = RtlImageNtHeader( *module ))) return STATUS_INVALID_IMAGE_FORMAT;
1876 map_size = (nt->OptionalHeader.SizeOfImage + page_size - 1) & ~(page_size - 1);
1877 if ((status = perform_relocations( *module, nt, map_size ))) return status;
1879 /* create the MODREF */
1881 if (!(wm = alloc_module( *module, nt_name, (image_info->u.ImageFlags & IMAGE_FLAGS_WineBuiltin) )))
1882 return STATUS_NO_MEMORY;
1884 if (id) wm->id = *id;
1885 if (image_info->LoaderFlags) wm->ldr.Flags |= LDR_COR_IMAGE;
1886 if (image_info->u.ImageFlags & IMAGE_FLAGS_ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
1888 set_security_cookie( *module, map_size );
1890 /* fixup imports */
1892 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1893 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1894 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1896 if (wm->ldr.Flags & LDR_COR_ILONLY)
1897 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
1898 else
1899 status = fixup_imports( wm, load_path );
1900 if (status != STATUS_SUCCESS)
1902 /* the module has only be inserted in the load & memory order lists */
1903 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
1904 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
1906 /* FIXME: there are several more dangling references
1907 * left. Including dlls loaded by this dll before the
1908 * failed one. Unrolling is rather difficult with the
1909 * current structure and we can leave them lying
1910 * around with no problems, so we don't care.
1911 * As these might reference our wm, we don't free it.
1913 *module = NULL;
1914 return status;
1918 TRACE( "loaded %s %p %p\n", debugstr_us(nt_name), wm, *module );
1920 /* send DLL load event */
1922 SERVER_START_REQ( load_dll )
1924 req->base = wine_server_client_ptr( *module );
1925 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1926 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1927 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1928 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1929 wine_server_call( req );
1931 SERVER_END_REQ;
1933 if (image_info->u.ImageFlags & IMAGE_FLAGS_WineBuiltin)
1935 if (TRACE_ON(relay)) RELAY_SetupDLL( *module );
1937 else
1939 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( *module );
1942 TRACE_(loaddll)( "Loaded %s at %p: %s\n", debugstr_w(wm->ldr.FullDllName.Buffer), *module,
1943 (image_info->u.ImageFlags & IMAGE_FLAGS_WineBuiltin) ? "builtin" : "native" );
1945 wm->ldr.LoadCount = 1;
1946 *pwm = wm;
1947 *module = NULL;
1948 return STATUS_SUCCESS;
1952 /*************************************************************************
1953 * build_builtin_module
1955 * Build the module for a builtin library.
1957 static NTSTATUS build_builtin_module( const WCHAR *load_path, const UNICODE_STRING *nt_name,
1958 void *module, DWORD flags, WINE_MODREF **pwm )
1960 NTSTATUS status;
1961 SECTION_IMAGE_INFORMATION image_info = { 0 };
1963 image_info.u.ImageFlags = IMAGE_FLAGS_WineBuiltin;
1964 status = build_module( load_path, nt_name, &module, &image_info, NULL, flags, pwm );
1965 if (status && module) unix_funcs->unload_builtin_dll( module );
1966 return status;
1970 #ifdef _WIN64
1971 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1972 static BOOL convert_to_pe64( HMODULE module, const SECTION_IMAGE_INFORMATION *info )
1974 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
1975 IMAGE_DIRECTORY_ENTRY_SECURITY,
1976 IMAGE_DIRECTORY_ENTRY_BASERELOC,
1977 IMAGE_DIRECTORY_ENTRY_DEBUG,
1978 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
1979 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
1980 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
1981 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1982 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
1983 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
1984 SIZE_T size = min( nt->OptionalHeader.SizeOfHeaders, nt->OptionalHeader.SizeOfImage );
1985 void *addr = module;
1986 ULONG i, old_prot;
1988 if (nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return TRUE; /* already 64-bit */
1990 TRACE( "%p\n", module );
1992 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
1993 return FALSE;
1995 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
1997 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1998 return FALSE;
2001 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
2002 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
2003 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
2004 hdr64.AddressOfEntryPoint = 0;
2005 hdr64.ImageBase = hdr32.ImageBase;
2006 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
2007 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
2008 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
2009 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
2010 hdr64.LoaderFlags = hdr32.LoaderFlags;
2011 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
2012 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
2013 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
2015 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
2016 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
2017 nt->OptionalHeader = hdr64;
2018 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2019 return TRUE;
2022 /* check COM header for ILONLY flag, ignoring runtime version */
2023 static BOOL get_cor_header( HANDLE file, const SECTION_IMAGE_INFORMATION *info, IMAGE_COR20_HEADER *cor )
2025 IMAGE_DOS_HEADER mz;
2026 IMAGE_NT_HEADERS32 nt;
2027 IO_STATUS_BLOCK io;
2028 LARGE_INTEGER offset;
2029 IMAGE_SECTION_HEADER sec[96];
2030 unsigned int i, count;
2031 DWORD va, size;
2033 offset.QuadPart = 0;
2034 if (NtReadFile( file, 0, NULL, NULL, &io, &mz, sizeof(mz), &offset, NULL )) return FALSE;
2035 if (io.Information != sizeof(mz)) return FALSE;
2036 if (mz.e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
2037 offset.QuadPart = mz.e_lfanew;
2038 if (NtReadFile( file, 0, NULL, NULL, &io, &nt, sizeof(nt), &offset, NULL )) return FALSE;
2039 if (io.Information != sizeof(nt)) return FALSE;
2040 if (nt.Signature != IMAGE_NT_SIGNATURE) return FALSE;
2041 if (nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC) return FALSE;
2042 va = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].VirtualAddress;
2043 size = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR].Size;
2044 if (!va || size < sizeof(*cor)) return FALSE;
2045 offset.QuadPart = offsetof( IMAGE_NT_HEADERS32, OptionalHeader ) + nt.FileHeader.SizeOfOptionalHeader;
2046 count = min( 96, nt.FileHeader.NumberOfSections );
2047 if (NtReadFile( file, 0, NULL, NULL, &io, &sec, count * sizeof(*sec), &offset, NULL )) return FALSE;
2048 if (io.Information != count * sizeof(*sec)) return FALSE;
2049 for (i = 0; i < count; i++)
2051 if (va < sec[i].VirtualAddress) continue;
2052 if (sec[i].Misc.VirtualSize && va - sec[i].VirtualAddress >= sec[i].Misc.VirtualSize) continue;
2053 offset.QuadPart = sec->PointerToRawData + va - sec[i].VirtualAddress;
2054 if (NtReadFile( file, 0, NULL, NULL, &io, cor, sizeof(*cor), &offset, NULL )) return FALSE;
2055 return (io.Information == sizeof(*cor));
2057 return FALSE;
2059 #endif
2061 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2062 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2063 static BOOL is_valid_binary( HANDLE file, const SECTION_IMAGE_INFORMATION *info )
2065 #ifdef __i386__
2066 return info->Machine == IMAGE_FILE_MACHINE_I386;
2067 #elif defined(__arm__)
2068 return info->Machine == IMAGE_FILE_MACHINE_ARM ||
2069 info->Machine == IMAGE_FILE_MACHINE_THUMB ||
2070 info->Machine == IMAGE_FILE_MACHINE_ARMNT;
2071 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2072 #ifdef __x86_64__
2073 if (info->Machine == IMAGE_FILE_MACHINE_AMD64) return TRUE;
2074 #else
2075 if (info->Machine == IMAGE_FILE_MACHINE_ARM64) return TRUE;
2076 #endif
2077 if (!info->ImageContainsCode) return TRUE;
2078 if (!(info->u.ImageFlags & IMAGE_FLAGS_ComPlusNativeReady))
2080 IMAGE_COR20_HEADER cor_header;
2081 if (!get_cor_header( file, info, &cor_header )) return FALSE;
2082 if (!(cor_header.Flags & COMIMAGE_FLAGS_ILONLY)) return FALSE;
2084 return TRUE;
2085 #else
2086 return FALSE; /* no wow64 support on other platforms */
2087 #endif
2091 /******************************************************************
2092 * get_module_path_end
2094 * Returns the end of the directory component of the module path.
2096 static inline const WCHAR *get_module_path_end( const WCHAR *module )
2098 const WCHAR *p;
2099 const WCHAR *mod_end = module;
2101 if ((p = wcsrchr( mod_end, '\\' ))) mod_end = p;
2102 if ((p = wcsrchr( mod_end, '/' ))) mod_end = p;
2103 if (mod_end == module + 2 && module[1] == ':') mod_end++;
2104 if (mod_end == module && module[0] && module[1] == ':') mod_end += 2;
2105 return mod_end;
2109 /******************************************************************
2110 * append_path
2112 * Append a counted string to the load path. Helper for get_dll_load_path.
2114 static inline WCHAR *append_path( WCHAR *p, const WCHAR *str, int len )
2116 if (len == -1) len = wcslen(str);
2117 if (!len) return p;
2118 memcpy( p, str, len * sizeof(WCHAR) );
2119 p[len] = ';';
2120 return p + len + 1;
2124 /******************************************************************
2125 * get_dll_load_path
2127 static NTSTATUS get_dll_load_path( LPCWSTR module, LPCWSTR dll_dir, ULONG safe_mode, WCHAR **path )
2129 const WCHAR *mod_end = module;
2130 UNICODE_STRING name, value;
2131 WCHAR *p, *ret;
2132 int len = ARRAY_SIZE(system_path) + 1, path_len = 0;
2134 if (module)
2136 mod_end = get_module_path_end( module );
2137 len += (mod_end - module) + 1;
2140 RtlInitUnicodeString( &name, L"PATH" );
2141 value.Length = 0;
2142 value.MaximumLength = 0;
2143 value.Buffer = NULL;
2144 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2145 path_len = value.Length;
2147 if (dll_dir) len += wcslen( dll_dir ) + 1;
2148 else len += 2; /* current directory */
2149 if (!(p = ret = RtlAllocateHeap( GetProcessHeap(), 0, path_len + len * sizeof(WCHAR) )))
2150 return STATUS_NO_MEMORY;
2152 p = append_path( p, module, mod_end - module );
2153 if (dll_dir) p = append_path( p, dll_dir, -1 );
2154 else if (!safe_mode) p = append_path( p, L".", -1 );
2155 p = append_path( p, system_path, -1 );
2156 if (!dll_dir && safe_mode) p = append_path( p, L".", -1 );
2158 value.Buffer = p;
2159 value.MaximumLength = path_len;
2161 while (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) == STATUS_BUFFER_TOO_SMALL)
2163 WCHAR *new_ptr;
2165 /* grow the buffer and retry */
2166 path_len = value.Length;
2167 if (!(new_ptr = RtlReAllocateHeap( GetProcessHeap(), 0, ret, path_len + len * sizeof(WCHAR) )))
2169 RtlFreeHeap( GetProcessHeap(), 0, ret );
2170 return STATUS_NO_MEMORY;
2172 value.Buffer = new_ptr + (value.Buffer - ret);
2173 value.MaximumLength = path_len;
2174 ret = new_ptr;
2176 value.Buffer[value.Length / sizeof(WCHAR)] = 0;
2177 *path = ret;
2178 return STATUS_SUCCESS;
2182 /******************************************************************
2183 * get_dll_load_path_search_flags
2185 static NTSTATUS get_dll_load_path_search_flags( LPCWSTR module, DWORD flags, WCHAR **path )
2187 const WCHAR *image = NULL, *mod_end, *image_end;
2188 struct dll_dir_entry *dir;
2189 WCHAR *p, *ret;
2190 int len = 1;
2192 if (flags & LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
2193 flags |= (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
2194 LOAD_LIBRARY_SEARCH_USER_DIRS |
2195 LOAD_LIBRARY_SEARCH_SYSTEM32);
2197 if (flags & LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)
2199 DWORD type = RtlDetermineDosPathNameType_U( module );
2200 if (type != ABSOLUTE_DRIVE_PATH && type != ABSOLUTE_PATH && type != DEVICE_PATH)
2201 return STATUS_INVALID_PARAMETER;
2202 mod_end = get_module_path_end( module );
2203 len += (mod_end - module) + 1;
2205 else module = NULL;
2207 if (flags & LOAD_LIBRARY_SEARCH_APPLICATION_DIR)
2209 image = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
2210 image_end = get_module_path_end( image );
2211 len += (image_end - image) + 1;
2214 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2216 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2217 len += wcslen( dir->dir + 4 /* \??\ */ ) + 1;
2218 if (dll_directory.Length) len += dll_directory.Length / sizeof(WCHAR) + 1;
2221 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) len += wcslen( system_dir );
2223 if ((p = ret = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2225 if (module) p = append_path( p, module, mod_end - module );
2226 if (image) p = append_path( p, image, image_end - image );
2227 if (flags & LOAD_LIBRARY_SEARCH_USER_DIRS)
2229 LIST_FOR_EACH_ENTRY( dir, &dll_dir_list, struct dll_dir_entry, entry )
2230 p = append_path( p, dir->dir + 4 /* \??\ */, -1 );
2231 p = append_path( p, dll_directory.Buffer, dll_directory.Length / sizeof(WCHAR) );
2233 if (flags & LOAD_LIBRARY_SEARCH_SYSTEM32) wcscpy( p, system_dir );
2234 else
2236 if (p > ret) p--;
2237 *p = 0;
2240 *path = ret;
2241 return STATUS_SUCCESS;
2245 /***********************************************************************
2246 * open_dll_file
2248 * Open a file for a new dll. Helper for find_dll_file.
2250 static NTSTATUS open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2251 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2253 FILE_BASIC_INFORMATION info;
2254 OBJECT_ATTRIBUTES attr;
2255 IO_STATUS_BLOCK io;
2256 LARGE_INTEGER size;
2257 FILE_OBJECTID_BUFFER fid;
2258 NTSTATUS status;
2259 HANDLE handle;
2261 if ((*pwm = find_fullname_module( nt_name ))) return STATUS_SUCCESS;
2263 attr.Length = sizeof(attr);
2264 attr.RootDirectory = 0;
2265 attr.Attributes = OBJ_CASE_INSENSITIVE;
2266 attr.ObjectName = nt_name;
2267 attr.SecurityDescriptor = NULL;
2268 attr.SecurityQualityOfService = NULL;
2269 if ((status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2270 FILE_SHARE_READ | FILE_SHARE_DELETE,
2271 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
2273 if (status != STATUS_OBJECT_PATH_NOT_FOUND &&
2274 status != STATUS_OBJECT_NAME_NOT_FOUND &&
2275 !NtQueryAttributesFile( &attr, &info ))
2277 /* if the file exists but failed to open, report the error */
2278 return status;
2280 /* otherwise continue searching */
2281 return STATUS_DLL_NOT_FOUND;
2284 if (!NtFsControlFile( handle, 0, NULL, NULL, &io, FSCTL_GET_OBJECT_ID, NULL, 0, &fid, sizeof(fid) ))
2286 memcpy( id, fid.ObjectId, sizeof(*id) );
2287 if ((*pwm = find_fileid_module( id )))
2289 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2290 (*pwm)->ldr.DllBase, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2291 NtClose( handle );
2292 return STATUS_SUCCESS;
2296 size.QuadPart = 0;
2297 status = NtCreateSection( mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2298 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2299 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, handle );
2300 if (!status)
2302 NtQuerySection( *mapping, SectionImageInformation, image_info, sizeof(*image_info), NULL );
2303 if (!is_valid_binary( handle, image_info ))
2305 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name), image_info->Machine );
2306 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2307 NtClose( *mapping );
2310 NtClose( handle );
2311 return status;
2315 /******************************************************************************
2316 * load_native_dll (internal)
2318 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, HANDLE mapping,
2319 const SECTION_IMAGE_INFORMATION *image_info, const struct file_id *id,
2320 DWORD flags, WINE_MODREF** pwm )
2322 void *module = NULL;
2323 SIZE_T len = 0;
2324 NTSTATUS status = NtMapViewOfSection( mapping, NtCurrentProcess(), &module, 0, 0, NULL, &len,
2325 ViewShare, 0, PAGE_EXECUTE_READ );
2327 if (status == STATUS_IMAGE_NOT_AT_BASE) status = STATUS_SUCCESS;
2328 #ifdef _WIN64
2329 if (!status && !convert_to_pe64( module, image_info )) status = STATUS_INVALID_IMAGE_FORMAT;
2330 #endif
2331 if (!status) status = build_module( load_path, nt_name, &module, image_info, id, flags, pwm );
2332 if (status && module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2333 return status;
2337 /***********************************************************************
2338 * load_so_dll
2340 static NTSTATUS load_so_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name,
2341 DWORD flags, WINE_MODREF **pwm )
2343 void *module;
2344 NTSTATUS status;
2345 WINE_MODREF *wm;
2346 UNICODE_STRING win_name = *nt_name;
2348 TRACE( "trying %s as so lib\n", debugstr_us(&win_name) );
2349 if (unix_funcs->load_so_dll( &win_name, &module ))
2351 WARN( "failed to load .so lib %s\n", debugstr_us(nt_name) );
2352 return STATUS_INVALID_IMAGE_FORMAT;
2355 if ((wm = get_modref( module ))) /* already loaded */
2357 TRACE( "Found %s at %p for builtin %s\n",
2358 debugstr_w(wm->ldr.FullDllName.Buffer), wm->ldr.DllBase, debugstr_us(nt_name) );
2359 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2361 else
2363 if ((status = build_builtin_module( load_path, &win_name, module, flags, &wm ))) return status;
2364 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_us(nt_name), module );
2366 *pwm = wm;
2367 return STATUS_SUCCESS;
2371 /***********************************************************************
2372 * load_builtin_dll
2374 static NTSTATUS load_builtin_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name,
2375 DWORD flags, WINE_MODREF** pwm )
2377 const WCHAR *name, *p;
2378 NTSTATUS status;
2379 void *module, *unix_entry = NULL;
2380 SECTION_IMAGE_INFORMATION image_info;
2382 /* Fix the name in case we have a full path and extension */
2383 name = nt_name->Buffer;
2384 if ((p = wcsrchr( name, '\\' ))) name = p + 1;
2385 if ((p = wcsrchr( name, '/' ))) name = p + 1;
2387 TRACE("Trying built-in %s\n", debugstr_w(name));
2389 status = unix_funcs->load_builtin_dll( name, &module, &unix_entry, &image_info );
2390 if (status) return status;
2392 if ((*pwm = get_modref( module ))) /* already loaded */
2394 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2395 TRACE( "Found %s for %s at %p, count=%d\n",
2396 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(name),
2397 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2398 return STATUS_SUCCESS;
2401 TRACE( "loading %s from %s\n", debugstr_w(name), debugstr_us(nt_name) );
2402 status = build_module( load_path, nt_name, &module, &image_info, NULL, flags, pwm );
2403 if (!status) (*pwm)->unix_entry = unix_entry;
2404 else if (module) unix_funcs->unload_builtin_dll( module );
2405 return status;
2409 /***********************************************************************
2410 * find_actctx_dll
2412 * Find the full path (if any) of the dll from the activation context.
2414 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2416 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2418 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2419 ACTCTX_SECTION_KEYED_DATA data;
2420 UNICODE_STRING nameW;
2421 NTSTATUS status;
2422 SIZE_T needed, size = 1024;
2423 WCHAR *p;
2425 RtlInitUnicodeString( &nameW, libname );
2426 data.cbSize = sizeof(data);
2427 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2428 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2429 &nameW, &data );
2430 if (status != STATUS_SUCCESS) return status;
2432 for (;;)
2434 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2436 status = STATUS_NO_MEMORY;
2437 goto done;
2439 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2440 AssemblyDetailedInformationInActivationContext,
2441 info, size, &needed );
2442 if (status == STATUS_SUCCESS) break;
2443 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2444 RtlFreeHeap( GetProcessHeap(), 0, info );
2445 size = needed;
2446 /* restart with larger buffer */
2449 if (!info->lpAssemblyManifestPath)
2451 status = STATUS_SXS_KEY_NOT_FOUND;
2452 goto done;
2455 if ((p = wcsrchr( info->lpAssemblyManifestPath, '\\' )))
2457 DWORD len, dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2458 p++;
2459 len = wcslen( p );
2460 if (!dirlen || len <= dirlen ||
2461 RtlCompareUnicodeStrings( p, dirlen, info->lpAssemblyDirectoryName, dirlen, TRUE ) ||
2462 wcsicmp( p + dirlen, L".manifest" ))
2464 /* manifest name does not match directory name, so it's not a global
2465 * windows/winsxs manifest; use the manifest directory name instead */
2466 dirlen = p - info->lpAssemblyManifestPath;
2467 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2468 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2470 status = STATUS_NO_MEMORY;
2471 goto done;
2473 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2474 p += dirlen;
2475 wcscpy( p, libname );
2476 goto done;
2480 if (!info->lpAssemblyDirectoryName)
2482 status = STATUS_SXS_KEY_NOT_FOUND;
2483 goto done;
2486 needed = (wcslen(windows_dir) * sizeof(WCHAR) +
2487 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2489 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2491 status = STATUS_NO_MEMORY;
2492 goto done;
2494 wcscpy( p, windows_dir );
2495 p += wcslen(p);
2496 memcpy( p, winsxsW, sizeof(winsxsW) );
2497 p += ARRAY_SIZE( winsxsW );
2498 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2499 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2500 *p++ = '\\';
2501 wcscpy( p, libname );
2502 done:
2503 RtlFreeHeap( GetProcessHeap(), 0, info );
2504 RtlReleaseActivationContext( data.hActCtx );
2505 return status;
2509 /***********************************************************************
2510 * search_dll_file
2512 * Search for dll in the specified paths.
2514 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name,
2515 WINE_MODREF **pwm, HANDLE *mapping, SECTION_IMAGE_INFORMATION *image_info,
2516 struct file_id *id )
2518 WCHAR *name;
2519 BOOL found_image = FALSE;
2520 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2521 ULONG len = wcslen( paths );
2523 if (len < wcslen( system_dir )) len = wcslen( system_dir );
2524 len += wcslen( search ) + 2;
2526 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2527 return STATUS_NO_MEMORY;
2529 while (*paths)
2531 LPCWSTR ptr = paths;
2533 while (*ptr && *ptr != ';') ptr++;
2534 len = ptr - paths;
2535 if (*ptr == ';') ptr++;
2536 memcpy( name, paths, len * sizeof(WCHAR) );
2537 if (len && name[len - 1] != '\\') name[len++] = '\\';
2538 wcscpy( name + len, search );
2540 nt_name->Buffer = NULL;
2541 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( name, nt_name, NULL, NULL ))) goto done;
2543 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
2544 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2545 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2546 RtlFreeUnicodeString( nt_name );
2547 paths = ptr;
2550 if (!found_image)
2552 /* not found, return file in the system dir to be loaded as builtin */
2553 wcscpy( name, system_dir );
2554 wcscat( name, search );
2555 if (!RtlDosPathNameToNtPathName_U( name, nt_name, NULL, NULL )) status = STATUS_NO_MEMORY;
2557 else status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2559 done:
2560 RtlFreeHeap( GetProcessHeap(), 0, name );
2561 return status;
2565 /***********************************************************************
2566 * find_dll_file
2568 * Find the file (or already loaded module) for a given dll name.
2570 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2571 UNICODE_STRING *nt_name, WINE_MODREF **pwm, HANDLE *mapping,
2572 SECTION_IMAGE_INFORMATION *image_info, struct file_id *id )
2574 WCHAR *ext, *dllname;
2575 NTSTATUS status;
2576 ULONG wow64_old_value = 0;
2578 *pwm = NULL;
2579 dllname = NULL;
2581 if (default_ext) /* first append default extension */
2583 if (!(ext = wcsrchr( libname, '.')) || wcschr( ext, '/' ) || wcschr( ext, '\\'))
2585 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2586 (wcslen(libname)+wcslen(default_ext)+1) * sizeof(WCHAR))))
2587 return STATUS_NO_MEMORY;
2588 wcscpy( dllname, libname );
2589 wcscat( dllname, default_ext );
2590 libname = dllname;
2594 /* Win 7/2008R2 and up seem to re-enable WoW64 FS redirection when loading libraries */
2595 if (is_wow64) RtlWow64EnableFsRedirectionEx( 0, &wow64_old_value );
2597 nt_name->Buffer = NULL;
2599 if (!contains_path( libname ))
2601 WCHAR *fullname = NULL;
2603 status = find_actctx_dll( libname, &fullname );
2604 if (status == STATUS_SUCCESS)
2606 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2607 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2608 libname = dllname = fullname;
2610 else
2612 if (status != STATUS_SXS_KEY_NOT_FOUND) goto done;
2613 if ((*pwm = find_basename_module( libname )) != NULL)
2615 status = STATUS_SUCCESS;
2616 goto done;
2621 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2622 status = search_dll_file( load_path, libname, nt_name, pwm, mapping, image_info, id );
2623 else if (!(status = RtlDosPathNameToNtPathName_U_WithStatus( libname, nt_name, NULL, NULL )))
2624 status = open_dll_file( nt_name, pwm, mapping, image_info, id );
2626 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) status = STATUS_INVALID_IMAGE_FORMAT;
2628 done:
2629 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2630 if (wow64_old_value) RtlWow64EnableFsRedirectionEx( 1, &wow64_old_value );
2631 return status;
2635 /***********************************************************************
2636 * load_dll (internal)
2638 * Load a PE style module according to the load order.
2639 * The loader_section must be locked while calling this function.
2641 static NTSTATUS load_dll( const WCHAR *load_path, const WCHAR *libname, const WCHAR *default_ext,
2642 DWORD flags, WINE_MODREF** pwm )
2644 enum loadorder loadorder;
2645 WINE_MODREF *main_exe;
2646 UNICODE_STRING nt_name;
2647 struct file_id id;
2648 HANDLE mapping = 0;
2649 SECTION_IMAGE_INFORMATION image_info;
2650 NTSTATUS nts;
2652 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2654 nts = find_dll_file( load_path, libname, default_ext, &nt_name, pwm, &mapping, &image_info, &id );
2656 if (*pwm) /* found already loaded module */
2658 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2660 TRACE("Found %s for %s at %p, count=%d\n",
2661 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2662 (*pwm)->ldr.DllBase, (*pwm)->ldr.LoadCount);
2663 RtlFreeUnicodeString( &nt_name );
2664 return STATUS_SUCCESS;
2667 if (nts && nts != STATUS_DLL_NOT_FOUND && nts != STATUS_INVALID_IMAGE_NOT_MZ) goto done;
2669 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2670 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, &nt_name );
2672 switch (nts)
2674 case STATUS_INVALID_IMAGE_NOT_MZ: /* not in PE format, maybe it's a .so file */
2675 switch (loadorder)
2677 case LO_NATIVE:
2678 case LO_NATIVE_BUILTIN:
2679 case LO_BUILTIN:
2680 case LO_BUILTIN_NATIVE:
2681 case LO_DEFAULT:
2682 if (!load_so_dll( load_path, &nt_name, flags, pwm )) nts = STATUS_SUCCESS;
2683 break;
2684 default:
2685 nts = STATUS_DLL_NOT_FOUND;
2686 break;
2688 break;
2690 case STATUS_SUCCESS: /* valid PE file */
2691 if (image_info.u.ImageFlags & IMAGE_FLAGS_WineBuiltin)
2693 switch (loadorder)
2695 case LO_NATIVE_BUILTIN:
2696 case LO_BUILTIN:
2697 case LO_BUILTIN_NATIVE:
2698 case LO_DEFAULT:
2699 nts = load_builtin_dll( load_path, &nt_name, flags, pwm );
2700 if (nts == STATUS_DLL_NOT_FOUND)
2701 nts = load_native_dll( load_path, &nt_name, mapping, &image_info, &id, flags, pwm );
2702 break;
2703 default:
2704 nts = STATUS_DLL_NOT_FOUND;
2705 break;
2707 break;
2709 if (!(image_info.u.ImageFlags & IMAGE_FLAGS_WineFakeDll))
2711 switch (loadorder)
2713 case LO_NATIVE:
2714 case LO_NATIVE_BUILTIN:
2715 nts = load_native_dll( load_path, &nt_name, mapping, &image_info, &id, flags, pwm );
2716 break;
2717 case LO_BUILTIN:
2718 nts = load_builtin_dll( load_path, &nt_name, flags, pwm );
2719 break;
2720 case LO_BUILTIN_NATIVE:
2721 case LO_DEFAULT:
2722 nts = load_builtin_dll( load_path, &nt_name, flags, pwm );
2723 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2724 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2726 /* stub-only dll, try native */
2727 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_us(&nt_name) );
2728 LdrUnloadDll( (*pwm)->ldr.DllBase );
2729 nts = STATUS_DLL_NOT_FOUND;
2731 if (nts == STATUS_DLL_NOT_FOUND)
2732 nts = load_native_dll( load_path, &nt_name, mapping, &image_info, &id, flags, pwm );
2733 break;
2734 default:
2735 nts = STATUS_DLL_NOT_FOUND;
2736 break;
2738 break;
2740 TRACE( "%s is a fake Wine dll\n", debugstr_us(&nt_name) );
2741 /* fall through */
2743 case STATUS_DLL_NOT_FOUND: /* no file found, try builtin */
2744 switch (loadorder)
2746 case LO_NATIVE_BUILTIN:
2747 case LO_BUILTIN:
2748 case LO_BUILTIN_NATIVE:
2749 case LO_DEFAULT:
2750 nts = load_builtin_dll( load_path, &nt_name, flags, pwm );
2751 break;
2752 default:
2753 nts = STATUS_DLL_NOT_FOUND;
2754 break;
2756 break;
2759 done:
2760 if (nts == STATUS_SUCCESS)
2761 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name), (*pwm)->ldr.DllBase);
2762 else
2763 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2765 if (mapping) NtClose( mapping );
2766 RtlFreeUnicodeString( &nt_name );
2767 return nts;
2771 /***********************************************************************
2772 * __wine_init_unix_lib
2774 NTSTATUS __cdecl __wine_init_unix_lib( HMODULE module, DWORD reason, const void *ptr_in, void *ptr_out )
2776 WINE_MODREF *wm;
2777 NTSTATUS ret = STATUS_DLL_NOT_FOUND;
2779 RtlEnterCriticalSection( &loader_section );
2781 if ((wm = get_modref( module )))
2783 NTSTATUS (CDECL *init_func)( HMODULE, DWORD, const void *, void * ) = wm->unix_entry;
2784 if (init_func) ret = init_func( module, reason, ptr_in, ptr_out );
2786 else ret = STATUS_INVALID_HANDLE;
2788 RtlLeaveCriticalSection( &loader_section );
2789 return ret;
2793 /******************************************************************
2794 * LdrLoadDll (NTDLL.@)
2796 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2797 const UNICODE_STRING *libname, HMODULE* hModule)
2799 WINE_MODREF *wm;
2800 NTSTATUS nts;
2802 RtlEnterCriticalSection( &loader_section );
2804 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2805 nts = load_dll( path_name, libname->Buffer, L".dll", flags, &wm );
2807 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2809 nts = process_attach( wm, NULL );
2810 if (nts != STATUS_SUCCESS)
2812 LdrUnloadDll(wm->ldr.DllBase);
2813 wm = NULL;
2816 *hModule = (wm) ? wm->ldr.DllBase : NULL;
2818 RtlLeaveCriticalSection( &loader_section );
2819 return nts;
2823 /******************************************************************
2824 * LdrGetDllHandle (NTDLL.@)
2826 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2828 NTSTATUS status;
2829 UNICODE_STRING nt_name;
2830 WINE_MODREF *wm;
2831 HANDLE mapping;
2832 SECTION_IMAGE_INFORMATION image_info;
2833 struct file_id id;
2835 RtlEnterCriticalSection( &loader_section );
2837 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2839 status = find_dll_file( load_path, name->Buffer, L".dll", &nt_name, &wm, &mapping, &image_info, &id );
2841 if (wm) *base = wm->ldr.DllBase;
2842 else
2844 if (status == STATUS_SUCCESS) NtClose( mapping );
2845 status = STATUS_DLL_NOT_FOUND;
2847 RtlFreeUnicodeString( &nt_name );
2849 RtlLeaveCriticalSection( &loader_section );
2850 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2851 return status;
2855 /******************************************************************
2856 * LdrAddRefDll (NTDLL.@)
2858 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2860 NTSTATUS ret = STATUS_SUCCESS;
2861 WINE_MODREF *wm;
2863 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2865 RtlEnterCriticalSection( &loader_section );
2867 if ((wm = get_modref( module )))
2869 if (flags & LDR_ADDREF_DLL_PIN)
2870 wm->ldr.LoadCount = -1;
2871 else
2872 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2873 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2875 else ret = STATUS_INVALID_PARAMETER;
2877 RtlLeaveCriticalSection( &loader_section );
2878 return ret;
2882 /***********************************************************************
2883 * LdrProcessRelocationBlock (NTDLL.@)
2885 * Apply relocations to a given page of a mapped PE image.
2887 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2888 USHORT *relocs, INT_PTR delta )
2890 while (count--)
2892 USHORT offset = *relocs & 0xfff;
2893 int type = *relocs >> 12;
2894 switch(type)
2896 case IMAGE_REL_BASED_ABSOLUTE:
2897 break;
2898 case IMAGE_REL_BASED_HIGH:
2899 *(short *)((char *)page + offset) += HIWORD(delta);
2900 break;
2901 case IMAGE_REL_BASED_LOW:
2902 *(short *)((char *)page + offset) += LOWORD(delta);
2903 break;
2904 case IMAGE_REL_BASED_HIGHLOW:
2905 *(int *)((char *)page + offset) += delta;
2906 break;
2907 #ifdef _WIN64
2908 case IMAGE_REL_BASED_DIR64:
2909 *(INT_PTR *)((char *)page + offset) += delta;
2910 break;
2911 #elif defined(__arm__)
2912 case IMAGE_REL_BASED_THUMB_MOV32:
2914 DWORD inst = *(INT_PTR *)((char *)page + offset);
2915 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2916 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2917 DWORD hi_delta;
2919 if ((inst & 0x8000fbf0) != 0x0000f240)
2920 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2922 imm16 += LOWORD(delta);
2923 hi_delta = HIWORD(delta) + HIWORD(imm16);
2924 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2925 ((imm16 >> 12) & 0x000f) +
2926 ((imm16 << 20) & 0x70000000) +
2927 ((imm16 << 16) & 0xff0000);
2929 if (hi_delta != 0)
2931 inst = *(INT_PTR *)((char *)page + offset + 4);
2932 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2933 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2935 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2936 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2938 imm16 += hi_delta;
2939 if (imm16 > 0xffff)
2940 ERR("resulting immediate value won't fit: %08x\n", imm16);
2941 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2942 ((imm16 >> 1) & 0x0400) +
2943 ((imm16 >> 12) & 0x000f) +
2944 ((imm16 << 20) & 0x70000000) +
2945 ((imm16 << 16) & 0xff0000);
2948 break;
2949 #endif
2950 default:
2951 FIXME("Unknown/unsupported fixup type %x.\n", type);
2952 return NULL;
2954 relocs++;
2956 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2960 /******************************************************************
2961 * LdrQueryProcessModuleInformation
2964 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2965 ULONG buf_size, ULONG* req_size)
2967 SYSTEM_MODULE* sm = &smi->Modules[0];
2968 ULONG size = sizeof(ULONG);
2969 NTSTATUS nts = STATUS_SUCCESS;
2970 ANSI_STRING str;
2971 char* ptr;
2972 PLIST_ENTRY mark, entry;
2973 LDR_DATA_TABLE_ENTRY *mod;
2974 WORD id = 0;
2976 smi->ModulesCount = 0;
2978 RtlEnterCriticalSection( &loader_section );
2979 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2980 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2982 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
2983 size += sizeof(*sm);
2984 if (size <= buf_size)
2986 sm->Section = 0; /* FIXME */
2987 sm->MappedBaseAddress = mod->DllBase;
2988 sm->ImageBaseAddress = mod->DllBase;
2989 sm->ImageSize = mod->SizeOfImage;
2990 sm->Flags = mod->Flags;
2991 sm->LoadOrderIndex = id++;
2992 sm->InitOrderIndex = 0; /* FIXME */
2993 sm->LoadCount = mod->LoadCount;
2994 str.Length = 0;
2995 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2996 str.Buffer = (char*)sm->Name;
2997 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2998 ptr = strrchr(str.Buffer, '\\');
2999 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
3001 smi->ModulesCount++;
3002 sm++;
3004 else nts = STATUS_INFO_LENGTH_MISMATCH;
3006 RtlLeaveCriticalSection( &loader_section );
3008 if (req_size) *req_size = size;
3010 return nts;
3014 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
3016 NTSTATUS status;
3017 UNICODE_STRING str;
3018 ULONG size;
3019 WCHAR buffer[64];
3020 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3022 RtlInitUnicodeString( &str, name );
3024 size = sizeof(buffer) - sizeof(WCHAR);
3025 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
3026 return status;
3028 if (info->Type != REG_DWORD)
3030 buffer[size / sizeof(WCHAR)] = 0;
3031 *value = wcstoul( (WCHAR *)info->Data, 0, 16 );
3033 else memcpy( value, info->Data, sizeof(*value) );
3034 return status;
3037 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
3038 void *data, ULONG in_size, ULONG *out_size )
3040 NTSTATUS status;
3041 UNICODE_STRING str;
3042 ULONG size;
3043 char *buffer;
3044 KEY_VALUE_PARTIAL_INFORMATION *info;
3045 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
3047 RtlInitUnicodeString( &str, name );
3049 size = info_size + in_size;
3050 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
3051 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3052 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
3053 if (!status || status == STATUS_BUFFER_OVERFLOW)
3055 if (out_size) *out_size = info->DataLength;
3056 if (data && !status) memcpy( data, info->Data, info->DataLength );
3058 RtlFreeHeap( GetProcessHeap(), 0, buffer );
3059 return status;
3063 /******************************************************************
3064 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3066 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
3067 void *data, ULONG in_size, ULONG *out_size )
3069 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
3070 'S','o','f','t','w','a','r','e','\\',
3071 'M','i','c','r','o','s','o','f','t','\\',
3072 'W','i','n','d','o','w','s',' ','N','T','\\',
3073 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3074 'I','m','a','g','e',' ','F','i','l','e',' ',
3075 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3076 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
3077 OBJECT_ATTRIBUTES attr;
3078 UNICODE_STRING name_str;
3079 HANDLE hkey;
3080 NTSTATUS status;
3081 ULONG len;
3082 WCHAR *p;
3084 attr.Length = sizeof(attr);
3085 attr.RootDirectory = 0;
3086 attr.ObjectName = &name_str;
3087 attr.Attributes = OBJ_CASE_INSENSITIVE;
3088 attr.SecurityDescriptor = NULL;
3089 attr.SecurityQualityOfService = NULL;
3091 p = key->Buffer + key->Length / sizeof(WCHAR);
3092 while (p > key->Buffer && p[-1] != '\\') p--;
3093 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
3094 name_str.Buffer = path;
3095 name_str.Length = sizeof(optionsW) + len;
3096 name_str.MaximumLength = name_str.Length;
3097 memcpy( path, optionsW, sizeof(optionsW) );
3098 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
3099 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
3101 if (type == REG_DWORD)
3103 if (out_size) *out_size = sizeof(ULONG);
3104 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
3105 else status = STATUS_BUFFER_OVERFLOW;
3107 else status = query_string_option( hkey, value, type, data, in_size, out_size );
3109 NtClose( hkey );
3110 return status;
3114 /******************************************************************
3115 * RtlDllShutdownInProgress (NTDLL.@)
3117 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
3119 return process_detaching;
3122 /****************************************************************************
3123 * LdrResolveDelayLoadedAPI (NTDLL.@)
3125 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
3126 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
3127 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
3128 IMAGE_THUNK_DATA* addr, ULONG flags )
3130 IMAGE_THUNK_DATA *pIAT, *pINT;
3131 DELAYLOAD_INFO delayinfo;
3132 UNICODE_STRING mod;
3133 const CHAR* name;
3134 HMODULE *phmod;
3135 NTSTATUS nts;
3136 FARPROC fp;
3137 DWORD id;
3139 TRACE( "(%p, %p, %p, %p, %p, 0x%08x)\n", base, desc, dllhook, syshook, addr, flags );
3141 phmod = get_rva(base, desc->ModuleHandleRVA);
3142 pIAT = get_rva(base, desc->ImportAddressTableRVA);
3143 pINT = get_rva(base, desc->ImportNameTableRVA);
3144 name = get_rva(base, desc->DllNameRVA);
3145 id = addr - pIAT;
3147 if (!*phmod)
3149 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
3151 nts = STATUS_NO_MEMORY;
3152 goto fail;
3154 nts = LdrLoadDll(NULL, 0, &mod, phmod);
3155 RtlFreeUnicodeString(&mod);
3156 if (nts) goto fail;
3159 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3160 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
3161 else
3163 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3164 ANSI_STRING fnc;
3166 RtlInitAnsiString(&fnc, (char*)iibn->Name);
3167 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
3169 if (!nts)
3171 pIAT[id].u1.Function = (ULONG_PTR)fp;
3172 return fp;
3175 fail:
3176 delayinfo.Size = sizeof(delayinfo);
3177 delayinfo.DelayloadDescriptor = desc;
3178 delayinfo.ThunkAddress = addr;
3179 delayinfo.TargetDllName = name;
3180 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
3181 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
3182 delayinfo.TargetModuleBase = *phmod;
3183 delayinfo.Unused = NULL;
3184 delayinfo.LastError = nts;
3186 if (dllhook)
3187 return dllhook(4, &delayinfo);
3189 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3191 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3192 return syshook(name, (const char *)ord);
3194 else
3196 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3197 return syshook(name, (const char *)iibn->Name);
3201 /******************************************************************
3202 * LdrShutdownProcess (NTDLL.@)
3205 void WINAPI LdrShutdownProcess(void)
3207 BOOL detaching = process_detaching;
3209 TRACE("()\n");
3211 process_detaching = TRUE;
3212 if (!detaching)
3213 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3215 process_detach();
3219 /******************************************************************
3220 * RtlExitUserProcess (NTDLL.@)
3222 void WINAPI RtlExitUserProcess( DWORD status )
3224 RtlEnterCriticalSection( &loader_section );
3225 RtlAcquirePebLock();
3226 NtTerminateProcess( 0, status );
3227 LdrShutdownProcess();
3228 for (;;) NtTerminateProcess( GetCurrentProcess(), status );
3231 /******************************************************************
3232 * LdrShutdownThread (NTDLL.@)
3235 void WINAPI LdrShutdownThread(void)
3237 PLIST_ENTRY mark, entry;
3238 LDR_DATA_TABLE_ENTRY *mod;
3239 WINE_MODREF *wm;
3240 UINT i;
3241 void **pointers;
3243 TRACE("()\n");
3245 /* don't do any detach calls if process is exiting */
3246 if (process_detaching) return;
3248 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 1 );
3250 RtlEnterCriticalSection( &loader_section );
3251 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3253 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3254 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3256 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY,
3257 InInitializationOrderLinks);
3258 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3259 continue;
3260 if ( mod->Flags & LDR_NO_DLL_CALLS )
3261 continue;
3263 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3264 DLL_THREAD_DETACH, NULL );
3267 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_DETACH );
3269 RtlAcquirePebLock();
3270 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3271 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3273 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3274 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3276 RtlProcessFlsData( NtCurrentTeb()->FlsSlots, 2 );
3277 NtCurrentTeb()->FlsSlots = NULL;
3278 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3279 NtCurrentTeb()->TlsExpansionSlots = NULL;
3280 RtlReleasePebLock();
3282 RtlLeaveCriticalSection( &loader_section );
3286 /***********************************************************************
3287 * free_modref
3290 static void free_modref( WINE_MODREF *wm )
3292 RemoveEntryList(&wm->ldr.InLoadOrderLinks);
3293 RemoveEntryList(&wm->ldr.InMemoryOrderLinks);
3294 if (wm->ldr.InInitializationOrderLinks.Flink)
3295 RemoveEntryList(&wm->ldr.InInitializationOrderLinks);
3297 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3298 if (!TRACE_ON(module))
3299 TRACE_(loaddll)("Unloaded module %s : %s\n",
3300 debugstr_w(wm->ldr.FullDllName.Buffer),
3301 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3303 SERVER_START_REQ( unload_dll )
3305 req->base = wine_server_client_ptr( wm->ldr.DllBase );
3306 wine_server_call( req );
3308 SERVER_END_REQ;
3310 free_tls_slot( &wm->ldr );
3311 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3312 unix_funcs->unload_builtin_dll( wm->ldr.DllBase );
3313 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.DllBase );
3314 if (cached_modref == wm) cached_modref = NULL;
3315 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3316 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
3317 RtlFreeHeap( GetProcessHeap(), 0, wm );
3320 /***********************************************************************
3321 * MODULE_FlushModrefs
3323 * Remove all unused modrefs and call the internal unloading routines
3324 * for the library type.
3326 * The loader_section must be locked while calling this function.
3328 static void MODULE_FlushModrefs(void)
3330 PLIST_ENTRY mark, entry, prev;
3331 LDR_DATA_TABLE_ENTRY *mod;
3332 WINE_MODREF*wm;
3334 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3335 for (entry = mark->Blink; entry != mark; entry = prev)
3337 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks);
3338 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3339 prev = entry->Blink;
3340 if (!mod->LoadCount) free_modref( wm );
3343 /* check load order list too for modules that haven't been initialized yet */
3344 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3345 for (entry = mark->Blink; entry != mark; entry = prev)
3347 mod = CONTAINING_RECORD(entry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
3348 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3349 prev = entry->Blink;
3350 if (!mod->LoadCount) free_modref( wm );
3354 /***********************************************************************
3355 * MODULE_DecRefCount
3357 * The loader_section must be locked while calling this function.
3359 static void MODULE_DecRefCount( WINE_MODREF *wm )
3361 int i;
3363 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3364 return;
3366 if ( wm->ldr.LoadCount <= 0 )
3367 return;
3369 --wm->ldr.LoadCount;
3370 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3372 if ( wm->ldr.LoadCount == 0 )
3374 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3376 for ( i = 0; i < wm->nDeps; i++ )
3377 if ( wm->deps[i] )
3378 MODULE_DecRefCount( wm->deps[i] );
3380 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3382 module_push_unload_trace( &wm->ldr );
3386 /******************************************************************
3387 * LdrUnloadDll (NTDLL.@)
3391 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3393 WINE_MODREF *wm;
3394 NTSTATUS retv = STATUS_SUCCESS;
3396 if (process_detaching) return retv;
3398 TRACE("(%p)\n", hModule);
3400 RtlEnterCriticalSection( &loader_section );
3402 free_lib_count++;
3403 if ((wm = get_modref( hModule )) != NULL)
3405 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3407 /* Recursively decrement reference counts */
3408 MODULE_DecRefCount( wm );
3410 /* Call process detach notifications */
3411 if ( free_lib_count <= 1 )
3413 process_detach();
3414 MODULE_FlushModrefs();
3417 TRACE("END\n");
3419 else
3420 retv = STATUS_DLL_NOT_FOUND;
3422 free_lib_count--;
3424 RtlLeaveCriticalSection( &loader_section );
3426 return retv;
3429 /***********************************************************************
3430 * RtlImageNtHeader (NTDLL.@)
3432 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3434 IMAGE_NT_HEADERS *ret;
3436 __TRY
3438 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3440 ret = NULL;
3441 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3443 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3444 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3447 __EXCEPT_PAGE_FAULT
3449 return NULL;
3451 __ENDTRY
3452 return ret;
3455 /***********************************************************************
3456 * process_breakpoint
3458 * Trigger a debug breakpoint if the process is being debugged.
3460 static void process_breakpoint(void)
3462 DWORD_PTR port = 0;
3464 NtQueryInformationProcess( GetCurrentProcess(), ProcessDebugPort, &port, sizeof(port), NULL );
3465 if (!port) return;
3467 __TRY
3469 DbgBreakPoint();
3471 __EXCEPT_ALL
3473 /* do nothing */
3475 __ENDTRY
3479 /******************************************************************
3480 * LdrInitializeThunk (NTDLL.@)
3482 * Attach to all the loaded dlls.
3483 * If this is the first time, perform the full process initialization.
3485 void WINAPI LdrInitializeThunk( CONTEXT *context, ULONG_PTR unknown2, ULONG_PTR unknown3, ULONG_PTR unknown4 )
3487 static int attach_done;
3488 int i;
3489 NTSTATUS status;
3490 ULONG_PTR cookie;
3491 WINE_MODREF *wm;
3492 void **entry;
3493 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3495 #ifdef __i386__
3496 entry = (void **)&context->Eax;
3497 #elif defined(__x86_64__)
3498 entry = (void **)&context->Rcx;
3499 #elif defined(__arm__)
3500 entry = (void **)&context->R0;
3501 #elif defined(__aarch64__)
3502 entry = (void **)&context->u.s.X0;
3503 #endif
3505 if (process_detaching) NtTerminateThread( GetCurrentThread(), 0 );
3507 RtlEnterCriticalSection( &loader_section );
3509 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3510 assert( wm );
3512 if (!imports_fixup_done)
3514 actctx_init();
3515 if (wm->ldr.Flags & LDR_COR_ILONLY)
3516 status = fixup_imports_ilonly( wm, load_path, entry );
3517 else
3518 status = fixup_imports( wm, load_path );
3520 if (status)
3522 ERR( "Importing dlls for %s failed, status %x\n",
3523 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3524 NtTerminateProcess( GetCurrentProcess(), status );
3526 imports_fixup_done = TRUE;
3529 RtlAcquirePebLock();
3530 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3531 RtlReleasePebLock();
3533 NtCurrentTeb()->FlsSlots = fls_alloc_data();
3535 if (!attach_done) /* first time around */
3537 attach_done = 1;
3538 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3540 ERR( "TLS init failed when loading %s, status %x\n",
3541 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3542 NtTerminateProcess( GetCurrentProcess(), status );
3544 wm->ldr.LoadCount = -1;
3545 wm->ldr.Flags |= LDR_PROCESS_ATTACHED; /* don't try to attach again */
3546 if (wm->ldr.ActivationContext)
3547 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
3549 for (i = 0; i < wm->nDeps; i++)
3551 if (!wm->deps[i]) continue;
3552 if ((status = process_attach( wm->deps[i], context )) != STATUS_SUCCESS)
3554 if (last_failed_modref)
3555 ERR( "%s failed to initialize, aborting\n",
3556 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3557 ERR( "Initializing dlls for %s failed, status %x\n",
3558 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3559 NtTerminateProcess( GetCurrentProcess(), status );
3562 attach_implicitly_loaded_dlls( context );
3563 unix_funcs->virtual_release_address_space();
3564 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_PROCESS_ATTACH );
3565 if (wm->ldr.Flags & LDR_WINE_INTERNAL) unix_funcs->init_builtin_dll( wm->ldr.DllBase );
3566 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
3567 process_breakpoint();
3569 else
3571 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3572 NtTerminateThread( GetCurrentThread(), status );
3573 thread_attach();
3574 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.DllBase, DLL_THREAD_ATTACH );
3577 RtlLeaveCriticalSection( &loader_section );
3578 signal_start_thread( context );
3582 /***********************************************************************
3583 * load_global_options
3585 static void load_global_options(void)
3587 OBJECT_ATTRIBUTES attr;
3588 UNICODE_STRING name_str;
3589 HANDLE hkey;
3590 ULONG value;
3592 attr.Length = sizeof(attr);
3593 attr.RootDirectory = 0;
3594 attr.ObjectName = &name_str;
3595 attr.Attributes = OBJ_CASE_INSENSITIVE;
3596 attr.SecurityDescriptor = NULL;
3597 attr.SecurityQualityOfService = NULL;
3598 RtlInitUnicodeString( &name_str, L"Machine\\System\\CurrentControlSet\\Control\\Session Manager" );
3600 if (!NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))
3602 query_dword_option( hkey, L"GlobalFlag", &NtCurrentTeb()->Peb->NtGlobalFlag );
3603 query_dword_option( hkey, L"SafeProcessSearchMode", &path_safe_mode );
3604 query_dword_option( hkey, L"SafeDllSearchMode", &dll_safe_mode );
3606 if (!query_dword_option( hkey, L"CriticalSectionTimeout", &value ))
3607 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3609 if (!query_dword_option( hkey, L"HeapSegmentReserve", &value ))
3610 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3612 if (!query_dword_option( hkey, L"HeapSegmentCommit", &value ))
3613 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3615 if (!query_dword_option( hkey, L"HeapDeCommitTotalFreeThreshold", &value ))
3616 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3618 if (!query_dword_option( hkey, L"HeapDeCommitFreeBlockThreshold", &value ))
3619 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3621 NtClose( hkey );
3623 LdrQueryImageFileExecutionOptions( &NtCurrentTeb()->Peb->ProcessParameters->ImagePathName,
3624 L"GlobalFlag", REG_DWORD, &NtCurrentTeb()->Peb->NtGlobalFlag,
3625 sizeof(DWORD), NULL );
3626 heap_set_debug_flags( GetProcessHeap() );
3630 /***********************************************************************
3631 * RtlImageDirectoryEntryToData (NTDLL.@)
3633 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3635 const IMAGE_NT_HEADERS *nt;
3636 DWORD addr;
3638 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
3639 module = (HMODULE)((ULONG_PTR)module & ~3);
3640 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3641 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3643 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3645 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3646 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3647 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3648 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3650 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3652 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3654 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3655 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3656 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3657 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3659 else return NULL;
3661 /* not mapped as image, need to find the section containing the virtual address */
3662 return RtlImageRvaToVa( nt, module, addr, NULL );
3666 /***********************************************************************
3667 * RtlImageRvaToSection (NTDLL.@)
3669 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3670 HMODULE module, DWORD rva )
3672 int i;
3673 const IMAGE_SECTION_HEADER *sec;
3675 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3676 nt->FileHeader.SizeOfOptionalHeader);
3677 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3679 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3680 return (PIMAGE_SECTION_HEADER)sec;
3682 return NULL;
3686 /***********************************************************************
3687 * RtlImageRvaToVa (NTDLL.@)
3689 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3690 DWORD rva, IMAGE_SECTION_HEADER **section )
3692 IMAGE_SECTION_HEADER *sec;
3694 if (section && *section) /* try this section first */
3696 sec = *section;
3697 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3698 goto found;
3700 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3701 found:
3702 if (section) *section = sec;
3703 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3707 /***********************************************************************
3708 * RtlPcToFileHeader (NTDLL.@)
3710 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3712 LDR_DATA_TABLE_ENTRY *module;
3713 PVOID ret = NULL;
3715 RtlEnterCriticalSection( &loader_section );
3716 if (!LdrFindEntryForAddress( pc, &module )) ret = module->DllBase;
3717 RtlLeaveCriticalSection( &loader_section );
3718 *address = ret;
3719 return ret;
3723 /****************************************************************************
3724 * LdrGetDllDirectory (NTDLL.@)
3726 NTSTATUS WINAPI LdrGetDllDirectory( UNICODE_STRING *dir )
3728 NTSTATUS status = STATUS_SUCCESS;
3730 RtlEnterCriticalSection( &dlldir_section );
3731 dir->Length = dll_directory.Length + sizeof(WCHAR);
3732 if (dir->MaximumLength >= dir->Length) RtlCopyUnicodeString( dir, &dll_directory );
3733 else
3735 status = STATUS_BUFFER_TOO_SMALL;
3736 if (dir->MaximumLength) dir->Buffer[0] = 0;
3738 RtlLeaveCriticalSection( &dlldir_section );
3739 return status;
3743 /****************************************************************************
3744 * LdrSetDllDirectory (NTDLL.@)
3746 NTSTATUS WINAPI LdrSetDllDirectory( const UNICODE_STRING *dir )
3748 NTSTATUS status = STATUS_SUCCESS;
3749 UNICODE_STRING new;
3751 if (!dir->Buffer) RtlInitUnicodeString( &new, NULL );
3752 else if ((status = RtlDuplicateUnicodeString( 1, dir, &new ))) return status;
3754 RtlEnterCriticalSection( &dlldir_section );
3755 RtlFreeUnicodeString( &dll_directory );
3756 dll_directory = new;
3757 RtlLeaveCriticalSection( &dlldir_section );
3758 return status;
3762 /****************************************************************************
3763 * LdrAddDllDirectory (NTDLL.@)
3765 NTSTATUS WINAPI LdrAddDllDirectory( const UNICODE_STRING *dir, void **cookie )
3767 FILE_BASIC_INFORMATION info;
3768 UNICODE_STRING nt_name;
3769 NTSTATUS status;
3770 OBJECT_ATTRIBUTES attr;
3771 DWORD len;
3772 struct dll_dir_entry *ptr;
3773 DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U( dir->Buffer );
3775 if (type != ABSOLUTE_PATH && type != ABSOLUTE_DRIVE_PATH)
3776 return STATUS_INVALID_PARAMETER;
3778 status = RtlDosPathNameToNtPathName_U_WithStatus( dir->Buffer, &nt_name, NULL, NULL );
3779 if (status) return status;
3780 len = nt_name.Length / sizeof(WCHAR);
3781 if (!(ptr = RtlAllocateHeap( GetProcessHeap(), 0, offsetof(struct dll_dir_entry, dir[++len] ))))
3782 return STATUS_NO_MEMORY;
3783 memcpy( ptr->dir, nt_name.Buffer, len * sizeof(WCHAR) );
3785 attr.Length = sizeof(attr);
3786 attr.RootDirectory = 0;
3787 attr.Attributes = OBJ_CASE_INSENSITIVE;
3788 attr.ObjectName = &nt_name;
3789 attr.SecurityDescriptor = NULL;
3790 attr.SecurityQualityOfService = NULL;
3791 status = NtQueryAttributesFile( &attr, &info );
3792 RtlFreeUnicodeString( &nt_name );
3794 if (!status)
3796 TRACE( "%s\n", debugstr_w( ptr->dir ));
3797 RtlEnterCriticalSection( &dlldir_section );
3798 list_add_head( &dll_dir_list, &ptr->entry );
3799 RtlLeaveCriticalSection( &dlldir_section );
3800 *cookie = ptr;
3802 else RtlFreeHeap( GetProcessHeap(), 0, ptr );
3803 return status;
3807 /****************************************************************************
3808 * LdrRemoveDllDirectory (NTDLL.@)
3810 NTSTATUS WINAPI LdrRemoveDllDirectory( void *cookie )
3812 struct dll_dir_entry *ptr = cookie;
3814 TRACE( "%s\n", debugstr_w( ptr->dir ));
3816 RtlEnterCriticalSection( &dlldir_section );
3817 list_remove( &ptr->entry );
3818 RtlFreeHeap( GetProcessHeap(), 0, ptr );
3819 RtlLeaveCriticalSection( &dlldir_section );
3820 return STATUS_SUCCESS;
3824 /*************************************************************************
3825 * LdrSetDefaultDllDirectories (NTDLL.@)
3827 NTSTATUS WINAPI LdrSetDefaultDllDirectories( ULONG flags )
3829 /* LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR doesn't make sense in default dirs */
3830 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
3831 LOAD_LIBRARY_SEARCH_USER_DIRS |
3832 LOAD_LIBRARY_SEARCH_SYSTEM32 |
3833 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
3835 if (!flags || (flags & ~load_library_search_flags)) return STATUS_INVALID_PARAMETER;
3836 default_search_flags = flags;
3837 return STATUS_SUCCESS;
3841 /******************************************************************
3842 * LdrGetDllPath (NTDLL.@)
3844 NTSTATUS WINAPI LdrGetDllPath( PCWSTR module, ULONG flags, PWSTR *path, PWSTR *unknown )
3846 NTSTATUS status;
3847 const ULONG load_library_search_flags = (LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR |
3848 LOAD_LIBRARY_SEARCH_APPLICATION_DIR |
3849 LOAD_LIBRARY_SEARCH_USER_DIRS |
3850 LOAD_LIBRARY_SEARCH_SYSTEM32 |
3851 LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
3853 if (flags & LOAD_WITH_ALTERED_SEARCH_PATH)
3855 if (flags & load_library_search_flags) return STATUS_INVALID_PARAMETER;
3856 if (default_search_flags) flags |= default_search_flags | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR;
3858 else if (!(flags & load_library_search_flags)) flags |= default_search_flags;
3860 RtlEnterCriticalSection( &dlldir_section );
3862 if (flags & load_library_search_flags)
3864 status = get_dll_load_path_search_flags( module, flags, path );
3866 else
3868 const WCHAR *dlldir = dll_directory.Length ? dll_directory.Buffer : NULL;
3869 if (!(flags & LOAD_WITH_ALTERED_SEARCH_PATH))
3870 module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3871 status = get_dll_load_path( module, dlldir, dll_safe_mode, path );
3874 RtlLeaveCriticalSection( &dlldir_section );
3875 *unknown = NULL;
3876 return status;
3880 /*************************************************************************
3881 * RtlSetSearchPathMode (NTDLL.@)
3883 NTSTATUS WINAPI RtlSetSearchPathMode( ULONG flags )
3885 int val;
3887 switch (flags)
3889 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE:
3890 val = 1;
3891 break;
3892 case BASE_SEARCH_PATH_DISABLE_SAFE_SEARCHMODE:
3893 val = 0;
3894 break;
3895 case BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT:
3896 InterlockedExchange( (int *)&path_safe_mode, 2 );
3897 return STATUS_SUCCESS;
3898 default:
3899 return STATUS_INVALID_PARAMETER;
3902 for (;;)
3904 int prev = path_safe_mode;
3905 if (prev == 2) break; /* permanently set */
3906 if (InterlockedCompareExchange( (int *)&path_safe_mode, val, prev ) == prev) return STATUS_SUCCESS;
3908 return STATUS_ACCESS_DENIED;
3912 /******************************************************************
3913 * RtlGetExePath (NTDLL.@)
3915 NTSTATUS WINAPI RtlGetExePath( PCWSTR name, PWSTR *path )
3917 const WCHAR *dlldir = L".";
3918 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3920 /* same check as NeedCurrentDirectoryForExePathW */
3921 if (!wcschr( name, '\\' ))
3923 UNICODE_STRING name, value = { 0 };
3925 RtlInitUnicodeString( &name, L"NoDefaultCurrentDirectoryInExePath" );
3926 if (RtlQueryEnvironmentVariable_U( NULL, &name, &value ) != STATUS_VARIABLE_NOT_FOUND)
3927 dlldir = L"";
3929 return get_dll_load_path( module, dlldir, FALSE, path );
3933 /******************************************************************
3934 * RtlGetSearchPath (NTDLL.@)
3936 NTSTATUS WINAPI RtlGetSearchPath( PWSTR *path )
3938 const WCHAR *module = NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer;
3939 return get_dll_load_path( module, NULL, path_safe_mode, path );
3943 /******************************************************************
3944 * RtlReleasePath (NTDLL.@)
3946 void WINAPI RtlReleasePath( PWSTR path )
3948 RtlFreeHeap( GetProcessHeap(), 0, path );
3952 /******************************************************************
3953 * DllMain (NTDLL.@)
3955 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3957 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3958 return TRUE;
3962 /***********************************************************************
3963 * restart_winevdm
3965 static void restart_winevdm( RTL_USER_PROCESS_PARAMETERS *params )
3967 DWORD len;
3968 WCHAR *appname, *cmdline;
3970 len = wcslen(system_dir) + wcslen(L"winevdm.exe") + 1;
3971 appname = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
3972 wcscpy( appname, (is_win64 || is_wow64) ? syswow64_dir : system_dir );
3973 wcscat( appname, L"winevdm.exe" );
3975 len += 16 + wcslen(params->ImagePathName.Buffer) + wcslen(params->CommandLine.Buffer);
3976 cmdline = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
3977 swprintf( cmdline, len, L"%s --app-name \"%s\" %s",
3978 appname, params->ImagePathName.Buffer, params->CommandLine.Buffer );
3980 RtlInitUnicodeString( &params->ImagePathName, appname );
3981 RtlInitUnicodeString( &params->CommandLine, cmdline );
3985 /***********************************************************************
3986 * process_init
3988 static NTSTATUS process_init(void)
3990 RTL_USER_PROCESS_PARAMETERS *params;
3991 WINE_MODREF *wm;
3992 NTSTATUS status;
3993 ANSI_STRING func_name;
3994 UNICODE_STRING nt_name;
3995 MEMORY_BASIC_INFORMATION meminfo;
3996 INITIAL_TEB stack;
3997 TEB *teb = NtCurrentTeb();
3998 PEB *peb = teb->Peb;
4000 peb->LdrData = &ldr;
4001 peb->FastPebLock = &peb_lock;
4002 peb->TlsBitmap = &tls_bitmap;
4003 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
4004 peb->LoaderLock = &loader_section;
4005 peb->OSMajorVersion = 5;
4006 peb->OSMinorVersion = 1;
4007 peb->OSBuildNumber = 0xA28;
4008 peb->OSPlatformId = VER_PLATFORM_WIN32_NT;
4009 peb->SessionId = 1;
4010 peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL );
4012 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
4013 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
4014 sizeof(peb->TlsExpansionBitmapBits) * 8 );
4015 RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
4016 init_global_fls_data();
4018 InitializeListHead( &ldr.InLoadOrderModuleList );
4019 InitializeListHead( &ldr.InMemoryOrderModuleList );
4020 InitializeListHead( &ldr.InInitializationOrderModuleList );
4022 #ifndef _WIN64
4023 is_wow64 = !!NtCurrentTeb64();
4024 #endif
4026 init_unix_codepage();
4027 init_directories();
4028 init_user_process_params();
4029 params = peb->ProcessParameters;
4031 load_global_options();
4032 version_init();
4034 /* setup the load callback and create ntdll modref */
4035 RtlInitUnicodeString( &nt_name, L"\\??\\C:\\windows\\system32\\ntdll.dll" );
4036 NtQueryVirtualMemory( GetCurrentProcess(), process_init, MemoryBasicInformation,
4037 &meminfo, sizeof(meminfo), NULL );
4038 status = build_builtin_module( params->DllPath.Buffer, &nt_name, meminfo.AllocationBase, 0, &wm );
4039 assert( !status );
4041 if ((status = load_dll( params->DllPath.Buffer, L"C:\\windows\\system32\\kernel32.dll",
4042 NULL, 0, &wm )) != STATUS_SUCCESS)
4044 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
4045 NtTerminateProcess( GetCurrentProcess(), status );
4047 RtlInitAnsiString( &func_name, "BaseThreadInitThunk" );
4048 if ((status = LdrGetProcedureAddress( wm->ldr.DllBase, &func_name,
4049 0, (void **)&pBaseThreadInitThunk )) != STATUS_SUCCESS)
4051 MESSAGE( "wine: could not find BaseThreadInitThunk in kernel32.dll, status %x\n", status );
4052 NtTerminateProcess( GetCurrentProcess(), status );
4055 init_locale( wm->ldr.DllBase );
4057 if (!(status = load_dll( params->DllPath.Buffer, params->ImagePathName.Buffer, NULL,
4058 DONT_RESOLVE_DLL_REFERENCES, &wm )))
4060 peb->ImageBaseAddress = wm->ldr.DllBase;
4061 TRACE( "main exe loaded %s at %p\n", debugstr_us(&params->ImagePathName), peb->ImageBaseAddress );
4062 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
4064 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
4065 NtTerminateProcess( GetCurrentProcess(), STATUS_INVALID_IMAGE_FORMAT );
4068 else
4070 switch (status)
4072 case STATUS_INVALID_IMAGE_NOT_MZ:
4074 WCHAR *p = wcsrchr( params->ImagePathName.Buffer, '.' );
4075 if (p && (!wcsicmp( p, L".com" ) || !wcsicmp( p, L".pif" )))
4077 restart_winevdm( params );
4078 status = STATUS_INVALID_IMAGE_WIN_16;
4080 return status;
4082 case STATUS_INVALID_IMAGE_WIN_16:
4083 case STATUS_INVALID_IMAGE_NE_FORMAT:
4084 case STATUS_INVALID_IMAGE_PROTECT:
4085 restart_winevdm( params );
4086 return status;
4087 case STATUS_CONFLICTING_ADDRESSES:
4088 case STATUS_NO_MEMORY:
4089 case STATUS_INVALID_IMAGE_FORMAT:
4090 return status;
4091 case STATUS_INVALID_IMAGE_WIN_64:
4092 ERR( "%s 64-bit application not supported in 32-bit prefix\n",
4093 debugstr_us(&params->ImagePathName) );
4094 break;
4095 case STATUS_DLL_NOT_FOUND:
4096 ERR( "%s not found\n", debugstr_us(&params->ImagePathName) );
4097 break;
4098 default:
4099 ERR( "failed to load %s, error %x\n", debugstr_us(&params->ImagePathName), status );
4100 break;
4102 NtTerminateProcess( GetCurrentProcess(), status );
4105 #ifndef _WIN64
4106 if (NtCurrentTeb64())
4108 PEB64 *peb64 = UlongToPtr( NtCurrentTeb64()->Peb );
4109 peb64->ImageBaseAddress = PtrToUlong( peb->ImageBaseAddress );
4110 peb64->OSMajorVersion = peb->OSMajorVersion;
4111 peb64->OSMinorVersion = peb->OSMinorVersion;
4112 peb64->OSBuildNumber = peb->OSBuildNumber;
4113 peb64->OSPlatformId = peb->OSPlatformId;
4114 peb64->SessionId = peb->SessionId;
4116 #endif
4118 /* the main exe needs to be the first in the load order list */
4119 RemoveEntryList( &wm->ldr.InLoadOrderLinks );
4120 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderLinks );
4121 RemoveEntryList( &wm->ldr.InMemoryOrderLinks );
4122 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderLinks );
4124 RtlCreateUserStack( 0, 0, 0, 0x10000, 0x10000, &stack );
4125 teb->Tib.StackBase = stack.StackBase;
4126 teb->Tib.StackLimit = stack.StackLimit;
4127 teb->DeallocationStack = stack.DeallocationStack;
4128 return STATUS_SUCCESS;
4131 /***********************************************************************
4132 * __wine_set_unix_funcs
4134 NTSTATUS CDECL __wine_set_unix_funcs( int version, const struct unix_funcs *funcs )
4136 assert( version == NTDLL_UNIXLIB_VERSION );
4137 unix_funcs = funcs;
4138 return process_init();