ntdll: Remove no longer used parameter from find_fileid_module().
[wine.git] / dlls / ntdll / loader.c
blobe7a9c2cadfa1de5dbdf8270728fb22b735de37f8
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++;
163 /*************************************************************************
164 * call_dll_entry_point
166 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
167 * their entry point, so we need a small asm wrapper. Testing indicates
168 * that only modifying esi leads to a crash, so use this one to backup
169 * ebp while running the dll entry proc.
171 #ifdef __i386__
172 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
173 __ASM_GLOBAL_FUNC(call_dll_entry_point,
174 "pushl %ebp\n\t"
175 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
176 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
177 "movl %esp,%ebp\n\t"
178 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
179 "pushl %ebx\n\t"
180 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
181 "pushl %esi\n\t"
182 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
183 "pushl %edi\n\t"
184 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
185 "movl %ebp,%esi\n\t"
186 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
187 "pushl 20(%ebp)\n\t"
188 "pushl 16(%ebp)\n\t"
189 "pushl 12(%ebp)\n\t"
190 "movl 8(%ebp),%eax\n\t"
191 "call *%eax\n\t"
192 "movl %esi,%ebp\n\t"
193 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
194 "leal -12(%ebp),%esp\n\t"
195 "popl %edi\n\t"
196 __ASM_CFI(".cfi_same_value %edi\n\t")
197 "popl %esi\n\t"
198 __ASM_CFI(".cfi_same_value %esi\n\t")
199 "popl %ebx\n\t"
200 __ASM_CFI(".cfi_same_value %ebx\n\t")
201 "popl %ebp\n\t"
202 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
203 __ASM_CFI(".cfi_same_value %ebp\n\t")
204 "ret" )
205 #else /* __i386__ */
206 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
207 UINT reason, void *reserved )
209 return proc( module, reason, reserved );
211 #endif /* __i386__ */
214 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
215 /*************************************************************************
216 * stub_entry_point
218 * Entry point for stub functions.
220 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
222 EXCEPTION_RECORD rec;
224 rec.ExceptionCode = EXCEPTION_WINE_STUB;
225 rec.ExceptionFlags = EH_NONCONTINUABLE;
226 rec.ExceptionRecord = NULL;
227 rec.ExceptionAddress = ret_addr;
228 rec.NumberParameters = 2;
229 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
230 rec.ExceptionInformation[1] = (ULONG_PTR)name;
231 for (;;) RtlRaiseException( &rec );
235 #include "pshpack1.h"
236 #ifdef __i386__
237 struct stub
239 BYTE pushl1; /* pushl $name */
240 const char *name;
241 BYTE pushl2; /* pushl $dll */
242 const char *dll;
243 BYTE call; /* call stub_entry_point */
244 DWORD entry;
246 #elif defined(__arm__)
247 struct stub
249 DWORD ldr_r0; /* ldr r0, $dll */
250 DWORD ldr_r1; /* ldr r1, $name */
251 DWORD mov_r2_lr; /* mov r2, lr */
252 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
253 const char *dll;
254 const char *name;
255 const void* entry;
257 #elif defined(__aarch64__)
258 struct stub
260 DWORD ldr_x0; /* ldr x0, $dll */
261 DWORD ldr_x1; /* ldr x1, $name */
262 DWORD mov_x2_lr; /* mov x2, lr */
263 DWORD ldr_x16; /* ldr x16, $entry */
264 DWORD br_x16; /* br x16 */
265 const char *dll;
266 const char *name;
267 const void *entry;
269 #else
270 struct stub
272 BYTE movq_rdi[2]; /* movq $dll,%rdi */
273 const char *dll;
274 BYTE movq_rsi[2]; /* movq $name,%rsi */
275 const char *name;
276 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
277 BYTE movq_rax[2]; /* movq $entry, %rax */
278 const void* entry;
279 BYTE jmpq_rax[2]; /* jmp %rax */
281 #endif
282 #include "poppack.h"
284 /*************************************************************************
285 * allocate_stub
287 * Allocate a stub entry point.
289 static ULONG_PTR allocate_stub( const char *dll, const char *name )
291 #define MAX_SIZE 65536
292 static struct stub *stubs;
293 static unsigned int nb_stubs;
294 struct stub *stub;
296 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
298 if (!stubs)
300 SIZE_T size = MAX_SIZE;
301 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
302 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
303 return 0xdeadbeef;
305 stub = &stubs[nb_stubs++];
306 #ifdef __i386__
307 stub->pushl1 = 0x68; /* pushl $name */
308 stub->name = name;
309 stub->pushl2 = 0x68; /* pushl $dll */
310 stub->dll = dll;
311 stub->call = 0xe8; /* call stub_entry_point */
312 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
313 #elif defined(__arm__)
314 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
315 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
316 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
317 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
318 stub->dll = dll;
319 stub->name = name;
320 stub->entry = stub_entry_point;
321 #elif defined(__aarch64__)
322 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
323 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
324 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
325 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
326 stub->br_x16 = 0xd61f0200; /* br x16 */
327 stub->dll = dll;
328 stub->name = name;
329 stub->entry = stub_entry_point;
330 #else
331 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
332 stub->movq_rdi[1] = 0xbf;
333 stub->dll = dll;
334 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
335 stub->movq_rsi[1] = 0xbe;
336 stub->name = name;
337 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
338 stub->movq_rsp_rdx[1] = 0x8b;
339 stub->movq_rsp_rdx[2] = 0x14;
340 stub->movq_rsp_rdx[3] = 0x24;
341 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
342 stub->movq_rax[1] = 0xb8;
343 stub->entry = stub_entry_point;
344 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
345 stub->jmpq_rax[1] = 0xe0;
346 #endif
347 return (ULONG_PTR)stub;
350 #else /* __i386__ */
351 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
352 #endif /* __i386__ */
354 /* call ldr notifications */
355 static void call_ldr_notifications( ULONG reason, LDR_MODULE *module )
357 struct ldr_notification *notify, *notify_next;
358 LDR_DLL_NOTIFICATION_DATA data;
360 data.Loaded.Flags = 0;
361 data.Loaded.FullDllName = &module->FullDllName;
362 data.Loaded.BaseDllName = &module->BaseDllName;
363 data.Loaded.DllBase = module->BaseAddress;
364 data.Loaded.SizeOfImage = module->SizeOfImage;
366 LIST_FOR_EACH_ENTRY_SAFE( notify, notify_next, &ldr_notifications, struct ldr_notification, entry )
368 TRACE_(relay)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
369 notify->callback, reason, &data, notify->context );
371 notify->callback(reason, &data, notify->context);
373 TRACE_(relay)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
374 notify->callback, reason, &data, notify->context );
378 /*************************************************************************
379 * get_modref
381 * Looks for the referenced HMODULE in the current process
382 * The loader_section must be locked while calling this function.
384 static WINE_MODREF *get_modref( HMODULE hmod )
386 PLIST_ENTRY mark, entry;
387 PLDR_MODULE mod;
389 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
391 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
392 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
394 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
395 if (mod->BaseAddress == hmod)
396 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
398 return NULL;
402 /**********************************************************************
403 * find_basename_module
405 * Find a module from its base name.
406 * The loader_section must be locked while calling this function
408 static WINE_MODREF *find_basename_module( LPCWSTR name )
410 PLIST_ENTRY mark, entry;
412 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
413 return cached_modref;
415 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
416 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
418 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
419 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
421 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
422 return cached_modref;
425 return NULL;
429 /**********************************************************************
430 * find_fullname_module
432 * Find a module from its full path name.
433 * The loader_section must be locked while calling this function
435 static WINE_MODREF *find_fullname_module( const UNICODE_STRING *nt_name )
437 PLIST_ENTRY mark, entry;
438 UNICODE_STRING name = *nt_name;
440 if (name.Length <= 4 * sizeof(WCHAR)) return NULL;
441 name.Length -= 4 * sizeof(WCHAR); /* for \??\ prefix */
442 name.Buffer += 4;
444 if (cached_modref && RtlEqualUnicodeString( &name, &cached_modref->ldr.FullDllName, TRUE ))
445 return cached_modref;
447 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
448 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
450 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
451 if (RtlEqualUnicodeString( &name, &mod->FullDllName, TRUE ))
453 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
454 return cached_modref;
457 return NULL;
461 /**********************************************************************
462 * find_fileid_module
464 * Find a module from its file id.
465 * The loader_section must be locked while calling this function
467 static WINE_MODREF *find_fileid_module( struct stat *st )
469 LIST_ENTRY *mark, *entry;
471 if (cached_modref && cached_modref->dev == st->st_dev && cached_modref->ino == st->st_ino)
472 return cached_modref;
474 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
475 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
477 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
478 WINE_MODREF *wm = CONTAINING_RECORD( mod, WINE_MODREF, ldr );
480 if (wm->dev == st->st_dev && wm->ino == st->st_ino)
482 cached_modref = wm;
483 return wm;
486 return NULL;
490 /*************************************************************************
491 * find_forwarded_export
493 * Find the final function pointer for a forwarded function.
494 * The loader_section must be locked while calling this function.
496 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
498 const IMAGE_EXPORT_DIRECTORY *exports;
499 DWORD exp_size;
500 WINE_MODREF *wm;
501 WCHAR mod_name[32];
502 const char *end = strrchr(forward, '.');
503 FARPROC proc = NULL;
505 if (!end) return NULL;
506 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
507 ascii_to_unicode( mod_name, forward, end - forward );
508 mod_name[end - forward] = 0;
509 if (!strchrW( mod_name, '.' ))
511 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
512 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
515 if (!(wm = find_basename_module( mod_name )))
517 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
518 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
519 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
521 if (!imports_fixup_done && current_modref)
523 WINE_MODREF **deps;
524 if (current_modref->alloc_deps)
525 deps = RtlReAllocateHeap( GetProcessHeap(), 0, current_modref->deps,
526 (current_modref->alloc_deps + 1) * sizeof(*deps) );
527 else
528 deps = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps) );
529 if (deps)
531 deps[current_modref->nDeps++] = wm;
532 current_modref->deps = deps;
533 current_modref->alloc_deps++;
536 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
538 LdrUnloadDll( wm->ldr.BaseAddress );
539 wm = NULL;
543 if (!wm)
545 ERR( "module not found for forward '%s' used by %s\n",
546 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
547 return NULL;
550 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
551 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
553 const char *name = end + 1;
554 if (*name == '#') /* ordinal */
555 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
556 else
557 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
560 if (!proc)
562 ERR("function not found for forward '%s' used by %s."
563 " If you are using builtin %s, try using the native one instead.\n",
564 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
565 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
567 return proc;
571 /*************************************************************************
572 * find_ordinal_export
574 * Find an exported function by ordinal.
575 * The exports base must have been subtracted from the ordinal already.
576 * The loader_section must be locked while calling this function.
578 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
579 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
581 FARPROC proc;
582 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
584 if (ordinal >= exports->NumberOfFunctions)
586 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
587 return NULL;
589 if (!functions[ordinal]) return NULL;
591 proc = get_rva( module, functions[ordinal] );
593 /* if the address falls into the export dir, it's a forward */
594 if (((const char *)proc >= (const char *)exports) &&
595 ((const char *)proc < (const char *)exports + exp_size))
596 return find_forwarded_export( module, (const char *)proc, load_path );
598 if (TRACE_ON(snoop))
600 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
601 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
603 if (TRACE_ON(relay))
605 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
606 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
608 return proc;
612 /*************************************************************************
613 * find_named_export
615 * Find an exported function by name.
616 * The loader_section must be locked while calling this function.
618 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
619 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
621 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
622 const DWORD *names = get_rva( module, exports->AddressOfNames );
623 int min = 0, max = exports->NumberOfNames - 1;
625 /* first check the hint */
626 if (hint >= 0 && hint <= max)
628 char *ename = get_rva( module, names[hint] );
629 if (!strcmp( ename, name ))
630 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
633 /* then do a binary search */
634 while (min <= max)
636 int res, pos = (min + max) / 2;
637 char *ename = get_rva( module, names[pos] );
638 if (!(res = strcmp( ename, name )))
639 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
640 if (res > 0) max = pos - 1;
641 else min = pos + 1;
643 return NULL;
648 /*************************************************************************
649 * import_dll
651 * Import the dll specified by the given import descriptor.
652 * The loader_section must be locked while calling this function.
654 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
656 NTSTATUS status;
657 WINE_MODREF *wmImp;
658 HMODULE imp_mod;
659 const IMAGE_EXPORT_DIRECTORY *exports;
660 DWORD exp_size;
661 const IMAGE_THUNK_DATA *import_list;
662 IMAGE_THUNK_DATA *thunk_list;
663 WCHAR buffer[32];
664 const char *name = get_rva( module, descr->Name );
665 DWORD len = strlen(name);
666 PVOID protect_base;
667 SIZE_T protect_size = 0;
668 DWORD protect_old;
670 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
671 if (descr->u.OriginalFirstThunk)
672 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
673 else
674 import_list = thunk_list;
676 if (!import_list->u1.Ordinal)
678 WARN( "Skipping unused import %s\n", name );
679 *pwm = NULL;
680 return TRUE;
683 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
685 if (len * sizeof(WCHAR) < sizeof(buffer))
687 ascii_to_unicode( buffer, name, len );
688 buffer[len] = 0;
689 status = load_dll( load_path, buffer, 0, &wmImp );
691 else /* need to allocate a larger buffer */
693 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
694 if (!ptr) return FALSE;
695 ascii_to_unicode( ptr, name, len );
696 ptr[len] = 0;
697 status = load_dll( load_path, ptr, 0, &wmImp );
698 RtlFreeHeap( GetProcessHeap(), 0, ptr );
701 if (status)
703 if (status == STATUS_DLL_NOT_FOUND)
704 ERR("Library %s (which is needed by %s) not found\n",
705 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
706 else
707 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
708 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
709 return FALSE;
712 /* unprotect the import address table since it can be located in
713 * readonly section */
714 while (import_list[protect_size].u1.Ordinal) protect_size++;
715 protect_base = thunk_list;
716 protect_size *= sizeof(*thunk_list);
717 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
718 &protect_size, PAGE_READWRITE, &protect_old );
720 imp_mod = wmImp->ldr.BaseAddress;
721 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
723 if (!exports)
725 /* set all imported function to deadbeef */
726 while (import_list->u1.Ordinal)
728 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
730 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
731 WARN("No implementation for %s.%d", name, ordinal );
732 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
734 else
736 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
737 WARN("No implementation for %s.%s", name, pe_name->Name );
738 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
740 WARN(" imported from %s, allocating stub %p\n",
741 debugstr_w(current_modref->ldr.FullDllName.Buffer),
742 (void *)thunk_list->u1.Function );
743 import_list++;
744 thunk_list++;
746 goto done;
749 while (import_list->u1.Ordinal)
751 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
753 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
755 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
756 ordinal - exports->Base, load_path );
757 if (!thunk_list->u1.Function)
759 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
760 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
761 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
762 (void *)thunk_list->u1.Function );
764 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
766 else /* import by name */
768 IMAGE_IMPORT_BY_NAME *pe_name;
769 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
770 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
771 (const char*)pe_name->Name,
772 pe_name->Hint, load_path );
773 if (!thunk_list->u1.Function)
775 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
776 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
777 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
778 (void *)thunk_list->u1.Function );
780 TRACE_(imports)("--- %s %s.%d = %p\n",
781 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
783 import_list++;
784 thunk_list++;
787 done:
788 /* restore old protection of the import address table */
789 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
790 *pwm = wmImp;
791 return TRUE;
795 /***********************************************************************
796 * create_module_activation_context
798 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
800 NTSTATUS status;
801 LDR_RESOURCE_INFO info;
802 const IMAGE_RESOURCE_DATA_ENTRY *entry;
804 info.Type = RT_MANIFEST;
805 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
806 info.Language = 0;
807 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
809 ACTCTXW ctx;
810 ctx.cbSize = sizeof(ctx);
811 ctx.lpSource = NULL;
812 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
813 ctx.hModule = module->BaseAddress;
814 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
815 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
817 return status;
821 /*************************************************************************
822 * is_dll_native_subsystem
824 * Check if dll is a proper native driver.
825 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
826 * while being perfectly normal DLLs. This heuristic should catch such breakages.
828 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
830 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
831 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
832 const IMAGE_IMPORT_DESCRIPTOR *imports;
833 DWORD i, size;
834 WCHAR buffer[16];
836 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
837 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
839 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
840 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
842 for (i = 0; imports[i].Name; i++)
844 const char *name = get_rva( module, imports[i].Name );
845 DWORD len = strlen(name);
846 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
847 ascii_to_unicode( buffer, name, len + 1 );
848 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
850 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
851 return FALSE;
855 return TRUE;
858 /*************************************************************************
859 * alloc_tls_slot
861 * Allocate a TLS slot for a newly-loaded module.
862 * The loader_section must be locked while calling this function.
864 static SHORT alloc_tls_slot( LDR_MODULE *mod )
866 const IMAGE_TLS_DIRECTORY *dir;
867 ULONG i, size;
868 void *new_ptr;
869 LIST_ENTRY *entry;
871 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
872 return -1;
874 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
875 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
877 for (i = 0; i < tls_module_count; i++)
879 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
880 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
881 break;
884 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
885 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
886 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
888 if (i == tls_module_count)
890 UINT new_count = max( 32, tls_module_count * 2 );
892 if (!tls_dirs)
893 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
894 else
895 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
896 new_count * sizeof(*tls_dirs) );
897 if (!new_ptr) return -1;
899 /* resize the pointer block in all running threads */
900 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
902 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
903 void **old = teb->ThreadLocalStoragePointer;
904 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
906 if (!new) return -1;
907 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
908 teb->ThreadLocalStoragePointer = new;
909 #if defined(__APPLE__) && defined(__x86_64__)
910 if (teb->Reserved5[0])
911 ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
912 #endif
913 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
914 /* FIXME: can't free old block here, should be freed at thread exit */
917 tls_dirs = new_ptr;
918 tls_module_count = new_count;
921 /* allocate the data block in all running threads */
922 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
924 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
926 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
927 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
928 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
930 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
931 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
933 RtlFreeHeap( GetProcessHeap(), 0,
934 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
937 *(DWORD *)dir->AddressOfIndex = i;
938 tls_dirs[i] = *dir;
939 return i;
943 /*************************************************************************
944 * free_tls_slot
946 * Free the module TLS slot on unload.
947 * The loader_section must be locked while calling this function.
949 static void free_tls_slot( LDR_MODULE *mod )
951 ULONG i = (USHORT)mod->TlsIndex;
953 if (mod->TlsIndex == -1) return;
954 assert( i < tls_module_count );
955 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
959 /****************************************************************
960 * fixup_imports_ilonly
962 * Fixup imports for an IL-only module. All we do is import mscoree.
963 * The loader_section must be locked while calling this function.
965 static NTSTATUS fixup_imports_ilonly( WINE_MODREF *wm, LPCWSTR load_path, void **entry )
967 static const WCHAR mscoreeW[] = {'m','s','c','o','r','e','e','.','d','l','l',0};
968 IMAGE_EXPORT_DIRECTORY *exports;
969 DWORD exp_size;
970 NTSTATUS status;
971 void *proc = NULL;
972 WINE_MODREF *prev, *imp;
974 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
975 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
977 wm->nDeps = 1;
978 wm->alloc_deps = 1;
979 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(WINE_MODREF *) );
981 prev = current_modref;
982 current_modref = wm;
983 if (!(status = load_dll( load_path, mscoreeW, 0, &imp ))) wm->deps[0] = imp;
984 current_modref = prev;
985 if (status)
987 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
988 debugstr_w(wm->ldr.BaseDllName.Buffer) );
989 return status;
992 TRACE( "loaded mscoree for %s\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
994 if ((exports = RtlImageDirectoryEntryToData( imp->ldr.BaseAddress, TRUE,
995 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
997 const char *name = (wm->ldr.Flags & LDR_IMAGE_IS_DLL) ? "_CorDllMain" : "_CorExeMain";
998 proc = find_named_export( imp->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
1000 if (!proc) return STATUS_PROCEDURE_NOT_FOUND;
1001 *entry = proc;
1002 return STATUS_SUCCESS;
1006 /****************************************************************
1007 * fixup_imports
1009 * Fixup all imports of a given module.
1010 * The loader_section must be locked while calling this function.
1012 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
1014 int i, dep, nb_imports;
1015 const IMAGE_IMPORT_DESCRIPTOR *imports;
1016 WINE_MODREF *prev, *imp;
1017 DWORD size;
1018 NTSTATUS status;
1019 ULONG_PTR cookie;
1021 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
1022 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1024 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
1026 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
1027 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
1028 return STATUS_SUCCESS;
1030 nb_imports = 0;
1031 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
1033 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
1035 if (!create_module_activation_context( &wm->ldr ))
1036 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1038 /* Allocate module dependency list */
1039 wm->alloc_deps = nb_imports;
1040 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
1042 /* load the imported modules. They are automatically
1043 * added to the modref list of the process.
1045 prev = current_modref;
1046 current_modref = wm;
1047 status = STATUS_SUCCESS;
1048 for (i = 0; i < nb_imports; i++)
1050 dep = wm->nDeps++;
1052 if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &imp ))
1054 imp = NULL;
1055 status = STATUS_DLL_NOT_FOUND;
1057 wm->deps[dep] = imp;
1059 current_modref = prev;
1060 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1061 return status;
1065 /*************************************************************************
1066 * alloc_module
1068 * Allocate a WINE_MODREF structure and add it to the process list
1069 * The loader_section must be locked while calling this function.
1071 static WINE_MODREF *alloc_module( HMODULE hModule, const UNICODE_STRING *nt_name )
1073 WINE_MODREF *wm;
1074 const WCHAR *p;
1075 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
1077 if (!(wm = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) ))) return NULL;
1079 wm->ldr.BaseAddress = hModule;
1080 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
1081 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
1082 wm->ldr.TlsIndex = -1;
1083 wm->ldr.LoadCount = 1;
1085 RtlCreateUnicodeString( &wm->ldr.FullDllName, nt_name->Buffer + 4 /* \??\ prefix */ );
1086 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
1087 else p = wm->ldr.FullDllName.Buffer;
1088 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1090 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
1092 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1093 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1094 if (nt->OptionalHeader.AddressOfEntryPoint)
1095 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1098 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1099 &wm->ldr.InLoadOrderModuleList);
1100 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1101 &wm->ldr.InMemoryOrderModuleList);
1102 /* wait until init is called for inserting into InInitializationOrderModuleList */
1104 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1106 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1107 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1108 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1110 return wm;
1114 /*************************************************************************
1115 * alloc_thread_tls
1117 * Allocate the per-thread structure for module TLS storage.
1119 static NTSTATUS alloc_thread_tls(void)
1121 void **pointers;
1122 UINT i, size;
1124 if (!tls_module_count) return STATUS_SUCCESS;
1126 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1127 tls_module_count * sizeof(*pointers) )))
1128 return STATUS_NO_MEMORY;
1130 for (i = 0; i < tls_module_count; i++)
1132 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1134 if (!dir) continue;
1135 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1136 if (!size && !dir->SizeOfZeroFill) continue;
1138 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1140 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1141 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1142 return STATUS_NO_MEMORY;
1144 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1145 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1147 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1148 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1150 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1151 #if defined(__APPLE__) && defined(__x86_64__)
1152 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
1154 : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
1155 #endif
1156 return STATUS_SUCCESS;
1160 /*************************************************************************
1161 * call_tls_callbacks
1163 static void call_tls_callbacks( HMODULE module, UINT reason )
1165 const IMAGE_TLS_DIRECTORY *dir;
1166 const PIMAGE_TLS_CALLBACK *callback;
1167 ULONG dirsize;
1169 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1170 if (!dir || !dir->AddressOfCallBacks) return;
1172 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1174 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1175 *callback, module, reason_names[reason] );
1176 __TRY
1178 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1180 __EXCEPT_ALL
1182 TRACE_(relay)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1183 GetExceptionCode(), callback, module, reason_names[reason] );
1184 return;
1186 __ENDTRY
1187 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1188 *callback, module, reason_names[reason] );
1193 /*************************************************************************
1194 * MODULE_InitDLL
1196 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1198 WCHAR mod_name[32];
1199 NTSTATUS status = STATUS_SUCCESS;
1200 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1201 void *module = wm->ldr.BaseAddress;
1202 BOOL retv = FALSE;
1204 /* Skip calls for modules loaded with special load flags */
1206 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1207 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1208 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1210 if (TRACE_ON(relay))
1212 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1213 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1214 mod_name[len / sizeof(WCHAR)] = 0;
1215 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1216 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1218 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1219 reason_names[reason], lpReserved );
1221 __TRY
1223 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1224 if (!retv)
1225 status = STATUS_DLL_INIT_FAILED;
1227 __EXCEPT_ALL
1229 status = GetExceptionCode();
1230 TRACE_(relay)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1231 status, entry, module, reason_names[reason], lpReserved );
1233 __ENDTRY
1235 /* The state of the module list may have changed due to the call
1236 to the dll. We cannot assume that this module has not been
1237 deleted. */
1238 if (TRACE_ON(relay))
1239 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1240 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1241 else
1242 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1244 return status;
1248 /*************************************************************************
1249 * process_attach
1251 * Send the process attach notification to all DLLs the given module
1252 * depends on (recursively). This is somewhat complicated due to the fact that
1254 * - we have to respect the module dependencies, i.e. modules implicitly
1255 * referenced by another module have to be initialized before the module
1256 * itself can be initialized
1258 * - the initialization routine of a DLL can itself call LoadLibrary,
1259 * thereby introducing a whole new set of dependencies (even involving
1260 * the 'old' modules) at any time during the whole process
1262 * (Note that this routine can be recursively entered not only directly
1263 * from itself, but also via LoadLibrary from one of the called initialization
1264 * routines.)
1266 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1267 * the process *detach* notifications to be sent in the correct order.
1268 * This must not only take into account module dependencies, but also
1269 * 'hidden' dependencies created by modules calling LoadLibrary in their
1270 * attach notification routine.
1272 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1273 * list after the attach notification has returned. This implies that the
1274 * detach notifications are called in the reverse of the sequence the attach
1275 * notifications *returned*.
1277 * The loader_section must be locked while calling this function.
1279 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1281 NTSTATUS status = STATUS_SUCCESS;
1282 ULONG_PTR cookie;
1283 int i;
1285 if (process_detaching) return status;
1287 /* prevent infinite recursion in case of cyclical dependencies */
1288 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1289 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1290 return status;
1292 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1294 /* Tag current MODREF to prevent recursive loop */
1295 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1296 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1297 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1299 /* Recursively attach all DLLs this one depends on */
1300 for ( i = 0; i < wm->nDeps; i++ )
1302 if (!wm->deps[i]) continue;
1303 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1306 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1307 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1308 &wm->ldr.InInitializationOrderModuleList);
1310 /* Call DLL entry point */
1311 if (status == STATUS_SUCCESS)
1313 WINE_MODREF *prev = current_modref;
1314 current_modref = wm;
1316 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED, &wm->ldr );
1317 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1318 if (status == STATUS_SUCCESS)
1320 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1322 else
1324 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1325 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, &wm->ldr );
1327 /* point to the name so LdrInitializeThunk can print it */
1328 last_failed_modref = wm;
1329 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1331 current_modref = prev;
1334 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1335 /* Remove recursion flag */
1336 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1338 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1339 return status;
1343 /**********************************************************************
1344 * attach_implicitly_loaded_dlls
1346 * Attach to the (builtin) dlls that have been implicitly loaded because
1347 * of a dependency at the Unix level, but not imported at the Win32 level.
1349 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1351 for (;;)
1353 PLIST_ENTRY mark, entry;
1355 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1356 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1358 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1360 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1361 TRACE( "found implicitly loaded %s, attaching to it\n",
1362 debugstr_w(mod->BaseDllName.Buffer));
1363 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1364 break; /* restart the search from the start */
1366 if (entry == mark) break; /* nothing found */
1371 /*************************************************************************
1372 * process_detach
1374 * Send DLL process detach notifications. See the comment about calling
1375 * sequence at process_attach.
1377 static void process_detach(void)
1379 PLIST_ENTRY mark, entry;
1380 PLDR_MODULE mod;
1382 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1385 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1387 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1388 InInitializationOrderModuleList);
1389 /* Check whether to detach this DLL */
1390 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1391 continue;
1392 if ( mod->LoadCount && !process_detaching )
1393 continue;
1395 /* Call detach notification */
1396 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1397 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1398 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1399 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED, mod );
1401 /* Restart at head of WINE_MODREF list, as entries might have
1402 been added and/or removed while performing the call ... */
1403 break;
1405 } while (entry != mark);
1408 /*************************************************************************
1409 * thread_attach
1411 * Send DLL thread attach notifications. These are sent in the
1412 * reverse sequence of process detach notification.
1413 * The loader_section must be locked while calling this function.
1415 static void thread_attach(void)
1417 PLIST_ENTRY mark, entry;
1418 PLDR_MODULE mod;
1420 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1421 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1423 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1424 InInitializationOrderModuleList);
1425 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1426 continue;
1427 if ( mod->Flags & LDR_NO_DLL_CALLS )
1428 continue;
1430 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1434 /******************************************************************
1435 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1438 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1440 WINE_MODREF *wm;
1441 NTSTATUS ret = STATUS_SUCCESS;
1443 RtlEnterCriticalSection( &loader_section );
1445 wm = get_modref( hModule );
1446 if (!wm || wm->ldr.TlsIndex != -1)
1447 ret = STATUS_DLL_NOT_FOUND;
1448 else
1449 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1451 RtlLeaveCriticalSection( &loader_section );
1453 return ret;
1456 /******************************************************************
1457 * LdrFindEntryForAddress (NTDLL.@)
1459 * The loader_section must be locked while calling this function
1461 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1463 PLIST_ENTRY mark, entry;
1464 PLDR_MODULE mod;
1466 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1467 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1469 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1470 if (mod->BaseAddress <= addr &&
1471 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1473 *pmod = mod;
1474 return STATUS_SUCCESS;
1477 return STATUS_NO_MORE_ENTRIES;
1480 /******************************************************************
1481 * LdrEnumerateLoadedModules (NTDLL.@)
1483 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1485 LIST_ENTRY *mark, *entry;
1486 LDR_MODULE *mod;
1487 BOOLEAN stop = FALSE;
1489 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1491 if (unknown || !callback)
1492 return STATUS_INVALID_PARAMETER;
1494 RtlEnterCriticalSection( &loader_section );
1496 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1497 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1499 mod = CONTAINING_RECORD( entry, LDR_MODULE, InMemoryOrderModuleList );
1500 callback( mod, context, &stop );
1501 if (stop) break;
1504 RtlLeaveCriticalSection( &loader_section );
1505 return STATUS_SUCCESS;
1508 /******************************************************************
1509 * LdrRegisterDllNotification (NTDLL.@)
1511 NTSTATUS WINAPI LdrRegisterDllNotification(ULONG flags, PLDR_DLL_NOTIFICATION_FUNCTION callback,
1512 void *context, void **cookie)
1514 struct ldr_notification *notify;
1516 TRACE( "(%x, %p, %p, %p)\n", flags, callback, context, cookie );
1518 if (!callback || !cookie)
1519 return STATUS_INVALID_PARAMETER;
1521 if (flags)
1522 FIXME( "ignoring flags %x\n", flags );
1524 notify = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify) );
1525 if (!notify) return STATUS_NO_MEMORY;
1526 notify->callback = callback;
1527 notify->context = context;
1529 RtlEnterCriticalSection( &loader_section );
1530 list_add_tail( &ldr_notifications, &notify->entry );
1531 RtlLeaveCriticalSection( &loader_section );
1533 *cookie = notify;
1534 return STATUS_SUCCESS;
1537 /******************************************************************
1538 * LdrUnregisterDllNotification (NTDLL.@)
1540 NTSTATUS WINAPI LdrUnregisterDllNotification( void *cookie )
1542 struct ldr_notification *notify = cookie;
1544 TRACE( "(%p)\n", cookie );
1546 if (!notify) return STATUS_INVALID_PARAMETER;
1548 RtlEnterCriticalSection( &loader_section );
1549 list_remove( &notify->entry );
1550 RtlLeaveCriticalSection( &loader_section );
1552 RtlFreeHeap( GetProcessHeap(), 0, notify );
1553 return STATUS_SUCCESS;
1556 /******************************************************************
1557 * LdrLockLoaderLock (NTDLL.@)
1559 * Note: some flags are not implemented.
1560 * Flag 0x01 is used to raise exceptions on errors.
1562 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1564 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1566 if (result) *result = 0;
1567 if (magic) *magic = 0;
1568 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1569 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1570 if (!magic) return STATUS_INVALID_PARAMETER_3;
1572 if (flags & 0x2)
1574 if (!RtlTryEnterCriticalSection( &loader_section ))
1576 *result = 2;
1577 return STATUS_SUCCESS;
1579 *result = 1;
1581 else
1583 RtlEnterCriticalSection( &loader_section );
1584 if (result) *result = 1;
1586 *magic = GetCurrentThreadId();
1587 return STATUS_SUCCESS;
1591 /******************************************************************
1592 * LdrUnlockLoaderUnlock (NTDLL.@)
1594 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1596 if (magic)
1598 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1599 RtlLeaveCriticalSection( &loader_section );
1601 return STATUS_SUCCESS;
1605 /******************************************************************
1606 * LdrGetProcedureAddress (NTDLL.@)
1608 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1609 ULONG ord, PVOID *address)
1611 IMAGE_EXPORT_DIRECTORY *exports;
1612 DWORD exp_size;
1613 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1615 RtlEnterCriticalSection( &loader_section );
1617 /* check if the module itself is invalid to return the proper error */
1618 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1619 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1620 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1622 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1623 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1624 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1625 if (proc)
1627 *address = proc;
1628 ret = STATUS_SUCCESS;
1632 RtlLeaveCriticalSection( &loader_section );
1633 return ret;
1637 /***********************************************************************
1638 * is_fake_dll
1640 * Check if a loaded native dll is a Wine fake dll.
1642 static BOOL is_fake_dll( HANDLE handle )
1644 static const char fakedll_signature[] = "Wine placeholder DLL";
1645 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1646 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1647 IO_STATUS_BLOCK io;
1648 LARGE_INTEGER offset;
1650 offset.QuadPart = 0;
1651 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1652 if (io.Information < sizeof(buffer)) return FALSE;
1653 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1654 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1655 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1656 return FALSE;
1660 /***********************************************************************
1661 * get_builtin_fullname
1663 * Build the full pathname for a builtin dll.
1665 static BOOL get_builtin_fullname( UNICODE_STRING *nt_name, const UNICODE_STRING *path,
1666 const char *filename )
1668 static const WCHAR nt_prefixW[] = {'\\','?','?','\\',0};
1669 static const WCHAR soW[] = {'.','s','o',0};
1670 WCHAR *p, *fullname;
1671 size_t i, len = strlen(filename);
1673 /* check if path can correspond to the dll we have */
1674 if (path && (p = strrchrW( path->Buffer, '\\' )))
1676 p++;
1677 for (i = 0; i < len; i++)
1678 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1679 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1681 /* the filename matches, use path as the full path */
1682 len += p - path->Buffer;
1683 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1684 return FALSE;
1685 memcpy( fullname, path->Buffer, len * sizeof(WCHAR) );
1686 fullname[len] = 0;
1687 goto done;
1691 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1692 (strlenW(system_dir) + len + 5) * sizeof(WCHAR) )))
1693 return FALSE;
1694 strcpyW( fullname, nt_prefixW );
1695 strcatW( fullname, system_dir );
1696 ascii_to_unicode( fullname + strlenW(fullname), filename, len + 1 );
1697 done:
1698 RtlInitUnicodeString( nt_name, fullname );
1699 return TRUE;
1703 /*************************************************************************
1704 * is_16bit_builtin
1706 static BOOL is_16bit_builtin( HMODULE module )
1708 const IMAGE_EXPORT_DIRECTORY *exports;
1709 DWORD exp_size;
1711 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1712 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1713 return FALSE;
1715 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1719 /***********************************************************************
1720 * load_builtin_callback
1722 * Load a library in memory; callback function for wine_dll_register
1724 static void load_builtin_callback( void *module, const char *filename )
1726 static const WCHAR emptyW[1];
1727 IMAGE_NT_HEADERS *nt;
1728 WINE_MODREF *wm;
1729 UNICODE_STRING nt_name;
1730 const WCHAR *load_path;
1732 if (!module)
1734 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1735 return;
1737 if (!(nt = RtlImageNtHeader( module )))
1739 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1740 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1741 return;
1744 virtual_create_builtin_view( module );
1746 /* create the MODREF */
1748 if (!get_builtin_fullname( &nt_name, builtin_load_info->filename, filename ))
1750 ERR( "can't load %s\n", filename );
1751 builtin_load_info->status = STATUS_NO_MEMORY;
1752 return;
1755 wm = alloc_module( module, &nt_name );
1756 RtlFreeUnicodeString( &nt_name );
1757 if (!wm)
1759 ERR( "can't load %s\n", filename );
1760 builtin_load_info->status = STATUS_NO_MEMORY;
1761 return;
1763 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1765 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1766 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1767 is_16bit_builtin( module ))
1769 /* fixup imports */
1771 load_path = builtin_load_info->load_path;
1772 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1773 if (!load_path) load_path = emptyW;
1774 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1776 /* the module has only be inserted in the load & memory order lists */
1777 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1778 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1779 /* FIXME: free the modref */
1780 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1781 return;
1785 builtin_load_info->wm = wm;
1786 TRACE( "loaded %s %p %p\n", filename, wm, module );
1788 /* send the DLL load event */
1790 SERVER_START_REQ( load_dll )
1792 req->base = wine_server_client_ptr( module );
1793 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1794 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1795 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1796 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1797 wine_server_call( req );
1799 SERVER_END_REQ;
1801 /* setup relay debugging entry points */
1802 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1806 /***********************************************************************
1807 * set_security_cookie
1809 * Create a random security cookie for buffer overflow protection. Make
1810 * sure it does not accidentally match the default cookie value.
1812 static void set_security_cookie( void *module, SIZE_T len )
1814 static ULONG seed;
1815 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1816 ULONG loadcfg_size;
1817 ULONG_PTR *cookie;
1819 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1820 if (!loadcfg) return;
1821 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1822 if (!loadcfg->SecurityCookie) return;
1823 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1824 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1826 WARN( "security cookie %p outside of image %p-%p\n",
1827 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1828 return;
1831 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1832 TRACE( "initializing security cookie %p\n", cookie );
1834 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1835 for (;;)
1837 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1838 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1839 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1840 *cookie = RtlRandom( &seed );
1841 #ifdef DEFAULT_SECURITY_COOKIE_64
1842 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1844 *cookie = RtlRandom( &seed );
1845 /* fill up, but keep the highest word clear */
1846 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1848 #endif
1849 else
1850 break;
1854 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1856 IMAGE_NT_HEADERS *nt;
1857 char *base;
1858 IMAGE_BASE_RELOCATION *rel, *end;
1859 const IMAGE_DATA_DIRECTORY *relocs;
1860 const IMAGE_SECTION_HEADER *sec;
1861 INT_PTR delta;
1862 ULONG protect_old[96], i;
1864 nt = RtlImageNtHeader( module );
1865 base = (char *)nt->OptionalHeader.ImageBase;
1867 assert( module != base );
1869 /* no relocations are performed on non page-aligned binaries */
1870 if (nt->OptionalHeader.SectionAlignment < page_size)
1871 return STATUS_SUCCESS;
1873 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1874 return STATUS_SUCCESS;
1876 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1878 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1880 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1881 base, module );
1882 return STATUS_CONFLICTING_ADDRESSES;
1885 if (!relocs->Size) return STATUS_SUCCESS;
1886 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1888 if (nt->FileHeader.NumberOfSections > ARRAY_SIZE( protect_old ))
1889 return STATUS_INVALID_IMAGE_FORMAT;
1891 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1892 nt->FileHeader.SizeOfOptionalHeader);
1893 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1895 void *addr = get_rva( module, sec[i].VirtualAddress );
1896 SIZE_T size = sec[i].SizeOfRawData;
1897 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1898 &size, PAGE_READWRITE, &protect_old[i] );
1901 TRACE( "relocating from %p-%p to %p-%p\n",
1902 base, base + len, module, (char *)module + len );
1904 rel = get_rva( module, relocs->VirtualAddress );
1905 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1906 delta = (char *)module - base;
1908 while (rel < end - 1 && rel->SizeOfBlock)
1910 if (rel->VirtualAddress >= len)
1912 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1913 return STATUS_ACCESS_VIOLATION;
1915 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1916 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1917 (USHORT *)(rel + 1), delta );
1918 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1921 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1923 void *addr = get_rva( module, sec[i].VirtualAddress );
1924 SIZE_T size = sec[i].SizeOfRawData;
1925 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1926 &size, protect_old[i], &protect_old[i] );
1929 return STATUS_SUCCESS;
1932 #ifdef _WIN64
1933 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1934 static BOOL convert_to_pe64( HMODULE module, const pe_image_info_t *info )
1936 static const ULONG copy_dirs[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE,
1937 IMAGE_DIRECTORY_ENTRY_SECURITY,
1938 IMAGE_DIRECTORY_ENTRY_BASERELOC,
1939 IMAGE_DIRECTORY_ENTRY_DEBUG,
1940 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR };
1941 IMAGE_OPTIONAL_HEADER32 hdr32 = { IMAGE_NT_OPTIONAL_HDR32_MAGIC };
1942 IMAGE_OPTIONAL_HEADER64 hdr64 = { IMAGE_NT_OPTIONAL_HDR64_MAGIC };
1943 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module );
1944 SIZE_T hdr_size = min( sizeof(hdr32), nt->FileHeader.SizeOfOptionalHeader );
1945 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER *)((char *)&nt->OptionalHeader + hdr_size);
1946 SIZE_T size = info->header_size;
1947 void *addr = module;
1948 ULONG i, old_prot;
1950 TRACE( "%p\n", module );
1952 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, PAGE_READWRITE, &old_prot ))
1953 return FALSE;
1955 if ((char *)module + size < (char *)(nt + 1) + nt->FileHeader.NumberOfSections * sizeof(*sec))
1957 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1958 return FALSE;
1961 memcpy( &hdr32, &nt->OptionalHeader, hdr_size );
1962 memcpy( &hdr64, &hdr32, offsetof( IMAGE_OPTIONAL_HEADER64, SizeOfStackReserve ));
1963 hdr64.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
1964 hdr64.AddressOfEntryPoint = 0;
1965 hdr64.ImageBase = hdr32.ImageBase;
1966 hdr64.SizeOfStackReserve = hdr32.SizeOfStackReserve;
1967 hdr64.SizeOfStackCommit = hdr32.SizeOfStackCommit;
1968 hdr64.SizeOfHeapReserve = hdr32.SizeOfHeapReserve;
1969 hdr64.SizeOfHeapCommit = hdr32.SizeOfHeapCommit;
1970 hdr64.LoaderFlags = hdr32.LoaderFlags;
1971 hdr64.NumberOfRvaAndSizes = hdr32.NumberOfRvaAndSizes;
1972 for (i = 0; i < ARRAY_SIZE( copy_dirs ); i++)
1973 hdr64.DataDirectory[copy_dirs[i]] = hdr32.DataDirectory[copy_dirs[i]];
1975 memmove( nt + 1, sec, nt->FileHeader.NumberOfSections * sizeof(*sec) );
1976 nt->FileHeader.SizeOfOptionalHeader = sizeof(hdr64);
1977 nt->OptionalHeader = hdr64;
1978 NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size, old_prot, &old_prot );
1979 return TRUE;
1981 #endif
1983 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
1984 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
1985 static BOOL is_valid_binary( HMODULE module, const pe_image_info_t *info )
1987 #ifdef __i386__
1988 return info->machine == IMAGE_FILE_MACHINE_I386;
1989 #elif defined(__arm__)
1990 return info->machine == IMAGE_FILE_MACHINE_ARM ||
1991 info->machine == IMAGE_FILE_MACHINE_THUMB ||
1992 info->machine == IMAGE_FILE_MACHINE_ARMNT;
1993 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
1994 #ifdef __x86_64__
1995 if (info->machine == IMAGE_FILE_MACHINE_AMD64) return TRUE;
1996 #else
1997 if (info->machine == IMAGE_FILE_MACHINE_ARM64) return TRUE;
1998 #endif
1999 if (!info->contains_code) return TRUE;
2000 if (!(info->image_flags & IMAGE_FLAGS_ComPlusNativeReady))
2002 /* check COM header directly, ignoring runtime version */
2003 DWORD size;
2004 const IMAGE_COR20_HEADER *cor_header = RtlImageDirectoryEntryToData( module, TRUE,
2005 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &size );
2006 if (!cor_header || !(cor_header->Flags & COMIMAGE_FLAGS_ILONLY)) return FALSE;
2008 return convert_to_pe64( module, info );
2009 #else
2010 return FALSE; /* no wow64 support on other platforms */
2011 #endif
2015 /******************************************************************************
2016 * load_native_dll (internal)
2018 static NTSTATUS load_native_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, HANDLE file,
2019 DWORD flags, WINE_MODREF** pwm, struct stat *st )
2021 void *module;
2022 HANDLE mapping;
2023 LARGE_INTEGER size;
2024 IMAGE_NT_HEADERS *nt;
2025 SIZE_T len = 0;
2026 WINE_MODREF *wm;
2027 NTSTATUS status;
2028 pe_image_info_t image_info;
2030 TRACE("Trying native dll %s\n", debugstr_us(nt_name));
2032 size.QuadPart = 0;
2033 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
2034 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
2035 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
2036 if (status != STATUS_SUCCESS) return status;
2038 module = NULL;
2039 status = virtual_map_section( mapping, &module, 0, 0, NULL, &len, PAGE_EXECUTE_READ, &image_info );
2040 NtClose( mapping );
2042 if ((status == STATUS_SUCCESS || status == STATUS_IMAGE_NOT_AT_BASE) &&
2043 !is_valid_binary( module, &image_info ))
2045 NtUnmapViewOfSection( NtCurrentProcess(), module );
2046 return STATUS_INVALID_IMAGE_FORMAT;
2049 /* perform base relocation, if necessary */
2051 if (status == STATUS_IMAGE_NOT_AT_BASE)
2052 status = perform_relocations( module, len );
2054 if (status != STATUS_SUCCESS)
2056 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2057 return status;
2060 /* create the MODREF */
2062 if (!(wm = alloc_module( module, nt_name )))
2064 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
2065 return STATUS_NO_MEMORY;
2068 wm->dev = st->st_dev;
2069 wm->ino = st->st_ino;
2070 if (image_info.loader_flags) wm->ldr.Flags |= LDR_COR_IMAGE;
2071 if (image_info.image_flags & IMAGE_FLAGS_ComPlusILOnly) wm->ldr.Flags |= LDR_COR_ILONLY;
2073 set_security_cookie( module, len );
2075 /* fixup imports */
2077 nt = RtlImageNtHeader( module );
2079 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
2080 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
2081 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
2083 if (wm->ldr.Flags & LDR_COR_ILONLY)
2084 status = fixup_imports_ilonly( wm, load_path, &wm->ldr.EntryPoint );
2085 else
2086 status = fixup_imports( wm, load_path );
2087 if (status != STATUS_SUCCESS)
2089 /* the module has only be inserted in the load & memory order lists */
2090 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2091 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2093 /* FIXME: there are several more dangling references
2094 * left. Including dlls loaded by this dll before the
2095 * failed one. Unrolling is rather difficult with the
2096 * current structure and we can leave them lying
2097 * around with no problems, so we don't care.
2098 * As these might reference our wm, we don't free it.
2100 return status;
2104 /* send DLL load event */
2106 SERVER_START_REQ( load_dll )
2108 req->base = wine_server_client_ptr( module );
2109 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
2110 req->dbg_size = nt->FileHeader.NumberOfSymbols;
2111 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
2112 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
2113 wine_server_call( req );
2115 SERVER_END_REQ;
2117 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
2119 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
2121 wm->ldr.LoadCount = 1;
2122 *pwm = wm;
2123 return STATUS_SUCCESS;
2127 /***********************************************************************
2128 * load_builtin_dll
2130 static NTSTATUS load_builtin_dll( LPCWSTR load_path, const UNICODE_STRING *nt_name, HANDLE file,
2131 DWORD flags, WINE_MODREF** pwm )
2133 char error[256], dllname[MAX_PATH];
2134 const WCHAR *name, *p;
2135 DWORD len, i;
2136 void *handle;
2137 struct builtin_load_info info, *prev_info;
2139 /* Fix the name in case we have a full path and extension */
2140 name = nt_name->Buffer;
2141 if ((p = strrchrW( name, '\\' ))) name = p + 1;
2142 if ((p = strrchrW( name, '/' ))) name = p + 1;
2144 /* load_library will modify info.status. Note also that load_library can be
2145 * called several times, if the .so file we're loading has dependencies.
2146 * info.status will gather all the errors we may get while loading all these
2147 * libraries
2149 info.load_path = load_path;
2150 info.filename = NULL;
2151 info.status = STATUS_SUCCESS;
2152 info.wm = NULL;
2154 if (file) /* we have a real file, try to load it */
2156 ANSI_STRING unix_name;
2158 TRACE("Trying built-in %s\n", debugstr_us(nt_name));
2160 if (wine_nt_to_unix_file_name( nt_name, &unix_name, FILE_OPEN, FALSE ))
2161 return STATUS_DLL_NOT_FOUND;
2162 prev_info = builtin_load_info;
2163 info.filename = nt_name;
2164 builtin_load_info = &info;
2165 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
2166 builtin_load_info = prev_info;
2167 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
2168 if (!handle)
2170 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_us(nt_name), error );
2171 return STATUS_INVALID_IMAGE_FORMAT;
2174 else
2176 int file_exists;
2178 TRACE("Trying built-in %s\n", debugstr_w(name));
2180 /* we don't want to depend on the current codepage here */
2181 len = strlenW( name ) + 1;
2182 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
2183 for (i = 0; i < len; i++)
2185 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
2186 dllname[i] = (char)name[i];
2187 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
2190 prev_info = builtin_load_info;
2191 builtin_load_info = &info;
2192 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
2193 builtin_load_info = prev_info;
2194 if (!handle)
2196 if (!file_exists)
2198 /* The file does not exist -> WARN() */
2199 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
2200 return STATUS_DLL_NOT_FOUND;
2202 /* ERR() for all other errors (missing functions, ...) */
2203 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
2204 return STATUS_PROCEDURE_NOT_FOUND;
2208 if (info.status != STATUS_SUCCESS)
2210 wine_dll_unload( handle );
2211 return info.status;
2214 if (!info.wm)
2216 PLIST_ENTRY mark, entry;
2218 /* The constructor wasn't called, this means the .so is already
2219 * loaded under a different name. Try to find the wm for it. */
2221 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2222 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2224 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2225 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
2227 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2228 TRACE( "Found %s at %p for builtin %s\n",
2229 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress,
2230 debugstr_us(nt_name) );
2231 break;
2234 wine_dll_unload( handle ); /* release the libdl refcount */
2235 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2236 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2238 else
2240 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2241 info.wm->ldr.LoadCount = 1;
2242 info.wm->ldr.SectionHandle = handle;
2245 *pwm = info.wm;
2246 return STATUS_SUCCESS;
2250 /***********************************************************************
2251 * find_actctx_dll
2253 * Find the full path (if any) of the dll from the activation context.
2255 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2257 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2258 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2260 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2261 ACTCTX_SECTION_KEYED_DATA data;
2262 UNICODE_STRING nameW;
2263 NTSTATUS status;
2264 SIZE_T needed, size = 1024;
2265 WCHAR *p;
2267 RtlInitUnicodeString( &nameW, libname );
2268 data.cbSize = sizeof(data);
2269 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2270 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2271 &nameW, &data );
2272 if (status != STATUS_SUCCESS) return status;
2274 for (;;)
2276 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2278 status = STATUS_NO_MEMORY;
2279 goto done;
2281 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2282 AssemblyDetailedInformationInActivationContext,
2283 info, size, &needed );
2284 if (status == STATUS_SUCCESS) break;
2285 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2286 RtlFreeHeap( GetProcessHeap(), 0, info );
2287 size = needed;
2288 /* restart with larger buffer */
2291 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2293 status = STATUS_SXS_KEY_NOT_FOUND;
2294 goto done;
2297 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2299 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2301 p++;
2302 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2304 /* manifest name does not match directory name, so it's not a global
2305 * windows/winsxs manifest; use the manifest directory name instead */
2306 dirlen = p - info->lpAssemblyManifestPath;
2307 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2308 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2310 status = STATUS_NO_MEMORY;
2311 goto done;
2313 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2314 p += dirlen;
2315 strcpyW( p, libname );
2316 goto done;
2320 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2321 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2323 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2325 status = STATUS_NO_MEMORY;
2326 goto done;
2328 strcpyW( p, user_shared_data->NtSystemRoot );
2329 p += strlenW(p);
2330 memcpy( p, winsxsW, sizeof(winsxsW) );
2331 p += ARRAY_SIZE( winsxsW );
2332 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2333 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2334 *p++ = '\\';
2335 strcpyW( p, libname );
2336 done:
2337 RtlFreeHeap( GetProcessHeap(), 0, info );
2338 RtlReleaseActivationContext( data.hActCtx );
2339 return status;
2343 /***********************************************************************
2344 * open_dll_file
2346 * Open a file for a new dll. Helper for find_dll_file.
2348 static HANDLE open_dll_file( UNICODE_STRING *nt_name, WINE_MODREF **pwm, struct stat *st )
2350 OBJECT_ATTRIBUTES attr;
2351 IO_STATUS_BLOCK io;
2352 HANDLE handle;
2353 int fd, needs_close;
2355 if ((*pwm = find_fullname_module( nt_name ))) return 0;
2357 attr.Length = sizeof(attr);
2358 attr.RootDirectory = 0;
2359 attr.Attributes = OBJ_CASE_INSENSITIVE;
2360 attr.ObjectName = nt_name;
2361 attr.SecurityDescriptor = NULL;
2362 attr.SecurityQualityOfService = NULL;
2363 if (NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ | FILE_SHARE_DELETE,
2364 FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE ))
2365 return 0;
2367 if (!server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL ))
2369 fstat( fd, st );
2370 if (needs_close) close( fd );
2371 if ((*pwm = find_fileid_module( st )))
2373 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name->Buffer ),
2374 (*pwm)->ldr.BaseAddress, debugstr_w( (*pwm)->ldr.FullDllName.Buffer ));
2375 NtClose( handle );
2376 return 0;
2379 return handle;
2383 /***********************************************************************
2384 * search_dll_file
2386 * Search for dll in the specified paths.
2388 static NTSTATUS search_dll_file( LPCWSTR paths, LPCWSTR search, UNICODE_STRING *nt_name )
2390 WCHAR *name;
2391 NTSTATUS status = STATUS_DLL_NOT_FOUND;
2392 ULONG len = strlenW( paths );
2394 if (len < strlenW( system_dir )) len = strlenW( system_dir );
2395 len += strlenW( search ) + 2;
2397 if (!(name = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2398 return STATUS_NO_MEMORY;
2400 while (*paths)
2402 LPCWSTR ptr = paths;
2404 while (*ptr && *ptr != ';') ptr++;
2405 len = ptr - paths;
2406 if (*ptr == ';') ptr++;
2407 memcpy( name, paths, len * sizeof(WCHAR) );
2408 if (len && name[len - 1] != '\\') name[len++] = '\\';
2409 strcpyW( name + len, search );
2410 if (RtlDoesFileExists_U( name ))
2412 if (!RtlDosPathNameToNtPathName_U( name, nt_name, NULL, NULL ))
2413 status = STATUS_NO_MEMORY;
2414 else
2415 status = STATUS_SUCCESS;
2416 goto done;
2418 paths = ptr;
2421 /* not found, return file in the system dir to be loaded as builtin */
2422 strcpyW( name, system_dir );
2423 strcatW( name, search );
2424 if (!RtlDosPathNameToNtPathName_U( name, nt_name, NULL, NULL )) status = STATUS_NO_MEMORY;
2426 done:
2427 RtlFreeHeap( GetProcessHeap(), 0, name );
2428 return status;
2432 /***********************************************************************
2433 * find_dll_file
2435 * Find the file (or already loaded module) for a given dll name.
2437 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2438 UNICODE_STRING *nt_name, WINE_MODREF **pwm,
2439 HANDLE *handle, struct stat *st )
2441 WCHAR *ext, *dllname;
2442 NTSTATUS status;
2444 /* first append .dll if needed */
2446 *handle = 0;
2447 dllname = NULL;
2448 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2450 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2451 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2452 return STATUS_NO_MEMORY;
2453 strcpyW( dllname, libname );
2454 strcatW( dllname, dllW );
2455 libname = dllname;
2458 nt_name->Buffer = NULL;
2460 if (!contains_path( libname ))
2462 WCHAR *fullname = NULL;
2464 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2466 status = find_actctx_dll( libname, &fullname );
2467 if (status == STATUS_SUCCESS)
2469 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2470 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2471 libname = dllname = fullname;
2473 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2475 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2476 return status;
2480 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2482 /* we need to search for it */
2483 if (!(status = search_dll_file( load_path, libname, nt_name )))
2485 *handle = open_dll_file( nt_name, pwm, st );
2487 else if (status != STATUS_DLL_NOT_FOUND)
2489 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2490 return status;
2492 goto found;
2495 /* absolute path name */
2497 if (!RtlDosPathNameToNtPathName_U( libname, nt_name, NULL, NULL ))
2499 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2500 return STATUS_NO_MEMORY;
2502 *handle = open_dll_file( nt_name, pwm, st );
2504 found:
2505 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2506 return STATUS_SUCCESS;
2510 /***********************************************************************
2511 * load_dll (internal)
2513 * Load a PE style module according to the load order.
2514 * The loader_section must be locked while calling this function.
2516 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2518 enum loadorder loadorder;
2519 WINE_MODREF *main_exe;
2520 UNICODE_STRING nt_name;
2521 struct stat st;
2522 HANDLE handle;
2523 NTSTATUS nts;
2525 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2527 *pwm = NULL;
2528 nts = find_dll_file( load_path, libname, &nt_name, pwm, &handle, &st );
2529 if (nts) return nts;
2531 if (*pwm) /* found already loaded module */
2533 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2535 TRACE("Found %s for %s at %p, count=%d\n",
2536 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2537 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2538 RtlFreeUnicodeString( &nt_name );
2539 return STATUS_SUCCESS;
2542 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2543 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, &nt_name );
2545 if (handle && is_fake_dll( handle ))
2547 TRACE( "%s is a fake Wine dll\n", debugstr_us(&nt_name) );
2548 NtClose( handle );
2549 handle = 0;
2552 switch(loadorder)
2554 case LO_INVALID:
2555 nts = STATUS_NO_MEMORY;
2556 break;
2557 case LO_DISABLED:
2558 nts = STATUS_DLL_NOT_FOUND;
2559 break;
2560 case LO_NATIVE:
2561 case LO_NATIVE_BUILTIN:
2562 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2563 else
2565 nts = load_native_dll( load_path, &nt_name, handle, flags, pwm, &st );
2566 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2567 /* not in PE format, maybe it's a builtin */
2568 nts = load_builtin_dll( load_path, &nt_name, handle, flags, pwm );
2570 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2571 nts = load_builtin_dll( load_path, &nt_name, 0, flags, pwm );
2572 break;
2573 case LO_BUILTIN:
2574 case LO_BUILTIN_NATIVE:
2575 case LO_DEFAULT: /* default is builtin,native */
2576 nts = load_builtin_dll( load_path, &nt_name, handle, flags, pwm );
2577 if (!handle) break; /* nothing else we can try */
2578 /* file is not a builtin library, try without using the specified file */
2579 if (nts != STATUS_SUCCESS)
2580 nts = load_builtin_dll( load_path, &nt_name, 0, flags, pwm );
2581 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2582 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2584 /* stub-only dll, try native */
2585 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_us(&nt_name) );
2586 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2587 nts = STATUS_DLL_NOT_FOUND;
2589 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2590 nts = load_native_dll( load_path, &nt_name, handle, flags, pwm, &st );
2591 break;
2594 if (nts == STATUS_SUCCESS)
2595 TRACE("Loaded module %s (%s) at %p\n", debugstr_us(&nt_name),
2596 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native", (*pwm)->ldr.BaseAddress);
2597 else
2598 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2600 if (handle) NtClose( handle );
2601 RtlFreeUnicodeString( &nt_name );
2602 return nts;
2605 /******************************************************************
2606 * LdrLoadDll (NTDLL.@)
2608 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2609 const UNICODE_STRING *libname, HMODULE* hModule)
2611 WINE_MODREF *wm;
2612 NTSTATUS nts;
2614 RtlEnterCriticalSection( &loader_section );
2616 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2617 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2619 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2621 nts = process_attach( wm, NULL );
2622 if (nts != STATUS_SUCCESS)
2624 LdrUnloadDll(wm->ldr.BaseAddress);
2625 wm = NULL;
2628 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2630 RtlLeaveCriticalSection( &loader_section );
2631 return nts;
2635 /******************************************************************
2636 * LdrGetDllHandle (NTDLL.@)
2638 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2640 NTSTATUS status;
2641 UNICODE_STRING nt_name;
2642 WINE_MODREF *wm;
2643 HANDLE handle;
2644 struct stat st;
2646 RtlEnterCriticalSection( &loader_section );
2648 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2650 status = find_dll_file( load_path, name->Buffer, &nt_name, &wm, &handle, &st );
2651 if (handle) NtClose( handle );
2652 RtlFreeUnicodeString( &nt_name );
2654 if (status == STATUS_SUCCESS)
2656 if (wm) *base = wm->ldr.BaseAddress;
2657 else status = STATUS_DLL_NOT_FOUND;
2660 RtlLeaveCriticalSection( &loader_section );
2661 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2662 return status;
2666 /******************************************************************
2667 * LdrAddRefDll (NTDLL.@)
2669 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2671 NTSTATUS ret = STATUS_SUCCESS;
2672 WINE_MODREF *wm;
2674 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2676 RtlEnterCriticalSection( &loader_section );
2678 if ((wm = get_modref( module )))
2680 if (flags & LDR_ADDREF_DLL_PIN)
2681 wm->ldr.LoadCount = -1;
2682 else
2683 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2684 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2686 else ret = STATUS_INVALID_PARAMETER;
2688 RtlLeaveCriticalSection( &loader_section );
2689 return ret;
2693 /***********************************************************************
2694 * LdrProcessRelocationBlock (NTDLL.@)
2696 * Apply relocations to a given page of a mapped PE image.
2698 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2699 USHORT *relocs, INT_PTR delta )
2701 while (count--)
2703 USHORT offset = *relocs & 0xfff;
2704 int type = *relocs >> 12;
2705 switch(type)
2707 case IMAGE_REL_BASED_ABSOLUTE:
2708 break;
2709 case IMAGE_REL_BASED_HIGH:
2710 *(short *)((char *)page + offset) += HIWORD(delta);
2711 break;
2712 case IMAGE_REL_BASED_LOW:
2713 *(short *)((char *)page + offset) += LOWORD(delta);
2714 break;
2715 case IMAGE_REL_BASED_HIGHLOW:
2716 *(int *)((char *)page + offset) += delta;
2717 break;
2718 #ifdef _WIN64
2719 case IMAGE_REL_BASED_DIR64:
2720 *(INT_PTR *)((char *)page + offset) += delta;
2721 break;
2722 #elif defined(__arm__)
2723 case IMAGE_REL_BASED_THUMB_MOV32:
2725 DWORD inst = *(INT_PTR *)((char *)page + offset);
2726 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2727 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2728 DWORD hi_delta;
2730 if ((inst & 0x8000fbf0) != 0x0000f240)
2731 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2733 imm16 += LOWORD(delta);
2734 hi_delta = HIWORD(delta) + HIWORD(imm16);
2735 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2736 ((imm16 >> 12) & 0x000f) +
2737 ((imm16 << 20) & 0x70000000) +
2738 ((imm16 << 16) & 0xff0000);
2740 if (hi_delta != 0)
2742 inst = *(INT_PTR *)((char *)page + offset + 4);
2743 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2744 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2746 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2747 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2749 imm16 += hi_delta;
2750 if (imm16 > 0xffff)
2751 ERR("resulting immediate value won't fit: %08x\n", imm16);
2752 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2753 ((imm16 >> 1) & 0x0400) +
2754 ((imm16 >> 12) & 0x000f) +
2755 ((imm16 << 20) & 0x70000000) +
2756 ((imm16 << 16) & 0xff0000);
2759 break;
2760 #endif
2761 default:
2762 FIXME("Unknown/unsupported fixup type %x.\n", type);
2763 return NULL;
2765 relocs++;
2767 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2771 /******************************************************************
2772 * LdrQueryProcessModuleInformation
2775 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2776 ULONG buf_size, ULONG* req_size)
2778 SYSTEM_MODULE* sm = &smi->Modules[0];
2779 ULONG size = sizeof(ULONG);
2780 NTSTATUS nts = STATUS_SUCCESS;
2781 ANSI_STRING str;
2782 char* ptr;
2783 PLIST_ENTRY mark, entry;
2784 PLDR_MODULE mod;
2785 WORD id = 0;
2787 smi->ModulesCount = 0;
2789 RtlEnterCriticalSection( &loader_section );
2790 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2791 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2793 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2794 size += sizeof(*sm);
2795 if (size <= buf_size)
2797 sm->Reserved1 = 0; /* FIXME */
2798 sm->Reserved2 = 0; /* FIXME */
2799 sm->ImageBaseAddress = mod->BaseAddress;
2800 sm->ImageSize = mod->SizeOfImage;
2801 sm->Flags = mod->Flags;
2802 sm->Id = id++;
2803 sm->Rank = 0; /* FIXME */
2804 sm->Unknown = 0; /* FIXME */
2805 str.Length = 0;
2806 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2807 str.Buffer = (char*)sm->Name;
2808 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2809 ptr = strrchr(str.Buffer, '\\');
2810 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2812 smi->ModulesCount++;
2813 sm++;
2815 else nts = STATUS_INFO_LENGTH_MISMATCH;
2817 RtlLeaveCriticalSection( &loader_section );
2819 if (req_size) *req_size = size;
2821 return nts;
2825 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2827 NTSTATUS status;
2828 UNICODE_STRING str;
2829 ULONG size;
2830 WCHAR buffer[64];
2831 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2833 RtlInitUnicodeString( &str, name );
2835 size = sizeof(buffer) - sizeof(WCHAR);
2836 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2837 return status;
2839 if (info->Type != REG_DWORD)
2841 buffer[size / sizeof(WCHAR)] = 0;
2842 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2844 else memcpy( value, info->Data, sizeof(*value) );
2845 return status;
2848 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2849 void *data, ULONG in_size, ULONG *out_size )
2851 NTSTATUS status;
2852 UNICODE_STRING str;
2853 ULONG size;
2854 char *buffer;
2855 KEY_VALUE_PARTIAL_INFORMATION *info;
2856 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2858 RtlInitUnicodeString( &str, name );
2860 size = info_size + in_size;
2861 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2862 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2863 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2864 if (!status || status == STATUS_BUFFER_OVERFLOW)
2866 if (out_size) *out_size = info->DataLength;
2867 if (data && !status) memcpy( data, info->Data, info->DataLength );
2869 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2870 return status;
2874 /******************************************************************
2875 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2877 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2878 void *data, ULONG in_size, ULONG *out_size )
2880 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2881 'S','o','f','t','w','a','r','e','\\',
2882 'M','i','c','r','o','s','o','f','t','\\',
2883 'W','i','n','d','o','w','s',' ','N','T','\\',
2884 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2885 'I','m','a','g','e',' ','F','i','l','e',' ',
2886 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2887 WCHAR path[MAX_PATH + ARRAY_SIZE( optionsW )];
2888 OBJECT_ATTRIBUTES attr;
2889 UNICODE_STRING name_str;
2890 HANDLE hkey;
2891 NTSTATUS status;
2892 ULONG len;
2893 WCHAR *p;
2895 attr.Length = sizeof(attr);
2896 attr.RootDirectory = 0;
2897 attr.ObjectName = &name_str;
2898 attr.Attributes = OBJ_CASE_INSENSITIVE;
2899 attr.SecurityDescriptor = NULL;
2900 attr.SecurityQualityOfService = NULL;
2902 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2903 else p = key->Buffer;
2904 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2905 name_str.Buffer = path;
2906 name_str.Length = sizeof(optionsW) + len;
2907 name_str.MaximumLength = name_str.Length;
2908 memcpy( path, optionsW, sizeof(optionsW) );
2909 memcpy( path + ARRAY_SIZE( optionsW ), p, len );
2910 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2912 if (type == REG_DWORD)
2914 if (out_size) *out_size = sizeof(ULONG);
2915 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2916 else status = STATUS_BUFFER_OVERFLOW;
2918 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2920 NtClose( hkey );
2921 return status;
2925 /******************************************************************
2926 * RtlDllShutdownInProgress (NTDLL.@)
2928 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2930 return process_detaching;
2933 /****************************************************************************
2934 * LdrResolveDelayLoadedAPI (NTDLL.@)
2936 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2937 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook,
2938 PDELAYLOAD_FAILURE_SYSTEM_ROUTINE syshook,
2939 IMAGE_THUNK_DATA* addr, ULONG flags )
2941 IMAGE_THUNK_DATA *pIAT, *pINT;
2942 DELAYLOAD_INFO delayinfo;
2943 UNICODE_STRING mod;
2944 const CHAR* name;
2945 HMODULE *phmod;
2946 NTSTATUS nts;
2947 FARPROC fp;
2948 DWORD id;
2950 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2952 phmod = get_rva(base, desc->ModuleHandleRVA);
2953 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2954 pINT = get_rva(base, desc->ImportNameTableRVA);
2955 name = get_rva(base, desc->DllNameRVA);
2956 id = addr - pIAT;
2958 if (!*phmod)
2960 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2962 nts = STATUS_NO_MEMORY;
2963 goto fail;
2965 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2966 RtlFreeUnicodeString(&mod);
2967 if (nts) goto fail;
2970 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2971 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2972 else
2974 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2975 ANSI_STRING fnc;
2977 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2978 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2980 if (!nts)
2982 pIAT[id].u1.Function = (ULONG_PTR)fp;
2983 return fp;
2986 fail:
2987 delayinfo.Size = sizeof(delayinfo);
2988 delayinfo.DelayloadDescriptor = desc;
2989 delayinfo.ThunkAddress = addr;
2990 delayinfo.TargetDllName = name;
2991 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2992 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2993 delayinfo.TargetModuleBase = *phmod;
2994 delayinfo.Unused = NULL;
2995 delayinfo.LastError = nts;
2997 if (dllhook)
2998 return dllhook(4, &delayinfo);
3000 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
3002 DWORD_PTR ord = LOWORD(pINT[id].u1.Ordinal);
3003 return syshook(name, (const char *)ord);
3005 else
3007 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
3008 return syshook(name, (const char *)iibn->Name);
3012 /******************************************************************
3013 * LdrShutdownProcess (NTDLL.@)
3016 void WINAPI LdrShutdownProcess(void)
3018 TRACE("()\n");
3019 process_detaching = TRUE;
3020 process_detach();
3024 /******************************************************************
3025 * RtlExitUserProcess (NTDLL.@)
3027 void WINAPI RtlExitUserProcess( DWORD status )
3029 RtlEnterCriticalSection( &loader_section );
3030 RtlAcquirePebLock();
3031 NtTerminateProcess( 0, status );
3032 LdrShutdownProcess();
3033 NtTerminateProcess( GetCurrentProcess(), status );
3034 exit( status );
3037 /******************************************************************
3038 * LdrShutdownThread (NTDLL.@)
3041 void WINAPI LdrShutdownThread(void)
3043 PLIST_ENTRY mark, entry;
3044 PLDR_MODULE mod;
3045 UINT i;
3046 void **pointers;
3048 TRACE("()\n");
3050 /* don't do any detach calls if process is exiting */
3051 if (process_detaching) return;
3053 RtlEnterCriticalSection( &loader_section );
3055 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3056 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
3058 mod = CONTAINING_RECORD(entry, LDR_MODULE,
3059 InInitializationOrderModuleList);
3060 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
3061 continue;
3062 if ( mod->Flags & LDR_NO_DLL_CALLS )
3063 continue;
3065 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
3066 DLL_THREAD_DETACH, NULL );
3069 RtlAcquirePebLock();
3070 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
3071 RtlReleasePebLock();
3073 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
3075 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
3076 RtlFreeHeap( GetProcessHeap(), 0, pointers );
3078 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
3079 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
3080 RtlLeaveCriticalSection( &loader_section );
3084 /***********************************************************************
3085 * free_modref
3088 static void free_modref( WINE_MODREF *wm )
3090 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
3091 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
3092 if (wm->ldr.InInitializationOrderModuleList.Flink)
3093 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
3095 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
3096 if (!TRACE_ON(module))
3097 TRACE_(loaddll)("Unloaded module %s : %s\n",
3098 debugstr_w(wm->ldr.FullDllName.Buffer),
3099 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
3101 SERVER_START_REQ( unload_dll )
3103 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
3104 wine_server_call( req );
3106 SERVER_END_REQ;
3108 free_tls_slot( &wm->ldr );
3109 RtlReleaseActivationContext( wm->ldr.ActivationContext );
3110 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
3111 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
3112 if (cached_modref == wm) cached_modref = NULL;
3113 RtlFreeUnicodeString( &wm->ldr.FullDllName );
3114 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
3115 RtlFreeHeap( GetProcessHeap(), 0, wm );
3118 /***********************************************************************
3119 * MODULE_FlushModrefs
3121 * Remove all unused modrefs and call the internal unloading routines
3122 * for the library type.
3124 * The loader_section must be locked while calling this function.
3126 static void MODULE_FlushModrefs(void)
3128 PLIST_ENTRY mark, entry, prev;
3129 PLDR_MODULE mod;
3130 WINE_MODREF*wm;
3132 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
3133 for (entry = mark->Blink; entry != mark; entry = prev)
3135 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
3136 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3137 prev = entry->Blink;
3138 if (!mod->LoadCount) free_modref( wm );
3141 /* check load order list too for modules that haven't been initialized yet */
3142 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3143 for (entry = mark->Blink; entry != mark; entry = prev)
3145 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
3146 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
3147 prev = entry->Blink;
3148 if (!mod->LoadCount) free_modref( wm );
3152 /***********************************************************************
3153 * MODULE_DecRefCount
3155 * The loader_section must be locked while calling this function.
3157 static void MODULE_DecRefCount( WINE_MODREF *wm )
3159 int i;
3161 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
3162 return;
3164 if ( wm->ldr.LoadCount <= 0 )
3165 return;
3167 --wm->ldr.LoadCount;
3168 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
3170 if ( wm->ldr.LoadCount == 0 )
3172 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
3174 for ( i = 0; i < wm->nDeps; i++ )
3175 if ( wm->deps[i] )
3176 MODULE_DecRefCount( wm->deps[i] );
3178 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
3182 /******************************************************************
3183 * LdrUnloadDll (NTDLL.@)
3187 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
3189 WINE_MODREF *wm;
3190 NTSTATUS retv = STATUS_SUCCESS;
3192 if (process_detaching) return retv;
3194 TRACE("(%p)\n", hModule);
3196 RtlEnterCriticalSection( &loader_section );
3198 free_lib_count++;
3199 if ((wm = get_modref( hModule )) != NULL)
3201 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
3203 /* Recursively decrement reference counts */
3204 MODULE_DecRefCount( wm );
3206 /* Call process detach notifications */
3207 if ( free_lib_count <= 1 )
3209 process_detach();
3210 MODULE_FlushModrefs();
3213 TRACE("END\n");
3215 else
3216 retv = STATUS_DLL_NOT_FOUND;
3218 free_lib_count--;
3220 RtlLeaveCriticalSection( &loader_section );
3222 return retv;
3225 /***********************************************************************
3226 * RtlImageNtHeader (NTDLL.@)
3228 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
3230 IMAGE_NT_HEADERS *ret;
3232 __TRY
3234 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3236 ret = NULL;
3237 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3239 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3240 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3243 __EXCEPT_PAGE_FAULT
3245 return NULL;
3247 __ENDTRY
3248 return ret;
3252 /***********************************************************************
3253 * attach_dlls
3255 * Attach to all the loaded dlls.
3256 * If this is the first time, perform the full process initialization.
3258 NTSTATUS attach_dlls( CONTEXT *context, void **entry )
3260 NTSTATUS status;
3261 WINE_MODREF *wm;
3262 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3264 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3266 if (process_detaching) return STATUS_SUCCESS;
3268 RtlEnterCriticalSection( &loader_section );
3270 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3271 assert( wm );
3273 if (!imports_fixup_done)
3275 actctx_init();
3276 if (wm->ldr.Flags & LDR_COR_ILONLY)
3277 status = fixup_imports_ilonly( wm, load_path, entry );
3278 else
3279 status = fixup_imports( wm, load_path );
3281 if (status)
3283 ERR( "Importing dlls for %s failed, status %x\n",
3284 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3285 NtTerminateProcess( GetCurrentProcess(), status );
3287 imports_fixup_done = TRUE;
3290 RtlAcquirePebLock();
3291 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3292 RtlReleasePebLock();
3294 if (!(wm->ldr.Flags & LDR_PROCESS_ATTACHED)) /* first time around */
3296 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3298 ERR( "TLS init failed when loading %s, status %x\n",
3299 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3300 NtTerminateProcess( GetCurrentProcess(), status );
3302 if ((status = process_attach( wm, context )) != STATUS_SUCCESS)
3304 if (last_failed_modref)
3305 ERR( "%s failed to initialize, aborting\n",
3306 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3307 ERR( "Initializing dlls for %s failed, status %x\n",
3308 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3309 NtTerminateProcess( GetCurrentProcess(), status );
3311 attach_implicitly_loaded_dlls( context );
3312 virtual_release_address_space();
3314 else
3316 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3317 NtTerminateThread( GetCurrentThread(), status );
3318 thread_attach();
3321 RtlLeaveCriticalSection( &loader_section );
3322 return STATUS_SUCCESS;
3326 /***********************************************************************
3327 * load_global_options
3329 static void load_global_options(void)
3331 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3332 'S','y','s','t','e','m','\\',
3333 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3334 'C','o','n','t','r','o','l','\\',
3335 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3336 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3337 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};
3338 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3339 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3340 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};
3341 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};
3343 OBJECT_ATTRIBUTES attr;
3344 UNICODE_STRING name_str;
3345 HANDLE hkey;
3346 ULONG value;
3348 attr.Length = sizeof(attr);
3349 attr.RootDirectory = 0;
3350 attr.ObjectName = &name_str;
3351 attr.Attributes = OBJ_CASE_INSENSITIVE;
3352 attr.SecurityDescriptor = NULL;
3353 attr.SecurityQualityOfService = NULL;
3354 RtlInitUnicodeString( &name_str, sessionW );
3356 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3358 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3360 query_dword_option( hkey, critsectW, &value );
3361 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3363 query_dword_option( hkey, heapresW, &value );
3364 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3366 query_dword_option( hkey, heapcommitW, &value );
3367 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3369 query_dword_option( hkey, decommittotalW, &value );
3370 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3372 query_dword_option( hkey, decommitfreeW, &value );
3373 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3375 NtClose( hkey );
3379 /******************************************************************
3380 * LdrInitializeThunk (NTDLL.@)
3383 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3384 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3386 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3387 NTSTATUS status;
3388 WINE_MODREF *wm;
3389 PEB *peb = NtCurrentTeb()->Peb;
3391 kernel32_start_process = kernel_start;
3393 /* allocate the modref for the main exe (if not already done) */
3394 wm = get_modref( peb->ImageBaseAddress );
3395 assert( wm );
3396 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3398 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3399 exit(1);
3402 peb->LoaderLock = &loader_section;
3403 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3404 if (!peb->ProcessParameters->WindowTitle.Buffer)
3405 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3406 version_init( wm->ldr.FullDllName.Buffer );
3407 virtual_set_large_address_space();
3409 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3410 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3411 heap_set_debug_flags( GetProcessHeap() );
3413 /* the main exe needs to be the first in the load order list */
3414 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3415 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3416 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3417 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3419 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL )) != STATUS_SUCCESS)
3421 ERR( "Main exe initialization for %s failed, status %x\n",
3422 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3423 NtTerminateProcess( GetCurrentProcess(), status );
3425 server_init_process_done();
3429 /***********************************************************************
3430 * RtlImageDirectoryEntryToData (NTDLL.@)
3432 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3434 const IMAGE_NT_HEADERS *nt;
3435 DWORD addr;
3437 if ((ULONG_PTR)module & 1) image = FALSE; /* mapped as data file */
3438 module = (HMODULE)((ULONG_PTR)module & ~3);
3439 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3440 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3442 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3444 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3445 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3446 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3447 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3449 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3451 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3453 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3454 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3455 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3456 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3458 else return NULL;
3460 /* not mapped as image, need to find the section containing the virtual address */
3461 return RtlImageRvaToVa( nt, module, addr, NULL );
3465 /***********************************************************************
3466 * RtlImageRvaToSection (NTDLL.@)
3468 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3469 HMODULE module, DWORD rva )
3471 int i;
3472 const IMAGE_SECTION_HEADER *sec;
3474 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3475 nt->FileHeader.SizeOfOptionalHeader);
3476 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3478 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3479 return (PIMAGE_SECTION_HEADER)sec;
3481 return NULL;
3485 /***********************************************************************
3486 * RtlImageRvaToVa (NTDLL.@)
3488 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3489 DWORD rva, IMAGE_SECTION_HEADER **section )
3491 IMAGE_SECTION_HEADER *sec;
3493 if (section && *section) /* try this section first */
3495 sec = *section;
3496 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3497 goto found;
3499 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3500 found:
3501 if (section) *section = sec;
3502 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3506 /***********************************************************************
3507 * RtlPcToFileHeader (NTDLL.@)
3509 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3511 LDR_MODULE *module;
3512 PVOID ret = NULL;
3514 RtlEnterCriticalSection( &loader_section );
3515 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3516 RtlLeaveCriticalSection( &loader_section );
3517 *address = ret;
3518 return ret;
3522 /***********************************************************************
3523 * NtLoadDriver (NTDLL.@)
3524 * ZwLoadDriver (NTDLL.@)
3526 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3528 FIXME("(%p), stub!\n",DriverServiceName);
3529 return STATUS_NOT_IMPLEMENTED;
3533 /***********************************************************************
3534 * NtUnloadDriver (NTDLL.@)
3535 * ZwUnloadDriver (NTDLL.@)
3537 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3539 FIXME("(%p), stub!\n",DriverServiceName);
3540 return STATUS_NOT_IMPLEMENTED;
3544 /******************************************************************
3545 * DllMain (NTDLL.@)
3547 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3549 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3550 return TRUE;
3554 /***********************************************************************
3555 * __wine_process_init
3557 void __wine_process_init(void)
3559 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3561 WINE_MODREF *wm;
3562 NTSTATUS status;
3563 ANSI_STRING func_name;
3564 UNICODE_STRING nt_name;
3565 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3567 thread_init();
3569 /* retrieve current umask */
3570 FILE_umask = umask(0777);
3571 umask( FILE_umask );
3573 load_global_options();
3575 /* setup the load callback and create ntdll modref */
3576 wine_dll_set_callback( load_builtin_callback );
3578 RtlInitUnicodeString( &nt_name, kernel32W );
3579 if ((status = load_builtin_dll( NULL, &nt_name, 0, 0, &wm )) != STATUS_SUCCESS)
3581 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3582 exit(1);
3584 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3585 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3586 0, (void **)&init_func )) != STATUS_SUCCESS)
3588 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3589 exit(1);
3591 init_func();