ntdll: Don't clear the last page of the initial stack.
[wine.git] / dlls / ntdll / loader.c
blob31d83236c47618263e53acb41998caf7f3878730
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);
52 WINE_DECLARE_DEBUG_CHANNEL(pid);
54 #ifdef _WIN64
55 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
56 #endif
57 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
58 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
60 /* we don't want to include winuser.h */
61 #define RT_MANIFEST ((ULONG_PTR)24)
62 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
64 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
65 typedef void (CALLBACK *LDRENUMPROC)(LDR_MODULE *, void *, BOOLEAN *);
67 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 (process_attach( wm, NULL ) != STATUS_SUCCESS)
477 LdrUnloadDll( wm->ldr.BaseAddress );
478 wm = NULL;
482 if (!wm)
484 ERR( "module not found for forward '%s' used by %s\n",
485 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
486 return NULL;
489 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
490 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
492 const char *name = end + 1;
493 if (*name == '#') /* ordinal */
494 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
495 else
496 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
499 if (!proc)
501 ERR("function not found for forward '%s' used by %s."
502 " If you are using builtin %s, try using the native one instead.\n",
503 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
504 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
506 return proc;
510 /*************************************************************************
511 * find_ordinal_export
513 * Find an exported function by ordinal.
514 * The exports base must have been subtracted from the ordinal already.
515 * The loader_section must be locked while calling this function.
517 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
518 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
520 FARPROC proc;
521 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
523 if (ordinal >= exports->NumberOfFunctions)
525 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
526 return NULL;
528 if (!functions[ordinal]) return NULL;
530 proc = get_rva( module, functions[ordinal] );
532 /* if the address falls into the export dir, it's a forward */
533 if (((const char *)proc >= (const char *)exports) &&
534 ((const char *)proc < (const char *)exports + exp_size))
535 return find_forwarded_export( module, (const char *)proc, load_path );
537 if (TRACE_ON(snoop))
539 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
540 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
542 if (TRACE_ON(relay))
544 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
545 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
547 return proc;
551 /*************************************************************************
552 * find_named_export
554 * Find an exported function by name.
555 * The loader_section must be locked while calling this function.
557 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
558 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
560 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
561 const DWORD *names = get_rva( module, exports->AddressOfNames );
562 int min = 0, max = exports->NumberOfNames - 1;
564 /* first check the hint */
565 if (hint >= 0 && hint <= max)
567 char *ename = get_rva( module, names[hint] );
568 if (!strcmp( ename, name ))
569 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
572 /* then do a binary search */
573 while (min <= max)
575 int res, pos = (min + max) / 2;
576 char *ename = get_rva( module, names[pos] );
577 if (!(res = strcmp( ename, name )))
578 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
579 if (res > 0) max = pos - 1;
580 else min = pos + 1;
582 return NULL;
587 /*************************************************************************
588 * import_dll
590 * Import the dll specified by the given import descriptor.
591 * The loader_section must be locked while calling this function.
593 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
595 NTSTATUS status;
596 WINE_MODREF *wmImp;
597 HMODULE imp_mod;
598 const IMAGE_EXPORT_DIRECTORY *exports;
599 DWORD exp_size;
600 const IMAGE_THUNK_DATA *import_list;
601 IMAGE_THUNK_DATA *thunk_list;
602 WCHAR buffer[32];
603 const char *name = get_rva( module, descr->Name );
604 DWORD len = strlen(name);
605 PVOID protect_base;
606 SIZE_T protect_size = 0;
607 DWORD protect_old;
609 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
610 if (descr->u.OriginalFirstThunk)
611 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
612 else
613 import_list = thunk_list;
615 if (!import_list->u1.Ordinal)
617 WARN( "Skipping unused import %s\n", name );
618 *pwm = NULL;
619 return TRUE;
622 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
624 if (len * sizeof(WCHAR) < sizeof(buffer))
626 ascii_to_unicode( buffer, name, len );
627 buffer[len] = 0;
628 status = load_dll( load_path, buffer, 0, &wmImp );
630 else /* need to allocate a larger buffer */
632 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
633 if (!ptr) return FALSE;
634 ascii_to_unicode( ptr, name, len );
635 ptr[len] = 0;
636 status = load_dll( load_path, ptr, 0, &wmImp );
637 RtlFreeHeap( GetProcessHeap(), 0, ptr );
640 if (status)
642 if (status == STATUS_DLL_NOT_FOUND)
643 ERR("Library %s (which is needed by %s) not found\n",
644 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
645 else
646 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
647 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
648 return FALSE;
651 /* unprotect the import address table since it can be located in
652 * readonly section */
653 while (import_list[protect_size].u1.Ordinal) protect_size++;
654 protect_base = thunk_list;
655 protect_size *= sizeof(*thunk_list);
656 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
657 &protect_size, PAGE_READWRITE, &protect_old );
659 imp_mod = wmImp->ldr.BaseAddress;
660 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
662 if (!exports)
664 /* set all imported function to deadbeef */
665 while (import_list->u1.Ordinal)
667 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
669 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
670 WARN("No implementation for %s.%d", name, ordinal );
671 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
673 else
675 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
676 WARN("No implementation for %s.%s", name, pe_name->Name );
677 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
679 WARN(" imported from %s, allocating stub %p\n",
680 debugstr_w(current_modref->ldr.FullDllName.Buffer),
681 (void *)thunk_list->u1.Function );
682 import_list++;
683 thunk_list++;
685 goto done;
688 while (import_list->u1.Ordinal)
690 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
692 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
694 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
695 ordinal - exports->Base, load_path );
696 if (!thunk_list->u1.Function)
698 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
699 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
700 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
701 (void *)thunk_list->u1.Function );
703 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
705 else /* import by name */
707 IMAGE_IMPORT_BY_NAME *pe_name;
708 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
709 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
710 (const char*)pe_name->Name,
711 pe_name->Hint, load_path );
712 if (!thunk_list->u1.Function)
714 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
715 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
716 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
717 (void *)thunk_list->u1.Function );
719 TRACE_(imports)("--- %s %s.%d = %p\n",
720 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
722 import_list++;
723 thunk_list++;
726 done:
727 /* restore old protection of the import address table */
728 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
729 *pwm = wmImp;
730 return TRUE;
734 /***********************************************************************
735 * create_module_activation_context
737 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
739 NTSTATUS status;
740 LDR_RESOURCE_INFO info;
741 const IMAGE_RESOURCE_DATA_ENTRY *entry;
743 info.Type = RT_MANIFEST;
744 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
745 info.Language = 0;
746 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
748 ACTCTXW ctx;
749 ctx.cbSize = sizeof(ctx);
750 ctx.lpSource = NULL;
751 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
752 ctx.hModule = module->BaseAddress;
753 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
754 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
756 return status;
760 /*************************************************************************
761 * is_dll_native_subsystem
763 * Check if dll is a proper native driver.
764 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
765 * while being perfectly normal DLLs. This heuristic should catch such breakages.
767 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
769 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
770 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
771 const IMAGE_IMPORT_DESCRIPTOR *imports;
772 DWORD i, size;
773 WCHAR buffer[16];
775 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
776 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
778 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
779 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
781 for (i = 0; imports[i].Name; i++)
783 const char *name = get_rva( module, imports[i].Name );
784 DWORD len = strlen(name);
785 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
786 ascii_to_unicode( buffer, name, len + 1 );
787 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
789 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
790 return FALSE;
794 return TRUE;
797 /*************************************************************************
798 * alloc_tls_slot
800 * Allocate a TLS slot for a newly-loaded module.
801 * The loader_section must be locked while calling this function.
803 static SHORT alloc_tls_slot( LDR_MODULE *mod )
805 const IMAGE_TLS_DIRECTORY *dir;
806 ULONG i, size;
807 void *new_ptr;
808 LIST_ENTRY *entry;
810 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
811 return -1;
813 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
814 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
816 for (i = 0; i < tls_module_count; i++)
818 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
819 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
820 break;
823 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
824 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
825 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
827 if (i == tls_module_count)
829 UINT new_count = max( 32, tls_module_count * 2 );
831 if (!tls_dirs)
832 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
833 else
834 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
835 new_count * sizeof(*tls_dirs) );
836 if (!new_ptr) return -1;
838 /* resize the pointer block in all running threads */
839 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
841 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
842 void **old = teb->ThreadLocalStoragePointer;
843 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
845 if (!new) return -1;
846 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
847 teb->ThreadLocalStoragePointer = new;
848 #if defined(__APPLE__) && defined(__x86_64__)
849 if (teb->Reserved5[0])
850 ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
851 #endif
852 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
853 /* FIXME: can't free old block here, should be freed at thread exit */
856 tls_dirs = new_ptr;
857 tls_module_count = new_count;
860 /* allocate the data block in all running threads */
861 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
863 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
865 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
866 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
867 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
869 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
870 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
872 RtlFreeHeap( GetProcessHeap(), 0,
873 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
876 *(DWORD *)dir->AddressOfIndex = i;
877 tls_dirs[i] = *dir;
878 return i;
882 /*************************************************************************
883 * free_tls_slot
885 * Free the module TLS slot on unload.
886 * The loader_section must be locked while calling this function.
888 static void free_tls_slot( LDR_MODULE *mod )
890 ULONG i = (USHORT)mod->TlsIndex;
892 if (mod->TlsIndex == -1) return;
893 assert( i < tls_module_count );
894 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
898 /****************************************************************
899 * fixup_imports
901 * Fixup all imports of a given module.
902 * The loader_section must be locked while calling this function.
904 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
906 int i, nb_imports;
907 const IMAGE_IMPORT_DESCRIPTOR *imports;
908 WINE_MODREF *prev;
909 DWORD size;
910 NTSTATUS status;
911 ULONG_PTR cookie;
913 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
914 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
916 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
918 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
919 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
920 return STATUS_SUCCESS;
922 nb_imports = 0;
923 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
925 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
927 if (!create_module_activation_context( &wm->ldr ))
928 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
930 /* Allocate module dependency list */
931 wm->nDeps = nb_imports;
932 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
934 /* load the imported modules. They are automatically
935 * added to the modref list of the process.
937 prev = current_modref;
938 current_modref = wm;
939 status = STATUS_SUCCESS;
940 for (i = 0; i < nb_imports; i++)
942 if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &wm->deps[i] ))
944 wm->deps[i] = NULL;
945 status = STATUS_DLL_NOT_FOUND;
948 current_modref = prev;
949 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
950 return status;
954 /*************************************************************************
955 * alloc_module
957 * Allocate a WINE_MODREF structure and add it to the process list
958 * The loader_section must be locked while calling this function.
960 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
962 WINE_MODREF *wm;
963 const WCHAR *p;
964 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
966 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
968 wm->nDeps = 0;
969 wm->deps = NULL;
971 wm->ldr.BaseAddress = hModule;
972 wm->ldr.EntryPoint = NULL;
973 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
974 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
975 wm->ldr.TlsIndex = -1;
976 wm->ldr.LoadCount = 1;
977 wm->ldr.SectionHandle = NULL;
978 wm->ldr.CheckSum = 0;
979 wm->ldr.TimeDateStamp = 0;
980 wm->ldr.ActivationContext = 0;
982 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
983 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
984 else p = wm->ldr.FullDllName.Buffer;
985 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
987 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
989 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
990 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
991 if (nt->OptionalHeader.AddressOfEntryPoint)
992 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
995 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
996 &wm->ldr.InLoadOrderModuleList);
997 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
998 &wm->ldr.InMemoryOrderModuleList);
1000 /* wait until init is called for inserting into this list */
1001 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
1002 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
1004 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
1006 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
1007 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
1008 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
1010 return wm;
1014 /*************************************************************************
1015 * alloc_thread_tls
1017 * Allocate the per-thread structure for module TLS storage.
1019 static NTSTATUS alloc_thread_tls(void)
1021 void **pointers;
1022 UINT i, size;
1024 if (!tls_module_count) return STATUS_SUCCESS;
1026 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1027 tls_module_count * sizeof(*pointers) )))
1028 return STATUS_NO_MEMORY;
1030 for (i = 0; i < tls_module_count; i++)
1032 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1034 if (!dir) continue;
1035 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1036 if (!size && !dir->SizeOfZeroFill) continue;
1038 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1040 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1041 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1042 return STATUS_NO_MEMORY;
1044 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1045 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1047 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1048 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1050 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1051 #if defined(__APPLE__) && defined(__x86_64__)
1052 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
1054 : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
1055 #endif
1056 return STATUS_SUCCESS;
1060 /*************************************************************************
1061 * call_tls_callbacks
1063 static void call_tls_callbacks( HMODULE module, UINT reason )
1065 const IMAGE_TLS_DIRECTORY *dir;
1066 const PIMAGE_TLS_CALLBACK *callback;
1067 ULONG dirsize;
1069 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1070 if (!dir || !dir->AddressOfCallBacks) return;
1072 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1074 if (TRACE_ON(relay))
1076 if (TRACE_ON(pid))
1077 DPRINTF( "%04x:", GetCurrentProcessId() );
1078 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1079 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1081 __TRY
1083 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1085 __EXCEPT_ALL
1087 if (TRACE_ON(relay))
1089 if (TRACE_ON(pid))
1090 DPRINTF( "%04x:", GetCurrentProcessId() );
1091 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1092 GetCurrentThreadId(), callback, module, reason_names[reason] );
1094 return;
1096 __ENDTRY
1097 if (TRACE_ON(relay))
1099 if (TRACE_ON(pid))
1100 DPRINTF( "%04x:", GetCurrentProcessId() );
1101 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1102 GetCurrentThreadId(), *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 if (TRACE_ON(pid))
1131 DPRINTF( "%04x:", GetCurrentProcessId() );
1132 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1133 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1134 reason_names[reason], lpReserved );
1136 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1137 reason_names[reason], lpReserved );
1139 __TRY
1141 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1142 if (!retv)
1143 status = STATUS_DLL_INIT_FAILED;
1145 __EXCEPT_ALL
1147 if (TRACE_ON(relay))
1149 if (TRACE_ON(pid))
1150 DPRINTF( "%04x:", GetCurrentProcessId() );
1151 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1152 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1154 status = GetExceptionCode();
1156 __ENDTRY
1158 /* The state of the module list may have changed due to the call
1159 to the dll. We cannot assume that this module has not been
1160 deleted. */
1161 if (TRACE_ON(relay))
1163 if (TRACE_ON(pid))
1164 DPRINTF( "%04x:", GetCurrentProcessId() );
1165 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1166 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1167 reason_names[reason], lpReserved, retv );
1169 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1171 return status;
1175 /*************************************************************************
1176 * process_attach
1178 * Send the process attach notification to all DLLs the given module
1179 * depends on (recursively). This is somewhat complicated due to the fact that
1181 * - we have to respect the module dependencies, i.e. modules implicitly
1182 * referenced by another module have to be initialized before the module
1183 * itself can be initialized
1185 * - the initialization routine of a DLL can itself call LoadLibrary,
1186 * thereby introducing a whole new set of dependencies (even involving
1187 * the 'old' modules) at any time during the whole process
1189 * (Note that this routine can be recursively entered not only directly
1190 * from itself, but also via LoadLibrary from one of the called initialization
1191 * routines.)
1193 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1194 * the process *detach* notifications to be sent in the correct order.
1195 * This must not only take into account module dependencies, but also
1196 * 'hidden' dependencies created by modules calling LoadLibrary in their
1197 * attach notification routine.
1199 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1200 * list after the attach notification has returned. This implies that the
1201 * detach notifications are called in the reverse of the sequence the attach
1202 * notifications *returned*.
1204 * The loader_section must be locked while calling this function.
1206 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1208 NTSTATUS status = STATUS_SUCCESS;
1209 ULONG_PTR cookie;
1210 int i;
1212 if (process_detaching) return status;
1214 /* prevent infinite recursion in case of cyclical dependencies */
1215 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1216 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1217 return status;
1219 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1221 /* Tag current MODREF to prevent recursive loop */
1222 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1223 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1224 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1226 /* Recursively attach all DLLs this one depends on */
1227 for ( i = 0; i < wm->nDeps; i++ )
1229 if (!wm->deps[i]) continue;
1230 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1233 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1234 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1235 &wm->ldr.InInitializationOrderModuleList);
1237 /* Call DLL entry point */
1238 if (status == STATUS_SUCCESS)
1240 WINE_MODREF *prev = current_modref;
1241 current_modref = wm;
1242 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1243 if (status == STATUS_SUCCESS)
1244 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1245 else
1247 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1248 /* point to the name so LdrInitializeThunk can print it */
1249 last_failed_modref = wm;
1250 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1252 current_modref = prev;
1255 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1256 /* Remove recursion flag */
1257 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1259 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1260 return status;
1264 /**********************************************************************
1265 * attach_implicitly_loaded_dlls
1267 * Attach to the (builtin) dlls that have been implicitly loaded because
1268 * of a dependency at the Unix level, but not imported at the Win32 level.
1270 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1272 for (;;)
1274 PLIST_ENTRY mark, entry;
1276 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1277 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1279 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1281 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1282 TRACE( "found implicitly loaded %s, attaching to it\n",
1283 debugstr_w(mod->BaseDllName.Buffer));
1284 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1285 break; /* restart the search from the start */
1287 if (entry == mark) break; /* nothing found */
1292 /*************************************************************************
1293 * process_detach
1295 * Send DLL process detach notifications. See the comment about calling
1296 * sequence at process_attach.
1298 static void process_detach(void)
1300 PLIST_ENTRY mark, entry;
1301 PLDR_MODULE mod;
1303 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1306 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1308 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1309 InInitializationOrderModuleList);
1310 /* Check whether to detach this DLL */
1311 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1312 continue;
1313 if ( mod->LoadCount && !process_detaching )
1314 continue;
1316 /* Call detach notification */
1317 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1318 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1319 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1321 /* Restart at head of WINE_MODREF list, as entries might have
1322 been added and/or removed while performing the call ... */
1323 break;
1325 } while (entry != mark);
1328 /*************************************************************************
1329 * MODULE_DllThreadAttach
1331 * Send DLL thread attach notifications. These are sent in the
1332 * reverse sequence of process detach notification.
1335 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1337 PLIST_ENTRY mark, entry;
1338 PLDR_MODULE mod;
1339 NTSTATUS status;
1341 /* don't do any attach calls if process is exiting */
1342 if (process_detaching) return STATUS_SUCCESS;
1344 RtlEnterCriticalSection( &loader_section );
1346 RtlAcquirePebLock();
1347 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1348 RtlReleasePebLock();
1350 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1352 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1353 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1355 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1356 InInitializationOrderModuleList);
1357 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1358 continue;
1359 if ( mod->Flags & LDR_NO_DLL_CALLS )
1360 continue;
1362 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1363 DLL_THREAD_ATTACH, lpReserved );
1366 done:
1367 RtlLeaveCriticalSection( &loader_section );
1368 return status;
1371 /******************************************************************
1372 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1375 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1377 WINE_MODREF *wm;
1378 NTSTATUS ret = STATUS_SUCCESS;
1380 RtlEnterCriticalSection( &loader_section );
1382 wm = get_modref( hModule );
1383 if (!wm || wm->ldr.TlsIndex != -1)
1384 ret = STATUS_DLL_NOT_FOUND;
1385 else
1386 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1388 RtlLeaveCriticalSection( &loader_section );
1390 return ret;
1393 /******************************************************************
1394 * LdrFindEntryForAddress (NTDLL.@)
1396 * The loader_section must be locked while calling this function
1398 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1400 PLIST_ENTRY mark, entry;
1401 PLDR_MODULE mod;
1403 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1404 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1406 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1407 if (mod->BaseAddress <= addr &&
1408 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1410 *pmod = mod;
1411 return STATUS_SUCCESS;
1414 return STATUS_NO_MORE_ENTRIES;
1417 /******************************************************************
1418 * LdrEnumerateLoadedModules (NTDLL.@)
1420 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1422 LIST_ENTRY *mark, *entry;
1423 LDR_MODULE *mod;
1424 BOOLEAN stop = FALSE;
1426 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1428 if (unknown || !callback)
1429 return STATUS_INVALID_PARAMETER;
1431 RtlEnterCriticalSection( &loader_section );
1433 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1434 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1436 mod = CONTAINING_RECORD( entry, LDR_MODULE, InMemoryOrderModuleList );
1437 callback( mod, context, &stop );
1438 if (stop) break;
1441 RtlLeaveCriticalSection( &loader_section );
1442 return STATUS_SUCCESS;
1445 /******************************************************************
1446 * LdrLockLoaderLock (NTDLL.@)
1448 * Note: some flags are not implemented.
1449 * Flag 0x01 is used to raise exceptions on errors.
1451 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1453 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1455 if (result) *result = 0;
1456 if (magic) *magic = 0;
1457 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1458 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1459 if (!magic) return STATUS_INVALID_PARAMETER_3;
1461 if (flags & 0x2)
1463 if (!RtlTryEnterCriticalSection( &loader_section ))
1465 *result = 2;
1466 return STATUS_SUCCESS;
1468 *result = 1;
1470 else
1472 RtlEnterCriticalSection( &loader_section );
1473 if (result) *result = 1;
1475 *magic = GetCurrentThreadId();
1476 return STATUS_SUCCESS;
1480 /******************************************************************
1481 * LdrUnlockLoaderUnlock (NTDLL.@)
1483 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1485 if (magic)
1487 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1488 RtlLeaveCriticalSection( &loader_section );
1490 return STATUS_SUCCESS;
1494 /******************************************************************
1495 * LdrGetProcedureAddress (NTDLL.@)
1497 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1498 ULONG ord, PVOID *address)
1500 IMAGE_EXPORT_DIRECTORY *exports;
1501 DWORD exp_size;
1502 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1504 RtlEnterCriticalSection( &loader_section );
1506 /* check if the module itself is invalid to return the proper error */
1507 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1508 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1509 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1511 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1512 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1513 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1514 if (proc)
1516 *address = proc;
1517 ret = STATUS_SUCCESS;
1521 RtlLeaveCriticalSection( &loader_section );
1522 return ret;
1526 /***********************************************************************
1527 * is_fake_dll
1529 * Check if a loaded native dll is a Wine fake dll.
1531 static BOOL is_fake_dll( HANDLE handle )
1533 static const char fakedll_signature[] = "Wine placeholder DLL";
1534 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1535 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1536 IO_STATUS_BLOCK io;
1537 LARGE_INTEGER offset;
1539 offset.QuadPart = 0;
1540 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1541 if (io.Information < sizeof(buffer)) return FALSE;
1542 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1543 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1544 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1545 return FALSE;
1549 /***********************************************************************
1550 * get_builtin_fullname
1552 * Build the full pathname for a builtin dll.
1554 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1556 static const WCHAR soW[] = {'.','s','o',0};
1557 WCHAR *p, *fullname;
1558 size_t i, len = strlen(filename);
1560 /* check if path can correspond to the dll we have */
1561 if (path && (p = strrchrW( path, '\\' )))
1563 p++;
1564 for (i = 0; i < len; i++)
1565 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1566 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1568 /* the filename matches, use path as the full path */
1569 len += p - path;
1570 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1572 memcpy( fullname, path, len * sizeof(WCHAR) );
1573 fullname[len] = 0;
1575 return fullname;
1579 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1580 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1582 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1583 p = fullname + system_dir.Length / sizeof(WCHAR);
1584 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1585 ascii_to_unicode( p, filename, len + 1 );
1587 return fullname;
1591 /*************************************************************************
1592 * is_16bit_builtin
1594 static BOOL is_16bit_builtin( HMODULE module )
1596 const IMAGE_EXPORT_DIRECTORY *exports;
1597 DWORD exp_size;
1599 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1600 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1601 return FALSE;
1603 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1607 /***********************************************************************
1608 * load_builtin_callback
1610 * Load a library in memory; callback function for wine_dll_register
1612 static void load_builtin_callback( void *module, const char *filename )
1614 static const WCHAR emptyW[1];
1615 IMAGE_NT_HEADERS *nt;
1616 WINE_MODREF *wm;
1617 WCHAR *fullname;
1618 const WCHAR *load_path;
1620 if (!module)
1622 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1623 return;
1625 if (!(nt = RtlImageNtHeader( module )))
1627 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1628 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1629 return;
1632 virtual_create_builtin_view( module );
1634 /* create the MODREF */
1636 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1638 ERR( "can't load %s\n", filename );
1639 builtin_load_info->status = STATUS_NO_MEMORY;
1640 return;
1643 wm = alloc_module( module, fullname );
1644 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1645 if (!wm)
1647 ERR( "can't load %s\n", filename );
1648 builtin_load_info->status = STATUS_NO_MEMORY;
1649 return;
1651 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1653 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1654 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1655 is_16bit_builtin( module ))
1657 /* fixup imports */
1659 load_path = builtin_load_info->load_path;
1660 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1661 if (!load_path) load_path = emptyW;
1662 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1664 /* the module has only be inserted in the load & memory order lists */
1665 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1666 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1667 /* FIXME: free the modref */
1668 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1669 return;
1673 builtin_load_info->wm = wm;
1674 TRACE( "loaded %s %p %p\n", filename, wm, module );
1676 /* send the DLL load event */
1678 SERVER_START_REQ( load_dll )
1680 req->mapping = 0;
1681 req->base = wine_server_client_ptr( module );
1682 req->size = nt->OptionalHeader.SizeOfImage;
1683 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1684 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1685 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1686 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1687 wine_server_call( req );
1689 SERVER_END_REQ;
1691 /* setup relay debugging entry points */
1692 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1696 /***********************************************************************
1697 * set_security_cookie
1699 * Create a random security cookie for buffer overflow protection. Make
1700 * sure it does not accidentally match the default cookie value.
1702 static void set_security_cookie( void *module, SIZE_T len )
1704 static ULONG seed;
1705 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1706 ULONG loadcfg_size;
1707 ULONG_PTR *cookie;
1709 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1710 if (!loadcfg) return;
1711 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1712 if (!loadcfg->SecurityCookie) return;
1713 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1714 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1716 WARN( "security cookie %p outside of image %p-%p\n",
1717 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1718 return;
1721 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1722 TRACE( "initializing security cookie %p\n", cookie );
1724 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1725 for (;;)
1727 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1728 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1729 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1730 *cookie = RtlRandom( &seed );
1731 #ifdef DEFAULT_SECURITY_COOKIE_64
1732 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1734 *cookie = RtlRandom( &seed );
1735 /* fill up, but keep the highest word clear */
1736 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1738 #endif
1739 else
1740 break;
1744 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1746 IMAGE_NT_HEADERS *nt;
1747 char *base;
1748 IMAGE_BASE_RELOCATION *rel, *end;
1749 const IMAGE_DATA_DIRECTORY *relocs;
1750 const IMAGE_SECTION_HEADER *sec;
1751 INT_PTR delta;
1752 ULONG protect_old[96], i;
1754 nt = RtlImageNtHeader( module );
1755 base = (char *)nt->OptionalHeader.ImageBase;
1757 assert( module != base );
1759 /* no relocations are performed on non page-aligned binaries */
1760 if (nt->OptionalHeader.SectionAlignment < page_size)
1761 return STATUS_SUCCESS;
1763 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1764 return STATUS_SUCCESS;
1766 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1768 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1770 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1771 base, module );
1772 return STATUS_CONFLICTING_ADDRESSES;
1775 if (!relocs->Size) return STATUS_SUCCESS;
1776 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1778 if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
1779 return STATUS_INVALID_IMAGE_FORMAT;
1781 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1782 nt->FileHeader.SizeOfOptionalHeader);
1783 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1785 void *addr = get_rva( module, sec[i].VirtualAddress );
1786 SIZE_T size = sec[i].SizeOfRawData;
1787 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1788 &size, PAGE_READWRITE, &protect_old[i] );
1791 TRACE( "relocating from %p-%p to %p-%p\n",
1792 base, base + len, module, (char *)module + len );
1794 rel = get_rva( module, relocs->VirtualAddress );
1795 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1796 delta = (char *)module - base;
1798 while (rel < end - 1 && rel->SizeOfBlock)
1800 if (rel->VirtualAddress >= len)
1802 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1803 return STATUS_ACCESS_VIOLATION;
1805 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1806 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1807 (USHORT *)(rel + 1), delta );
1808 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1811 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1813 void *addr = get_rva( module, sec[i].VirtualAddress );
1814 SIZE_T size = sec[i].SizeOfRawData;
1815 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1816 &size, protect_old[i], &protect_old[i] );
1819 return STATUS_SUCCESS;
1822 /******************************************************************************
1823 * load_native_dll (internal)
1825 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1826 DWORD flags, WINE_MODREF** pwm )
1828 void *module;
1829 HANDLE mapping;
1830 LARGE_INTEGER size;
1831 IMAGE_NT_HEADERS *nt;
1832 SIZE_T len = 0;
1833 WINE_MODREF *wm;
1834 NTSTATUS status;
1836 TRACE("Trying native dll %s\n", debugstr_w(name));
1838 size.QuadPart = 0;
1839 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
1840 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
1841 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1842 if (status != STATUS_SUCCESS) return status;
1844 module = NULL;
1845 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1846 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1848 /* perform base relocation, if necessary */
1850 if (status == STATUS_IMAGE_NOT_AT_BASE)
1851 status = perform_relocations( module, len );
1853 if (status != STATUS_SUCCESS)
1855 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1856 goto done;
1859 /* create the MODREF */
1861 if (!(wm = alloc_module( module, name )))
1863 status = STATUS_NO_MEMORY;
1864 goto done;
1867 set_security_cookie( module, len );
1869 /* fixup imports */
1871 nt = RtlImageNtHeader( module );
1873 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1874 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1875 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1877 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1879 /* the module has only be inserted in the load & memory order lists */
1880 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1881 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1883 /* FIXME: there are several more dangling references
1884 * left. Including dlls loaded by this dll before the
1885 * failed one. Unrolling is rather difficult with the
1886 * current structure and we can leave them lying
1887 * around with no problems, so we don't care.
1888 * As these might reference our wm, we don't free it.
1890 goto done;
1894 /* send DLL load event */
1896 SERVER_START_REQ( load_dll )
1898 req->mapping = wine_server_obj_handle( mapping );
1899 req->base = wine_server_client_ptr( module );
1900 req->size = nt->OptionalHeader.SizeOfImage;
1901 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1902 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1903 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1904 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1905 wine_server_call( req );
1907 SERVER_END_REQ;
1909 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1911 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1913 wm->ldr.LoadCount = 1;
1914 *pwm = wm;
1915 status = STATUS_SUCCESS;
1916 done:
1917 NtClose( mapping );
1918 return status;
1922 /***********************************************************************
1923 * load_builtin_dll
1925 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1926 DWORD flags, WINE_MODREF** pwm )
1928 char error[256], dllname[MAX_PATH];
1929 const WCHAR *name, *p;
1930 DWORD len, i;
1931 void *handle;
1932 struct builtin_load_info info, *prev_info;
1934 /* Fix the name in case we have a full path and extension */
1935 name = path;
1936 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1937 if ((p = strrchrW( name, '/' ))) name = p + 1;
1939 /* load_library will modify info.status. Note also that load_library can be
1940 * called several times, if the .so file we're loading has dependencies.
1941 * info.status will gather all the errors we may get while loading all these
1942 * libraries
1944 info.load_path = load_path;
1945 info.filename = NULL;
1946 info.status = STATUS_SUCCESS;
1947 info.wm = NULL;
1949 if (file) /* we have a real file, try to load it */
1951 UNICODE_STRING nt_name;
1952 ANSI_STRING unix_name;
1954 TRACE("Trying built-in %s\n", debugstr_w(path));
1956 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1957 return STATUS_DLL_NOT_FOUND;
1959 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1961 RtlFreeUnicodeString( &nt_name );
1962 return STATUS_DLL_NOT_FOUND;
1964 prev_info = builtin_load_info;
1965 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1966 builtin_load_info = &info;
1967 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1968 builtin_load_info = prev_info;
1969 RtlFreeUnicodeString( &nt_name );
1970 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1971 if (!handle)
1973 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1974 return STATUS_INVALID_IMAGE_FORMAT;
1977 else
1979 int file_exists;
1981 TRACE("Trying built-in %s\n", debugstr_w(name));
1983 /* we don't want to depend on the current codepage here */
1984 len = strlenW( name ) + 1;
1985 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1986 for (i = 0; i < len; i++)
1988 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1989 dllname[i] = (char)name[i];
1990 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1993 prev_info = builtin_load_info;
1994 builtin_load_info = &info;
1995 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1996 builtin_load_info = prev_info;
1997 if (!handle)
1999 if (!file_exists)
2001 /* The file does not exist -> WARN() */
2002 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
2003 return STATUS_DLL_NOT_FOUND;
2005 /* ERR() for all other errors (missing functions, ...) */
2006 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
2007 return STATUS_PROCEDURE_NOT_FOUND;
2011 if (info.status != STATUS_SUCCESS)
2013 wine_dll_unload( handle );
2014 return info.status;
2017 if (!info.wm)
2019 PLIST_ENTRY mark, entry;
2021 /* The constructor wasn't called, this means the .so is already
2022 * loaded under a different name. Try to find the wm for it. */
2024 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2025 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2027 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2028 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
2030 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2031 TRACE( "Found %s at %p for builtin %s\n",
2032 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
2033 break;
2036 wine_dll_unload( handle ); /* release the libdl refcount */
2037 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2038 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2040 else
2042 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2043 info.wm->ldr.LoadCount = 1;
2044 info.wm->ldr.SectionHandle = handle;
2047 *pwm = info.wm;
2048 return STATUS_SUCCESS;
2052 /***********************************************************************
2053 * find_actctx_dll
2055 * Find the full path (if any) of the dll from the activation context.
2057 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2059 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2060 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2062 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2063 ACTCTX_SECTION_KEYED_DATA data;
2064 UNICODE_STRING nameW;
2065 NTSTATUS status;
2066 SIZE_T needed, size = 1024;
2067 WCHAR *p;
2069 RtlInitUnicodeString( &nameW, libname );
2070 data.cbSize = sizeof(data);
2071 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2072 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2073 &nameW, &data );
2074 if (status != STATUS_SUCCESS) return status;
2076 for (;;)
2078 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2080 status = STATUS_NO_MEMORY;
2081 goto done;
2083 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2084 AssemblyDetailedInformationInActivationContext,
2085 info, size, &needed );
2086 if (status == STATUS_SUCCESS) break;
2087 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2088 RtlFreeHeap( GetProcessHeap(), 0, info );
2089 size = needed;
2090 /* restart with larger buffer */
2093 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2095 status = STATUS_SXS_KEY_NOT_FOUND;
2096 goto done;
2099 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2101 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2103 p++;
2104 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2106 /* manifest name does not match directory name, so it's not a global
2107 * windows/winsxs manifest; use the manifest directory name instead */
2108 dirlen = p - info->lpAssemblyManifestPath;
2109 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2110 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2112 status = STATUS_NO_MEMORY;
2113 goto done;
2115 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2116 p += dirlen;
2117 strcpyW( p, libname );
2118 goto done;
2122 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2123 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2125 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2127 status = STATUS_NO_MEMORY;
2128 goto done;
2130 strcpyW( p, user_shared_data->NtSystemRoot );
2131 p += strlenW(p);
2132 memcpy( p, winsxsW, sizeof(winsxsW) );
2133 p += sizeof(winsxsW) / sizeof(WCHAR);
2134 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2135 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2136 *p++ = '\\';
2137 strcpyW( p, libname );
2138 done:
2139 RtlFreeHeap( GetProcessHeap(), 0, info );
2140 RtlReleaseActivationContext( data.hActCtx );
2141 return status;
2145 /***********************************************************************
2146 * find_dll_file
2148 * Find the file (or already loaded module) for a given dll name.
2150 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2151 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
2153 OBJECT_ATTRIBUTES attr;
2154 IO_STATUS_BLOCK io;
2155 UNICODE_STRING nt_name;
2156 WCHAR *file_part, *ext, *dllname;
2157 ULONG len;
2159 /* first append .dll if needed */
2161 dllname = NULL;
2162 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2164 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2165 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2166 return STATUS_NO_MEMORY;
2167 strcpyW( dllname, libname );
2168 strcatW( dllname, dllW );
2169 libname = dllname;
2172 nt_name.Buffer = NULL;
2174 if (!contains_path( libname ))
2176 NTSTATUS status;
2177 WCHAR *fullname = NULL;
2179 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2181 status = find_actctx_dll( libname, &fullname );
2182 if (status == STATUS_SUCCESS)
2184 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2185 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2186 libname = dllname = fullname;
2188 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2190 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2191 return status;
2195 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2197 /* we need to search for it */
2198 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2199 if (len)
2201 if (len >= *size) goto overflow;
2202 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2204 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2206 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2207 return STATUS_NO_MEMORY;
2209 attr.Length = sizeof(attr);
2210 attr.RootDirectory = 0;
2211 attr.Attributes = OBJ_CASE_INSENSITIVE;
2212 attr.ObjectName = &nt_name;
2213 attr.SecurityDescriptor = NULL;
2214 attr.SecurityQualityOfService = NULL;
2215 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2216 goto found;
2219 /* not found */
2221 if (!contains_path( libname ))
2223 /* if libname doesn't contain a path at all, we simply return the name as is,
2224 * to be loaded as builtin */
2225 len = strlenW(libname) * sizeof(WCHAR);
2226 if (len >= *size) goto overflow;
2227 strcpyW( filename, libname );
2228 goto found;
2232 /* absolute path name, or relative path name but not found above */
2234 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2236 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2237 return STATUS_NO_MEMORY;
2239 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2240 if (len >= *size) goto overflow;
2241 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2242 if (!(*pwm = find_fullname_module( filename )) && handle)
2244 attr.Length = sizeof(attr);
2245 attr.RootDirectory = 0;
2246 attr.Attributes = OBJ_CASE_INSENSITIVE;
2247 attr.ObjectName = &nt_name;
2248 attr.SecurityDescriptor = NULL;
2249 attr.SecurityQualityOfService = NULL;
2250 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2252 found:
2253 RtlFreeUnicodeString( &nt_name );
2254 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2255 return STATUS_SUCCESS;
2257 overflow:
2258 RtlFreeUnicodeString( &nt_name );
2259 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2260 *size = len + sizeof(WCHAR);
2261 return STATUS_BUFFER_TOO_SMALL;
2265 /***********************************************************************
2266 * load_dll (internal)
2268 * Load a PE style module according to the load order.
2269 * The loader_section must be locked while calling this function.
2271 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2273 enum loadorder loadorder;
2274 WCHAR buffer[64];
2275 WCHAR *filename;
2276 ULONG size;
2277 WINE_MODREF *main_exe;
2278 HANDLE handle = 0;
2279 NTSTATUS nts;
2281 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2283 *pwm = NULL;
2284 filename = buffer;
2285 size = sizeof(buffer);
2286 for (;;)
2288 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2289 if (nts == STATUS_SUCCESS) break;
2290 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2291 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2292 /* grow the buffer and retry */
2293 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2296 if (*pwm) /* found already loaded module */
2298 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2300 TRACE("Found %s for %s at %p, count=%d\n",
2301 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2302 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2303 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2304 return STATUS_SUCCESS;
2307 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2308 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2310 if (handle && is_fake_dll( handle ))
2312 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2313 NtClose( handle );
2314 handle = 0;
2317 switch(loadorder)
2319 case LO_INVALID:
2320 nts = STATUS_NO_MEMORY;
2321 break;
2322 case LO_DISABLED:
2323 nts = STATUS_DLL_NOT_FOUND;
2324 break;
2325 case LO_NATIVE:
2326 case LO_NATIVE_BUILTIN:
2327 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2328 else
2330 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2331 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2332 /* not in PE format, maybe it's a builtin */
2333 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2335 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2336 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2337 break;
2338 case LO_BUILTIN:
2339 case LO_BUILTIN_NATIVE:
2340 case LO_DEFAULT: /* default is builtin,native */
2341 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2342 if (!handle) break; /* nothing else we can try */
2343 /* file is not a builtin library, try without using the specified file */
2344 if (nts != STATUS_SUCCESS)
2345 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2346 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2347 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2349 /* stub-only dll, try native */
2350 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2351 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2352 nts = STATUS_DLL_NOT_FOUND;
2354 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2355 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2356 break;
2359 if (nts == STATUS_SUCCESS)
2361 /* Initialize DLL just loaded */
2362 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2363 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2364 (*pwm)->ldr.BaseAddress);
2365 if (handle) NtClose( handle );
2366 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2367 return nts;
2370 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2371 if (handle) NtClose( handle );
2372 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2373 return nts;
2376 /******************************************************************
2377 * LdrLoadDll (NTDLL.@)
2379 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2380 const UNICODE_STRING *libname, HMODULE* hModule)
2382 WINE_MODREF *wm;
2383 NTSTATUS nts;
2385 RtlEnterCriticalSection( &loader_section );
2387 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2388 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2390 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2392 nts = process_attach( wm, NULL );
2393 if (nts != STATUS_SUCCESS)
2395 LdrUnloadDll(wm->ldr.BaseAddress);
2396 wm = NULL;
2399 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2401 RtlLeaveCriticalSection( &loader_section );
2402 return nts;
2406 /******************************************************************
2407 * LdrGetDllHandle (NTDLL.@)
2409 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2411 NTSTATUS status;
2412 WCHAR buffer[128];
2413 WCHAR *filename;
2414 ULONG size;
2415 WINE_MODREF *wm;
2417 RtlEnterCriticalSection( &loader_section );
2419 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2421 filename = buffer;
2422 size = sizeof(buffer);
2423 for (;;)
2425 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2426 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2427 if (status != STATUS_BUFFER_TOO_SMALL) break;
2428 /* grow the buffer and retry */
2429 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2431 status = STATUS_NO_MEMORY;
2432 break;
2436 if (status == STATUS_SUCCESS)
2438 if (wm) *base = wm->ldr.BaseAddress;
2439 else status = STATUS_DLL_NOT_FOUND;
2442 RtlLeaveCriticalSection( &loader_section );
2443 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2444 return status;
2448 /******************************************************************
2449 * LdrAddRefDll (NTDLL.@)
2451 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2453 NTSTATUS ret = STATUS_SUCCESS;
2454 WINE_MODREF *wm;
2456 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2458 RtlEnterCriticalSection( &loader_section );
2460 if ((wm = get_modref( module )))
2462 if (flags & LDR_ADDREF_DLL_PIN)
2463 wm->ldr.LoadCount = -1;
2464 else
2465 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2466 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2468 else ret = STATUS_INVALID_PARAMETER;
2470 RtlLeaveCriticalSection( &loader_section );
2471 return ret;
2475 /***********************************************************************
2476 * LdrProcessRelocationBlock (NTDLL.@)
2478 * Apply relocations to a given page of a mapped PE image.
2480 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2481 USHORT *relocs, INT_PTR delta )
2483 while (count--)
2485 USHORT offset = *relocs & 0xfff;
2486 int type = *relocs >> 12;
2487 switch(type)
2489 case IMAGE_REL_BASED_ABSOLUTE:
2490 break;
2491 case IMAGE_REL_BASED_HIGH:
2492 *(short *)((char *)page + offset) += HIWORD(delta);
2493 break;
2494 case IMAGE_REL_BASED_LOW:
2495 *(short *)((char *)page + offset) += LOWORD(delta);
2496 break;
2497 case IMAGE_REL_BASED_HIGHLOW:
2498 *(int *)((char *)page + offset) += delta;
2499 break;
2500 #ifdef _WIN64
2501 case IMAGE_REL_BASED_DIR64:
2502 *(INT_PTR *)((char *)page + offset) += delta;
2503 break;
2504 #elif defined(__arm__)
2505 case IMAGE_REL_BASED_THUMB_MOV32:
2507 DWORD inst = *(INT_PTR *)((char *)page + offset);
2508 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2509 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2510 DWORD hi_delta;
2512 if ((inst & 0x8000fbf0) != 0x0000f240)
2513 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2515 imm16 += LOWORD(delta);
2516 hi_delta = HIWORD(delta) + HIWORD(imm16);
2517 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2518 ((imm16 >> 12) & 0x000f) +
2519 ((imm16 << 20) & 0x70000000) +
2520 ((imm16 << 16) & 0xff0000);
2522 if (hi_delta != 0)
2524 inst = *(INT_PTR *)((char *)page + offset + 4);
2525 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2526 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2528 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2529 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2531 imm16 += hi_delta;
2532 if (imm16 > 0xffff)
2533 ERR("resulting immediate value won't fit: %08x\n", imm16);
2534 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2535 ((imm16 >> 1) & 0x0400) +
2536 ((imm16 >> 12) & 0x000f) +
2537 ((imm16 << 20) & 0x70000000) +
2538 ((imm16 << 16) & 0xff0000);
2541 break;
2542 #endif
2543 default:
2544 FIXME("Unknown/unsupported fixup type %x.\n", type);
2545 return NULL;
2547 relocs++;
2549 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2553 /******************************************************************
2554 * LdrQueryProcessModuleInformation
2557 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2558 ULONG buf_size, ULONG* req_size)
2560 SYSTEM_MODULE* sm = &smi->Modules[0];
2561 ULONG size = sizeof(ULONG);
2562 NTSTATUS nts = STATUS_SUCCESS;
2563 ANSI_STRING str;
2564 char* ptr;
2565 PLIST_ENTRY mark, entry;
2566 PLDR_MODULE mod;
2567 WORD id = 0;
2569 smi->ModulesCount = 0;
2571 RtlEnterCriticalSection( &loader_section );
2572 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2573 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2575 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2576 size += sizeof(*sm);
2577 if (size <= buf_size)
2579 sm->Reserved1 = 0; /* FIXME */
2580 sm->Reserved2 = 0; /* FIXME */
2581 sm->ImageBaseAddress = mod->BaseAddress;
2582 sm->ImageSize = mod->SizeOfImage;
2583 sm->Flags = mod->Flags;
2584 sm->Id = id++;
2585 sm->Rank = 0; /* FIXME */
2586 sm->Unknown = 0; /* FIXME */
2587 str.Length = 0;
2588 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2589 str.Buffer = (char*)sm->Name;
2590 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2591 ptr = strrchr(str.Buffer, '\\');
2592 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2594 smi->ModulesCount++;
2595 sm++;
2597 else nts = STATUS_INFO_LENGTH_MISMATCH;
2599 RtlLeaveCriticalSection( &loader_section );
2601 if (req_size) *req_size = size;
2603 return nts;
2607 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2609 NTSTATUS status;
2610 UNICODE_STRING str;
2611 ULONG size;
2612 WCHAR buffer[64];
2613 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2615 RtlInitUnicodeString( &str, name );
2617 size = sizeof(buffer) - sizeof(WCHAR);
2618 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2619 return status;
2621 if (info->Type != REG_DWORD)
2623 buffer[size / sizeof(WCHAR)] = 0;
2624 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2626 else memcpy( value, info->Data, sizeof(*value) );
2627 return status;
2630 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2631 void *data, ULONG in_size, ULONG *out_size )
2633 NTSTATUS status;
2634 UNICODE_STRING str;
2635 ULONG size;
2636 char *buffer;
2637 KEY_VALUE_PARTIAL_INFORMATION *info;
2638 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2640 RtlInitUnicodeString( &str, name );
2642 size = info_size + in_size;
2643 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2644 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2645 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2646 if (!status || status == STATUS_BUFFER_OVERFLOW)
2648 if (out_size) *out_size = info->DataLength;
2649 if (data && !status) memcpy( data, info->Data, info->DataLength );
2651 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2652 return status;
2656 /******************************************************************
2657 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2659 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2660 void *data, ULONG in_size, ULONG *out_size )
2662 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2663 'S','o','f','t','w','a','r','e','\\',
2664 'M','i','c','r','o','s','o','f','t','\\',
2665 'W','i','n','d','o','w','s',' ','N','T','\\',
2666 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2667 'I','m','a','g','e',' ','F','i','l','e',' ',
2668 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2669 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2670 OBJECT_ATTRIBUTES attr;
2671 UNICODE_STRING name_str;
2672 HANDLE hkey;
2673 NTSTATUS status;
2674 ULONG len;
2675 WCHAR *p;
2677 attr.Length = sizeof(attr);
2678 attr.RootDirectory = 0;
2679 attr.ObjectName = &name_str;
2680 attr.Attributes = OBJ_CASE_INSENSITIVE;
2681 attr.SecurityDescriptor = NULL;
2682 attr.SecurityQualityOfService = NULL;
2684 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2685 else p = key->Buffer;
2686 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2687 name_str.Buffer = path;
2688 name_str.Length = sizeof(optionsW) + len;
2689 name_str.MaximumLength = name_str.Length;
2690 memcpy( path, optionsW, sizeof(optionsW) );
2691 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2692 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2694 if (type == REG_DWORD)
2696 if (out_size) *out_size = sizeof(ULONG);
2697 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2698 else status = STATUS_BUFFER_OVERFLOW;
2700 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2702 NtClose( hkey );
2703 return status;
2707 /******************************************************************
2708 * RtlDllShutdownInProgress (NTDLL.@)
2710 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2712 return process_detaching;
2715 /****************************************************************************
2716 * LdrResolveDelayLoadedAPI (NTDLL.@)
2718 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2719 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2720 IMAGE_THUNK_DATA* addr, ULONG flags )
2722 IMAGE_THUNK_DATA *pIAT, *pINT;
2723 DELAYLOAD_INFO delayinfo;
2724 UNICODE_STRING mod;
2725 const CHAR* name;
2726 HMODULE *phmod;
2727 NTSTATUS nts;
2728 FARPROC fp;
2729 DWORD id;
2731 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2733 phmod = get_rva(base, desc->ModuleHandleRVA);
2734 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2735 pINT = get_rva(base, desc->ImportNameTableRVA);
2736 name = get_rva(base, desc->DllNameRVA);
2737 id = addr - pIAT;
2739 if (!*phmod)
2741 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2743 nts = STATUS_NO_MEMORY;
2744 goto fail;
2746 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2747 RtlFreeUnicodeString(&mod);
2748 if (nts) goto fail;
2751 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2752 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2753 else
2755 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2756 ANSI_STRING fnc;
2758 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2759 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2761 if (!nts)
2763 pIAT[id].u1.Function = (ULONG_PTR)fp;
2764 return fp;
2767 fail:
2768 delayinfo.Size = sizeof(delayinfo);
2769 delayinfo.DelayloadDescriptor = desc;
2770 delayinfo.ThunkAddress = addr;
2771 delayinfo.TargetDllName = name;
2772 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2773 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2774 delayinfo.TargetModuleBase = *phmod;
2775 delayinfo.Unused = NULL;
2776 delayinfo.LastError = nts;
2777 return dllhook(4, &delayinfo);
2780 /******************************************************************
2781 * LdrShutdownProcess (NTDLL.@)
2784 void WINAPI LdrShutdownProcess(void)
2786 TRACE("()\n");
2787 process_detaching = TRUE;
2788 process_detach();
2792 /******************************************************************
2793 * RtlExitUserProcess (NTDLL.@)
2795 void WINAPI RtlExitUserProcess( DWORD status )
2797 RtlEnterCriticalSection( &loader_section );
2798 RtlAcquirePebLock();
2799 NtTerminateProcess( 0, status );
2800 LdrShutdownProcess();
2801 NtTerminateProcess( GetCurrentProcess(), status );
2802 exit( status );
2805 /******************************************************************
2806 * LdrShutdownThread (NTDLL.@)
2809 void WINAPI LdrShutdownThread(void)
2811 PLIST_ENTRY mark, entry;
2812 PLDR_MODULE mod;
2813 UINT i;
2814 void **pointers;
2816 TRACE("()\n");
2818 /* don't do any detach calls if process is exiting */
2819 if (process_detaching) return;
2821 RtlEnterCriticalSection( &loader_section );
2823 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2824 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2826 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2827 InInitializationOrderModuleList);
2828 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2829 continue;
2830 if ( mod->Flags & LDR_NO_DLL_CALLS )
2831 continue;
2833 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2834 DLL_THREAD_DETACH, NULL );
2837 RtlAcquirePebLock();
2838 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2839 RtlReleasePebLock();
2841 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2843 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2844 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2846 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2847 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2848 RtlLeaveCriticalSection( &loader_section );
2852 /***********************************************************************
2853 * free_modref
2856 static void free_modref( WINE_MODREF *wm )
2858 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2859 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2860 if (wm->ldr.InInitializationOrderModuleList.Flink)
2861 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2863 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2864 if (!TRACE_ON(module))
2865 TRACE_(loaddll)("Unloaded module %s : %s\n",
2866 debugstr_w(wm->ldr.FullDllName.Buffer),
2867 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2869 SERVER_START_REQ( unload_dll )
2871 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2872 wine_server_call( req );
2874 SERVER_END_REQ;
2876 free_tls_slot( &wm->ldr );
2877 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2878 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2879 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2880 if (cached_modref == wm) cached_modref = NULL;
2881 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2882 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2883 RtlFreeHeap( GetProcessHeap(), 0, wm );
2886 /***********************************************************************
2887 * MODULE_FlushModrefs
2889 * Remove all unused modrefs and call the internal unloading routines
2890 * for the library type.
2892 * The loader_section must be locked while calling this function.
2894 static void MODULE_FlushModrefs(void)
2896 PLIST_ENTRY mark, entry, prev;
2897 PLDR_MODULE mod;
2898 WINE_MODREF*wm;
2900 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2901 for (entry = mark->Blink; entry != mark; entry = prev)
2903 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2904 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2905 prev = entry->Blink;
2906 if (!mod->LoadCount) free_modref( wm );
2909 /* check load order list too for modules that haven't been initialized yet */
2910 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2911 for (entry = mark->Blink; entry != mark; entry = prev)
2913 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2914 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2915 prev = entry->Blink;
2916 if (!mod->LoadCount) free_modref( wm );
2920 /***********************************************************************
2921 * MODULE_DecRefCount
2923 * The loader_section must be locked while calling this function.
2925 static void MODULE_DecRefCount( WINE_MODREF *wm )
2927 int i;
2929 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2930 return;
2932 if ( wm->ldr.LoadCount <= 0 )
2933 return;
2935 --wm->ldr.LoadCount;
2936 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2938 if ( wm->ldr.LoadCount == 0 )
2940 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2942 for ( i = 0; i < wm->nDeps; i++ )
2943 if ( wm->deps[i] )
2944 MODULE_DecRefCount( wm->deps[i] );
2946 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2950 /******************************************************************
2951 * LdrUnloadDll (NTDLL.@)
2955 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2957 WINE_MODREF *wm;
2958 NTSTATUS retv = STATUS_SUCCESS;
2960 if (process_detaching) return retv;
2962 TRACE("(%p)\n", hModule);
2964 RtlEnterCriticalSection( &loader_section );
2966 free_lib_count++;
2967 if ((wm = get_modref( hModule )) != NULL)
2969 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2971 /* Recursively decrement reference counts */
2972 MODULE_DecRefCount( wm );
2974 /* Call process detach notifications */
2975 if ( free_lib_count <= 1 )
2977 process_detach();
2978 MODULE_FlushModrefs();
2981 TRACE("END\n");
2983 else
2984 retv = STATUS_DLL_NOT_FOUND;
2986 free_lib_count--;
2988 RtlLeaveCriticalSection( &loader_section );
2990 return retv;
2993 /***********************************************************************
2994 * RtlImageNtHeader (NTDLL.@)
2996 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2998 IMAGE_NT_HEADERS *ret;
3000 __TRY
3002 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3004 ret = NULL;
3005 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3007 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3008 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3011 __EXCEPT_PAGE_FAULT
3013 return NULL;
3015 __ENDTRY
3016 return ret;
3020 /***********************************************************************
3021 * attach_process_dlls
3023 * Initial attach to all the dlls loaded by the process.
3025 static NTSTATUS attach_process_dlls( void *wm )
3027 NTSTATUS status;
3029 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3031 RtlEnterCriticalSection( &loader_section );
3032 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
3034 if (last_failed_modref)
3035 ERR( "%s failed to initialize, aborting\n",
3036 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3037 return status;
3039 attach_implicitly_loaded_dlls( (LPVOID)1 );
3040 RtlLeaveCriticalSection( &loader_section );
3041 return status;
3045 /***********************************************************************
3046 * load_global_options
3048 static void load_global_options(void)
3050 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3051 'S','y','s','t','e','m','\\',
3052 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3053 'C','o','n','t','r','o','l','\\',
3054 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3055 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3056 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};
3057 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3058 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3059 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};
3060 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};
3062 OBJECT_ATTRIBUTES attr;
3063 UNICODE_STRING name_str;
3064 HANDLE hkey;
3065 ULONG value;
3067 attr.Length = sizeof(attr);
3068 attr.RootDirectory = 0;
3069 attr.ObjectName = &name_str;
3070 attr.Attributes = OBJ_CASE_INSENSITIVE;
3071 attr.SecurityDescriptor = NULL;
3072 attr.SecurityQualityOfService = NULL;
3073 RtlInitUnicodeString( &name_str, sessionW );
3075 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3077 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3079 query_dword_option( hkey, critsectW, &value );
3080 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3082 query_dword_option( hkey, heapresW, &value );
3083 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3085 query_dword_option( hkey, heapcommitW, &value );
3086 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3088 query_dword_option( hkey, decommittotalW, &value );
3089 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3091 query_dword_option( hkey, decommitfreeW, &value );
3092 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3094 NtClose( hkey );
3098 /***********************************************************************
3099 * start_process
3101 static void start_process( void *arg )
3103 call_thread_entry_point( kernel32_start_process, arg );
3106 /******************************************************************
3107 * LdrInitializeThunk (NTDLL.@)
3110 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3111 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3113 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3114 NTSTATUS status;
3115 WINE_MODREF *wm;
3116 LPCWSTR load_path;
3117 PEB *peb = NtCurrentTeb()->Peb;
3119 kernel32_start_process = kernel_start;
3120 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
3122 /* allocate the modref for the main exe (if not already done) */
3123 wm = get_modref( peb->ImageBaseAddress );
3124 assert( wm );
3125 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3127 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3128 exit(1);
3131 peb->LoaderLock = &loader_section;
3132 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3133 if (!peb->ProcessParameters->WindowTitle.Buffer)
3134 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3135 version_init( wm->ldr.FullDllName.Buffer );
3136 virtual_set_large_address_space();
3138 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3139 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3141 /* the main exe needs to be the first in the load order list */
3142 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3143 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3144 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3145 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3147 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
3148 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
3150 actctx_init();
3151 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3152 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
3153 heap_set_debug_flags( GetProcessHeap() );
3155 status = wine_call_on_stack( attach_process_dlls, wm, (char *)NtCurrentTeb()->Tib.StackBase - page_size );
3156 if (status != STATUS_SUCCESS) goto error;
3158 virtual_release_address_space();
3159 virtual_clear_thread_stack();
3160 wine_switch_to_stack( start_process, wm->ldr.EntryPoint, NtCurrentTeb()->Tib.StackBase );
3162 error:
3163 ERR( "Main exe initialization for %s failed, status %x\n",
3164 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3165 NtTerminateProcess( GetCurrentProcess(), status );
3169 /***********************************************************************
3170 * RtlImageDirectoryEntryToData (NTDLL.@)
3172 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3174 const IMAGE_NT_HEADERS *nt;
3175 DWORD addr;
3177 if ((ULONG_PTR)module & 1) /* mapped as data file */
3179 module = (HMODULE)((ULONG_PTR)module & ~1);
3180 image = FALSE;
3182 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3183 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3185 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3187 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3188 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3189 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3190 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3192 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3194 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3196 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3197 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3198 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3199 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3201 else return NULL;
3203 /* not mapped as image, need to find the section containing the virtual address */
3204 return RtlImageRvaToVa( nt, module, addr, NULL );
3208 /***********************************************************************
3209 * RtlImageRvaToSection (NTDLL.@)
3211 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3212 HMODULE module, DWORD rva )
3214 int i;
3215 const IMAGE_SECTION_HEADER *sec;
3217 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3218 nt->FileHeader.SizeOfOptionalHeader);
3219 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3221 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3222 return (PIMAGE_SECTION_HEADER)sec;
3224 return NULL;
3228 /***********************************************************************
3229 * RtlImageRvaToVa (NTDLL.@)
3231 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3232 DWORD rva, IMAGE_SECTION_HEADER **section )
3234 IMAGE_SECTION_HEADER *sec;
3236 if (section && *section) /* try this section first */
3238 sec = *section;
3239 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3240 goto found;
3242 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3243 found:
3244 if (section) *section = sec;
3245 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3249 /***********************************************************************
3250 * RtlPcToFileHeader (NTDLL.@)
3252 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3254 LDR_MODULE *module;
3255 PVOID ret = NULL;
3257 RtlEnterCriticalSection( &loader_section );
3258 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3259 RtlLeaveCriticalSection( &loader_section );
3260 *address = ret;
3261 return ret;
3265 /***********************************************************************
3266 * NtLoadDriver (NTDLL.@)
3267 * ZwLoadDriver (NTDLL.@)
3269 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3271 FIXME("(%p), stub!\n",DriverServiceName);
3272 return STATUS_NOT_IMPLEMENTED;
3276 /***********************************************************************
3277 * NtUnloadDriver (NTDLL.@)
3278 * ZwUnloadDriver (NTDLL.@)
3280 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3282 FIXME("(%p), stub!\n",DriverServiceName);
3283 return STATUS_NOT_IMPLEMENTED;
3287 /******************************************************************
3288 * DllMain (NTDLL.@)
3290 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3292 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3293 return TRUE;
3297 /******************************************************************
3298 * __wine_init_windows_dir (NTDLL.@)
3300 * Windows and system dir initialization once kernel32 has been loaded.
3302 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3304 PLIST_ENTRY mark, entry;
3305 LPWSTR buffer, p;
3307 strcpyW( user_shared_data->NtSystemRoot, windir );
3308 DIR_init_windows_dir( windir, sysdir );
3310 /* prepend the system dir to the name of the already created modules */
3311 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3312 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3314 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3316 assert( mod->Flags & LDR_WINE_INTERNAL );
3318 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3319 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3320 if (!buffer) continue;
3321 strcpyW( buffer, system_dir.Buffer );
3322 p = buffer + strlenW( buffer );
3323 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3324 strcpyW( p, mod->FullDllName.Buffer );
3325 RtlInitUnicodeString( &mod->FullDllName, buffer );
3326 RtlInitUnicodeString( &mod->BaseDllName, p );
3331 /***********************************************************************
3332 * __wine_process_init
3334 void __wine_process_init(void)
3336 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3338 WINE_MODREF *wm;
3339 NTSTATUS status;
3340 ANSI_STRING func_name;
3341 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3343 main_exe_file = thread_init();
3345 /* retrieve current umask */
3346 FILE_umask = umask(0777);
3347 umask( FILE_umask );
3349 load_global_options();
3351 /* setup the load callback and create ntdll modref */
3352 wine_dll_set_callback( load_builtin_callback );
3354 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3356 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3357 exit(1);
3359 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3360 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3362 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3363 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3364 0, (void **)&init_func )) != STATUS_SUCCESS)
3366 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3367 exit(1);
3369 init_func();