winedbg: Properly manage Wine's dbghelp extensions for constant symbols which value...
[wine/wine-gecko.git] / dlls / ntdll / loader.c
blob71d7ecd7cf9d9dbbf57c8a82e13400c59864f0b8
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 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
102 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
104 static RTL_CRITICAL_SECTION loader_section;
105 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
107 0, 0, &loader_section,
108 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
109 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
111 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
113 static WINE_MODREF *cached_modref;
114 static WINE_MODREF *current_modref;
115 static WINE_MODREF *last_failed_modref;
117 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
118 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
119 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
120 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
121 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
122 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
124 /* convert PE image VirtualAddress to Real Address */
125 static inline void *get_rva( HMODULE module, DWORD va )
127 return (void *)((char *)module + va);
130 /* check whether the file name contains a path */
131 static inline int contains_path( LPCWSTR name )
133 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
136 /* convert from straight ASCII to Unicode without depending on the current codepage */
137 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
139 while (len--) *dst++ = (unsigned char)*src++;
143 /*************************************************************************
144 * call_dll_entry_point
146 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
147 * their entry point, so we need a small asm wrapper.
149 #ifdef __i386__
150 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
151 __ASM_GLOBAL_FUNC(call_dll_entry_point,
152 "pushl %ebp\n\t"
153 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
154 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
155 "movl %esp,%ebp\n\t"
156 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
157 "pushl %ebx\n\t"
158 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
159 "subl $8,%esp\n\t"
160 "pushl 20(%ebp)\n\t"
161 "pushl 16(%ebp)\n\t"
162 "pushl 12(%ebp)\n\t"
163 "movl 8(%ebp),%eax\n\t"
164 "call *%eax\n\t"
165 "leal -4(%ebp),%esp\n\t"
166 "popl %ebx\n\t"
167 __ASM_CFI(".cfi_same_value %ebx\n\t")
168 "popl %ebp\n\t"
169 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
170 __ASM_CFI(".cfi_same_value %ebp\n\t")
171 "ret" )
172 #else /* __i386__ */
173 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
174 UINT reason, void *reserved )
176 return proc( module, reason, reserved );
178 #endif /* __i386__ */
181 #if defined(__i386__) || defined(__x86_64__)
182 /*************************************************************************
183 * stub_entry_point
185 * Entry point for stub functions.
187 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
189 EXCEPTION_RECORD rec;
191 rec.ExceptionCode = EXCEPTION_WINE_STUB;
192 rec.ExceptionFlags = EH_NONCONTINUABLE;
193 rec.ExceptionRecord = NULL;
194 rec.ExceptionAddress = ret_addr;
195 rec.NumberParameters = 2;
196 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
197 rec.ExceptionInformation[1] = (ULONG_PTR)name;
198 for (;;) RtlRaiseException( &rec );
202 #include "pshpack1.h"
203 #ifdef __i386__
204 struct stub
206 BYTE pushl1; /* pushl $name */
207 const char *name;
208 BYTE pushl2; /* pushl $dll */
209 const char *dll;
210 BYTE call; /* call stub_entry_point */
211 DWORD entry;
213 #else
214 struct stub
216 BYTE movq_rdi[2]; /* movq $dll,%rdi */
217 const char *dll;
218 BYTE movq_rsi[2]; /* movq $name,%rsi */
219 const char *name;
220 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
221 BYTE movq_rax[2]; /* movq $entry, %rax */
222 const void* entry;
223 BYTE jmpq_rax[2]; /* jmp %rax */
225 #endif
226 #include "poppack.h"
228 /*************************************************************************
229 * allocate_stub
231 * Allocate a stub entry point.
233 static ULONG_PTR allocate_stub( const char *dll, const char *name )
235 #define MAX_SIZE 65536
236 static struct stub *stubs;
237 static unsigned int nb_stubs;
238 struct stub *stub;
240 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
242 if (!stubs)
244 SIZE_T size = MAX_SIZE;
245 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
246 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
247 return 0xdeadbeef;
249 stub = &stubs[nb_stubs++];
250 #ifdef __i386__
251 stub->pushl1 = 0x68; /* pushl $name */
252 stub->name = name;
253 stub->pushl2 = 0x68; /* pushl $dll */
254 stub->dll = dll;
255 stub->call = 0xe8; /* call stub_entry_point */
256 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
257 #else
258 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
259 stub->movq_rdi[1] = 0xbf;
260 stub->dll = dll;
261 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
262 stub->movq_rsi[1] = 0xbe;
263 stub->name = name;
264 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
265 stub->movq_rsp_rdx[1] = 0x8b;
266 stub->movq_rsp_rdx[2] = 0x14;
267 stub->movq_rsp_rdx[3] = 0x24;
268 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
269 stub->movq_rax[1] = 0xb8;
270 stub->entry = stub_entry_point;
271 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
272 stub->jmpq_rax[1] = 0xe0;
273 #endif
274 return (ULONG_PTR)stub;
277 #else /* __i386__ */
278 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
279 #endif /* __i386__ */
282 /*************************************************************************
283 * get_modref
285 * Looks for the referenced HMODULE in the current process
286 * The loader_section must be locked while calling this function.
288 static WINE_MODREF *get_modref( HMODULE hmod )
290 PLIST_ENTRY mark, entry;
291 PLDR_MODULE mod;
293 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
295 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
296 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
298 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
299 if (mod->BaseAddress == hmod)
300 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
301 if (mod->BaseAddress > (void*)hmod) break;
303 return NULL;
307 /**********************************************************************
308 * find_basename_module
310 * Find a module from its base name.
311 * The loader_section must be locked while calling this function
313 static WINE_MODREF *find_basename_module( LPCWSTR name )
315 PLIST_ENTRY mark, entry;
317 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
318 return cached_modref;
320 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
321 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
323 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
324 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
326 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
327 return cached_modref;
330 return NULL;
334 /**********************************************************************
335 * find_fullname_module
337 * Find a module from its full path name.
338 * The loader_section must be locked while calling this function
340 static WINE_MODREF *find_fullname_module( LPCWSTR name )
342 PLIST_ENTRY mark, entry;
344 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
345 return cached_modref;
347 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
348 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
350 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
351 if (!strcmpiW( name, mod->FullDllName.Buffer ))
353 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
354 return cached_modref;
357 return NULL;
361 /*************************************************************************
362 * find_forwarded_export
364 * Find the final function pointer for a forwarded function.
365 * The loader_section must be locked while calling this function.
367 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
369 const IMAGE_EXPORT_DIRECTORY *exports;
370 DWORD exp_size;
371 WINE_MODREF *wm;
372 WCHAR mod_name[32];
373 const char *end = strrchr(forward, '.');
374 FARPROC proc = NULL;
376 if (!end) return NULL;
377 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
378 ascii_to_unicode( mod_name, forward, end - forward );
379 mod_name[end - forward] = 0;
380 if (!strchrW( mod_name, '.' ))
382 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
383 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
386 if (!(wm = find_basename_module( mod_name )))
388 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
389 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
390 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
392 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
394 LdrUnloadDll( wm->ldr.BaseAddress );
395 wm = NULL;
399 if (!wm)
401 ERR( "module not found for forward '%s' used by %s\n",
402 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
403 return NULL;
406 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
407 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
409 const char *name = end + 1;
410 if (*name == '#') /* ordinal */
411 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
412 else
413 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
416 if (!proc)
418 ERR("function not found for forward '%s' used by %s."
419 " If you are using builtin %s, try using the native one instead.\n",
420 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
421 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
423 return proc;
427 /*************************************************************************
428 * find_ordinal_export
430 * Find an exported function by ordinal.
431 * The exports base must have been subtracted from the ordinal already.
432 * The loader_section must be locked while calling this function.
434 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
435 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
437 FARPROC proc;
438 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
440 if (ordinal >= exports->NumberOfFunctions)
442 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
443 return NULL;
445 if (!functions[ordinal]) return NULL;
447 proc = get_rva( module, functions[ordinal] );
449 /* if the address falls into the export dir, it's a forward */
450 if (((const char *)proc >= (const char *)exports) &&
451 ((const char *)proc < (const char *)exports + exp_size))
452 return find_forwarded_export( module, (const char *)proc, load_path );
454 if (TRACE_ON(snoop))
456 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
457 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
459 if (TRACE_ON(relay))
461 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
462 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
464 return proc;
468 /*************************************************************************
469 * find_named_export
471 * Find an exported function by name.
472 * The loader_section must be locked while calling this function.
474 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
475 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
477 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
478 const DWORD *names = get_rva( module, exports->AddressOfNames );
479 int min = 0, max = exports->NumberOfNames - 1;
481 /* first check the hint */
482 if (hint >= 0 && hint <= max)
484 char *ename = get_rva( module, names[hint] );
485 if (!strcmp( ename, name ))
486 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
489 /* then do a binary search */
490 while (min <= max)
492 int res, pos = (min + max) / 2;
493 char *ename = get_rva( module, names[pos] );
494 if (!(res = strcmp( ename, name )))
495 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
496 if (res > 0) max = pos - 1;
497 else min = pos + 1;
499 return NULL;
504 /*************************************************************************
505 * import_dll
507 * Import the dll specified by the given import descriptor.
508 * The loader_section must be locked while calling this function.
510 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
512 NTSTATUS status;
513 WINE_MODREF *wmImp;
514 HMODULE imp_mod;
515 const IMAGE_EXPORT_DIRECTORY *exports;
516 DWORD exp_size;
517 const IMAGE_THUNK_DATA *import_list;
518 IMAGE_THUNK_DATA *thunk_list;
519 WCHAR buffer[32];
520 const char *name = get_rva( module, descr->Name );
521 DWORD len = strlen(name);
522 PVOID protect_base;
523 SIZE_T protect_size = 0;
524 DWORD protect_old;
526 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
527 if (descr->u.OriginalFirstThunk)
528 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
529 else
530 import_list = thunk_list;
532 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
534 if (len * sizeof(WCHAR) < sizeof(buffer))
536 ascii_to_unicode( buffer, name, len );
537 buffer[len] = 0;
538 status = load_dll( load_path, buffer, 0, &wmImp );
540 else /* need to allocate a larger buffer */
542 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
543 if (!ptr) return NULL;
544 ascii_to_unicode( ptr, name, len );
545 ptr[len] = 0;
546 status = load_dll( load_path, ptr, 0, &wmImp );
547 RtlFreeHeap( GetProcessHeap(), 0, ptr );
550 if (status)
552 if (status == STATUS_DLL_NOT_FOUND)
553 ERR("Library %s (which is needed by %s) not found\n",
554 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
555 else
556 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
557 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
558 return NULL;
561 /* unprotect the import address table since it can be located in
562 * readonly section */
563 while (import_list[protect_size].u1.Ordinal) protect_size++;
564 protect_base = thunk_list;
565 protect_size *= sizeof(*thunk_list);
566 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
567 &protect_size, PAGE_WRITECOPY, &protect_old );
569 imp_mod = wmImp->ldr.BaseAddress;
570 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
572 if (!exports)
574 /* set all imported function to deadbeef */
575 while (import_list->u1.Ordinal)
577 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
579 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
580 WARN("No implementation for %s.%d", name, ordinal );
581 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
583 else
585 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
586 WARN("No implementation for %s.%s", name, pe_name->Name );
587 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
589 WARN(" imported from %s, allocating stub %p\n",
590 debugstr_w(current_modref->ldr.FullDllName.Buffer),
591 (void *)thunk_list->u1.Function );
592 import_list++;
593 thunk_list++;
595 goto done;
598 while (import_list->u1.Ordinal)
600 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
602 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
604 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
605 ordinal - exports->Base, load_path );
606 if (!thunk_list->u1.Function)
608 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
609 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
610 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
611 (void *)thunk_list->u1.Function );
613 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
615 else /* import by name */
617 IMAGE_IMPORT_BY_NAME *pe_name;
618 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
619 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
620 (const char*)pe_name->Name,
621 pe_name->Hint, load_path );
622 if (!thunk_list->u1.Function)
624 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
625 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
626 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
627 (void *)thunk_list->u1.Function );
629 TRACE_(imports)("--- %s %s.%d = %p\n",
630 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
632 import_list++;
633 thunk_list++;
636 done:
637 /* restore old protection of the import address table */
638 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
639 return wmImp;
643 /***********************************************************************
644 * create_module_activation_context
646 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
648 NTSTATUS status;
649 LDR_RESOURCE_INFO info;
650 const IMAGE_RESOURCE_DATA_ENTRY *entry;
652 info.Type = RT_MANIFEST;
653 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
654 info.Language = 0;
655 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
657 ACTCTXW ctx;
658 ctx.cbSize = sizeof(ctx);
659 ctx.lpSource = NULL;
660 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
661 ctx.hModule = module->BaseAddress;
662 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
663 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
665 return status;
669 /****************************************************************
670 * fixup_imports
672 * Fixup all imports of a given module.
673 * The loader_section must be locked while calling this function.
675 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
677 int i, nb_imports;
678 const IMAGE_IMPORT_DESCRIPTOR *imports;
679 WINE_MODREF *prev;
680 DWORD size;
681 NTSTATUS status;
682 ULONG_PTR cookie;
684 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
685 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
687 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
688 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
689 return STATUS_SUCCESS;
691 nb_imports = 0;
692 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
694 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
696 if (!create_module_activation_context( &wm->ldr ))
697 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
699 /* Allocate module dependency list */
700 wm->nDeps = nb_imports;
701 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
703 /* load the imported modules. They are automatically
704 * added to the modref list of the process.
706 prev = current_modref;
707 current_modref = wm;
708 status = STATUS_SUCCESS;
709 for (i = 0; i < nb_imports; i++)
711 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
712 status = STATUS_DLL_NOT_FOUND;
714 current_modref = prev;
715 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
716 return status;
720 /*************************************************************************
721 * is_dll_native_subsystem
723 * Check if dll is a proper native driver.
724 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
725 * while being perfectly normal DLLs. This heuristic should catch such breakages.
727 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
729 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
730 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
731 const IMAGE_IMPORT_DESCRIPTOR *imports;
732 DWORD i, size;
733 WCHAR buffer[16];
735 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
736 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
738 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
739 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
741 for (i = 0; imports[i].Name; i++)
743 const char *name = get_rva( module, imports[i].Name );
744 DWORD len = strlen(name);
745 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
746 ascii_to_unicode( buffer, name, len + 1 );
747 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
749 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
750 return FALSE;
754 return TRUE;
758 /*************************************************************************
759 * alloc_module
761 * Allocate a WINE_MODREF structure and add it to the process list
762 * The loader_section must be locked while calling this function.
764 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
766 WINE_MODREF *wm;
767 const WCHAR *p;
768 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
769 PLIST_ENTRY entry, mark;
771 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
773 wm->nDeps = 0;
774 wm->deps = NULL;
776 wm->ldr.BaseAddress = hModule;
777 wm->ldr.EntryPoint = NULL;
778 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
779 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
780 wm->ldr.LoadCount = 1;
781 wm->ldr.TlsIndex = -1;
782 wm->ldr.SectionHandle = NULL;
783 wm->ldr.CheckSum = 0;
784 wm->ldr.TimeDateStamp = 0;
785 wm->ldr.ActivationContext = 0;
787 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
788 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
789 else p = wm->ldr.FullDllName.Buffer;
790 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
792 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
794 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
795 if (nt->OptionalHeader.AddressOfEntryPoint)
796 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
799 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
800 &wm->ldr.InLoadOrderModuleList);
802 /* insert module in MemoryList, sorted in increasing base addresses */
803 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
804 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
806 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
807 break;
809 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
810 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
811 wm->ldr.InMemoryOrderModuleList.Flink = entry;
812 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
814 /* wait until init is called for inserting into this list */
815 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
816 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
818 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
820 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
821 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
822 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
824 return wm;
828 /*************************************************************************
829 * alloc_process_tls
831 * Allocate the process-wide structure for module TLS storage.
833 static NTSTATUS alloc_process_tls(void)
835 PLIST_ENTRY mark, entry;
836 PLDR_MODULE mod;
837 const IMAGE_TLS_DIRECTORY *dir;
838 ULONG size, i;
840 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
841 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
843 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
844 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
845 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
846 continue;
847 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
848 if (!size) continue;
849 tls_total_size += size;
850 tls_module_count++;
852 if (!tls_module_count) return STATUS_SUCCESS;
854 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
856 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
857 if (!tls_dirs) return STATUS_NO_MEMORY;
859 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
861 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
862 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
863 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
864 continue;
865 tls_dirs[i] = dir;
866 *(DWORD *)dir->AddressOfIndex = i;
867 mod->TlsIndex = i;
868 mod->LoadCount = -1; /* can't unload it */
869 i++;
871 return STATUS_SUCCESS;
875 /*************************************************************************
876 * alloc_thread_tls
878 * Allocate the per-thread structure for module TLS storage.
880 static NTSTATUS alloc_thread_tls(void)
882 void **pointers;
883 char *data;
884 UINT i;
886 if (!tls_module_count) return STATUS_SUCCESS;
888 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
889 tls_module_count * sizeof(*pointers) )))
890 return STATUS_NO_MEMORY;
892 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
894 RtlFreeHeap( GetProcessHeap(), 0, pointers );
895 return STATUS_NO_MEMORY;
898 for (i = 0; i < tls_module_count; i++)
900 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
901 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
903 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
904 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
905 (void *)dir->StartAddressOfRawData, data );
907 pointers[i] = data;
908 memcpy( data, (void *)dir->StartAddressOfRawData, size );
909 data += size;
910 memset( data, 0, dir->SizeOfZeroFill );
911 data += dir->SizeOfZeroFill;
913 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
914 return STATUS_SUCCESS;
918 /*************************************************************************
919 * call_tls_callbacks
921 static void call_tls_callbacks( HMODULE module, UINT reason )
923 const IMAGE_TLS_DIRECTORY *dir;
924 const PIMAGE_TLS_CALLBACK *callback;
925 ULONG dirsize;
927 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
928 if (!dir || !dir->AddressOfCallBacks) return;
930 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
932 if (TRACE_ON(relay))
933 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
934 GetCurrentThreadId(), *callback, module, reason_names[reason] );
935 __TRY
937 (*callback)( module, reason, NULL );
939 __EXCEPT_ALL
941 if (TRACE_ON(relay))
942 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
943 GetCurrentThreadId(), callback, module, reason_names[reason] );
944 return;
946 __ENDTRY
947 if (TRACE_ON(relay))
948 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
949 GetCurrentThreadId(), *callback, module, reason_names[reason] );
954 /*************************************************************************
955 * MODULE_InitDLL
957 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
959 WCHAR mod_name[32];
960 NTSTATUS status = STATUS_SUCCESS;
961 DLLENTRYPROC entry = wm->ldr.EntryPoint;
962 void *module = wm->ldr.BaseAddress;
963 BOOL retv = TRUE;
965 /* Skip calls for modules loaded with special load flags */
967 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
968 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
969 if (!entry) return STATUS_SUCCESS;
971 if (TRACE_ON(relay))
973 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
974 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
975 mod_name[len / sizeof(WCHAR)] = 0;
976 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
977 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
978 reason_names[reason], lpReserved );
980 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
981 reason_names[reason], lpReserved );
983 __TRY
985 retv = call_dll_entry_point( entry, module, reason, lpReserved );
986 if (!retv)
987 status = STATUS_DLL_INIT_FAILED;
989 __EXCEPT_ALL
991 if (TRACE_ON(relay))
992 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
993 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
994 status = GetExceptionCode();
996 __ENDTRY
998 /* The state of the module list may have changed due to the call
999 to the dll. We cannot assume that this module has not been
1000 deleted. */
1001 if (TRACE_ON(relay))
1002 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1003 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1004 reason_names[reason], lpReserved, retv );
1005 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1007 return status;
1011 /*************************************************************************
1012 * process_attach
1014 * Send the process attach notification to all DLLs the given module
1015 * depends on (recursively). This is somewhat complicated due to the fact that
1017 * - we have to respect the module dependencies, i.e. modules implicitly
1018 * referenced by another module have to be initialized before the module
1019 * itself can be initialized
1021 * - the initialization routine of a DLL can itself call LoadLibrary,
1022 * thereby introducing a whole new set of dependencies (even involving
1023 * the 'old' modules) at any time during the whole process
1025 * (Note that this routine can be recursively entered not only directly
1026 * from itself, but also via LoadLibrary from one of the called initialization
1027 * routines.)
1029 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1030 * the process *detach* notifications to be sent in the correct order.
1031 * This must not only take into account module dependencies, but also
1032 * 'hidden' dependencies created by modules calling LoadLibrary in their
1033 * attach notification routine.
1035 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1036 * list after the attach notification has returned. This implies that the
1037 * detach notifications are called in the reverse of the sequence the attach
1038 * notifications *returned*.
1040 * The loader_section must be locked while calling this function.
1042 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1044 NTSTATUS status = STATUS_SUCCESS;
1045 ULONG_PTR cookie;
1046 int i;
1048 if (process_detaching) return status;
1050 /* prevent infinite recursion in case of cyclical dependencies */
1051 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1052 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1053 return status;
1055 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1057 /* Tag current MODREF to prevent recursive loop */
1058 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1059 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1060 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1062 /* Recursively attach all DLLs this one depends on */
1063 for ( i = 0; i < wm->nDeps; i++ )
1065 if (!wm->deps[i]) continue;
1066 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1069 /* Call DLL entry point */
1070 if (status == STATUS_SUCCESS)
1072 WINE_MODREF *prev = current_modref;
1073 current_modref = wm;
1074 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1075 if (status == STATUS_SUCCESS)
1076 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1077 else
1079 /* point to the name so LdrInitializeThunk can print it */
1080 last_failed_modref = wm;
1081 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1083 current_modref = prev;
1086 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1087 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1088 &wm->ldr.InInitializationOrderModuleList);
1090 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1091 /* Remove recursion flag */
1092 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1094 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1095 return status;
1099 /**********************************************************************
1100 * attach_implicitly_loaded_dlls
1102 * Attach to the (builtin) dlls that have been implicitly loaded because
1103 * of a dependency at the Unix level, but not imported at the Win32 level.
1105 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1107 for (;;)
1109 PLIST_ENTRY mark, entry;
1111 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1112 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1114 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1116 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1117 TRACE( "found implicitly loaded %s, attaching to it\n",
1118 debugstr_w(mod->BaseDllName.Buffer));
1119 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1120 break; /* restart the search from the start */
1122 if (entry == mark) break; /* nothing found */
1127 /*************************************************************************
1128 * process_detach
1130 * Send DLL process detach notifications. See the comment about calling
1131 * sequence at process_attach. Unless the bForceDetach flag
1132 * is set, only DLLs with zero refcount are notified.
1134 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1136 PLIST_ENTRY mark, entry;
1137 PLDR_MODULE mod;
1139 RtlEnterCriticalSection( &loader_section );
1140 if (bForceDetach) process_detaching = 1;
1141 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1144 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1146 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1147 InInitializationOrderModuleList);
1148 /* Check whether to detach this DLL */
1149 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1150 continue;
1151 if ( mod->LoadCount && !bForceDetach )
1152 continue;
1154 /* Call detach notification */
1155 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1156 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1157 DLL_PROCESS_DETACH, lpReserved );
1159 /* Restart at head of WINE_MODREF list, as entries might have
1160 been added and/or removed while performing the call ... */
1161 break;
1163 } while (entry != mark);
1165 RtlLeaveCriticalSection( &loader_section );
1168 /*************************************************************************
1169 * MODULE_DllThreadAttach
1171 * Send DLL thread attach notifications. These are sent in the
1172 * reverse sequence of process detach notification.
1175 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1177 PLIST_ENTRY mark, entry;
1178 PLDR_MODULE mod;
1179 NTSTATUS status;
1181 /* don't do any attach calls if process is exiting */
1182 if (process_detaching) return STATUS_SUCCESS;
1183 /* FIXME: there is still a race here */
1185 RtlEnterCriticalSection( &loader_section );
1187 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1189 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1190 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1192 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1193 InInitializationOrderModuleList);
1194 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1195 continue;
1196 if ( mod->Flags & LDR_NO_DLL_CALLS )
1197 continue;
1199 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1200 DLL_THREAD_ATTACH, lpReserved );
1203 done:
1204 RtlLeaveCriticalSection( &loader_section );
1205 return status;
1208 /******************************************************************
1209 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1212 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1214 WINE_MODREF *wm;
1215 NTSTATUS ret = STATUS_SUCCESS;
1217 RtlEnterCriticalSection( &loader_section );
1219 wm = get_modref( hModule );
1220 if (!wm || wm->ldr.TlsIndex != -1)
1221 ret = STATUS_DLL_NOT_FOUND;
1222 else
1223 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1225 RtlLeaveCriticalSection( &loader_section );
1227 return ret;
1230 /******************************************************************
1231 * LdrFindEntryForAddress (NTDLL.@)
1233 * The loader_section must be locked while calling this function
1235 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1237 PLIST_ENTRY mark, entry;
1238 PLDR_MODULE mod;
1240 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1241 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1243 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1244 if (mod->BaseAddress <= addr &&
1245 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1247 *pmod = mod;
1248 return STATUS_SUCCESS;
1250 if (mod->BaseAddress > addr) break;
1252 return STATUS_NO_MORE_ENTRIES;
1255 /******************************************************************
1256 * LdrLockLoaderLock (NTDLL.@)
1258 * Note: flags are not implemented.
1259 * Flag 0x01 is used to raise exceptions on errors.
1260 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1262 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1264 if (flags) FIXME( "flags %x not supported\n", flags );
1266 if (result) *result = 1;
1267 if (!magic) return STATUS_INVALID_PARAMETER_3;
1268 RtlEnterCriticalSection( &loader_section );
1269 *magic = GetCurrentThreadId();
1270 return STATUS_SUCCESS;
1274 /******************************************************************
1275 * LdrUnlockLoaderUnlock (NTDLL.@)
1277 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1279 if (magic)
1281 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1282 RtlLeaveCriticalSection( &loader_section );
1284 return STATUS_SUCCESS;
1288 /******************************************************************
1289 * LdrGetProcedureAddress (NTDLL.@)
1291 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1292 ULONG ord, PVOID *address)
1294 IMAGE_EXPORT_DIRECTORY *exports;
1295 DWORD exp_size;
1296 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1298 RtlEnterCriticalSection( &loader_section );
1300 /* check if the module itself is invalid to return the proper error */
1301 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1302 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1303 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1305 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1306 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1307 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1308 if (proc)
1310 *address = proc;
1311 ret = STATUS_SUCCESS;
1315 RtlLeaveCriticalSection( &loader_section );
1316 return ret;
1320 /***********************************************************************
1321 * is_fake_dll
1323 * Check if a loaded native dll is a Wine fake dll.
1325 static BOOL is_fake_dll( HANDLE handle )
1327 static const char fakedll_signature[] = "Wine placeholder DLL";
1328 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1329 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1330 IO_STATUS_BLOCK io;
1331 LARGE_INTEGER offset;
1333 offset.QuadPart = 0;
1334 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1335 if (io.Information < sizeof(buffer)) return FALSE;
1336 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1337 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1338 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1339 return FALSE;
1343 /***********************************************************************
1344 * get_builtin_fullname
1346 * Build the full pathname for a builtin dll.
1348 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1350 static const WCHAR soW[] = {'.','s','o',0};
1351 WCHAR *p, *fullname;
1352 size_t i, len = strlen(filename);
1354 /* check if path can correspond to the dll we have */
1355 if (path && (p = strrchrW( path, '\\' )))
1357 p++;
1358 for (i = 0; i < len; i++)
1359 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1360 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1362 /* the filename matches, use path as the full path */
1363 len += p - path;
1364 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1366 memcpy( fullname, path, len * sizeof(WCHAR) );
1367 fullname[len] = 0;
1369 return fullname;
1373 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1374 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1376 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1377 p = fullname + system_dir.Length / sizeof(WCHAR);
1378 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1379 ascii_to_unicode( p, filename, len + 1 );
1381 return fullname;
1385 /***********************************************************************
1386 * load_builtin_callback
1388 * Load a library in memory; callback function for wine_dll_register
1390 static void load_builtin_callback( void *module, const char *filename )
1392 static const WCHAR emptyW[1];
1393 IMAGE_NT_HEADERS *nt;
1394 WINE_MODREF *wm;
1395 WCHAR *fullname;
1396 const WCHAR *load_path;
1398 if (!module)
1400 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1401 return;
1403 if (!(nt = RtlImageNtHeader( module )))
1405 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1406 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1407 return;
1409 virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1410 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1411 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1413 /* create the MODREF */
1415 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1417 ERR( "can't load %s\n", filename );
1418 builtin_load_info->status = STATUS_NO_MEMORY;
1419 return;
1422 wm = alloc_module( module, fullname );
1423 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1424 if (!wm)
1426 ERR( "can't load %s\n", filename );
1427 builtin_load_info->status = STATUS_NO_MEMORY;
1428 return;
1430 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1432 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1433 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1435 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1437 else
1439 /* fixup imports */
1441 load_path = builtin_load_info->load_path;
1442 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1443 if (!load_path) load_path = emptyW;
1444 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1446 /* the module has only be inserted in the load & memory order lists */
1447 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1448 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1449 /* FIXME: free the modref */
1450 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1451 return;
1455 builtin_load_info->wm = wm;
1456 TRACE( "loaded %s %p %p\n", filename, wm, module );
1458 /* send the DLL load event */
1460 SERVER_START_REQ( load_dll )
1462 req->handle = 0;
1463 req->base = wine_server_client_ptr( module );
1464 req->size = nt->OptionalHeader.SizeOfImage;
1465 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1466 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1467 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1468 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1469 wine_server_call( req );
1471 SERVER_END_REQ;
1473 /* setup relay debugging entry points */
1474 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1478 /******************************************************************************
1479 * load_native_dll (internal)
1481 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1482 DWORD flags, WINE_MODREF** pwm )
1484 void *module;
1485 HANDLE mapping;
1486 LARGE_INTEGER size;
1487 IMAGE_NT_HEADERS *nt;
1488 SIZE_T len = 0;
1489 WINE_MODREF *wm;
1490 NTSTATUS status;
1492 TRACE("Trying native dll %s\n", debugstr_w(name));
1494 size.QuadPart = 0;
1495 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1496 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1497 if (status != STATUS_SUCCESS) return status;
1499 module = NULL;
1500 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1501 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1502 NtClose( mapping );
1503 if (status != STATUS_SUCCESS) return status;
1505 /* create the MODREF */
1507 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1509 /* fixup imports */
1511 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1513 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1515 /* the module has only be inserted in the load & memory order lists */
1516 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1517 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1519 /* FIXME: there are several more dangling references
1520 * left. Including dlls loaded by this dll before the
1521 * failed one. Unrolling is rather difficult with the
1522 * current structure and we can leave them lying
1523 * around with no problems, so we don't care.
1524 * As these might reference our wm, we don't free it.
1526 return status;
1530 /* send DLL load event */
1532 nt = RtlImageNtHeader( module );
1534 SERVER_START_REQ( load_dll )
1536 req->handle = wine_server_obj_handle( file );
1537 req->base = wine_server_client_ptr( module );
1538 req->size = nt->OptionalHeader.SizeOfImage;
1539 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1540 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1541 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1542 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1543 wine_server_call( req );
1545 SERVER_END_REQ;
1547 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1549 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1551 wm->ldr.LoadCount = 1;
1552 *pwm = wm;
1553 return STATUS_SUCCESS;
1557 /***********************************************************************
1558 * load_builtin_dll
1560 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1561 DWORD flags, WINE_MODREF** pwm )
1563 char error[256], dllname[MAX_PATH];
1564 const WCHAR *name, *p;
1565 DWORD len, i;
1566 void *handle = NULL;
1567 struct builtin_load_info info, *prev_info;
1569 /* Fix the name in case we have a full path and extension */
1570 name = path;
1571 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1572 if ((p = strrchrW( name, '/' ))) name = p + 1;
1574 /* load_library will modify info.status. Note also that load_library can be
1575 * called several times, if the .so file we're loading has dependencies.
1576 * info.status will gather all the errors we may get while loading all these
1577 * libraries
1579 info.load_path = load_path;
1580 info.filename = NULL;
1581 info.status = STATUS_SUCCESS;
1582 info.wm = NULL;
1584 if (file) /* we have a real file, try to load it */
1586 UNICODE_STRING nt_name;
1587 ANSI_STRING unix_name;
1589 TRACE("Trying built-in %s\n", debugstr_w(path));
1591 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1592 return STATUS_DLL_NOT_FOUND;
1594 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1596 RtlFreeUnicodeString( &nt_name );
1597 return STATUS_DLL_NOT_FOUND;
1599 prev_info = builtin_load_info;
1600 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1601 builtin_load_info = &info;
1602 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1603 builtin_load_info = prev_info;
1604 RtlFreeUnicodeString( &nt_name );
1605 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1606 if (!handle)
1608 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1609 return STATUS_INVALID_IMAGE_FORMAT;
1612 else
1614 int file_exists;
1616 TRACE("Trying built-in %s\n", debugstr_w(name));
1618 /* we don't want to depend on the current codepage here */
1619 len = strlenW( name ) + 1;
1620 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1621 for (i = 0; i < len; i++)
1623 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1624 dllname[i] = (char)name[i];
1625 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1628 prev_info = builtin_load_info;
1629 builtin_load_info = &info;
1630 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1631 builtin_load_info = prev_info;
1632 if (!handle)
1634 if (!file_exists)
1636 /* The file does not exist -> WARN() */
1637 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1638 return STATUS_DLL_NOT_FOUND;
1640 /* ERR() for all other errors (missing functions, ...) */
1641 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1642 return STATUS_PROCEDURE_NOT_FOUND;
1646 if (info.status != STATUS_SUCCESS)
1648 wine_dll_unload( handle );
1649 return info.status;
1652 if (!info.wm)
1654 PLIST_ENTRY mark, entry;
1656 /* The constructor wasn't called, this means the .so is already
1657 * loaded under a different name. Try to find the wm for it. */
1659 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1660 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1662 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1663 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1665 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1666 TRACE( "Found %s at %p for builtin %s\n",
1667 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1668 break;
1671 wine_dll_unload( handle ); /* release the libdl refcount */
1672 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1673 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1675 else
1677 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1678 info.wm->ldr.LoadCount = 1;
1679 info.wm->ldr.SectionHandle = handle;
1682 *pwm = info.wm;
1683 return STATUS_SUCCESS;
1687 /***********************************************************************
1688 * find_actctx_dll
1690 * Find the full path (if any) of the dll from the activation context.
1692 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1694 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1695 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1697 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1698 ACTCTX_SECTION_KEYED_DATA data;
1699 UNICODE_STRING nameW;
1700 NTSTATUS status;
1701 SIZE_T needed, size = 1024;
1702 WCHAR *p;
1704 RtlInitUnicodeString( &nameW, libname );
1705 data.cbSize = sizeof(data);
1706 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1707 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1708 &nameW, &data );
1709 if (status != STATUS_SUCCESS) return status;
1711 for (;;)
1713 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1715 status = STATUS_NO_MEMORY;
1716 goto done;
1718 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1719 AssemblyDetailedInformationInActivationContext,
1720 info, size, &needed );
1721 if (status == STATUS_SUCCESS) break;
1722 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1723 RtlFreeHeap( GetProcessHeap(), 0, info );
1724 size = needed;
1725 /* restart with larger buffer */
1728 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1730 status = STATUS_SXS_KEY_NOT_FOUND;
1731 goto done;
1734 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1736 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1738 p++;
1739 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1741 /* manifest name does not match directory name, so it's not a global
1742 * windows/winsxs manifest; use the manifest directory name instead */
1743 dirlen = p - info->lpAssemblyManifestPath;
1744 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1745 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1747 status = STATUS_NO_MEMORY;
1748 goto done;
1750 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1751 p += dirlen;
1752 strcpyW( p, libname );
1753 goto done;
1757 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1758 nameW.Length + 2*sizeof(WCHAR));
1760 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1762 status = STATUS_NO_MEMORY;
1763 goto done;
1765 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1766 p += windows_dir.Length / sizeof(WCHAR);
1767 memcpy( p, winsxsW, sizeof(winsxsW) );
1768 p += sizeof(winsxsW) / sizeof(WCHAR);
1769 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1770 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1771 *p++ = '\\';
1772 strcpyW( p, libname );
1773 done:
1774 RtlFreeHeap( GetProcessHeap(), 0, info );
1775 RtlReleaseActivationContext( data.hActCtx );
1776 return status;
1780 /***********************************************************************
1781 * find_dll_file
1783 * Find the file (or already loaded module) for a given dll name.
1785 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1786 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1788 OBJECT_ATTRIBUTES attr;
1789 IO_STATUS_BLOCK io;
1790 UNICODE_STRING nt_name;
1791 WCHAR *file_part, *ext, *dllname;
1792 ULONG len;
1794 /* first append .dll if needed */
1796 dllname = NULL;
1797 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1799 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1800 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1801 return STATUS_NO_MEMORY;
1802 strcpyW( dllname, libname );
1803 strcatW( dllname, dllW );
1804 libname = dllname;
1807 nt_name.Buffer = NULL;
1809 if (!contains_path( libname ))
1811 NTSTATUS status;
1812 WCHAR *fullname = NULL;
1814 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1816 status = find_actctx_dll( libname, &fullname );
1817 if (status == STATUS_SUCCESS)
1819 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1820 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1821 libname = dllname = fullname;
1823 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1825 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1826 return status;
1830 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1832 /* we need to search for it */
1833 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1834 if (len)
1836 if (len >= *size) goto overflow;
1837 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1839 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1841 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1842 return STATUS_NO_MEMORY;
1844 attr.Length = sizeof(attr);
1845 attr.RootDirectory = 0;
1846 attr.Attributes = OBJ_CASE_INSENSITIVE;
1847 attr.ObjectName = &nt_name;
1848 attr.SecurityDescriptor = NULL;
1849 attr.SecurityQualityOfService = NULL;
1850 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1851 goto found;
1854 /* not found */
1856 if (!contains_path( libname ))
1858 /* if libname doesn't contain a path at all, we simply return the name as is,
1859 * to be loaded as builtin */
1860 len = strlenW(libname) * sizeof(WCHAR);
1861 if (len >= *size) goto overflow;
1862 strcpyW( filename, libname );
1863 goto found;
1867 /* absolute path name, or relative path name but not found above */
1869 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1871 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1872 return STATUS_NO_MEMORY;
1874 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1875 if (len >= *size) goto overflow;
1876 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1877 if (!(*pwm = find_fullname_module( filename )) && handle)
1879 attr.Length = sizeof(attr);
1880 attr.RootDirectory = 0;
1881 attr.Attributes = OBJ_CASE_INSENSITIVE;
1882 attr.ObjectName = &nt_name;
1883 attr.SecurityDescriptor = NULL;
1884 attr.SecurityQualityOfService = NULL;
1885 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1887 found:
1888 RtlFreeUnicodeString( &nt_name );
1889 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1890 return STATUS_SUCCESS;
1892 overflow:
1893 RtlFreeUnicodeString( &nt_name );
1894 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1895 *size = len + sizeof(WCHAR);
1896 return STATUS_BUFFER_TOO_SMALL;
1900 /***********************************************************************
1901 * load_dll (internal)
1903 * Load a PE style module according to the load order.
1904 * The loader_section must be locked while calling this function.
1906 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1908 enum loadorder loadorder;
1909 WCHAR buffer[32];
1910 WCHAR *filename;
1911 ULONG size;
1912 WINE_MODREF *main_exe;
1913 HANDLE handle = 0;
1914 NTSTATUS nts;
1916 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1918 *pwm = NULL;
1919 filename = buffer;
1920 size = sizeof(buffer);
1921 for (;;)
1923 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1924 if (nts == STATUS_SUCCESS) break;
1925 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1926 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1927 /* grow the buffer and retry */
1928 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1931 if (*pwm) /* found already loaded module */
1933 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1935 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1937 TRACE("Found %s for %s at %p, count=%d\n",
1938 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1939 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1940 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1941 return STATUS_SUCCESS;
1944 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1945 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1947 if (handle && is_fake_dll( handle ))
1949 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1950 NtClose( handle );
1951 handle = 0;
1954 switch(loadorder)
1956 case LO_INVALID:
1957 nts = STATUS_NO_MEMORY;
1958 break;
1959 case LO_DISABLED:
1960 nts = STATUS_DLL_NOT_FOUND;
1961 break;
1962 case LO_NATIVE:
1963 case LO_NATIVE_BUILTIN:
1964 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1965 else
1967 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1968 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1969 /* not in PE format, maybe it's a builtin */
1970 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1972 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1973 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1974 break;
1975 case LO_BUILTIN:
1976 case LO_BUILTIN_NATIVE:
1977 case LO_DEFAULT: /* default is builtin,native */
1978 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1979 if (!handle) break; /* nothing else we can try */
1980 /* file is not a builtin library, try without using the specified file */
1981 if (nts != STATUS_SUCCESS)
1982 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1983 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1984 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1986 /* stub-only dll, try native */
1987 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1988 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1989 nts = STATUS_DLL_NOT_FOUND;
1991 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1992 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1993 break;
1996 if (nts == STATUS_SUCCESS)
1998 /* Initialize DLL just loaded */
1999 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2000 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2001 (*pwm)->ldr.BaseAddress);
2002 if (handle) NtClose( handle );
2003 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2004 return nts;
2007 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2008 if (handle) NtClose( handle );
2009 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2010 return nts;
2013 /******************************************************************
2014 * LdrLoadDll (NTDLL.@)
2016 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2017 const UNICODE_STRING *libname, HMODULE* hModule)
2019 WINE_MODREF *wm;
2020 NTSTATUS nts;
2022 RtlEnterCriticalSection( &loader_section );
2024 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2025 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2027 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2029 nts = process_attach( wm, NULL );
2030 if (nts != STATUS_SUCCESS)
2032 LdrUnloadDll(wm->ldr.BaseAddress);
2033 wm = NULL;
2036 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2038 RtlLeaveCriticalSection( &loader_section );
2039 return nts;
2043 /******************************************************************
2044 * LdrGetDllHandle (NTDLL.@)
2046 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2048 NTSTATUS status;
2049 WCHAR buffer[128];
2050 WCHAR *filename;
2051 ULONG size;
2052 WINE_MODREF *wm;
2054 RtlEnterCriticalSection( &loader_section );
2056 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2058 filename = buffer;
2059 size = sizeof(buffer);
2060 for (;;)
2062 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2063 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2064 if (status != STATUS_BUFFER_TOO_SMALL) break;
2065 /* grow the buffer and retry */
2066 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2068 status = STATUS_NO_MEMORY;
2069 break;
2073 if (status == STATUS_SUCCESS)
2075 if (wm) *base = wm->ldr.BaseAddress;
2076 else status = STATUS_DLL_NOT_FOUND;
2079 RtlLeaveCriticalSection( &loader_section );
2080 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2081 return status;
2085 /******************************************************************
2086 * LdrAddRefDll (NTDLL.@)
2088 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2090 NTSTATUS ret = STATUS_SUCCESS;
2091 WINE_MODREF *wm;
2093 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2095 RtlEnterCriticalSection( &loader_section );
2097 if ((wm = get_modref( module )))
2099 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2100 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2102 else ret = STATUS_INVALID_PARAMETER;
2104 RtlLeaveCriticalSection( &loader_section );
2105 return ret;
2109 /***********************************************************************
2110 * LdrProcessRelocationBlock (NTDLL.@)
2112 * Apply relocations to a given page of a mapped PE image.
2114 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2115 USHORT *relocs, INT_PTR delta )
2117 while (count--)
2119 USHORT offset = *relocs & 0xfff;
2120 int type = *relocs >> 12;
2121 switch(type)
2123 case IMAGE_REL_BASED_ABSOLUTE:
2124 break;
2125 #ifdef __i386__
2126 case IMAGE_REL_BASED_HIGH:
2127 *(short *)((char *)page + offset) += HIWORD(delta);
2128 break;
2129 case IMAGE_REL_BASED_LOW:
2130 *(short *)((char *)page + offset) += LOWORD(delta);
2131 break;
2132 case IMAGE_REL_BASED_HIGHLOW:
2133 *(int *)((char *)page + offset) += delta;
2134 break;
2135 #elif defined(__x86_64__)
2136 case IMAGE_REL_BASED_DIR64:
2137 *(INT_PTR *)((char *)page + offset) += delta;
2138 break;
2139 #endif
2140 default:
2141 FIXME("Unknown/unsupported fixup type %x.\n", type);
2142 return NULL;
2144 relocs++;
2146 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2150 /******************************************************************
2151 * LdrQueryProcessModuleInformation
2154 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2155 ULONG buf_size, ULONG* req_size)
2157 SYSTEM_MODULE* sm = &smi->Modules[0];
2158 ULONG size = sizeof(ULONG);
2159 NTSTATUS nts = STATUS_SUCCESS;
2160 ANSI_STRING str;
2161 char* ptr;
2162 PLIST_ENTRY mark, entry;
2163 PLDR_MODULE mod;
2164 WORD id = 0;
2166 smi->ModulesCount = 0;
2168 RtlEnterCriticalSection( &loader_section );
2169 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2170 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2172 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2173 size += sizeof(*sm);
2174 if (size <= buf_size)
2176 sm->Reserved1 = 0; /* FIXME */
2177 sm->Reserved2 = 0; /* FIXME */
2178 sm->ImageBaseAddress = mod->BaseAddress;
2179 sm->ImageSize = mod->SizeOfImage;
2180 sm->Flags = mod->Flags;
2181 sm->Id = id++;
2182 sm->Rank = 0; /* FIXME */
2183 sm->Unknown = 0; /* FIXME */
2184 str.Length = 0;
2185 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2186 str.Buffer = (char*)sm->Name;
2187 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2188 ptr = strrchr(str.Buffer, '\\');
2189 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2191 smi->ModulesCount++;
2192 sm++;
2194 else nts = STATUS_INFO_LENGTH_MISMATCH;
2196 RtlLeaveCriticalSection( &loader_section );
2198 if (req_size) *req_size = size;
2200 return nts;
2204 /******************************************************************
2205 * RtlDllShutdownInProgress (NTDLL.@)
2207 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2209 return process_detaching;
2213 /******************************************************************
2214 * LdrShutdownProcess (NTDLL.@)
2217 void WINAPI LdrShutdownProcess(void)
2219 TRACE("()\n");
2220 process_detach( TRUE, (LPVOID)1 );
2223 /******************************************************************
2224 * LdrShutdownThread (NTDLL.@)
2227 void WINAPI LdrShutdownThread(void)
2229 PLIST_ENTRY mark, entry;
2230 PLDR_MODULE mod;
2232 TRACE("()\n");
2234 /* don't do any detach calls if process is exiting */
2235 if (process_detaching) return;
2236 /* FIXME: there is still a race here */
2238 RtlEnterCriticalSection( &loader_section );
2240 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2241 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2243 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2244 InInitializationOrderModuleList);
2245 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2246 continue;
2247 if ( mod->Flags & LDR_NO_DLL_CALLS )
2248 continue;
2250 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2251 DLL_THREAD_DETACH, NULL );
2254 RtlLeaveCriticalSection( &loader_section );
2255 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2259 /***********************************************************************
2260 * free_modref
2263 static void free_modref( WINE_MODREF *wm )
2265 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2266 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2267 if (wm->ldr.InInitializationOrderModuleList.Flink)
2268 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2270 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2271 if (!TRACE_ON(module))
2272 TRACE_(loaddll)("Unloaded module %s : %s\n",
2273 debugstr_w(wm->ldr.FullDllName.Buffer),
2274 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2276 SERVER_START_REQ( unload_dll )
2278 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2279 wine_server_call( req );
2281 SERVER_END_REQ;
2283 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2284 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2285 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2286 if (cached_modref == wm) cached_modref = NULL;
2287 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2288 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2289 RtlFreeHeap( GetProcessHeap(), 0, wm );
2292 /***********************************************************************
2293 * MODULE_FlushModrefs
2295 * Remove all unused modrefs and call the internal unloading routines
2296 * for the library type.
2298 * The loader_section must be locked while calling this function.
2300 static void MODULE_FlushModrefs(void)
2302 PLIST_ENTRY mark, entry, prev;
2303 PLDR_MODULE mod;
2304 WINE_MODREF*wm;
2306 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2307 for (entry = mark->Blink; entry != mark; entry = prev)
2309 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2310 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2311 prev = entry->Blink;
2312 if (!mod->LoadCount) free_modref( wm );
2315 /* check load order list too for modules that haven't been initialized yet */
2316 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2317 for (entry = mark->Blink; entry != mark; entry = prev)
2319 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2320 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2321 prev = entry->Blink;
2322 if (!mod->LoadCount) free_modref( wm );
2326 /***********************************************************************
2327 * MODULE_DecRefCount
2329 * The loader_section must be locked while calling this function.
2331 static void MODULE_DecRefCount( WINE_MODREF *wm )
2333 int i;
2335 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2336 return;
2338 if ( wm->ldr.LoadCount <= 0 )
2339 return;
2341 --wm->ldr.LoadCount;
2342 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2344 if ( wm->ldr.LoadCount == 0 )
2346 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2348 for ( i = 0; i < wm->nDeps; i++ )
2349 if ( wm->deps[i] )
2350 MODULE_DecRefCount( wm->deps[i] );
2352 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2356 /******************************************************************
2357 * LdrUnloadDll (NTDLL.@)
2361 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2363 NTSTATUS retv = STATUS_SUCCESS;
2365 TRACE("(%p)\n", hModule);
2367 RtlEnterCriticalSection( &loader_section );
2369 /* if we're stopping the whole process (and forcing the removal of all
2370 * DLLs) the library will be freed anyway
2372 if (!process_detaching)
2374 WINE_MODREF *wm;
2376 free_lib_count++;
2377 if ((wm = get_modref( hModule )) != NULL)
2379 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2381 /* Recursively decrement reference counts */
2382 MODULE_DecRefCount( wm );
2384 /* Call process detach notifications */
2385 if ( free_lib_count <= 1 )
2387 process_detach( FALSE, NULL );
2388 MODULE_FlushModrefs();
2391 TRACE("END\n");
2393 else
2394 retv = STATUS_DLL_NOT_FOUND;
2396 free_lib_count--;
2399 RtlLeaveCriticalSection( &loader_section );
2401 return retv;
2404 /***********************************************************************
2405 * RtlImageNtHeader (NTDLL.@)
2407 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2409 IMAGE_NT_HEADERS *ret;
2411 __TRY
2413 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2415 ret = NULL;
2416 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2418 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2419 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2422 __EXCEPT_PAGE_FAULT
2424 return NULL;
2426 __ENDTRY
2427 return ret;
2431 /***********************************************************************
2432 * attach_process_dlls
2434 * Initial attach to all the dlls loaded by the process.
2436 static NTSTATUS attach_process_dlls( void *wm )
2438 NTSTATUS status;
2440 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2442 RtlEnterCriticalSection( &loader_section );
2443 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2445 if (last_failed_modref)
2446 ERR( "%s failed to initialize, aborting\n",
2447 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2448 return status;
2450 attach_implicitly_loaded_dlls( (LPVOID)1 );
2451 RtlLeaveCriticalSection( &loader_section );
2452 return status;
2456 /***********************************************************************
2457 * start_process
2459 static void start_process( void *kernel_start )
2461 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2464 /******************************************************************
2465 * LdrInitializeThunk (NTDLL.@)
2468 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2469 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2471 NTSTATUS status;
2472 WINE_MODREF *wm;
2473 LPCWSTR load_path;
2474 PEB *peb = NtCurrentTeb()->Peb;
2475 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2477 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2479 /* allocate the modref for the main exe (if not already done) */
2480 wm = get_modref( peb->ImageBaseAddress );
2481 assert( wm );
2482 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2484 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2485 exit(1);
2488 peb->LoaderLock = &loader_section;
2489 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2490 version_init( wm->ldr.FullDllName.Buffer );
2492 /* the main exe needs to be the first in the load order list */
2493 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2494 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2496 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2497 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2499 actctx_init();
2500 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2501 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2502 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2503 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2505 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2506 if (status != STATUS_SUCCESS) goto error;
2508 virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2509 virtual_clear_thread_stack();
2510 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2512 error:
2513 ERR( "Main exe initialization for %s failed, status %x\n",
2514 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2515 NtTerminateProcess( GetCurrentProcess(), status );
2519 /***********************************************************************
2520 * RtlImageDirectoryEntryToData (NTDLL.@)
2522 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2524 const IMAGE_NT_HEADERS *nt;
2525 DWORD addr;
2527 if ((ULONG_PTR)module & 1) /* mapped as data file */
2529 module = (HMODULE)((ULONG_PTR)module & ~1);
2530 image = FALSE;
2532 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2533 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2535 const IMAGE_NT_HEADERS64 *nt64 = (IMAGE_NT_HEADERS64 *)nt;
2537 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2538 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2539 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2540 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2542 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2544 const IMAGE_NT_HEADERS32 *nt32 = (IMAGE_NT_HEADERS32 *)nt;
2546 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2547 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2548 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2549 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2551 else return NULL;
2553 /* not mapped as image, need to find the section containing the virtual address */
2554 return RtlImageRvaToVa( nt, module, addr, NULL );
2558 /***********************************************************************
2559 * RtlImageRvaToSection (NTDLL.@)
2561 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2562 HMODULE module, DWORD rva )
2564 int i;
2565 const IMAGE_SECTION_HEADER *sec;
2567 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2568 nt->FileHeader.SizeOfOptionalHeader);
2569 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2571 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2572 return (PIMAGE_SECTION_HEADER)sec;
2574 return NULL;
2578 /***********************************************************************
2579 * RtlImageRvaToVa (NTDLL.@)
2581 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2582 DWORD rva, IMAGE_SECTION_HEADER **section )
2584 IMAGE_SECTION_HEADER *sec;
2586 if (section && *section) /* try this section first */
2588 sec = *section;
2589 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2590 goto found;
2592 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2593 found:
2594 if (section) *section = sec;
2595 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2599 /***********************************************************************
2600 * RtlPcToFileHeader (NTDLL.@)
2602 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2604 LDR_MODULE *module;
2605 PVOID ret = NULL;
2607 RtlEnterCriticalSection( &loader_section );
2608 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2609 RtlLeaveCriticalSection( &loader_section );
2610 *address = ret;
2611 return ret;
2615 /***********************************************************************
2616 * NtLoadDriver (NTDLL.@)
2617 * ZwLoadDriver (NTDLL.@)
2619 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2621 FIXME("(%p), stub!\n",DriverServiceName);
2622 return STATUS_NOT_IMPLEMENTED;
2626 /***********************************************************************
2627 * NtUnloadDriver (NTDLL.@)
2628 * ZwUnloadDriver (NTDLL.@)
2630 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2632 FIXME("(%p), stub!\n",DriverServiceName);
2633 return STATUS_NOT_IMPLEMENTED;
2637 /******************************************************************
2638 * DllMain (NTDLL.@)
2640 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2642 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2643 return TRUE;
2647 /******************************************************************
2648 * __wine_init_windows_dir (NTDLL.@)
2650 * Windows and system dir initialization once kernel32 has been loaded.
2652 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2654 PLIST_ENTRY mark, entry;
2655 LPWSTR buffer, p;
2657 RtlCreateUnicodeString( &windows_dir, windir );
2658 RtlCreateUnicodeString( &system_dir, sysdir );
2659 strcpyW( user_shared_data->NtSystemRoot, windir );
2661 /* prepend the system dir to the name of the already created modules */
2662 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2663 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2665 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2667 assert( mod->Flags & LDR_WINE_INTERNAL );
2669 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2670 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2671 if (!buffer) continue;
2672 strcpyW( buffer, system_dir.Buffer );
2673 p = buffer + strlenW( buffer );
2674 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2675 strcpyW( p, mod->FullDllName.Buffer );
2676 RtlInitUnicodeString( &mod->FullDllName, buffer );
2677 RtlInitUnicodeString( &mod->BaseDllName, p );
2682 /***********************************************************************
2683 * __wine_process_init
2685 void __wine_process_init(void)
2687 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2689 WINE_MODREF *wm;
2690 NTSTATUS status;
2691 ANSI_STRING func_name;
2692 void (* DECLSPEC_NORETURN CDECL init_func)(void);
2693 extern mode_t FILE_umask;
2695 main_exe_file = thread_init();
2697 /* retrieve current umask */
2698 FILE_umask = umask(0777);
2699 umask( FILE_umask );
2701 /* setup the load callback and create ntdll modref */
2702 wine_dll_set_callback( load_builtin_callback );
2704 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2706 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2707 exit(1);
2709 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2710 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2712 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2713 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2714 0, (void **)&init_func )) != STATUS_SUCCESS)
2716 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2717 exit(1);
2719 init_func();