wined3d: Add an ARB_sync implementation of event queries.
[wine.git] / dlls / ntdll / loader.c
blob7bbcf95b85aeef953dbf802827170098dc78a1e9
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 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winnt.h"
38 #include "winternl.h"
40 #include "wine/exception.h"
41 #include "wine/library.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
46 #include "ddk/wdm.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
52 WINE_DECLARE_DEBUG_CHANNEL(imports);
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
60 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
61 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
63 static const char * const reason_names[] =
65 "PROCESS_DETACH",
66 "PROCESS_ATTACH",
67 "THREAD_ATTACH",
68 "THREAD_DETACH",
69 NULL, NULL, NULL, NULL,
70 "WINE_PREATTACH"
73 static const WCHAR dllW[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
78 LDR_MODULE ldr;
79 int nDeps;
80 struct _wine_modref **deps;
81 } WINE_MODREF;
83 /* info about the current builtin dll load */
84 /* used to keep track of things across the register_dll constructor call */
85 struct builtin_load_info
87 const WCHAR *load_path;
88 const WCHAR *filename;
89 NTSTATUS status;
90 WINE_MODREF *wm;
93 static struct builtin_load_info default_load_info;
94 static struct builtin_load_info *builtin_load_info = &default_load_info;
96 static HANDLE main_exe_file;
97 static UINT tls_module_count; /* number of modules with TLS directory */
98 static UINT tls_total_size; /* total size of TLS storage */
99 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
101 static RTL_CRITICAL_SECTION loader_section;
102 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
104 0, 0, &loader_section,
105 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
106 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
108 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
110 static WINE_MODREF *cached_modref;
111 static WINE_MODREF *current_modref;
112 static WINE_MODREF *last_failed_modref;
114 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
115 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
116 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
117 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
118 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
119 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
121 /* convert PE image VirtualAddress to Real Address */
122 static inline void *get_rva( HMODULE module, DWORD va )
124 return (void *)((char *)module + va);
127 /* check whether the file name contains a path */
128 static inline int contains_path( LPCWSTR name )
130 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
133 /* convert from straight ASCII to Unicode without depending on the current codepage */
134 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
136 while (len--) *dst++ = (unsigned char)*src++;
140 /*************************************************************************
141 * call_dll_entry_point
143 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
144 * their entry point, so we need a small asm wrapper.
146 #ifdef __i386__
147 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
148 __ASM_GLOBAL_FUNC(call_dll_entry_point,
149 "pushl %ebp\n\t"
150 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
151 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
152 "movl %esp,%ebp\n\t"
153 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
154 "pushl %ebx\n\t"
155 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
156 "subl $8,%esp\n\t"
157 "pushl 20(%ebp)\n\t"
158 "pushl 16(%ebp)\n\t"
159 "pushl 12(%ebp)\n\t"
160 "movl 8(%ebp),%eax\n\t"
161 "call *%eax\n\t"
162 "leal -4(%ebp),%esp\n\t"
163 "popl %ebx\n\t"
164 __ASM_CFI(".cfi_same_value %ebx\n\t")
165 "popl %ebp\n\t"
166 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
167 __ASM_CFI(".cfi_same_value %ebp\n\t")
168 "ret" )
169 #else /* __i386__ */
170 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
171 UINT reason, void *reserved )
173 return proc( module, reason, reserved );
175 #endif /* __i386__ */
178 #if defined(__i386__) || defined(__x86_64__)
179 /*************************************************************************
180 * stub_entry_point
182 * Entry point for stub functions.
184 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
186 EXCEPTION_RECORD rec;
188 rec.ExceptionCode = EXCEPTION_WINE_STUB;
189 rec.ExceptionFlags = EH_NONCONTINUABLE;
190 rec.ExceptionRecord = NULL;
191 rec.ExceptionAddress = ret_addr;
192 rec.NumberParameters = 2;
193 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
194 rec.ExceptionInformation[1] = (ULONG_PTR)name;
195 for (;;) RtlRaiseException( &rec );
199 #include "pshpack1.h"
200 #ifdef __i386__
201 struct stub
203 BYTE pushl1; /* pushl $name */
204 const char *name;
205 BYTE pushl2; /* pushl $dll */
206 const char *dll;
207 BYTE call; /* call stub_entry_point */
208 DWORD entry;
210 #else
211 struct stub
213 BYTE movq_rdi[2]; /* movq $dll,%rdi */
214 const char *dll;
215 BYTE movq_rsi[2]; /* movq $name,%rsi */
216 const char *name;
217 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
218 BYTE movq_rax[2]; /* movq $entry, %rax */
219 const void* entry;
220 BYTE jmpq_rax[2]; /* jmp %rax */
222 #endif
223 #include "poppack.h"
225 /*************************************************************************
226 * allocate_stub
228 * Allocate a stub entry point.
230 static ULONG_PTR allocate_stub( const char *dll, const char *name )
232 #define MAX_SIZE 65536
233 static struct stub *stubs;
234 static unsigned int nb_stubs;
235 struct stub *stub;
237 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
239 if (!stubs)
241 SIZE_T size = MAX_SIZE;
242 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
243 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
244 return 0xdeadbeef;
246 stub = &stubs[nb_stubs++];
247 #ifdef __i386__
248 stub->pushl1 = 0x68; /* pushl $name */
249 stub->name = name;
250 stub->pushl2 = 0x68; /* pushl $dll */
251 stub->dll = dll;
252 stub->call = 0xe8; /* call stub_entry_point */
253 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
254 #else
255 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
256 stub->movq_rdi[1] = 0xbf;
257 stub->dll = dll;
258 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
259 stub->movq_rsi[1] = 0xbe;
260 stub->name = name;
261 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
262 stub->movq_rsp_rdx[1] = 0x8b;
263 stub->movq_rsp_rdx[2] = 0x14;
264 stub->movq_rsp_rdx[3] = 0x24;
265 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
266 stub->movq_rax[1] = 0xb8;
267 stub->entry = stub_entry_point;
268 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
269 stub->jmpq_rax[1] = 0xe0;
270 #endif
271 return (ULONG_PTR)stub;
274 #else /* __i386__ */
275 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
276 #endif /* __i386__ */
279 /*************************************************************************
280 * get_modref
282 * Looks for the referenced HMODULE in the current process
283 * The loader_section must be locked while calling this function.
285 static WINE_MODREF *get_modref( HMODULE hmod )
287 PLIST_ENTRY mark, entry;
288 PLDR_MODULE mod;
290 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
292 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
293 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
295 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
296 if (mod->BaseAddress == hmod)
297 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
298 if (mod->BaseAddress > (void*)hmod) break;
300 return NULL;
304 /**********************************************************************
305 * find_basename_module
307 * Find a module from its base name.
308 * The loader_section must be locked while calling this function
310 static WINE_MODREF *find_basename_module( LPCWSTR name )
312 PLIST_ENTRY mark, entry;
314 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
315 return cached_modref;
317 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
318 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
320 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
321 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
323 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
324 return cached_modref;
327 return NULL;
331 /**********************************************************************
332 * find_fullname_module
334 * Find a module from its full path name.
335 * The loader_section must be locked while calling this function
337 static WINE_MODREF *find_fullname_module( LPCWSTR name )
339 PLIST_ENTRY mark, entry;
341 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
342 return cached_modref;
344 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
345 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
347 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
348 if (!strcmpiW( name, mod->FullDllName.Buffer ))
350 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
351 return cached_modref;
354 return NULL;
358 /*************************************************************************
359 * find_forwarded_export
361 * Find the final function pointer for a forwarded function.
362 * The loader_section must be locked while calling this function.
364 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
366 const IMAGE_EXPORT_DIRECTORY *exports;
367 DWORD exp_size;
368 WINE_MODREF *wm;
369 WCHAR mod_name[32];
370 const char *end = strrchr(forward, '.');
371 FARPROC proc = NULL;
373 if (!end) return NULL;
374 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
375 ascii_to_unicode( mod_name, forward, end - forward );
376 mod_name[end - forward] = 0;
377 if (!strchrW( mod_name, '.' ))
379 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
380 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
383 if (!(wm = find_basename_module( mod_name )))
385 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
386 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
387 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
389 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
391 LdrUnloadDll( wm->ldr.BaseAddress );
392 wm = NULL;
396 if (!wm)
398 ERR( "module not found for forward '%s' used by %s\n",
399 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
400 return NULL;
403 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
404 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
406 const char *name = end + 1;
407 if (*name == '#') /* ordinal */
408 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
409 else
410 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
413 if (!proc)
415 ERR("function not found for forward '%s' used by %s."
416 " If you are using builtin %s, try using the native one instead.\n",
417 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
418 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
420 return proc;
424 /*************************************************************************
425 * find_ordinal_export
427 * Find an exported function by ordinal.
428 * The exports base must have been subtracted from the ordinal already.
429 * The loader_section must be locked while calling this function.
431 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
432 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
434 FARPROC proc;
435 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
437 if (ordinal >= exports->NumberOfFunctions)
439 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
440 return NULL;
442 if (!functions[ordinal]) return NULL;
444 proc = get_rva( module, functions[ordinal] );
446 /* if the address falls into the export dir, it's a forward */
447 if (((const char *)proc >= (const char *)exports) &&
448 ((const char *)proc < (const char *)exports + exp_size))
449 return find_forwarded_export( module, (const char *)proc, load_path );
451 if (TRACE_ON(snoop))
453 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
454 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
456 if (TRACE_ON(relay))
458 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
459 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
461 return proc;
465 /*************************************************************************
466 * find_named_export
468 * Find an exported function by name.
469 * The loader_section must be locked while calling this function.
471 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
472 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
474 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
475 const DWORD *names = get_rva( module, exports->AddressOfNames );
476 int min = 0, max = exports->NumberOfNames - 1;
478 /* first check the hint */
479 if (hint >= 0 && hint <= max)
481 char *ename = get_rva( module, names[hint] );
482 if (!strcmp( ename, name ))
483 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
486 /* then do a binary search */
487 while (min <= max)
489 int res, pos = (min + max) / 2;
490 char *ename = get_rva( module, names[pos] );
491 if (!(res = strcmp( ename, name )))
492 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
493 if (res > 0) max = pos - 1;
494 else min = pos + 1;
496 return NULL;
501 /*************************************************************************
502 * import_dll
504 * Import the dll specified by the given import descriptor.
505 * The loader_section must be locked while calling this function.
507 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
509 NTSTATUS status;
510 WINE_MODREF *wmImp;
511 HMODULE imp_mod;
512 const IMAGE_EXPORT_DIRECTORY *exports;
513 DWORD exp_size;
514 const IMAGE_THUNK_DATA *import_list;
515 IMAGE_THUNK_DATA *thunk_list;
516 WCHAR buffer[32];
517 const char *name = get_rva( module, descr->Name );
518 DWORD len = strlen(name);
519 PVOID protect_base;
520 SIZE_T protect_size = 0;
521 DWORD protect_old;
523 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
524 if (descr->u.OriginalFirstThunk)
525 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
526 else
527 import_list = thunk_list;
529 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
531 if (len * sizeof(WCHAR) < sizeof(buffer))
533 ascii_to_unicode( buffer, name, len );
534 buffer[len] = 0;
535 status = load_dll( load_path, buffer, 0, &wmImp );
537 else /* need to allocate a larger buffer */
539 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
540 if (!ptr) return NULL;
541 ascii_to_unicode( ptr, name, len );
542 ptr[len] = 0;
543 status = load_dll( load_path, ptr, 0, &wmImp );
544 RtlFreeHeap( GetProcessHeap(), 0, ptr );
547 if (status)
549 if (status == STATUS_DLL_NOT_FOUND)
550 ERR("Library %s (which is needed by %s) not found\n",
551 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
552 else
553 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
554 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
555 return NULL;
558 /* unprotect the import address table since it can be located in
559 * readonly section */
560 while (import_list[protect_size].u1.Ordinal) protect_size++;
561 protect_base = thunk_list;
562 protect_size *= sizeof(*thunk_list);
563 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
564 &protect_size, PAGE_WRITECOPY, &protect_old );
566 imp_mod = wmImp->ldr.BaseAddress;
567 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
569 if (!exports)
571 /* set all imported function to deadbeef */
572 while (import_list->u1.Ordinal)
574 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
576 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
577 WARN("No implementation for %s.%d", name, ordinal );
578 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
580 else
582 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
583 WARN("No implementation for %s.%s", name, pe_name->Name );
584 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
586 WARN(" imported from %s, allocating stub %p\n",
587 debugstr_w(current_modref->ldr.FullDllName.Buffer),
588 (void *)thunk_list->u1.Function );
589 import_list++;
590 thunk_list++;
592 goto done;
595 while (import_list->u1.Ordinal)
597 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
599 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
601 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
602 ordinal - exports->Base, load_path );
603 if (!thunk_list->u1.Function)
605 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
606 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
607 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
608 (void *)thunk_list->u1.Function );
610 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
612 else /* import by name */
614 IMAGE_IMPORT_BY_NAME *pe_name;
615 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
616 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
617 (const char*)pe_name->Name,
618 pe_name->Hint, load_path );
619 if (!thunk_list->u1.Function)
621 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
622 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
623 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
624 (void *)thunk_list->u1.Function );
626 TRACE_(imports)("--- %s %s.%d = %p\n",
627 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
629 import_list++;
630 thunk_list++;
633 done:
634 /* restore old protection of the import address table */
635 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
636 return wmImp;
640 /***********************************************************************
641 * create_module_activation_context
643 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
645 NTSTATUS status;
646 LDR_RESOURCE_INFO info;
647 const IMAGE_RESOURCE_DATA_ENTRY *entry;
649 info.Type = RT_MANIFEST;
650 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
651 info.Language = 0;
652 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
654 ACTCTXW ctx;
655 ctx.cbSize = sizeof(ctx);
656 ctx.lpSource = NULL;
657 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
658 ctx.hModule = module->BaseAddress;
659 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
660 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
662 return status;
666 /****************************************************************
667 * fixup_imports
669 * Fixup all imports of a given module.
670 * The loader_section must be locked while calling this function.
672 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
674 int i, nb_imports;
675 const IMAGE_IMPORT_DESCRIPTOR *imports;
676 WINE_MODREF *prev;
677 DWORD size;
678 NTSTATUS status;
679 ULONG_PTR cookie;
681 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
682 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
684 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
685 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
686 return STATUS_SUCCESS;
688 nb_imports = 0;
689 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
691 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
693 if (!create_module_activation_context( &wm->ldr ))
694 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
696 /* Allocate module dependency list */
697 wm->nDeps = nb_imports;
698 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
700 /* load the imported modules. They are automatically
701 * added to the modref list of the process.
703 prev = current_modref;
704 current_modref = wm;
705 status = STATUS_SUCCESS;
706 for (i = 0; i < nb_imports; i++)
708 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
709 status = STATUS_DLL_NOT_FOUND;
711 current_modref = prev;
712 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
713 return status;
717 /*************************************************************************
718 * is_dll_native_subsystem
720 * Check if dll is a proper native driver.
721 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
722 * while being perfectly normal DLLs. This heuristic should catch such breakages.
724 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
726 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
727 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
728 const IMAGE_IMPORT_DESCRIPTOR *imports;
729 DWORD i, size;
730 WCHAR buffer[16];
732 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
733 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
735 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
736 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
738 for (i = 0; imports[i].Name; i++)
740 const char *name = get_rva( module, imports[i].Name );
741 DWORD len = strlen(name);
742 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
743 ascii_to_unicode( buffer, name, len + 1 );
744 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
746 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
747 return FALSE;
751 return TRUE;
755 /*************************************************************************
756 * alloc_module
758 * Allocate a WINE_MODREF structure and add it to the process list
759 * The loader_section must be locked while calling this function.
761 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
763 WINE_MODREF *wm;
764 const WCHAR *p;
765 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
766 PLIST_ENTRY entry, mark;
768 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
770 wm->nDeps = 0;
771 wm->deps = NULL;
773 wm->ldr.BaseAddress = hModule;
774 wm->ldr.EntryPoint = NULL;
775 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
776 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
777 wm->ldr.LoadCount = 1;
778 wm->ldr.TlsIndex = -1;
779 wm->ldr.SectionHandle = NULL;
780 wm->ldr.CheckSum = 0;
781 wm->ldr.TimeDateStamp = 0;
782 wm->ldr.ActivationContext = 0;
784 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
785 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
786 else p = wm->ldr.FullDllName.Buffer;
787 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
789 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
791 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
792 if (nt->OptionalHeader.AddressOfEntryPoint)
793 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
796 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
797 &wm->ldr.InLoadOrderModuleList);
799 /* insert module in MemoryList, sorted in increasing base addresses */
800 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
801 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
803 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
804 break;
806 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
807 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
808 wm->ldr.InMemoryOrderModuleList.Flink = entry;
809 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
811 /* wait until init is called for inserting into this list */
812 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
813 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
815 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
817 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
818 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
819 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
821 return wm;
825 /*************************************************************************
826 * alloc_process_tls
828 * Allocate the process-wide structure for module TLS storage.
830 static NTSTATUS alloc_process_tls(void)
832 PLIST_ENTRY mark, entry;
833 PLDR_MODULE mod;
834 const IMAGE_TLS_DIRECTORY *dir;
835 ULONG size, i;
837 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
838 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
840 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
841 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
842 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
843 continue;
844 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
845 if (!size && !dir->AddressOfCallBacks) continue;
846 tls_total_size += size;
847 tls_module_count++;
849 if (!tls_module_count) return STATUS_SUCCESS;
851 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
853 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
854 if (!tls_dirs) return STATUS_NO_MEMORY;
856 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
858 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
859 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
860 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
861 continue;
862 tls_dirs[i] = dir;
863 *(DWORD *)dir->AddressOfIndex = i;
864 mod->TlsIndex = i;
865 mod->LoadCount = -1; /* can't unload it */
866 i++;
868 return STATUS_SUCCESS;
872 /*************************************************************************
873 * alloc_thread_tls
875 * Allocate the per-thread structure for module TLS storage.
877 static NTSTATUS alloc_thread_tls(void)
879 void **pointers;
880 char *data;
881 UINT i;
883 if (!tls_module_count) return STATUS_SUCCESS;
885 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
886 tls_module_count * sizeof(*pointers) )))
887 return STATUS_NO_MEMORY;
889 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
891 RtlFreeHeap( GetProcessHeap(), 0, pointers );
892 return STATUS_NO_MEMORY;
895 for (i = 0; i < tls_module_count; i++)
897 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
898 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
900 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
901 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
902 (void *)dir->StartAddressOfRawData, data );
904 pointers[i] = data;
905 memcpy( data, (void *)dir->StartAddressOfRawData, size );
906 data += size;
907 memset( data, 0, dir->SizeOfZeroFill );
908 data += dir->SizeOfZeroFill;
910 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
911 return STATUS_SUCCESS;
915 /*************************************************************************
916 * call_tls_callbacks
918 static void call_tls_callbacks( HMODULE module, UINT reason )
920 const IMAGE_TLS_DIRECTORY *dir;
921 const PIMAGE_TLS_CALLBACK *callback;
922 ULONG dirsize;
924 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
925 if (!dir || !dir->AddressOfCallBacks) return;
927 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
929 if (TRACE_ON(relay))
930 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
931 GetCurrentThreadId(), *callback, module, reason_names[reason] );
932 __TRY
934 (*callback)( module, reason, NULL );
936 __EXCEPT_ALL
938 if (TRACE_ON(relay))
939 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
940 GetCurrentThreadId(), callback, module, reason_names[reason] );
941 return;
943 __ENDTRY
944 if (TRACE_ON(relay))
945 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
946 GetCurrentThreadId(), *callback, module, reason_names[reason] );
951 /*************************************************************************
952 * MODULE_InitDLL
954 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
956 WCHAR mod_name[32];
957 NTSTATUS status = STATUS_SUCCESS;
958 DLLENTRYPROC entry = wm->ldr.EntryPoint;
959 void *module = wm->ldr.BaseAddress;
960 BOOL retv = TRUE;
962 /* Skip calls for modules loaded with special load flags */
964 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
965 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
966 if (!entry) return STATUS_SUCCESS;
968 if (TRACE_ON(relay))
970 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
971 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
972 mod_name[len / sizeof(WCHAR)] = 0;
973 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
974 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
975 reason_names[reason], lpReserved );
977 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
978 reason_names[reason], lpReserved );
980 __TRY
982 retv = call_dll_entry_point( entry, module, reason, lpReserved );
983 if (!retv)
984 status = STATUS_DLL_INIT_FAILED;
986 __EXCEPT_ALL
988 if (TRACE_ON(relay))
989 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
990 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
991 status = GetExceptionCode();
993 __ENDTRY
995 /* The state of the module list may have changed due to the call
996 to the dll. We cannot assume that this module has not been
997 deleted. */
998 if (TRACE_ON(relay))
999 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1000 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1001 reason_names[reason], lpReserved, retv );
1002 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1004 return status;
1008 /*************************************************************************
1009 * process_attach
1011 * Send the process attach notification to all DLLs the given module
1012 * depends on (recursively). This is somewhat complicated due to the fact that
1014 * - we have to respect the module dependencies, i.e. modules implicitly
1015 * referenced by another module have to be initialized before the module
1016 * itself can be initialized
1018 * - the initialization routine of a DLL can itself call LoadLibrary,
1019 * thereby introducing a whole new set of dependencies (even involving
1020 * the 'old' modules) at any time during the whole process
1022 * (Note that this routine can be recursively entered not only directly
1023 * from itself, but also via LoadLibrary from one of the called initialization
1024 * routines.)
1026 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1027 * the process *detach* notifications to be sent in the correct order.
1028 * This must not only take into account module dependencies, but also
1029 * 'hidden' dependencies created by modules calling LoadLibrary in their
1030 * attach notification routine.
1032 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1033 * list after the attach notification has returned. This implies that the
1034 * detach notifications are called in the reverse of the sequence the attach
1035 * notifications *returned*.
1037 * The loader_section must be locked while calling this function.
1039 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1041 NTSTATUS status = STATUS_SUCCESS;
1042 ULONG_PTR cookie;
1043 int i;
1045 if (process_detaching) return status;
1047 /* prevent infinite recursion in case of cyclical dependencies */
1048 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1049 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1050 return status;
1052 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1054 /* Tag current MODREF to prevent recursive loop */
1055 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1056 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1057 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1059 /* Recursively attach all DLLs this one depends on */
1060 for ( i = 0; i < wm->nDeps; i++ )
1062 if (!wm->deps[i]) continue;
1063 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1066 /* Call DLL entry point */
1067 if (status == STATUS_SUCCESS)
1069 WINE_MODREF *prev = current_modref;
1070 current_modref = wm;
1071 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1072 if (status == STATUS_SUCCESS)
1073 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1074 else
1076 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1077 /* point to the name so LdrInitializeThunk can print it */
1078 last_failed_modref = wm;
1079 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1081 current_modref = prev;
1084 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1085 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1086 &wm->ldr.InInitializationOrderModuleList);
1088 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1089 /* Remove recursion flag */
1090 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1092 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1093 return status;
1097 /**********************************************************************
1098 * attach_implicitly_loaded_dlls
1100 * Attach to the (builtin) dlls that have been implicitly loaded because
1101 * of a dependency at the Unix level, but not imported at the Win32 level.
1103 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1105 for (;;)
1107 PLIST_ENTRY mark, entry;
1109 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1110 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1112 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1114 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1115 TRACE( "found implicitly loaded %s, attaching to it\n",
1116 debugstr_w(mod->BaseDllName.Buffer));
1117 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1118 break; /* restart the search from the start */
1120 if (entry == mark) break; /* nothing found */
1125 /*************************************************************************
1126 * process_detach
1128 * Send DLL process detach notifications. See the comment about calling
1129 * sequence at process_attach. Unless the bForceDetach flag
1130 * is set, only DLLs with zero refcount are notified.
1132 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1134 PLIST_ENTRY mark, entry;
1135 PLDR_MODULE mod;
1137 RtlEnterCriticalSection( &loader_section );
1138 if (bForceDetach) process_detaching = 1;
1139 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1142 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1144 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1145 InInitializationOrderModuleList);
1146 /* Check whether to detach this DLL */
1147 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1148 continue;
1149 if ( mod->LoadCount && !bForceDetach )
1150 continue;
1152 /* Call detach notification */
1153 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1154 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1155 DLL_PROCESS_DETACH, lpReserved );
1157 /* Restart at head of WINE_MODREF list, as entries might have
1158 been added and/or removed while performing the call ... */
1159 break;
1161 } while (entry != mark);
1163 RtlLeaveCriticalSection( &loader_section );
1166 /*************************************************************************
1167 * MODULE_DllThreadAttach
1169 * Send DLL thread attach notifications. These are sent in the
1170 * reverse sequence of process detach notification.
1173 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1175 PLIST_ENTRY mark, entry;
1176 PLDR_MODULE mod;
1177 NTSTATUS status;
1179 /* don't do any attach calls if process is exiting */
1180 if (process_detaching) return STATUS_SUCCESS;
1181 /* FIXME: there is still a race here */
1183 RtlEnterCriticalSection( &loader_section );
1185 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1187 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1188 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1190 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1191 InInitializationOrderModuleList);
1192 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1193 continue;
1194 if ( mod->Flags & LDR_NO_DLL_CALLS )
1195 continue;
1197 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1198 DLL_THREAD_ATTACH, lpReserved );
1201 done:
1202 RtlLeaveCriticalSection( &loader_section );
1203 return status;
1206 /******************************************************************
1207 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1210 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1212 WINE_MODREF *wm;
1213 NTSTATUS ret = STATUS_SUCCESS;
1215 RtlEnterCriticalSection( &loader_section );
1217 wm = get_modref( hModule );
1218 if (!wm || wm->ldr.TlsIndex != -1)
1219 ret = STATUS_DLL_NOT_FOUND;
1220 else
1221 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1223 RtlLeaveCriticalSection( &loader_section );
1225 return ret;
1228 /******************************************************************
1229 * LdrFindEntryForAddress (NTDLL.@)
1231 * The loader_section must be locked while calling this function
1233 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1235 PLIST_ENTRY mark, entry;
1236 PLDR_MODULE mod;
1238 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1239 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1241 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1242 if (mod->BaseAddress <= addr &&
1243 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1245 *pmod = mod;
1246 return STATUS_SUCCESS;
1248 if (mod->BaseAddress > addr) break;
1250 return STATUS_NO_MORE_ENTRIES;
1253 /******************************************************************
1254 * LdrLockLoaderLock (NTDLL.@)
1256 * Note: flags are not implemented.
1257 * Flag 0x01 is used to raise exceptions on errors.
1258 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1260 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1262 if (flags) FIXME( "flags %x not supported\n", flags );
1264 if (result) *result = 1;
1265 if (!magic) return STATUS_INVALID_PARAMETER_3;
1266 RtlEnterCriticalSection( &loader_section );
1267 *magic = GetCurrentThreadId();
1268 return STATUS_SUCCESS;
1272 /******************************************************************
1273 * LdrUnlockLoaderUnlock (NTDLL.@)
1275 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1277 if (magic)
1279 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1280 RtlLeaveCriticalSection( &loader_section );
1282 return STATUS_SUCCESS;
1286 /******************************************************************
1287 * LdrGetProcedureAddress (NTDLL.@)
1289 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1290 ULONG ord, PVOID *address)
1292 IMAGE_EXPORT_DIRECTORY *exports;
1293 DWORD exp_size;
1294 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1296 RtlEnterCriticalSection( &loader_section );
1298 /* check if the module itself is invalid to return the proper error */
1299 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1300 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1301 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1303 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1304 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1305 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1306 if (proc)
1308 *address = proc;
1309 ret = STATUS_SUCCESS;
1313 RtlLeaveCriticalSection( &loader_section );
1314 return ret;
1318 /***********************************************************************
1319 * is_fake_dll
1321 * Check if a loaded native dll is a Wine fake dll.
1323 static BOOL is_fake_dll( HANDLE handle )
1325 static const char fakedll_signature[] = "Wine placeholder DLL";
1326 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1327 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1328 IO_STATUS_BLOCK io;
1329 LARGE_INTEGER offset;
1331 offset.QuadPart = 0;
1332 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1333 if (io.Information < sizeof(buffer)) return FALSE;
1334 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1335 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1336 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1337 return FALSE;
1341 /***********************************************************************
1342 * get_builtin_fullname
1344 * Build the full pathname for a builtin dll.
1346 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1348 static const WCHAR soW[] = {'.','s','o',0};
1349 WCHAR *p, *fullname;
1350 size_t i, len = strlen(filename);
1352 /* check if path can correspond to the dll we have */
1353 if (path && (p = strrchrW( path, '\\' )))
1355 p++;
1356 for (i = 0; i < len; i++)
1357 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1358 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1360 /* the filename matches, use path as the full path */
1361 len += p - path;
1362 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1364 memcpy( fullname, path, len * sizeof(WCHAR) );
1365 fullname[len] = 0;
1367 return fullname;
1371 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1372 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1374 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1375 p = fullname + system_dir.Length / sizeof(WCHAR);
1376 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1377 ascii_to_unicode( p, filename, len + 1 );
1379 return fullname;
1383 /***********************************************************************
1384 * load_builtin_callback
1386 * Load a library in memory; callback function for wine_dll_register
1388 static void load_builtin_callback( void *module, const char *filename )
1390 static const WCHAR emptyW[1];
1391 IMAGE_NT_HEADERS *nt;
1392 WINE_MODREF *wm;
1393 WCHAR *fullname;
1394 const WCHAR *load_path;
1396 if (!module)
1398 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1399 return;
1401 if (!(nt = RtlImageNtHeader( module )))
1403 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1404 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1405 return;
1407 virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1408 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1409 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1411 /* create the MODREF */
1413 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1415 ERR( "can't load %s\n", filename );
1416 builtin_load_info->status = STATUS_NO_MEMORY;
1417 return;
1420 wm = alloc_module( module, fullname );
1421 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1422 if (!wm)
1424 ERR( "can't load %s\n", filename );
1425 builtin_load_info->status = STATUS_NO_MEMORY;
1426 return;
1428 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1430 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1431 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1433 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1435 else
1437 /* fixup imports */
1439 load_path = builtin_load_info->load_path;
1440 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1441 if (!load_path) load_path = emptyW;
1442 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1444 /* the module has only be inserted in the load & memory order lists */
1445 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1446 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1447 /* FIXME: free the modref */
1448 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1449 return;
1453 builtin_load_info->wm = wm;
1454 TRACE( "loaded %s %p %p\n", filename, wm, module );
1456 /* send the DLL load event */
1458 SERVER_START_REQ( load_dll )
1460 req->handle = 0;
1461 req->base = wine_server_client_ptr( module );
1462 req->size = nt->OptionalHeader.SizeOfImage;
1463 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1464 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1465 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1466 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1467 wine_server_call( req );
1469 SERVER_END_REQ;
1471 /* setup relay debugging entry points */
1472 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1476 /******************************************************************************
1477 * load_native_dll (internal)
1479 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1480 DWORD flags, WINE_MODREF** pwm )
1482 void *module;
1483 HANDLE mapping;
1484 LARGE_INTEGER size;
1485 IMAGE_NT_HEADERS *nt;
1486 SIZE_T len = 0;
1487 WINE_MODREF *wm;
1488 NTSTATUS status;
1490 TRACE("Trying native dll %s\n", debugstr_w(name));
1492 size.QuadPart = 0;
1493 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1494 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1495 if (status != STATUS_SUCCESS) return status;
1497 module = NULL;
1498 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1499 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1500 NtClose( mapping );
1501 if (status != STATUS_SUCCESS) return status;
1503 /* create the MODREF */
1505 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1507 /* fixup imports */
1509 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1511 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1513 /* the module has only be inserted in the load & memory order lists */
1514 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1515 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1517 /* FIXME: there are several more dangling references
1518 * left. Including dlls loaded by this dll before the
1519 * failed one. Unrolling is rather difficult with the
1520 * current structure and we can leave them lying
1521 * around with no problems, so we don't care.
1522 * As these might reference our wm, we don't free it.
1524 return status;
1528 /* send DLL load event */
1530 nt = RtlImageNtHeader( module );
1532 SERVER_START_REQ( load_dll )
1534 req->handle = wine_server_obj_handle( file );
1535 req->base = wine_server_client_ptr( module );
1536 req->size = nt->OptionalHeader.SizeOfImage;
1537 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1538 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1539 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1540 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1541 wine_server_call( req );
1543 SERVER_END_REQ;
1545 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1547 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1549 wm->ldr.LoadCount = 1;
1550 *pwm = wm;
1551 return STATUS_SUCCESS;
1555 /***********************************************************************
1556 * load_builtin_dll
1558 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1559 DWORD flags, WINE_MODREF** pwm )
1561 char error[256], dllname[MAX_PATH];
1562 const WCHAR *name, *p;
1563 DWORD len, i;
1564 void *handle = NULL;
1565 struct builtin_load_info info, *prev_info;
1567 /* Fix the name in case we have a full path and extension */
1568 name = path;
1569 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1570 if ((p = strrchrW( name, '/' ))) name = p + 1;
1572 /* load_library will modify info.status. Note also that load_library can be
1573 * called several times, if the .so file we're loading has dependencies.
1574 * info.status will gather all the errors we may get while loading all these
1575 * libraries
1577 info.load_path = load_path;
1578 info.filename = NULL;
1579 info.status = STATUS_SUCCESS;
1580 info.wm = NULL;
1582 if (file) /* we have a real file, try to load it */
1584 UNICODE_STRING nt_name;
1585 ANSI_STRING unix_name;
1587 TRACE("Trying built-in %s\n", debugstr_w(path));
1589 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1590 return STATUS_DLL_NOT_FOUND;
1592 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1594 RtlFreeUnicodeString( &nt_name );
1595 return STATUS_DLL_NOT_FOUND;
1597 prev_info = builtin_load_info;
1598 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1599 builtin_load_info = &info;
1600 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1601 builtin_load_info = prev_info;
1602 RtlFreeUnicodeString( &nt_name );
1603 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1604 if (!handle)
1606 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1607 return STATUS_INVALID_IMAGE_FORMAT;
1610 else
1612 int file_exists;
1614 TRACE("Trying built-in %s\n", debugstr_w(name));
1616 /* we don't want to depend on the current codepage here */
1617 len = strlenW( name ) + 1;
1618 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1619 for (i = 0; i < len; i++)
1621 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1622 dllname[i] = (char)name[i];
1623 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1626 prev_info = builtin_load_info;
1627 builtin_load_info = &info;
1628 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1629 builtin_load_info = prev_info;
1630 if (!handle)
1632 if (!file_exists)
1634 /* The file does not exist -> WARN() */
1635 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1636 return STATUS_DLL_NOT_FOUND;
1638 /* ERR() for all other errors (missing functions, ...) */
1639 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1640 return STATUS_PROCEDURE_NOT_FOUND;
1644 if (info.status != STATUS_SUCCESS)
1646 wine_dll_unload( handle );
1647 return info.status;
1650 if (!info.wm)
1652 PLIST_ENTRY mark, entry;
1654 /* The constructor wasn't called, this means the .so is already
1655 * loaded under a different name. Try to find the wm for it. */
1657 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1658 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1660 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1661 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1663 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1664 TRACE( "Found %s at %p for builtin %s\n",
1665 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1666 break;
1669 wine_dll_unload( handle ); /* release the libdl refcount */
1670 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1671 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1673 else
1675 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1676 info.wm->ldr.LoadCount = 1;
1677 info.wm->ldr.SectionHandle = handle;
1680 *pwm = info.wm;
1681 return STATUS_SUCCESS;
1685 /***********************************************************************
1686 * find_actctx_dll
1688 * Find the full path (if any) of the dll from the activation context.
1690 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1692 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1693 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1695 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1696 ACTCTX_SECTION_KEYED_DATA data;
1697 UNICODE_STRING nameW;
1698 NTSTATUS status;
1699 SIZE_T needed, size = 1024;
1700 WCHAR *p;
1702 RtlInitUnicodeString( &nameW, libname );
1703 data.cbSize = sizeof(data);
1704 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1705 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1706 &nameW, &data );
1707 if (status != STATUS_SUCCESS) return status;
1709 for (;;)
1711 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1713 status = STATUS_NO_MEMORY;
1714 goto done;
1716 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1717 AssemblyDetailedInformationInActivationContext,
1718 info, size, &needed );
1719 if (status == STATUS_SUCCESS) break;
1720 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1721 RtlFreeHeap( GetProcessHeap(), 0, info );
1722 size = needed;
1723 /* restart with larger buffer */
1726 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1728 status = STATUS_SXS_KEY_NOT_FOUND;
1729 goto done;
1732 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1734 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1736 p++;
1737 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1739 /* manifest name does not match directory name, so it's not a global
1740 * windows/winsxs manifest; use the manifest directory name instead */
1741 dirlen = p - info->lpAssemblyManifestPath;
1742 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1743 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1745 status = STATUS_NO_MEMORY;
1746 goto done;
1748 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1749 p += dirlen;
1750 strcpyW( p, libname );
1751 goto done;
1755 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1756 nameW.Length + 2*sizeof(WCHAR));
1758 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1760 status = STATUS_NO_MEMORY;
1761 goto done;
1763 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1764 p += windows_dir.Length / sizeof(WCHAR);
1765 memcpy( p, winsxsW, sizeof(winsxsW) );
1766 p += sizeof(winsxsW) / sizeof(WCHAR);
1767 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1768 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1769 *p++ = '\\';
1770 strcpyW( p, libname );
1771 done:
1772 RtlFreeHeap( GetProcessHeap(), 0, info );
1773 RtlReleaseActivationContext( data.hActCtx );
1774 return status;
1778 /***********************************************************************
1779 * find_dll_file
1781 * Find the file (or already loaded module) for a given dll name.
1783 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1784 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1786 OBJECT_ATTRIBUTES attr;
1787 IO_STATUS_BLOCK io;
1788 UNICODE_STRING nt_name;
1789 WCHAR *file_part, *ext, *dllname;
1790 ULONG len;
1792 /* first append .dll if needed */
1794 dllname = NULL;
1795 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1797 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1798 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1799 return STATUS_NO_MEMORY;
1800 strcpyW( dllname, libname );
1801 strcatW( dllname, dllW );
1802 libname = dllname;
1805 nt_name.Buffer = NULL;
1807 if (!contains_path( libname ))
1809 NTSTATUS status;
1810 WCHAR *fullname = NULL;
1812 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1814 status = find_actctx_dll( libname, &fullname );
1815 if (status == STATUS_SUCCESS)
1817 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1818 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1819 libname = dllname = fullname;
1821 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1823 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1824 return status;
1828 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1830 /* we need to search for it */
1831 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1832 if (len)
1834 if (len >= *size) goto overflow;
1835 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1837 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1839 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1840 return STATUS_NO_MEMORY;
1842 attr.Length = sizeof(attr);
1843 attr.RootDirectory = 0;
1844 attr.Attributes = OBJ_CASE_INSENSITIVE;
1845 attr.ObjectName = &nt_name;
1846 attr.SecurityDescriptor = NULL;
1847 attr.SecurityQualityOfService = NULL;
1848 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1849 goto found;
1852 /* not found */
1854 if (!contains_path( libname ))
1856 /* if libname doesn't contain a path at all, we simply return the name as is,
1857 * to be loaded as builtin */
1858 len = strlenW(libname) * sizeof(WCHAR);
1859 if (len >= *size) goto overflow;
1860 strcpyW( filename, libname );
1861 goto found;
1865 /* absolute path name, or relative path name but not found above */
1867 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1869 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1870 return STATUS_NO_MEMORY;
1872 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1873 if (len >= *size) goto overflow;
1874 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1875 if (!(*pwm = find_fullname_module( filename )) && handle)
1877 attr.Length = sizeof(attr);
1878 attr.RootDirectory = 0;
1879 attr.Attributes = OBJ_CASE_INSENSITIVE;
1880 attr.ObjectName = &nt_name;
1881 attr.SecurityDescriptor = NULL;
1882 attr.SecurityQualityOfService = NULL;
1883 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1885 found:
1886 RtlFreeUnicodeString( &nt_name );
1887 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1888 return STATUS_SUCCESS;
1890 overflow:
1891 RtlFreeUnicodeString( &nt_name );
1892 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1893 *size = len + sizeof(WCHAR);
1894 return STATUS_BUFFER_TOO_SMALL;
1898 /***********************************************************************
1899 * load_dll (internal)
1901 * Load a PE style module according to the load order.
1902 * The loader_section must be locked while calling this function.
1904 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1906 enum loadorder loadorder;
1907 WCHAR buffer[32];
1908 WCHAR *filename;
1909 ULONG size;
1910 WINE_MODREF *main_exe;
1911 HANDLE handle = 0;
1912 NTSTATUS nts;
1914 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1916 *pwm = NULL;
1917 filename = buffer;
1918 size = sizeof(buffer);
1919 for (;;)
1921 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1922 if (nts == STATUS_SUCCESS) break;
1923 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1924 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1925 /* grow the buffer and retry */
1926 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1929 if (*pwm) /* found already loaded module */
1931 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1933 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1935 TRACE("Found %s for %s at %p, count=%d\n",
1936 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1937 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1938 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1939 return STATUS_SUCCESS;
1942 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1943 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1945 if (handle && is_fake_dll( handle ))
1947 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1948 NtClose( handle );
1949 handle = 0;
1952 switch(loadorder)
1954 case LO_INVALID:
1955 nts = STATUS_NO_MEMORY;
1956 break;
1957 case LO_DISABLED:
1958 nts = STATUS_DLL_NOT_FOUND;
1959 break;
1960 case LO_NATIVE:
1961 case LO_NATIVE_BUILTIN:
1962 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1963 else
1965 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1966 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1967 /* not in PE format, maybe it's a builtin */
1968 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1970 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1971 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1972 break;
1973 case LO_BUILTIN:
1974 case LO_BUILTIN_NATIVE:
1975 case LO_DEFAULT: /* default is builtin,native */
1976 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1977 if (!handle) break; /* nothing else we can try */
1978 /* file is not a builtin library, try without using the specified file */
1979 if (nts != STATUS_SUCCESS)
1980 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1981 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1982 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1984 /* stub-only dll, try native */
1985 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1986 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1987 nts = STATUS_DLL_NOT_FOUND;
1989 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1990 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1991 break;
1994 if (nts == STATUS_SUCCESS)
1996 /* Initialize DLL just loaded */
1997 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1998 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1999 (*pwm)->ldr.BaseAddress);
2000 if (handle) NtClose( handle );
2001 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2002 return nts;
2005 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2006 if (handle) NtClose( handle );
2007 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2008 return nts;
2011 /******************************************************************
2012 * LdrLoadDll (NTDLL.@)
2014 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2015 const UNICODE_STRING *libname, HMODULE* hModule)
2017 WINE_MODREF *wm;
2018 NTSTATUS nts;
2020 RtlEnterCriticalSection( &loader_section );
2022 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2023 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2025 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2027 nts = process_attach( wm, NULL );
2028 if (nts != STATUS_SUCCESS)
2030 LdrUnloadDll(wm->ldr.BaseAddress);
2031 wm = NULL;
2034 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2036 RtlLeaveCriticalSection( &loader_section );
2037 return nts;
2041 /******************************************************************
2042 * LdrGetDllHandle (NTDLL.@)
2044 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2046 NTSTATUS status;
2047 WCHAR buffer[128];
2048 WCHAR *filename;
2049 ULONG size;
2050 WINE_MODREF *wm;
2052 RtlEnterCriticalSection( &loader_section );
2054 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2056 filename = buffer;
2057 size = sizeof(buffer);
2058 for (;;)
2060 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2061 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2062 if (status != STATUS_BUFFER_TOO_SMALL) break;
2063 /* grow the buffer and retry */
2064 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2066 status = STATUS_NO_MEMORY;
2067 break;
2071 if (status == STATUS_SUCCESS)
2073 if (wm) *base = wm->ldr.BaseAddress;
2074 else status = STATUS_DLL_NOT_FOUND;
2077 RtlLeaveCriticalSection( &loader_section );
2078 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2079 return status;
2083 /******************************************************************
2084 * LdrAddRefDll (NTDLL.@)
2086 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2088 NTSTATUS ret = STATUS_SUCCESS;
2089 WINE_MODREF *wm;
2091 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2093 RtlEnterCriticalSection( &loader_section );
2095 if ((wm = get_modref( module )))
2097 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2098 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2100 else ret = STATUS_INVALID_PARAMETER;
2102 RtlLeaveCriticalSection( &loader_section );
2103 return ret;
2107 /***********************************************************************
2108 * LdrProcessRelocationBlock (NTDLL.@)
2110 * Apply relocations to a given page of a mapped PE image.
2112 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2113 USHORT *relocs, INT_PTR delta )
2115 while (count--)
2117 USHORT offset = *relocs & 0xfff;
2118 int type = *relocs >> 12;
2119 switch(type)
2121 case IMAGE_REL_BASED_ABSOLUTE:
2122 break;
2123 #ifdef __i386__
2124 case IMAGE_REL_BASED_HIGH:
2125 *(short *)((char *)page + offset) += HIWORD(delta);
2126 break;
2127 case IMAGE_REL_BASED_LOW:
2128 *(short *)((char *)page + offset) += LOWORD(delta);
2129 break;
2130 case IMAGE_REL_BASED_HIGHLOW:
2131 *(int *)((char *)page + offset) += delta;
2132 break;
2133 #elif defined(__x86_64__)
2134 case IMAGE_REL_BASED_DIR64:
2135 *(INT_PTR *)((char *)page + offset) += delta;
2136 break;
2137 #endif
2138 default:
2139 FIXME("Unknown/unsupported fixup type %x.\n", type);
2140 return NULL;
2142 relocs++;
2144 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2148 /******************************************************************
2149 * LdrQueryProcessModuleInformation
2152 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2153 ULONG buf_size, ULONG* req_size)
2155 SYSTEM_MODULE* sm = &smi->Modules[0];
2156 ULONG size = sizeof(ULONG);
2157 NTSTATUS nts = STATUS_SUCCESS;
2158 ANSI_STRING str;
2159 char* ptr;
2160 PLIST_ENTRY mark, entry;
2161 PLDR_MODULE mod;
2162 WORD id = 0;
2164 smi->ModulesCount = 0;
2166 RtlEnterCriticalSection( &loader_section );
2167 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2168 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2170 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2171 size += sizeof(*sm);
2172 if (size <= buf_size)
2174 sm->Reserved1 = 0; /* FIXME */
2175 sm->Reserved2 = 0; /* FIXME */
2176 sm->ImageBaseAddress = mod->BaseAddress;
2177 sm->ImageSize = mod->SizeOfImage;
2178 sm->Flags = mod->Flags;
2179 sm->Id = id++;
2180 sm->Rank = 0; /* FIXME */
2181 sm->Unknown = 0; /* FIXME */
2182 str.Length = 0;
2183 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2184 str.Buffer = (char*)sm->Name;
2185 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2186 ptr = strrchr(str.Buffer, '\\');
2187 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2189 smi->ModulesCount++;
2190 sm++;
2192 else nts = STATUS_INFO_LENGTH_MISMATCH;
2194 RtlLeaveCriticalSection( &loader_section );
2196 if (req_size) *req_size = size;
2198 return nts;
2202 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2204 NTSTATUS status;
2205 UNICODE_STRING str;
2206 ULONG size;
2207 WCHAR buffer[64];
2208 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2210 RtlInitUnicodeString( &str, name );
2212 size = sizeof(buffer) - sizeof(WCHAR);
2213 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2214 return status;
2216 if (info->Type != REG_DWORD)
2218 buffer[size / sizeof(WCHAR)] = 0;
2219 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2221 else memcpy( value, info->Data, sizeof(*value) );
2222 return status;
2225 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2226 void *data, ULONG in_size, ULONG *out_size )
2228 NTSTATUS status;
2229 UNICODE_STRING str;
2230 ULONG size;
2231 char *buffer;
2232 KEY_VALUE_PARTIAL_INFORMATION *info;
2233 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2235 RtlInitUnicodeString( &str, name );
2237 size = info_size + in_size;
2238 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2239 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2240 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2241 if (!status || status == STATUS_BUFFER_OVERFLOW)
2243 if (out_size) *out_size = info->DataLength;
2244 if (data && !status) memcpy( data, info->Data, info->DataLength );
2246 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2247 return status;
2251 /******************************************************************
2252 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2254 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2255 void *data, ULONG in_size, ULONG *out_size )
2257 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2258 'S','o','f','t','w','a','r','e','\\',
2259 'M','i','c','r','o','s','o','f','t','\\',
2260 'W','i','n','d','o','w','s',' ','N','T','\\',
2261 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2262 'I','m','a','g','e',' ','F','i','l','e',' ',
2263 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2264 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2265 OBJECT_ATTRIBUTES attr;
2266 UNICODE_STRING name_str;
2267 HANDLE hkey;
2268 NTSTATUS status;
2269 ULONG len;
2270 WCHAR *p;
2272 attr.Length = sizeof(attr);
2273 attr.RootDirectory = 0;
2274 attr.ObjectName = &name_str;
2275 attr.Attributes = OBJ_CASE_INSENSITIVE;
2276 attr.SecurityDescriptor = NULL;
2277 attr.SecurityQualityOfService = NULL;
2279 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2280 else p = key->Buffer;
2281 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2282 name_str.Buffer = path;
2283 name_str.Length = sizeof(optionsW) + len;
2284 name_str.MaximumLength = name_str.Length;
2285 memcpy( path, optionsW, sizeof(optionsW) );
2286 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2287 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2289 if (type == REG_DWORD)
2291 if (out_size) *out_size = sizeof(ULONG);
2292 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2293 else status = STATUS_BUFFER_OVERFLOW;
2295 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2297 NtClose( hkey );
2298 return status;
2302 /******************************************************************
2303 * RtlDllShutdownInProgress (NTDLL.@)
2305 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2307 return process_detaching;
2311 /******************************************************************
2312 * LdrShutdownProcess (NTDLL.@)
2315 void WINAPI LdrShutdownProcess(void)
2317 TRACE("()\n");
2318 process_detach( TRUE, (LPVOID)1 );
2321 /******************************************************************
2322 * LdrShutdownThread (NTDLL.@)
2325 void WINAPI LdrShutdownThread(void)
2327 PLIST_ENTRY mark, entry;
2328 PLDR_MODULE mod;
2330 TRACE("()\n");
2332 /* don't do any detach calls if process is exiting */
2333 if (process_detaching) return;
2334 /* FIXME: there is still a race here */
2336 RtlEnterCriticalSection( &loader_section );
2338 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2339 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2341 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2342 InInitializationOrderModuleList);
2343 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2344 continue;
2345 if ( mod->Flags & LDR_NO_DLL_CALLS )
2346 continue;
2348 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2349 DLL_THREAD_DETACH, NULL );
2352 RtlLeaveCriticalSection( &loader_section );
2353 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2357 /***********************************************************************
2358 * free_modref
2361 static void free_modref( WINE_MODREF *wm )
2363 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2364 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2365 if (wm->ldr.InInitializationOrderModuleList.Flink)
2366 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2368 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2369 if (!TRACE_ON(module))
2370 TRACE_(loaddll)("Unloaded module %s : %s\n",
2371 debugstr_w(wm->ldr.FullDllName.Buffer),
2372 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2374 SERVER_START_REQ( unload_dll )
2376 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2377 wine_server_call( req );
2379 SERVER_END_REQ;
2381 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2382 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2383 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2384 if (cached_modref == wm) cached_modref = NULL;
2385 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2386 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2387 RtlFreeHeap( GetProcessHeap(), 0, wm );
2390 /***********************************************************************
2391 * MODULE_FlushModrefs
2393 * Remove all unused modrefs and call the internal unloading routines
2394 * for the library type.
2396 * The loader_section must be locked while calling this function.
2398 static void MODULE_FlushModrefs(void)
2400 PLIST_ENTRY mark, entry, prev;
2401 PLDR_MODULE mod;
2402 WINE_MODREF*wm;
2404 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2405 for (entry = mark->Blink; entry != mark; entry = prev)
2407 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2408 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2409 prev = entry->Blink;
2410 if (!mod->LoadCount) free_modref( wm );
2413 /* check load order list too for modules that haven't been initialized yet */
2414 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2415 for (entry = mark->Blink; entry != mark; entry = prev)
2417 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2418 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2419 prev = entry->Blink;
2420 if (!mod->LoadCount) free_modref( wm );
2424 /***********************************************************************
2425 * MODULE_DecRefCount
2427 * The loader_section must be locked while calling this function.
2429 static void MODULE_DecRefCount( WINE_MODREF *wm )
2431 int i;
2433 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2434 return;
2436 if ( wm->ldr.LoadCount <= 0 )
2437 return;
2439 --wm->ldr.LoadCount;
2440 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2442 if ( wm->ldr.LoadCount == 0 )
2444 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2446 for ( i = 0; i < wm->nDeps; i++ )
2447 if ( wm->deps[i] )
2448 MODULE_DecRefCount( wm->deps[i] );
2450 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2454 /******************************************************************
2455 * LdrUnloadDll (NTDLL.@)
2459 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2461 NTSTATUS retv = STATUS_SUCCESS;
2463 TRACE("(%p)\n", hModule);
2465 RtlEnterCriticalSection( &loader_section );
2467 /* if we're stopping the whole process (and forcing the removal of all
2468 * DLLs) the library will be freed anyway
2470 if (!process_detaching)
2472 WINE_MODREF *wm;
2474 free_lib_count++;
2475 if ((wm = get_modref( hModule )) != NULL)
2477 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2479 /* Recursively decrement reference counts */
2480 MODULE_DecRefCount( wm );
2482 /* Call process detach notifications */
2483 if ( free_lib_count <= 1 )
2485 process_detach( FALSE, NULL );
2486 MODULE_FlushModrefs();
2489 TRACE("END\n");
2491 else
2492 retv = STATUS_DLL_NOT_FOUND;
2494 free_lib_count--;
2497 RtlLeaveCriticalSection( &loader_section );
2499 return retv;
2502 /***********************************************************************
2503 * RtlImageNtHeader (NTDLL.@)
2505 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2507 IMAGE_NT_HEADERS *ret;
2509 __TRY
2511 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2513 ret = NULL;
2514 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2516 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2517 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2520 __EXCEPT_PAGE_FAULT
2522 return NULL;
2524 __ENDTRY
2525 return ret;
2529 /***********************************************************************
2530 * attach_process_dlls
2532 * Initial attach to all the dlls loaded by the process.
2534 static NTSTATUS attach_process_dlls( void *wm )
2536 NTSTATUS status;
2538 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2540 RtlEnterCriticalSection( &loader_section );
2541 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2543 if (last_failed_modref)
2544 ERR( "%s failed to initialize, aborting\n",
2545 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2546 return status;
2548 attach_implicitly_loaded_dlls( (LPVOID)1 );
2549 RtlLeaveCriticalSection( &loader_section );
2550 return status;
2554 /***********************************************************************
2555 * load_global_options
2557 static void load_global_options(void)
2559 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2560 'S','y','s','t','e','m','\\',
2561 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2562 'C','o','n','t','r','o','l','\\',
2563 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2564 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2565 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};
2566 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2567 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2568 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};
2569 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};
2571 OBJECT_ATTRIBUTES attr;
2572 UNICODE_STRING name_str;
2573 HANDLE hkey;
2574 ULONG value;
2576 attr.Length = sizeof(attr);
2577 attr.RootDirectory = 0;
2578 attr.ObjectName = &name_str;
2579 attr.Attributes = OBJ_CASE_INSENSITIVE;
2580 attr.SecurityDescriptor = NULL;
2581 attr.SecurityQualityOfService = NULL;
2582 RtlInitUnicodeString( &name_str, sessionW );
2584 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2586 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2588 query_dword_option( hkey, critsectW, &value );
2589 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2591 query_dword_option( hkey, heapresW, &value );
2592 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2594 query_dword_option( hkey, heapcommitW, &value );
2595 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2597 query_dword_option( hkey, decommittotalW, &value );
2598 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2600 query_dword_option( hkey, decommitfreeW, &value );
2601 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2603 NtClose( hkey );
2607 /***********************************************************************
2608 * start_process
2610 static void start_process( void *kernel_start )
2612 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2615 /******************************************************************
2616 * LdrInitializeThunk (NTDLL.@)
2619 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2620 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2622 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2623 NTSTATUS status;
2624 WINE_MODREF *wm;
2625 LPCWSTR load_path;
2626 PEB *peb = NtCurrentTeb()->Peb;
2627 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2629 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2631 /* allocate the modref for the main exe (if not already done) */
2632 wm = get_modref( peb->ImageBaseAddress );
2633 assert( wm );
2634 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2636 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2637 exit(1);
2640 peb->LoaderLock = &loader_section;
2641 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2642 version_init( wm->ldr.FullDllName.Buffer );
2644 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2645 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2647 /* the main exe needs to be the first in the load order list */
2648 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2649 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2651 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2652 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2654 actctx_init();
2655 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2656 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2657 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2658 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2659 heap_set_debug_flags( GetProcessHeap() );
2661 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2662 if (status != STATUS_SUCCESS) goto error;
2664 virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2665 virtual_clear_thread_stack();
2666 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2668 error:
2669 ERR( "Main exe initialization for %s failed, status %x\n",
2670 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2671 NtTerminateProcess( GetCurrentProcess(), status );
2675 /***********************************************************************
2676 * RtlImageDirectoryEntryToData (NTDLL.@)
2678 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2680 const IMAGE_NT_HEADERS *nt;
2681 DWORD addr;
2683 if ((ULONG_PTR)module & 1) /* mapped as data file */
2685 module = (HMODULE)((ULONG_PTR)module & ~1);
2686 image = FALSE;
2688 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2689 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2691 const IMAGE_NT_HEADERS64 *nt64 = (IMAGE_NT_HEADERS64 *)nt;
2693 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2694 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2695 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2696 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2698 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2700 const IMAGE_NT_HEADERS32 *nt32 = (IMAGE_NT_HEADERS32 *)nt;
2702 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2703 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2704 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2705 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2707 else return NULL;
2709 /* not mapped as image, need to find the section containing the virtual address */
2710 return RtlImageRvaToVa( nt, module, addr, NULL );
2714 /***********************************************************************
2715 * RtlImageRvaToSection (NTDLL.@)
2717 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2718 HMODULE module, DWORD rva )
2720 int i;
2721 const IMAGE_SECTION_HEADER *sec;
2723 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2724 nt->FileHeader.SizeOfOptionalHeader);
2725 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2727 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2728 return (PIMAGE_SECTION_HEADER)sec;
2730 return NULL;
2734 /***********************************************************************
2735 * RtlImageRvaToVa (NTDLL.@)
2737 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2738 DWORD rva, IMAGE_SECTION_HEADER **section )
2740 IMAGE_SECTION_HEADER *sec;
2742 if (section && *section) /* try this section first */
2744 sec = *section;
2745 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2746 goto found;
2748 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2749 found:
2750 if (section) *section = sec;
2751 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2755 /***********************************************************************
2756 * RtlPcToFileHeader (NTDLL.@)
2758 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2760 LDR_MODULE *module;
2761 PVOID ret = NULL;
2763 RtlEnterCriticalSection( &loader_section );
2764 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2765 RtlLeaveCriticalSection( &loader_section );
2766 *address = ret;
2767 return ret;
2771 /***********************************************************************
2772 * NtLoadDriver (NTDLL.@)
2773 * ZwLoadDriver (NTDLL.@)
2775 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2777 FIXME("(%p), stub!\n",DriverServiceName);
2778 return STATUS_NOT_IMPLEMENTED;
2782 /***********************************************************************
2783 * NtUnloadDriver (NTDLL.@)
2784 * ZwUnloadDriver (NTDLL.@)
2786 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2788 FIXME("(%p), stub!\n",DriverServiceName);
2789 return STATUS_NOT_IMPLEMENTED;
2793 /******************************************************************
2794 * DllMain (NTDLL.@)
2796 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2798 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2799 return TRUE;
2803 /******************************************************************
2804 * __wine_init_windows_dir (NTDLL.@)
2806 * Windows and system dir initialization once kernel32 has been loaded.
2808 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2810 PLIST_ENTRY mark, entry;
2811 LPWSTR buffer, p;
2813 DIR_init_windows_dir( windir, sysdir );
2814 strcpyW( user_shared_data->NtSystemRoot, windir );
2816 /* prepend the system dir to the name of the already created modules */
2817 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2818 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2820 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2822 assert( mod->Flags & LDR_WINE_INTERNAL );
2824 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2825 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2826 if (!buffer) continue;
2827 strcpyW( buffer, system_dir.Buffer );
2828 p = buffer + strlenW( buffer );
2829 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2830 strcpyW( p, mod->FullDllName.Buffer );
2831 RtlInitUnicodeString( &mod->FullDllName, buffer );
2832 RtlInitUnicodeString( &mod->BaseDllName, p );
2837 /***********************************************************************
2838 * __wine_process_init
2840 void __wine_process_init(void)
2842 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2844 WINE_MODREF *wm;
2845 NTSTATUS status;
2846 ANSI_STRING func_name;
2847 void (* DECLSPEC_NORETURN CDECL init_func)(void);
2848 extern mode_t FILE_umask;
2850 main_exe_file = thread_init();
2852 /* retrieve current umask */
2853 FILE_umask = umask(0777);
2854 umask( FILE_umask );
2856 load_global_options();
2858 /* setup the load callback and create ntdll modref */
2859 wine_dll_set_callback( load_builtin_callback );
2861 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2863 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2864 exit(1);
2866 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2867 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2869 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2870 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2871 0, (void **)&init_func )) != STATUS_SUCCESS)
2873 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2874 exit(1);
2876 init_func();