kernel32/tests: Also test wrong architecture with matching 32/64 bitness.
[wine.git] / dlls / ntdll / loader.c
blob53280a4497fda2fb6f250e201c386b043f7d9d2f
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 BYTE ldr_r0[4]; /* ldr r0, $dll */
234 BYTE ldr_r1[4]; /* ldr r1, $name */
235 BYTE mov_r2_lr[4]; /* mov r2, lr */
236 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #4] */
237 const char *dll;
238 const char *name;
239 const void* entry;
241 #elif defined(__aarch64__)
242 struct stub
244 BYTE ldr_x0[4]; /* ldr x0, $dll */
245 BYTE ldr_x1[4]; /* ldr x1, $name */
246 BYTE mov_x2_lr[4]; /* mov x2, lr */
247 BYTE ldr_x16[4]; /* ldr x16, $entry */
248 BYTE br_x16[4]; /* 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[0] = 0x08; /* ldr r0, [pc, #8] ($dll) */
299 stub->ldr_r0[1] = 0x00;
300 stub->ldr_r0[2] = 0x9f;
301 stub->ldr_r0[3] = 0xe5;
302 stub->ldr_r1[0] = 0x08; /* ldr r1, [pc, #8] ($name) */
303 stub->ldr_r1[1] = 0x10;
304 stub->ldr_r1[2] = 0x9f;
305 stub->ldr_r1[3] = 0xe5;
306 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
307 stub->mov_r2_lr[1] = 0x20;
308 stub->mov_r2_lr[2] = 0xa0;
309 stub->mov_r2_lr[3] = 0xe1;
310 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #4] */
311 stub->ldr_pc_pc[1] = 0xf0;
312 stub->ldr_pc_pc[2] = 0x9f;
313 stub->ldr_pc_pc[3] = 0xe5;
314 stub->dll = dll;
315 stub->name = name;
316 stub->entry = stub_entry_point;
317 #elif defined(__aarch64__)
318 stub->ldr_x0[0] = 0xa0; /* ldr x0, #20 ($dll) */
319 stub->ldr_x0[1] = 0x00;
320 stub->ldr_x0[2] = 0x00;
321 stub->ldr_x0[3] = 0x58;
322 stub->ldr_x1[0] = 0xc1; /* ldr x1, #24 ($name) */
323 stub->ldr_x1[1] = 0x00;
324 stub->ldr_x1[2] = 0x00;
325 stub->ldr_x1[3] = 0x58;
326 stub->mov_x2_lr[0] = 0xe2; /* mov x2, lr */
327 stub->mov_x2_lr[1] = 0x03;
328 stub->mov_x2_lr[2] = 0x1e;
329 stub->mov_x2_lr[3] = 0xaa;
330 stub->ldr_x16[0] = 0xd0; /* ldr x16, #24 ($entry) */
331 stub->ldr_x16[1] = 0x00;
332 stub->ldr_x16[2] = 0x00;
333 stub->ldr_x16[3] = 0x58;
334 stub->br_x16[0] = 0x00; /* br x16 */
335 stub->br_x16[1] = 0x02;
336 stub->br_x16[2] = 0x1f;
337 stub->br_x16[3] = 0xd6;
338 stub->dll = dll;
339 stub->name = name;
340 stub->entry = stub_entry_point;
341 #else
342 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
343 stub->movq_rdi[1] = 0xbf;
344 stub->dll = dll;
345 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
346 stub->movq_rsi[1] = 0xbe;
347 stub->name = name;
348 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
349 stub->movq_rsp_rdx[1] = 0x8b;
350 stub->movq_rsp_rdx[2] = 0x14;
351 stub->movq_rsp_rdx[3] = 0x24;
352 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
353 stub->movq_rax[1] = 0xb8;
354 stub->entry = stub_entry_point;
355 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
356 stub->jmpq_rax[1] = 0xe0;
357 #endif
358 return (ULONG_PTR)stub;
361 #else /* __i386__ */
362 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
363 #endif /* __i386__ */
366 /*************************************************************************
367 * get_modref
369 * Looks for the referenced HMODULE in the current process
370 * The loader_section must be locked while calling this function.
372 static WINE_MODREF *get_modref( HMODULE hmod )
374 PLIST_ENTRY mark, entry;
375 PLDR_MODULE mod;
377 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
379 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
380 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
382 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
383 if (mod->BaseAddress == hmod)
384 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
386 return NULL;
390 /**********************************************************************
391 * find_basename_module
393 * Find a module from its base name.
394 * The loader_section must be locked while calling this function
396 static WINE_MODREF *find_basename_module( LPCWSTR name )
398 PLIST_ENTRY mark, entry;
400 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.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->BaseDllName.Buffer ))
409 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
410 return cached_modref;
413 return NULL;
417 /**********************************************************************
418 * find_fullname_module
420 * Find a module from its full path name.
421 * The loader_section must be locked while calling this function
423 static WINE_MODREF *find_fullname_module( LPCWSTR name )
425 PLIST_ENTRY mark, entry;
427 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
428 return cached_modref;
430 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
431 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
433 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
434 if (!strcmpiW( name, mod->FullDllName.Buffer ))
436 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
437 return cached_modref;
440 return NULL;
444 /*************************************************************************
445 * find_forwarded_export
447 * Find the final function pointer for a forwarded function.
448 * The loader_section must be locked while calling this function.
450 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
452 const IMAGE_EXPORT_DIRECTORY *exports;
453 DWORD exp_size;
454 WINE_MODREF *wm;
455 WCHAR mod_name[32];
456 const char *end = strrchr(forward, '.');
457 FARPROC proc = NULL;
459 if (!end) return NULL;
460 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
461 ascii_to_unicode( mod_name, forward, end - forward );
462 mod_name[end - forward] = 0;
463 if (!strchrW( mod_name, '.' ))
465 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
466 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
469 if (!(wm = find_basename_module( mod_name )))
471 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
472 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
473 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
475 if (!imports_fixup_done && current_modref)
477 WINE_MODREF **deps;
478 if (current_modref->nDeps)
479 deps = RtlReAllocateHeap( GetProcessHeap(), 0, current_modref->deps,
480 (current_modref->nDeps + 1) * sizeof(*deps) );
481 else
482 deps = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps) );
483 if (deps)
485 deps[current_modref->nDeps++] = wm;
486 current_modref->deps = deps;
489 else if (process_attach( wm, NULL ) != STATUS_SUCCESS)
491 LdrUnloadDll( wm->ldr.BaseAddress );
492 wm = NULL;
496 if (!wm)
498 ERR( "module not found for forward '%s' used by %s\n",
499 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
500 return NULL;
503 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
504 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
506 const char *name = end + 1;
507 if (*name == '#') /* ordinal */
508 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
509 else
510 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
513 if (!proc)
515 ERR("function not found for forward '%s' used by %s."
516 " If you are using builtin %s, try using the native one instead.\n",
517 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
518 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
520 return proc;
524 /*************************************************************************
525 * find_ordinal_export
527 * Find an exported function by ordinal.
528 * The exports base must have been subtracted from the ordinal already.
529 * The loader_section must be locked while calling this function.
531 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
532 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
534 FARPROC proc;
535 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
537 if (ordinal >= exports->NumberOfFunctions)
539 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
540 return NULL;
542 if (!functions[ordinal]) return NULL;
544 proc = get_rva( module, functions[ordinal] );
546 /* if the address falls into the export dir, it's a forward */
547 if (((const char *)proc >= (const char *)exports) &&
548 ((const char *)proc < (const char *)exports + exp_size))
549 return find_forwarded_export( module, (const char *)proc, load_path );
551 if (TRACE_ON(snoop))
553 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
554 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
556 if (TRACE_ON(relay))
558 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
559 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
561 return proc;
565 /*************************************************************************
566 * find_named_export
568 * Find an exported function by name.
569 * The loader_section must be locked while calling this function.
571 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
572 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
574 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
575 const DWORD *names = get_rva( module, exports->AddressOfNames );
576 int min = 0, max = exports->NumberOfNames - 1;
578 /* first check the hint */
579 if (hint >= 0 && hint <= max)
581 char *ename = get_rva( module, names[hint] );
582 if (!strcmp( ename, name ))
583 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
586 /* then do a binary search */
587 while (min <= max)
589 int res, pos = (min + max) / 2;
590 char *ename = get_rva( module, names[pos] );
591 if (!(res = strcmp( ename, name )))
592 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
593 if (res > 0) max = pos - 1;
594 else min = pos + 1;
596 return NULL;
601 /*************************************************************************
602 * import_dll
604 * Import the dll specified by the given import descriptor.
605 * The loader_section must be locked while calling this function.
607 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
609 NTSTATUS status;
610 WINE_MODREF *wmImp;
611 HMODULE imp_mod;
612 const IMAGE_EXPORT_DIRECTORY *exports;
613 DWORD exp_size;
614 const IMAGE_THUNK_DATA *import_list;
615 IMAGE_THUNK_DATA *thunk_list;
616 WCHAR buffer[32];
617 const char *name = get_rva( module, descr->Name );
618 DWORD len = strlen(name);
619 PVOID protect_base;
620 SIZE_T protect_size = 0;
621 DWORD protect_old;
623 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
624 if (descr->u.OriginalFirstThunk)
625 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
626 else
627 import_list = thunk_list;
629 if (!import_list->u1.Ordinal)
631 WARN( "Skipping unused import %s\n", name );
632 *pwm = NULL;
633 return TRUE;
636 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
638 if (len * sizeof(WCHAR) < sizeof(buffer))
640 ascii_to_unicode( buffer, name, len );
641 buffer[len] = 0;
642 status = load_dll( load_path, buffer, 0, &wmImp );
644 else /* need to allocate a larger buffer */
646 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
647 if (!ptr) return FALSE;
648 ascii_to_unicode( ptr, name, len );
649 ptr[len] = 0;
650 status = load_dll( load_path, ptr, 0, &wmImp );
651 RtlFreeHeap( GetProcessHeap(), 0, ptr );
654 if (status)
656 if (status == STATUS_DLL_NOT_FOUND)
657 ERR("Library %s (which is needed by %s) not found\n",
658 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
659 else
660 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
661 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
662 return FALSE;
665 /* unprotect the import address table since it can be located in
666 * readonly section */
667 while (import_list[protect_size].u1.Ordinal) protect_size++;
668 protect_base = thunk_list;
669 protect_size *= sizeof(*thunk_list);
670 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
671 &protect_size, PAGE_READWRITE, &protect_old );
673 imp_mod = wmImp->ldr.BaseAddress;
674 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
676 if (!exports)
678 /* set all imported function to deadbeef */
679 while (import_list->u1.Ordinal)
681 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
683 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
684 WARN("No implementation for %s.%d", name, ordinal );
685 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
687 else
689 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
690 WARN("No implementation for %s.%s", name, pe_name->Name );
691 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
693 WARN(" imported from %s, allocating stub %p\n",
694 debugstr_w(current_modref->ldr.FullDllName.Buffer),
695 (void *)thunk_list->u1.Function );
696 import_list++;
697 thunk_list++;
699 goto done;
702 while (import_list->u1.Ordinal)
704 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
706 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
708 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
709 ordinal - exports->Base, load_path );
710 if (!thunk_list->u1.Function)
712 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
713 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
714 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
715 (void *)thunk_list->u1.Function );
717 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
719 else /* import by name */
721 IMAGE_IMPORT_BY_NAME *pe_name;
722 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
723 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
724 (const char*)pe_name->Name,
725 pe_name->Hint, load_path );
726 if (!thunk_list->u1.Function)
728 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
729 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
730 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
731 (void *)thunk_list->u1.Function );
733 TRACE_(imports)("--- %s %s.%d = %p\n",
734 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
736 import_list++;
737 thunk_list++;
740 done:
741 /* restore old protection of the import address table */
742 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
743 *pwm = wmImp;
744 return TRUE;
748 /***********************************************************************
749 * create_module_activation_context
751 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
753 NTSTATUS status;
754 LDR_RESOURCE_INFO info;
755 const IMAGE_RESOURCE_DATA_ENTRY *entry;
757 info.Type = RT_MANIFEST;
758 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
759 info.Language = 0;
760 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
762 ACTCTXW ctx;
763 ctx.cbSize = sizeof(ctx);
764 ctx.lpSource = NULL;
765 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
766 ctx.hModule = module->BaseAddress;
767 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
768 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
770 return status;
774 /*************************************************************************
775 * is_dll_native_subsystem
777 * Check if dll is a proper native driver.
778 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
779 * while being perfectly normal DLLs. This heuristic should catch such breakages.
781 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
783 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
784 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
785 const IMAGE_IMPORT_DESCRIPTOR *imports;
786 DWORD i, size;
787 WCHAR buffer[16];
789 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
790 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
792 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
793 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
795 for (i = 0; imports[i].Name; i++)
797 const char *name = get_rva( module, imports[i].Name );
798 DWORD len = strlen(name);
799 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
800 ascii_to_unicode( buffer, name, len + 1 );
801 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
803 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
804 return FALSE;
808 return TRUE;
811 /*************************************************************************
812 * alloc_tls_slot
814 * Allocate a TLS slot for a newly-loaded module.
815 * The loader_section must be locked while calling this function.
817 static SHORT alloc_tls_slot( LDR_MODULE *mod )
819 const IMAGE_TLS_DIRECTORY *dir;
820 ULONG i, size;
821 void *new_ptr;
822 LIST_ENTRY *entry;
824 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
825 return -1;
827 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
828 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
830 for (i = 0; i < tls_module_count; i++)
832 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
833 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
834 break;
837 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
838 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
839 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
841 if (i == tls_module_count)
843 UINT new_count = max( 32, tls_module_count * 2 );
845 if (!tls_dirs)
846 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
847 else
848 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
849 new_count * sizeof(*tls_dirs) );
850 if (!new_ptr) return -1;
852 /* resize the pointer block in all running threads */
853 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
855 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
856 void **old = teb->ThreadLocalStoragePointer;
857 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
859 if (!new) return -1;
860 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
861 teb->ThreadLocalStoragePointer = new;
862 #if defined(__APPLE__) && defined(__x86_64__)
863 if (teb->Reserved5[0])
864 ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
865 #endif
866 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
867 /* FIXME: can't free old block here, should be freed at thread exit */
870 tls_dirs = new_ptr;
871 tls_module_count = new_count;
874 /* allocate the data block in all running threads */
875 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
877 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
879 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
880 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
881 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
883 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
884 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
886 RtlFreeHeap( GetProcessHeap(), 0,
887 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
890 *(DWORD *)dir->AddressOfIndex = i;
891 tls_dirs[i] = *dir;
892 return i;
896 /*************************************************************************
897 * free_tls_slot
899 * Free the module TLS slot on unload.
900 * The loader_section must be locked while calling this function.
902 static void free_tls_slot( LDR_MODULE *mod )
904 ULONG i = (USHORT)mod->TlsIndex;
906 if (mod->TlsIndex == -1) return;
907 assert( i < tls_module_count );
908 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
912 /****************************************************************
913 * fixup_imports
915 * Fixup all imports of a given module.
916 * The loader_section must be locked while calling this function.
918 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
920 int i, nb_imports;
921 const IMAGE_IMPORT_DESCRIPTOR *imports;
922 WINE_MODREF *prev, *imp;
923 DWORD size;
924 NTSTATUS status;
925 ULONG_PTR cookie;
927 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
928 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
930 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
932 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
933 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
934 return STATUS_SUCCESS;
936 nb_imports = 0;
937 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
939 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
941 if (!create_module_activation_context( &wm->ldr ))
942 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
944 /* Allocate module dependency list */
945 wm->nDeps = nb_imports;
946 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
948 /* load the imported modules. They are automatically
949 * added to the modref list of the process.
951 prev = current_modref;
952 current_modref = wm;
953 status = STATUS_SUCCESS;
954 for (i = 0; i < nb_imports; i++)
956 if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &imp ))
958 imp = NULL;
959 status = STATUS_DLL_NOT_FOUND;
961 wm->deps[i] = imp;
963 current_modref = prev;
964 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
965 return status;
969 /*************************************************************************
970 * alloc_module
972 * Allocate a WINE_MODREF structure and add it to the process list
973 * The loader_section must be locked while calling this function.
975 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
977 WINE_MODREF *wm;
978 const WCHAR *p;
979 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
981 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
983 wm->nDeps = 0;
984 wm->deps = NULL;
986 wm->ldr.BaseAddress = hModule;
987 wm->ldr.EntryPoint = NULL;
988 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
989 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
990 wm->ldr.TlsIndex = -1;
991 wm->ldr.LoadCount = 1;
992 wm->ldr.SectionHandle = NULL;
993 wm->ldr.CheckSum = 0;
994 wm->ldr.TimeDateStamp = 0;
995 wm->ldr.ActivationContext = 0;
997 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
998 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
999 else p = wm->ldr.FullDllName.Buffer;
1000 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
1002 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
1004 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
1005 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
1006 if (nt->OptionalHeader.AddressOfEntryPoint)
1007 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
1010 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
1011 &wm->ldr.InLoadOrderModuleList);
1012 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
1013 &wm->ldr.InMemoryOrderModuleList);
1015 /* wait until init is called for inserting into this list */
1016 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
1017 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
1019 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1021 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1022 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1023 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1025 return wm;
1029 /*************************************************************************
1030 * alloc_thread_tls
1032 * Allocate the per-thread structure for module TLS storage.
1034 static NTSTATUS alloc_thread_tls(void)
1036 void **pointers;
1037 UINT i, size;
1039 if (!tls_module_count) return STATUS_SUCCESS;
1041 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1042 tls_module_count * sizeof(*pointers) )))
1043 return STATUS_NO_MEMORY;
1045 for (i = 0; i < tls_module_count; i++)
1047 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1049 if (!dir) continue;
1050 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1051 if (!size && !dir->SizeOfZeroFill) continue;
1053 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1055 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1056 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1057 return STATUS_NO_MEMORY;
1059 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1060 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1062 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1063 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1065 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1066 #if defined(__APPLE__) && defined(__x86_64__)
1067 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
1069 : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
1070 #endif
1071 return STATUS_SUCCESS;
1075 /*************************************************************************
1076 * call_tls_callbacks
1078 static void call_tls_callbacks( HMODULE module, UINT reason )
1080 const IMAGE_TLS_DIRECTORY *dir;
1081 const PIMAGE_TLS_CALLBACK *callback;
1082 ULONG dirsize;
1084 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1085 if (!dir || !dir->AddressOfCallBacks) return;
1087 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1089 TRACE_(relay)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1090 *callback, module, reason_names[reason] );
1091 __TRY
1093 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1095 __EXCEPT_ALL
1097 TRACE_(relay)("\1exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1098 callback, module, reason_names[reason] );
1099 return;
1101 __ENDTRY
1102 TRACE_(relay)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1103 *callback, module, reason_names[reason] );
1108 /*************************************************************************
1109 * MODULE_InitDLL
1111 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1113 WCHAR mod_name[32];
1114 NTSTATUS status = STATUS_SUCCESS;
1115 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1116 void *module = wm->ldr.BaseAddress;
1117 BOOL retv = FALSE;
1119 /* Skip calls for modules loaded with special load flags */
1121 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1122 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1123 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1125 if (TRACE_ON(relay))
1127 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1128 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1129 mod_name[len / sizeof(WCHAR)] = 0;
1130 TRACE_(relay)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1131 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved );
1133 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1134 reason_names[reason], lpReserved );
1136 __TRY
1138 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1139 if (!retv)
1140 status = STATUS_DLL_INIT_FAILED;
1142 __EXCEPT_ALL
1144 TRACE_(relay)("\1exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1145 entry, module, reason_names[reason], lpReserved );
1146 status = GetExceptionCode();
1148 __ENDTRY
1150 /* The state of the module list may have changed due to the call
1151 to the dll. We cannot assume that this module has not been
1152 deleted. */
1153 if (TRACE_ON(relay))
1154 TRACE_(relay)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1155 entry, module, debugstr_w(mod_name), reason_names[reason], lpReserved, retv );
1156 else
1157 TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1159 return status;
1163 /*************************************************************************
1164 * process_attach
1166 * Send the process attach notification to all DLLs the given module
1167 * depends on (recursively). This is somewhat complicated due to the fact that
1169 * - we have to respect the module dependencies, i.e. modules implicitly
1170 * referenced by another module have to be initialized before the module
1171 * itself can be initialized
1173 * - the initialization routine of a DLL can itself call LoadLibrary,
1174 * thereby introducing a whole new set of dependencies (even involving
1175 * the 'old' modules) at any time during the whole process
1177 * (Note that this routine can be recursively entered not only directly
1178 * from itself, but also via LoadLibrary from one of the called initialization
1179 * routines.)
1181 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1182 * the process *detach* notifications to be sent in the correct order.
1183 * This must not only take into account module dependencies, but also
1184 * 'hidden' dependencies created by modules calling LoadLibrary in their
1185 * attach notification routine.
1187 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1188 * list after the attach notification has returned. This implies that the
1189 * detach notifications are called in the reverse of the sequence the attach
1190 * notifications *returned*.
1192 * The loader_section must be locked while calling this function.
1194 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1196 NTSTATUS status = STATUS_SUCCESS;
1197 ULONG_PTR cookie;
1198 int i;
1200 if (process_detaching) return status;
1202 /* prevent infinite recursion in case of cyclical dependencies */
1203 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1204 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1205 return status;
1207 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1209 /* Tag current MODREF to prevent recursive loop */
1210 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1211 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1212 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1214 /* Recursively attach all DLLs this one depends on */
1215 for ( i = 0; i < wm->nDeps; i++ )
1217 if (!wm->deps[i]) continue;
1218 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1221 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1222 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1223 &wm->ldr.InInitializationOrderModuleList);
1225 /* Call DLL entry point */
1226 if (status == STATUS_SUCCESS)
1228 WINE_MODREF *prev = current_modref;
1229 current_modref = wm;
1230 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1231 if (status == STATUS_SUCCESS)
1232 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1233 else
1235 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1236 /* point to the name so LdrInitializeThunk can print it */
1237 last_failed_modref = wm;
1238 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1240 current_modref = prev;
1243 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1244 /* Remove recursion flag */
1245 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1247 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1248 return status;
1252 /**********************************************************************
1253 * attach_implicitly_loaded_dlls
1255 * Attach to the (builtin) dlls that have been implicitly loaded because
1256 * of a dependency at the Unix level, but not imported at the Win32 level.
1258 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1260 for (;;)
1262 PLIST_ENTRY mark, entry;
1264 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1265 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1267 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1269 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1270 TRACE( "found implicitly loaded %s, attaching to it\n",
1271 debugstr_w(mod->BaseDllName.Buffer));
1272 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1273 break; /* restart the search from the start */
1275 if (entry == mark) break; /* nothing found */
1280 /*************************************************************************
1281 * process_detach
1283 * Send DLL process detach notifications. See the comment about calling
1284 * sequence at process_attach.
1286 static void process_detach(void)
1288 PLIST_ENTRY mark, entry;
1289 PLDR_MODULE mod;
1291 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1294 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1296 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1297 InInitializationOrderModuleList);
1298 /* Check whether to detach this DLL */
1299 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1300 continue;
1301 if ( mod->LoadCount && !process_detaching )
1302 continue;
1304 /* Call detach notification */
1305 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1306 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1307 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1309 /* Restart at head of WINE_MODREF list, as entries might have
1310 been added and/or removed while performing the call ... */
1311 break;
1313 } while (entry != mark);
1316 /*************************************************************************
1317 * thread_attach
1319 * Send DLL thread attach notifications. These are sent in the
1320 * reverse sequence of process detach notification.
1321 * The loader_section must be locked while calling this function.
1323 static void thread_attach(void)
1325 PLIST_ENTRY mark, entry;
1326 PLDR_MODULE mod;
1328 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1329 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1331 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1332 InInitializationOrderModuleList);
1333 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1334 continue;
1335 if ( mod->Flags & LDR_NO_DLL_CALLS )
1336 continue;
1338 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), DLL_THREAD_ATTACH, NULL );
1342 /******************************************************************
1343 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1346 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1348 WINE_MODREF *wm;
1349 NTSTATUS ret = STATUS_SUCCESS;
1351 RtlEnterCriticalSection( &loader_section );
1353 wm = get_modref( hModule );
1354 if (!wm || wm->ldr.TlsIndex != -1)
1355 ret = STATUS_DLL_NOT_FOUND;
1356 else
1357 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1359 RtlLeaveCriticalSection( &loader_section );
1361 return ret;
1364 /******************************************************************
1365 * LdrFindEntryForAddress (NTDLL.@)
1367 * The loader_section must be locked while calling this function
1369 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1371 PLIST_ENTRY mark, entry;
1372 PLDR_MODULE mod;
1374 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1375 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1377 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1378 if (mod->BaseAddress <= addr &&
1379 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1381 *pmod = mod;
1382 return STATUS_SUCCESS;
1385 return STATUS_NO_MORE_ENTRIES;
1388 /******************************************************************
1389 * LdrEnumerateLoadedModules (NTDLL.@)
1391 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1393 LIST_ENTRY *mark, *entry;
1394 LDR_MODULE *mod;
1395 BOOLEAN stop = FALSE;
1397 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1399 if (unknown || !callback)
1400 return STATUS_INVALID_PARAMETER;
1402 RtlEnterCriticalSection( &loader_section );
1404 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1405 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1407 mod = CONTAINING_RECORD( entry, LDR_MODULE, InMemoryOrderModuleList );
1408 callback( mod, context, &stop );
1409 if (stop) break;
1412 RtlLeaveCriticalSection( &loader_section );
1413 return STATUS_SUCCESS;
1416 /******************************************************************
1417 * LdrLockLoaderLock (NTDLL.@)
1419 * Note: some flags are not implemented.
1420 * Flag 0x01 is used to raise exceptions on errors.
1422 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1424 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1426 if (result) *result = 0;
1427 if (magic) *magic = 0;
1428 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1429 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1430 if (!magic) return STATUS_INVALID_PARAMETER_3;
1432 if (flags & 0x2)
1434 if (!RtlTryEnterCriticalSection( &loader_section ))
1436 *result = 2;
1437 return STATUS_SUCCESS;
1439 *result = 1;
1441 else
1443 RtlEnterCriticalSection( &loader_section );
1444 if (result) *result = 1;
1446 *magic = GetCurrentThreadId();
1447 return STATUS_SUCCESS;
1451 /******************************************************************
1452 * LdrUnlockLoaderUnlock (NTDLL.@)
1454 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1456 if (magic)
1458 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1459 RtlLeaveCriticalSection( &loader_section );
1461 return STATUS_SUCCESS;
1465 /******************************************************************
1466 * LdrGetProcedureAddress (NTDLL.@)
1468 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1469 ULONG ord, PVOID *address)
1471 IMAGE_EXPORT_DIRECTORY *exports;
1472 DWORD exp_size;
1473 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1475 RtlEnterCriticalSection( &loader_section );
1477 /* check if the module itself is invalid to return the proper error */
1478 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1479 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1480 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1482 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1483 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1484 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1485 if (proc)
1487 *address = proc;
1488 ret = STATUS_SUCCESS;
1492 RtlLeaveCriticalSection( &loader_section );
1493 return ret;
1497 /***********************************************************************
1498 * is_fake_dll
1500 * Check if a loaded native dll is a Wine fake dll.
1502 static BOOL is_fake_dll( HANDLE handle )
1504 static const char fakedll_signature[] = "Wine placeholder DLL";
1505 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1506 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1507 IO_STATUS_BLOCK io;
1508 LARGE_INTEGER offset;
1510 offset.QuadPart = 0;
1511 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1512 if (io.Information < sizeof(buffer)) return FALSE;
1513 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1514 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1515 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1516 return FALSE;
1520 /***********************************************************************
1521 * get_builtin_fullname
1523 * Build the full pathname for a builtin dll.
1525 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1527 static const WCHAR soW[] = {'.','s','o',0};
1528 WCHAR *p, *fullname;
1529 size_t i, len = strlen(filename);
1531 /* check if path can correspond to the dll we have */
1532 if (path && (p = strrchrW( path, '\\' )))
1534 p++;
1535 for (i = 0; i < len; i++)
1536 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1537 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1539 /* the filename matches, use path as the full path */
1540 len += p - path;
1541 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1543 memcpy( fullname, path, len * sizeof(WCHAR) );
1544 fullname[len] = 0;
1546 return fullname;
1550 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1551 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1553 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1554 p = fullname + system_dir.Length / sizeof(WCHAR);
1555 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1556 ascii_to_unicode( p, filename, len + 1 );
1558 return fullname;
1562 /*************************************************************************
1563 * is_16bit_builtin
1565 static BOOL is_16bit_builtin( HMODULE module )
1567 const IMAGE_EXPORT_DIRECTORY *exports;
1568 DWORD exp_size;
1570 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1571 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1572 return FALSE;
1574 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1578 /***********************************************************************
1579 * load_builtin_callback
1581 * Load a library in memory; callback function for wine_dll_register
1583 static void load_builtin_callback( void *module, const char *filename )
1585 static const WCHAR emptyW[1];
1586 IMAGE_NT_HEADERS *nt;
1587 WINE_MODREF *wm;
1588 WCHAR *fullname;
1589 const WCHAR *load_path;
1591 if (!module)
1593 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1594 return;
1596 if (!(nt = RtlImageNtHeader( module )))
1598 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1599 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1600 return;
1603 virtual_create_builtin_view( module );
1605 /* create the MODREF */
1607 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1609 ERR( "can't load %s\n", filename );
1610 builtin_load_info->status = STATUS_NO_MEMORY;
1611 return;
1614 wm = alloc_module( module, fullname );
1615 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1616 if (!wm)
1618 ERR( "can't load %s\n", filename );
1619 builtin_load_info->status = STATUS_NO_MEMORY;
1620 return;
1622 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1624 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1625 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1626 is_16bit_builtin( module ))
1628 /* fixup imports */
1630 load_path = builtin_load_info->load_path;
1631 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1632 if (!load_path) load_path = emptyW;
1633 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1635 /* the module has only be inserted in the load & memory order lists */
1636 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1637 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1638 /* FIXME: free the modref */
1639 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1640 return;
1644 builtin_load_info->wm = wm;
1645 TRACE( "loaded %s %p %p\n", filename, wm, module );
1647 /* send the DLL load event */
1649 SERVER_START_REQ( load_dll )
1651 req->base = wine_server_client_ptr( module );
1652 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1653 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1654 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1655 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1656 wine_server_call( req );
1658 SERVER_END_REQ;
1660 /* setup relay debugging entry points */
1661 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1665 /***********************************************************************
1666 * set_security_cookie
1668 * Create a random security cookie for buffer overflow protection. Make
1669 * sure it does not accidentally match the default cookie value.
1671 static void set_security_cookie( void *module, SIZE_T len )
1673 static ULONG seed;
1674 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1675 ULONG loadcfg_size;
1676 ULONG_PTR *cookie;
1678 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1679 if (!loadcfg) return;
1680 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1681 if (!loadcfg->SecurityCookie) return;
1682 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1683 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1685 WARN( "security cookie %p outside of image %p-%p\n",
1686 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1687 return;
1690 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1691 TRACE( "initializing security cookie %p\n", cookie );
1693 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1694 for (;;)
1696 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1697 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1698 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1699 *cookie = RtlRandom( &seed );
1700 #ifdef DEFAULT_SECURITY_COOKIE_64
1701 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1703 *cookie = RtlRandom( &seed );
1704 /* fill up, but keep the highest word clear */
1705 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1707 #endif
1708 else
1709 break;
1713 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1715 IMAGE_NT_HEADERS *nt;
1716 char *base;
1717 IMAGE_BASE_RELOCATION *rel, *end;
1718 const IMAGE_DATA_DIRECTORY *relocs;
1719 const IMAGE_SECTION_HEADER *sec;
1720 INT_PTR delta;
1721 ULONG protect_old[96], i;
1723 nt = RtlImageNtHeader( module );
1724 base = (char *)nt->OptionalHeader.ImageBase;
1726 assert( module != base );
1728 /* no relocations are performed on non page-aligned binaries */
1729 if (nt->OptionalHeader.SectionAlignment < page_size)
1730 return STATUS_SUCCESS;
1732 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1733 return STATUS_SUCCESS;
1735 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1737 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1739 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1740 base, module );
1741 return STATUS_CONFLICTING_ADDRESSES;
1744 if (!relocs->Size) return STATUS_SUCCESS;
1745 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1747 if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
1748 return STATUS_INVALID_IMAGE_FORMAT;
1750 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1751 nt->FileHeader.SizeOfOptionalHeader);
1752 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1754 void *addr = get_rva( module, sec[i].VirtualAddress );
1755 SIZE_T size = sec[i].SizeOfRawData;
1756 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1757 &size, PAGE_READWRITE, &protect_old[i] );
1760 TRACE( "relocating from %p-%p to %p-%p\n",
1761 base, base + len, module, (char *)module + len );
1763 rel = get_rva( module, relocs->VirtualAddress );
1764 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1765 delta = (char *)module - base;
1767 while (rel < end - 1 && rel->SizeOfBlock)
1769 if (rel->VirtualAddress >= len)
1771 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1772 return STATUS_ACCESS_VIOLATION;
1774 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1775 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1776 (USHORT *)(rel + 1), delta );
1777 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1780 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1782 void *addr = get_rva( module, sec[i].VirtualAddress );
1783 SIZE_T size = sec[i].SizeOfRawData;
1784 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1785 &size, protect_old[i], &protect_old[i] );
1788 return STATUS_SUCCESS;
1791 /******************************************************************************
1792 * load_native_dll (internal)
1794 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1795 DWORD flags, WINE_MODREF** pwm )
1797 void *module;
1798 HANDLE mapping;
1799 LARGE_INTEGER size;
1800 IMAGE_NT_HEADERS *nt;
1801 SIZE_T len = 0;
1802 WINE_MODREF *wm;
1803 NTSTATUS status;
1805 TRACE("Trying native dll %s\n", debugstr_w(name));
1807 size.QuadPart = 0;
1808 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
1809 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
1810 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1811 if (status != STATUS_SUCCESS) return status;
1813 module = NULL;
1814 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1815 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1817 /* perform base relocation, if necessary */
1819 if (status == STATUS_IMAGE_NOT_AT_BASE)
1820 status = perform_relocations( module, len );
1822 if (status != STATUS_SUCCESS)
1824 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1825 goto done;
1828 /* create the MODREF */
1830 if (!(wm = alloc_module( module, name )))
1832 status = STATUS_NO_MEMORY;
1833 goto done;
1836 set_security_cookie( module, len );
1838 /* fixup imports */
1840 nt = RtlImageNtHeader( module );
1842 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1843 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1844 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1846 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1848 /* the module has only be inserted in the load & memory order lists */
1849 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1850 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1852 /* FIXME: there are several more dangling references
1853 * left. Including dlls loaded by this dll before the
1854 * failed one. Unrolling is rather difficult with the
1855 * current structure and we can leave them lying
1856 * around with no problems, so we don't care.
1857 * As these might reference our wm, we don't free it.
1859 goto done;
1863 /* send DLL load event */
1865 SERVER_START_REQ( load_dll )
1867 req->base = wine_server_client_ptr( module );
1868 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1869 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1870 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1871 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1872 wine_server_call( req );
1874 SERVER_END_REQ;
1876 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1878 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1880 wm->ldr.LoadCount = 1;
1881 *pwm = wm;
1882 status = STATUS_SUCCESS;
1883 done:
1884 NtClose( mapping );
1885 return status;
1889 /***********************************************************************
1890 * load_builtin_dll
1892 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1893 DWORD flags, WINE_MODREF** pwm )
1895 char error[256], dllname[MAX_PATH];
1896 const WCHAR *name, *p;
1897 DWORD len, i;
1898 void *handle;
1899 struct builtin_load_info info, *prev_info;
1901 /* Fix the name in case we have a full path and extension */
1902 name = path;
1903 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1904 if ((p = strrchrW( name, '/' ))) name = p + 1;
1906 /* load_library will modify info.status. Note also that load_library can be
1907 * called several times, if the .so file we're loading has dependencies.
1908 * info.status will gather all the errors we may get while loading all these
1909 * libraries
1911 info.load_path = load_path;
1912 info.filename = NULL;
1913 info.status = STATUS_SUCCESS;
1914 info.wm = NULL;
1916 if (file) /* we have a real file, try to load it */
1918 UNICODE_STRING nt_name;
1919 ANSI_STRING unix_name;
1921 TRACE("Trying built-in %s\n", debugstr_w(path));
1923 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1924 return STATUS_DLL_NOT_FOUND;
1926 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1928 RtlFreeUnicodeString( &nt_name );
1929 return STATUS_DLL_NOT_FOUND;
1931 prev_info = builtin_load_info;
1932 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1933 builtin_load_info = &info;
1934 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1935 builtin_load_info = prev_info;
1936 RtlFreeUnicodeString( &nt_name );
1937 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1938 if (!handle)
1940 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1941 return STATUS_INVALID_IMAGE_FORMAT;
1944 else
1946 int file_exists;
1948 TRACE("Trying built-in %s\n", debugstr_w(name));
1950 /* we don't want to depend on the current codepage here */
1951 len = strlenW( name ) + 1;
1952 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1953 for (i = 0; i < len; i++)
1955 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1956 dllname[i] = (char)name[i];
1957 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1960 prev_info = builtin_load_info;
1961 builtin_load_info = &info;
1962 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1963 builtin_load_info = prev_info;
1964 if (!handle)
1966 if (!file_exists)
1968 /* The file does not exist -> WARN() */
1969 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1970 return STATUS_DLL_NOT_FOUND;
1972 /* ERR() for all other errors (missing functions, ...) */
1973 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1974 return STATUS_PROCEDURE_NOT_FOUND;
1978 if (info.status != STATUS_SUCCESS)
1980 wine_dll_unload( handle );
1981 return info.status;
1984 if (!info.wm)
1986 PLIST_ENTRY mark, entry;
1988 /* The constructor wasn't called, this means the .so is already
1989 * loaded under a different name. Try to find the wm for it. */
1991 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1992 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1994 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1995 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1997 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1998 TRACE( "Found %s at %p for builtin %s\n",
1999 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
2000 break;
2003 wine_dll_unload( handle ); /* release the libdl refcount */
2004 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2005 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2007 else
2009 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2010 info.wm->ldr.LoadCount = 1;
2011 info.wm->ldr.SectionHandle = handle;
2014 *pwm = info.wm;
2015 return STATUS_SUCCESS;
2019 /***********************************************************************
2020 * find_actctx_dll
2022 * Find the full path (if any) of the dll from the activation context.
2024 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2026 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2027 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2029 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2030 ACTCTX_SECTION_KEYED_DATA data;
2031 UNICODE_STRING nameW;
2032 NTSTATUS status;
2033 SIZE_T needed, size = 1024;
2034 WCHAR *p;
2036 RtlInitUnicodeString( &nameW, libname );
2037 data.cbSize = sizeof(data);
2038 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2039 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2040 &nameW, &data );
2041 if (status != STATUS_SUCCESS) return status;
2043 for (;;)
2045 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2047 status = STATUS_NO_MEMORY;
2048 goto done;
2050 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2051 AssemblyDetailedInformationInActivationContext,
2052 info, size, &needed );
2053 if (status == STATUS_SUCCESS) break;
2054 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2055 RtlFreeHeap( GetProcessHeap(), 0, info );
2056 size = needed;
2057 /* restart with larger buffer */
2060 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2062 status = STATUS_SXS_KEY_NOT_FOUND;
2063 goto done;
2066 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2068 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2070 p++;
2071 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2073 /* manifest name does not match directory name, so it's not a global
2074 * windows/winsxs manifest; use the manifest directory name instead */
2075 dirlen = p - info->lpAssemblyManifestPath;
2076 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2077 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2079 status = STATUS_NO_MEMORY;
2080 goto done;
2082 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2083 p += dirlen;
2084 strcpyW( p, libname );
2085 goto done;
2089 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2090 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2092 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2094 status = STATUS_NO_MEMORY;
2095 goto done;
2097 strcpyW( p, user_shared_data->NtSystemRoot );
2098 p += strlenW(p);
2099 memcpy( p, winsxsW, sizeof(winsxsW) );
2100 p += sizeof(winsxsW) / sizeof(WCHAR);
2101 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2102 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2103 *p++ = '\\';
2104 strcpyW( p, libname );
2105 done:
2106 RtlFreeHeap( GetProcessHeap(), 0, info );
2107 RtlReleaseActivationContext( data.hActCtx );
2108 return status;
2112 /***********************************************************************
2113 * find_dll_file
2115 * Find the file (or already loaded module) for a given dll name.
2117 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2118 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
2120 OBJECT_ATTRIBUTES attr;
2121 IO_STATUS_BLOCK io;
2122 UNICODE_STRING nt_name;
2123 WCHAR *file_part, *ext, *dllname;
2124 ULONG len;
2126 /* first append .dll if needed */
2128 dllname = NULL;
2129 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2131 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2132 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2133 return STATUS_NO_MEMORY;
2134 strcpyW( dllname, libname );
2135 strcatW( dllname, dllW );
2136 libname = dllname;
2139 nt_name.Buffer = NULL;
2141 if (!contains_path( libname ))
2143 NTSTATUS status;
2144 WCHAR *fullname = NULL;
2146 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2148 status = find_actctx_dll( libname, &fullname );
2149 if (status == STATUS_SUCCESS)
2151 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2152 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2153 libname = dllname = fullname;
2155 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2157 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2158 return status;
2162 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2164 /* we need to search for it */
2165 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2166 if (len)
2168 if (len >= *size) goto overflow;
2169 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2171 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2173 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2174 return STATUS_NO_MEMORY;
2176 attr.Length = sizeof(attr);
2177 attr.RootDirectory = 0;
2178 attr.Attributes = OBJ_CASE_INSENSITIVE;
2179 attr.ObjectName = &nt_name;
2180 attr.SecurityDescriptor = NULL;
2181 attr.SecurityQualityOfService = NULL;
2182 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2183 goto found;
2186 /* not found */
2188 if (!contains_path( libname ))
2190 /* if libname doesn't contain a path at all, we simply return the name as is,
2191 * to be loaded as builtin */
2192 len = strlenW(libname) * sizeof(WCHAR);
2193 if (len >= *size) goto overflow;
2194 strcpyW( filename, libname );
2195 goto found;
2199 /* absolute path name, or relative path name but not found above */
2201 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2203 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2204 return STATUS_NO_MEMORY;
2206 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2207 if (len >= *size) goto overflow;
2208 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2209 if (!(*pwm = find_fullname_module( filename )) && handle)
2211 attr.Length = sizeof(attr);
2212 attr.RootDirectory = 0;
2213 attr.Attributes = OBJ_CASE_INSENSITIVE;
2214 attr.ObjectName = &nt_name;
2215 attr.SecurityDescriptor = NULL;
2216 attr.SecurityQualityOfService = NULL;
2217 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2219 found:
2220 RtlFreeUnicodeString( &nt_name );
2221 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2222 return STATUS_SUCCESS;
2224 overflow:
2225 RtlFreeUnicodeString( &nt_name );
2226 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2227 *size = len + sizeof(WCHAR);
2228 return STATUS_BUFFER_TOO_SMALL;
2232 /***********************************************************************
2233 * load_dll (internal)
2235 * Load a PE style module according to the load order.
2236 * The loader_section must be locked while calling this function.
2238 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2240 enum loadorder loadorder;
2241 WCHAR buffer[64];
2242 WCHAR *filename;
2243 ULONG size;
2244 WINE_MODREF *main_exe;
2245 HANDLE handle = 0;
2246 NTSTATUS nts;
2248 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2250 *pwm = NULL;
2251 filename = buffer;
2252 size = sizeof(buffer);
2253 for (;;)
2255 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2256 if (nts == STATUS_SUCCESS) break;
2257 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2258 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2259 /* grow the buffer and retry */
2260 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2263 if (*pwm) /* found already loaded module */
2265 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2267 TRACE("Found %s for %s at %p, count=%d\n",
2268 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2269 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2270 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2271 return STATUS_SUCCESS;
2274 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2275 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2277 if (handle && is_fake_dll( handle ))
2279 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2280 NtClose( handle );
2281 handle = 0;
2284 switch(loadorder)
2286 case LO_INVALID:
2287 nts = STATUS_NO_MEMORY;
2288 break;
2289 case LO_DISABLED:
2290 nts = STATUS_DLL_NOT_FOUND;
2291 break;
2292 case LO_NATIVE:
2293 case LO_NATIVE_BUILTIN:
2294 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2295 else
2297 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2298 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2299 /* not in PE format, maybe it's a builtin */
2300 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2302 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2303 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2304 break;
2305 case LO_BUILTIN:
2306 case LO_BUILTIN_NATIVE:
2307 case LO_DEFAULT: /* default is builtin,native */
2308 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2309 if (!handle) break; /* nothing else we can try */
2310 /* file is not a builtin library, try without using the specified file */
2311 if (nts != STATUS_SUCCESS)
2312 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2313 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2314 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2316 /* stub-only dll, try native */
2317 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2318 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2319 nts = STATUS_DLL_NOT_FOUND;
2321 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2322 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2323 break;
2326 if (nts == STATUS_SUCCESS)
2328 /* Initialize DLL just loaded */
2329 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2330 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2331 (*pwm)->ldr.BaseAddress);
2332 if (handle) NtClose( handle );
2333 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2334 return nts;
2337 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2338 if (handle) NtClose( handle );
2339 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2340 return nts;
2343 /******************************************************************
2344 * LdrLoadDll (NTDLL.@)
2346 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2347 const UNICODE_STRING *libname, HMODULE* hModule)
2349 WINE_MODREF *wm;
2350 NTSTATUS nts;
2352 RtlEnterCriticalSection( &loader_section );
2354 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2355 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2357 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2359 nts = process_attach( wm, NULL );
2360 if (nts != STATUS_SUCCESS)
2362 LdrUnloadDll(wm->ldr.BaseAddress);
2363 wm = NULL;
2366 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2368 RtlLeaveCriticalSection( &loader_section );
2369 return nts;
2373 /******************************************************************
2374 * LdrGetDllHandle (NTDLL.@)
2376 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2378 NTSTATUS status;
2379 WCHAR buffer[128];
2380 WCHAR *filename;
2381 ULONG size;
2382 WINE_MODREF *wm;
2384 RtlEnterCriticalSection( &loader_section );
2386 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2388 filename = buffer;
2389 size = sizeof(buffer);
2390 for (;;)
2392 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2393 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2394 if (status != STATUS_BUFFER_TOO_SMALL) break;
2395 /* grow the buffer and retry */
2396 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2398 status = STATUS_NO_MEMORY;
2399 break;
2403 if (status == STATUS_SUCCESS)
2405 if (wm) *base = wm->ldr.BaseAddress;
2406 else status = STATUS_DLL_NOT_FOUND;
2409 RtlLeaveCriticalSection( &loader_section );
2410 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2411 return status;
2415 /******************************************************************
2416 * LdrAddRefDll (NTDLL.@)
2418 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2420 NTSTATUS ret = STATUS_SUCCESS;
2421 WINE_MODREF *wm;
2423 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2425 RtlEnterCriticalSection( &loader_section );
2427 if ((wm = get_modref( module )))
2429 if (flags & LDR_ADDREF_DLL_PIN)
2430 wm->ldr.LoadCount = -1;
2431 else
2432 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2433 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2435 else ret = STATUS_INVALID_PARAMETER;
2437 RtlLeaveCriticalSection( &loader_section );
2438 return ret;
2442 /***********************************************************************
2443 * LdrProcessRelocationBlock (NTDLL.@)
2445 * Apply relocations to a given page of a mapped PE image.
2447 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2448 USHORT *relocs, INT_PTR delta )
2450 while (count--)
2452 USHORT offset = *relocs & 0xfff;
2453 int type = *relocs >> 12;
2454 switch(type)
2456 case IMAGE_REL_BASED_ABSOLUTE:
2457 break;
2458 case IMAGE_REL_BASED_HIGH:
2459 *(short *)((char *)page + offset) += HIWORD(delta);
2460 break;
2461 case IMAGE_REL_BASED_LOW:
2462 *(short *)((char *)page + offset) += LOWORD(delta);
2463 break;
2464 case IMAGE_REL_BASED_HIGHLOW:
2465 *(int *)((char *)page + offset) += delta;
2466 break;
2467 #ifdef _WIN64
2468 case IMAGE_REL_BASED_DIR64:
2469 *(INT_PTR *)((char *)page + offset) += delta;
2470 break;
2471 #elif defined(__arm__)
2472 case IMAGE_REL_BASED_THUMB_MOV32:
2474 DWORD inst = *(INT_PTR *)((char *)page + offset);
2475 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2476 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2477 DWORD hi_delta;
2479 if ((inst & 0x8000fbf0) != 0x0000f240)
2480 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2482 imm16 += LOWORD(delta);
2483 hi_delta = HIWORD(delta) + HIWORD(imm16);
2484 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2485 ((imm16 >> 12) & 0x000f) +
2486 ((imm16 << 20) & 0x70000000) +
2487 ((imm16 << 16) & 0xff0000);
2489 if (hi_delta != 0)
2491 inst = *(INT_PTR *)((char *)page + offset + 4);
2492 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2493 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2495 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2496 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2498 imm16 += hi_delta;
2499 if (imm16 > 0xffff)
2500 ERR("resulting immediate value won't fit: %08x\n", imm16);
2501 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2502 ((imm16 >> 1) & 0x0400) +
2503 ((imm16 >> 12) & 0x000f) +
2504 ((imm16 << 20) & 0x70000000) +
2505 ((imm16 << 16) & 0xff0000);
2508 break;
2509 #endif
2510 default:
2511 FIXME("Unknown/unsupported fixup type %x.\n", type);
2512 return NULL;
2514 relocs++;
2516 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2520 /******************************************************************
2521 * LdrQueryProcessModuleInformation
2524 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2525 ULONG buf_size, ULONG* req_size)
2527 SYSTEM_MODULE* sm = &smi->Modules[0];
2528 ULONG size = sizeof(ULONG);
2529 NTSTATUS nts = STATUS_SUCCESS;
2530 ANSI_STRING str;
2531 char* ptr;
2532 PLIST_ENTRY mark, entry;
2533 PLDR_MODULE mod;
2534 WORD id = 0;
2536 smi->ModulesCount = 0;
2538 RtlEnterCriticalSection( &loader_section );
2539 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2540 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2542 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2543 size += sizeof(*sm);
2544 if (size <= buf_size)
2546 sm->Reserved1 = 0; /* FIXME */
2547 sm->Reserved2 = 0; /* FIXME */
2548 sm->ImageBaseAddress = mod->BaseAddress;
2549 sm->ImageSize = mod->SizeOfImage;
2550 sm->Flags = mod->Flags;
2551 sm->Id = id++;
2552 sm->Rank = 0; /* FIXME */
2553 sm->Unknown = 0; /* FIXME */
2554 str.Length = 0;
2555 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2556 str.Buffer = (char*)sm->Name;
2557 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2558 ptr = strrchr(str.Buffer, '\\');
2559 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2561 smi->ModulesCount++;
2562 sm++;
2564 else nts = STATUS_INFO_LENGTH_MISMATCH;
2566 RtlLeaveCriticalSection( &loader_section );
2568 if (req_size) *req_size = size;
2570 return nts;
2574 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2576 NTSTATUS status;
2577 UNICODE_STRING str;
2578 ULONG size;
2579 WCHAR buffer[64];
2580 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2582 RtlInitUnicodeString( &str, name );
2584 size = sizeof(buffer) - sizeof(WCHAR);
2585 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2586 return status;
2588 if (info->Type != REG_DWORD)
2590 buffer[size / sizeof(WCHAR)] = 0;
2591 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2593 else memcpy( value, info->Data, sizeof(*value) );
2594 return status;
2597 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2598 void *data, ULONG in_size, ULONG *out_size )
2600 NTSTATUS status;
2601 UNICODE_STRING str;
2602 ULONG size;
2603 char *buffer;
2604 KEY_VALUE_PARTIAL_INFORMATION *info;
2605 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2607 RtlInitUnicodeString( &str, name );
2609 size = info_size + in_size;
2610 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2611 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2612 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2613 if (!status || status == STATUS_BUFFER_OVERFLOW)
2615 if (out_size) *out_size = info->DataLength;
2616 if (data && !status) memcpy( data, info->Data, info->DataLength );
2618 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2619 return status;
2623 /******************************************************************
2624 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2626 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2627 void *data, ULONG in_size, ULONG *out_size )
2629 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2630 'S','o','f','t','w','a','r','e','\\',
2631 'M','i','c','r','o','s','o','f','t','\\',
2632 'W','i','n','d','o','w','s',' ','N','T','\\',
2633 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2634 'I','m','a','g','e',' ','F','i','l','e',' ',
2635 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2636 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2637 OBJECT_ATTRIBUTES attr;
2638 UNICODE_STRING name_str;
2639 HANDLE hkey;
2640 NTSTATUS status;
2641 ULONG len;
2642 WCHAR *p;
2644 attr.Length = sizeof(attr);
2645 attr.RootDirectory = 0;
2646 attr.ObjectName = &name_str;
2647 attr.Attributes = OBJ_CASE_INSENSITIVE;
2648 attr.SecurityDescriptor = NULL;
2649 attr.SecurityQualityOfService = NULL;
2651 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2652 else p = key->Buffer;
2653 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2654 name_str.Buffer = path;
2655 name_str.Length = sizeof(optionsW) + len;
2656 name_str.MaximumLength = name_str.Length;
2657 memcpy( path, optionsW, sizeof(optionsW) );
2658 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2659 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2661 if (type == REG_DWORD)
2663 if (out_size) *out_size = sizeof(ULONG);
2664 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2665 else status = STATUS_BUFFER_OVERFLOW;
2667 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2669 NtClose( hkey );
2670 return status;
2674 /******************************************************************
2675 * RtlDllShutdownInProgress (NTDLL.@)
2677 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2679 return process_detaching;
2682 /****************************************************************************
2683 * LdrResolveDelayLoadedAPI (NTDLL.@)
2685 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2686 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2687 IMAGE_THUNK_DATA* addr, ULONG flags )
2689 IMAGE_THUNK_DATA *pIAT, *pINT;
2690 DELAYLOAD_INFO delayinfo;
2691 UNICODE_STRING mod;
2692 const CHAR* name;
2693 HMODULE *phmod;
2694 NTSTATUS nts;
2695 FARPROC fp;
2696 DWORD id;
2698 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2700 phmod = get_rva(base, desc->ModuleHandleRVA);
2701 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2702 pINT = get_rva(base, desc->ImportNameTableRVA);
2703 name = get_rva(base, desc->DllNameRVA);
2704 id = addr - pIAT;
2706 if (!*phmod)
2708 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2710 nts = STATUS_NO_MEMORY;
2711 goto fail;
2713 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2714 RtlFreeUnicodeString(&mod);
2715 if (nts) goto fail;
2718 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2719 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2720 else
2722 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2723 ANSI_STRING fnc;
2725 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2726 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2728 if (!nts)
2730 pIAT[id].u1.Function = (ULONG_PTR)fp;
2731 return fp;
2734 fail:
2735 delayinfo.Size = sizeof(delayinfo);
2736 delayinfo.DelayloadDescriptor = desc;
2737 delayinfo.ThunkAddress = addr;
2738 delayinfo.TargetDllName = name;
2739 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2740 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2741 delayinfo.TargetModuleBase = *phmod;
2742 delayinfo.Unused = NULL;
2743 delayinfo.LastError = nts;
2744 return dllhook(4, &delayinfo);
2747 /******************************************************************
2748 * LdrShutdownProcess (NTDLL.@)
2751 void WINAPI LdrShutdownProcess(void)
2753 TRACE("()\n");
2754 process_detaching = TRUE;
2755 process_detach();
2759 /******************************************************************
2760 * RtlExitUserProcess (NTDLL.@)
2762 void WINAPI RtlExitUserProcess( DWORD status )
2764 RtlEnterCriticalSection( &loader_section );
2765 RtlAcquirePebLock();
2766 NtTerminateProcess( 0, status );
2767 LdrShutdownProcess();
2768 NtTerminateProcess( GetCurrentProcess(), status );
2769 exit( status );
2772 /******************************************************************
2773 * LdrShutdownThread (NTDLL.@)
2776 void WINAPI LdrShutdownThread(void)
2778 PLIST_ENTRY mark, entry;
2779 PLDR_MODULE mod;
2780 UINT i;
2781 void **pointers;
2783 TRACE("()\n");
2785 /* don't do any detach calls if process is exiting */
2786 if (process_detaching) return;
2788 RtlEnterCriticalSection( &loader_section );
2790 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2791 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2793 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2794 InInitializationOrderModuleList);
2795 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2796 continue;
2797 if ( mod->Flags & LDR_NO_DLL_CALLS )
2798 continue;
2800 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2801 DLL_THREAD_DETACH, NULL );
2804 RtlAcquirePebLock();
2805 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2806 RtlReleasePebLock();
2808 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2810 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2811 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2813 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2814 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2815 RtlLeaveCriticalSection( &loader_section );
2819 /***********************************************************************
2820 * free_modref
2823 static void free_modref( WINE_MODREF *wm )
2825 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2826 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2827 if (wm->ldr.InInitializationOrderModuleList.Flink)
2828 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2830 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2831 if (!TRACE_ON(module))
2832 TRACE_(loaddll)("Unloaded module %s : %s\n",
2833 debugstr_w(wm->ldr.FullDllName.Buffer),
2834 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2836 SERVER_START_REQ( unload_dll )
2838 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2839 wine_server_call( req );
2841 SERVER_END_REQ;
2843 free_tls_slot( &wm->ldr );
2844 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2845 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2846 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2847 if (cached_modref == wm) cached_modref = NULL;
2848 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2849 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2850 RtlFreeHeap( GetProcessHeap(), 0, wm );
2853 /***********************************************************************
2854 * MODULE_FlushModrefs
2856 * Remove all unused modrefs and call the internal unloading routines
2857 * for the library type.
2859 * The loader_section must be locked while calling this function.
2861 static void MODULE_FlushModrefs(void)
2863 PLIST_ENTRY mark, entry, prev;
2864 PLDR_MODULE mod;
2865 WINE_MODREF*wm;
2867 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2868 for (entry = mark->Blink; entry != mark; entry = prev)
2870 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2871 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2872 prev = entry->Blink;
2873 if (!mod->LoadCount) free_modref( wm );
2876 /* check load order list too for modules that haven't been initialized yet */
2877 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2878 for (entry = mark->Blink; entry != mark; entry = prev)
2880 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2881 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2882 prev = entry->Blink;
2883 if (!mod->LoadCount) free_modref( wm );
2887 /***********************************************************************
2888 * MODULE_DecRefCount
2890 * The loader_section must be locked while calling this function.
2892 static void MODULE_DecRefCount( WINE_MODREF *wm )
2894 int i;
2896 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2897 return;
2899 if ( wm->ldr.LoadCount <= 0 )
2900 return;
2902 --wm->ldr.LoadCount;
2903 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2905 if ( wm->ldr.LoadCount == 0 )
2907 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2909 for ( i = 0; i < wm->nDeps; i++ )
2910 if ( wm->deps[i] )
2911 MODULE_DecRefCount( wm->deps[i] );
2913 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2917 /******************************************************************
2918 * LdrUnloadDll (NTDLL.@)
2922 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2924 WINE_MODREF *wm;
2925 NTSTATUS retv = STATUS_SUCCESS;
2927 if (process_detaching) return retv;
2929 TRACE("(%p)\n", hModule);
2931 RtlEnterCriticalSection( &loader_section );
2933 free_lib_count++;
2934 if ((wm = get_modref( hModule )) != NULL)
2936 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2938 /* Recursively decrement reference counts */
2939 MODULE_DecRefCount( wm );
2941 /* Call process detach notifications */
2942 if ( free_lib_count <= 1 )
2944 process_detach();
2945 MODULE_FlushModrefs();
2948 TRACE("END\n");
2950 else
2951 retv = STATUS_DLL_NOT_FOUND;
2953 free_lib_count--;
2955 RtlLeaveCriticalSection( &loader_section );
2957 return retv;
2960 /***********************************************************************
2961 * RtlImageNtHeader (NTDLL.@)
2963 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2965 IMAGE_NT_HEADERS *ret;
2967 __TRY
2969 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2971 ret = NULL;
2972 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2974 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2975 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2978 __EXCEPT_PAGE_FAULT
2980 return NULL;
2982 __ENDTRY
2983 return ret;
2987 /***********************************************************************
2988 * attach_dlls
2990 * Attach to all the loaded dlls.
2991 * If this is the first time, perform the full process initialization.
2993 NTSTATUS attach_dlls( CONTEXT *context, BOOL suspend )
2995 NTSTATUS status;
2996 WINE_MODREF *wm;
2997 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2999 if (suspend) wait_suspend( context );
3001 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3003 if (process_detaching) return STATUS_SUCCESS;
3005 RtlEnterCriticalSection( &loader_section );
3007 wm = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
3008 assert( wm );
3010 if (!imports_fixup_done)
3012 actctx_init();
3013 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
3015 ERR( "Importing dlls for %s failed, status %x\n",
3016 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3017 NtTerminateProcess( GetCurrentProcess(), status );
3019 imports_fixup_done = TRUE;
3022 RtlAcquirePebLock();
3023 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
3024 RtlReleasePebLock();
3026 if (!(wm->ldr.Flags & LDR_PROCESS_ATTACHED)) /* first time around */
3028 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3030 ERR( "TLS init failed when loading %s, status %x\n",
3031 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3032 NtTerminateProcess( GetCurrentProcess(), status );
3034 if ((status = process_attach( wm, context )) != STATUS_SUCCESS)
3036 if (last_failed_modref)
3037 ERR( "%s failed to initialize, aborting\n",
3038 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3039 ERR( "Initializing dlls for %s failed, status %x\n",
3040 debugstr_w(NtCurrentTeb()->Peb->ProcessParameters->ImagePathName.Buffer), status );
3041 NtTerminateProcess( GetCurrentProcess(), status );
3043 attach_implicitly_loaded_dlls( context );
3044 virtual_release_address_space();
3046 else
3048 if ((status = alloc_thread_tls()) != STATUS_SUCCESS)
3049 NtTerminateThread( GetCurrentThread(), status );
3050 thread_attach();
3053 RtlLeaveCriticalSection( &loader_section );
3054 return STATUS_SUCCESS;
3058 /***********************************************************************
3059 * load_global_options
3061 static void load_global_options(void)
3063 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3064 'S','y','s','t','e','m','\\',
3065 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3066 'C','o','n','t','r','o','l','\\',
3067 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3068 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3069 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};
3070 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3071 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3072 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};
3073 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};
3075 OBJECT_ATTRIBUTES attr;
3076 UNICODE_STRING name_str;
3077 HANDLE hkey;
3078 ULONG value;
3080 attr.Length = sizeof(attr);
3081 attr.RootDirectory = 0;
3082 attr.ObjectName = &name_str;
3083 attr.Attributes = OBJ_CASE_INSENSITIVE;
3084 attr.SecurityDescriptor = NULL;
3085 attr.SecurityQualityOfService = NULL;
3086 RtlInitUnicodeString( &name_str, sessionW );
3088 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3090 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3092 query_dword_option( hkey, critsectW, &value );
3093 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3095 query_dword_option( hkey, heapresW, &value );
3096 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3098 query_dword_option( hkey, heapcommitW, &value );
3099 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3101 query_dword_option( hkey, decommittotalW, &value );
3102 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3104 query_dword_option( hkey, decommitfreeW, &value );
3105 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3107 NtClose( hkey );
3111 /******************************************************************
3112 * LdrInitializeThunk (NTDLL.@)
3115 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3116 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3118 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3119 NTSTATUS status;
3120 WINE_MODREF *wm;
3121 PEB *peb = NtCurrentTeb()->Peb;
3123 kernel32_start_process = kernel_start;
3124 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
3126 /* allocate the modref for the main exe (if not already done) */
3127 wm = get_modref( peb->ImageBaseAddress );
3128 assert( wm );
3129 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3131 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3132 exit(1);
3135 peb->LoaderLock = &loader_section;
3136 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3137 if (!peb->ProcessParameters->WindowTitle.Buffer)
3138 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3139 version_init( wm->ldr.FullDllName.Buffer );
3140 virtual_set_large_address_space();
3142 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3143 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3144 heap_set_debug_flags( GetProcessHeap() );
3146 /* the main exe needs to be the first in the load order list */
3147 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3148 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3149 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3150 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3152 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL )) != STATUS_SUCCESS)
3154 ERR( "Main exe initialization for %s failed, status %x\n",
3155 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3156 NtTerminateProcess( GetCurrentProcess(), status );
3158 server_init_process_done();
3162 /***********************************************************************
3163 * RtlImageDirectoryEntryToData (NTDLL.@)
3165 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3167 const IMAGE_NT_HEADERS *nt;
3168 DWORD addr;
3170 if ((ULONG_PTR)module & 1) /* mapped as data file */
3172 module = (HMODULE)((ULONG_PTR)module & ~1);
3173 image = FALSE;
3175 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3176 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3178 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3180 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3181 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3182 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3183 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3185 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3187 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3189 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3190 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3191 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3192 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3194 else return NULL;
3196 /* not mapped as image, need to find the section containing the virtual address */
3197 return RtlImageRvaToVa( nt, module, addr, NULL );
3201 /***********************************************************************
3202 * RtlImageRvaToSection (NTDLL.@)
3204 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3205 HMODULE module, DWORD rva )
3207 int i;
3208 const IMAGE_SECTION_HEADER *sec;
3210 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3211 nt->FileHeader.SizeOfOptionalHeader);
3212 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3214 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3215 return (PIMAGE_SECTION_HEADER)sec;
3217 return NULL;
3221 /***********************************************************************
3222 * RtlImageRvaToVa (NTDLL.@)
3224 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3225 DWORD rva, IMAGE_SECTION_HEADER **section )
3227 IMAGE_SECTION_HEADER *sec;
3229 if (section && *section) /* try this section first */
3231 sec = *section;
3232 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3233 goto found;
3235 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3236 found:
3237 if (section) *section = sec;
3238 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3242 /***********************************************************************
3243 * RtlPcToFileHeader (NTDLL.@)
3245 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3247 LDR_MODULE *module;
3248 PVOID ret = NULL;
3250 RtlEnterCriticalSection( &loader_section );
3251 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3252 RtlLeaveCriticalSection( &loader_section );
3253 *address = ret;
3254 return ret;
3258 /***********************************************************************
3259 * NtLoadDriver (NTDLL.@)
3260 * ZwLoadDriver (NTDLL.@)
3262 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3264 FIXME("(%p), stub!\n",DriverServiceName);
3265 return STATUS_NOT_IMPLEMENTED;
3269 /***********************************************************************
3270 * NtUnloadDriver (NTDLL.@)
3271 * ZwUnloadDriver (NTDLL.@)
3273 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3275 FIXME("(%p), stub!\n",DriverServiceName);
3276 return STATUS_NOT_IMPLEMENTED;
3280 /******************************************************************
3281 * DllMain (NTDLL.@)
3283 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3285 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3286 return TRUE;
3290 /******************************************************************
3291 * __wine_init_windows_dir (NTDLL.@)
3293 * Windows and system dir initialization once kernel32 has been loaded.
3295 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3297 PLIST_ENTRY mark, entry;
3298 LPWSTR buffer, p;
3300 strcpyW( user_shared_data->NtSystemRoot, windir );
3301 DIR_init_windows_dir( windir, sysdir );
3303 /* prepend the system dir to the name of the already created modules */
3304 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3305 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3307 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3309 assert( mod->Flags & LDR_WINE_INTERNAL );
3311 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3312 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3313 if (!buffer) continue;
3314 strcpyW( buffer, system_dir.Buffer );
3315 p = buffer + strlenW( buffer );
3316 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3317 strcpyW( p, mod->FullDllName.Buffer );
3318 RtlInitUnicodeString( &mod->FullDllName, buffer );
3319 RtlInitUnicodeString( &mod->BaseDllName, p );
3324 /***********************************************************************
3325 * __wine_process_init
3327 void __wine_process_init(void)
3329 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3331 WINE_MODREF *wm;
3332 NTSTATUS status;
3333 ANSI_STRING func_name;
3334 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3336 main_exe_file = thread_init();
3338 /* retrieve current umask */
3339 FILE_umask = umask(0777);
3340 umask( FILE_umask );
3342 load_global_options();
3344 /* setup the load callback and create ntdll modref */
3345 wine_dll_set_callback( load_builtin_callback );
3347 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3349 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3350 exit(1);
3352 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3353 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3355 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3356 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3357 0, (void **)&init_func )) != STATUS_SUCCESS)
3359 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3360 exit(1);
3362 init_func();