wer: Add new stubbed wer.dll.
[wine/hramrach.git] / dlls / ntdll / loader.c
blob07248794aaf22bcc8036eaa78a86b90607126517
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;
1408 virtual_create_builtin_view( module );
1410 /* create the MODREF */
1412 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1414 ERR( "can't load %s\n", filename );
1415 builtin_load_info->status = STATUS_NO_MEMORY;
1416 return;
1419 wm = alloc_module( module, fullname );
1420 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1421 if (!wm)
1423 ERR( "can't load %s\n", filename );
1424 builtin_load_info->status = STATUS_NO_MEMORY;
1425 return;
1427 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1429 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1430 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1432 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1434 else
1436 /* fixup imports */
1438 load_path = builtin_load_info->load_path;
1439 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1440 if (!load_path) load_path = emptyW;
1441 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1443 /* the module has only be inserted in the load & memory order lists */
1444 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1445 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1446 /* FIXME: free the modref */
1447 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1448 return;
1452 builtin_load_info->wm = wm;
1453 TRACE( "loaded %s %p %p\n", filename, wm, module );
1455 /* send the DLL load event */
1457 SERVER_START_REQ( load_dll )
1459 req->handle = 0;
1460 req->base = wine_server_client_ptr( module );
1461 req->size = nt->OptionalHeader.SizeOfImage;
1462 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1463 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1464 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1465 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1466 wine_server_call( req );
1468 SERVER_END_REQ;
1470 /* setup relay debugging entry points */
1471 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1475 /******************************************************************************
1476 * load_native_dll (internal)
1478 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1479 DWORD flags, WINE_MODREF** pwm )
1481 void *module;
1482 HANDLE mapping;
1483 LARGE_INTEGER size;
1484 IMAGE_NT_HEADERS *nt;
1485 SIZE_T len = 0;
1486 WINE_MODREF *wm;
1487 NTSTATUS status;
1489 TRACE("Trying native dll %s\n", debugstr_w(name));
1491 size.QuadPart = 0;
1492 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1493 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1494 if (status != STATUS_SUCCESS) return status;
1496 module = NULL;
1497 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1498 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1499 NtClose( mapping );
1500 if (status < 0) return status;
1502 /* create the MODREF */
1504 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1506 /* fixup imports */
1508 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1510 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1512 /* the module has only be inserted in the load & memory order lists */
1513 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1514 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1516 /* FIXME: there are several more dangling references
1517 * left. Including dlls loaded by this dll before the
1518 * failed one. Unrolling is rather difficult with the
1519 * current structure and we can leave them lying
1520 * around with no problems, so we don't care.
1521 * As these might reference our wm, we don't free it.
1523 return status;
1527 /* send DLL load event */
1529 nt = RtlImageNtHeader( module );
1531 SERVER_START_REQ( load_dll )
1533 req->handle = wine_server_obj_handle( file );
1534 req->base = wine_server_client_ptr( module );
1535 req->size = nt->OptionalHeader.SizeOfImage;
1536 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1537 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1538 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1539 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1540 wine_server_call( req );
1542 SERVER_END_REQ;
1544 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1546 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1548 wm->ldr.LoadCount = 1;
1549 *pwm = wm;
1550 return STATUS_SUCCESS;
1554 /***********************************************************************
1555 * load_builtin_dll
1557 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1558 DWORD flags, WINE_MODREF** pwm )
1560 char error[256], dllname[MAX_PATH];
1561 const WCHAR *name, *p;
1562 DWORD len, i;
1563 void *handle = NULL;
1564 struct builtin_load_info info, *prev_info;
1566 /* Fix the name in case we have a full path and extension */
1567 name = path;
1568 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1569 if ((p = strrchrW( name, '/' ))) name = p + 1;
1571 /* load_library will modify info.status. Note also that load_library can be
1572 * called several times, if the .so file we're loading has dependencies.
1573 * info.status will gather all the errors we may get while loading all these
1574 * libraries
1576 info.load_path = load_path;
1577 info.filename = NULL;
1578 info.status = STATUS_SUCCESS;
1579 info.wm = NULL;
1581 if (file) /* we have a real file, try to load it */
1583 UNICODE_STRING nt_name;
1584 ANSI_STRING unix_name;
1586 TRACE("Trying built-in %s\n", debugstr_w(path));
1588 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1589 return STATUS_DLL_NOT_FOUND;
1591 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1593 RtlFreeUnicodeString( &nt_name );
1594 return STATUS_DLL_NOT_FOUND;
1596 prev_info = builtin_load_info;
1597 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1598 builtin_load_info = &info;
1599 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1600 builtin_load_info = prev_info;
1601 RtlFreeUnicodeString( &nt_name );
1602 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1603 if (!handle)
1605 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1606 return STATUS_INVALID_IMAGE_FORMAT;
1609 else
1611 int file_exists;
1613 TRACE("Trying built-in %s\n", debugstr_w(name));
1615 /* we don't want to depend on the current codepage here */
1616 len = strlenW( name ) + 1;
1617 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1618 for (i = 0; i < len; i++)
1620 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1621 dllname[i] = (char)name[i];
1622 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1625 prev_info = builtin_load_info;
1626 builtin_load_info = &info;
1627 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1628 builtin_load_info = prev_info;
1629 if (!handle)
1631 if (!file_exists)
1633 /* The file does not exist -> WARN() */
1634 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1635 return STATUS_DLL_NOT_FOUND;
1637 /* ERR() for all other errors (missing functions, ...) */
1638 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1639 return STATUS_PROCEDURE_NOT_FOUND;
1643 if (info.status != STATUS_SUCCESS)
1645 wine_dll_unload( handle );
1646 return info.status;
1649 if (!info.wm)
1651 PLIST_ENTRY mark, entry;
1653 /* The constructor wasn't called, this means the .so is already
1654 * loaded under a different name. Try to find the wm for it. */
1656 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1657 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1659 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1660 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1662 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1663 TRACE( "Found %s at %p for builtin %s\n",
1664 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1665 break;
1668 wine_dll_unload( handle ); /* release the libdl refcount */
1669 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1670 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1672 else
1674 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1675 info.wm->ldr.LoadCount = 1;
1676 info.wm->ldr.SectionHandle = handle;
1679 *pwm = info.wm;
1680 return STATUS_SUCCESS;
1684 /***********************************************************************
1685 * find_actctx_dll
1687 * Find the full path (if any) of the dll from the activation context.
1689 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1691 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1692 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1694 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1695 ACTCTX_SECTION_KEYED_DATA data;
1696 UNICODE_STRING nameW;
1697 NTSTATUS status;
1698 SIZE_T needed, size = 1024;
1699 WCHAR *p;
1701 RtlInitUnicodeString( &nameW, libname );
1702 data.cbSize = sizeof(data);
1703 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1704 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1705 &nameW, &data );
1706 if (status != STATUS_SUCCESS) return status;
1708 for (;;)
1710 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1712 status = STATUS_NO_MEMORY;
1713 goto done;
1715 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1716 AssemblyDetailedInformationInActivationContext,
1717 info, size, &needed );
1718 if (status == STATUS_SUCCESS) break;
1719 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1720 RtlFreeHeap( GetProcessHeap(), 0, info );
1721 size = needed;
1722 /* restart with larger buffer */
1725 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1727 status = STATUS_SXS_KEY_NOT_FOUND;
1728 goto done;
1731 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1733 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1735 p++;
1736 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1738 /* manifest name does not match directory name, so it's not a global
1739 * windows/winsxs manifest; use the manifest directory name instead */
1740 dirlen = p - info->lpAssemblyManifestPath;
1741 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1742 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1744 status = STATUS_NO_MEMORY;
1745 goto done;
1747 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1748 p += dirlen;
1749 strcpyW( p, libname );
1750 goto done;
1754 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1755 nameW.Length + 2*sizeof(WCHAR));
1757 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1759 status = STATUS_NO_MEMORY;
1760 goto done;
1762 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1763 p += windows_dir.Length / sizeof(WCHAR);
1764 memcpy( p, winsxsW, sizeof(winsxsW) );
1765 p += sizeof(winsxsW) / sizeof(WCHAR);
1766 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1767 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1768 *p++ = '\\';
1769 strcpyW( p, libname );
1770 done:
1771 RtlFreeHeap( GetProcessHeap(), 0, info );
1772 RtlReleaseActivationContext( data.hActCtx );
1773 return status;
1777 /***********************************************************************
1778 * find_dll_file
1780 * Find the file (or already loaded module) for a given dll name.
1782 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1783 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1785 OBJECT_ATTRIBUTES attr;
1786 IO_STATUS_BLOCK io;
1787 UNICODE_STRING nt_name;
1788 WCHAR *file_part, *ext, *dllname;
1789 ULONG len;
1791 /* first append .dll if needed */
1793 dllname = NULL;
1794 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1796 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1797 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1798 return STATUS_NO_MEMORY;
1799 strcpyW( dllname, libname );
1800 strcatW( dllname, dllW );
1801 libname = dllname;
1804 nt_name.Buffer = NULL;
1806 if (!contains_path( libname ))
1808 NTSTATUS status;
1809 WCHAR *fullname = NULL;
1811 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1813 status = find_actctx_dll( libname, &fullname );
1814 if (status == STATUS_SUCCESS)
1816 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1817 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1818 libname = dllname = fullname;
1820 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1822 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1823 return status;
1827 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1829 /* we need to search for it */
1830 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1831 if (len)
1833 if (len >= *size) goto overflow;
1834 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1836 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1838 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1839 return STATUS_NO_MEMORY;
1841 attr.Length = sizeof(attr);
1842 attr.RootDirectory = 0;
1843 attr.Attributes = OBJ_CASE_INSENSITIVE;
1844 attr.ObjectName = &nt_name;
1845 attr.SecurityDescriptor = NULL;
1846 attr.SecurityQualityOfService = NULL;
1847 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1848 goto found;
1851 /* not found */
1853 if (!contains_path( libname ))
1855 /* if libname doesn't contain a path at all, we simply return the name as is,
1856 * to be loaded as builtin */
1857 len = strlenW(libname) * sizeof(WCHAR);
1858 if (len >= *size) goto overflow;
1859 strcpyW( filename, libname );
1860 goto found;
1864 /* absolute path name, or relative path name but not found above */
1866 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1868 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1869 return STATUS_NO_MEMORY;
1871 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1872 if (len >= *size) goto overflow;
1873 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1874 if (!(*pwm = find_fullname_module( filename )) && handle)
1876 attr.Length = sizeof(attr);
1877 attr.RootDirectory = 0;
1878 attr.Attributes = OBJ_CASE_INSENSITIVE;
1879 attr.ObjectName = &nt_name;
1880 attr.SecurityDescriptor = NULL;
1881 attr.SecurityQualityOfService = NULL;
1882 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1884 found:
1885 RtlFreeUnicodeString( &nt_name );
1886 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1887 return STATUS_SUCCESS;
1889 overflow:
1890 RtlFreeUnicodeString( &nt_name );
1891 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1892 *size = len + sizeof(WCHAR);
1893 return STATUS_BUFFER_TOO_SMALL;
1897 /***********************************************************************
1898 * load_dll (internal)
1900 * Load a PE style module according to the load order.
1901 * The loader_section must be locked while calling this function.
1903 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1905 enum loadorder loadorder;
1906 WCHAR buffer[32];
1907 WCHAR *filename;
1908 ULONG size;
1909 WINE_MODREF *main_exe;
1910 HANDLE handle = 0;
1911 NTSTATUS nts;
1913 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1915 *pwm = NULL;
1916 filename = buffer;
1917 size = sizeof(buffer);
1918 for (;;)
1920 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1921 if (nts == STATUS_SUCCESS) break;
1922 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1923 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1924 /* grow the buffer and retry */
1925 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1928 if (*pwm) /* found already loaded module */
1930 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1932 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1934 TRACE("Found %s for %s at %p, count=%d\n",
1935 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1936 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1937 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1938 return STATUS_SUCCESS;
1941 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1942 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1944 if (handle && is_fake_dll( handle ))
1946 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1947 NtClose( handle );
1948 handle = 0;
1951 switch(loadorder)
1953 case LO_INVALID:
1954 nts = STATUS_NO_MEMORY;
1955 break;
1956 case LO_DISABLED:
1957 nts = STATUS_DLL_NOT_FOUND;
1958 break;
1959 case LO_NATIVE:
1960 case LO_NATIVE_BUILTIN:
1961 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1962 else
1964 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1965 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1966 /* not in PE format, maybe it's a builtin */
1967 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1969 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1970 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1971 break;
1972 case LO_BUILTIN:
1973 case LO_BUILTIN_NATIVE:
1974 case LO_DEFAULT: /* default is builtin,native */
1975 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1976 if (!handle) break; /* nothing else we can try */
1977 /* file is not a builtin library, try without using the specified file */
1978 if (nts != STATUS_SUCCESS)
1979 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1980 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1981 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1983 /* stub-only dll, try native */
1984 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1985 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1986 nts = STATUS_DLL_NOT_FOUND;
1988 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1989 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1990 break;
1993 if (nts == STATUS_SUCCESS)
1995 /* Initialize DLL just loaded */
1996 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1997 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1998 (*pwm)->ldr.BaseAddress);
1999 if (handle) NtClose( handle );
2000 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2001 return nts;
2004 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2005 if (handle) NtClose( handle );
2006 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2007 return nts;
2010 /******************************************************************
2011 * LdrLoadDll (NTDLL.@)
2013 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2014 const UNICODE_STRING *libname, HMODULE* hModule)
2016 WINE_MODREF *wm;
2017 NTSTATUS nts;
2019 RtlEnterCriticalSection( &loader_section );
2021 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2022 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2024 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2026 nts = process_attach( wm, NULL );
2027 if (nts != STATUS_SUCCESS)
2029 LdrUnloadDll(wm->ldr.BaseAddress);
2030 wm = NULL;
2033 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2035 RtlLeaveCriticalSection( &loader_section );
2036 return nts;
2040 /******************************************************************
2041 * LdrGetDllHandle (NTDLL.@)
2043 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2045 NTSTATUS status;
2046 WCHAR buffer[128];
2047 WCHAR *filename;
2048 ULONG size;
2049 WINE_MODREF *wm;
2051 RtlEnterCriticalSection( &loader_section );
2053 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2055 filename = buffer;
2056 size = sizeof(buffer);
2057 for (;;)
2059 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2060 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2061 if (status != STATUS_BUFFER_TOO_SMALL) break;
2062 /* grow the buffer and retry */
2063 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2065 status = STATUS_NO_MEMORY;
2066 break;
2070 if (status == STATUS_SUCCESS)
2072 if (wm) *base = wm->ldr.BaseAddress;
2073 else status = STATUS_DLL_NOT_FOUND;
2076 RtlLeaveCriticalSection( &loader_section );
2077 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2078 return status;
2082 /******************************************************************
2083 * LdrAddRefDll (NTDLL.@)
2085 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2087 NTSTATUS ret = STATUS_SUCCESS;
2088 WINE_MODREF *wm;
2090 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2092 RtlEnterCriticalSection( &loader_section );
2094 if ((wm = get_modref( module )))
2096 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2097 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2099 else ret = STATUS_INVALID_PARAMETER;
2101 RtlLeaveCriticalSection( &loader_section );
2102 return ret;
2106 /***********************************************************************
2107 * LdrProcessRelocationBlock (NTDLL.@)
2109 * Apply relocations to a given page of a mapped PE image.
2111 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2112 USHORT *relocs, INT_PTR delta )
2114 while (count--)
2116 USHORT offset = *relocs & 0xfff;
2117 int type = *relocs >> 12;
2118 switch(type)
2120 case IMAGE_REL_BASED_ABSOLUTE:
2121 break;
2122 case IMAGE_REL_BASED_HIGH:
2123 *(short *)((char *)page + offset) += HIWORD(delta);
2124 break;
2125 case IMAGE_REL_BASED_LOW:
2126 *(short *)((char *)page + offset) += LOWORD(delta);
2127 break;
2128 case IMAGE_REL_BASED_HIGHLOW:
2129 *(int *)((char *)page + offset) += delta;
2130 break;
2131 #ifdef __x86_64__
2132 case IMAGE_REL_BASED_DIR64:
2133 *(INT_PTR *)((char *)page + offset) += delta;
2134 break;
2135 #endif
2136 default:
2137 FIXME("Unknown/unsupported fixup type %x.\n", type);
2138 return NULL;
2140 relocs++;
2142 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2146 /******************************************************************
2147 * LdrQueryProcessModuleInformation
2150 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2151 ULONG buf_size, ULONG* req_size)
2153 SYSTEM_MODULE* sm = &smi->Modules[0];
2154 ULONG size = sizeof(ULONG);
2155 NTSTATUS nts = STATUS_SUCCESS;
2156 ANSI_STRING str;
2157 char* ptr;
2158 PLIST_ENTRY mark, entry;
2159 PLDR_MODULE mod;
2160 WORD id = 0;
2162 smi->ModulesCount = 0;
2164 RtlEnterCriticalSection( &loader_section );
2165 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2166 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2168 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2169 size += sizeof(*sm);
2170 if (size <= buf_size)
2172 sm->Reserved1 = 0; /* FIXME */
2173 sm->Reserved2 = 0; /* FIXME */
2174 sm->ImageBaseAddress = mod->BaseAddress;
2175 sm->ImageSize = mod->SizeOfImage;
2176 sm->Flags = mod->Flags;
2177 sm->Id = id++;
2178 sm->Rank = 0; /* FIXME */
2179 sm->Unknown = 0; /* FIXME */
2180 str.Length = 0;
2181 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2182 str.Buffer = (char*)sm->Name;
2183 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2184 ptr = strrchr(str.Buffer, '\\');
2185 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2187 smi->ModulesCount++;
2188 sm++;
2190 else nts = STATUS_INFO_LENGTH_MISMATCH;
2192 RtlLeaveCriticalSection( &loader_section );
2194 if (req_size) *req_size = size;
2196 return nts;
2200 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2202 NTSTATUS status;
2203 UNICODE_STRING str;
2204 ULONG size;
2205 WCHAR buffer[64];
2206 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2208 RtlInitUnicodeString( &str, name );
2210 size = sizeof(buffer) - sizeof(WCHAR);
2211 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2212 return status;
2214 if (info->Type != REG_DWORD)
2216 buffer[size / sizeof(WCHAR)] = 0;
2217 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2219 else memcpy( value, info->Data, sizeof(*value) );
2220 return status;
2223 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2224 void *data, ULONG in_size, ULONG *out_size )
2226 NTSTATUS status;
2227 UNICODE_STRING str;
2228 ULONG size;
2229 char *buffer;
2230 KEY_VALUE_PARTIAL_INFORMATION *info;
2231 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2233 RtlInitUnicodeString( &str, name );
2235 size = info_size + in_size;
2236 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2237 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2238 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2239 if (!status || status == STATUS_BUFFER_OVERFLOW)
2241 if (out_size) *out_size = info->DataLength;
2242 if (data && !status) memcpy( data, info->Data, info->DataLength );
2244 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2245 return status;
2249 /******************************************************************
2250 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2252 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2253 void *data, ULONG in_size, ULONG *out_size )
2255 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2256 'S','o','f','t','w','a','r','e','\\',
2257 'M','i','c','r','o','s','o','f','t','\\',
2258 'W','i','n','d','o','w','s',' ','N','T','\\',
2259 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2260 'I','m','a','g','e',' ','F','i','l','e',' ',
2261 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2262 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2263 OBJECT_ATTRIBUTES attr;
2264 UNICODE_STRING name_str;
2265 HANDLE hkey;
2266 NTSTATUS status;
2267 ULONG len;
2268 WCHAR *p;
2270 attr.Length = sizeof(attr);
2271 attr.RootDirectory = 0;
2272 attr.ObjectName = &name_str;
2273 attr.Attributes = OBJ_CASE_INSENSITIVE;
2274 attr.SecurityDescriptor = NULL;
2275 attr.SecurityQualityOfService = NULL;
2277 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2278 else p = key->Buffer;
2279 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2280 name_str.Buffer = path;
2281 name_str.Length = sizeof(optionsW) + len;
2282 name_str.MaximumLength = name_str.Length;
2283 memcpy( path, optionsW, sizeof(optionsW) );
2284 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2285 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2287 if (type == REG_DWORD)
2289 if (out_size) *out_size = sizeof(ULONG);
2290 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2291 else status = STATUS_BUFFER_OVERFLOW;
2293 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2295 NtClose( hkey );
2296 return status;
2300 /******************************************************************
2301 * RtlDllShutdownInProgress (NTDLL.@)
2303 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2305 return process_detaching;
2309 /******************************************************************
2310 * LdrShutdownProcess (NTDLL.@)
2313 void WINAPI LdrShutdownProcess(void)
2315 TRACE("()\n");
2316 process_detach( TRUE, (LPVOID)1 );
2319 /******************************************************************
2320 * LdrShutdownThread (NTDLL.@)
2323 void WINAPI LdrShutdownThread(void)
2325 PLIST_ENTRY mark, entry;
2326 PLDR_MODULE mod;
2328 TRACE("()\n");
2330 /* don't do any detach calls if process is exiting */
2331 if (process_detaching) return;
2332 /* FIXME: there is still a race here */
2334 RtlEnterCriticalSection( &loader_section );
2336 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2337 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2339 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2340 InInitializationOrderModuleList);
2341 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2342 continue;
2343 if ( mod->Flags & LDR_NO_DLL_CALLS )
2344 continue;
2346 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2347 DLL_THREAD_DETACH, NULL );
2350 RtlLeaveCriticalSection( &loader_section );
2351 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2355 /***********************************************************************
2356 * free_modref
2359 static void free_modref( WINE_MODREF *wm )
2361 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2362 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2363 if (wm->ldr.InInitializationOrderModuleList.Flink)
2364 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2366 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2367 if (!TRACE_ON(module))
2368 TRACE_(loaddll)("Unloaded module %s : %s\n",
2369 debugstr_w(wm->ldr.FullDllName.Buffer),
2370 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2372 SERVER_START_REQ( unload_dll )
2374 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2375 wine_server_call( req );
2377 SERVER_END_REQ;
2379 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2380 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2381 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2382 if (cached_modref == wm) cached_modref = NULL;
2383 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2384 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2385 RtlFreeHeap( GetProcessHeap(), 0, wm );
2388 /***********************************************************************
2389 * MODULE_FlushModrefs
2391 * Remove all unused modrefs and call the internal unloading routines
2392 * for the library type.
2394 * The loader_section must be locked while calling this function.
2396 static void MODULE_FlushModrefs(void)
2398 PLIST_ENTRY mark, entry, prev;
2399 PLDR_MODULE mod;
2400 WINE_MODREF*wm;
2402 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2403 for (entry = mark->Blink; entry != mark; entry = prev)
2405 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2406 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2407 prev = entry->Blink;
2408 if (!mod->LoadCount) free_modref( wm );
2411 /* check load order list too for modules that haven't been initialized yet */
2412 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2413 for (entry = mark->Blink; entry != mark; entry = prev)
2415 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2416 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2417 prev = entry->Blink;
2418 if (!mod->LoadCount) free_modref( wm );
2422 /***********************************************************************
2423 * MODULE_DecRefCount
2425 * The loader_section must be locked while calling this function.
2427 static void MODULE_DecRefCount( WINE_MODREF *wm )
2429 int i;
2431 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2432 return;
2434 if ( wm->ldr.LoadCount <= 0 )
2435 return;
2437 --wm->ldr.LoadCount;
2438 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2440 if ( wm->ldr.LoadCount == 0 )
2442 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2444 for ( i = 0; i < wm->nDeps; i++ )
2445 if ( wm->deps[i] )
2446 MODULE_DecRefCount( wm->deps[i] );
2448 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2452 /******************************************************************
2453 * LdrUnloadDll (NTDLL.@)
2457 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2459 NTSTATUS retv = STATUS_SUCCESS;
2461 TRACE("(%p)\n", hModule);
2463 RtlEnterCriticalSection( &loader_section );
2465 /* if we're stopping the whole process (and forcing the removal of all
2466 * DLLs) the library will be freed anyway
2468 if (!process_detaching)
2470 WINE_MODREF *wm;
2472 free_lib_count++;
2473 if ((wm = get_modref( hModule )) != NULL)
2475 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2477 /* Recursively decrement reference counts */
2478 MODULE_DecRefCount( wm );
2480 /* Call process detach notifications */
2481 if ( free_lib_count <= 1 )
2483 process_detach( FALSE, NULL );
2484 MODULE_FlushModrefs();
2487 TRACE("END\n");
2489 else
2490 retv = STATUS_DLL_NOT_FOUND;
2492 free_lib_count--;
2495 RtlLeaveCriticalSection( &loader_section );
2497 return retv;
2500 /***********************************************************************
2501 * RtlImageNtHeader (NTDLL.@)
2503 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2505 IMAGE_NT_HEADERS *ret;
2507 __TRY
2509 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2511 ret = NULL;
2512 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2514 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2515 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2518 __EXCEPT_PAGE_FAULT
2520 return NULL;
2522 __ENDTRY
2523 return ret;
2527 /***********************************************************************
2528 * attach_process_dlls
2530 * Initial attach to all the dlls loaded by the process.
2532 static NTSTATUS attach_process_dlls( void *wm )
2534 NTSTATUS status;
2536 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2538 RtlEnterCriticalSection( &loader_section );
2539 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2541 if (last_failed_modref)
2542 ERR( "%s failed to initialize, aborting\n",
2543 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2544 return status;
2546 attach_implicitly_loaded_dlls( (LPVOID)1 );
2547 RtlLeaveCriticalSection( &loader_section );
2548 return status;
2552 /***********************************************************************
2553 * load_global_options
2555 static void load_global_options(void)
2557 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2558 'S','y','s','t','e','m','\\',
2559 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2560 'C','o','n','t','r','o','l','\\',
2561 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2562 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2563 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};
2564 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2565 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2566 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};
2567 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};
2569 OBJECT_ATTRIBUTES attr;
2570 UNICODE_STRING name_str;
2571 HANDLE hkey;
2572 ULONG value;
2574 attr.Length = sizeof(attr);
2575 attr.RootDirectory = 0;
2576 attr.ObjectName = &name_str;
2577 attr.Attributes = OBJ_CASE_INSENSITIVE;
2578 attr.SecurityDescriptor = NULL;
2579 attr.SecurityQualityOfService = NULL;
2580 RtlInitUnicodeString( &name_str, sessionW );
2582 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2584 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2586 query_dword_option( hkey, critsectW, &value );
2587 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2589 query_dword_option( hkey, heapresW, &value );
2590 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2592 query_dword_option( hkey, heapcommitW, &value );
2593 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2595 query_dword_option( hkey, decommittotalW, &value );
2596 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2598 query_dword_option( hkey, decommitfreeW, &value );
2599 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2601 NtClose( hkey );
2605 /***********************************************************************
2606 * start_process
2608 static void start_process( void *kernel_start )
2610 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2613 /******************************************************************
2614 * LdrInitializeThunk (NTDLL.@)
2617 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2618 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2620 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2621 NTSTATUS status;
2622 WINE_MODREF *wm;
2623 LPCWSTR load_path;
2624 PEB *peb = NtCurrentTeb()->Peb;
2625 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2627 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2629 /* allocate the modref for the main exe (if not already done) */
2630 wm = get_modref( peb->ImageBaseAddress );
2631 assert( wm );
2632 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2634 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2635 exit(1);
2638 peb->LoaderLock = &loader_section;
2639 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2640 if (!peb->ProcessParameters->WindowTitle.Buffer)
2641 peb->ProcessParameters->WindowTitle = 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 = (const 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 = (const 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();