ntoskrnl.exe: Implement ExAcquireFastMutex and ExReleaseFastMutex.
[wine.git] / dlls / ntdll / loader.c
blob8dae813e14765a4fc24763f9749349d8dcef213d
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 "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdarg.h>
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
29 #endif
31 #include "ntstatus.h"
32 #define WIN32_NO_STATUS
33 #define NONAMELESSUNION
34 #include "windef.h"
35 #include "winnt.h"
36 #include "winternl.h"
37 #include "delayloadhandler.h"
39 #include "wine/exception.h"
40 #include "wine/library.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43 #include "wine/list.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
46 #include "ddk/wdm.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
52 WINE_DECLARE_DEBUG_CHANNEL(imports);
54 #ifdef _WIN64
55 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
56 #endif
57 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
58 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
60 /* we don't want to include winuser.h */
61 #define RT_MANIFEST ((ULONG_PTR)24)
62 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
64 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
65 typedef void (CALLBACK *LDRENUMPROC)(LDR_MODULE *, void *, BOOLEAN *);
67 /* system directory with trailing backslash */
68 const WCHAR system_dir[] = {'C',':','\\','w','i','n','d','o','w','s','\\',
69 's','y','s','t','e','m','3','2','\\',0};
71 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
72 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
73 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
75 struct ldr_notification
77 struct list entry;
78 PLDR_DLL_NOTIFICATION_FUNCTION callback;
79 void *context;
82 static struct list ldr_notifications = LIST_INIT( ldr_notifications );
84 static const char * const reason_names[] =
86 "PROCESS_DETACH",
87 "PROCESS_ATTACH",
88 "THREAD_ATTACH",
89 "THREAD_DETACH",
90 NULL, NULL, NULL, NULL,
91 "WINE_PREATTACH"
94 static const WCHAR dllW[] = {'.','d','l','l',0};
96 /* internal representation of 32bit modules. per process. */
97 typedef struct _wine_modref
99 LDR_MODULE ldr;
100 dev_t dev;
101 ino_t ino;
102 int alloc_deps;
103 int nDeps;
104 struct _wine_modref **deps;
105 } WINE_MODREF;
107 /* info about the current builtin dll load */
108 /* used to keep track of things across the register_dll constructor call */
109 struct builtin_load_info
111 const WCHAR *load_path;
112 const UNICODE_STRING *filename;
113 NTSTATUS status;
114 WINE_MODREF *wm;
117 static struct builtin_load_info default_load_info;
118 static struct builtin_load_info *builtin_load_info = &default_load_info;
120 static UINT tls_module_count; /* number of modules with TLS directory */
121 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
122 LIST_ENTRY tls_links = { &tls_links, &tls_links };
124 static RTL_CRITICAL_SECTION loader_section;
125 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
127 0, 0, &loader_section,
128 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
129 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
131 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
133 static WINE_MODREF *cached_modref;
134 static WINE_MODREF *current_modref;
135 static WINE_MODREF *last_failed_modref;
137 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
138 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
139 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
140 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
141 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
142 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
144 /* convert PE image VirtualAddress to Real Address */
145 static inline void *get_rva( HMODULE module, DWORD va )
147 return (void *)((char *)module + va);
150 /* check whether the file name contains a path */
151 static inline BOOL contains_path( LPCWSTR name )
153 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
156 /* convert from straight ASCII to Unicode without depending on the current codepage */
157 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
159 while (len--) *dst++ = (unsigned char)*src++;
162 #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64
164 typedef struct _RTL_UNLOAD_EVENT_TRACE
166 void *BaseAddress;
167 SIZE_T SizeOfImage;
168 ULONG Sequence;
169 ULONG TimeDateStamp;
170 ULONG CheckSum;
171 WCHAR ImageName[32];
172 } RTL_UNLOAD_EVENT_TRACE, *PRTL_UNLOAD_EVENT_TRACE;
174 static RTL_UNLOAD_EVENT_TRACE unload_traces[RTL_UNLOAD_EVENT_TRACE_NUMBER];
175 static unsigned int unload_trace_seq;
177 static void module_push_unload_trace( const LDR_MODULE *ldr )
179 RTL_UNLOAD_EVENT_TRACE *ptr = &unload_traces[unload_trace_seq];
180 unsigned int len = min(sizeof(ptr->ImageName) - sizeof(WCHAR), ldr->BaseDllName.Length);
182 ptr->BaseAddress = ldr->BaseAddress;
183 ptr->SizeOfImage = ldr->SizeOfImage;
184 ptr->Sequence = unload_trace_seq;
185 ptr->TimeDateStamp = ldr->TimeDateStamp;
186 ptr->CheckSum = ldr->CheckSum;
187 memcpy(ptr->ImageName, ldr->BaseDllName.Buffer, len);
188 ptr->ImageName[len / sizeof(*ptr->ImageName)] = 0;
190 unload_trace_seq = (unload_trace_seq + 1) % ARRAY_SIZE(unload_traces);
193 /*********************************************************************
194 * RtlGetUnloadEventTrace [NTDLL.@]
196 RTL_UNLOAD_EVENT_TRACE * WINAPI RtlGetUnloadEventTrace(void)
198 return unload_traces;
201 /*********************************************************************
202 * RtlGetUnloadEventTraceEx [NTDLL.@]
204 void WINAPI RtlGetUnloadEventTraceEx(ULONG **size, ULONG **count, void **trace)
206 static unsigned int element_size = sizeof(*unload_traces);
207 static unsigned int element_count = ARRAY_SIZE(unload_traces);
209 *size = &element_size;
210 *count = &element_count;
211 *trace = unload_traces;
214 /*************************************************************************
215 * call_dll_entry_point
217 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
218 * their entry point, so we need a small asm wrapper. Testing indicates
219 * that only modifying esi leads to a crash, so use this one to backup
220 * ebp while running the dll entry proc.
222 #ifdef __i386__
223 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
224 __ASM_GLOBAL_FUNC(call_dll_entry_point,
225 "pushl %ebp\n\t"
226 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
227 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
228 "movl %esp,%ebp\n\t"
229 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
230 "pushl %ebx\n\t"
231 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
232 "pushl %esi\n\t"
233 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
234 "pushl %edi\n\t"
235 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
236 "movl %ebp,%esi\n\t"
237 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
238 "pushl 20(%ebp)\n\t"
239 "pushl 16(%ebp)\n\t"
240 "pushl 12(%ebp)\n\t"
241 "movl 8(%ebp),%eax\n\t"
242 "call *%eax\n\t"
243 "movl %esi,%ebp\n\t"
244 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
245 "leal -12(%ebp),%esp\n\t"
246 "popl %edi\n\t"
247 __ASM_CFI(".cfi_same_value %edi\n\t")
248 "popl %esi\n\t"
249 __ASM_CFI(".cfi_same_value %esi\n\t")
250 "popl %ebx\n\t"
251 __ASM_CFI(".cfi_same_value %ebx\n\t")
252 "popl %ebp\n\t"
253 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
254 __ASM_CFI(".cfi_same_value %ebp\n\t")
255 "ret" )
256 #else /* __i386__ */
257 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
258 UINT reason, void *reserved )
260 return proc( module, reason, reserved );
262 #endif /* __i386__ */
265 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
266 /*************************************************************************
267 * stub_entry_point
269 * Entry point for stub functions.
271 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
273 EXCEPTION_RECORD rec;
275 rec.ExceptionCode = EXCEPTION_WINE_STUB;
276 rec.ExceptionFlags = EH_NONCONTINUABLE;
277 rec.ExceptionRecord = NULL;
278 rec.ExceptionAddress = ret_addr;
279 rec.NumberParameters = 2;
280 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
281 rec.ExceptionInformation[1] = (ULONG_PTR)name;
282 for (;;) RtlRaiseException( &rec );
286 #include "pshpack1.h"
287 #ifdef __i386__
288 struct stub
290 BYTE pushl1; /* pushl $name */
291 const char *name;
292 BYTE pushl2; /* pushl $dll */
293 const char *dll;
294 BYTE call; /* call stub_entry_point */
295 DWORD entry;
297 #elif defined(__arm__)
298 struct stub
300 DWORD ldr_r0; /* ldr r0, $dll */
301 DWORD ldr_r1; /* ldr r1, $name */
302 DWORD mov_r2_lr; /* mov r2, lr */
303 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
304 const char *dll;
305 const char *name;
306 const void* entry;
308 #elif defined(__aarch64__)
309 struct stub
311 DWORD ldr_x0; /* ldr x0, $dll */
312 DWORD ldr_x1; /* ldr x1, $name */
313 DWORD mov_x2_lr; /* mov x2, lr */
314 DWORD ldr_x16; /* ldr x16, $entry */
315 DWORD br_x16; /* br x16 */
316 const char *dll;
317 const char *name;
318 const void *entry;
320 #else
321 struct stub
323 BYTE movq_rdi[2]; /* movq $dll,%rdi */
324 const char *dll;
325 BYTE movq_rsi[2]; /* movq $name,%rsi */
326 const char *name;
327 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
328 BYTE movq_rax[2]; /* movq $entry, %rax */
329 const void* entry;
330 BYTE jmpq_rax[2]; /* jmp %rax */
332 #endif
333 #include "poppack.h"
335 /*************************************************************************
336 * allocate_stub
338 * Allocate a stub entry point.
340 static ULONG_PTR allocate_stub( const char *dll, const char *name )
342 #define MAX_SIZE 65536
343 static struct stub *stubs;
344 static unsigned int nb_stubs;
345 struct stub *stub;
347 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
349 if (!stubs)
351 SIZE_T size = MAX_SIZE;
352 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
353 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
354 return 0xdeadbeef;
356 stub = &stubs[nb_stubs++];
357 #ifdef __i386__
358 stub->pushl1 = 0x68; /* pushl $name */
359 stub->name = name;
360 stub->pushl2 = 0x68; /* pushl $dll */
361 stub->dll = dll;
362 stub->call = 0xe8; /* call stub_entry_point */
363 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
364 #elif defined(__arm__)
365 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
366 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
367 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
368 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
369 stub->dll = dll;
370 stub->name = name;
371 stub->entry = stub_entry_point;
372 #elif defined(__aarch64__)
373 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
374 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
375 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
376 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
377 stub->br_x16 = 0xd61f0200; /* br x16 */
378 stub->dll = dll;
379 stub->name = name;
380 stub->entry = stub_entry_point;
381 #else
382 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
383 stub->movq_rdi[1] = 0xbf;
384 stub->dll = dll;
385 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
386 stub->movq_rsi[1] = 0xbe;
387 stub->name = name;
388 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
389 stub->movq_rsp_rdx[1] = 0x8b;
390 stub->movq_rsp_rdx[2] = 0x14;
391 stub->movq_rsp_rdx[3] = 0x24;
392 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
393 stub->movq_rax[1] = 0xb8;
394 stub->entry = stub_entry_point;
395 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
396 stub->jmpq_rax[1] = 0xe0;
397 #endif
398 return (ULONG_PTR)stub;
401 #else /* __i386__ */
402 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
403 #endif /* __i386__ */
405 /* call ldr notifications */
406 static void call_ldr_notifications( ULONG reason, LDR_MODULE *module )
408 struct ldr_notification *notify, *notify_next;
409 LDR_DLL_NOTIFICATION_DATA data;
411 data.Loaded.Flags = 0;
412 data.Loaded.FullDllName = &module->FullDllName;
413 data.Loaded.BaseDllName = &module->BaseDllName;
414 data.Loaded.DllBase = module->BaseAddress;
415 data.Loaded.SizeOfImage = module->SizeOfImage;
417 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
419 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
420 notify->callback, reason, &data, notify->context );
422 notify->callback(reason, &data, notify->context);
424 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
425 notify->callback, reason, &data, notify->context );
429 /*************************************************************************
430 * get_modref
432 * Looks for the referenced HMODULE in the current process
433 * The loader_section must be locked while calling this function.
435 static WINE_MODREF *get_modref( HMODULE hmod )
437 PLIST_ENTRY mark, entry;
438 PLDR_MODULE mod;
440 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
442 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
443 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
445 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
446 if (mod->BaseAddress == hmod)
447 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
449 return NULL;
453 /**********************************************************************
454 * find_basename_module
456 * Find a module from its base name.
457 * The loader_section must be locked while calling this function
459 static WINE_MODREF *find_basename_module( LPCWSTR name )
461 PLIST_ENTRY mark, entry;
463 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
464 return cached_modref;
466 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
467 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
469 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
470 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
472 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
473 return cached_modref;
476 return NULL;
480 /**********************************************************************
481 * find_fullname_module
483 * Find a module from its full path name.
484 * The loader_section must be locked while calling this function
486 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
488 PLIST_ENTRY mark, entry;
489 UNICODE_STRING name = *nt_name;
491 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
492 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
493 name.Buffer += 4;
495 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
496 return cached_modref;
498 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
499 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
501 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
502 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
504 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
505 return cached_modref;
508 return NULL;
512 /**********************************************************************
513 * find_fileid_module
515 * Find a module from its file id.
516 * The loader_section must be locked while calling this function
518 static WINE_MODREF *find_fileid_module( struct stat *st )
520 LIST_ENTRY *mark, *entry;
522 if (cached_modref && cached_modref->dev == st->st_dev && cached_modref->ino == st->st_ino)
523 return cached_modref;
525 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
526 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
528 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
529 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
531 if (wm->dev == st->st_dev && wm->ino == st->st_ino)
533 cached_modref = wm;
534 return wm;
537 return NULL;
541 /*************************************************************************
542 * find_forwarded_export
544 * Find the final function pointer for a forwarded function.
545 * The loader_section must be locked while calling this function.
547 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
549 const IMAGE_EXPORT_DIRECTORY *exports;
550 DWORD exp_size;
551 WINE_MODREF *wm;
552 WCHAR mod_name[32];
553 const char *end = strrchr(forward, '.');
554 FARPROC proc = NULL;
556 if (!end) return NULL;
557 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
558 ascii_to_unicode( mod_name, forward, end - forward );
559 mod_name[end - forward] = 0;
560 if (!strchrW( mod_name, '.' ))
562 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
563 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
566 if (!(wm = find_basename_module( mod_name )))
568 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
569 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
570 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
572 if (!imports_fixup_done && current_modref)
574 WINE_MODREF **deps;
575 if (current_modref->alloc_deps)
576 deps = RtlReAllocateHeap( GetProcessHeap(), 0, current_modref->deps,
577 (current_modref->alloc_deps + 1) * sizeof(*deps) );
578 else
579 deps = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps) );
580 if (deps)
582 deps[current_modref->nDeps++] = wm;
583 current_modref->deps = deps;
584 current_modref->alloc_deps++;
587 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
589 LdrUnloadDll( wm->ldr.BaseAddress );
590 wm = NULL;
594 if (!wm)
596 ERR( "module not found for forward '%s' used by %s\n",
597 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
598 return NULL;
601 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
602 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
604 const char *name = end + 1;
605 if (*name == '#') /* ordinal */
606 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
607 else
608 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
611 if (!proc)
613 ERR("function not found for forward '%s' used by %s."
614 " If you are using builtin %s, try using the native one instead.\n",
615 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
616 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
618 return proc;
622 /*************************************************************************
623 * find_ordinal_export
625 * Find an exported function by ordinal.
626 * The exports base must have been subtracted from the ordinal already.
627 * The loader_section must be locked while calling this function.
629 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
630 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
632 FARPROC proc;
633 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
635 if (ordinal >= exports->NumberOfFunctions)
637 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
638 return NULL;
640 if (!functions[ordinal]) return NULL;
642 proc = get_rva( module, functions[ordinal] );
644 /* if the address falls into the export dir, it's a forward */
645 if (((const char *)proc >= (const char *)exports) &&
646 ((const char *)proc < (const char *)exports + exp_size))
647 return find_forwarded_export( module, (const char *)proc, load_path );
649 if (TRACE_ON(snoop))
651 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
652 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
654 if (TRACE_ON(relay))
656 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
657 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
659 return proc;
663 /*************************************************************************
664 * find_named_export
666 * Find an exported function by name.
667 * The loader_section must be locked while calling this function.
669 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
670 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
672 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
673 const DWORD *names = get_rva( module, exports->AddressOfNames );
674 int min = 0, max = exports->NumberOfNames - 1;
676 /* first check the hint */
677 if (hint >= 0 && hint <= max)
679 char *ename = get_rva( module, names[hint] );
680 if (!strcmp( ename, name ))
681 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
684 /* then do a binary search */
685 while (min <= max)
687 int res, pos = (min + max) / 2;
688 char *ename = get_rva( module, names[pos] );
689 if (!(res = strcmp( ename, name )))
690 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
691 if (res > 0) max = pos - 1;
692 else min = pos + 1;
694 return NULL;
699 /*************************************************************************
700 * import_dll
702 * Import the dll specified by the given import descriptor.
703 * The loader_section must be locked while calling this function.
705 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
707 NTSTATUS status;
708 WINE_MODREF *wmImp;
709 HMODULE imp_mod;
710 const IMAGE_EXPORT_DIRECTORY *exports;
711 DWORD exp_size;
712 const IMAGE_THUNK_DATA *import_list;
713 IMAGE_THUNK_DATA *thunk_list;
714 WCHAR buffer[32];
715 const char *name = get_rva( module, descr->Name );
716 DWORD len = strlen(name);
717 PVOID protect_base;
718 SIZE_T protect_size = 0;
719 DWORD protect_old;
721 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
722 if (descr->u.OriginalFirstThunk)
723 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
724 else
725 import_list = thunk_list;
727 if (!import_list->u1.Ordinal)
729 WARN( "Skipping unused import %s\n", name );
730 *pwm = NULL;
731 return TRUE;
734 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
736 if (len * sizeof(WCHAR) < sizeof(buffer))
738 ascii_to_unicode( buffer, name, len );
739 buffer[len] = 0;
740 status = load_dll( load_path, buffer, 0, &wmImp );
742 else /* need to allocate a larger buffer */
744 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
745 if (!ptr) return FALSE;
746 ascii_to_unicode( ptr, name, len );
747 ptr[len] = 0;
748 status = load_dll( load_path, ptr, 0, &wmImp );
749 RtlFreeHeap( GetProcessHeap(), 0, ptr );
752 if (status)
754 if (status == STATUS_DLL_NOT_FOUND)
755 ERR("Library %s (which is needed by %s) not found\n",
756 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
757 else
758 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
759 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
760 return FALSE;
763 /* unprotect the import address table since it can be located in
764 * readonly section */
765 while (import_list[protect_size].u1.Ordinal) protect_size++;
766 protect_base = thunk_list;
767 protect_size *= sizeof(*thunk_list);
768 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
769 &protect_size, PAGE_READWRITE, &protect_old );
771 imp_mod = wmImp->ldr.BaseAddress;
772 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
774 if (!exports)
776 /* set all imported function to deadbeef */
777 while (import_list->u1.Ordinal)
779 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
781 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
782 WARN("No implementation for %s.%d", name, ordinal );
783 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
785 else
787 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
788 WARN("No implementation for %s.%s", name, pe_name->Name );
789 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
791 WARN(" imported from %s, allocating stub %p\n",
792 debugstr_w(current_modref->ldr.FullDllName.Buffer),
793 (void *)thunk_list->u1.Function );
794 import_list++;
795 thunk_list++;
797 goto done;
800 while (import_list->u1.Ordinal)
802 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
804 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
806 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
807 ordinal - exports->Base, load_path );
808 if (!thunk_list->u1.Function)
810 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
811 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
812 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
813 (void *)thunk_list->u1.Function );
815 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
817 else /* import by name */
819 IMAGE_IMPORT_BY_NAME *pe_name;
820 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
821 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
822 (const char*)pe_name->Name,
823 pe_name->Hint, load_path );
824 if (!thunk_list->u1.Function)
826 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
827 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
828 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
829 (void *)thunk_list->u1.Function );
831 TRACE_(imports)("--- %s %s.%d = %p\n",
832 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
834 import_list++;
835 thunk_list++;
838 done:
839 /* restore old protection of the import address table */
840 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
841 *pwm = wmImp;
842 return TRUE;
846 /***********************************************************************
847 * create_module_activation_context
849 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
851 NTSTATUS status;
852 LDR_RESOURCE_INFO info;
853 const IMAGE_RESOURCE_DATA_ENTRY *entry;
855 info.Type = RT_MANIFEST;
856 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
857 info.Language = 0;
858 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
860 ACTCTXW ctx;
861 ctx.cbSize = sizeof(ctx);
862 ctx.lpSource = NULL;
863 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
864 ctx.hModule = module->BaseAddress;
865 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
866 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
868 return status;
872 /*************************************************************************
873 * is_dll_native_subsystem
875 * Check if dll is a proper native driver.
876 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
877 * while being perfectly normal DLLs. This heuristic should catch such breakages.
879 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
881 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
882 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
883 const IMAGE_IMPORT_DESCRIPTOR *imports;
884 DWORD i, size;
885 WCHAR buffer[16];
887 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
888 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
890 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
891 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
893 for (i = 0; imports[i].Name; i++)
895 const char *name = get_rva( module, imports[i].Name );
896 DWORD len = strlen(name);
897 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
898 ascii_to_unicode( buffer, name, len + 1 );
899 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
901 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
902 return FALSE;
906 return TRUE;
909 /*************************************************************************
910 * alloc_tls_slot
912 * Allocate a TLS slot for a newly-loaded module.
913 * The loader_section must be locked while calling this function.
915 static SHORT alloc_tls_slot( LDR_MODULE *mod )
917 const IMAGE_TLS_DIRECTORY *dir;
918 ULONG i, size;
919 void *new_ptr;
920 LIST_ENTRY *entry;
922 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
923 return -1;
925 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
926 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
928 for (i = 0; i < tls_module_count; i++)
930 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
931 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
932 break;
935 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
936 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
937 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
939 if (i == tls_module_count)
941 UINT new_count = max( 32, tls_module_count * 2 );
943 if (!tls_dirs)
944 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
945 else
946 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
947 new_count * sizeof(*tls_dirs) );
948 if (!new_ptr) return -1;
950 /* resize the pointer block in all running threads */
951 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
953 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
954 void **old = teb->ThreadLocalStoragePointer;
955 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
957 if (!new) return -1;
958 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
959 teb->ThreadLocalStoragePointer = new;
960 #if defined(__APPLE__) && defined(__x86_64__)
961 if (teb->Reserved5[0])
962 ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
963 #endif
964 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
965 /* FIXME: can't free old block here, should be freed at thread exit */
968 tls_dirs = new_ptr;
969 tls_module_count = new_count;
972 /* allocate the data block in all running threads */
973 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
975 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
977 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
978 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
979 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
981 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
982 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
984 RtlFreeHeap( GetProcessHeap(), 0,
985 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
988 *(DWORD *)dir->AddressOfIndex = i;
989 tls_dirs[i] = *dir;
990 return i;
994 /*************************************************************************
995 * free_tls_slot
997 * Free the module TLS slot on unload.
998 * The loader_section must be locked while calling this function.
1000 static void free_tls_slot( LDR_MODULE *mod )
1002 ULONG i = (USHORT)mod->TlsIndex;
1004 if (mod->TlsIndex == -1) return;
1005 assert( i < tls_module_count );
1006 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
1010 /****************************************************************
1011 * fixup_imports_ilonly
1013 * Fixup imports for an IL-only module. All we do is import mscoree.
1014 * The loader_section must be locked while calling this function.
1016 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
1018 static const WCHAR mscoreeW[] = {'m','s','c','o','r','e','e','.','d','l','l',0};
1019 IMAGE_EXPORT_DIRECTORY *exports;
1020 DWORD exp_size;
1021 NTSTATUS status;
1022 void *proc = NULL;
1023 WINE_MODREF *prev, *imp;
1025 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1026 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1028 wm->nDeps = 1;
1029 wm->alloc_deps = 1;
1030 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(WINE_MODREF *) );
1032 prev = current_modref;
1033 current_modref = wm;
1034 if (!(status = load_dll( load_path, mscoreeW, 0, &imp ))) wm->deps[0] = imp;
1035 current_modref = prev;
1036 if (status)
1038 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
1039 debugstr_w(wm->ldr.BaseDllName.Buffer) );
1040 return status;
1043 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1045 if ((exports = RtlImageDirectoryEntryToData( imp->ldr.BaseAddress, TRUE,
1046 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1048 const char *name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
1049 proc = find_named_export( imp->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
1051 if (!proc) return STATUS_PROCEDURE_NOT_FOUND;
1052 *entry = proc;
1053 return STATUS_SUCCESS;
1057 /****************************************************************
1058 * fixup_imports
1060 * Fixup all imports of a given module.
1061 * The loader_section must be locked while calling this function.
1063 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1065 int i, dep, nb_imports;
1066 const IMAGE_IMPORT_DESCRIPTOR *imports;
1067 WINE_MODREF *prev, *imp;
1068 DWORD size;
1069 NTSTATUS status;
1070 ULONG_PTR cookie;
1072 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1073 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1075 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
1077 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
1078 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1079 return STATUS_SUCCESS;
1081 nb_imports = 0;
1082 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1084 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1086 if (!create_module_activation_context( &wm->ldr ))
1087 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1089 /* Allocate module dependency list */
1090 wm->alloc_deps = nb_imports;
1091 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
1093 /* load the imported modules. They are automatically
1094 * added to the modref list of the process.
1096 prev = current_modref;
1097 current_modref = wm;
1098 status = STATUS_SUCCESS;
1099 for (i = 0; i < nb_imports; i++)
1101 dep = wm->nDeps++;
1103 if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &imp ))
1105 imp = NULL;
1106 status = STATUS_DLL_NOT_FOUND;
1108 wm->deps[dep] = imp;
1110 current_modref = prev;
1111 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1112 return status;
1116 /*************************************************************************
1117 * alloc_module
1119 * Allocate a WINE_MODREF structure and add it to the process list
1120 * The loader_section must be locked while calling this function.
1122 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name )
1124 WINE_MODREF *wm;
1125 const WCHAR *p;
1126 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1128 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1130 wm->ldr.BaseAddress = hModule;
1131 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1132 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
1133 wm->ldr.TlsIndex = -1;
1134 wm->ldr.LoadCount = 1;
1136 RtlCreateUnicodeString( &wm->ldr.FullDllName, nt_name->Buffer + 4 /* \??\ prefix */ );
1137 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
1138 else p = wm->ldr.FullDllName.Buffer;
1139 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1141 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
1143 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1144 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1145 if (nt->OptionalHeader.AddressOfEntryPoint)
1146 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1149 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1150 &wm->ldr.InLoadOrderModuleList);
1151 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1152 &wm->ldr.InMemoryOrderModuleList);
1153 /* wait until init is called for inserting into InInitializationOrderModuleList */
1155 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1157 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1158 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1159 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1161 return wm;
1165 /*************************************************************************
1166 * alloc_thread_tls
1168 * Allocate the per-thread structure for module TLS storage.
1170 static NTSTATUS alloc_thread_tls(void)
1172 void **pointers;
1173 UINT i, size;
1175 if (!tls_module_count) return STATUS_SUCCESS;
1177 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1178 tls_module_count * sizeof(*pointers) )))
1179 return STATUS_NO_MEMORY;
1181 for (i = 0; i < tls_module_count; i++)
1183 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1185 if (!dir) continue;
1186 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1187 if (!size && !dir->SizeOfZeroFill) continue;
1189 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1191 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1192 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1193 return STATUS_NO_MEMORY;
1195 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1196 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1198 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1199 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1201 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1202 #if defined(__APPLE__) && defined(__x86_64__)
1203 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
1205 : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
1206 #endif
1207 return STATUS_SUCCESS;
1211 /*************************************************************************
1212 * call_tls_callbacks
1214 static void call_tls_callbacks( HMODULE module, UINT reason )
1216 const IMAGE_TLS_DIRECTORY *dir;
1217 const PIMAGE_TLS_CALLBACK *callback;
1218 ULONG dirsize;
1220 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1221 if (!dir || !dir->AddressOfCallBacks) return;
1223 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1225 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1226 *callback, module, reason_names[reason] );
1227 __TRY
1229 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1231 __EXCEPT_ALL
1233 TRACE_(relay)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1234 GetExceptionCode(), callback, module, reason_names[reason] );
1235 return;
1237 __ENDTRY
1238 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1239 *callback, module, reason_names[reason] );
1244 /*************************************************************************
1245 * MODULE_InitDLL
1247 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1249 WCHAR mod_name[32];
1250 NTSTATUS status = STATUS_SUCCESS;
1251 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1252 void *module = wm->ldr.BaseAddress;
1253 BOOL retv = FALSE;
1255 /* Skip calls for modules loaded with special load flags */
1257 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1258 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1259 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1261 if (TRACE_ON(relay))
1263 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1264 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1265 mod_name[len / sizeof(WCHAR)] = 0;
1266 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1267 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1269 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1270 reason_names[reason], lpReserved );
1272 __TRY
1274 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1275 if (!retv)
1276 status = STATUS_DLL_INIT_FAILED;
1278 __EXCEPT_ALL
1280 status = GetExceptionCode();
1281 TRACE_(relay)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1282 status, entry, module, reason_names[reason], lpReserved );
1284 __ENDTRY
1286 /* The state of the module list may have changed due to the call
1287 to the dll. We cannot assume that this module has not been
1288 deleted. */
1289 if (TRACE_ON(relay))
1290 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1291 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1292 else
1293 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1295 return status;
1299 /*************************************************************************
1300 * process_attach
1302 * Send the process attach notification to all DLLs the given module
1303 * depends on (recursively). This is somewhat complicated due to the fact that
1305 * - we have to respect the module dependencies, i.e. modules implicitly
1306 * referenced by another module have to be initialized before the module
1307 * itself can be initialized
1309 * - the initialization routine of a DLL can itself call LoadLibrary,
1310 * thereby introducing a whole new set of dependencies (even involving
1311 * the 'old' modules) at any time during the whole process
1313 * (Note that this routine can be recursively entered not only directly
1314 * from itself, but also via LoadLibrary from one of the called initialization
1315 * routines.)
1317 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1318 * the process *detach* notifications to be sent in the correct order.
1319 * This must not only take into account module dependencies, but also
1320 * 'hidden' dependencies created by modules calling LoadLibrary in their
1321 * attach notification routine.
1323 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1324 * list after the attach notification has returned. This implies that the
1325 * detach notifications are called in the reverse of the sequence the attach
1326 * notifications *returned*.
1328 * The loader_section must be locked while calling this function.
1330 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1332 NTSTATUS status = STATUS_SUCCESS;
1333 ULONG_PTR cookie;
1334 int i;
1336 if (process_detaching) return status;
1338 /* prevent infinite recursion in case of cyclical dependencies */
1339 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1340 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1341 return status;
1343 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1345 /* Tag current MODREF to prevent recursive loop */
1346 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1347 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1348 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1350 /* Recursively attach all DLLs this one depends on */
1351 for ( i = 0; i < wm->nDeps; i++ )
1353 if (!wm->deps[i]) continue;
1354 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1357 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1358 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1359 &wm->ldr.InInitializationOrderModuleList);
1361 /* Call DLL entry point */
1362 if (status == STATUS_SUCCESS)
1364 WINE_MODREF *prev = current_modref;
1365 current_modref = wm;
1367 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1368 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1369 if (status == STATUS_SUCCESS)
1371 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1373 else
1375 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1376 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1378 /* point to the name so LdrInitializeThunk can print it */
1379 last_failed_modref = wm;
1380 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1382 current_modref = prev;
1385 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1386 /* Remove recursion flag */
1387 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1389 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1390 return status;
1394 /**********************************************************************
1395 * attach_implicitly_loaded_dlls
1397 * Attach to the (builtin) dlls that have been implicitly loaded because
1398 * of a dependency at the Unix level, but not imported at the Win32 level.
1400 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1402 for (;;)
1404 PLIST_ENTRY mark, entry;
1406 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1407 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1409 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1411 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1412 TRACE( "found implicitly loaded %s, attaching to it\n",
1413 debugstr_w(mod->BaseDllName.Buffer));
1414 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1415 break; /* restart the search from the start */
1417 if (entry == mark) break; /* nothing found */
1422 /*************************************************************************
1423 * process_detach
1425 * Send DLL process detach notifications. See the comment about calling
1426 * sequence at process_attach.
1428 static void process_detach(void)
1430 PLIST_ENTRY mark, entry;
1431 PLDR_MODULE mod;
1433 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1436 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1438 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1439 InInitializationOrderModuleList);
1440 /* Check whether to detach this DLL */
1441 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1442 continue;
1443 if ( mod->LoadCount && !process_detaching )
1444 continue;
1446 /* Call detach notification */
1447 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1448 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1449 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1450 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1452 /* Restart at head of WINE_MODREF list, as entries might have
1453 been added and/or removed while performing the call ... */
1454 break;
1456 } while (entry != mark);
1459 /*************************************************************************
1460 * thread_attach
1462 * Send DLL thread attach notifications. These are sent in the
1463 * reverse sequence of process detach notification.
1464 * The loader_section must be locked while calling this function.
1466 static void thread_attach(void)
1468 PLIST_ENTRY mark, entry;
1469 PLDR_MODULE mod;
1471 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1472 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1474 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1475 InInitializationOrderModuleList);
1476 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1477 continue;
1478 if ( mod->Flags & LDR_NO_DLL_CALLS )
1479 continue;
1481 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1485 /******************************************************************
1486 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1489 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1491 WINE_MODREF *wm;
1492 NTSTATUS ret = STATUS_SUCCESS;
1494 RtlEnterCriticalSection( &loader_section );
1496 wm = get_modref( hModule );
1497 if (!wm || wm->ldr.TlsIndex != -1)
1498 ret = STATUS_DLL_NOT_FOUND;
1499 else
1500 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1502 RtlLeaveCriticalSection( &loader_section );
1504 return ret;
1507 /******************************************************************
1508 * LdrFindEntryForAddress (NTDLL.@)
1510 * The loader_section must be locked while calling this function
1512 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1514 PLIST_ENTRY mark, entry;
1515 PLDR_MODULE mod;
1517 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1518 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1520 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1521 if (mod->BaseAddress <= addr &&
1522 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1524 *pmod = mod;
1525 return STATUS_SUCCESS;
1528 return STATUS_NO_MORE_ENTRIES;
1531 /******************************************************************
1532 * LdrEnumerateLoadedModules (NTDLL.@)
1534 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1536 LIST_ENTRY *mark, *entry;
1537 LDR_MODULE *mod;
1538 BOOLEAN stop = FALSE;
1540 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1542 if (unknown || !callback)
1543 return STATUS_INVALID_PARAMETER;
1545 RtlEnterCriticalSection( &loader_section );
1547 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1548 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1550 mod = CONTAINING_RECORD( entry, LDR_MODULE, InMemoryOrderModuleList );
1551 callback( mod, context, &stop );
1552 if (stop) break;
1555 RtlLeaveCriticalSection( &loader_section );
1556 return STATUS_SUCCESS;
1559 /******************************************************************
1560 * LdrRegisterDllNotification (NTDLL.@)
1562 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1563 void *context, void **cookie)
1565 struct ldr_notification *notify;
1567 TRACE( "(%x, %p, %p, %p)\n", flags, callback, context, cookie );
1569 if (!callback || !cookie)
1570 return STATUS_INVALID_PARAMETER;
1572 if (flags)
1573 FIXME( "ignoring flags %x\n", flags );
1575 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1576 if (!notify) return STATUS_NO_MEMORY;
1577 notify->callback = callback;
1578 notify->context = context;
1580 RtlEnterCriticalSection( &loader_section );
1581 list_add_tail( &ldr_notifications, &notify->entry );
1582 RtlLeaveCriticalSection( &loader_section );
1584 *cookie = notify;
1585 return STATUS_SUCCESS;
1588 /******************************************************************
1589 * LdrUnregisterDllNotification (NTDLL.@)
1591 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1593 struct ldr_notification *notify = cookie;
1595 TRACE( "(%p)\n", cookie );
1597 if (!notify) return STATUS_INVALID_PARAMETER;
1599 RtlEnterCriticalSection( &loader_section );
1600 list_remove( &notify->entry );
1601 RtlLeaveCriticalSection( &loader_section );
1603 RtlFreeHeap( GetProcessHeap(), 0, notify );
1604 return STATUS_SUCCESS;
1607 /******************************************************************
1608 * LdrLockLoaderLock (NTDLL.@)
1610 * Note: some flags are not implemented.
1611 * Flag 0x01 is used to raise exceptions on errors.
1613 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1615 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1617 if (result) *result = 0;
1618 if (magic) *magic = 0;
1619 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1620 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1621 if (!magic) return STATUS_INVALID_PARAMETER_3;
1623 if (flags & 0x2)
1625 if (!RtlTryEnterCriticalSection( &loader_section ))
1627 *result = 2;
1628 return STATUS_SUCCESS;
1630 *result = 1;
1632 else
1634 RtlEnterCriticalSection( &loader_section );
1635 if (result) *result = 1;
1637 *magic = GetCurrentThreadId();
1638 return STATUS_SUCCESS;
1642 /******************************************************************
1643 * LdrUnlockLoaderUnlock (NTDLL.@)
1645 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1647 if (magic)
1649 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1650 RtlLeaveCriticalSection( &loader_section );
1652 return STATUS_SUCCESS;
1656 /******************************************************************
1657 * LdrGetProcedureAddress (NTDLL.@)
1659 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1660 ULONG ord, PVOID *address)
1662 IMAGE_EXPORT_DIRECTORY *exports;
1663 DWORD exp_size;
1664 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1666 RtlEnterCriticalSection( &loader_section );
1668 /* check if the module itself is invalid to return the proper error */
1669 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1670 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1671 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1673 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1674 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1675 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1676 if (proc)
1678 *address = proc;
1679 ret = STATUS_SUCCESS;
1683 RtlLeaveCriticalSection( &loader_section );
1684 return ret;
1688 /***********************************************************************
1689 * get_builtin_fullname
1691 * Build the full pathname for a builtin dll.
1693 static BOOL get_builtin_fullname( UNICODE_STRING *nt_name, const UNICODE_STRING *path,
1694 const char *filename )
1696 static const WCHAR nt_prefixW[] = {'\\','?','?','\\',0};
1697 static const WCHAR soW[] = {'.','s','o',0};
1698 WCHAR *p, *fullname;
1699 size_t i, len = strlen(filename);
1701 /* check if path can correspond to the dll we have */
1702 if (path && (p = strrchrW( path->Buffer, '\\' )))
1704 p++;
1705 for (i = 0; i < len; i++)
1706 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1707 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1709 /* the filename matches, use path as the full path */
1710 len += p - path->Buffer;
1711 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1712 return FALSE;
1713 memcpy( fullname, path->Buffer, len * sizeof(WCHAR) );
1714 fullname[len] = 0;
1715 goto done;
1719 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1720 (strlenW(system_dir) + len + 5) * sizeof(WCHAR) )))
1721 return FALSE;
1722 strcpyW( fullname, nt_prefixW );
1723 strcatW( fullname, system_dir );
1724 ascii_to_unicode( fullname + strlenW(fullname), filename, len + 1 );
1725 done:
1726 RtlInitUnicodeString( nt_name, fullname );
1727 return TRUE;
1731 /*************************************************************************
1732 * is_16bit_builtin
1734 static BOOL is_16bit_builtin( HMODULE module )
1736 const IMAGE_EXPORT_DIRECTORY *exports;
1737 DWORD exp_size;
1739 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1740 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1741 return FALSE;
1743 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1747 /***********************************************************************
1748 * load_builtin_callback
1750 * Load a library in memory; callback function for wine_dll_register
1752 static void load_builtin_callback( void *module, const char *filename )
1754 static const WCHAR emptyW[1];
1755 IMAGE_NT_HEADERS *nt;
1756 WINE_MODREF *wm;
1757 UNICODE_STRING nt_name;
1758 const WCHAR *load_path;
1760 if (!module)
1762 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1763 return;
1765 if (!(nt = RtlImageNtHeader( module )))
1767 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1768 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1769 return;
1772 virtual_create_builtin_view( module );
1774 /* create the MODREF */
1776 if (!get_builtin_fullname( &nt_name, builtin_load_info->filename, filename ))
1778 ERR( "can't load %s\n", filename );
1779 builtin_load_info->status = STATUS_NO_MEMORY;
1780 return;
1783 wm = alloc_module( module, &nt_name );
1784 RtlFreeUnicodeString( &nt_name );
1785 if (!wm)
1787 ERR( "can't load %s\n", filename );
1788 builtin_load_info->status = STATUS_NO_MEMORY;
1789 return;
1791 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1793 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1794 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1795 is_16bit_builtin( module ))
1797 /* fixup imports */
1799 load_path = builtin_load_info->load_path;
1800 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1801 if (!load_path) load_path = emptyW;
1802 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1804 /* the module has only be inserted in the load & memory order lists */
1805 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1806 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1807 /* FIXME: free the modref */
1808 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1809 return;
1813 builtin_load_info->wm = wm;
1814 TRACE( "loaded %s %p %p\n", filename, wm, module );
1816 /* send the DLL load event */
1818 SERVER_START_REQ( load_dll )
1820 req->base = wine_server_client_ptr( module );
1821 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1822 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1823 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1824 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1825 wine_server_call( req );
1827 SERVER_END_REQ;
1829 /* setup relay debugging entry points */
1830 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1834 /***********************************************************************
1835 * set_security_cookie
1837 * Create a random security cookie for buffer overflow protection. Make
1838 * sure it does not accidentally match the default cookie value.
1840 static void set_security_cookie( void *module, SIZE_T len )
1842 static ULONG seed;
1843 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1844 ULONG loadcfg_size;
1845 ULONG_PTR *cookie;
1847 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1848 if (!loadcfg) return;
1849 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1850 if (!loadcfg->SecurityCookie) return;
1851 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1852 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1854 WARN( "security cookie %p outside of image %p-%p\n",
1855 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1856 return;
1859 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1860 TRACE( "initializing security cookie %p\n", cookie );
1862 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1863 for (;;)
1865 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1866 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1867 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1868 *cookie = RtlRandom( &seed );
1869 #ifdef DEFAULT_SECURITY_COOKIE_64
1870 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1872 *cookie = RtlRandom( &seed );
1873 /* fill up, but keep the highest word clear */
1874 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1876 #endif
1877 else
1878 break;
1882 static NTSTATUS perform_relocations( void *module, IMAGE_NT_HEADERS *nt, SIZE_T len )
1884 char *base;
1885 IMAGE_BASE_RELOCATION *rel, *end;
1886 const IMAGE_DATA_DIRECTORY *relocs;
1887 const IMAGE_SECTION_HEADER *sec;
1888 INT_PTR delta;
1889 ULONG protect_old[96], i;
1891 base = (char *)nt->OptionalHeader.ImageBase;
1892 if (module == base) return STATUS_SUCCESS; /* nothing to do */
1894 /* no relocations are performed on non page-aligned binaries */
1895 if (nt->OptionalHeader.SectionAlignment < page_size)
1896 return STATUS_SUCCESS;
1898 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1899 return STATUS_SUCCESS;
1901 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1903 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1905 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1906 base, module );
1907 return STATUS_CONFLICTING_ADDRESSES;
1910 if (!relocs->Size) return STATUS_SUCCESS;
1911 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1913 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
1914 return STATUS_INVALID_IMAGE_FORMAT;
1916 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1917 nt->FileHeader.SizeOfOptionalHeader);
1918 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1920 void *addr = get_rva( module, sec[i].VirtualAddress );
1921 SIZE_T size = sec[i].SizeOfRawData;
1922 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1923 &size, PAGE_READWRITE, &protect_old[i] );
1926 TRACE( "relocating from %p-%p to %p-%p\n",
1927 base, base + len, module, (char *)module + len );
1929 rel = get_rva( module, relocs->VirtualAddress );
1930 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1931 delta = (char *)module - base;
1933 while (rel < end - 1 && rel->SizeOfBlock)
1935 if (rel->VirtualAddress >= len)
1937 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1938 return STATUS_ACCESS_VIOLATION;
1940 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1941 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1942 (USHORT *)(rel + 1), delta );
1943 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1946 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1948 void *addr = get_rva( module, sec[i].VirtualAddress );
1949 SIZE_T size = sec[i].SizeOfRawData;
1950 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1951 &size, protect_old[i], &protect_old[i] );
1954 return STATUS_SUCCESS;
1957 #ifdef _WIN64
1958 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1959 static BOOL convert_to_pe64( HMODULE module, const pe_image_info_t *info )
1961 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
1962 IMAGE_DIRECTORY_ENTRY_SECURITY,
1963 IMAGE_DIRECTORY_ENTRY_BASERELOC,
1964 IMAGE_DIRECTORY_ENTRY_DEBUG,
1965 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
1966 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
1967 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
1968 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1969 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
1970 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
1971 SIZE_T size = info->header_size;
1972 void *addr = module;
1973 ULONG i, old_prot;
1975 TRACE( "%p\n", module );
1977 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
1978 return FALSE;
1980 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
1982 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1983 return FALSE;
1986 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
1987 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
1988 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1989 hdr64.AddressOfEntryPoint = 0;
1990 hdr64.ImageBase = hdr32.ImageBase;
1991 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
1992 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
1993 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
1994 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
1995 hdr64.LoaderFlags = hdr32.LoaderFlags;
1996 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
1997 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
1998 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
2000 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
2001 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
2002 nt->OptionalHeader = hdr64;
2003 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
2004 return TRUE;
2006 #endif
2008 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
2009 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
2010 static BOOL is_valid_binary( HMODULE module, const pe_image_info_t *info )
2012 #ifdef __i386__
2013 return info->machine == IMAGE_FILE_MACHINE_I386;
2014 #elif defined(__arm__)
2015 return info->machine == IMAGE_FILE_MACHINE_ARM ||
2016 info->machine == IMAGE_FILE_MACHINE_THUMB ||
2017 info->machine == IMAGE_FILE_MACHINE_ARMNT;
2018 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
2019 #ifdef __x86_64__
2020 if (info->machine == IMAGE_FILE_MACHINE_AMD64) return TRUE;
2021 #else
2022 if (info->machine == IMAGE_FILE_MACHINE_ARM64) return TRUE;
2023 #endif
2024 if (!info->contains_code) return TRUE;
2025 if (!(info->image_flags & IMAGE_FLAGS_ComPlusNativeReady))
2027 /* check COM header directly, ignoring runtime version */
2028 DWORD size;
2029 const IMAGE_COR20_HEADER *cor_header = RtlImageDirectoryEntryToData( module, TRUE,
2030 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size );
2031 if (!cor_header || !(cor_header->Flags & COMIMAGE_FLAGS_ILONLY)) return FALSE;
2033 return convert_to_pe64( module, info );
2034 #else
2035 return FALSE; /* no wow64 support on other platforms */
2036 #endif
2040 /***********************************************************************
2041 * open_dll_file
2043 * Open a file for a new dll. Helper for find_dll_file.
2045 static NTSTATUS open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm,
2046 void **module, pe_image_info_t *image_info, struct stat *st )
2048 FILE_BASIC_INFORMATION info;
2049 OBJECT_ATTRIBUTES attr;
2050 IO_STATUS_BLOCK io;
2051 LARGE_INTEGER size;
2052 SIZE_T len = 0;
2053 NTSTATUS status;
2054 HANDLE handle, mapping;
2055 int fd, needs_close;
2057 if ((*pwm = find_fullname_module( nt_name ))) return STATUS_SUCCESS;
2059 attr.Length = sizeof(attr);
2060 attr.RootDirectory = 0;
2061 attr.Attributes = OBJ_CASE_INSENSITIVE;
2062 attr.ObjectName = nt_name;
2063 attr.SecurityDescriptor = NULL;
2064 attr.SecurityQualityOfService = NULL;
2065 if ((status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io,
2066 FILE_SHARE_READ | FILE_SHARE_DELETE,
2067 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE )))
2069 if (status != STATUS_OBJECT_PATH_NOT_FOUND &&
2070 status != STATUS_OBJECT_NAME_NOT_FOUND &&
2071 !NtQueryAttributesFile( &attr, &info ))
2073 /* if the file exists but failed to open, report the error */
2074 return status;
2076 /* otherwise continue searching */
2077 return STATUS_DLL_NOT_FOUND;
2080 if (!server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL ))
2082 fstat( fd, st );
2083 if (needs_close) close( fd );
2084 if ((*pwm = find_fileid_module( st )))
2086 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2087 (*pwm)->ldr.BaseAddress, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2088 NtClose( handle );
2089 return STATUS_SUCCESS;
2093 size.QuadPart = 0;
2094 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2095 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2096 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, handle );
2097 NtClose( handle );
2099 if (!status)
2101 status = virtual_map_section( mapping, module, 0, 0, NULL, &len,
2102 PAGE_EXECUTE_READ, image_info );
2103 if (status == STATUS_IMAGE_NOT_AT_BASE) status = STATUS_SUCCESS;
2104 NtClose( mapping );
2106 if (!status && !is_valid_binary( *module, image_info ))
2108 TRACE( "%s is for arch %x, continuing search\n", debugstr_us(nt_name), image_info->machine );
2109 NtUnmapViewOfSection( NtCurrentProcess(), *module );
2110 status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2112 return status;
2116 /******************************************************************************
2117 * load_native_dll (internal)
2119 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, void *module,
2120 const pe_image_info_t *image_info, DWORD flags, WINE_MODREF** pwm,
2121 struct stat *st )
2123 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
2124 WINE_MODREF *wm;
2125 NTSTATUS status;
2126 const char *dll_type = (image_info->image_flags & IMAGE_FLAGS_WineBuiltin) ? "PE builtin" : "native";
2128 TRACE("Trying %s dll %s\n", dll_type, debugstr_us(nt_name) );
2130 /* perform base relocation, if necessary */
2132 if ((status = perform_relocations( module, nt, image_info->map_size )))
2134 NtUnmapViewOfSection( NtCurrentProcess(), module );
2135 return status;
2138 /* create the MODREF */
2140 if (!(wm = alloc_module( module, nt_name )))
2142 NtUnmapViewOfSection( NtCurrentProcess(), module );
2143 return STATUS_NO_MEMORY;
2146 wm->dev = st->st_dev;
2147 wm->ino = st->st_ino;
2148 if (image_info->loader_flags) wm->ldr.Flags |= LDR_COR_IMAGE;
2149 if (image_info->image_flags & IMAGE_FLAGS_ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
2151 set_security_cookie( module, image_info->map_size );
2153 /* fixup imports */
2155 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
2156 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
2157 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
2159 if (wm->ldr.Flags & LDR_COR_ILONLY)
2160 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
2161 else
2162 status = fixup_imports( wm, load_path );
2163 if (status != STATUS_SUCCESS)
2165 /* the module has only be inserted in the load & memory order lists */
2166 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2167 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2169 /* FIXME: there are several more dangling references
2170 * left. Including dlls loaded by this dll before the
2171 * failed one. Unrolling is rather difficult with the
2172 * current structure and we can leave them lying
2173 * around with no problems, so we don't care.
2174 * As these might reference our wm, we don't free it.
2176 return status;
2180 /* send DLL load event */
2182 SERVER_START_REQ( load_dll )
2184 req->base = wine_server_client_ptr( module );
2185 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
2186 req->dbg_size = nt->FileHeader.NumberOfSymbols;
2187 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
2188 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
2189 wine_server_call( req );
2191 SERVER_END_REQ;
2193 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
2195 TRACE_(loaddll)( "Loaded %s at %p: %s\n", debugstr_w(wm->ldr.FullDllName.Buffer), module, dll_type );
2197 wm->ldr.LoadCount = 1;
2198 *pwm = wm;
2199 return STATUS_SUCCESS;
2203 /* check if the library is the correct architecture */
2204 /* only returns false for a valid library of the wrong arch */
2205 static int check_library_arch( int fd )
2207 #ifdef __APPLE__
2208 struct /* Mach-O header */
2210 unsigned int magic;
2211 unsigned int cputype;
2212 } header;
2214 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
2215 if (header.magic != 0xfeedface) return 1;
2216 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
2217 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
2218 #else
2219 struct /* ELF header */
2221 unsigned char magic[4];
2222 unsigned char class;
2223 unsigned char data;
2224 unsigned char version;
2225 } header;
2227 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
2228 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
2229 if (header.version != 1 /* EV_CURRENT */) return 1;
2230 #ifdef WORDS_BIGENDIAN
2231 if (header.data != 2 /* ELFDATA2MSB */) return 1;
2232 #else
2233 if (header.data != 1 /* ELFDATA2LSB */) return 1;
2234 #endif
2235 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
2236 else return header.class == 2; /* ELFCLASS64 */
2237 #endif
2240 static inline char *prepend( char *buffer, const char *str, size_t len )
2242 return memcpy( buffer - len, str, len );
2245 /***********************************************************************
2246 * open_builtin_file
2248 static NTSTATUS open_builtin_file( char *name, WINE_MODREF **pwm, void **module,
2249 pe_image_info_t *image_info, struct stat *st, char **so_name )
2251 ANSI_STRING strA;
2252 UNICODE_STRING nt_name;
2253 NTSTATUS status;
2254 int fd;
2256 nt_name.Buffer = NULL;
2257 RtlInitString( &strA, name );
2258 if ((status = wine_unix_to_nt_file_name( &strA, &nt_name ))) return status;
2260 status = open_dll_file( &nt_name, pwm, module, image_info, st );
2261 RtlFreeUnicodeString( &nt_name );
2263 /* ignore non-builtins */
2264 if (!status && !*pwm && !(image_info->image_flags & IMAGE_FLAGS_WineBuiltin))
2266 WARN( "%s found in WINEDLLPATH but not a builtin, ignoring\n", debugstr_a(name) );
2267 NtUnmapViewOfSection( NtCurrentProcess(), *module );
2268 status = STATUS_DLL_NOT_FOUND;
2271 if (status != STATUS_DLL_NOT_FOUND) return status;
2273 /* try .so file */
2275 strcat( name, ".so" );
2276 if ((fd = open( name, O_RDONLY )) != -1)
2278 if (check_library_arch( fd ))
2280 if ((*so_name = RtlAllocateHeap( GetProcessHeap(), 0, strlen(name) + 1 )))
2281 strcpy( *so_name, name );
2282 status = STATUS_SUCCESS;
2284 else status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2285 close( fd );
2287 return status;
2291 /***********************************************************************
2292 * find_builtin_dll
2294 static NTSTATUS find_builtin_dll( const WCHAR *name, WINE_MODREF **pwm,
2295 void **module, pe_image_info_t *image_info, struct stat *st,
2296 char **so_name )
2298 const char *path, *build_dir = wine_get_build_dir();
2299 unsigned int i, pos, len, namelen, maxlen = 0;
2300 char *ptr, *file;
2301 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2302 BOOL found_image = FALSE;
2304 len = strlenW( name );
2305 if (build_dir) maxlen = strlen(build_dir) + sizeof("/programs/") + len;
2306 for (i = 0; (path = wine_dll_enum_load_path( i )); i++) maxlen = max( maxlen, strlen(path) );
2307 maxlen += len + sizeof(".so");
2309 if (!(file = RtlAllocateHeap( GetProcessHeap(), 0, maxlen ))) return STATUS_NO_MEMORY;
2311 pos = maxlen - len - sizeof(".so");
2312 /* we don't want to depend on the current codepage here */
2313 for (i = 0; i < len; i++)
2315 if (name[i] > 127) goto done;
2316 file[pos + i] = (char)name[i];
2317 if (file[pos + i] >= 'A' && file[pos + i] <= 'Z') file[pos + i] += 'a' - 'A';
2319 file[--pos] = '/';
2321 if (build_dir)
2323 /* try as a dll */
2324 ptr = file + pos;
2325 namelen = len + 1;
2326 file[pos + len + 1] = 0;
2327 if (namelen > 4 && !memcmp( ptr + namelen - 4, ".dll", 4 )) namelen -= 4;
2328 ptr = prepend( ptr, ptr, namelen );
2329 ptr = prepend( ptr, "/dlls", sizeof("/dlls") - 1 );
2330 ptr = prepend( ptr, build_dir, strlen(build_dir) );
2331 status = open_builtin_file( ptr, pwm, module, image_info, st, so_name );
2332 if (status != STATUS_DLL_NOT_FOUND) goto done;
2334 /* now as a program */
2335 ptr = file + pos;
2336 namelen = len + 1;
2337 file[pos + len + 1] = 0;
2338 if (namelen > 4 && !memcmp( ptr + namelen - 4, ".exe", 4 )) namelen -= 4;
2339 ptr = prepend( ptr, ptr, namelen );
2340 ptr = prepend( ptr, "/programs", sizeof("/programs") - 1 );
2341 ptr = prepend( ptr, build_dir, strlen(build_dir) );
2342 status = open_builtin_file( ptr, pwm, module, image_info, st, so_name );
2343 if (status != STATUS_DLL_NOT_FOUND) goto done;
2346 for (i = 0; (path = wine_dll_enum_load_path( i )); i++)
2348 file[pos + len + 1] = 0;
2349 ptr = prepend( file + pos, path, strlen(path) );
2350 status = open_builtin_file( ptr, pwm, module, image_info, st, so_name );
2351 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2352 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2355 if (found_image) status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2356 WARN( "cannot find builtin library for %s\n", debugstr_w(name) );
2358 done:
2359 RtlFreeHeap( GetProcessHeap(), 0, file );
2360 return status;
2364 /***********************************************************************
2365 * load_builtin_dll
2367 static NTSTATUS load_builtin_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, BOOL has_file,
2368 DWORD flags, WINE_MODREF** pwm )
2370 char error[256];
2371 const WCHAR *name, *p;
2372 void *handle;
2373 struct builtin_load_info info, *prev_info;
2375 /* Fix the name in case we have a full path and extension */
2376 name = nt_name->Buffer;
2377 if ((p = strrchrW( name, '\\' ))) name = p + 1;
2378 if ((p = strrchrW( name, '/' ))) name = p + 1;
2380 /* load_library will modify info.status. Note also that load_library can be
2381 * called several times, if the .so file we're loading has dependencies.
2382 * info.status will gather all the errors we may get while loading all these
2383 * libraries
2385 info.load_path = load_path;
2386 info.filename = NULL;
2387 info.status = STATUS_SUCCESS;
2388 info.wm = NULL;
2390 if (has_file) /* we have a real file, try to load it */
2392 ANSI_STRING unix_name;
2394 TRACE("Trying built-in %s\n", debugstr_us(nt_name));
2396 if (wine_nt_to_unix_file_name( nt_name, &unix_name, FILE_OPEN, FALSE ))
2397 return STATUS_DLL_NOT_FOUND;
2398 prev_info = builtin_load_info;
2399 info.filename = nt_name;
2400 builtin_load_info = &info;
2401 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
2402 builtin_load_info = prev_info;
2403 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
2404 if (!handle)
2406 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_us(nt_name), error );
2407 return STATUS_INVALID_IMAGE_FORMAT;
2410 else
2412 NTSTATUS status;
2413 void *module = NULL;
2414 pe_image_info_t image_info;
2415 struct stat st;
2416 char *so_name;
2418 TRACE("Trying built-in %s\n", debugstr_w(name));
2420 status = find_builtin_dll( name, pwm, &module, &image_info, &st, &so_name );
2421 if (status) return status;
2423 if (*pwm)
2425 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2426 TRACE( "Found %s for %s at %p, count=%d\n",
2427 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(name),
2428 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2429 return STATUS_SUCCESS;
2431 if (module)
2433 TRACE( "loading %s from PE builtin %s\n", debugstr_w(name), debugstr_us(nt_name) );
2434 return load_native_dll( load_path, nt_name, module, &image_info, flags, pwm, &st );
2437 TRACE( "loading %s from so lib %s\n", debugstr_w(name), debugstr_a(so_name) );
2438 prev_info = builtin_load_info;
2439 builtin_load_info = &info;
2440 handle = wine_dlopen( so_name, RTLD_NOW, error, sizeof(error) );
2441 builtin_load_info = prev_info;
2442 RtlFreeHeap( GetProcessHeap(), 0, so_name );
2443 if (!handle)
2445 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
2446 return STATUS_PROCEDURE_NOT_FOUND;
2450 if (info.status != STATUS_SUCCESS)
2452 wine_dll_unload( handle );
2453 return info.status;
2456 if (!info.wm)
2458 PLIST_ENTRY mark, entry;
2460 /* The constructor wasn't called, this means the .so is already
2461 * loaded under a different name. Try to find the wm for it. */
2463 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2464 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2466 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2467 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
2469 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2470 TRACE( "Found %s at %p for builtin %s\n",
2471 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress,
2472 debugstr_us(nt_name) );
2473 break;
2476 wine_dll_unload( handle ); /* release the libdl refcount */
2477 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2478 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2480 else
2482 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2483 info.wm->ldr.LoadCount = 1;
2484 info.wm->ldr.SectionHandle = handle;
2487 *pwm = info.wm;
2488 return STATUS_SUCCESS;
2492 /***********************************************************************
2493 * find_actctx_dll
2495 * Find the full path (if any) of the dll from the activation context.
2497 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2499 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2500 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2502 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2503 ACTCTX_SECTION_KEYED_DATA data;
2504 UNICODE_STRING nameW;
2505 NTSTATUS status;
2506 SIZE_T needed, size = 1024;
2507 WCHAR *p;
2509 RtlInitUnicodeString( &nameW, libname );
2510 data.cbSize = sizeof(data);
2511 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2512 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2513 &nameW, &data );
2514 if (status != STATUS_SUCCESS) return status;
2516 for (;;)
2518 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2520 status = STATUS_NO_MEMORY;
2521 goto done;
2523 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2524 AssemblyDetailedInformationInActivationContext,
2525 info, size, &needed );
2526 if (status == STATUS_SUCCESS) break;
2527 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2528 RtlFreeHeap( GetProcessHeap(), 0, info );
2529 size = needed;
2530 /* restart with larger buffer */
2533 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2535 status = STATUS_SXS_KEY_NOT_FOUND;
2536 goto done;
2539 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2541 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2543 p++;
2544 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2546 /* manifest name does not match directory name, so it's not a global
2547 * windows/winsxs manifest; use the manifest directory name instead */
2548 dirlen = p - info->lpAssemblyManifestPath;
2549 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2550 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2552 status = STATUS_NO_MEMORY;
2553 goto done;
2555 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2556 p += dirlen;
2557 strcpyW( p, libname );
2558 goto done;
2562 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2563 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2565 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2567 status = STATUS_NO_MEMORY;
2568 goto done;
2570 strcpyW( p, user_shared_data->NtSystemRoot );
2571 p += strlenW(p);
2572 memcpy( p, winsxsW, sizeof(winsxsW) );
2573 p += ARRAY_SIZE( winsxsW );
2574 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2575 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2576 *p++ = '\\';
2577 strcpyW( p, libname );
2578 done:
2579 RtlFreeHeap( GetProcessHeap(), 0, info );
2580 RtlReleaseActivationContext( data.hActCtx );
2581 return status;
2585 /***********************************************************************
2586 * search_dll_file
2588 * Search for dll in the specified paths.
2590 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name,
2591 WINE_MODREF **pwm, void **module, pe_image_info_t *image_info,
2592 struct stat *st )
2594 WCHAR *name;
2595 BOOL found_image = FALSE;
2596 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2597 ULONG len = strlenW( paths );
2599 if (len < strlenW( system_dir )) len = strlenW( system_dir );
2600 len += strlenW( search ) + 2;
2602 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2603 return STATUS_NO_MEMORY;
2605 while (*paths)
2607 LPCWSTR ptr = paths;
2609 while (*ptr && *ptr != ';') ptr++;
2610 len = ptr - paths;
2611 if (*ptr == ';') ptr++;
2612 memcpy( name, paths, len * sizeof(WCHAR) );
2613 if (len && name[len - 1] != '\\') name[len++] = '\\';
2614 strcpyW( name + len, search );
2616 nt_name->Buffer = NULL;
2617 if ((status = RtlDosPathNameToNtPathName_U_WithStatus( name, nt_name, NULL, NULL ))) goto done;
2619 status = open_dll_file( nt_name, pwm, module, image_info, st );
2620 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) found_image = TRUE;
2621 else if (status != STATUS_DLL_NOT_FOUND) goto done;
2622 RtlFreeUnicodeString( nt_name );
2623 paths = ptr;
2626 if (!found_image)
2628 /* not found, return file in the system dir to be loaded as builtin */
2629 strcpyW( name, system_dir );
2630 strcatW( name, search );
2631 if (!RtlDosPathNameToNtPathName_U( name, nt_name, NULL, NULL )) status = STATUS_NO_MEMORY;
2633 else status = STATUS_IMAGE_MACHINE_TYPE_MISMATCH;
2635 done:
2636 RtlFreeHeap( GetProcessHeap(), 0, name );
2637 return status;
2641 /***********************************************************************
2642 * find_dll_file
2644 * Find the file (or already loaded module) for a given dll name.
2646 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2647 UNICODE_STRING *nt_name, WINE_MODREF **pwm,
2648 void **module, pe_image_info_t *image_info, struct stat *st )
2650 WCHAR *ext, *dllname;
2651 NTSTATUS status = STATUS_SUCCESS;
2653 /* first append .dll if needed */
2655 *pwm = NULL;
2656 *module = NULL;
2657 dllname = NULL;
2658 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2660 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2661 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2662 return STATUS_NO_MEMORY;
2663 strcpyW( dllname, libname );
2664 strcatW( dllname, dllW );
2665 libname = dllname;
2668 nt_name->Buffer = NULL;
2670 if (!contains_path( libname ))
2672 WCHAR *fullname = NULL;
2674 if ((*pwm = find_basename_module( libname )) != NULL) goto done;
2676 status = find_actctx_dll( libname, &fullname );
2677 if (status == STATUS_SUCCESS)
2679 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2680 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2681 libname = dllname = fullname;
2683 else if (status != STATUS_SXS_KEY_NOT_FOUND) goto done;
2686 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2687 status = search_dll_file( load_path, libname, nt_name, pwm, module, image_info, st );
2688 else if (!(status = RtlDosPathNameToNtPathName_U_WithStatus( libname, nt_name, NULL, NULL )))
2689 status = open_dll_file( nt_name, pwm, module, image_info, st );
2691 if (status == STATUS_IMAGE_MACHINE_TYPE_MISMATCH) status = STATUS_INVALID_IMAGE_FORMAT;
2693 done:
2694 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2695 return status;
2699 /***********************************************************************
2700 * load_dll (internal)
2702 * Load a PE style module according to the load order.
2703 * The loader_section must be locked while calling this function.
2705 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2707 enum loadorder loadorder;
2708 WINE_MODREF *main_exe;
2709 UNICODE_STRING nt_name;
2710 struct stat st;
2711 void *module;
2712 pe_image_info_t image_info;
2713 NTSTATUS nts;
2715 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2717 nts = find_dll_file( load_path, libname, &nt_name, pwm, &module, &image_info, &st );
2719 if (*pwm) /* found already loaded module */
2721 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2723 TRACE("Found %s for %s at %p, count=%d\n",
2724 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2725 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2726 RtlFreeUnicodeString( &nt_name );
2727 return STATUS_SUCCESS;
2730 if (nts && nts != STATUS_DLL_NOT_FOUND && nts != STATUS_INVALID_IMAGE_NOT_MZ) goto done;
2732 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2733 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, &nt_name );
2735 switch (nts)
2737 case STATUS_INVALID_IMAGE_NOT_MZ: /* not in PE format, maybe it's a .so file */
2738 switch (loadorder)
2740 case LO_NATIVE:
2741 case LO_NATIVE_BUILTIN:
2742 case LO_BUILTIN:
2743 case LO_BUILTIN_NATIVE:
2744 case LO_DEFAULT:
2745 if (!load_builtin_dll( load_path, &nt_name, TRUE, flags, pwm )) nts = STATUS_SUCCESS;
2746 break;
2747 default:
2748 nts = STATUS_DLL_NOT_FOUND;
2749 break;
2751 break;
2753 case STATUS_SUCCESS: /* valid PE file */
2754 if (image_info.image_flags & IMAGE_FLAGS_WineBuiltin)
2756 NtUnmapViewOfSection( NtCurrentProcess(), module );
2757 switch (loadorder)
2759 case LO_NATIVE_BUILTIN:
2760 case LO_BUILTIN:
2761 case LO_BUILTIN_NATIVE:
2762 case LO_DEFAULT:
2763 nts = load_builtin_dll( load_path, &nt_name, FALSE, flags, pwm );
2764 break;
2765 default:
2766 nts = STATUS_DLL_NOT_FOUND;
2767 break;
2769 break;
2771 if (!(image_info.image_flags & IMAGE_FLAGS_WineFakeDll))
2773 switch (loadorder)
2775 case LO_NATIVE:
2776 case LO_NATIVE_BUILTIN:
2777 nts = load_native_dll( load_path, &nt_name, module, &image_info, flags, pwm, &st );
2778 module = NULL;
2779 break;
2780 case LO_BUILTIN:
2781 nts = load_builtin_dll( load_path, &nt_name, FALSE, flags, pwm );
2782 break;
2783 case LO_BUILTIN_NATIVE:
2784 case LO_DEFAULT:
2785 nts = load_builtin_dll( load_path, &nt_name, FALSE, flags, pwm );
2786 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2787 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2789 /* stub-only dll, try native */
2790 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_us(&nt_name) );
2791 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2792 nts = STATUS_DLL_NOT_FOUND;
2794 if (nts == STATUS_DLL_NOT_FOUND)
2796 nts = load_native_dll( load_path, &nt_name, module, &image_info, flags, pwm, &st );
2797 module = NULL;
2799 break;
2800 default:
2801 nts = STATUS_DLL_NOT_FOUND;
2802 break;
2804 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2805 break;
2807 TRACE( "%s is a fake Wine dll\n", debugstr_us(&nt_name) );
2808 NtUnmapViewOfSection( NtCurrentProcess(), module );
2809 /* fall through */
2811 case STATUS_DLL_NOT_FOUND: /* no file found, try builtin */
2812 switch (loadorder)
2814 case LO_NATIVE_BUILTIN:
2815 case LO_BUILTIN:
2816 case LO_BUILTIN_NATIVE:
2817 case LO_DEFAULT:
2818 nts = load_builtin_dll( load_path, &nt_name, FALSE, flags, pwm );
2819 break;
2820 default:
2821 nts = STATUS_DLL_NOT_FOUND;
2822 break;
2824 break;
2827 done:
2828 if (nts == STATUS_SUCCESS)
2829 TRACE("Loaded module %s at %p\n", debugstr_us(&nt_name), (*pwm)->ldr.BaseAddress);
2830 else
2831 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2833 RtlFreeUnicodeString( &nt_name );
2834 return nts;
2837 /******************************************************************
2838 * LdrLoadDll (NTDLL.@)
2840 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2841 const UNICODE_STRING *libname, HMODULE* hModule)
2843 WINE_MODREF *wm;
2844 NTSTATUS nts;
2846 RtlEnterCriticalSection( &loader_section );
2848 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2849 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2851 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2853 nts = process_attach( wm, NULL );
2854 if (nts != STATUS_SUCCESS)
2856 LdrUnloadDll(wm->ldr.BaseAddress);
2857 wm = NULL;
2860 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2862 RtlLeaveCriticalSection( &loader_section );
2863 return nts;
2867 /******************************************************************
2868 * LdrGetDllHandle (NTDLL.@)
2870 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2872 NTSTATUS status;
2873 UNICODE_STRING nt_name;
2874 WINE_MODREF *wm;
2875 void *module;
2876 pe_image_info_t image_info;
2877 struct stat st;
2879 RtlEnterCriticalSection( &loader_section );
2881 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2883 status = find_dll_file( load_path, name->Buffer, &nt_name, &wm, &module, &image_info, &st );
2885 if (wm) *base = wm->ldr.BaseAddress;
2886 else
2888 if (status == STATUS_SUCCESS) NtUnmapViewOfSection( NtCurrentProcess(), module );
2889 status = STATUS_DLL_NOT_FOUND;
2891 RtlFreeUnicodeString( &nt_name );
2893 RtlLeaveCriticalSection( &loader_section );
2894 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2895 return status;
2899 /******************************************************************
2900 * LdrAddRefDll (NTDLL.@)
2902 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2904 NTSTATUS ret = STATUS_SUCCESS;
2905 WINE_MODREF *wm;
2907 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2909 RtlEnterCriticalSection( &loader_section );
2911 if ((wm = get_modref( module )))
2913 if (flags & LDR_ADDREF_DLL_PIN)
2914 wm->ldr.LoadCount = -1;
2915 else
2916 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2917 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2919 else ret = STATUS_INVALID_PARAMETER;
2921 RtlLeaveCriticalSection( &loader_section );
2922 return ret;
2926 /***********************************************************************
2927 * LdrProcessRelocationBlock (NTDLL.@)
2929 * Apply relocations to a given page of a mapped PE image.
2931 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2932 USHORT *relocs, INT_PTR delta )
2934 while (count--)
2936 USHORT offset = *relocs & 0xfff;
2937 int type = *relocs >> 12;
2938 switch(type)
2940 case IMAGE_REL_BASED_ABSOLUTE:
2941 break;
2942 case IMAGE_REL_BASED_HIGH:
2943 *(short *)((char *)page + offset) += HIWORD(delta);
2944 break;
2945 case IMAGE_REL_BASED_LOW:
2946 *(short *)((char *)page + offset) += LOWORD(delta);
2947 break;
2948 case IMAGE_REL_BASED_HIGHLOW:
2949 *(int *)((char *)page + offset) += delta;
2950 break;
2951 #ifdef _WIN64
2952 case IMAGE_REL_BASED_DIR64:
2953 *(INT_PTR *)((char *)page + offset) += delta;
2954 break;
2955 #elif defined(__arm__)
2956 case IMAGE_REL_BASED_THUMB_MOV32:
2958 DWORD inst = *(INT_PTR *)((char *)page + offset);
2959 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2960 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2961 DWORD hi_delta;
2963 if ((inst & 0x8000fbf0) != 0x0000f240)
2964 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2966 imm16 += LOWORD(delta);
2967 hi_delta = HIWORD(delta) + HIWORD(imm16);
2968 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2969 ((imm16 >> 12) & 0x000f) +
2970 ((imm16 << 20) & 0x70000000) +
2971 ((imm16 << 16) & 0xff0000);
2973 if (hi_delta != 0)
2975 inst = *(INT_PTR *)((char *)page + offset + 4);
2976 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2977 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2979 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2980 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2982 imm16 += hi_delta;
2983 if (imm16 > 0xffff)
2984 ERR("resulting immediate value won't fit: %08x\n", imm16);
2985 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2986 ((imm16 >> 1) & 0x0400) +
2987 ((imm16 >> 12) & 0x000f) +
2988 ((imm16 << 20) & 0x70000000) +
2989 ((imm16 << 16) & 0xff0000);
2992 break;
2993 #endif
2994 default:
2995 FIXME("Unknown/unsupported fixup type %x.\n", type);
2996 return NULL;
2998 relocs++;
3000 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
3004 /******************************************************************
3005 * LdrQueryProcessModuleInformation
3008 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
3009 ULONG buf_size, ULONG* req_size)
3011 SYSTEM_MODULE* sm = &smi->Modules[0];
3012 ULONG size = sizeof(ULONG);
3013 NTSTATUS nts = STATUS_SUCCESS;
3014 ANSI_STRING str;
3015 char* ptr;
3016 PLIST_ENTRY mark, entry;
3017 PLDR_MODULE mod;
3018 WORD id = 0;
3020 smi->ModulesCount = 0;
3022 RtlEnterCriticalSection( &loader_section );
3023 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3024 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3026 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
3027 size += sizeof(*sm);
3028 if (size <= buf_size)
3030 sm->Reserved1 = 0; /* FIXME */
3031 sm->Reserved2 = 0; /* FIXME */
3032 sm->ImageBaseAddress = mod->BaseAddress;
3033 sm->ImageSize = mod->SizeOfImage;
3034 sm->Flags = mod->Flags;
3035 sm->Id = id++;
3036 sm->Rank = 0; /* FIXME */
3037 sm->Unknown = 0; /* FIXME */
3038 str.Length = 0;
3039 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
3040 str.Buffer = (char*)sm->Name;
3041 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
3042 ptr = strrchr(str.Buffer, '\\');
3043 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
3045 smi->ModulesCount++;
3046 sm++;
3048 else nts = STATUS_INFO_LENGTH_MISMATCH;
3050 RtlLeaveCriticalSection( &loader_section );
3052 if (req_size) *req_size = size;
3054 return nts;
3058 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
3060 NTSTATUS status;
3061 UNICODE_STRING str;
3062 ULONG size;
3063 WCHAR buffer[64];
3064 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3066 RtlInitUnicodeString( &str, name );
3068 size = sizeof(buffer) - sizeof(WCHAR);
3069 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
3070 return status;
3072 if (info->Type != REG_DWORD)
3074 buffer[size / sizeof(WCHAR)] = 0;
3075 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
3077 else memcpy( value, info->Data, sizeof(*value) );
3078 return status;
3081 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
3082 void *data, ULONG in_size, ULONG *out_size )
3084 NTSTATUS status;
3085 UNICODE_STRING str;
3086 ULONG size;
3087 char *buffer;
3088 KEY_VALUE_PARTIAL_INFORMATION *info;
3089 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
3091 RtlInitUnicodeString( &str, name );
3093 size = info_size + in_size;
3094 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
3095 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
3096 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
3097 if (!status || status == STATUS_BUFFER_OVERFLOW)
3099 if (out_size) *out_size = info->DataLength;
3100 if (data && !status) memcpy( data, info->Data, info->DataLength );
3102 RtlFreeHeap( GetProcessHeap(), 0, buffer );
3103 return status;
3107 /******************************************************************
3108 * LdrQueryImageFileExecutionOptions (NTDLL.@)
3110 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
3111 void *data, ULONG in_size, ULONG *out_size )
3113 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
3114 'S','o','f','t','w','a','r','e','\\',
3115 'M','i','c','r','o','s','o','f','t','\\',
3116 'W','i','n','d','o','w','s',' ','N','T','\\',
3117 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
3118 'I','m','a','g','e',' ','F','i','l','e',' ',
3119 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
3120 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
3121 OBJECT_ATTRIBUTES attr;
3122 UNICODE_STRING name_str;
3123 HANDLE hkey;
3124 NTSTATUS status;
3125 ULONG len;
3126 WCHAR *p;
3128 attr.Length = sizeof(attr);
3129 attr.RootDirectory = 0;
3130 attr.ObjectName = &name_str;
3131 attr.Attributes = OBJ_CASE_INSENSITIVE;
3132 attr.SecurityDescriptor = NULL;
3133 attr.SecurityQualityOfService = NULL;
3135 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
3136 else p = key->Buffer;
3137 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
3138 name_str.Buffer = path;
3139 name_str.Length = sizeof(optionsW) + len;
3140 name_str.MaximumLength = name_str.Length;
3141 memcpy( path, optionsW, sizeof(optionsW) );
3142 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
3143 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
3145 if (type == REG_DWORD)
3147 if (out_size) *out_size = sizeof(ULONG);
3148 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
3149 else status = STATUS_BUFFER_OVERFLOW;
3151 else status = query_string_option( hkey, value, type, data, in_size, out_size );
3153 NtClose( hkey );
3154 return status;
3158 /******************************************************************
3159 * RtlDllShutdownInProgress (NTDLL.@)
3161 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
3163 return process_detaching;
3166 /****************************************************************************
3167 * LdrResolveDelayLoadedAPI (NTDLL.@)
3169 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
3170 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
3171 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
3172 IMAGE_THUNK_DATA* addr, ULONG flags )
3174 IMAGE_THUNK_DATA *pIAT, *pINT;
3175 DELAYLOAD_INFO delayinfo;
3176 UNICODE_STRING mod;
3177 const CHAR* name;
3178 HMODULE *phmod;
3179 NTSTATUS nts;
3180 FARPROC fp;
3181 DWORD id;
3183 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
3185 phmod = get_rva(base, desc->ModuleHandleRVA);
3186 pIAT = get_rva(base, desc->ImportAddressTableRVA);
3187 pINT = get_rva(base, desc->ImportNameTableRVA);
3188 name = get_rva(base, desc->DllNameRVA);
3189 id = addr - pIAT;
3191 if (!*phmod)
3193 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
3195 nts = STATUS_NO_MEMORY;
3196 goto fail;
3198 nts = LdrLoadDll(NULL, 0, &mod, phmod);
3199 RtlFreeUnicodeString(&mod);
3200 if (nts) goto fail;
3203 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3204 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
3205 else
3207 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3208 ANSI_STRING fnc;
3210 RtlInitAnsiString(&fnc, (char*)iibn->Name);
3211 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
3213 if (!nts)
3215 pIAT[id].u1.Function = (ULONG_PTR)fp;
3216 return fp;
3219 fail:
3220 delayinfo.Size = sizeof(delayinfo);
3221 delayinfo.DelayloadDescriptor = desc;
3222 delayinfo.ThunkAddress = addr;
3223 delayinfo.TargetDllName = name;
3224 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
3225 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
3226 delayinfo.TargetModuleBase = *phmod;
3227 delayinfo.Unused = NULL;
3228 delayinfo.LastError = nts;
3230 if (dllhook)
3231 return dllhook(4, &delayinfo);
3233 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3235 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3236 return syshook(name, (const char *)ord);
3238 else
3240 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3241 return syshook(name, (const char *)iibn->Name);
3245 /******************************************************************
3246 * LdrShutdownProcess (NTDLL.@)
3249 void WINAPI LdrShutdownProcess(void)
3251 TRACE("()\n");
3252 process_detaching = TRUE;
3253 process_detach();
3257 /******************************************************************
3258 * RtlExitUserProcess (NTDLL.@)
3260 void WINAPI RtlExitUserProcess( DWORD status )
3262 RtlEnterCriticalSection( &loader_section );
3263 RtlAcquirePebLock();
3264 NtTerminateProcess( 0, status );
3265 LdrShutdownProcess();
3266 NtTerminateProcess( GetCurrentProcess(), status );
3267 exit( get_unix_exit_code( status ));
3270 /******************************************************************
3271 * LdrShutdownThread (NTDLL.@)
3274 void WINAPI LdrShutdownThread(void)
3276 PLIST_ENTRY mark, entry;
3277 PLDR_MODULE mod;
3278 UINT i;
3279 void **pointers;
3281 TRACE("()\n");
3283 /* don't do any detach calls if process is exiting */
3284 if (process_detaching) return;
3286 RtlEnterCriticalSection( &loader_section );
3288 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3289 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3291 mod = CONTAINING_RECORD(entry, LDR_MODULE,
3292 InInitializationOrderModuleList);
3293 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3294 continue;
3295 if ( mod->Flags & LDR_NO_DLL_CALLS )
3296 continue;
3298 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3299 DLL_THREAD_DETACH, NULL );
3302 RtlAcquirePebLock();
3303 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3304 RtlReleasePebLock();
3306 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3308 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3309 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3311 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
3312 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3313 RtlLeaveCriticalSection( &loader_section );
3317 /***********************************************************************
3318 * free_modref
3321 static void free_modref( WINE_MODREF *wm )
3323 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
3324 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
3325 if (wm->ldr.InInitializationOrderModuleList.Flink)
3326 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
3328 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3329 if (!TRACE_ON(module))
3330 TRACE_(loaddll)("Unloaded module %s : %s\n",
3331 debugstr_w(wm->ldr.FullDllName.Buffer),
3332 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3334 SERVER_START_REQ( unload_dll )
3336 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
3337 wine_server_call( req );
3339 SERVER_END_REQ;
3341 free_tls_slot( &wm->ldr );
3342 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3343 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
3344 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
3345 if (cached_modref == wm) cached_modref = NULL;
3346 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3347 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
3348 RtlFreeHeap( GetProcessHeap(), 0, wm );
3351 /***********************************************************************
3352 * MODULE_FlushModrefs
3354 * Remove all unused modrefs and call the internal unloading routines
3355 * for the library type.
3357 * The loader_section must be locked while calling this function.
3359 static void MODULE_FlushModrefs(void)
3361 PLIST_ENTRY mark, entry, prev;
3362 PLDR_MODULE mod;
3363 WINE_MODREF*wm;
3365 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3366 for (entry = mark->Blink; entry != mark; entry = prev)
3368 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
3369 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3370 prev = entry->Blink;
3371 if (!mod->LoadCount) free_modref( wm );
3374 /* check load order list too for modules that haven't been initialized yet */
3375 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3376 for (entry = mark->Blink; entry != mark; entry = prev)
3378 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
3379 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3380 prev = entry->Blink;
3381 if (!mod->LoadCount) free_modref( wm );
3385 /***********************************************************************
3386 * MODULE_DecRefCount
3388 * The loader_section must be locked while calling this function.
3390 static void MODULE_DecRefCount( WINE_MODREF *wm )
3392 int i;
3394 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3395 return;
3397 if ( wm->ldr.LoadCount <= 0 )
3398 return;
3400 --wm->ldr.LoadCount;
3401 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3403 if ( wm->ldr.LoadCount == 0 )
3405 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3407 for ( i = 0; i < wm->nDeps; i++ )
3408 if ( wm->deps[i] )
3409 MODULE_DecRefCount( wm->deps[i] );
3411 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3413 module_push_unload_trace( &wm->ldr );
3417 /******************************************************************
3418 * LdrUnloadDll (NTDLL.@)
3422 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3424 WINE_MODREF *wm;
3425 NTSTATUS retv = STATUS_SUCCESS;
3427 if (process_detaching) return retv;
3429 TRACE("(%p)\n", hModule);
3431 RtlEnterCriticalSection( &loader_section );
3433 free_lib_count++;
3434 if ((wm = get_modref( hModule )) != NULL)
3436 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3438 /* Recursively decrement reference counts */
3439 MODULE_DecRefCount( wm );
3441 /* Call process detach notifications */
3442 if ( free_lib_count <= 1 )
3444 process_detach();
3445 MODULE_FlushModrefs();
3448 TRACE("END\n");
3450 else
3451 retv = STATUS_DLL_NOT_FOUND;
3453 free_lib_count--;
3455 RtlLeaveCriticalSection( &loader_section );
3457 return retv;
3460 /***********************************************************************
3461 * RtlImageNtHeader (NTDLL.@)
3463 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3465 IMAGE_NT_HEADERS *ret;
3467 __TRY
3469 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3471 ret = NULL;
3472 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3474 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3475 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3478 __EXCEPT_PAGE_FAULT
3480 return NULL;
3482 __ENDTRY
3483 return ret;
3487 /******************************************************************
3488 * LdrInitializeThunk (NTDLL.@)
3490 * Attach to all the loaded dlls.
3491 * If this is the first time, perform the full process initialization.
3493 void WINAPI LdrInitializeThunk( CONTEXT *context, void **entry, ULONG_PTR unknown3, ULONG_PTR unknown4 )
3495 NTSTATUS status;
3496 WINE_MODREF *wm;
3497 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3499 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3501 if (process_detaching) return;
3503 RtlEnterCriticalSection( &loader_section );
3505 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3506 assert( wm );
3508 if (!imports_fixup_done)
3510 actctx_init();
3511 if (wm->ldr.Flags & LDR_COR_ILONLY)
3512 status = fixup_imports_ilonly( wm, load_path, entry );
3513 else
3514 status = fixup_imports( wm, load_path );
3516 if (status)
3518 ERR( "Importing dlls for %s failed, status %x\n",
3519 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3520 NtTerminateProcess( GetCurrentProcess(), status );
3522 imports_fixup_done = TRUE;
3525 RtlAcquirePebLock();
3526 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3527 RtlReleasePebLock();
3529 if (!(wm->ldr.Flags & LDR_PROCESS_ATTACHED)) /* first time around */
3531 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3533 ERR( "TLS init failed when loading %s, status %x\n",
3534 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3535 NtTerminateProcess( GetCurrentProcess(), status );
3537 if ((status = process_attach( wm, context )) != STATUS_SUCCESS)
3539 if (last_failed_modref)
3540 ERR( "%s failed to initialize, aborting\n",
3541 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3542 ERR( "Initializing dlls for %s failed, status %x\n",
3543 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3544 NtTerminateProcess( GetCurrentProcess(), status );
3546 attach_implicitly_loaded_dlls( context );
3547 virtual_release_address_space();
3549 else
3551 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3552 NtTerminateThread( GetCurrentThread(), status );
3553 thread_attach();
3556 RtlLeaveCriticalSection( &loader_section );
3560 /***********************************************************************
3561 * load_global_options
3563 static void load_global_options(void)
3565 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3566 'S','y','s','t','e','m','\\',
3567 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3568 'C','o','n','t','r','o','l','\\',
3569 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3570 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3571 static const WCHAR critsectW[] = {'C','r','i','t','i','c','a','l','S','e','c','t','i','o','n','T','i','m','e','o','u','t',0};
3572 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3573 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3574 static const WCHAR decommittotalW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','T','o','t','a','l','F','r','e','e','T','h','r','e','s','h','o','l','d',0};
3575 static const WCHAR decommitfreeW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','F','r','e','e','B','l','o','c','k','T','h','r','e','s','h','o','l','d',0};
3577 OBJECT_ATTRIBUTES attr;
3578 UNICODE_STRING name_str;
3579 HANDLE hkey;
3580 ULONG value;
3582 attr.Length = sizeof(attr);
3583 attr.RootDirectory = 0;
3584 attr.ObjectName = &name_str;
3585 attr.Attributes = OBJ_CASE_INSENSITIVE;
3586 attr.SecurityDescriptor = NULL;
3587 attr.SecurityQualityOfService = NULL;
3588 RtlInitUnicodeString( &name_str, sessionW );
3590 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3592 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3594 query_dword_option( hkey, critsectW, &value );
3595 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3597 query_dword_option( hkey, heapresW, &value );
3598 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3600 query_dword_option( hkey, heapcommitW, &value );
3601 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3603 query_dword_option( hkey, decommittotalW, &value );
3604 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3606 query_dword_option( hkey, decommitfreeW, &value );
3607 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3609 NtClose( hkey );
3613 /***********************************************************************
3614 * RtlImageDirectoryEntryToData (NTDLL.@)
3616 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3618 const IMAGE_NT_HEADERS *nt;
3619 DWORD addr;
3621 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
3622 module = (HMODULE)((ULONG_PTR)module & ~3);
3623 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3624 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3626 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3628 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3629 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3630 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3631 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3633 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3635 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3637 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3638 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3639 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3640 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3642 else return NULL;
3644 /* not mapped as image, need to find the section containing the virtual address */
3645 return RtlImageRvaToVa( nt, module, addr, NULL );
3649 /***********************************************************************
3650 * RtlImageRvaToSection (NTDLL.@)
3652 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3653 HMODULE module, DWORD rva )
3655 int i;
3656 const IMAGE_SECTION_HEADER *sec;
3658 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3659 nt->FileHeader.SizeOfOptionalHeader);
3660 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3662 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3663 return (PIMAGE_SECTION_HEADER)sec;
3665 return NULL;
3669 /***********************************************************************
3670 * RtlImageRvaToVa (NTDLL.@)
3672 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3673 DWORD rva, IMAGE_SECTION_HEADER **section )
3675 IMAGE_SECTION_HEADER *sec;
3677 if (section && *section) /* try this section first */
3679 sec = *section;
3680 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3681 goto found;
3683 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3684 found:
3685 if (section) *section = sec;
3686 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3690 /***********************************************************************
3691 * RtlPcToFileHeader (NTDLL.@)
3693 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3695 LDR_MODULE *module;
3696 PVOID ret = NULL;
3698 RtlEnterCriticalSection( &loader_section );
3699 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3700 RtlLeaveCriticalSection( &loader_section );
3701 *address = ret;
3702 return ret;
3706 /***********************************************************************
3707 * NtLoadDriver (NTDLL.@)
3708 * ZwLoadDriver (NTDLL.@)
3710 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3712 FIXME("(%p), stub!\n",DriverServiceName);
3713 return STATUS_NOT_IMPLEMENTED;
3717 /***********************************************************************
3718 * NtUnloadDriver (NTDLL.@)
3719 * ZwUnloadDriver (NTDLL.@)
3721 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3723 FIXME("(%p), stub!\n",DriverServiceName);
3724 return STATUS_NOT_IMPLEMENTED;
3728 /******************************************************************
3729 * DllMain (NTDLL.@)
3731 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3733 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3734 return TRUE;
3738 /***********************************************************************
3739 * __wine_process_init
3741 void __wine_process_init(void)
3743 static const WCHAR kernel32W[] = {'C',':','\\','w','i','n','d','o','w','s','\\',
3744 's','y','s','t','e','m','3','2','\\',
3745 'k','e','r','n','e','l','3','2','.','d','l','l',0};
3746 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3748 WINE_MODREF *wm;
3749 NTSTATUS status;
3750 ANSI_STRING func_name;
3751 UNICODE_STRING nt_name;
3752 void * (CDECL *init_func)(void);
3754 thread_init();
3756 /* retrieve current umask */
3757 FILE_umask = umask(0777);
3758 umask( FILE_umask );
3760 load_global_options();
3762 /* setup the load callback and create ntdll modref */
3763 wine_dll_set_callback( load_builtin_callback );
3765 RtlInitUnicodeString( &nt_name, kernel32W );
3766 if ((status = load_builtin_dll( NULL, &nt_name, FALSE, 0, &wm )) != STATUS_SUCCESS)
3768 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3769 exit(1);
3771 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3772 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3773 0, (void **)&init_func )) != STATUS_SUCCESS)
3775 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3776 exit(1);
3779 kernel32_start_process = init_func();
3781 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3782 assert( wm );
3783 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3785 MESSAGE( "wine: %s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3786 exit(1);
3789 NtCurrentTeb()->Peb->LoaderLock = &loader_section;
3790 update_user_process_params( &wm->ldr.FullDllName );
3791 version_init( wm->ldr.FullDllName.Buffer );
3792 virtual_set_large_address_space();
3794 LdrQueryImageFileExecutionOptions( &wm->ldr.FullDllName, globalflagW, REG_DWORD,
3795 &NtCurrentTeb()->Peb->NtGlobalFlag, sizeof(DWORD), NULL );
3796 heap_set_debug_flags( GetProcessHeap() );
3798 /* the main exe needs to be the first in the load order list */
3799 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3800 InsertHeadList( &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3801 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3802 InsertHeadList( &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3804 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL )) != STATUS_SUCCESS)
3806 ERR( "Main exe initialization for %s failed, status %x\n",
3807 debugstr_w(wm->ldr.FullDllName.Buffer), status );
3808 NtTerminateProcess( GetCurrentProcess(), status );
3810 server_init_process_done();