hal: Mark function that are only called from assembly as hidden.
[wine.git] / dlls / ntdll / loader.c
blobdd1f74c0fcc3c7292b41f075b05929539634035a
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 struct start_params
105 void *kernel_start;
106 LPTHREAD_START_ROUTINE entry;
109 static HANDLE main_exe_file;
110 static UINT tls_module_count; /* number of modules with TLS directory */
111 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
112 LIST_ENTRY tls_links = { &tls_links, &tls_links };
114 static RTL_CRITICAL_SECTION loader_section;
115 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
117 0, 0, &loader_section,
118 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
119 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
121 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
123 static WINE_MODREF *cached_modref;
124 static WINE_MODREF *current_modref;
125 static WINE_MODREF *last_failed_modref;
127 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
128 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
129 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
130 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
131 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
132 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
134 /* convert PE image VirtualAddress to Real Address */
135 static inline void *get_rva( HMODULE module, DWORD va )
137 return (void *)((char *)module + va);
140 /* check whether the file name contains a path */
141 static inline BOOL contains_path( LPCWSTR name )
143 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
146 /* convert from straight ASCII to Unicode without depending on the current codepage */
147 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
149 while (len--) *dst++ = (unsigned char)*src++;
153 /*************************************************************************
154 * call_dll_entry_point
156 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
157 * their entry point, so we need a small asm wrapper. Testing indicates
158 * that only modifying esi leads to a crash, so use this one to backup
159 * ebp while running the dll entry proc.
161 #ifdef __i386__
162 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
163 __ASM_GLOBAL_FUNC(call_dll_entry_point,
164 "pushl %ebp\n\t"
165 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
166 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
167 "movl %esp,%ebp\n\t"
168 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
169 "pushl %ebx\n\t"
170 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
171 "pushl %esi\n\t"
172 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
173 "pushl %edi\n\t"
174 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
175 "movl %ebp,%esi\n\t"
176 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
177 "pushl 20(%ebp)\n\t"
178 "pushl 16(%ebp)\n\t"
179 "pushl 12(%ebp)\n\t"
180 "movl 8(%ebp),%eax\n\t"
181 "call *%eax\n\t"
182 "movl %esi,%ebp\n\t"
183 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
184 "leal -12(%ebp),%esp\n\t"
185 "popl %edi\n\t"
186 __ASM_CFI(".cfi_same_value %edi\n\t")
187 "popl %esi\n\t"
188 __ASM_CFI(".cfi_same_value %esi\n\t")
189 "popl %ebx\n\t"
190 __ASM_CFI(".cfi_same_value %ebx\n\t")
191 "popl %ebp\n\t"
192 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
193 __ASM_CFI(".cfi_same_value %ebp\n\t")
194 "ret" )
195 #else /* __i386__ */
196 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
197 UINT reason, void *reserved )
199 return proc( module, reason, reserved );
201 #endif /* __i386__ */
204 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
205 /*************************************************************************
206 * stub_entry_point
208 * Entry point for stub functions.
210 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
212 EXCEPTION_RECORD rec;
214 rec.ExceptionCode = EXCEPTION_WINE_STUB;
215 rec.ExceptionFlags = EH_NONCONTINUABLE;
216 rec.ExceptionRecord = NULL;
217 rec.ExceptionAddress = ret_addr;
218 rec.NumberParameters = 2;
219 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
220 rec.ExceptionInformation[1] = (ULONG_PTR)name;
221 for (;;) RtlRaiseException( &rec );
225 #include "pshpack1.h"
226 #ifdef __i386__
227 struct stub
229 BYTE pushl1; /* pushl $name */
230 const char *name;
231 BYTE pushl2; /* pushl $dll */
232 const char *dll;
233 BYTE call; /* call stub_entry_point */
234 DWORD entry;
236 #elif defined(__arm__)
237 struct stub
239 BYTE ldr_r0[4]; /* ldr r0, $dll */
240 BYTE mov_pc_pc1[4]; /* mov pc,pc */
241 const char *dll;
242 BYTE ldr_r1[4]; /* ldr r1, $name */
243 BYTE mov_pc_pc2[4]; /* mov pc,pc */
244 const char *name;
245 BYTE mov_r2_lr[4]; /* mov r2, lr */
246 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #-4] */
247 const void* entry;
249 #else
250 struct stub
252 BYTE movq_rdi[2]; /* movq $dll,%rdi */
253 const char *dll;
254 BYTE movq_rsi[2]; /* movq $name,%rsi */
255 const char *name;
256 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
257 BYTE movq_rax[2]; /* movq $entry, %rax */
258 const void* entry;
259 BYTE jmpq_rax[2]; /* jmp %rax */
261 #endif
262 #include "poppack.h"
264 /*************************************************************************
265 * allocate_stub
267 * Allocate a stub entry point.
269 static ULONG_PTR allocate_stub( const char *dll, const char *name )
271 #define MAX_SIZE 65536
272 static struct stub *stubs;
273 static unsigned int nb_stubs;
274 struct stub *stub;
276 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
278 if (!stubs)
280 SIZE_T size = MAX_SIZE;
281 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
282 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
283 return 0xdeadbeef;
285 stub = &stubs[nb_stubs++];
286 #ifdef __i386__
287 stub->pushl1 = 0x68; /* pushl $name */
288 stub->name = name;
289 stub->pushl2 = 0x68; /* pushl $dll */
290 stub->dll = dll;
291 stub->call = 0xe8; /* call stub_entry_point */
292 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
293 #elif defined(__arm__)
294 stub->ldr_r0[0] = 0x00; /* ldr r0, $dll */
295 stub->ldr_r0[1] = 0x00;
296 stub->ldr_r0[2] = 0x9f;
297 stub->ldr_r0[3] = 0xe5;
298 stub->mov_pc_pc1[0] = 0x0f; /* mov pc,pc */
299 stub->mov_pc_pc1[1] = 0xf0;
300 stub->mov_pc_pc1[2] = 0xa0;
301 stub->mov_pc_pc1[3] = 0xe1;
302 stub->dll = dll;
303 stub->ldr_r1[0] = 0x00; /* ldr r1, $name */
304 stub->ldr_r1[1] = 0x10;
305 stub->ldr_r1[2] = 0x9f;
306 stub->ldr_r1[3] = 0xe5;
307 stub->mov_pc_pc2[0] = 0x0f; /* mov pc,pc */
308 stub->mov_pc_pc2[1] = 0xf0;
309 stub->mov_pc_pc2[2] = 0xa0;
310 stub->mov_pc_pc2[3] = 0xe1;
311 stub->name = name;
312 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
313 stub->mov_r2_lr[1] = 0x20;
314 stub->mov_r2_lr[2] = 0xa0;
315 stub->mov_r2_lr[3] = 0xe1;
316 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #-4] */
317 stub->ldr_pc_pc[1] = 0xf0;
318 stub->ldr_pc_pc[2] = 0x1f;
319 stub->ldr_pc_pc[3] = 0xe5;
320 stub->entry = stub_entry_point;
321 #else
322 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
323 stub->movq_rdi[1] = 0xbf;
324 stub->dll = dll;
325 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
326 stub->movq_rsi[1] = 0xbe;
327 stub->name = name;
328 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
329 stub->movq_rsp_rdx[1] = 0x8b;
330 stub->movq_rsp_rdx[2] = 0x14;
331 stub->movq_rsp_rdx[3] = 0x24;
332 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
333 stub->movq_rax[1] = 0xb8;
334 stub->entry = stub_entry_point;
335 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
336 stub->jmpq_rax[1] = 0xe0;
337 #endif
338 return (ULONG_PTR)stub;
341 #else /* __i386__ */
342 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
343 #endif /* __i386__ */
346 /*************************************************************************
347 * get_modref
349 * Looks for the referenced HMODULE in the current process
350 * The loader_section must be locked while calling this function.
352 static WINE_MODREF *get_modref( HMODULE hmod )
354 PLIST_ENTRY mark, entry;
355 PLDR_MODULE mod;
357 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
359 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
360 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
362 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
363 if (mod->BaseAddress == hmod)
364 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
366 return NULL;
370 /**********************************************************************
371 * find_basename_module
373 * Find a module from its base name.
374 * The loader_section must be locked while calling this function
376 static WINE_MODREF *find_basename_module( LPCWSTR name )
378 PLIST_ENTRY mark, entry;
380 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
381 return cached_modref;
383 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
384 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
386 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
387 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
389 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
390 return cached_modref;
393 return NULL;
397 /**********************************************************************
398 * find_fullname_module
400 * Find a module from its full path name.
401 * The loader_section must be locked while calling this function
403 static WINE_MODREF *find_fullname_module( LPCWSTR name )
405 PLIST_ENTRY mark, entry;
407 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
408 return cached_modref;
410 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
411 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
413 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
414 if (!strcmpiW( name, mod->FullDllName.Buffer ))
416 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
417 return cached_modref;
420 return NULL;
424 /*************************************************************************
425 * find_forwarded_export
427 * Find the final function pointer for a forwarded function.
428 * The loader_section must be locked while calling this function.
430 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
432 const IMAGE_EXPORT_DIRECTORY *exports;
433 DWORD exp_size;
434 WINE_MODREF *wm;
435 WCHAR mod_name[32];
436 const char *end = strrchr(forward, '.');
437 FARPROC proc = NULL;
439 if (!end) return NULL;
440 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
441 ascii_to_unicode( mod_name, forward, end - forward );
442 mod_name[end - forward] = 0;
443 if (!strchrW( mod_name, '.' ))
445 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
446 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
449 if (!(wm = find_basename_module( mod_name )))
451 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
452 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
453 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
455 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
457 LdrUnloadDll( wm->ldr.BaseAddress );
458 wm = NULL;
462 if (!wm)
464 ERR( "module not found for forward '%s' used by %s\n",
465 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
466 return NULL;
469 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
470 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
472 const char *name = end + 1;
473 if (*name == '#') /* ordinal */
474 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
475 else
476 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
479 if (!proc)
481 ERR("function not found for forward '%s' used by %s."
482 " If you are using builtin %s, try using the native one instead.\n",
483 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
484 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
486 return proc;
490 /*************************************************************************
491 * find_ordinal_export
493 * Find an exported function by ordinal.
494 * The exports base must have been subtracted from the ordinal already.
495 * The loader_section must be locked while calling this function.
497 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
498 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
500 FARPROC proc;
501 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
503 if (ordinal >= exports->NumberOfFunctions)
505 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
506 return NULL;
508 if (!functions[ordinal]) return NULL;
510 proc = get_rva( module, functions[ordinal] );
512 /* if the address falls into the export dir, it's a forward */
513 if (((const char *)proc >= (const char *)exports) &&
514 ((const char *)proc < (const char *)exports + exp_size))
515 return find_forwarded_export( module, (const char *)proc, load_path );
517 if (TRACE_ON(snoop))
519 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
520 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
522 if (TRACE_ON(relay))
524 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
525 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
527 return proc;
531 /*************************************************************************
532 * find_named_export
534 * Find an exported function by name.
535 * The loader_section must be locked while calling this function.
537 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
538 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
540 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
541 const DWORD *names = get_rva( module, exports->AddressOfNames );
542 int min = 0, max = exports->NumberOfNames - 1;
544 /* first check the hint */
545 if (hint >= 0 && hint <= max)
547 char *ename = get_rva( module, names[hint] );
548 if (!strcmp( ename, name ))
549 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
552 /* then do a binary search */
553 while (min <= max)
555 int res, pos = (min + max) / 2;
556 char *ename = get_rva( module, names[pos] );
557 if (!(res = strcmp( ename, name )))
558 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
559 if (res > 0) max = pos - 1;
560 else min = pos + 1;
562 return NULL;
567 /*************************************************************************
568 * import_dll
570 * Import the dll specified by the given import descriptor.
571 * The loader_section must be locked while calling this function.
573 static BOOL import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path, WINE_MODREF **pwm )
575 NTSTATUS status;
576 WINE_MODREF *wmImp;
577 HMODULE imp_mod;
578 const IMAGE_EXPORT_DIRECTORY *exports;
579 DWORD exp_size;
580 const IMAGE_THUNK_DATA *import_list;
581 IMAGE_THUNK_DATA *thunk_list;
582 WCHAR buffer[32];
583 const char *name = get_rva( module, descr->Name );
584 DWORD len = strlen(name);
585 PVOID protect_base;
586 SIZE_T protect_size = 0;
587 DWORD protect_old;
589 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
590 if (descr->u.OriginalFirstThunk)
591 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
592 else
593 import_list = thunk_list;
595 if (!import_list->u1.Ordinal)
597 WARN( "Skipping unused import %s\n", name );
598 *pwm = NULL;
599 return TRUE;
602 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
604 if (len * sizeof(WCHAR) < sizeof(buffer))
606 ascii_to_unicode( buffer, name, len );
607 buffer[len] = 0;
608 status = load_dll( load_path, buffer, 0, &wmImp );
610 else /* need to allocate a larger buffer */
612 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
613 if (!ptr) return FALSE;
614 ascii_to_unicode( ptr, name, len );
615 ptr[len] = 0;
616 status = load_dll( load_path, ptr, 0, &wmImp );
617 RtlFreeHeap( GetProcessHeap(), 0, ptr );
620 if (status)
622 if (status == STATUS_DLL_NOT_FOUND)
623 ERR("Library %s (which is needed by %s) not found\n",
624 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
625 else
626 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
627 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
628 return FALSE;
631 /* unprotect the import address table since it can be located in
632 * readonly section */
633 while (import_list[protect_size].u1.Ordinal) protect_size++;
634 protect_base = thunk_list;
635 protect_size *= sizeof(*thunk_list);
636 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
637 &protect_size, PAGE_READWRITE, &protect_old );
639 imp_mod = wmImp->ldr.BaseAddress;
640 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
642 if (!exports)
644 /* set all imported function to deadbeef */
645 while (import_list->u1.Ordinal)
647 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
649 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
650 WARN("No implementation for %s.%d", name, ordinal );
651 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
653 else
655 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
656 WARN("No implementation for %s.%s", name, pe_name->Name );
657 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
659 WARN(" imported from %s, allocating stub %p\n",
660 debugstr_w(current_modref->ldr.FullDllName.Buffer),
661 (void *)thunk_list->u1.Function );
662 import_list++;
663 thunk_list++;
665 goto done;
668 while (import_list->u1.Ordinal)
670 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
672 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
674 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
675 ordinal - exports->Base, load_path );
676 if (!thunk_list->u1.Function)
678 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
679 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
680 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
681 (void *)thunk_list->u1.Function );
683 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
685 else /* import by name */
687 IMAGE_IMPORT_BY_NAME *pe_name;
688 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
689 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
690 (const char*)pe_name->Name,
691 pe_name->Hint, load_path );
692 if (!thunk_list->u1.Function)
694 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
695 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
696 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
697 (void *)thunk_list->u1.Function );
699 TRACE_(imports)("--- %s %s.%d = %p\n",
700 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
702 import_list++;
703 thunk_list++;
706 done:
707 /* restore old protection of the import address table */
708 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
709 *pwm = wmImp;
710 return TRUE;
714 /***********************************************************************
715 * create_module_activation_context
717 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
719 NTSTATUS status;
720 LDR_RESOURCE_INFO info;
721 const IMAGE_RESOURCE_DATA_ENTRY *entry;
723 info.Type = RT_MANIFEST;
724 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
725 info.Language = 0;
726 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
728 ACTCTXW ctx;
729 ctx.cbSize = sizeof(ctx);
730 ctx.lpSource = NULL;
731 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
732 ctx.hModule = module->BaseAddress;
733 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
734 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
736 return status;
740 /*************************************************************************
741 * is_dll_native_subsystem
743 * Check if dll is a proper native driver.
744 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
745 * while being perfectly normal DLLs. This heuristic should catch such breakages.
747 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
749 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
750 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
751 const IMAGE_IMPORT_DESCRIPTOR *imports;
752 DWORD i, size;
753 WCHAR buffer[16];
755 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
756 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
758 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
759 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
761 for (i = 0; imports[i].Name; i++)
763 const char *name = get_rva( module, imports[i].Name );
764 DWORD len = strlen(name);
765 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
766 ascii_to_unicode( buffer, name, len + 1 );
767 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
769 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
770 return FALSE;
774 return TRUE;
777 /*************************************************************************
778 * alloc_tls_slot
780 * Allocate a TLS slot for a newly-loaded module.
781 * The loader_section must be locked while calling this function.
783 static SHORT alloc_tls_slot( LDR_MODULE *mod )
785 const IMAGE_TLS_DIRECTORY *dir;
786 ULONG i, size;
787 void *new_ptr;
788 LIST_ENTRY *entry;
790 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
791 return -1;
793 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
794 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
796 for (i = 0; i < tls_module_count; i++)
798 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
799 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
800 break;
803 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
804 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
805 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
807 if (i == tls_module_count)
809 UINT new_count = max( 32, tls_module_count * 2 );
811 if (!tls_dirs)
812 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
813 else
814 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
815 new_count * sizeof(*tls_dirs) );
816 if (!new_ptr) return -1;
818 /* resize the pointer block in all running threads */
819 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
821 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
822 void **old = teb->ThreadLocalStoragePointer;
823 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
825 if (!new) return -1;
826 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
827 teb->ThreadLocalStoragePointer = new;
828 #if defined(__APPLE__) && defined(__x86_64__)
829 if (teb->Reserved5[0])
830 ((TEB*)teb->Reserved5[0])->ThreadLocalStoragePointer = new;
831 #endif
832 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
833 /* FIXME: can't free old block here, should be freed at thread exit */
836 tls_dirs = new_ptr;
837 tls_module_count = new_count;
840 /* allocate the data block in all running threads */
841 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
843 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
845 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
846 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
847 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
849 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
850 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
852 RtlFreeHeap( GetProcessHeap(), 0,
853 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
856 *(DWORD *)dir->AddressOfIndex = i;
857 tls_dirs[i] = *dir;
858 return i;
862 /*************************************************************************
863 * free_tls_slot
865 * Free the module TLS slot on unload.
866 * The loader_section must be locked while calling this function.
868 static void free_tls_slot( LDR_MODULE *mod )
870 ULONG i = (USHORT)mod->TlsIndex;
872 if (mod->TlsIndex == -1) return;
873 assert( i < tls_module_count );
874 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
878 /****************************************************************
879 * fixup_imports
881 * Fixup all imports of a given module.
882 * The loader_section must be locked while calling this function.
884 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
886 int i, nb_imports;
887 const IMAGE_IMPORT_DESCRIPTOR *imports;
888 WINE_MODREF *prev;
889 DWORD size;
890 NTSTATUS status;
891 ULONG_PTR cookie;
893 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
894 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
896 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
898 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
899 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
900 return STATUS_SUCCESS;
902 nb_imports = 0;
903 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
905 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
907 if (!create_module_activation_context( &wm->ldr ))
908 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
910 /* Allocate module dependency list */
911 wm->nDeps = nb_imports;
912 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
914 /* load the imported modules. They are automatically
915 * added to the modref list of the process.
917 prev = current_modref;
918 current_modref = wm;
919 status = STATUS_SUCCESS;
920 for (i = 0; i < nb_imports; i++)
922 if (!import_dll( wm->ldr.BaseAddress, &imports[i], load_path, &wm->deps[i] ))
924 wm->deps[i] = NULL;
925 status = STATUS_DLL_NOT_FOUND;
928 current_modref = prev;
929 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
930 return status;
934 /*************************************************************************
935 * alloc_module
937 * Allocate a WINE_MODREF structure and add it to the process list
938 * The loader_section must be locked while calling this function.
940 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
942 WINE_MODREF *wm;
943 const WCHAR *p;
944 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
946 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
948 wm->nDeps = 0;
949 wm->deps = NULL;
951 wm->ldr.BaseAddress = hModule;
952 wm->ldr.EntryPoint = NULL;
953 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
954 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
955 wm->ldr.TlsIndex = -1;
956 wm->ldr.LoadCount = 1;
957 wm->ldr.SectionHandle = NULL;
958 wm->ldr.CheckSum = 0;
959 wm->ldr.TimeDateStamp = 0;
960 wm->ldr.ActivationContext = 0;
962 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
963 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
964 else p = wm->ldr.FullDllName.Buffer;
965 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
967 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
969 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
970 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
971 if (nt->OptionalHeader.AddressOfEntryPoint)
972 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
975 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
976 &wm->ldr.InLoadOrderModuleList);
977 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList,
978 &wm->ldr.InMemoryOrderModuleList);
980 /* wait until init is called for inserting into this list */
981 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
982 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
984 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
986 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
987 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
988 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
990 return wm;
994 /*************************************************************************
995 * alloc_thread_tls
997 * Allocate the per-thread structure for module TLS storage.
999 static NTSTATUS alloc_thread_tls(void)
1001 void **pointers;
1002 UINT i, size;
1004 if (!tls_module_count) return STATUS_SUCCESS;
1006 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
1007 tls_module_count * sizeof(*pointers) )))
1008 return STATUS_NO_MEMORY;
1010 for (i = 0; i < tls_module_count; i++)
1012 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1014 if (!dir) continue;
1015 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1016 if (!size && !dir->SizeOfZeroFill) continue;
1018 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1020 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1021 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1022 return STATUS_NO_MEMORY;
1024 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1025 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1027 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1028 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1030 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1031 #if defined(__APPLE__) && defined(__x86_64__)
1032 __asm__ volatile (".byte 0x65\n\tmovq %0,%c1"
1034 : "r" (pointers), "n" (FIELD_OFFSET(TEB, ThreadLocalStoragePointer)));
1035 #endif
1036 return STATUS_SUCCESS;
1040 /*************************************************************************
1041 * call_tls_callbacks
1043 static void call_tls_callbacks( HMODULE module, UINT reason )
1045 const IMAGE_TLS_DIRECTORY *dir;
1046 const PIMAGE_TLS_CALLBACK *callback;
1047 ULONG dirsize;
1049 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1050 if (!dir || !dir->AddressOfCallBacks) return;
1052 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1054 if (TRACE_ON(relay))
1056 if (TRACE_ON(pid))
1057 DPRINTF( "%04x:", GetCurrentProcessId() );
1058 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1059 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1061 __TRY
1063 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1065 __EXCEPT_ALL
1067 if (TRACE_ON(relay))
1069 if (TRACE_ON(pid))
1070 DPRINTF( "%04x:", GetCurrentProcessId() );
1071 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1072 GetCurrentThreadId(), callback, module, reason_names[reason] );
1074 return;
1076 __ENDTRY
1077 if (TRACE_ON(relay))
1079 if (TRACE_ON(pid))
1080 DPRINTF( "%04x:", GetCurrentProcessId() );
1081 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1082 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1088 /*************************************************************************
1089 * MODULE_InitDLL
1091 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1093 WCHAR mod_name[32];
1094 NTSTATUS status = STATUS_SUCCESS;
1095 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1096 void *module = wm->ldr.BaseAddress;
1097 BOOL retv = FALSE;
1099 /* Skip calls for modules loaded with special load flags */
1101 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1102 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1103 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1105 if (TRACE_ON(relay))
1107 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1108 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1109 mod_name[len / sizeof(WCHAR)] = 0;
1110 if (TRACE_ON(pid))
1111 DPRINTF( "%04x:", GetCurrentProcessId() );
1112 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1113 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1114 reason_names[reason], lpReserved );
1116 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1117 reason_names[reason], lpReserved );
1119 __TRY
1121 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1122 if (!retv)
1123 status = STATUS_DLL_INIT_FAILED;
1125 __EXCEPT_ALL
1127 if (TRACE_ON(relay))
1129 if (TRACE_ON(pid))
1130 DPRINTF( "%04x:", GetCurrentProcessId() );
1131 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1132 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1134 status = GetExceptionCode();
1136 __ENDTRY
1138 /* The state of the module list may have changed due to the call
1139 to the dll. We cannot assume that this module has not been
1140 deleted. */
1141 if (TRACE_ON(relay))
1143 if (TRACE_ON(pid))
1144 DPRINTF( "%04x:", GetCurrentProcessId() );
1145 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1146 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1147 reason_names[reason], lpReserved, retv );
1149 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1151 return status;
1155 /*************************************************************************
1156 * process_attach
1158 * Send the process attach notification to all DLLs the given module
1159 * depends on (recursively). This is somewhat complicated due to the fact that
1161 * - we have to respect the module dependencies, i.e. modules implicitly
1162 * referenced by another module have to be initialized before the module
1163 * itself can be initialized
1165 * - the initialization routine of a DLL can itself call LoadLibrary,
1166 * thereby introducing a whole new set of dependencies (even involving
1167 * the 'old' modules) at any time during the whole process
1169 * (Note that this routine can be recursively entered not only directly
1170 * from itself, but also via LoadLibrary from one of the called initialization
1171 * routines.)
1173 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1174 * the process *detach* notifications to be sent in the correct order.
1175 * This must not only take into account module dependencies, but also
1176 * 'hidden' dependencies created by modules calling LoadLibrary in their
1177 * attach notification routine.
1179 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1180 * list after the attach notification has returned. This implies that the
1181 * detach notifications are called in the reverse of the sequence the attach
1182 * notifications *returned*.
1184 * The loader_section must be locked while calling this function.
1186 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1188 NTSTATUS status = STATUS_SUCCESS;
1189 ULONG_PTR cookie;
1190 int i;
1192 if (process_detaching) return status;
1194 /* prevent infinite recursion in case of cyclical dependencies */
1195 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1196 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1197 return status;
1199 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1201 /* Tag current MODREF to prevent recursive loop */
1202 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1203 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1204 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1206 /* Recursively attach all DLLs this one depends on */
1207 for ( i = 0; i < wm->nDeps; i++ )
1209 if (!wm->deps[i]) continue;
1210 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1213 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1214 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1215 &wm->ldr.InInitializationOrderModuleList);
1217 /* Call DLL entry point */
1218 if (status == STATUS_SUCCESS)
1220 WINE_MODREF *prev = current_modref;
1221 current_modref = wm;
1222 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1223 if (status == STATUS_SUCCESS)
1224 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1225 else
1227 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1228 /* point to the name so LdrInitializeThunk can print it */
1229 last_failed_modref = wm;
1230 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1232 current_modref = prev;
1235 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1236 /* Remove recursion flag */
1237 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1239 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1240 return status;
1244 /**********************************************************************
1245 * attach_implicitly_loaded_dlls
1247 * Attach to the (builtin) dlls that have been implicitly loaded because
1248 * of a dependency at the Unix level, but not imported at the Win32 level.
1250 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1252 for (;;)
1254 PLIST_ENTRY mark, entry;
1256 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1257 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1259 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1261 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1262 TRACE( "found implicitly loaded %s, attaching to it\n",
1263 debugstr_w(mod->BaseDllName.Buffer));
1264 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1265 break; /* restart the search from the start */
1267 if (entry == mark) break; /* nothing found */
1272 /*************************************************************************
1273 * process_detach
1275 * Send DLL process detach notifications. See the comment about calling
1276 * sequence at process_attach.
1278 static void process_detach(void)
1280 PLIST_ENTRY mark, entry;
1281 PLDR_MODULE mod;
1283 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1286 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1288 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1289 InInitializationOrderModuleList);
1290 /* Check whether to detach this DLL */
1291 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1292 continue;
1293 if ( mod->LoadCount && !process_detaching )
1294 continue;
1296 /* Call detach notification */
1297 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1298 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1299 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1301 /* Restart at head of WINE_MODREF list, as entries might have
1302 been added and/or removed while performing the call ... */
1303 break;
1305 } while (entry != mark);
1308 /*************************************************************************
1309 * MODULE_DllThreadAttach
1311 * Send DLL thread attach notifications. These are sent in the
1312 * reverse sequence of process detach notification.
1315 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1317 PLIST_ENTRY mark, entry;
1318 PLDR_MODULE mod;
1319 NTSTATUS status;
1321 /* don't do any attach calls if process is exiting */
1322 if (process_detaching) return STATUS_SUCCESS;
1324 RtlEnterCriticalSection( &loader_section );
1326 RtlAcquirePebLock();
1327 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1328 RtlReleasePebLock();
1330 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1332 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1333 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1335 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1336 InInitializationOrderModuleList);
1337 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1338 continue;
1339 if ( mod->Flags & LDR_NO_DLL_CALLS )
1340 continue;
1342 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1343 DLL_THREAD_ATTACH, lpReserved );
1346 done:
1347 RtlLeaveCriticalSection( &loader_section );
1348 return status;
1351 /******************************************************************
1352 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1355 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1357 WINE_MODREF *wm;
1358 NTSTATUS ret = STATUS_SUCCESS;
1360 RtlEnterCriticalSection( &loader_section );
1362 wm = get_modref( hModule );
1363 if (!wm || wm->ldr.TlsIndex != -1)
1364 ret = STATUS_DLL_NOT_FOUND;
1365 else
1366 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1368 RtlLeaveCriticalSection( &loader_section );
1370 return ret;
1373 /******************************************************************
1374 * LdrFindEntryForAddress (NTDLL.@)
1376 * The loader_section must be locked while calling this function
1378 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1380 PLIST_ENTRY mark, entry;
1381 PLDR_MODULE mod;
1383 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1384 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1386 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1387 if (mod->BaseAddress <= addr &&
1388 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1390 *pmod = mod;
1391 return STATUS_SUCCESS;
1394 return STATUS_NO_MORE_ENTRIES;
1397 /******************************************************************
1398 * LdrEnumerateLoadedModules (NTDLL.@)
1400 NTSTATUS WINAPI LdrEnumerateLoadedModules( void *unknown, LDRENUMPROC callback, void *context )
1402 LIST_ENTRY *mark, *entry;
1403 LDR_MODULE *mod;
1404 BOOLEAN stop = FALSE;
1406 TRACE( "(%p, %p, %p)\n", unknown, callback, context );
1408 if (unknown || !callback)
1409 return STATUS_INVALID_PARAMETER;
1411 RtlEnterCriticalSection( &loader_section );
1413 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1414 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1416 mod = CONTAINING_RECORD( entry, LDR_MODULE, InMemoryOrderModuleList );
1417 callback( mod, context, &stop );
1418 if (stop) break;
1421 RtlLeaveCriticalSection( &loader_section );
1422 return STATUS_SUCCESS;
1425 /******************************************************************
1426 * LdrLockLoaderLock (NTDLL.@)
1428 * Note: some flags are not implemented.
1429 * Flag 0x01 is used to raise exceptions on errors.
1431 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1433 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1435 if (result) *result = 0;
1436 if (magic) *magic = 0;
1437 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1438 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1439 if (!magic) return STATUS_INVALID_PARAMETER_3;
1441 if (flags & 0x2)
1443 if (!RtlTryEnterCriticalSection( &loader_section ))
1445 *result = 2;
1446 return STATUS_SUCCESS;
1448 *result = 1;
1450 else
1452 RtlEnterCriticalSection( &loader_section );
1453 if (result) *result = 1;
1455 *magic = GetCurrentThreadId();
1456 return STATUS_SUCCESS;
1460 /******************************************************************
1461 * LdrUnlockLoaderUnlock (NTDLL.@)
1463 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1465 if (magic)
1467 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1468 RtlLeaveCriticalSection( &loader_section );
1470 return STATUS_SUCCESS;
1474 /******************************************************************
1475 * LdrGetProcedureAddress (NTDLL.@)
1477 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1478 ULONG ord, PVOID *address)
1480 IMAGE_EXPORT_DIRECTORY *exports;
1481 DWORD exp_size;
1482 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1484 RtlEnterCriticalSection( &loader_section );
1486 /* check if the module itself is invalid to return the proper error */
1487 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1488 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1489 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1491 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1492 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1493 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1494 if (proc)
1496 *address = proc;
1497 ret = STATUS_SUCCESS;
1501 RtlLeaveCriticalSection( &loader_section );
1502 return ret;
1506 /***********************************************************************
1507 * is_fake_dll
1509 * Check if a loaded native dll is a Wine fake dll.
1511 static BOOL is_fake_dll( HANDLE handle )
1513 static const char fakedll_signature[] = "Wine placeholder DLL";
1514 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1515 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1516 IO_STATUS_BLOCK io;
1517 LARGE_INTEGER offset;
1519 offset.QuadPart = 0;
1520 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1521 if (io.Information < sizeof(buffer)) return FALSE;
1522 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1523 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1524 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1525 return FALSE;
1529 /***********************************************************************
1530 * get_builtin_fullname
1532 * Build the full pathname for a builtin dll.
1534 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1536 static const WCHAR soW[] = {'.','s','o',0};
1537 WCHAR *p, *fullname;
1538 size_t i, len = strlen(filename);
1540 /* check if path can correspond to the dll we have */
1541 if (path && (p = strrchrW( path, '\\' )))
1543 p++;
1544 for (i = 0; i < len; i++)
1545 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1546 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1548 /* the filename matches, use path as the full path */
1549 len += p - path;
1550 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1552 memcpy( fullname, path, len * sizeof(WCHAR) );
1553 fullname[len] = 0;
1555 return fullname;
1559 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1560 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1562 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1563 p = fullname + system_dir.Length / sizeof(WCHAR);
1564 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1565 ascii_to_unicode( p, filename, len + 1 );
1567 return fullname;
1571 /*************************************************************************
1572 * is_16bit_builtin
1574 static BOOL is_16bit_builtin( HMODULE module )
1576 const IMAGE_EXPORT_DIRECTORY *exports;
1577 DWORD exp_size;
1579 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1580 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1581 return FALSE;
1583 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1587 /***********************************************************************
1588 * load_builtin_callback
1590 * Load a library in memory; callback function for wine_dll_register
1592 static void load_builtin_callback( void *module, const char *filename )
1594 static const WCHAR emptyW[1];
1595 IMAGE_NT_HEADERS *nt;
1596 WINE_MODREF *wm;
1597 WCHAR *fullname;
1598 const WCHAR *load_path;
1600 if (!module)
1602 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1603 return;
1605 if (!(nt = RtlImageNtHeader( module )))
1607 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1608 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1609 return;
1612 virtual_create_builtin_view( module );
1614 /* create the MODREF */
1616 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1618 ERR( "can't load %s\n", filename );
1619 builtin_load_info->status = STATUS_NO_MEMORY;
1620 return;
1623 wm = alloc_module( module, fullname );
1624 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1625 if (!wm)
1627 ERR( "can't load %s\n", filename );
1628 builtin_load_info->status = STATUS_NO_MEMORY;
1629 return;
1631 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1633 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1634 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1635 is_16bit_builtin( module ))
1637 /* fixup imports */
1639 load_path = builtin_load_info->load_path;
1640 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1641 if (!load_path) load_path = emptyW;
1642 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1644 /* the module has only be inserted in the load & memory order lists */
1645 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1646 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1647 /* FIXME: free the modref */
1648 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1649 return;
1653 builtin_load_info->wm = wm;
1654 TRACE( "loaded %s %p %p\n", filename, wm, module );
1656 /* send the DLL load event */
1658 SERVER_START_REQ( load_dll )
1660 req->mapping = 0;
1661 req->base = wine_server_client_ptr( module );
1662 req->size = nt->OptionalHeader.SizeOfImage;
1663 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1664 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1665 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1666 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1667 wine_server_call( req );
1669 SERVER_END_REQ;
1671 /* setup relay debugging entry points */
1672 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1676 /***********************************************************************
1677 * set_security_cookie
1679 * Create a random security cookie for buffer overflow protection. Make
1680 * sure it does not accidentally match the default cookie value.
1682 static void set_security_cookie( void *module, SIZE_T len )
1684 static ULONG seed;
1685 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1686 ULONG loadcfg_size;
1687 ULONG_PTR *cookie;
1689 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1690 if (!loadcfg) return;
1691 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1692 if (!loadcfg->SecurityCookie) return;
1693 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1694 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1696 WARN( "security cookie %p outside of image %p-%p\n",
1697 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1698 return;
1701 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1702 TRACE( "initializing security cookie %p\n", cookie );
1704 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1705 for (;;)
1707 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1708 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1709 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1710 *cookie = RtlRandom( &seed );
1711 #ifdef DEFAULT_SECURITY_COOKIE_64
1712 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1714 *cookie = RtlRandom( &seed );
1715 /* fill up, but keep the highest word clear */
1716 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1718 #endif
1719 else
1720 break;
1724 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1726 IMAGE_NT_HEADERS *nt;
1727 char *base;
1728 IMAGE_BASE_RELOCATION *rel, *end;
1729 const IMAGE_DATA_DIRECTORY *relocs;
1730 const IMAGE_SECTION_HEADER *sec;
1731 INT_PTR delta;
1732 ULONG protect_old[96], i;
1734 nt = RtlImageNtHeader( module );
1735 base = (char *)nt->OptionalHeader.ImageBase;
1737 assert( module != base );
1739 /* no relocations are performed on non page-aligned binaries */
1740 if (nt->OptionalHeader.SectionAlignment < page_size)
1741 return STATUS_SUCCESS;
1743 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1744 return STATUS_SUCCESS;
1746 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1748 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1750 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1751 base, module );
1752 return STATUS_CONFLICTING_ADDRESSES;
1755 if (!relocs->Size) return STATUS_SUCCESS;
1756 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1758 if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
1759 return STATUS_INVALID_IMAGE_FORMAT;
1761 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1762 nt->FileHeader.SizeOfOptionalHeader);
1763 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1765 void *addr = get_rva( module, sec[i].VirtualAddress );
1766 SIZE_T size = sec[i].SizeOfRawData;
1767 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1768 &size, PAGE_READWRITE, &protect_old[i] );
1771 TRACE( "relocating from %p-%p to %p-%p\n",
1772 base, base + len, module, (char *)module + len );
1774 rel = get_rva( module, relocs->VirtualAddress );
1775 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1776 delta = (char *)module - base;
1778 while (rel < end - 1 && rel->SizeOfBlock)
1780 if (rel->VirtualAddress >= len)
1782 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1783 return STATUS_ACCESS_VIOLATION;
1785 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1786 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1787 (USHORT *)(rel + 1), delta );
1788 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1791 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1793 void *addr = get_rva( module, sec[i].VirtualAddress );
1794 SIZE_T size = sec[i].SizeOfRawData;
1795 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1796 &size, protect_old[i], &protect_old[i] );
1799 return STATUS_SUCCESS;
1802 /******************************************************************************
1803 * load_native_dll (internal)
1805 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1806 DWORD flags, WINE_MODREF** pwm )
1808 void *module;
1809 HANDLE mapping;
1810 LARGE_INTEGER size;
1811 IMAGE_NT_HEADERS *nt;
1812 SIZE_T len = 0;
1813 WINE_MODREF *wm;
1814 NTSTATUS status;
1816 TRACE("Trying native dll %s\n", debugstr_w(name));
1818 size.QuadPart = 0;
1819 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1820 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1821 if (status != STATUS_SUCCESS) return status;
1823 module = NULL;
1824 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1825 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1827 /* perform base relocation, if necessary */
1829 if (status == STATUS_IMAGE_NOT_AT_BASE)
1830 status = perform_relocations( module, len );
1832 if (status != STATUS_SUCCESS)
1834 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1835 goto done;
1838 /* create the MODREF */
1840 if (!(wm = alloc_module( module, name )))
1842 status = STATUS_NO_MEMORY;
1843 goto done;
1846 set_security_cookie( module, len );
1848 /* fixup imports */
1850 nt = RtlImageNtHeader( module );
1852 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1853 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1854 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1856 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1858 /* the module has only be inserted in the load & memory order lists */
1859 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1860 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1862 /* FIXME: there are several more dangling references
1863 * left. Including dlls loaded by this dll before the
1864 * failed one. Unrolling is rather difficult with the
1865 * current structure and we can leave them lying
1866 * around with no problems, so we don't care.
1867 * As these might reference our wm, we don't free it.
1869 goto done;
1873 /* send DLL load event */
1875 SERVER_START_REQ( load_dll )
1877 req->mapping = wine_server_obj_handle( mapping );
1878 req->base = wine_server_client_ptr( module );
1879 req->size = nt->OptionalHeader.SizeOfImage;
1880 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1881 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1882 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1883 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1884 wine_server_call( req );
1886 SERVER_END_REQ;
1888 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1890 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1892 wm->ldr.LoadCount = 1;
1893 *pwm = wm;
1894 status = STATUS_SUCCESS;
1895 done:
1896 NtClose( mapping );
1897 return status;
1901 /***********************************************************************
1902 * load_builtin_dll
1904 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1905 DWORD flags, WINE_MODREF** pwm )
1907 char error[256], dllname[MAX_PATH];
1908 const WCHAR *name, *p;
1909 DWORD len, i;
1910 void *handle;
1911 struct builtin_load_info info, *prev_info;
1913 /* Fix the name in case we have a full path and extension */
1914 name = path;
1915 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1916 if ((p = strrchrW( name, '/' ))) name = p + 1;
1918 /* load_library will modify info.status. Note also that load_library can be
1919 * called several times, if the .so file we're loading has dependencies.
1920 * info.status will gather all the errors we may get while loading all these
1921 * libraries
1923 info.load_path = load_path;
1924 info.filename = NULL;
1925 info.status = STATUS_SUCCESS;
1926 info.wm = NULL;
1928 if (file) /* we have a real file, try to load it */
1930 UNICODE_STRING nt_name;
1931 ANSI_STRING unix_name;
1933 TRACE("Trying built-in %s\n", debugstr_w(path));
1935 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1936 return STATUS_DLL_NOT_FOUND;
1938 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1940 RtlFreeUnicodeString( &nt_name );
1941 return STATUS_DLL_NOT_FOUND;
1943 prev_info = builtin_load_info;
1944 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1945 builtin_load_info = &info;
1946 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1947 builtin_load_info = prev_info;
1948 RtlFreeUnicodeString( &nt_name );
1949 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1950 if (!handle)
1952 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1953 return STATUS_INVALID_IMAGE_FORMAT;
1956 else
1958 int file_exists;
1960 TRACE("Trying built-in %s\n", debugstr_w(name));
1962 /* we don't want to depend on the current codepage here */
1963 len = strlenW( name ) + 1;
1964 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1965 for (i = 0; i < len; i++)
1967 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1968 dllname[i] = (char)name[i];
1969 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1972 prev_info = builtin_load_info;
1973 builtin_load_info = &info;
1974 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1975 builtin_load_info = prev_info;
1976 if (!handle)
1978 if (!file_exists)
1980 /* The file does not exist -> WARN() */
1981 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1982 return STATUS_DLL_NOT_FOUND;
1984 /* ERR() for all other errors (missing functions, ...) */
1985 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1986 return STATUS_PROCEDURE_NOT_FOUND;
1990 if (info.status != STATUS_SUCCESS)
1992 wine_dll_unload( handle );
1993 return info.status;
1996 if (!info.wm)
1998 PLIST_ENTRY mark, entry;
2000 /* The constructor wasn't called, this means the .so is already
2001 * loaded under a different name. Try to find the wm for it. */
2003 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2004 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2006 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2007 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
2009 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2010 TRACE( "Found %s at %p for builtin %s\n",
2011 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
2012 break;
2015 wine_dll_unload( handle ); /* release the libdl refcount */
2016 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
2017 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
2019 else
2021 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
2022 info.wm->ldr.LoadCount = 1;
2023 info.wm->ldr.SectionHandle = handle;
2026 *pwm = info.wm;
2027 return STATUS_SUCCESS;
2031 /***********************************************************************
2032 * find_actctx_dll
2034 * Find the full path (if any) of the dll from the activation context.
2036 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
2038 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
2039 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
2041 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2042 ACTCTX_SECTION_KEYED_DATA data;
2043 UNICODE_STRING nameW;
2044 NTSTATUS status;
2045 SIZE_T needed, size = 1024;
2046 WCHAR *p;
2048 RtlInitUnicodeString( &nameW, libname );
2049 data.cbSize = sizeof(data);
2050 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2051 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2052 &nameW, &data );
2053 if (status != STATUS_SUCCESS) return status;
2055 for (;;)
2057 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2059 status = STATUS_NO_MEMORY;
2060 goto done;
2062 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2063 AssemblyDetailedInformationInActivationContext,
2064 info, size, &needed );
2065 if (status == STATUS_SUCCESS) break;
2066 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2067 RtlFreeHeap( GetProcessHeap(), 0, info );
2068 size = needed;
2069 /* restart with larger buffer */
2072 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2074 status = STATUS_SXS_KEY_NOT_FOUND;
2075 goto done;
2078 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2080 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2082 p++;
2083 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2085 /* manifest name does not match directory name, so it's not a global
2086 * windows/winsxs manifest; use the manifest directory name instead */
2087 dirlen = p - info->lpAssemblyManifestPath;
2088 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2089 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2091 status = STATUS_NO_MEMORY;
2092 goto done;
2094 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2095 p += dirlen;
2096 strcpyW( p, libname );
2097 goto done;
2101 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2102 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2104 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2106 status = STATUS_NO_MEMORY;
2107 goto done;
2109 strcpyW( p, user_shared_data->NtSystemRoot );
2110 p += strlenW(p);
2111 memcpy( p, winsxsW, sizeof(winsxsW) );
2112 p += sizeof(winsxsW) / sizeof(WCHAR);
2113 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2114 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2115 *p++ = '\\';
2116 strcpyW( p, libname );
2117 done:
2118 RtlFreeHeap( GetProcessHeap(), 0, info );
2119 RtlReleaseActivationContext( data.hActCtx );
2120 return status;
2124 /***********************************************************************
2125 * find_dll_file
2127 * Find the file (or already loaded module) for a given dll name.
2129 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2130 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
2132 OBJECT_ATTRIBUTES attr;
2133 IO_STATUS_BLOCK io;
2134 UNICODE_STRING nt_name;
2135 WCHAR *file_part, *ext, *dllname;
2136 ULONG len;
2138 /* first append .dll if needed */
2140 dllname = NULL;
2141 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2143 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2144 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2145 return STATUS_NO_MEMORY;
2146 strcpyW( dllname, libname );
2147 strcatW( dllname, dllW );
2148 libname = dllname;
2151 nt_name.Buffer = NULL;
2153 if (!contains_path( libname ))
2155 NTSTATUS status;
2156 WCHAR *fullname = NULL;
2158 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2160 status = find_actctx_dll( libname, &fullname );
2161 if (status == STATUS_SUCCESS)
2163 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2164 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2165 libname = dllname = fullname;
2167 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2169 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2170 return status;
2174 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2176 /* we need to search for it */
2177 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2178 if (len)
2180 if (len >= *size) goto overflow;
2181 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2183 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2185 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2186 return STATUS_NO_MEMORY;
2188 attr.Length = sizeof(attr);
2189 attr.RootDirectory = 0;
2190 attr.Attributes = OBJ_CASE_INSENSITIVE;
2191 attr.ObjectName = &nt_name;
2192 attr.SecurityDescriptor = NULL;
2193 attr.SecurityQualityOfService = NULL;
2194 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2195 goto found;
2198 /* not found */
2200 if (!contains_path( libname ))
2202 /* if libname doesn't contain a path at all, we simply return the name as is,
2203 * to be loaded as builtin */
2204 len = strlenW(libname) * sizeof(WCHAR);
2205 if (len >= *size) goto overflow;
2206 strcpyW( filename, libname );
2207 goto found;
2211 /* absolute path name, or relative path name but not found above */
2213 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2215 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2216 return STATUS_NO_MEMORY;
2218 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2219 if (len >= *size) goto overflow;
2220 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2221 if (!(*pwm = find_fullname_module( filename )) && handle)
2223 attr.Length = sizeof(attr);
2224 attr.RootDirectory = 0;
2225 attr.Attributes = OBJ_CASE_INSENSITIVE;
2226 attr.ObjectName = &nt_name;
2227 attr.SecurityDescriptor = NULL;
2228 attr.SecurityQualityOfService = NULL;
2229 if (NtOpenFile( handle, GENERIC_READ|SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2231 found:
2232 RtlFreeUnicodeString( &nt_name );
2233 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2234 return STATUS_SUCCESS;
2236 overflow:
2237 RtlFreeUnicodeString( &nt_name );
2238 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2239 *size = len + sizeof(WCHAR);
2240 return STATUS_BUFFER_TOO_SMALL;
2244 /***********************************************************************
2245 * load_dll (internal)
2247 * Load a PE style module according to the load order.
2248 * The loader_section must be locked while calling this function.
2250 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2252 enum loadorder loadorder;
2253 WCHAR buffer[64];
2254 WCHAR *filename;
2255 ULONG size;
2256 WINE_MODREF *main_exe;
2257 HANDLE handle = 0;
2258 NTSTATUS nts;
2260 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2262 *pwm = NULL;
2263 filename = buffer;
2264 size = sizeof(buffer);
2265 for (;;)
2267 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2268 if (nts == STATUS_SUCCESS) break;
2269 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2270 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2271 /* grow the buffer and retry */
2272 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2275 if (*pwm) /* found already loaded module */
2277 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2279 TRACE("Found %s for %s at %p, count=%d\n",
2280 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2281 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2282 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2283 return STATUS_SUCCESS;
2286 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2287 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2289 if (handle && is_fake_dll( handle ))
2291 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2292 NtClose( handle );
2293 handle = 0;
2296 switch(loadorder)
2298 case LO_INVALID:
2299 nts = STATUS_NO_MEMORY;
2300 break;
2301 case LO_DISABLED:
2302 nts = STATUS_DLL_NOT_FOUND;
2303 break;
2304 case LO_NATIVE:
2305 case LO_NATIVE_BUILTIN:
2306 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2307 else
2309 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2310 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2311 /* not in PE format, maybe it's a builtin */
2312 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2314 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2315 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2316 break;
2317 case LO_BUILTIN:
2318 case LO_BUILTIN_NATIVE:
2319 case LO_DEFAULT: /* default is builtin,native */
2320 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2321 if (!handle) break; /* nothing else we can try */
2322 /* file is not a builtin library, try without using the specified file */
2323 if (nts != STATUS_SUCCESS)
2324 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2325 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2326 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2328 /* stub-only dll, try native */
2329 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2330 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2331 nts = STATUS_DLL_NOT_FOUND;
2333 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2334 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2335 break;
2338 if (nts == STATUS_SUCCESS)
2340 /* Initialize DLL just loaded */
2341 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2342 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2343 (*pwm)->ldr.BaseAddress);
2344 if (handle) NtClose( handle );
2345 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2346 return nts;
2349 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2350 if (handle) NtClose( handle );
2351 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2352 return nts;
2355 /******************************************************************
2356 * LdrLoadDll (NTDLL.@)
2358 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2359 const UNICODE_STRING *libname, HMODULE* hModule)
2361 WINE_MODREF *wm;
2362 NTSTATUS nts;
2364 RtlEnterCriticalSection( &loader_section );
2366 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2367 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2369 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2371 nts = process_attach( wm, NULL );
2372 if (nts != STATUS_SUCCESS)
2374 LdrUnloadDll(wm->ldr.BaseAddress);
2375 wm = NULL;
2378 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2380 RtlLeaveCriticalSection( &loader_section );
2381 return nts;
2385 /******************************************************************
2386 * LdrGetDllHandle (NTDLL.@)
2388 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2390 NTSTATUS status;
2391 WCHAR buffer[128];
2392 WCHAR *filename;
2393 ULONG size;
2394 WINE_MODREF *wm;
2396 RtlEnterCriticalSection( &loader_section );
2398 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2400 filename = buffer;
2401 size = sizeof(buffer);
2402 for (;;)
2404 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2405 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2406 if (status != STATUS_BUFFER_TOO_SMALL) break;
2407 /* grow the buffer and retry */
2408 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2410 status = STATUS_NO_MEMORY;
2411 break;
2415 if (status == STATUS_SUCCESS)
2417 if (wm) *base = wm->ldr.BaseAddress;
2418 else status = STATUS_DLL_NOT_FOUND;
2421 RtlLeaveCriticalSection( &loader_section );
2422 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2423 return status;
2427 /******************************************************************
2428 * LdrAddRefDll (NTDLL.@)
2430 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2432 NTSTATUS ret = STATUS_SUCCESS;
2433 WINE_MODREF *wm;
2435 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2437 RtlEnterCriticalSection( &loader_section );
2439 if ((wm = get_modref( module )))
2441 if (flags & LDR_ADDREF_DLL_PIN)
2442 wm->ldr.LoadCount = -1;
2443 else
2444 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2445 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2447 else ret = STATUS_INVALID_PARAMETER;
2449 RtlLeaveCriticalSection( &loader_section );
2450 return ret;
2454 /***********************************************************************
2455 * LdrProcessRelocationBlock (NTDLL.@)
2457 * Apply relocations to a given page of a mapped PE image.
2459 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2460 USHORT *relocs, INT_PTR delta )
2462 while (count--)
2464 USHORT offset = *relocs & 0xfff;
2465 int type = *relocs >> 12;
2466 switch(type)
2468 case IMAGE_REL_BASED_ABSOLUTE:
2469 break;
2470 case IMAGE_REL_BASED_HIGH:
2471 *(short *)((char *)page + offset) += HIWORD(delta);
2472 break;
2473 case IMAGE_REL_BASED_LOW:
2474 *(short *)((char *)page + offset) += LOWORD(delta);
2475 break;
2476 case IMAGE_REL_BASED_HIGHLOW:
2477 *(int *)((char *)page + offset) += delta;
2478 break;
2479 #ifdef _WIN64
2480 case IMAGE_REL_BASED_DIR64:
2481 *(INT_PTR *)((char *)page + offset) += delta;
2482 break;
2483 #elif defined(__arm__)
2484 case IMAGE_REL_BASED_THUMB_MOV32:
2486 DWORD inst = *(INT_PTR *)((char *)page + offset);
2487 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2488 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2489 DWORD hi_delta;
2491 if ((inst & 0x8000fbf0) != 0x0000f240)
2492 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2494 imm16 += LOWORD(delta);
2495 hi_delta = HIWORD(delta) + HIWORD(imm16);
2496 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2497 ((imm16 >> 12) & 0x000f) +
2498 ((imm16 << 20) & 0x70000000) +
2499 ((imm16 << 16) & 0xff0000);
2501 if (hi_delta != 0)
2503 inst = *(INT_PTR *)((char *)page + offset + 4);
2504 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2505 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2507 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2508 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2510 imm16 += hi_delta;
2511 if (imm16 > 0xffff)
2512 ERR("resulting immediate value won't fit: %08x\n", imm16);
2513 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2514 ((imm16 >> 1) & 0x0400) +
2515 ((imm16 >> 12) & 0x000f) +
2516 ((imm16 << 20) & 0x70000000) +
2517 ((imm16 << 16) & 0xff0000);
2520 break;
2521 #endif
2522 default:
2523 FIXME("Unknown/unsupported fixup type %x.\n", type);
2524 return NULL;
2526 relocs++;
2528 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2532 /******************************************************************
2533 * LdrQueryProcessModuleInformation
2536 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2537 ULONG buf_size, ULONG* req_size)
2539 SYSTEM_MODULE* sm = &smi->Modules[0];
2540 ULONG size = sizeof(ULONG);
2541 NTSTATUS nts = STATUS_SUCCESS;
2542 ANSI_STRING str;
2543 char* ptr;
2544 PLIST_ENTRY mark, entry;
2545 PLDR_MODULE mod;
2546 WORD id = 0;
2548 smi->ModulesCount = 0;
2550 RtlEnterCriticalSection( &loader_section );
2551 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2552 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2554 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2555 size += sizeof(*sm);
2556 if (size <= buf_size)
2558 sm->Reserved1 = 0; /* FIXME */
2559 sm->Reserved2 = 0; /* FIXME */
2560 sm->ImageBaseAddress = mod->BaseAddress;
2561 sm->ImageSize = mod->SizeOfImage;
2562 sm->Flags = mod->Flags;
2563 sm->Id = id++;
2564 sm->Rank = 0; /* FIXME */
2565 sm->Unknown = 0; /* FIXME */
2566 str.Length = 0;
2567 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2568 str.Buffer = (char*)sm->Name;
2569 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2570 ptr = strrchr(str.Buffer, '\\');
2571 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2573 smi->ModulesCount++;
2574 sm++;
2576 else nts = STATUS_INFO_LENGTH_MISMATCH;
2578 RtlLeaveCriticalSection( &loader_section );
2580 if (req_size) *req_size = size;
2582 return nts;
2586 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2588 NTSTATUS status;
2589 UNICODE_STRING str;
2590 ULONG size;
2591 WCHAR buffer[64];
2592 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2594 RtlInitUnicodeString( &str, name );
2596 size = sizeof(buffer) - sizeof(WCHAR);
2597 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2598 return status;
2600 if (info->Type != REG_DWORD)
2602 buffer[size / sizeof(WCHAR)] = 0;
2603 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2605 else memcpy( value, info->Data, sizeof(*value) );
2606 return status;
2609 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2610 void *data, ULONG in_size, ULONG *out_size )
2612 NTSTATUS status;
2613 UNICODE_STRING str;
2614 ULONG size;
2615 char *buffer;
2616 KEY_VALUE_PARTIAL_INFORMATION *info;
2617 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2619 RtlInitUnicodeString( &str, name );
2621 size = info_size + in_size;
2622 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2623 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2624 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2625 if (!status || status == STATUS_BUFFER_OVERFLOW)
2627 if (out_size) *out_size = info->DataLength;
2628 if (data && !status) memcpy( data, info->Data, info->DataLength );
2630 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2631 return status;
2635 /******************************************************************
2636 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2638 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2639 void *data, ULONG in_size, ULONG *out_size )
2641 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2642 'S','o','f','t','w','a','r','e','\\',
2643 'M','i','c','r','o','s','o','f','t','\\',
2644 'W','i','n','d','o','w','s',' ','N','T','\\',
2645 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2646 'I','m','a','g','e',' ','F','i','l','e',' ',
2647 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2648 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2649 OBJECT_ATTRIBUTES attr;
2650 UNICODE_STRING name_str;
2651 HANDLE hkey;
2652 NTSTATUS status;
2653 ULONG len;
2654 WCHAR *p;
2656 attr.Length = sizeof(attr);
2657 attr.RootDirectory = 0;
2658 attr.ObjectName = &name_str;
2659 attr.Attributes = OBJ_CASE_INSENSITIVE;
2660 attr.SecurityDescriptor = NULL;
2661 attr.SecurityQualityOfService = NULL;
2663 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2664 else p = key->Buffer;
2665 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2666 name_str.Buffer = path;
2667 name_str.Length = sizeof(optionsW) + len;
2668 name_str.MaximumLength = name_str.Length;
2669 memcpy( path, optionsW, sizeof(optionsW) );
2670 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2671 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2673 if (type == REG_DWORD)
2675 if (out_size) *out_size = sizeof(ULONG);
2676 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2677 else status = STATUS_BUFFER_OVERFLOW;
2679 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2681 NtClose( hkey );
2682 return status;
2686 /******************************************************************
2687 * RtlDllShutdownInProgress (NTDLL.@)
2689 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2691 return process_detaching;
2694 /****************************************************************************
2695 * LdrResolveDelayLoadedAPI (NTDLL.@)
2697 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2698 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2699 IMAGE_THUNK_DATA* addr, ULONG flags )
2701 IMAGE_THUNK_DATA *pIAT, *pINT;
2702 DELAYLOAD_INFO delayinfo;
2703 UNICODE_STRING mod;
2704 const CHAR* name;
2705 HMODULE *phmod;
2706 NTSTATUS nts;
2707 FARPROC fp;
2708 DWORD id;
2710 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2712 phmod = get_rva(base, desc->ModuleHandleRVA);
2713 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2714 pINT = get_rva(base, desc->ImportNameTableRVA);
2715 name = get_rva(base, desc->DllNameRVA);
2716 id = addr - pIAT;
2718 if (!*phmod)
2720 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2722 nts = STATUS_NO_MEMORY;
2723 goto fail;
2725 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2726 RtlFreeUnicodeString(&mod);
2727 if (nts) goto fail;
2730 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2731 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2732 else
2734 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2735 ANSI_STRING fnc;
2737 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2738 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2740 if (!nts)
2742 pIAT[id].u1.Function = (ULONG_PTR)fp;
2743 return fp;
2746 fail:
2747 delayinfo.Size = sizeof(delayinfo);
2748 delayinfo.DelayloadDescriptor = desc;
2749 delayinfo.ThunkAddress = addr;
2750 delayinfo.TargetDllName = name;
2751 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2752 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2753 delayinfo.TargetModuleBase = *phmod;
2754 delayinfo.Unused = NULL;
2755 delayinfo.LastError = nts;
2756 return dllhook(4, &delayinfo);
2759 /******************************************************************
2760 * LdrShutdownProcess (NTDLL.@)
2763 void WINAPI LdrShutdownProcess(void)
2765 TRACE("()\n");
2766 process_detaching = TRUE;
2767 process_detach();
2771 /******************************************************************
2772 * RtlExitUserProcess (NTDLL.@)
2774 void WINAPI RtlExitUserProcess( DWORD status )
2776 RtlEnterCriticalSection( &loader_section );
2777 RtlAcquirePebLock();
2778 NtTerminateProcess( 0, status );
2779 LdrShutdownProcess();
2780 NtTerminateProcess( GetCurrentProcess(), status );
2781 exit( status );
2784 /******************************************************************
2785 * LdrShutdownThread (NTDLL.@)
2788 void WINAPI LdrShutdownThread(void)
2790 PLIST_ENTRY mark, entry;
2791 PLDR_MODULE mod;
2792 UINT i;
2793 void **pointers;
2795 TRACE("()\n");
2797 /* don't do any detach calls if process is exiting */
2798 if (process_detaching) return;
2800 RtlEnterCriticalSection( &loader_section );
2802 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2803 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2805 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2806 InInitializationOrderModuleList);
2807 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2808 continue;
2809 if ( mod->Flags & LDR_NO_DLL_CALLS )
2810 continue;
2812 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2813 DLL_THREAD_DETACH, NULL );
2816 RtlAcquirePebLock();
2817 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2818 RtlReleasePebLock();
2820 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2822 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2823 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2825 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2826 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2827 RtlLeaveCriticalSection( &loader_section );
2831 /***********************************************************************
2832 * free_modref
2835 static void free_modref( WINE_MODREF *wm )
2837 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2838 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2839 if (wm->ldr.InInitializationOrderModuleList.Flink)
2840 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2842 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2843 if (!TRACE_ON(module))
2844 TRACE_(loaddll)("Unloaded module %s : %s\n",
2845 debugstr_w(wm->ldr.FullDllName.Buffer),
2846 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2848 SERVER_START_REQ( unload_dll )
2850 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2851 wine_server_call( req );
2853 SERVER_END_REQ;
2855 free_tls_slot( &wm->ldr );
2856 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2857 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2858 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2859 if (cached_modref == wm) cached_modref = NULL;
2860 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2861 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2862 RtlFreeHeap( GetProcessHeap(), 0, wm );
2865 /***********************************************************************
2866 * MODULE_FlushModrefs
2868 * Remove all unused modrefs and call the internal unloading routines
2869 * for the library type.
2871 * The loader_section must be locked while calling this function.
2873 static void MODULE_FlushModrefs(void)
2875 PLIST_ENTRY mark, entry, prev;
2876 PLDR_MODULE mod;
2877 WINE_MODREF*wm;
2879 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2880 for (entry = mark->Blink; entry != mark; entry = prev)
2882 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2883 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2884 prev = entry->Blink;
2885 if (!mod->LoadCount) free_modref( wm );
2888 /* check load order list too for modules that haven't been initialized yet */
2889 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2890 for (entry = mark->Blink; entry != mark; entry = prev)
2892 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2893 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2894 prev = entry->Blink;
2895 if (!mod->LoadCount) free_modref( wm );
2899 /***********************************************************************
2900 * MODULE_DecRefCount
2902 * The loader_section must be locked while calling this function.
2904 static void MODULE_DecRefCount( WINE_MODREF *wm )
2906 int i;
2908 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2909 return;
2911 if ( wm->ldr.LoadCount <= 0 )
2912 return;
2914 --wm->ldr.LoadCount;
2915 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2917 if ( wm->ldr.LoadCount == 0 )
2919 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2921 for ( i = 0; i < wm->nDeps; i++ )
2922 if ( wm->deps[i] )
2923 MODULE_DecRefCount( wm->deps[i] );
2925 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2929 /******************************************************************
2930 * LdrUnloadDll (NTDLL.@)
2934 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2936 WINE_MODREF *wm;
2937 NTSTATUS retv = STATUS_SUCCESS;
2939 if (process_detaching) return retv;
2941 TRACE("(%p)\n", hModule);
2943 RtlEnterCriticalSection( &loader_section );
2945 free_lib_count++;
2946 if ((wm = get_modref( hModule )) != NULL)
2948 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2950 /* Recursively decrement reference counts */
2951 MODULE_DecRefCount( wm );
2953 /* Call process detach notifications */
2954 if ( free_lib_count <= 1 )
2956 process_detach();
2957 MODULE_FlushModrefs();
2960 TRACE("END\n");
2962 else
2963 retv = STATUS_DLL_NOT_FOUND;
2965 free_lib_count--;
2967 RtlLeaveCriticalSection( &loader_section );
2969 return retv;
2972 /***********************************************************************
2973 * RtlImageNtHeader (NTDLL.@)
2975 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2977 IMAGE_NT_HEADERS *ret;
2979 __TRY
2981 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2983 ret = NULL;
2984 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2986 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2987 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2990 __EXCEPT_PAGE_FAULT
2992 return NULL;
2994 __ENDTRY
2995 return ret;
2999 /***********************************************************************
3000 * attach_process_dlls
3002 * Initial attach to all the dlls loaded by the process.
3004 static NTSTATUS attach_process_dlls( void *wm )
3006 NTSTATUS status;
3008 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
3010 RtlEnterCriticalSection( &loader_section );
3011 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
3013 if (last_failed_modref)
3014 ERR( "%s failed to initialize, aborting\n",
3015 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
3016 return status;
3018 attach_implicitly_loaded_dlls( (LPVOID)1 );
3019 RtlLeaveCriticalSection( &loader_section );
3020 return status;
3024 /***********************************************************************
3025 * load_global_options
3027 static void load_global_options(void)
3029 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
3030 'S','y','s','t','e','m','\\',
3031 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3032 'C','o','n','t','r','o','l','\\',
3033 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3034 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3035 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};
3036 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3037 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3038 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};
3039 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};
3041 OBJECT_ATTRIBUTES attr;
3042 UNICODE_STRING name_str;
3043 HANDLE hkey;
3044 ULONG value;
3046 attr.Length = sizeof(attr);
3047 attr.RootDirectory = 0;
3048 attr.ObjectName = &name_str;
3049 attr.Attributes = OBJ_CASE_INSENSITIVE;
3050 attr.SecurityDescriptor = NULL;
3051 attr.SecurityQualityOfService = NULL;
3052 RtlInitUnicodeString( &name_str, sessionW );
3054 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3056 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3058 query_dword_option( hkey, critsectW, &value );
3059 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3061 query_dword_option( hkey, heapresW, &value );
3062 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3064 query_dword_option( hkey, heapcommitW, &value );
3065 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3067 query_dword_option( hkey, decommittotalW, &value );
3068 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3070 query_dword_option( hkey, decommitfreeW, &value );
3071 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3073 NtClose( hkey );
3077 /***********************************************************************
3078 * start_process
3080 static void start_process( void *arg )
3082 struct start_params *start_params = (struct start_params *)arg;
3083 call_thread_entry_point( start_params->kernel_start, start_params->entry );
3086 /******************************************************************
3087 * LdrInitializeThunk (NTDLL.@)
3090 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3091 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3093 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3094 NTSTATUS status;
3095 WINE_MODREF *wm;
3096 LPCWSTR load_path;
3097 PEB *peb = NtCurrentTeb()->Peb;
3098 struct start_params start_params;
3100 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
3102 /* allocate the modref for the main exe (if not already done) */
3103 wm = get_modref( peb->ImageBaseAddress );
3104 assert( wm );
3105 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3107 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3108 exit(1);
3111 peb->LoaderLock = &loader_section;
3112 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3113 if (!peb->ProcessParameters->WindowTitle.Buffer)
3114 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3115 version_init( wm->ldr.FullDllName.Buffer );
3116 virtual_set_large_address_space();
3118 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3119 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3121 /* the main exe needs to be the first in the load order list */
3122 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3123 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3124 RemoveEntryList( &wm->ldr.InMemoryOrderModuleList );
3125 InsertHeadList( &peb->LdrData->InMemoryOrderModuleList, &wm->ldr.InMemoryOrderModuleList );
3127 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
3128 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
3130 actctx_init();
3131 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3132 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
3133 heap_set_debug_flags( GetProcessHeap() );
3135 /* Store original entrypoint (in case it gets corrupted) */
3136 start_params.kernel_start = kernel_start;
3137 start_params.entry = wm->ldr.EntryPoint;
3139 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
3140 if (status != STATUS_SUCCESS) goto error;
3142 virtual_release_address_space();
3143 virtual_clear_thread_stack();
3144 wine_switch_to_stack( start_process, &start_params, NtCurrentTeb()->Tib.StackBase );
3146 error:
3147 ERR( "Main exe initialization for %s failed, status %x\n",
3148 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3149 NtTerminateProcess( GetCurrentProcess(), status );
3153 /***********************************************************************
3154 * RtlImageDirectoryEntryToData (NTDLL.@)
3156 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3158 const IMAGE_NT_HEADERS *nt;
3159 DWORD addr;
3161 if ((ULONG_PTR)module & 1) /* mapped as data file */
3163 module = (HMODULE)((ULONG_PTR)module & ~1);
3164 image = FALSE;
3166 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3167 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3169 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3171 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3172 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3173 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3174 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3176 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3178 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3180 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3181 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3182 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3183 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3185 else return NULL;
3187 /* not mapped as image, need to find the section containing the virtual address */
3188 return RtlImageRvaToVa( nt, module, addr, NULL );
3192 /***********************************************************************
3193 * RtlImageRvaToSection (NTDLL.@)
3195 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3196 HMODULE module, DWORD rva )
3198 int i;
3199 const IMAGE_SECTION_HEADER *sec;
3201 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3202 nt->FileHeader.SizeOfOptionalHeader);
3203 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3205 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3206 return (PIMAGE_SECTION_HEADER)sec;
3208 return NULL;
3212 /***********************************************************************
3213 * RtlImageRvaToVa (NTDLL.@)
3215 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3216 DWORD rva, IMAGE_SECTION_HEADER **section )
3218 IMAGE_SECTION_HEADER *sec;
3220 if (section && *section) /* try this section first */
3222 sec = *section;
3223 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3224 goto found;
3226 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3227 found:
3228 if (section) *section = sec;
3229 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3233 /***********************************************************************
3234 * RtlPcToFileHeader (NTDLL.@)
3236 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3238 LDR_MODULE *module;
3239 PVOID ret = NULL;
3241 RtlEnterCriticalSection( &loader_section );
3242 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3243 RtlLeaveCriticalSection( &loader_section );
3244 *address = ret;
3245 return ret;
3249 /***********************************************************************
3250 * NtLoadDriver (NTDLL.@)
3251 * ZwLoadDriver (NTDLL.@)
3253 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3255 FIXME("(%p), stub!\n",DriverServiceName);
3256 return STATUS_NOT_IMPLEMENTED;
3260 /***********************************************************************
3261 * NtUnloadDriver (NTDLL.@)
3262 * ZwUnloadDriver (NTDLL.@)
3264 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3266 FIXME("(%p), stub!\n",DriverServiceName);
3267 return STATUS_NOT_IMPLEMENTED;
3271 /******************************************************************
3272 * DllMain (NTDLL.@)
3274 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3276 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3277 return TRUE;
3281 /******************************************************************
3282 * __wine_init_windows_dir (NTDLL.@)
3284 * Windows and system dir initialization once kernel32 has been loaded.
3286 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3288 PLIST_ENTRY mark, entry;
3289 LPWSTR buffer, p;
3291 strcpyW( user_shared_data->NtSystemRoot, windir );
3292 DIR_init_windows_dir( windir, sysdir );
3294 /* prepend the system dir to the name of the already created modules */
3295 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3296 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3298 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3300 assert( mod->Flags & LDR_WINE_INTERNAL );
3302 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3303 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3304 if (!buffer) continue;
3305 strcpyW( buffer, system_dir.Buffer );
3306 p = buffer + strlenW( buffer );
3307 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3308 strcpyW( p, mod->FullDllName.Buffer );
3309 RtlInitUnicodeString( &mod->FullDllName, buffer );
3310 RtlInitUnicodeString( &mod->BaseDllName, p );
3315 /***********************************************************************
3316 * __wine_process_init
3318 void __wine_process_init(void)
3320 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3322 WINE_MODREF *wm;
3323 NTSTATUS status;
3324 ANSI_STRING func_name;
3325 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3327 main_exe_file = thread_init();
3329 /* retrieve current umask */
3330 FILE_umask = umask(0777);
3331 umask( FILE_umask );
3333 load_global_options();
3335 /* setup the load callback and create ntdll modref */
3336 wine_dll_set_callback( load_builtin_callback );
3338 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3340 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3341 exit(1);
3343 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3344 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3346 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3347 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3348 0, (void **)&init_func )) != STATUS_SUCCESS)
3350 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3351 exit(1);
3353 init_func();