comctl32/tests: Replace asserts with regular test checks for Edit tests.
[wine.git] / dlls / ntdll / loader.c
blob77a16b3e3bfddbb7e5f9d6a75774d1e94aaebece
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/server.h"
44 #include "ntdll_misc.h"
45 #include "ddk/wdm.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 WINE_DECLARE_DEBUG_CHANNEL(snoop);
50 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
51 WINE_DECLARE_DEBUG_CHANNEL(imports);
53 #ifdef _WIN64
54 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
55 #endif
56 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
57 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
59 /* we don't want to include winuser.h */
60 #define RT_MANIFEST ((ULONG_PTR)24)
61 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
63 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
64 typedef void (CALLBACK *LDRENUMPROC)(LDR_MODULE *, void *, BOOLEAN *);
66 static BOOL imports_fixup_done = FALSE; /* set once the imports have been fixed up, before attaching them */
67 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
68 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
70 static const char * const reason_names[] =
72 "PROCESS_DETACH",
73 "PROCESS_ATTACH",
74 "THREAD_ATTACH",
75 "THREAD_DETACH",
76 NULL, NULL, NULL, NULL,
77 "WINE_PREATTACH"
80 static const WCHAR dllW[] = {'.','d','l','l',0};
82 /* internal representation of 32bit modules. per process. */
83 typedef struct _wine_modref
85 LDR_MODULE ldr;
86 int nDeps;
87 struct _wine_modref **deps;
88 } WINE_MODREF;
90 /* info about the current builtin dll load */
91 /* used to keep track of things across the register_dll constructor call */
92 struct builtin_load_info
94 const WCHAR *load_path;
95 const WCHAR *filename;
96 NTSTATUS status;
97 WINE_MODREF *wm;
100 static struct builtin_load_info default_load_info;
101 static struct builtin_load_info *builtin_load_info = &default_load_info;
103 static HANDLE main_exe_file;
104 static UINT tls_module_count; /* number of modules with TLS directory */
105 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
106 LIST_ENTRY tls_links = { &tls_links, &tls_links };
108 static RTL_CRITICAL_SECTION loader_section;
109 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
111 0, 0, &loader_section,
112 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
113 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
115 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
117 static WINE_MODREF *cached_modref;
118 static WINE_MODREF *current_modref;
119 static WINE_MODREF *last_failed_modref;
121 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
122 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
123 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
124 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
125 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
126 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
128 /* convert PE image VirtualAddress to Real Address */
129 static inline void *get_rva( HMODULE module, DWORD va )
131 return (void *)((char *)module + va);
134 /* check whether the file name contains a path */
135 static inline BOOL contains_path( LPCWSTR name )
137 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
140 /* convert from straight ASCII to Unicode without depending on the current codepage */
141 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
143 while (len--) *dst++ = (unsigned char)*src++;
147 /*************************************************************************
148 * call_dll_entry_point
150 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
151 * their entry point, so we need a small asm wrapper. Testing indicates
152 * that only modifying esi leads to a crash, so use this one to backup
153 * ebp while running the dll entry proc.
155 #ifdef __i386__
156 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
157 __ASM_GLOBAL_FUNC(call_dll_entry_point,
158 "pushl %ebp\n\t"
159 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
160 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
161 "movl %esp,%ebp\n\t"
162 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
163 "pushl %ebx\n\t"
164 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
165 "pushl %esi\n\t"
166 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
167 "pushl %edi\n\t"
168 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
169 "movl %ebp,%esi\n\t"
170 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
171 "pushl 20(%ebp)\n\t"
172 "pushl 16(%ebp)\n\t"
173 "pushl 12(%ebp)\n\t"
174 "movl 8(%ebp),%eax\n\t"
175 "call *%eax\n\t"
176 "movl %esi,%ebp\n\t"
177 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
178 "leal -12(%ebp),%esp\n\t"
179 "popl %edi\n\t"
180 __ASM_CFI(".cfi_same_value %edi\n\t")
181 "popl %esi\n\t"
182 __ASM_CFI(".cfi_same_value %esi\n\t")
183 "popl %ebx\n\t"
184 __ASM_CFI(".cfi_same_value %ebx\n\t")
185 "popl %ebp\n\t"
186 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
187 __ASM_CFI(".cfi_same_value %ebp\n\t")
188 "ret" )
189 #else /* __i386__ */
190 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
191 UINT reason, void *reserved )
193 return proc( module, reason, reserved );
195 #endif /* __i386__ */
198 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
199 /*************************************************************************
200 * stub_entry_point
202 * Entry point for stub functions.
204 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
206 EXCEPTION_RECORD rec;
208 rec.ExceptionCode = EXCEPTION_WINE_STUB;
209 rec.ExceptionFlags = EH_NONCONTINUABLE;
210 rec.ExceptionRecord = NULL;
211 rec.ExceptionAddress = ret_addr;
212 rec.NumberParameters = 2;
213 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
214 rec.ExceptionInformation[1] = (ULONG_PTR)name;
215 for (;;) RtlRaiseException( &rec );
219 #include "pshpack1.h"
220 #ifdef __i386__
221 struct stub
223 BYTE pushl1; /* pushl $name */
224 const char *name;
225 BYTE pushl2; /* pushl $dll */
226 const char *dll;
227 BYTE call; /* call stub_entry_point */
228 DWORD entry;
230 #elif defined(__arm__)
231 struct stub
233 DWORD ldr_r0; /* ldr r0, $dll */
234 DWORD ldr_r1; /* ldr r1, $name */
235 DWORD mov_r2_lr; /* mov r2, lr */
236 DWORD ldr_pc_pc; /* ldr pc, [pc, #4] */
237 const char *dll;
238 const char *name;
239 const void* entry;
241 #elif defined(__aarch64__)
242 struct stub
244 DWORD ldr_x0; /* ldr x0, $dll */
245 DWORD ldr_x1; /* ldr x1, $name */
246 DWORD mov_x2_lr; /* mov x2, lr */
247 DWORD ldr_x16; /* ldr x16, $entry */
248 DWORD br_x16; /* br x16 */
249 const char *dll;
250 const char *name;
251 const void *entry;
253 #else
254 struct stub
256 BYTE movq_rdi[2]; /* movq $dll,%rdi */
257 const char *dll;
258 BYTE movq_rsi[2]; /* movq $name,%rsi */
259 const char *name;
260 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
261 BYTE movq_rax[2]; /* movq $entry, %rax */
262 const void* entry;
263 BYTE jmpq_rax[2]; /* jmp %rax */
265 #endif
266 #include "poppack.h"
268 /*************************************************************************
269 * allocate_stub
271 * Allocate a stub entry point.
273 static ULONG_PTR allocate_stub( const char *dll, const char *name )
275 #define MAX_SIZE 65536
276 static struct stub *stubs;
277 static unsigned int nb_stubs;
278 struct stub *stub;
280 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
282 if (!stubs)
284 SIZE_T size = MAX_SIZE;
285 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
286 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
287 return 0xdeadbeef;
289 stub = &stubs[nb_stubs++];
290 #ifdef __i386__
291 stub->pushl1 = 0x68; /* pushl $name */
292 stub->name = name;
293 stub->pushl2 = 0x68; /* pushl $dll */
294 stub->dll = dll;
295 stub->call = 0xe8; /* call stub_entry_point */
296 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
297 #elif defined(__arm__)
298 stub->ldr_r0 = 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
299 stub->ldr_r1 = 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
300 stub->mov_r2_lr = 0xe1a0200e; /* mov r2, lr */
301 stub->ldr_pc_pc = 0xe59ff004; /* ldr pc, [pc, #4] */
302 stub->dll = dll;
303 stub->name = name;
304 stub->entry = stub_entry_point;
305 #elif defined(__aarch64__)
306 stub->ldr_x0 = 0x580000a0; /* ldr x0, #20 ($dll) */
307 stub->ldr_x1 = 0x580000c1; /* ldr x1, #24 ($name) */
308 stub->mov_x2_lr = 0xaa1e03e2; /* mov x2, lr */
309 stub->ldr_x16 = 0x580000d0; /* ldr x16, #24 ($entry) */
310 stub->br_x16 = 0xd61f0200; /* br x16 */
311 stub->dll = dll;
312 stub->name = name;
313 stub->entry = stub_entry_point;
314 #else
315 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
316 stub->movq_rdi[1] = 0xbf;
317 stub->dll = dll;
318 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
319 stub->movq_rsi[1] = 0xbe;
320 stub->name = name;
321 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
322 stub->movq_rsp_rdx[1] = 0x8b;
323 stub->movq_rsp_rdx[2] = 0x14;
324 stub->movq_rsp_rdx[3] = 0x24;
325 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
326 stub->movq_rax[1] = 0xb8;
327 stub->entry = stub_entry_point;
328 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
329 stub->jmpq_rax[1] = 0xe0;
330 #endif
331 return (ULONG_PTR)stub;
334 #else /* __i386__ */
335 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
336 #endif /* __i386__ */
339 /*************************************************************************
340 * get_modref
342 * Looks for the referenced HMODULE in the current process
343 * The loader_section must be locked while calling this function.
345 static WINE_MODREF *get_modref( HMODULE hmod )
347 PLIST_ENTRY mark, entry;
348 PLDR_MODULE mod;
350 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
352 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
353 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
355 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
356 if (mod->BaseAddress == hmod)
357 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
359 return NULL;
363 /**********************************************************************
364 * find_basename_module
366 * Find a module from its base name.
367 * The loader_section must be locked while calling this function
369 static WINE_MODREF *find_basename_module( LPCWSTR name )
371 PLIST_ENTRY mark, entry;
373 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
374 return cached_modref;
376 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
377 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
379 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
380 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
382 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
383 return cached_modref;
386 return NULL;
390 /**********************************************************************
391 * find_fullname_module
393 * Find a module from its full path name.
394 * The loader_section must be locked while calling this function
396 static WINE_MODREF *find_fullname_module( LPCWSTR name )
398 PLIST_ENTRY mark, entry;
400 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
401 return cached_modref;
403 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
404 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
406 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
407 if (!strcmpiW( name, mod->FullDllName.Buffer ))
409 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
410 return cached_modref;
413 return NULL;
417 /*************************************************************************
418 * find_forwarded_export
420 * Find the final function pointer for a forwarded function.
421 * The loader_section must be locked while calling this function.
423 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
425 const IMAGE_EXPORT_DIRECTORY *exports;
426 DWORD exp_size;
427 WINE_MODREF *wm;
428 WCHAR mod_name[32];
429 const char *end = strrchr(forward, '.');
430 FARPROC proc = NULL;
432 if (!end) return NULL;
433 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
434 ascii_to_unicode( mod_name, forward, end - forward );
435 mod_name[end - forward] = 0;
436 if (!strchrW( mod_name, '.' ))
438 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
439 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
442 if (!(wm = find_basename_module( mod_name )))
444 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
445 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
446 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
448 if (!imports_fixup_done && current_modref)
450 WINE_MODREF **deps;
451 if (current_modref->nDeps)
452 deps = RtlReAllocateHeap( GetProcessHeap(), 0, current_modref->deps,
453 (current_modref->nDeps + 1) * sizeof(*deps) );
454 else
455 deps = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps) );
456 if (deps)
458 deps[current_modref->nDeps++] = wm;
459 current_modref->deps = deps;
462 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
464 LdrUnloadDll( wm->ldr.BaseAddress );
465 wm = NULL;
469 if (!wm)
471 ERR( "module not found for forward '%s' used by %s\n",
472 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
473 return NULL;
476 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
477 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
479 const char *name = end + 1;
480 if (*name == '#') /* ordinal */
481 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
482 else
483 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
486 if (!proc)
488 ERR("function not found for forward '%s' used by %s."
489 " If you are using builtin %s, try using the native one instead.\n",
490 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
491 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
493 return proc;
497 /*************************************************************************
498 * find_ordinal_export
500 * Find an exported function by ordinal.
501 * The exports base must have been subtracted from the ordinal already.
502 * The loader_section must be locked while calling this function.
504 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
505 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
507 FARPROC proc;
508 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
510 if (ordinal >= exports->NumberOfFunctions)
512 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
513 return NULL;
515 if (!functions[ordinal]) return NULL;
517 proc = get_rva( module, functions[ordinal] );
519 /* if the address falls into the export dir, it's a forward */
520 if (((const char *)proc >= (const char *)exports) &&
521 ((const char *)proc < (const char *)exports + exp_size))
522 return find_forwarded_export( module, (const char *)proc, load_path );
524 if (TRACE_ON(snoop))
526 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
527 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
529 if (TRACE_ON(relay))
531 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
532 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
534 return proc;
538 /*************************************************************************
539 * find_named_export
541 * Find an exported function by name.
542 * The loader_section must be locked while calling this function.
544 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
545 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
547 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
548 const DWORD *names = get_rva( module, exports->AddressOfNames );
549 int min = 0, max = exports->NumberOfNames - 1;
551 /* first check the hint */
552 if (hint >= 0 && hint <= max)
554 char *ename = get_rva( module, names[hint] );
555 if (!strcmp( ename, name ))
556 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
559 /* then do a binary search */
560 while (min <= max)
562 int res, pos = (min + max) / 2;
563 char *ename = get_rva( module, names[pos] );
564 if (!(res = strcmp( ename, name )))
565 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
566 if (res > 0) max = pos - 1;
567 else min = pos + 1;
569 return NULL;
574 /*************************************************************************
575 * import_dll
577 * Import the dll specified by the given import descriptor.
578 * The loader_section must be locked while calling this function.
580 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
582 NTSTATUS status;
583 WINE_MODREF *wmImp;
584 HMODULE imp_mod;
585 const IMAGE_EXPORT_DIRECTORY *exports;
586 DWORD exp_size;
587 const IMAGE_THUNK_DATA *import_list;
588 IMAGE_THUNK_DATA *thunk_list;
589 WCHAR buffer[32];
590 const char *name = get_rva( module, descr->Name );
591 DWORD len = strlen(name);
592 PVOID protect_base;
593 SIZE_T protect_size = 0;
594 DWORD protect_old;
596 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
597 if (descr->u.OriginalFirstThunk)
598 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
599 else
600 import_list = thunk_list;
602 if (!import_list->u1.Ordinal)
604 WARN( "Skipping unused import %s\n", name );
605 *pwm = NULL;
606 return TRUE;
609 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
611 if (len * sizeof(WCHAR) < sizeof(buffer))
613 ascii_to_unicode( buffer, name, len );
614 buffer[len] = 0;
615 status = load_dll( load_path, buffer, 0, &wmImp );
617 else /* need to allocate a larger buffer */
619 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
620 if (!ptr) return FALSE;
621 ascii_to_unicode( ptr, name, len );
622 ptr[len] = 0;
623 status = load_dll( load_path, ptr, 0, &wmImp );
624 RtlFreeHeap( GetProcessHeap(), 0, ptr );
627 if (status)
629 if (status == STATUS_DLL_NOT_FOUND)
630 ERR("Library %s (which is needed by %s) not found\n",
631 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
632 else
633 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
634 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
635 return FALSE;
638 /* unprotect the import address table since it can be located in
639 * readonly section */
640 while (import_list[protect_size].u1.Ordinal) protect_size++;
641 protect_base = thunk_list;
642 protect_size *= sizeof(*thunk_list);
643 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
644 &protect_size, PAGE_READWRITE, &protect_old );
646 imp_mod = wmImp->ldr.BaseAddress;
647 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
649 if (!exports)
651 /* set all imported function to deadbeef */
652 while (import_list->u1.Ordinal)
654 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
656 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
657 WARN("No implementation for %s.%d", name, ordinal );
658 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
660 else
662 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
663 WARN("No implementation for %s.%s", name, pe_name->Name );
664 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
666 WARN(" imported from %s, allocating stub %p\n",
667 debugstr_w(current_modref->ldr.FullDllName.Buffer),
668 (void *)thunk_list->u1.Function );
669 import_list++;
670 thunk_list++;
672 goto done;
675 while (import_list->u1.Ordinal)
677 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
679 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
681 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
682 ordinal - exports->Base, load_path );
683 if (!thunk_list->u1.Function)
685 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
686 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
687 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
688 (void *)thunk_list->u1.Function );
690 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
692 else /* import by name */
694 IMAGE_IMPORT_BY_NAME *pe_name;
695 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
696 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
697 (const char*)pe_name->Name,
698 pe_name->Hint, load_path );
699 if (!thunk_list->u1.Function)
701 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
702 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
703 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
704 (void *)thunk_list->u1.Function );
706 TRACE_(imports)("--- %s %s.%d = %p\n",
707 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
709 import_list++;
710 thunk_list++;
713 done:
714 /* restore old protection of the import address table */
715 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
716 *pwm = wmImp;
717 return TRUE;
721 /***********************************************************************
722 * create_module_activation_context
724 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
726 NTSTATUS status;
727 LDR_RESOURCE_INFO info;
728 const IMAGE_RESOURCE_DATA_ENTRY *entry;
730 info.Type = RT_MANIFEST;
731 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
732 info.Language = 0;
733 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
735 ACTCTXW ctx;
736 ctx.cbSize = sizeof(ctx);
737 ctx.lpSource = NULL;
738 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
739 ctx.hModule = module->BaseAddress;
740 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
741 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
743 return status;
747 /*************************************************************************
748 * is_dll_native_subsystem
750 * Check if dll is a proper native driver.
751 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
752 * while being perfectly normal DLLs. This heuristic should catch such breakages.
754 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
756 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
757 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
758 const IMAGE_IMPORT_DESCRIPTOR *imports;
759 DWORD i, size;
760 WCHAR buffer[16];
762 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
763 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
765 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
766 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
768 for (i = 0; imports[i].Name; i++)
770 const char *name = get_rva( module, imports[i].Name );
771 DWORD len = strlen(name);
772 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
773 ascii_to_unicode( buffer, name, len + 1 );
774 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
776 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
777 return FALSE;
781 return TRUE;
784 /*************************************************************************
785 * alloc_tls_slot
787 * Allocate a TLS slot for a newly-loaded module.
788 * The loader_section must be locked while calling this function.
790 static SHORT alloc_tls_slot( LDR_MODULE *mod )
792 const IMAGE_TLS_DIRECTORY *dir;
793 ULONG i, size;
794 void *new_ptr;
795 LIST_ENTRY *entry;
797 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
798 return -1;
800 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
801 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
803 for (i = 0; i < tls_module_count; i++)
805 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
806 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
807 break;
810 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
811 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
812 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
814 if (i == tls_module_count)
816 UINT new_count = max( 32, tls_module_count * 2 );
818 if (!tls_dirs)
819 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
820 else
821 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
822 new_count * sizeof(*tls_dirs) );
823 if (!new_ptr) return -1;
825 /* resize the pointer block in all running threads */
826 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
828 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
829 void **old = teb->ThreadLocalStoragePointer;
830 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
832 if (!new) return -1;
833 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
834 teb->ThreadLocalStoragePointer = new;
835 #if defined(__APPLE__) && defined(__x86_64__)
836 if (teb->Reserved5[0])
837 ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
838 #endif
839 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
840 /* FIXME: can't free old block here, should be freed at thread exit */
843 tls_dirs = new_ptr;
844 tls_module_count = new_count;
847 /* allocate the data block in all running threads */
848 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
850 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
852 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
853 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
854 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
856 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
857 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
859 RtlFreeHeap( GetProcessHeap(), 0,
860 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
863 *(DWORD *)dir->AddressOfIndex = i;
864 tls_dirs[i] = *dir;
865 return i;
869 /*************************************************************************
870 * free_tls_slot
872 * Free the module TLS slot on unload.
873 * The loader_section must be locked while calling this function.
875 static void free_tls_slot( LDR_MODULE *mod )
877 ULONG i = (USHORT)mod->TlsIndex;
879 if (mod->TlsIndex == -1) return;
880 assert( i < tls_module_count );
881 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
885 /****************************************************************
886 * fixup_imports
888 * Fixup all imports of a given module.
889 * The loader_section must be locked while calling this function.
891 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
893 int i, nb_imports;
894 const IMAGE_IMPORT_DESCRIPTOR *imports;
895 WINE_MODREF *prev, *imp;
896 DWORD size;
897 NTSTATUS status;
898 ULONG_PTR cookie;
900 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
901 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
903 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
905 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
906 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
907 return STATUS_SUCCESS;
909 nb_imports = 0;
910 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
912 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
914 if (!create_module_activation_context( &wm->ldr ))
915 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
917 /* Allocate module dependency list */
918 wm->nDeps = nb_imports;
919 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
921 /* load the imported modules. They are automatically
922 * added to the modref list of the process.
924 prev = current_modref;
925 current_modref = wm;
926 status = STATUS_SUCCESS;
927 for (i = 0; i < nb_imports; i++)
929 if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &imp ))
931 imp = NULL;
932 status = STATUS_DLL_NOT_FOUND;
934 wm->deps[i] = imp;
936 current_modref = prev;
937 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
938 return status;
942 /*************************************************************************
943 * alloc_module
945 * Allocate a WINE_MODREF structure and add it to the process list
946 * The loader_section must be locked while calling this function.
948 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
950 WINE_MODREF *wm;
951 const WCHAR *p;
952 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
954 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
956 wm->nDeps = 0;
957 wm->deps = NULL;
959 wm->ldr.BaseAddress = hModule;
960 wm->ldr.EntryPoint = NULL;
961 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
962 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
963 wm->ldr.TlsIndex = -1;
964 wm->ldr.LoadCount = 1;
965 wm->ldr.SectionHandle = NULL;
966 wm->ldr.CheckSum = 0;
967 wm->ldr.TimeDateStamp = 0;
968 wm->ldr.ActivationContext = 0;
970 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
971 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
972 else p = wm->ldr.FullDllName.Buffer;
973 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
975 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
977 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
978 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
979 if (nt->OptionalHeader.AddressOfEntryPoint)
980 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
983 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
984 &wm->ldr.InLoadOrderModuleList);
985 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
986 &wm->ldr.InMemoryOrderModuleList);
988 /* wait until init is called for inserting into this list */
989 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
990 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
992 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
994 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
995 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
996 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
998 return wm;
1002 /*************************************************************************
1003 * alloc_thread_tls
1005 * Allocate the per-thread structure for module TLS storage.
1007 static NTSTATUS alloc_thread_tls(void)
1009 void **pointers;
1010 UINT i, size;
1012 if (!tls_module_count) return STATUS_SUCCESS;
1014 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1015 tls_module_count * sizeof(*pointers) )))
1016 return STATUS_NO_MEMORY;
1018 for (i = 0; i < tls_module_count; i++)
1020 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1022 if (!dir) continue;
1023 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1024 if (!size && !dir->SizeOfZeroFill) continue;
1026 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1028 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1029 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1030 return STATUS_NO_MEMORY;
1032 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1033 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1035 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1036 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1038 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1039 #if defined(__APPLE__) && defined(__x86_64__)
1040 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
1042 : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
1043 #endif
1044 return STATUS_SUCCESS;
1048 /*************************************************************************
1049 * call_tls_callbacks
1051 static void call_tls_callbacks( HMODULE module, UINT reason )
1053 const IMAGE_TLS_DIRECTORY *dir;
1054 const PIMAGE_TLS_CALLBACK *callback;
1055 ULONG dirsize;
1057 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1058 if (!dir || !dir->AddressOfCallBacks) return;
1060 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1062 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1063 *callback, module, reason_names[reason] );
1064 __TRY
1066 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1068 __EXCEPT_ALL
1070 TRACE_(relay)("\1exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1071 callback, module, reason_names[reason] );
1072 return;
1074 __ENDTRY
1075 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1076 *callback, module, reason_names[reason] );
1081 /*************************************************************************
1082 * MODULE_InitDLL
1084 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1086 WCHAR mod_name[32];
1087 NTSTATUS status = STATUS_SUCCESS;
1088 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1089 void *module = wm->ldr.BaseAddress;
1090 BOOL retv = FALSE;
1092 /* Skip calls for modules loaded with special load flags */
1094 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1095 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1096 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1098 if (TRACE_ON(relay))
1100 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1101 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1102 mod_name[len / sizeof(WCHAR)] = 0;
1103 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1104 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1106 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1107 reason_names[reason], lpReserved );
1109 __TRY
1111 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1112 if (!retv)
1113 status = STATUS_DLL_INIT_FAILED;
1115 __EXCEPT_ALL
1117 TRACE_(relay)("\1exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1118 entry, module, reason_names[reason], lpReserved );
1119 status = GetExceptionCode();
1121 __ENDTRY
1123 /* The state of the module list may have changed due to the call
1124 to the dll. We cannot assume that this module has not been
1125 deleted. */
1126 if (TRACE_ON(relay))
1127 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1128 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1129 else
1130 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1132 return status;
1136 /*************************************************************************
1137 * process_attach
1139 * Send the process attach notification to all DLLs the given module
1140 * depends on (recursively). This is somewhat complicated due to the fact that
1142 * - we have to respect the module dependencies, i.e. modules implicitly
1143 * referenced by another module have to be initialized before the module
1144 * itself can be initialized
1146 * - the initialization routine of a DLL can itself call LoadLibrary,
1147 * thereby introducing a whole new set of dependencies (even involving
1148 * the 'old' modules) at any time during the whole process
1150 * (Note that this routine can be recursively entered not only directly
1151 * from itself, but also via LoadLibrary from one of the called initialization
1152 * routines.)
1154 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1155 * the process *detach* notifications to be sent in the correct order.
1156 * This must not only take into account module dependencies, but also
1157 * 'hidden' dependencies created by modules calling LoadLibrary in their
1158 * attach notification routine.
1160 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1161 * list after the attach notification has returned. This implies that the
1162 * detach notifications are called in the reverse of the sequence the attach
1163 * notifications *returned*.
1165 * The loader_section must be locked while calling this function.
1167 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1169 NTSTATUS status = STATUS_SUCCESS;
1170 ULONG_PTR cookie;
1171 int i;
1173 if (process_detaching) return status;
1175 /* prevent infinite recursion in case of cyclical dependencies */
1176 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1177 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1178 return status;
1180 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1182 /* Tag current MODREF to prevent recursive loop */
1183 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1184 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1185 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1187 /* Recursively attach all DLLs this one depends on */
1188 for ( i = 0; i < wm->nDeps; i++ )
1190 if (!wm->deps[i]) continue;
1191 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1194 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1195 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1196 &wm->ldr.InInitializationOrderModuleList);
1198 /* Call DLL entry point */
1199 if (status == STATUS_SUCCESS)
1201 WINE_MODREF *prev = current_modref;
1202 current_modref = wm;
1203 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1204 if (status == STATUS_SUCCESS)
1205 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1206 else
1208 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1209 /* point to the name so LdrInitializeThunk can print it */
1210 last_failed_modref = wm;
1211 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1213 current_modref = prev;
1216 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1217 /* Remove recursion flag */
1218 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1220 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1221 return status;
1225 /**********************************************************************
1226 * attach_implicitly_loaded_dlls
1228 * Attach to the (builtin) dlls that have been implicitly loaded because
1229 * of a dependency at the Unix level, but not imported at the Win32 level.
1231 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1233 for (;;)
1235 PLIST_ENTRY mark, entry;
1237 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1238 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1240 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1242 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1243 TRACE( "found implicitly loaded %s, attaching to it\n",
1244 debugstr_w(mod->BaseDllName.Buffer));
1245 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1246 break; /* restart the search from the start */
1248 if (entry == mark) break; /* nothing found */
1253 /*************************************************************************
1254 * process_detach
1256 * Send DLL process detach notifications. See the comment about calling
1257 * sequence at process_attach.
1259 static void process_detach(void)
1261 PLIST_ENTRY mark, entry;
1262 PLDR_MODULE mod;
1264 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1267 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1269 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1270 InInitializationOrderModuleList);
1271 /* Check whether to detach this DLL */
1272 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1273 continue;
1274 if ( mod->LoadCount && !process_detaching )
1275 continue;
1277 /* Call detach notification */
1278 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1279 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1280 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1282 /* Restart at head of WINE_MODREF list, as entries might have
1283 been added and/or removed while performing the call ... */
1284 break;
1286 } while (entry != mark);
1289 /*************************************************************************
1290 * thread_attach
1292 * Send DLL thread attach notifications. These are sent in the
1293 * reverse sequence of process detach notification.
1294 * The loader_section must be locked while calling this function.
1296 static void thread_attach(void)
1298 PLIST_ENTRY mark, entry;
1299 PLDR_MODULE mod;
1301 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1302 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1304 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1305 InInitializationOrderModuleList);
1306 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1307 continue;
1308 if ( mod->Flags & LDR_NO_DLL_CALLS )
1309 continue;
1311 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1315 /******************************************************************
1316 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1319 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1321 WINE_MODREF *wm;
1322 NTSTATUS ret = STATUS_SUCCESS;
1324 RtlEnterCriticalSection( &loader_section );
1326 wm = get_modref( hModule );
1327 if (!wm || wm->ldr.TlsIndex != -1)
1328 ret = STATUS_DLL_NOT_FOUND;
1329 else
1330 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1332 RtlLeaveCriticalSection( &loader_section );
1334 return ret;
1337 /******************************************************************
1338 * LdrFindEntryForAddress (NTDLL.@)
1340 * The loader_section must be locked while calling this function
1342 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1344 PLIST_ENTRY mark, entry;
1345 PLDR_MODULE mod;
1347 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1348 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1350 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1351 if (mod->BaseAddress <= addr &&
1352 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1354 *pmod = mod;
1355 return STATUS_SUCCESS;
1358 return STATUS_NO_MORE_ENTRIES;
1361 /******************************************************************
1362 * LdrEnumerateLoadedModules (NTDLL.@)
1364 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1366 LIST_ENTRY *mark, *entry;
1367 LDR_MODULE *mod;
1368 BOOLEAN stop = FALSE;
1370 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1372 if (unknown || !callback)
1373 return STATUS_INVALID_PARAMETER;
1375 RtlEnterCriticalSection( &loader_section );
1377 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1378 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1380 mod = CONTAINING_RECORD( entry, LDR_MODULE, InMemoryOrderModuleList );
1381 callback( mod, context, &stop );
1382 if (stop) break;
1385 RtlLeaveCriticalSection( &loader_section );
1386 return STATUS_SUCCESS;
1389 /******************************************************************
1390 * LdrLockLoaderLock (NTDLL.@)
1392 * Note: some flags are not implemented.
1393 * Flag 0x01 is used to raise exceptions on errors.
1395 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1397 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1399 if (result) *result = 0;
1400 if (magic) *magic = 0;
1401 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1402 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1403 if (!magic) return STATUS_INVALID_PARAMETER_3;
1405 if (flags & 0x2)
1407 if (!RtlTryEnterCriticalSection( &loader_section ))
1409 *result = 2;
1410 return STATUS_SUCCESS;
1412 *result = 1;
1414 else
1416 RtlEnterCriticalSection( &loader_section );
1417 if (result) *result = 1;
1419 *magic = GetCurrentThreadId();
1420 return STATUS_SUCCESS;
1424 /******************************************************************
1425 * LdrUnlockLoaderUnlock (NTDLL.@)
1427 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1429 if (magic)
1431 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1432 RtlLeaveCriticalSection( &loader_section );
1434 return STATUS_SUCCESS;
1438 /******************************************************************
1439 * LdrGetProcedureAddress (NTDLL.@)
1441 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1442 ULONG ord, PVOID *address)
1444 IMAGE_EXPORT_DIRECTORY *exports;
1445 DWORD exp_size;
1446 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1448 RtlEnterCriticalSection( &loader_section );
1450 /* check if the module itself is invalid to return the proper error */
1451 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1452 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1453 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1455 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1456 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1457 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1458 if (proc)
1460 *address = proc;
1461 ret = STATUS_SUCCESS;
1465 RtlLeaveCriticalSection( &loader_section );
1466 return ret;
1470 /***********************************************************************
1471 * is_fake_dll
1473 * Check if a loaded native dll is a Wine fake dll.
1475 static BOOL is_fake_dll( HANDLE handle )
1477 static const char fakedll_signature[] = "Wine placeholder DLL";
1478 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1479 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1480 IO_STATUS_BLOCK io;
1481 LARGE_INTEGER offset;
1483 offset.QuadPart = 0;
1484 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1485 if (io.Information < sizeof(buffer)) return FALSE;
1486 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1487 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1488 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1489 return FALSE;
1493 /***********************************************************************
1494 * get_builtin_fullname
1496 * Build the full pathname for a builtin dll.
1498 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1500 static const WCHAR soW[] = {'.','s','o',0};
1501 WCHAR *p, *fullname;
1502 size_t i, len = strlen(filename);
1504 /* check if path can correspond to the dll we have */
1505 if (path && (p = strrchrW( path, '\\' )))
1507 p++;
1508 for (i = 0; i < len; i++)
1509 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1510 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1512 /* the filename matches, use path as the full path */
1513 len += p - path;
1514 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1516 memcpy( fullname, path, len * sizeof(WCHAR) );
1517 fullname[len] = 0;
1519 return fullname;
1523 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1524 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1526 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1527 p = fullname + system_dir.Length / sizeof(WCHAR);
1528 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1529 ascii_to_unicode( p, filename, len + 1 );
1531 return fullname;
1535 /*************************************************************************
1536 * is_16bit_builtin
1538 static BOOL is_16bit_builtin( HMODULE module )
1540 const IMAGE_EXPORT_DIRECTORY *exports;
1541 DWORD exp_size;
1543 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1544 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1545 return FALSE;
1547 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1551 /***********************************************************************
1552 * load_builtin_callback
1554 * Load a library in memory; callback function for wine_dll_register
1556 static void load_builtin_callback( void *module, const char *filename )
1558 static const WCHAR emptyW[1];
1559 IMAGE_NT_HEADERS *nt;
1560 WINE_MODREF *wm;
1561 WCHAR *fullname;
1562 const WCHAR *load_path;
1564 if (!module)
1566 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1567 return;
1569 if (!(nt = RtlImageNtHeader( module )))
1571 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1572 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1573 return;
1576 virtual_create_builtin_view( module );
1578 /* create the MODREF */
1580 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1582 ERR( "can't load %s\n", filename );
1583 builtin_load_info->status = STATUS_NO_MEMORY;
1584 return;
1587 wm = alloc_module( module, fullname );
1588 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1589 if (!wm)
1591 ERR( "can't load %s\n", filename );
1592 builtin_load_info->status = STATUS_NO_MEMORY;
1593 return;
1595 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1597 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1598 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1599 is_16bit_builtin( module ))
1601 /* fixup imports */
1603 load_path = builtin_load_info->load_path;
1604 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1605 if (!load_path) load_path = emptyW;
1606 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1608 /* the module has only be inserted in the load & memory order lists */
1609 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1610 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1611 /* FIXME: free the modref */
1612 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1613 return;
1617 builtin_load_info->wm = wm;
1618 TRACE( "loaded %s %p %p\n", filename, wm, module );
1620 /* send the DLL load event */
1622 SERVER_START_REQ( load_dll )
1624 req->base = wine_server_client_ptr( module );
1625 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1626 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1627 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1628 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1629 wine_server_call( req );
1631 SERVER_END_REQ;
1633 /* setup relay debugging entry points */
1634 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1638 /***********************************************************************
1639 * set_security_cookie
1641 * Create a random security cookie for buffer overflow protection. Make
1642 * sure it does not accidentally match the default cookie value.
1644 static void set_security_cookie( void *module, SIZE_T len )
1646 static ULONG seed;
1647 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1648 ULONG loadcfg_size;
1649 ULONG_PTR *cookie;
1651 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1652 if (!loadcfg) return;
1653 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1654 if (!loadcfg->SecurityCookie) return;
1655 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1656 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1658 WARN( "security cookie %p outside of image %p-%p\n",
1659 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1660 return;
1663 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1664 TRACE( "initializing security cookie %p\n", cookie );
1666 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1667 for (;;)
1669 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1670 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1671 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1672 *cookie = RtlRandom( &seed );
1673 #ifdef DEFAULT_SECURITY_COOKIE_64
1674 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1676 *cookie = RtlRandom( &seed );
1677 /* fill up, but keep the highest word clear */
1678 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1680 #endif
1681 else
1682 break;
1686 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1688 IMAGE_NT_HEADERS *nt;
1689 char *base;
1690 IMAGE_BASE_RELOCATION *rel, *end;
1691 const IMAGE_DATA_DIRECTORY *relocs;
1692 const IMAGE_SECTION_HEADER *sec;
1693 INT_PTR delta;
1694 ULONG protect_old[96], i;
1696 nt = RtlImageNtHeader( module );
1697 base = (char *)nt->OptionalHeader.ImageBase;
1699 assert( module != base );
1701 /* no relocations are performed on non page-aligned binaries */
1702 if (nt->OptionalHeader.SectionAlignment < page_size)
1703 return STATUS_SUCCESS;
1705 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1706 return STATUS_SUCCESS;
1708 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1710 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1712 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1713 base, module );
1714 return STATUS_CONFLICTING_ADDRESSES;
1717 if (!relocs->Size) return STATUS_SUCCESS;
1718 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1720 if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
1721 return STATUS_INVALID_IMAGE_FORMAT;
1723 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1724 nt->FileHeader.SizeOfOptionalHeader);
1725 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1727 void *addr = get_rva( module, sec[i].VirtualAddress );
1728 SIZE_T size = sec[i].SizeOfRawData;
1729 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1730 &size, PAGE_READWRITE, &protect_old[i] );
1733 TRACE( "relocating from %p-%p to %p-%p\n",
1734 base, base + len, module, (char *)module + len );
1736 rel = get_rva( module, relocs->VirtualAddress );
1737 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1738 delta = (char *)module - base;
1740 while (rel < end - 1 && rel->SizeOfBlock)
1742 if (rel->VirtualAddress >= len)
1744 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1745 return STATUS_ACCESS_VIOLATION;
1747 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1748 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1749 (USHORT *)(rel + 1), delta );
1750 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1753 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1755 void *addr = get_rva( module, sec[i].VirtualAddress );
1756 SIZE_T size = sec[i].SizeOfRawData;
1757 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1758 &size, protect_old[i], &protect_old[i] );
1761 return STATUS_SUCCESS;
1765 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
1766 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
1767 static BOOL is_valid_binary( const pe_image_info_t *info )
1769 #ifdef __i386__
1770 return info->machine == IMAGE_FILE_MACHINE_I386;
1771 #elif defined(__x86_64__)
1772 return info->machine == IMAGE_FILE_MACHINE_AMD64 || !info->contains_code;
1773 #elif defined(__arm__)
1774 return info->machine == IMAGE_FILE_MACHINE_ARM ||
1775 info->machine == IMAGE_FILE_MACHINE_THUMB ||
1776 info->machine == IMAGE_FILE_MACHINE_ARMNT;
1777 #elif defined(__aarch64__)
1778 return info->machine == IMAGE_FILE_MACHINE_ARM64 || !info->contains_code;
1779 #else
1780 return FALSE; /* no wow64 support on other platforms */
1781 #endif
1785 /******************************************************************************
1786 * load_native_dll (internal)
1788 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1789 DWORD flags, WINE_MODREF** pwm )
1791 void *module;
1792 HANDLE mapping;
1793 LARGE_INTEGER size;
1794 IMAGE_NT_HEADERS *nt;
1795 SIZE_T len = 0;
1796 WINE_MODREF *wm;
1797 NTSTATUS status;
1798 pe_image_info_t image_info;
1800 TRACE("Trying native dll %s\n", debugstr_w(name));
1802 size.QuadPart = 0;
1803 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
1804 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
1805 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1806 if (status != STATUS_SUCCESS) return status;
1808 module = NULL;
1809 status = virtual_map_section( mapping, &module, 0, 0, NULL, &len, PAGE_EXECUTE_READ, &image_info );
1810 NtClose( mapping );
1812 if ((status == STATUS_SUCCESS || status == STATUS_IMAGE_NOT_AT_BASE) &&
1813 !is_valid_binary( &image_info ))
1815 NtUnmapViewOfSection( NtCurrentProcess(), module );
1816 return STATUS_INVALID_IMAGE_FORMAT;
1819 /* perform base relocation, if necessary */
1821 if (status == STATUS_IMAGE_NOT_AT_BASE)
1822 status = perform_relocations( module, len );
1824 if (status != STATUS_SUCCESS)
1826 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1827 return status;
1830 /* create the MODREF */
1832 if (!(wm = alloc_module( module, name )))
1834 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1835 return STATUS_NO_MEMORY;
1838 set_security_cookie( module, len );
1840 /* fixup imports */
1842 nt = RtlImageNtHeader( module );
1844 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1845 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1846 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1848 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1850 /* the module has only be inserted in the load & memory order lists */
1851 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1852 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1854 /* FIXME: there are several more dangling references
1855 * left. Including dlls loaded by this dll before the
1856 * failed one. Unrolling is rather difficult with the
1857 * current structure and we can leave them lying
1858 * around with no problems, so we don't care.
1859 * As these might reference our wm, we don't free it.
1861 return status;
1865 /* send DLL load event */
1867 SERVER_START_REQ( load_dll )
1869 req->base = wine_server_client_ptr( module );
1870 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1871 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1872 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1873 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1874 wine_server_call( req );
1876 SERVER_END_REQ;
1878 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1880 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1882 wm->ldr.LoadCount = 1;
1883 *pwm = wm;
1884 return STATUS_SUCCESS;
1888 /***********************************************************************
1889 * load_builtin_dll
1891 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1892 DWORD flags, WINE_MODREF** pwm )
1894 char error[256], dllname[MAX_PATH];
1895 const WCHAR *name, *p;
1896 DWORD len, i;
1897 void *handle;
1898 struct builtin_load_info info, *prev_info;
1900 /* Fix the name in case we have a full path and extension */
1901 name = path;
1902 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1903 if ((p = strrchrW( name, '/' ))) name = p + 1;
1905 /* load_library will modify info.status. Note also that load_library can be
1906 * called several times, if the .so file we're loading has dependencies.
1907 * info.status will gather all the errors we may get while loading all these
1908 * libraries
1910 info.load_path = load_path;
1911 info.filename = NULL;
1912 info.status = STATUS_SUCCESS;
1913 info.wm = NULL;
1915 if (file) /* we have a real file, try to load it */
1917 UNICODE_STRING nt_name;
1918 ANSI_STRING unix_name;
1920 TRACE("Trying built-in %s\n", debugstr_w(path));
1922 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1923 return STATUS_DLL_NOT_FOUND;
1925 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1927 RtlFreeUnicodeString( &nt_name );
1928 return STATUS_DLL_NOT_FOUND;
1930 prev_info = builtin_load_info;
1931 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1932 builtin_load_info = &info;
1933 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1934 builtin_load_info = prev_info;
1935 RtlFreeUnicodeString( &nt_name );
1936 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1937 if (!handle)
1939 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1940 return STATUS_INVALID_IMAGE_FORMAT;
1943 else
1945 int file_exists;
1947 TRACE("Trying built-in %s\n", debugstr_w(name));
1949 /* we don't want to depend on the current codepage here */
1950 len = strlenW( name ) + 1;
1951 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1952 for (i = 0; i < len; i++)
1954 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1955 dllname[i] = (char)name[i];
1956 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1959 prev_info = builtin_load_info;
1960 builtin_load_info = &info;
1961 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1962 builtin_load_info = prev_info;
1963 if (!handle)
1965 if (!file_exists)
1967 /* The file does not exist -> WARN() */
1968 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1969 return STATUS_DLL_NOT_FOUND;
1971 /* ERR() for all other errors (missing functions, ...) */
1972 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1973 return STATUS_PROCEDURE_NOT_FOUND;
1977 if (info.status != STATUS_SUCCESS)
1979 wine_dll_unload( handle );
1980 return info.status;
1983 if (!info.wm)
1985 PLIST_ENTRY mark, entry;
1987 /* The constructor wasn't called, this means the .so is already
1988 * loaded under a different name. Try to find the wm for it. */
1990 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1991 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1993 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1994 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1996 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1997 TRACE( "Found %s at %p for builtin %s\n",
1998 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1999 break;
2002 wine_dll_unload( handle ); /* release the libdl refcount */
2003 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2004 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2006 else
2008 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2009 info.wm->ldr.LoadCount = 1;
2010 info.wm->ldr.SectionHandle = handle;
2013 *pwm = info.wm;
2014 return STATUS_SUCCESS;
2018 /***********************************************************************
2019 * find_actctx_dll
2021 * Find the full path (if any) of the dll from the activation context.
2023 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2025 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2026 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2028 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2029 ACTCTX_SECTION_KEYED_DATA data;
2030 UNICODE_STRING nameW;
2031 NTSTATUS status;
2032 SIZE_T needed, size = 1024;
2033 WCHAR *p;
2035 RtlInitUnicodeString( &nameW, libname );
2036 data.cbSize = sizeof(data);
2037 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2038 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2039 &nameW, &data );
2040 if (status != STATUS_SUCCESS) return status;
2042 for (;;)
2044 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2046 status = STATUS_NO_MEMORY;
2047 goto done;
2049 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2050 AssemblyDetailedInformationInActivationContext,
2051 info, size, &needed );
2052 if (status == STATUS_SUCCESS) break;
2053 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2054 RtlFreeHeap( GetProcessHeap(), 0, info );
2055 size = needed;
2056 /* restart with larger buffer */
2059 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2061 status = STATUS_SXS_KEY_NOT_FOUND;
2062 goto done;
2065 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2067 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2069 p++;
2070 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2072 /* manifest name does not match directory name, so it's not a global
2073 * windows/winsxs manifest; use the manifest directory name instead */
2074 dirlen = p - info->lpAssemblyManifestPath;
2075 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2076 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2078 status = STATUS_NO_MEMORY;
2079 goto done;
2081 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2082 p += dirlen;
2083 strcpyW( p, libname );
2084 goto done;
2088 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2089 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2091 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2093 status = STATUS_NO_MEMORY;
2094 goto done;
2096 strcpyW( p, user_shared_data->NtSystemRoot );
2097 p += strlenW(p);
2098 memcpy( p, winsxsW, sizeof(winsxsW) );
2099 p += sizeof(winsxsW) / sizeof(WCHAR);
2100 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2101 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2102 *p++ = '\\';
2103 strcpyW( p, libname );
2104 done:
2105 RtlFreeHeap( GetProcessHeap(), 0, info );
2106 RtlReleaseActivationContext( data.hActCtx );
2107 return status;
2111 /***********************************************************************
2112 * find_dll_file
2114 * Find the file (or already loaded module) for a given dll name.
2116 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2117 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
2119 OBJECT_ATTRIBUTES attr;
2120 IO_STATUS_BLOCK io;
2121 UNICODE_STRING nt_name;
2122 WCHAR *file_part, *ext, *dllname;
2123 ULONG len;
2125 /* first append .dll if needed */
2127 dllname = NULL;
2128 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2130 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2131 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2132 return STATUS_NO_MEMORY;
2133 strcpyW( dllname, libname );
2134 strcatW( dllname, dllW );
2135 libname = dllname;
2138 nt_name.Buffer = NULL;
2140 if (!contains_path( libname ))
2142 NTSTATUS status;
2143 WCHAR *fullname = NULL;
2145 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2147 status = find_actctx_dll( libname, &fullname );
2148 if (status == STATUS_SUCCESS)
2150 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2151 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2152 libname = dllname = fullname;
2154 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2156 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2157 return status;
2161 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2163 /* we need to search for it */
2164 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2165 if (len)
2167 if (len >= *size) goto overflow;
2168 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2170 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2172 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2173 return STATUS_NO_MEMORY;
2175 attr.Length = sizeof(attr);
2176 attr.RootDirectory = 0;
2177 attr.Attributes = OBJ_CASE_INSENSITIVE;
2178 attr.ObjectName = &nt_name;
2179 attr.SecurityDescriptor = NULL;
2180 attr.SecurityQualityOfService = NULL;
2181 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2182 goto found;
2185 /* not found */
2187 if (!contains_path( libname ))
2189 /* if libname doesn't contain a path at all, we simply return the name as is,
2190 * to be loaded as builtin */
2191 len = strlenW(libname) * sizeof(WCHAR);
2192 if (len >= *size) goto overflow;
2193 strcpyW( filename, libname );
2194 goto found;
2198 /* absolute path name, or relative path name but not found above */
2200 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2202 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2203 return STATUS_NO_MEMORY;
2205 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2206 if (len >= *size) goto overflow;
2207 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2208 if (!(*pwm = find_fullname_module( filename )) && handle)
2210 attr.Length = sizeof(attr);
2211 attr.RootDirectory = 0;
2212 attr.Attributes = OBJ_CASE_INSENSITIVE;
2213 attr.ObjectName = &nt_name;
2214 attr.SecurityDescriptor = NULL;
2215 attr.SecurityQualityOfService = NULL;
2216 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2218 found:
2219 RtlFreeUnicodeString( &nt_name );
2220 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2221 return STATUS_SUCCESS;
2223 overflow:
2224 RtlFreeUnicodeString( &nt_name );
2225 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2226 *size = len + sizeof(WCHAR);
2227 return STATUS_BUFFER_TOO_SMALL;
2231 /***********************************************************************
2232 * load_dll (internal)
2234 * Load a PE style module according to the load order.
2235 * The loader_section must be locked while calling this function.
2237 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2239 enum loadorder loadorder;
2240 WCHAR buffer[64];
2241 WCHAR *filename;
2242 ULONG size;
2243 WINE_MODREF *main_exe;
2244 HANDLE handle = 0;
2245 NTSTATUS nts;
2247 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2249 *pwm = NULL;
2250 filename = buffer;
2251 size = sizeof(buffer);
2252 for (;;)
2254 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2255 if (nts == STATUS_SUCCESS) break;
2256 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2257 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2258 /* grow the buffer and retry */
2259 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2262 if (*pwm) /* found already loaded module */
2264 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2266 TRACE("Found %s for %s at %p, count=%d\n",
2267 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2268 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2269 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2270 return STATUS_SUCCESS;
2273 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2274 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2276 if (handle && is_fake_dll( handle ))
2278 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2279 NtClose( handle );
2280 handle = 0;
2283 switch(loadorder)
2285 case LO_INVALID:
2286 nts = STATUS_NO_MEMORY;
2287 break;
2288 case LO_DISABLED:
2289 nts = STATUS_DLL_NOT_FOUND;
2290 break;
2291 case LO_NATIVE:
2292 case LO_NATIVE_BUILTIN:
2293 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2294 else
2296 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2297 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2298 /* not in PE format, maybe it's a builtin */
2299 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2301 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2302 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2303 break;
2304 case LO_BUILTIN:
2305 case LO_BUILTIN_NATIVE:
2306 case LO_DEFAULT: /* default is builtin,native */
2307 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2308 if (!handle) break; /* nothing else we can try */
2309 /* file is not a builtin library, try without using the specified file */
2310 if (nts != STATUS_SUCCESS)
2311 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2312 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2313 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2315 /* stub-only dll, try native */
2316 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2317 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2318 nts = STATUS_DLL_NOT_FOUND;
2320 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2321 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2322 break;
2325 if (nts == STATUS_SUCCESS)
2327 /* Initialize DLL just loaded */
2328 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2329 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2330 (*pwm)->ldr.BaseAddress);
2331 if (handle) NtClose( handle );
2332 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2333 return nts;
2336 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2337 if (handle) NtClose( handle );
2338 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2339 return nts;
2342 /******************************************************************
2343 * LdrLoadDll (NTDLL.@)
2345 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2346 const UNICODE_STRING *libname, HMODULE* hModule)
2348 WINE_MODREF *wm;
2349 NTSTATUS nts;
2351 RtlEnterCriticalSection( &loader_section );
2353 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2354 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2356 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2358 nts = process_attach( wm, NULL );
2359 if (nts != STATUS_SUCCESS)
2361 LdrUnloadDll(wm->ldr.BaseAddress);
2362 wm = NULL;
2365 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2367 RtlLeaveCriticalSection( &loader_section );
2368 return nts;
2372 /******************************************************************
2373 * LdrGetDllHandle (NTDLL.@)
2375 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2377 NTSTATUS status;
2378 WCHAR buffer[128];
2379 WCHAR *filename;
2380 ULONG size;
2381 WINE_MODREF *wm;
2383 RtlEnterCriticalSection( &loader_section );
2385 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2387 filename = buffer;
2388 size = sizeof(buffer);
2389 for (;;)
2391 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2392 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2393 if (status != STATUS_BUFFER_TOO_SMALL) break;
2394 /* grow the buffer and retry */
2395 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2397 status = STATUS_NO_MEMORY;
2398 break;
2402 if (status == STATUS_SUCCESS)
2404 if (wm) *base = wm->ldr.BaseAddress;
2405 else status = STATUS_DLL_NOT_FOUND;
2408 RtlLeaveCriticalSection( &loader_section );
2409 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2410 return status;
2414 /******************************************************************
2415 * LdrAddRefDll (NTDLL.@)
2417 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2419 NTSTATUS ret = STATUS_SUCCESS;
2420 WINE_MODREF *wm;
2422 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2424 RtlEnterCriticalSection( &loader_section );
2426 if ((wm = get_modref( module )))
2428 if (flags & LDR_ADDREF_DLL_PIN)
2429 wm->ldr.LoadCount = -1;
2430 else
2431 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2432 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2434 else ret = STATUS_INVALID_PARAMETER;
2436 RtlLeaveCriticalSection( &loader_section );
2437 return ret;
2441 /***********************************************************************
2442 * LdrProcessRelocationBlock (NTDLL.@)
2444 * Apply relocations to a given page of a mapped PE image.
2446 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2447 USHORT *relocs, INT_PTR delta )
2449 while (count--)
2451 USHORT offset = *relocs & 0xfff;
2452 int type = *relocs >> 12;
2453 switch(type)
2455 case IMAGE_REL_BASED_ABSOLUTE:
2456 break;
2457 case IMAGE_REL_BASED_HIGH:
2458 *(short *)((char *)page + offset) += HIWORD(delta);
2459 break;
2460 case IMAGE_REL_BASED_LOW:
2461 *(short *)((char *)page + offset) += LOWORD(delta);
2462 break;
2463 case IMAGE_REL_BASED_HIGHLOW:
2464 *(int *)((char *)page + offset) += delta;
2465 break;
2466 #ifdef _WIN64
2467 case IMAGE_REL_BASED_DIR64:
2468 *(INT_PTR *)((char *)page + offset) += delta;
2469 break;
2470 #elif defined(__arm__)
2471 case IMAGE_REL_BASED_THUMB_MOV32:
2473 DWORD inst = *(INT_PTR *)((char *)page + offset);
2474 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2475 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2476 DWORD hi_delta;
2478 if ((inst & 0x8000fbf0) != 0x0000f240)
2479 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2481 imm16 += LOWORD(delta);
2482 hi_delta = HIWORD(delta) + HIWORD(imm16);
2483 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2484 ((imm16 >> 12) & 0x000f) +
2485 ((imm16 << 20) & 0x70000000) +
2486 ((imm16 << 16) & 0xff0000);
2488 if (hi_delta != 0)
2490 inst = *(INT_PTR *)((char *)page + offset + 4);
2491 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2492 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2494 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2495 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2497 imm16 += hi_delta;
2498 if (imm16 > 0xffff)
2499 ERR("resulting immediate value won't fit: %08x\n", imm16);
2500 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2501 ((imm16 >> 1) & 0x0400) +
2502 ((imm16 >> 12) & 0x000f) +
2503 ((imm16 << 20) & 0x70000000) +
2504 ((imm16 << 16) & 0xff0000);
2507 break;
2508 #endif
2509 default:
2510 FIXME("Unknown/unsupported fixup type %x.\n", type);
2511 return NULL;
2513 relocs++;
2515 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2519 /******************************************************************
2520 * LdrQueryProcessModuleInformation
2523 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2524 ULONG buf_size, ULONG* req_size)
2526 SYSTEM_MODULE* sm = &smi->Modules[0];
2527 ULONG size = sizeof(ULONG);
2528 NTSTATUS nts = STATUS_SUCCESS;
2529 ANSI_STRING str;
2530 char* ptr;
2531 PLIST_ENTRY mark, entry;
2532 PLDR_MODULE mod;
2533 WORD id = 0;
2535 smi->ModulesCount = 0;
2537 RtlEnterCriticalSection( &loader_section );
2538 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2539 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2541 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2542 size += sizeof(*sm);
2543 if (size <= buf_size)
2545 sm->Reserved1 = 0; /* FIXME */
2546 sm->Reserved2 = 0; /* FIXME */
2547 sm->ImageBaseAddress = mod->BaseAddress;
2548 sm->ImageSize = mod->SizeOfImage;
2549 sm->Flags = mod->Flags;
2550 sm->Id = id++;
2551 sm->Rank = 0; /* FIXME */
2552 sm->Unknown = 0; /* FIXME */
2553 str.Length = 0;
2554 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2555 str.Buffer = (char*)sm->Name;
2556 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2557 ptr = strrchr(str.Buffer, '\\');
2558 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2560 smi->ModulesCount++;
2561 sm++;
2563 else nts = STATUS_INFO_LENGTH_MISMATCH;
2565 RtlLeaveCriticalSection( &loader_section );
2567 if (req_size) *req_size = size;
2569 return nts;
2573 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2575 NTSTATUS status;
2576 UNICODE_STRING str;
2577 ULONG size;
2578 WCHAR buffer[64];
2579 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2581 RtlInitUnicodeString( &str, name );
2583 size = sizeof(buffer) - sizeof(WCHAR);
2584 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2585 return status;
2587 if (info->Type != REG_DWORD)
2589 buffer[size / sizeof(WCHAR)] = 0;
2590 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2592 else memcpy( value, info->Data, sizeof(*value) );
2593 return status;
2596 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2597 void *data, ULONG in_size, ULONG *out_size )
2599 NTSTATUS status;
2600 UNICODE_STRING str;
2601 ULONG size;
2602 char *buffer;
2603 KEY_VALUE_PARTIAL_INFORMATION *info;
2604 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2606 RtlInitUnicodeString( &str, name );
2608 size = info_size + in_size;
2609 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2610 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2611 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2612 if (!status || status == STATUS_BUFFER_OVERFLOW)
2614 if (out_size) *out_size = info->DataLength;
2615 if (data && !status) memcpy( data, info->Data, info->DataLength );
2617 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2618 return status;
2622 /******************************************************************
2623 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2625 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2626 void *data, ULONG in_size, ULONG *out_size )
2628 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2629 'S','o','f','t','w','a','r','e','\\',
2630 'M','i','c','r','o','s','o','f','t','\\',
2631 'W','i','n','d','o','w','s',' ','N','T','\\',
2632 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2633 'I','m','a','g','e',' ','F','i','l','e',' ',
2634 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2635 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2636 OBJECT_ATTRIBUTES attr;
2637 UNICODE_STRING name_str;
2638 HANDLE hkey;
2639 NTSTATUS status;
2640 ULONG len;
2641 WCHAR *p;
2643 attr.Length = sizeof(attr);
2644 attr.RootDirectory = 0;
2645 attr.ObjectName = &name_str;
2646 attr.Attributes = OBJ_CASE_INSENSITIVE;
2647 attr.SecurityDescriptor = NULL;
2648 attr.SecurityQualityOfService = NULL;
2650 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2651 else p = key->Buffer;
2652 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2653 name_str.Buffer = path;
2654 name_str.Length = sizeof(optionsW) + len;
2655 name_str.MaximumLength = name_str.Length;
2656 memcpy( path, optionsW, sizeof(optionsW) );
2657 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2658 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2660 if (type == REG_DWORD)
2662 if (out_size) *out_size = sizeof(ULONG);
2663 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2664 else status = STATUS_BUFFER_OVERFLOW;
2666 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2668 NtClose( hkey );
2669 return status;
2673 /******************************************************************
2674 * RtlDllShutdownInProgress (NTDLL.@)
2676 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2678 return process_detaching;
2681 /****************************************************************************
2682 * LdrResolveDelayLoadedAPI (NTDLL.@)
2684 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2685 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2686 IMAGE_THUNK_DATA* addr, ULONG flags )
2688 IMAGE_THUNK_DATA *pIAT, *pINT;
2689 DELAYLOAD_INFO delayinfo;
2690 UNICODE_STRING mod;
2691 const CHAR* name;
2692 HMODULE *phmod;
2693 NTSTATUS nts;
2694 FARPROC fp;
2695 DWORD id;
2697 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2699 phmod = get_rva(base, desc->ModuleHandleRVA);
2700 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2701 pINT = get_rva(base, desc->ImportNameTableRVA);
2702 name = get_rva(base, desc->DllNameRVA);
2703 id = addr - pIAT;
2705 if (!*phmod)
2707 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2709 nts = STATUS_NO_MEMORY;
2710 goto fail;
2712 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2713 RtlFreeUnicodeString(&mod);
2714 if (nts) goto fail;
2717 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2718 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2719 else
2721 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2722 ANSI_STRING fnc;
2724 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2725 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2727 if (!nts)
2729 pIAT[id].u1.Function = (ULONG_PTR)fp;
2730 return fp;
2733 fail:
2734 delayinfo.Size = sizeof(delayinfo);
2735 delayinfo.DelayloadDescriptor = desc;
2736 delayinfo.ThunkAddress = addr;
2737 delayinfo.TargetDllName = name;
2738 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2739 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2740 delayinfo.TargetModuleBase = *phmod;
2741 delayinfo.Unused = NULL;
2742 delayinfo.LastError = nts;
2743 return dllhook(4, &delayinfo);
2746 /******************************************************************
2747 * LdrShutdownProcess (NTDLL.@)
2750 void WINAPI LdrShutdownProcess(void)
2752 TRACE("()\n");
2753 process_detaching = TRUE;
2754 process_detach();
2758 /******************************************************************
2759 * RtlExitUserProcess (NTDLL.@)
2761 void WINAPI RtlExitUserProcess( DWORD status )
2763 RtlEnterCriticalSection( &loader_section );
2764 RtlAcquirePebLock();
2765 NtTerminateProcess( 0, status );
2766 LdrShutdownProcess();
2767 NtTerminateProcess( GetCurrentProcess(), status );
2768 exit( status );
2771 /******************************************************************
2772 * LdrShutdownThread (NTDLL.@)
2775 void WINAPI LdrShutdownThread(void)
2777 PLIST_ENTRY mark, entry;
2778 PLDR_MODULE mod;
2779 UINT i;
2780 void **pointers;
2782 TRACE("()\n");
2784 /* don't do any detach calls if process is exiting */
2785 if (process_detaching) return;
2787 RtlEnterCriticalSection( &loader_section );
2789 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2790 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2792 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2793 InInitializationOrderModuleList);
2794 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2795 continue;
2796 if ( mod->Flags & LDR_NO_DLL_CALLS )
2797 continue;
2799 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2800 DLL_THREAD_DETACH, NULL );
2803 RtlAcquirePebLock();
2804 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2805 RtlReleasePebLock();
2807 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2809 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2810 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2812 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2813 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2814 RtlLeaveCriticalSection( &loader_section );
2818 /***********************************************************************
2819 * free_modref
2822 static void free_modref( WINE_MODREF *wm )
2824 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2825 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2826 if (wm->ldr.InInitializationOrderModuleList.Flink)
2827 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2829 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2830 if (!TRACE_ON(module))
2831 TRACE_(loaddll)("Unloaded module %s : %s\n",
2832 debugstr_w(wm->ldr.FullDllName.Buffer),
2833 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2835 SERVER_START_REQ( unload_dll )
2837 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2838 wine_server_call( req );
2840 SERVER_END_REQ;
2842 free_tls_slot( &wm->ldr );
2843 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2844 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2845 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2846 if (cached_modref == wm) cached_modref = NULL;
2847 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2848 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2849 RtlFreeHeap( GetProcessHeap(), 0, wm );
2852 /***********************************************************************
2853 * MODULE_FlushModrefs
2855 * Remove all unused modrefs and call the internal unloading routines
2856 * for the library type.
2858 * The loader_section must be locked while calling this function.
2860 static void MODULE_FlushModrefs(void)
2862 PLIST_ENTRY mark, entry, prev;
2863 PLDR_MODULE mod;
2864 WINE_MODREF*wm;
2866 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2867 for (entry = mark->Blink; entry != mark; entry = prev)
2869 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2870 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2871 prev = entry->Blink;
2872 if (!mod->LoadCount) free_modref( wm );
2875 /* check load order list too for modules that haven't been initialized yet */
2876 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2877 for (entry = mark->Blink; entry != mark; entry = prev)
2879 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2880 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2881 prev = entry->Blink;
2882 if (!mod->LoadCount) free_modref( wm );
2886 /***********************************************************************
2887 * MODULE_DecRefCount
2889 * The loader_section must be locked while calling this function.
2891 static void MODULE_DecRefCount( WINE_MODREF *wm )
2893 int i;
2895 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2896 return;
2898 if ( wm->ldr.LoadCount <= 0 )
2899 return;
2901 --wm->ldr.LoadCount;
2902 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2904 if ( wm->ldr.LoadCount == 0 )
2906 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2908 for ( i = 0; i < wm->nDeps; i++ )
2909 if ( wm->deps[i] )
2910 MODULE_DecRefCount( wm->deps[i] );
2912 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2916 /******************************************************************
2917 * LdrUnloadDll (NTDLL.@)
2921 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2923 WINE_MODREF *wm;
2924 NTSTATUS retv = STATUS_SUCCESS;
2926 if (process_detaching) return retv;
2928 TRACE("(%p)\n", hModule);
2930 RtlEnterCriticalSection( &loader_section );
2932 free_lib_count++;
2933 if ((wm = get_modref( hModule )) != NULL)
2935 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2937 /* Recursively decrement reference counts */
2938 MODULE_DecRefCount( wm );
2940 /* Call process detach notifications */
2941 if ( free_lib_count <= 1 )
2943 process_detach();
2944 MODULE_FlushModrefs();
2947 TRACE("END\n");
2949 else
2950 retv = STATUS_DLL_NOT_FOUND;
2952 free_lib_count--;
2954 RtlLeaveCriticalSection( &loader_section );
2956 return retv;
2959 /***********************************************************************
2960 * RtlImageNtHeader (NTDLL.@)
2962 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2964 IMAGE_NT_HEADERS *ret;
2966 __TRY
2968 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2970 ret = NULL;
2971 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2973 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2974 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2977 __EXCEPT_PAGE_FAULT
2979 return NULL;
2981 __ENDTRY
2982 return ret;
2986 /***********************************************************************
2987 * attach_dlls
2989 * Attach to all the loaded dlls.
2990 * If this is the first time, perform the full process initialization.
2992 NTSTATUS attach_dlls( CONTEXT *context )
2994 NTSTATUS status;
2995 WINE_MODREF *wm;
2996 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2998 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3000 if (process_detaching) return STATUS_SUCCESS;
3002 RtlEnterCriticalSection( &loader_section );
3004 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3005 assert( wm );
3007 if (!imports_fixup_done)
3009 actctx_init();
3010 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
3012 ERR( "Importing dlls for %s failed, status %x\n",
3013 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3014 NtTerminateProcess( GetCurrentProcess(), status );
3016 imports_fixup_done = TRUE;
3019 RtlAcquirePebLock();
3020 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3021 RtlReleasePebLock();
3023 if (!(wm->ldr.Flags & LDR_PROCESS_ATTACHED)) /* first time around */
3025 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3027 ERR( "TLS init failed when loading %s, status %x\n",
3028 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3029 NtTerminateProcess( GetCurrentProcess(), status );
3031 if ((status = process_attach( wm, context )) != STATUS_SUCCESS)
3033 if (last_failed_modref)
3034 ERR( "%s failed to initialize, aborting\n",
3035 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3036 ERR( "Initializing dlls for %s failed, status %x\n",
3037 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3038 NtTerminateProcess( GetCurrentProcess(), status );
3040 attach_implicitly_loaded_dlls( context );
3041 virtual_release_address_space();
3043 else
3045 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3046 NtTerminateThread( GetCurrentThread(), status );
3047 thread_attach();
3050 RtlLeaveCriticalSection( &loader_section );
3051 return STATUS_SUCCESS;
3055 /***********************************************************************
3056 * load_global_options
3058 static void load_global_options(void)
3060 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3061 'S','y','s','t','e','m','\\',
3062 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3063 'C','o','n','t','r','o','l','\\',
3064 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3065 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3066 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};
3067 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3068 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3069 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};
3070 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};
3072 OBJECT_ATTRIBUTES attr;
3073 UNICODE_STRING name_str;
3074 HANDLE hkey;
3075 ULONG value;
3077 attr.Length = sizeof(attr);
3078 attr.RootDirectory = 0;
3079 attr.ObjectName = &name_str;
3080 attr.Attributes = OBJ_CASE_INSENSITIVE;
3081 attr.SecurityDescriptor = NULL;
3082 attr.SecurityQualityOfService = NULL;
3083 RtlInitUnicodeString( &name_str, sessionW );
3085 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3087 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3089 query_dword_option( hkey, critsectW, &value );
3090 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3092 query_dword_option( hkey, heapresW, &value );
3093 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3095 query_dword_option( hkey, heapcommitW, &value );
3096 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3098 query_dword_option( hkey, decommittotalW, &value );
3099 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3101 query_dword_option( hkey, decommitfreeW, &value );
3102 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3104 NtClose( hkey );
3108 /******************************************************************
3109 * LdrInitializeThunk (NTDLL.@)
3112 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3113 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3115 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3116 NTSTATUS status;
3117 WINE_MODREF *wm;
3118 PEB *peb = NtCurrentTeb()->Peb;
3120 kernel32_start_process = kernel_start;
3121 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
3123 /* allocate the modref for the main exe (if not already done) */
3124 wm = get_modref( peb->ImageBaseAddress );
3125 assert( wm );
3126 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3128 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3129 exit(1);
3132 peb->LoaderLock = &loader_section;
3133 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3134 if (!peb->ProcessParameters->WindowTitle.Buffer)
3135 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3136 version_init( wm->ldr.FullDllName.Buffer );
3137 virtual_set_large_address_space();
3139 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3140 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3141 heap_set_debug_flags( GetProcessHeap() );
3143 /* the main exe needs to be the first in the load order list */
3144 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3145 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3146 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3147 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3149 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL )) != STATUS_SUCCESS)
3151 ERR( "Main exe initialization for %s failed, status %x\n",
3152 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3153 NtTerminateProcess( GetCurrentProcess(), status );
3155 server_init_process_done();
3159 /***********************************************************************
3160 * RtlImageDirectoryEntryToData (NTDLL.@)
3162 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3164 const IMAGE_NT_HEADERS *nt;
3165 DWORD addr;
3167 if ((ULONG_PTR)module & 1) /* mapped as data file */
3169 module = (HMODULE)((ULONG_PTR)module & ~1);
3170 image = FALSE;
3172 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3173 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3175 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3177 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3178 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3179 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3180 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3182 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3184 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3186 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3187 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3188 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3189 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3191 else return NULL;
3193 /* not mapped as image, need to find the section containing the virtual address */
3194 return RtlImageRvaToVa( nt, module, addr, NULL );
3198 /***********************************************************************
3199 * RtlImageRvaToSection (NTDLL.@)
3201 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3202 HMODULE module, DWORD rva )
3204 int i;
3205 const IMAGE_SECTION_HEADER *sec;
3207 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3208 nt->FileHeader.SizeOfOptionalHeader);
3209 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3211 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3212 return (PIMAGE_SECTION_HEADER)sec;
3214 return NULL;
3218 /***********************************************************************
3219 * RtlImageRvaToVa (NTDLL.@)
3221 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3222 DWORD rva, IMAGE_SECTION_HEADER **section )
3224 IMAGE_SECTION_HEADER *sec;
3226 if (section && *section) /* try this section first */
3228 sec = *section;
3229 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3230 goto found;
3232 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3233 found:
3234 if (section) *section = sec;
3235 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3239 /***********************************************************************
3240 * RtlPcToFileHeader (NTDLL.@)
3242 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3244 LDR_MODULE *module;
3245 PVOID ret = NULL;
3247 RtlEnterCriticalSection( &loader_section );
3248 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3249 RtlLeaveCriticalSection( &loader_section );
3250 *address = ret;
3251 return ret;
3255 /***********************************************************************
3256 * NtLoadDriver (NTDLL.@)
3257 * ZwLoadDriver (NTDLL.@)
3259 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3261 FIXME("(%p), stub!\n",DriverServiceName);
3262 return STATUS_NOT_IMPLEMENTED;
3266 /***********************************************************************
3267 * NtUnloadDriver (NTDLL.@)
3268 * ZwUnloadDriver (NTDLL.@)
3270 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3272 FIXME("(%p), stub!\n",DriverServiceName);
3273 return STATUS_NOT_IMPLEMENTED;
3277 /******************************************************************
3278 * DllMain (NTDLL.@)
3280 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3282 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3283 return TRUE;
3287 /******************************************************************
3288 * __wine_init_windows_dir (NTDLL.@)
3290 * Windows and system dir initialization once kernel32 has been loaded.
3292 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3294 PLIST_ENTRY mark, entry;
3295 LPWSTR buffer, p;
3297 strcpyW( user_shared_data->NtSystemRoot, windir );
3298 DIR_init_windows_dir( windir, sysdir );
3300 /* prepend the system dir to the name of the already created modules */
3301 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3302 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3304 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3306 assert( mod->Flags & LDR_WINE_INTERNAL );
3308 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3309 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3310 if (!buffer) continue;
3311 strcpyW( buffer, system_dir.Buffer );
3312 p = buffer + strlenW( buffer );
3313 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3314 strcpyW( p, mod->FullDllName.Buffer );
3315 RtlInitUnicodeString( &mod->FullDllName, buffer );
3316 RtlInitUnicodeString( &mod->BaseDllName, p );
3321 /***********************************************************************
3322 * __wine_process_init
3324 void __wine_process_init(void)
3326 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3328 WINE_MODREF *wm;
3329 NTSTATUS status;
3330 ANSI_STRING func_name;
3331 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3333 main_exe_file = thread_init();
3335 /* retrieve current umask */
3336 FILE_umask = umask(0777);
3337 umask( FILE_umask );
3339 load_global_options();
3341 /* setup the load callback and create ntdll modref */
3342 wine_dll_set_callback( load_builtin_callback );
3344 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3346 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3347 exit(1);
3349 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3350 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3352 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3353 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3354 0, (void **)&init_func )) != STATUS_SUCCESS)
3356 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3357 exit(1);
3359 init_func();