msvcp120: Implement concurrent_vector::_Segment_index_of.
[wine.git] / dlls / ntdll / loader.c
blob9c89d5715415960432e2aa609068d5505547eb6b
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->base = wine_server_client_ptr( module );
1681 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1682 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1683 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1684 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1685 wine_server_call( req );
1687 SERVER_END_REQ;
1689 /* setup relay debugging entry points */
1690 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1694 /***********************************************************************
1695 * set_security_cookie
1697 * Create a random security cookie for buffer overflow protection. Make
1698 * sure it does not accidentally match the default cookie value.
1700 static void set_security_cookie( void *module, SIZE_T len )
1702 static ULONG seed;
1703 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1704 ULONG loadcfg_size;
1705 ULONG_PTR *cookie;
1707 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1708 if (!loadcfg) return;
1709 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1710 if (!loadcfg->SecurityCookie) return;
1711 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1712 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1714 WARN( "security cookie %p outside of image %p-%p\n",
1715 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1716 return;
1719 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1720 TRACE( "initializing security cookie %p\n", cookie );
1722 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1723 for (;;)
1725 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1726 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1727 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1728 *cookie = RtlRandom( &seed );
1729 #ifdef DEFAULT_SECURITY_COOKIE_64
1730 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1732 *cookie = RtlRandom( &seed );
1733 /* fill up, but keep the highest word clear */
1734 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1736 #endif
1737 else
1738 break;
1742 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1744 IMAGE_NT_HEADERS *nt;
1745 char *base;
1746 IMAGE_BASE_RELOCATION *rel, *end;
1747 const IMAGE_DATA_DIRECTORY *relocs;
1748 const IMAGE_SECTION_HEADER *sec;
1749 INT_PTR delta;
1750 ULONG protect_old[96], i;
1752 nt = RtlImageNtHeader( module );
1753 base = (char *)nt->OptionalHeader.ImageBase;
1755 assert( module != base );
1757 /* no relocations are performed on non page-aligned binaries */
1758 if (nt->OptionalHeader.SectionAlignment < page_size)
1759 return STATUS_SUCCESS;
1761 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1762 return STATUS_SUCCESS;
1764 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1766 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1768 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1769 base, module );
1770 return STATUS_CONFLICTING_ADDRESSES;
1773 if (!relocs->Size) return STATUS_SUCCESS;
1774 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1776 if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
1777 return STATUS_INVALID_IMAGE_FORMAT;
1779 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1780 nt->FileHeader.SizeOfOptionalHeader);
1781 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1783 void *addr = get_rva( module, sec[i].VirtualAddress );
1784 SIZE_T size = sec[i].SizeOfRawData;
1785 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1786 &size, PAGE_READWRITE, &protect_old[i] );
1789 TRACE( "relocating from %p-%p to %p-%p\n",
1790 base, base + len, module, (char *)module + len );
1792 rel = get_rva( module, relocs->VirtualAddress );
1793 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1794 delta = (char *)module - base;
1796 while (rel < end - 1 && rel->SizeOfBlock)
1798 if (rel->VirtualAddress >= len)
1800 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1801 return STATUS_ACCESS_VIOLATION;
1803 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1804 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1805 (USHORT *)(rel + 1), delta );
1806 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1809 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1811 void *addr = get_rva( module, sec[i].VirtualAddress );
1812 SIZE_T size = sec[i].SizeOfRawData;
1813 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1814 &size, protect_old[i], &protect_old[i] );
1817 return STATUS_SUCCESS;
1820 /******************************************************************************
1821 * load_native_dll (internal)
1823 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1824 DWORD flags, WINE_MODREF** pwm )
1826 void *module;
1827 HANDLE mapping;
1828 LARGE_INTEGER size;
1829 IMAGE_NT_HEADERS *nt;
1830 SIZE_T len = 0;
1831 WINE_MODREF *wm;
1832 NTSTATUS status;
1834 TRACE("Trying native dll %s\n", debugstr_w(name));
1836 size.QuadPart = 0;
1837 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY |
1838 SECTION_MAP_READ | SECTION_MAP_EXECUTE,
1839 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1840 if (status != STATUS_SUCCESS) return status;
1842 module = NULL;
1843 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1844 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1846 /* perform base relocation, if necessary */
1848 if (status == STATUS_IMAGE_NOT_AT_BASE)
1849 status = perform_relocations( module, len );
1851 if (status != STATUS_SUCCESS)
1853 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1854 goto done;
1857 /* create the MODREF */
1859 if (!(wm = alloc_module( module, name )))
1861 status = STATUS_NO_MEMORY;
1862 goto done;
1865 set_security_cookie( module, len );
1867 /* fixup imports */
1869 nt = RtlImageNtHeader( module );
1871 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1872 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1873 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1875 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1877 /* the module has only be inserted in the load & memory order lists */
1878 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1879 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1881 /* FIXME: there are several more dangling references
1882 * left. Including dlls loaded by this dll before the
1883 * failed one. Unrolling is rather difficult with the
1884 * current structure and we can leave them lying
1885 * around with no problems, so we don't care.
1886 * As these might reference our wm, we don't free it.
1888 goto done;
1892 /* send DLL load event */
1894 SERVER_START_REQ( load_dll )
1896 req->base = wine_server_client_ptr( module );
1897 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1898 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1899 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1900 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1901 wine_server_call( req );
1903 SERVER_END_REQ;
1905 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1907 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1909 wm->ldr.LoadCount = 1;
1910 *pwm = wm;
1911 status = STATUS_SUCCESS;
1912 done:
1913 NtClose( mapping );
1914 return status;
1918 /***********************************************************************
1919 * load_builtin_dll
1921 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1922 DWORD flags, WINE_MODREF** pwm )
1924 char error[256], dllname[MAX_PATH];
1925 const WCHAR *name, *p;
1926 DWORD len, i;
1927 void *handle;
1928 struct builtin_load_info info, *prev_info;
1930 /* Fix the name in case we have a full path and extension */
1931 name = path;
1932 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1933 if ((p = strrchrW( name, '/' ))) name = p + 1;
1935 /* load_library will modify info.status. Note also that load_library can be
1936 * called several times, if the .so file we're loading has dependencies.
1937 * info.status will gather all the errors we may get while loading all these
1938 * libraries
1940 info.load_path = load_path;
1941 info.filename = NULL;
1942 info.status = STATUS_SUCCESS;
1943 info.wm = NULL;
1945 if (file) /* we have a real file, try to load it */
1947 UNICODE_STRING nt_name;
1948 ANSI_STRING unix_name;
1950 TRACE("Trying built-in %s\n", debugstr_w(path));
1952 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1953 return STATUS_DLL_NOT_FOUND;
1955 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1957 RtlFreeUnicodeString( &nt_name );
1958 return STATUS_DLL_NOT_FOUND;
1960 prev_info = builtin_load_info;
1961 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1962 builtin_load_info = &info;
1963 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1964 builtin_load_info = prev_info;
1965 RtlFreeUnicodeString( &nt_name );
1966 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1967 if (!handle)
1969 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1970 return STATUS_INVALID_IMAGE_FORMAT;
1973 else
1975 int file_exists;
1977 TRACE("Trying built-in %s\n", debugstr_w(name));
1979 /* we don't want to depend on the current codepage here */
1980 len = strlenW( name ) + 1;
1981 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1982 for (i = 0; i < len; i++)
1984 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1985 dllname[i] = (char)name[i];
1986 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1989 prev_info = builtin_load_info;
1990 builtin_load_info = &info;
1991 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1992 builtin_load_info = prev_info;
1993 if (!handle)
1995 if (!file_exists)
1997 /* The file does not exist -> WARN() */
1998 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1999 return STATUS_DLL_NOT_FOUND;
2001 /* ERR() for all other errors (missing functions, ...) */
2002 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
2003 return STATUS_PROCEDURE_NOT_FOUND;
2007 if (info.status != STATUS_SUCCESS)
2009 wine_dll_unload( handle );
2010 return info.status;
2013 if (!info.wm)
2015 PLIST_ENTRY mark, entry;
2017 /* The constructor wasn't called, this means the .so is already
2018 * loaded under a different name. Try to find the wm for it. */
2020 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2021 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2023 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2024 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
2026 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2027 TRACE( "Found %s at %p for builtin %s\n",
2028 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
2029 break;
2032 wine_dll_unload( handle ); /* release the libdl refcount */
2033 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2034 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2036 else
2038 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2039 info.wm->ldr.LoadCount = 1;
2040 info.wm->ldr.SectionHandle = handle;
2043 *pwm = info.wm;
2044 return STATUS_SUCCESS;
2048 /***********************************************************************
2049 * find_actctx_dll
2051 * Find the full path (if any) of the dll from the activation context.
2053 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2055 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2056 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2058 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2059 ACTCTX_SECTION_KEYED_DATA data;
2060 UNICODE_STRING nameW;
2061 NTSTATUS status;
2062 SIZE_T needed, size = 1024;
2063 WCHAR *p;
2065 RtlInitUnicodeString( &nameW, libname );
2066 data.cbSize = sizeof(data);
2067 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2068 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2069 &nameW, &data );
2070 if (status != STATUS_SUCCESS) return status;
2072 for (;;)
2074 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2076 status = STATUS_NO_MEMORY;
2077 goto done;
2079 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2080 AssemblyDetailedInformationInActivationContext,
2081 info, size, &needed );
2082 if (status == STATUS_SUCCESS) break;
2083 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2084 RtlFreeHeap( GetProcessHeap(), 0, info );
2085 size = needed;
2086 /* restart with larger buffer */
2089 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2091 status = STATUS_SXS_KEY_NOT_FOUND;
2092 goto done;
2095 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2097 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2099 p++;
2100 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2102 /* manifest name does not match directory name, so it's not a global
2103 * windows/winsxs manifest; use the manifest directory name instead */
2104 dirlen = p - info->lpAssemblyManifestPath;
2105 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2106 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2108 status = STATUS_NO_MEMORY;
2109 goto done;
2111 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2112 p += dirlen;
2113 strcpyW( p, libname );
2114 goto done;
2118 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2119 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2121 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2123 status = STATUS_NO_MEMORY;
2124 goto done;
2126 strcpyW( p, user_shared_data->NtSystemRoot );
2127 p += strlenW(p);
2128 memcpy( p, winsxsW, sizeof(winsxsW) );
2129 p += sizeof(winsxsW) / sizeof(WCHAR);
2130 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2131 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2132 *p++ = '\\';
2133 strcpyW( p, libname );
2134 done:
2135 RtlFreeHeap( GetProcessHeap(), 0, info );
2136 RtlReleaseActivationContext( data.hActCtx );
2137 return status;
2141 /***********************************************************************
2142 * find_dll_file
2144 * Find the file (or already loaded module) for a given dll name.
2146 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2147 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
2149 OBJECT_ATTRIBUTES attr;
2150 IO_STATUS_BLOCK io;
2151 UNICODE_STRING nt_name;
2152 WCHAR *file_part, *ext, *dllname;
2153 ULONG len;
2155 /* first append .dll if needed */
2157 dllname = NULL;
2158 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2160 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2161 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2162 return STATUS_NO_MEMORY;
2163 strcpyW( dllname, libname );
2164 strcatW( dllname, dllW );
2165 libname = dllname;
2168 nt_name.Buffer = NULL;
2170 if (!contains_path( libname ))
2172 NTSTATUS status;
2173 WCHAR *fullname = NULL;
2175 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2177 status = find_actctx_dll( libname, &fullname );
2178 if (status == STATUS_SUCCESS)
2180 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2181 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2182 libname = dllname = fullname;
2184 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2186 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2187 return status;
2191 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2193 /* we need to search for it */
2194 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2195 if (len)
2197 if (len >= *size) goto overflow;
2198 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2200 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2202 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2203 return STATUS_NO_MEMORY;
2205 attr.Length = sizeof(attr);
2206 attr.RootDirectory = 0;
2207 attr.Attributes = OBJ_CASE_INSENSITIVE;
2208 attr.ObjectName = &nt_name;
2209 attr.SecurityDescriptor = NULL;
2210 attr.SecurityQualityOfService = NULL;
2211 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2212 goto found;
2215 /* not found */
2217 if (!contains_path( libname ))
2219 /* if libname doesn't contain a path at all, we simply return the name as is,
2220 * to be loaded as builtin */
2221 len = strlenW(libname) * sizeof(WCHAR);
2222 if (len >= *size) goto overflow;
2223 strcpyW( filename, libname );
2224 goto found;
2228 /* absolute path name, or relative path name but not found above */
2230 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2232 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2233 return STATUS_NO_MEMORY;
2235 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2236 if (len >= *size) goto overflow;
2237 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2238 if (!(*pwm = find_fullname_module( filename )) && handle)
2240 attr.Length = sizeof(attr);
2241 attr.RootDirectory = 0;
2242 attr.Attributes = OBJ_CASE_INSENSITIVE;
2243 attr.ObjectName = &nt_name;
2244 attr.SecurityDescriptor = NULL;
2245 attr.SecurityQualityOfService = NULL;
2246 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2248 found:
2249 RtlFreeUnicodeString( &nt_name );
2250 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2251 return STATUS_SUCCESS;
2253 overflow:
2254 RtlFreeUnicodeString( &nt_name );
2255 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2256 *size = len + sizeof(WCHAR);
2257 return STATUS_BUFFER_TOO_SMALL;
2261 /***********************************************************************
2262 * load_dll (internal)
2264 * Load a PE style module according to the load order.
2265 * The loader_section must be locked while calling this function.
2267 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2269 enum loadorder loadorder;
2270 WCHAR buffer[64];
2271 WCHAR *filename;
2272 ULONG size;
2273 WINE_MODREF *main_exe;
2274 HANDLE handle = 0;
2275 NTSTATUS nts;
2277 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2279 *pwm = NULL;
2280 filename = buffer;
2281 size = sizeof(buffer);
2282 for (;;)
2284 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2285 if (nts == STATUS_SUCCESS) break;
2286 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2287 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2288 /* grow the buffer and retry */
2289 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2292 if (*pwm) /* found already loaded module */
2294 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2296 TRACE("Found %s for %s at %p, count=%d\n",
2297 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2298 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2299 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2300 return STATUS_SUCCESS;
2303 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2304 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2306 if (handle && is_fake_dll( handle ))
2308 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2309 NtClose( handle );
2310 handle = 0;
2313 switch(loadorder)
2315 case LO_INVALID:
2316 nts = STATUS_NO_MEMORY;
2317 break;
2318 case LO_DISABLED:
2319 nts = STATUS_DLL_NOT_FOUND;
2320 break;
2321 case LO_NATIVE:
2322 case LO_NATIVE_BUILTIN:
2323 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2324 else
2326 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2327 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2328 /* not in PE format, maybe it's a builtin */
2329 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2331 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2332 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2333 break;
2334 case LO_BUILTIN:
2335 case LO_BUILTIN_NATIVE:
2336 case LO_DEFAULT: /* default is builtin,native */
2337 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2338 if (!handle) break; /* nothing else we can try */
2339 /* file is not a builtin library, try without using the specified file */
2340 if (nts != STATUS_SUCCESS)
2341 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2342 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2343 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2345 /* stub-only dll, try native */
2346 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2347 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2348 nts = STATUS_DLL_NOT_FOUND;
2350 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2351 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2352 break;
2355 if (nts == STATUS_SUCCESS)
2357 /* Initialize DLL just loaded */
2358 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2359 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2360 (*pwm)->ldr.BaseAddress);
2361 if (handle) NtClose( handle );
2362 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2363 return nts;
2366 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2367 if (handle) NtClose( handle );
2368 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2369 return nts;
2372 /******************************************************************
2373 * LdrLoadDll (NTDLL.@)
2375 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2376 const UNICODE_STRING *libname, HMODULE* hModule)
2378 WINE_MODREF *wm;
2379 NTSTATUS nts;
2381 RtlEnterCriticalSection( &loader_section );
2383 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2384 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2386 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2388 nts = process_attach( wm, NULL );
2389 if (nts != STATUS_SUCCESS)
2391 LdrUnloadDll(wm->ldr.BaseAddress);
2392 wm = NULL;
2395 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2397 RtlLeaveCriticalSection( &loader_section );
2398 return nts;
2402 /******************************************************************
2403 * LdrGetDllHandle (NTDLL.@)
2405 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2407 NTSTATUS status;
2408 WCHAR buffer[128];
2409 WCHAR *filename;
2410 ULONG size;
2411 WINE_MODREF *wm;
2413 RtlEnterCriticalSection( &loader_section );
2415 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2417 filename = buffer;
2418 size = sizeof(buffer);
2419 for (;;)
2421 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2422 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2423 if (status != STATUS_BUFFER_TOO_SMALL) break;
2424 /* grow the buffer and retry */
2425 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2427 status = STATUS_NO_MEMORY;
2428 break;
2432 if (status == STATUS_SUCCESS)
2434 if (wm) *base = wm->ldr.BaseAddress;
2435 else status = STATUS_DLL_NOT_FOUND;
2438 RtlLeaveCriticalSection( &loader_section );
2439 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2440 return status;
2444 /******************************************************************
2445 * LdrAddRefDll (NTDLL.@)
2447 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2449 NTSTATUS ret = STATUS_SUCCESS;
2450 WINE_MODREF *wm;
2452 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2454 RtlEnterCriticalSection( &loader_section );
2456 if ((wm = get_modref( module )))
2458 if (flags & LDR_ADDREF_DLL_PIN)
2459 wm->ldr.LoadCount = -1;
2460 else
2461 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2462 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2464 else ret = STATUS_INVALID_PARAMETER;
2466 RtlLeaveCriticalSection( &loader_section );
2467 return ret;
2471 /***********************************************************************
2472 * LdrProcessRelocationBlock (NTDLL.@)
2474 * Apply relocations to a given page of a mapped PE image.
2476 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2477 USHORT *relocs, INT_PTR delta )
2479 while (count--)
2481 USHORT offset = *relocs & 0xfff;
2482 int type = *relocs >> 12;
2483 switch(type)
2485 case IMAGE_REL_BASED_ABSOLUTE:
2486 break;
2487 case IMAGE_REL_BASED_HIGH:
2488 *(short *)((char *)page + offset) += HIWORD(delta);
2489 break;
2490 case IMAGE_REL_BASED_LOW:
2491 *(short *)((char *)page + offset) += LOWORD(delta);
2492 break;
2493 case IMAGE_REL_BASED_HIGHLOW:
2494 *(int *)((char *)page + offset) += delta;
2495 break;
2496 #ifdef _WIN64
2497 case IMAGE_REL_BASED_DIR64:
2498 *(INT_PTR *)((char *)page + offset) += delta;
2499 break;
2500 #elif defined(__arm__)
2501 case IMAGE_REL_BASED_THUMB_MOV32:
2503 DWORD inst = *(INT_PTR *)((char *)page + offset);
2504 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2505 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2506 DWORD hi_delta;
2508 if ((inst & 0x8000fbf0) != 0x0000f240)
2509 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2511 imm16 += LOWORD(delta);
2512 hi_delta = HIWORD(delta) + HIWORD(imm16);
2513 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2514 ((imm16 >> 12) & 0x000f) +
2515 ((imm16 << 20) & 0x70000000) +
2516 ((imm16 << 16) & 0xff0000);
2518 if (hi_delta != 0)
2520 inst = *(INT_PTR *)((char *)page + offset + 4);
2521 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2522 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2524 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2525 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2527 imm16 += hi_delta;
2528 if (imm16 > 0xffff)
2529 ERR("resulting immediate value won't fit: %08x\n", imm16);
2530 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2531 ((imm16 >> 1) & 0x0400) +
2532 ((imm16 >> 12) & 0x000f) +
2533 ((imm16 << 20) & 0x70000000) +
2534 ((imm16 << 16) & 0xff0000);
2537 break;
2538 #endif
2539 default:
2540 FIXME("Unknown/unsupported fixup type %x.\n", type);
2541 return NULL;
2543 relocs++;
2545 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2549 /******************************************************************
2550 * LdrQueryProcessModuleInformation
2553 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2554 ULONG buf_size, ULONG* req_size)
2556 SYSTEM_MODULE* sm = &smi->Modules[0];
2557 ULONG size = sizeof(ULONG);
2558 NTSTATUS nts = STATUS_SUCCESS;
2559 ANSI_STRING str;
2560 char* ptr;
2561 PLIST_ENTRY mark, entry;
2562 PLDR_MODULE mod;
2563 WORD id = 0;
2565 smi->ModulesCount = 0;
2567 RtlEnterCriticalSection( &loader_section );
2568 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2569 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2571 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2572 size += sizeof(*sm);
2573 if (size <= buf_size)
2575 sm->Reserved1 = 0; /* FIXME */
2576 sm->Reserved2 = 0; /* FIXME */
2577 sm->ImageBaseAddress = mod->BaseAddress;
2578 sm->ImageSize = mod->SizeOfImage;
2579 sm->Flags = mod->Flags;
2580 sm->Id = id++;
2581 sm->Rank = 0; /* FIXME */
2582 sm->Unknown = 0; /* FIXME */
2583 str.Length = 0;
2584 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2585 str.Buffer = (char*)sm->Name;
2586 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2587 ptr = strrchr(str.Buffer, '\\');
2588 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2590 smi->ModulesCount++;
2591 sm++;
2593 else nts = STATUS_INFO_LENGTH_MISMATCH;
2595 RtlLeaveCriticalSection( &loader_section );
2597 if (req_size) *req_size = size;
2599 return nts;
2603 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2605 NTSTATUS status;
2606 UNICODE_STRING str;
2607 ULONG size;
2608 WCHAR buffer[64];
2609 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2611 RtlInitUnicodeString( &str, name );
2613 size = sizeof(buffer) - sizeof(WCHAR);
2614 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2615 return status;
2617 if (info->Type != REG_DWORD)
2619 buffer[size / sizeof(WCHAR)] = 0;
2620 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2622 else memcpy( value, info->Data, sizeof(*value) );
2623 return status;
2626 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2627 void *data, ULONG in_size, ULONG *out_size )
2629 NTSTATUS status;
2630 UNICODE_STRING str;
2631 ULONG size;
2632 char *buffer;
2633 KEY_VALUE_PARTIAL_INFORMATION *info;
2634 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2636 RtlInitUnicodeString( &str, name );
2638 size = info_size + in_size;
2639 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2640 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2641 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2642 if (!status || status == STATUS_BUFFER_OVERFLOW)
2644 if (out_size) *out_size = info->DataLength;
2645 if (data && !status) memcpy( data, info->Data, info->DataLength );
2647 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2648 return status;
2652 /******************************************************************
2653 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2655 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2656 void *data, ULONG in_size, ULONG *out_size )
2658 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2659 'S','o','f','t','w','a','r','e','\\',
2660 'M','i','c','r','o','s','o','f','t','\\',
2661 'W','i','n','d','o','w','s',' ','N','T','\\',
2662 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2663 'I','m','a','g','e',' ','F','i','l','e',' ',
2664 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2665 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2666 OBJECT_ATTRIBUTES attr;
2667 UNICODE_STRING name_str;
2668 HANDLE hkey;
2669 NTSTATUS status;
2670 ULONG len;
2671 WCHAR *p;
2673 attr.Length = sizeof(attr);
2674 attr.RootDirectory = 0;
2675 attr.ObjectName = &name_str;
2676 attr.Attributes = OBJ_CASE_INSENSITIVE;
2677 attr.SecurityDescriptor = NULL;
2678 attr.SecurityQualityOfService = NULL;
2680 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2681 else p = key->Buffer;
2682 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2683 name_str.Buffer = path;
2684 name_str.Length = sizeof(optionsW) + len;
2685 name_str.MaximumLength = name_str.Length;
2686 memcpy( path, optionsW, sizeof(optionsW) );
2687 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2688 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2690 if (type == REG_DWORD)
2692 if (out_size) *out_size = sizeof(ULONG);
2693 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2694 else status = STATUS_BUFFER_OVERFLOW;
2696 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2698 NtClose( hkey );
2699 return status;
2703 /******************************************************************
2704 * RtlDllShutdownInProgress (NTDLL.@)
2706 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2708 return process_detaching;
2711 /****************************************************************************
2712 * LdrResolveDelayLoadedAPI (NTDLL.@)
2714 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2715 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2716 IMAGE_THUNK_DATA* addr, ULONG flags )
2718 IMAGE_THUNK_DATA *pIAT, *pINT;
2719 DELAYLOAD_INFO delayinfo;
2720 UNICODE_STRING mod;
2721 const CHAR* name;
2722 HMODULE *phmod;
2723 NTSTATUS nts;
2724 FARPROC fp;
2725 DWORD id;
2727 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2729 phmod = get_rva(base, desc->ModuleHandleRVA);
2730 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2731 pINT = get_rva(base, desc->ImportNameTableRVA);
2732 name = get_rva(base, desc->DllNameRVA);
2733 id = addr - pIAT;
2735 if (!*phmod)
2737 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2739 nts = STATUS_NO_MEMORY;
2740 goto fail;
2742 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2743 RtlFreeUnicodeString(&mod);
2744 if (nts) goto fail;
2747 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2748 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2749 else
2751 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2752 ANSI_STRING fnc;
2754 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2755 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2757 if (!nts)
2759 pIAT[id].u1.Function = (ULONG_PTR)fp;
2760 return fp;
2763 fail:
2764 delayinfo.Size = sizeof(delayinfo);
2765 delayinfo.DelayloadDescriptor = desc;
2766 delayinfo.ThunkAddress = addr;
2767 delayinfo.TargetDllName = name;
2768 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2769 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2770 delayinfo.TargetModuleBase = *phmod;
2771 delayinfo.Unused = NULL;
2772 delayinfo.LastError = nts;
2773 return dllhook(4, &delayinfo);
2776 /******************************************************************
2777 * LdrShutdownProcess (NTDLL.@)
2780 void WINAPI LdrShutdownProcess(void)
2782 TRACE("()\n");
2783 process_detaching = TRUE;
2784 process_detach();
2788 /******************************************************************
2789 * RtlExitUserProcess (NTDLL.@)
2791 void WINAPI RtlExitUserProcess( DWORD status )
2793 RtlEnterCriticalSection( &loader_section );
2794 RtlAcquirePebLock();
2795 NtTerminateProcess( 0, status );
2796 LdrShutdownProcess();
2797 NtTerminateProcess( GetCurrentProcess(), status );
2798 exit( status );
2801 /******************************************************************
2802 * LdrShutdownThread (NTDLL.@)
2805 void WINAPI LdrShutdownThread(void)
2807 PLIST_ENTRY mark, entry;
2808 PLDR_MODULE mod;
2809 UINT i;
2810 void **pointers;
2812 TRACE("()\n");
2814 /* don't do any detach calls if process is exiting */
2815 if (process_detaching) return;
2817 RtlEnterCriticalSection( &loader_section );
2819 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2820 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2822 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2823 InInitializationOrderModuleList);
2824 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2825 continue;
2826 if ( mod->Flags & LDR_NO_DLL_CALLS )
2827 continue;
2829 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2830 DLL_THREAD_DETACH, NULL );
2833 RtlAcquirePebLock();
2834 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2835 RtlReleasePebLock();
2837 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2839 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2840 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2842 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2843 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2844 RtlLeaveCriticalSection( &loader_section );
2848 /***********************************************************************
2849 * free_modref
2852 static void free_modref( WINE_MODREF *wm )
2854 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2855 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2856 if (wm->ldr.InInitializationOrderModuleList.Flink)
2857 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2859 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2860 if (!TRACE_ON(module))
2861 TRACE_(loaddll)("Unloaded module %s : %s\n",
2862 debugstr_w(wm->ldr.FullDllName.Buffer),
2863 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2865 SERVER_START_REQ( unload_dll )
2867 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2868 wine_server_call( req );
2870 SERVER_END_REQ;
2872 free_tls_slot( &wm->ldr );
2873 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2874 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2875 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2876 if (cached_modref == wm) cached_modref = NULL;
2877 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2878 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2879 RtlFreeHeap( GetProcessHeap(), 0, wm );
2882 /***********************************************************************
2883 * MODULE_FlushModrefs
2885 * Remove all unused modrefs and call the internal unloading routines
2886 * for the library type.
2888 * The loader_section must be locked while calling this function.
2890 static void MODULE_FlushModrefs(void)
2892 PLIST_ENTRY mark, entry, prev;
2893 PLDR_MODULE mod;
2894 WINE_MODREF*wm;
2896 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2897 for (entry = mark->Blink; entry != mark; entry = prev)
2899 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2900 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2901 prev = entry->Blink;
2902 if (!mod->LoadCount) free_modref( wm );
2905 /* check load order list too for modules that haven't been initialized yet */
2906 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2907 for (entry = mark->Blink; entry != mark; entry = prev)
2909 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2910 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2911 prev = entry->Blink;
2912 if (!mod->LoadCount) free_modref( wm );
2916 /***********************************************************************
2917 * MODULE_DecRefCount
2919 * The loader_section must be locked while calling this function.
2921 static void MODULE_DecRefCount( WINE_MODREF *wm )
2923 int i;
2925 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2926 return;
2928 if ( wm->ldr.LoadCount <= 0 )
2929 return;
2931 --wm->ldr.LoadCount;
2932 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2934 if ( wm->ldr.LoadCount == 0 )
2936 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2938 for ( i = 0; i < wm->nDeps; i++ )
2939 if ( wm->deps[i] )
2940 MODULE_DecRefCount( wm->deps[i] );
2942 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2946 /******************************************************************
2947 * LdrUnloadDll (NTDLL.@)
2951 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2953 WINE_MODREF *wm;
2954 NTSTATUS retv = STATUS_SUCCESS;
2956 if (process_detaching) return retv;
2958 TRACE("(%p)\n", hModule);
2960 RtlEnterCriticalSection( &loader_section );
2962 free_lib_count++;
2963 if ((wm = get_modref( hModule )) != NULL)
2965 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2967 /* Recursively decrement reference counts */
2968 MODULE_DecRefCount( wm );
2970 /* Call process detach notifications */
2971 if ( free_lib_count <= 1 )
2973 process_detach();
2974 MODULE_FlushModrefs();
2977 TRACE("END\n");
2979 else
2980 retv = STATUS_DLL_NOT_FOUND;
2982 free_lib_count--;
2984 RtlLeaveCriticalSection( &loader_section );
2986 return retv;
2989 /***********************************************************************
2990 * RtlImageNtHeader (NTDLL.@)
2992 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2994 IMAGE_NT_HEADERS *ret;
2996 __TRY
2998 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
3000 ret = NULL;
3001 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
3003 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
3004 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
3007 __EXCEPT_PAGE_FAULT
3009 return NULL;
3011 __ENDTRY
3012 return ret;
3016 /***********************************************************************
3017 * attach_process_dlls
3019 * Initial attach to all the dlls loaded by the process.
3021 static NTSTATUS attach_process_dlls( void *wm )
3023 NTSTATUS status;
3025 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3027 RtlEnterCriticalSection( &loader_section );
3028 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
3030 if (last_failed_modref)
3031 ERR( "%s failed to initialize, aborting\n",
3032 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3033 return status;
3035 attach_implicitly_loaded_dlls( (LPVOID)1 );
3036 RtlLeaveCriticalSection( &loader_section );
3037 return status;
3041 /***********************************************************************
3042 * load_global_options
3044 static void load_global_options(void)
3046 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3047 'S','y','s','t','e','m','\\',
3048 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3049 'C','o','n','t','r','o','l','\\',
3050 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3051 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3052 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};
3053 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3054 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3055 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};
3056 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};
3058 OBJECT_ATTRIBUTES attr;
3059 UNICODE_STRING name_str;
3060 HANDLE hkey;
3061 ULONG value;
3063 attr.Length = sizeof(attr);
3064 attr.RootDirectory = 0;
3065 attr.ObjectName = &name_str;
3066 attr.Attributes = OBJ_CASE_INSENSITIVE;
3067 attr.SecurityDescriptor = NULL;
3068 attr.SecurityQualityOfService = NULL;
3069 RtlInitUnicodeString( &name_str, sessionW );
3071 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3073 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3075 query_dword_option( hkey, critsectW, &value );
3076 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3078 query_dword_option( hkey, heapresW, &value );
3079 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3081 query_dword_option( hkey, heapcommitW, &value );
3082 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3084 query_dword_option( hkey, decommittotalW, &value );
3085 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3087 query_dword_option( hkey, decommitfreeW, &value );
3088 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3090 NtClose( hkey );
3094 /***********************************************************************
3095 * start_process
3097 static void start_process( void *arg )
3099 call_thread_entry_point( kernel32_start_process, arg );
3102 /******************************************************************
3103 * LdrInitializeThunk (NTDLL.@)
3106 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3107 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3109 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3110 NTSTATUS status;
3111 WINE_MODREF *wm;
3112 LPCWSTR load_path;
3113 PEB *peb = NtCurrentTeb()->Peb;
3114 CONTEXT context = { 0 };
3116 kernel32_start_process = kernel_start;
3117 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
3119 /* allocate the modref for the main exe (if not already done) */
3120 wm = get_modref( peb->ImageBaseAddress );
3121 assert( wm );
3122 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3124 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3125 exit(1);
3128 peb->LoaderLock = &loader_section;
3129 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3130 if (!peb->ProcessParameters->WindowTitle.Buffer)
3131 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3132 version_init( wm->ldr.FullDllName.Buffer );
3133 virtual_set_large_address_space();
3135 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3136 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3138 /* the main exe needs to be the first in the load order list */
3139 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3140 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3141 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3142 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3144 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
3145 if ((status = server_init_process_done( &context )) != STATUS_SUCCESS) goto error;
3147 actctx_init();
3148 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3149 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
3150 heap_set_debug_flags( GetProcessHeap() );
3152 status = wine_call_on_stack( attach_process_dlls, wm, (char *)NtCurrentTeb()->Tib.StackBase - page_size );
3153 if (status != STATUS_SUCCESS) goto error;
3155 virtual_release_address_space();
3156 virtual_clear_thread_stack();
3157 if (context.ContextFlags) NtSetContextThread( GetCurrentThread(), &context );
3158 wine_switch_to_stack( start_process, wm->ldr.EntryPoint, NtCurrentTeb()->Tib.StackBase );
3160 error:
3161 ERR( "Main exe initialization for %s failed, status %x\n",
3162 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3163 NtTerminateProcess( GetCurrentProcess(), status );
3167 /***********************************************************************
3168 * RtlImageDirectoryEntryToData (NTDLL.@)
3170 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3172 const IMAGE_NT_HEADERS *nt;
3173 DWORD addr;
3175 if ((ULONG_PTR)module & 1) /* mapped as data file */
3177 module = (HMODULE)((ULONG_PTR)module & ~1);
3178 image = FALSE;
3180 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3181 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3183 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3185 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3186 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3187 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3188 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3190 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3192 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3194 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3195 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3196 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3197 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3199 else return NULL;
3201 /* not mapped as image, need to find the section containing the virtual address */
3202 return RtlImageRvaToVa( nt, module, addr, NULL );
3206 /***********************************************************************
3207 * RtlImageRvaToSection (NTDLL.@)
3209 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3210 HMODULE module, DWORD rva )
3212 int i;
3213 const IMAGE_SECTION_HEADER *sec;
3215 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3216 nt->FileHeader.SizeOfOptionalHeader);
3217 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3219 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3220 return (PIMAGE_SECTION_HEADER)sec;
3222 return NULL;
3226 /***********************************************************************
3227 * RtlImageRvaToVa (NTDLL.@)
3229 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3230 DWORD rva, IMAGE_SECTION_HEADER **section )
3232 IMAGE_SECTION_HEADER *sec;
3234 if (section && *section) /* try this section first */
3236 sec = *section;
3237 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3238 goto found;
3240 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3241 found:
3242 if (section) *section = sec;
3243 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3247 /***********************************************************************
3248 * RtlPcToFileHeader (NTDLL.@)
3250 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3252 LDR_MODULE *module;
3253 PVOID ret = NULL;
3255 RtlEnterCriticalSection( &loader_section );
3256 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3257 RtlLeaveCriticalSection( &loader_section );
3258 *address = ret;
3259 return ret;
3263 /***********************************************************************
3264 * NtLoadDriver (NTDLL.@)
3265 * ZwLoadDriver (NTDLL.@)
3267 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3269 FIXME("(%p), stub!\n",DriverServiceName);
3270 return STATUS_NOT_IMPLEMENTED;
3274 /***********************************************************************
3275 * NtUnloadDriver (NTDLL.@)
3276 * ZwUnloadDriver (NTDLL.@)
3278 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3280 FIXME("(%p), stub!\n",DriverServiceName);
3281 return STATUS_NOT_IMPLEMENTED;
3285 /******************************************************************
3286 * DllMain (NTDLL.@)
3288 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3290 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3291 return TRUE;
3295 /******************************************************************
3296 * __wine_init_windows_dir (NTDLL.@)
3298 * Windows and system dir initialization once kernel32 has been loaded.
3300 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3302 PLIST_ENTRY mark, entry;
3303 LPWSTR buffer, p;
3305 strcpyW( user_shared_data->NtSystemRoot, windir );
3306 DIR_init_windows_dir( windir, sysdir );
3308 /* prepend the system dir to the name of the already created modules */
3309 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3310 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3312 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3314 assert( mod->Flags & LDR_WINE_INTERNAL );
3316 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3317 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3318 if (!buffer) continue;
3319 strcpyW( buffer, system_dir.Buffer );
3320 p = buffer + strlenW( buffer );
3321 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3322 strcpyW( p, mod->FullDllName.Buffer );
3323 RtlInitUnicodeString( &mod->FullDllName, buffer );
3324 RtlInitUnicodeString( &mod->BaseDllName, p );
3329 /***********************************************************************
3330 * __wine_process_init
3332 void __wine_process_init(void)
3334 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3336 WINE_MODREF *wm;
3337 NTSTATUS status;
3338 ANSI_STRING func_name;
3339 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3341 main_exe_file = thread_init();
3343 /* retrieve current umask */
3344 FILE_umask = umask(0777);
3345 umask( FILE_umask );
3347 load_global_options();
3349 /* setup the load callback and create ntdll modref */
3350 wine_dll_set_callback( load_builtin_callback );
3352 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3354 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3355 exit(1);
3357 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3358 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3360 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3361 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3362 0, (void **)&init_func )) != STATUS_SUCCESS)
3364 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3365 exit(1);
3367 init_func();