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
23 #include "wine/port.h"
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
35 #define WIN32_NO_STATUS
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"
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[] =
69 NULL, NULL, NULL, NULL,
73 static const WCHAR dllW[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
80 struct _wine_modref **deps;
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;
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_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
120 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
122 /* convert PE image VirtualAddress to Real Address */
123 static inline void *get_rva( HMODULE module, DWORD va )
125 return (void *)((char *)module + va);
128 /* check whether the file name contains a path */
129 static inline int contains_path( LPCWSTR name )
131 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
134 /* convert from straight ASCII to Unicode without depending on the current codepage */
135 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
137 while (len--) *dst++ = (unsigned char)*src++;
141 /*************************************************************************
142 * call_dll_entry_point
144 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
145 * their entry point, so we need a small asm wrapper.
148 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
149 __ASM_GLOBAL_FUNC(call_dll_entry_point,
151 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
152 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
154 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
156 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
161 "movl 8(%ebp),%eax\n\t"
163 "leal -4(%ebp),%esp\n\t"
165 __ASM_CFI(".cfi_same_value %ebx\n\t")
167 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
168 __ASM_CFI(".cfi_same_value %ebp\n\t")
171 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
172 UINT reason, void *reserved )
174 return proc( module, reason, reserved );
176 #endif /* __i386__ */
179 #if defined(__i386__) || defined(__x86_64__)
180 /*************************************************************************
183 * Entry point for stub functions.
185 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
187 EXCEPTION_RECORD rec;
189 rec.ExceptionCode = EXCEPTION_WINE_STUB;
190 rec.ExceptionFlags = EH_NONCONTINUABLE;
191 rec.ExceptionRecord = NULL;
192 rec.ExceptionAddress = ret_addr;
193 rec.NumberParameters = 2;
194 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
195 rec.ExceptionInformation[1] = (ULONG_PTR)name;
196 for (;;) RtlRaiseException( &rec );
200 #include "pshpack1.h"
204 BYTE pushl1; /* pushl $name */
206 BYTE pushl2; /* pushl $dll */
208 BYTE call; /* call stub_entry_point */
214 BYTE movq_rdi[2]; /* movq $dll,%rdi */
216 BYTE movq_rsi[2]; /* movq $name,%rsi */
218 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
219 BYTE movq_rax[2]; /* movq $entry, %rax */
221 BYTE jmpq_rax[2]; /* jmp %rax */
226 /*************************************************************************
229 * Allocate a stub entry point.
231 static ULONG_PTR allocate_stub( const char *dll, const char *name )
233 #define MAX_SIZE 65536
234 static struct stub *stubs;
235 static unsigned int nb_stubs;
238 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
242 SIZE_T size = MAX_SIZE;
243 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
244 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
247 stub = &stubs[nb_stubs++];
249 stub->pushl1 = 0x68; /* pushl $name */
251 stub->pushl2 = 0x68; /* pushl $dll */
253 stub->call = 0xe8; /* call stub_entry_point */
254 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
256 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
257 stub->movq_rdi[1] = 0xbf;
259 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
260 stub->movq_rsi[1] = 0xbe;
262 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
263 stub->movq_rsp_rdx[1] = 0x8b;
264 stub->movq_rsp_rdx[2] = 0x14;
265 stub->movq_rsp_rdx[3] = 0x24;
266 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
267 stub->movq_rax[1] = 0xb8;
268 stub->entry = stub_entry_point;
269 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
270 stub->jmpq_rax[1] = 0xe0;
272 return (ULONG_PTR)stub;
276 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
277 #endif /* __i386__ */
280 /*************************************************************************
283 * Looks for the referenced HMODULE in the current process
284 * The loader_section must be locked while calling this function.
286 static WINE_MODREF *get_modref( HMODULE hmod )
288 PLIST_ENTRY mark, entry;
291 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
293 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
294 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
296 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
297 if (mod->BaseAddress == hmod)
298 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
299 if (mod->BaseAddress > (void*)hmod) break;
305 /**********************************************************************
306 * find_basename_module
308 * Find a module from its base name.
309 * The loader_section must be locked while calling this function
311 static WINE_MODREF *find_basename_module( LPCWSTR name )
313 PLIST_ENTRY mark, entry;
315 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
316 return cached_modref;
318 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
319 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
321 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
322 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
324 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
325 return cached_modref;
332 /**********************************************************************
333 * find_fullname_module
335 * Find a module from its full path name.
336 * The loader_section must be locked while calling this function
338 static WINE_MODREF *find_fullname_module( LPCWSTR name )
340 PLIST_ENTRY mark, entry;
342 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
343 return cached_modref;
345 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
346 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
348 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
349 if (!strcmpiW( name, mod->FullDllName.Buffer ))
351 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
352 return cached_modref;
359 /*************************************************************************
360 * find_forwarded_export
362 * Find the final function pointer for a forwarded function.
363 * The loader_section must be locked while calling this function.
365 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
367 const IMAGE_EXPORT_DIRECTORY *exports;
371 const char *end = strrchr(forward, '.');
374 if (!end) return NULL;
375 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
376 ascii_to_unicode( mod_name, forward, end - forward );
377 mod_name[end - forward] = 0;
378 if (!strchrW( mod_name, '.' ))
380 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
381 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
384 if (!(wm = find_basename_module( mod_name )))
386 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
387 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
388 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
390 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
392 LdrUnloadDll( wm->ldr.BaseAddress );
399 ERR( "module not found for forward '%s' used by %s\n",
400 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
404 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
405 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
406 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1, load_path );
410 ERR("function not found for forward '%s' used by %s."
411 " If you are using builtin %s, try using the native one instead.\n",
412 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
413 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
419 /*************************************************************************
420 * find_ordinal_export
422 * Find an exported function by ordinal.
423 * The exports base must have been subtracted from the ordinal already.
424 * The loader_section must be locked while calling this function.
426 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
427 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
430 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
432 if (ordinal >= exports->NumberOfFunctions)
434 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
437 if (!functions[ordinal]) return NULL;
439 proc = get_rva( module, functions[ordinal] );
441 /* if the address falls into the export dir, it's a forward */
442 if (((const char *)proc >= (const char *)exports) &&
443 ((const char *)proc < (const char *)exports + exp_size))
444 return find_forwarded_export( module, (const char *)proc, load_path );
448 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
449 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
453 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
454 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
460 /*************************************************************************
463 * Find an exported function by name.
464 * The loader_section must be locked while calling this function.
466 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
467 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
469 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
470 const DWORD *names = get_rva( module, exports->AddressOfNames );
471 int min = 0, max = exports->NumberOfNames - 1;
473 /* first check the hint */
474 if (hint >= 0 && hint <= max)
476 char *ename = get_rva( module, names[hint] );
477 if (!strcmp( ename, name ))
478 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
481 /* then do a binary search */
484 int res, pos = (min + max) / 2;
485 char *ename = get_rva( module, names[pos] );
486 if (!(res = strcmp( ename, name )))
487 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
488 if (res > 0) max = pos - 1;
496 /*************************************************************************
499 * Import the dll specified by the given import descriptor.
500 * The loader_section must be locked while calling this function.
502 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
507 const IMAGE_EXPORT_DIRECTORY *exports;
509 const IMAGE_THUNK_DATA *import_list;
510 IMAGE_THUNK_DATA *thunk_list;
512 const char *name = get_rva( module, descr->Name );
513 DWORD len = strlen(name);
515 SIZE_T protect_size = 0;
518 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
519 if (descr->u.OriginalFirstThunk)
520 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
522 import_list = thunk_list;
524 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
526 if (len * sizeof(WCHAR) < sizeof(buffer))
528 ascii_to_unicode( buffer, name, len );
530 status = load_dll( load_path, buffer, 0, &wmImp );
532 else /* need to allocate a larger buffer */
534 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
535 if (!ptr) return NULL;
536 ascii_to_unicode( ptr, name, len );
538 status = load_dll( load_path, ptr, 0, &wmImp );
539 RtlFreeHeap( GetProcessHeap(), 0, ptr );
544 if (status == STATUS_DLL_NOT_FOUND)
545 ERR("Library %s (which is needed by %s) not found\n",
546 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
548 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
549 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
553 /* unprotect the import address table since it can be located in
554 * readonly section */
555 while (import_list[protect_size].u1.Ordinal) protect_size++;
556 protect_base = thunk_list;
557 protect_size *= sizeof(*thunk_list);
558 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
559 &protect_size, PAGE_WRITECOPY, &protect_old );
561 imp_mod = wmImp->ldr.BaseAddress;
562 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
566 /* set all imported function to deadbeef */
567 while (import_list->u1.Ordinal)
569 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
571 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
572 WARN("No implementation for %s.%d", name, ordinal );
573 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
577 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
578 WARN("No implementation for %s.%s", name, pe_name->Name );
579 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
581 WARN(" imported from %s, allocating stub %p\n",
582 debugstr_w(current_modref->ldr.FullDllName.Buffer),
583 (void *)thunk_list->u1.Function );
590 while (import_list->u1.Ordinal)
592 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
594 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
596 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
597 ordinal - exports->Base, load_path );
598 if (!thunk_list->u1.Function)
600 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
601 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
602 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
603 (void *)thunk_list->u1.Function );
605 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
607 else /* import by name */
609 IMAGE_IMPORT_BY_NAME *pe_name;
610 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
611 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
612 (const char*)pe_name->Name,
613 pe_name->Hint, load_path );
614 if (!thunk_list->u1.Function)
616 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
617 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
618 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
619 (void *)thunk_list->u1.Function );
621 TRACE_(imports)("--- %s %s.%d = %p\n",
622 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
629 /* restore old protection of the import address table */
630 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
635 /***********************************************************************
636 * create_module_activation_context
638 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
641 LDR_RESOURCE_INFO info;
642 const IMAGE_RESOURCE_DATA_ENTRY *entry;
644 info.Type = RT_MANIFEST;
645 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
647 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
650 ctx.cbSize = sizeof(ctx);
652 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
653 ctx.hModule = module->BaseAddress;
654 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
655 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
661 /****************************************************************
664 * Fixup all imports of a given module.
665 * The loader_section must be locked while calling this function.
667 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
670 const IMAGE_IMPORT_DESCRIPTOR *imports;
676 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
677 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
679 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
680 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
681 return STATUS_SUCCESS;
684 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
686 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
688 if (!create_module_activation_context( &wm->ldr ))
689 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
691 /* Allocate module dependency list */
692 wm->nDeps = nb_imports;
693 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
695 /* load the imported modules. They are automatically
696 * added to the modref list of the process.
698 prev = current_modref;
700 status = STATUS_SUCCESS;
701 for (i = 0; i < nb_imports; i++)
703 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
704 status = STATUS_DLL_NOT_FOUND;
706 current_modref = prev;
707 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
712 /*************************************************************************
713 * is_dll_native_subsystem
715 * Check if dll is a proper native driver.
716 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
717 * while being perfectly normal DLLs. This heuristic should catch such breakages.
719 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
721 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
722 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
723 const IMAGE_IMPORT_DESCRIPTOR *imports;
727 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
728 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
730 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
731 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
733 for (i = 0; imports[i].Name; i++)
735 const char *name = get_rva( module, imports[i].Name );
736 DWORD len = strlen(name);
737 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
738 ascii_to_unicode( buffer, name, len + 1 );
739 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
741 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
750 /*************************************************************************
753 * Allocate a WINE_MODREF structure and add it to the process list
754 * The loader_section must be locked while calling this function.
756 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
760 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
761 PLIST_ENTRY entry, mark;
763 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
768 wm->ldr.BaseAddress = hModule;
769 wm->ldr.EntryPoint = NULL;
770 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
771 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
772 wm->ldr.LoadCount = 1;
773 wm->ldr.TlsIndex = -1;
774 wm->ldr.SectionHandle = NULL;
775 wm->ldr.CheckSum = 0;
776 wm->ldr.TimeDateStamp = 0;
777 wm->ldr.ActivationContext = 0;
779 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
780 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
781 else p = wm->ldr.FullDllName.Buffer;
782 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
784 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
786 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
787 if (nt->OptionalHeader.AddressOfEntryPoint)
788 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
791 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
792 &wm->ldr.InLoadOrderModuleList);
794 /* insert module in MemoryList, sorted in increasing base addresses */
795 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
796 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
798 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
801 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
802 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
803 wm->ldr.InMemoryOrderModuleList.Flink = entry;
804 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
806 /* wait until init is called for inserting into this list */
807 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
808 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
810 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
812 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
813 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
814 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
820 /*************************************************************************
823 * Allocate the process-wide structure for module TLS storage.
825 static NTSTATUS alloc_process_tls(void)
827 PLIST_ENTRY mark, entry;
829 const IMAGE_TLS_DIRECTORY *dir;
832 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
833 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
835 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
836 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
837 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
839 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
841 tls_total_size += size;
844 if (!tls_module_count) return STATUS_SUCCESS;
846 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
848 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
849 if (!tls_dirs) return STATUS_NO_MEMORY;
851 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
853 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
854 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
855 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
858 *(DWORD *)dir->AddressOfIndex = i;
860 mod->LoadCount = -1; /* can't unload it */
863 return STATUS_SUCCESS;
867 /*************************************************************************
870 * Allocate the per-thread structure for module TLS storage.
872 static NTSTATUS alloc_thread_tls(void)
878 if (!tls_module_count) return STATUS_SUCCESS;
880 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
881 tls_module_count * sizeof(*pointers) )))
882 return STATUS_NO_MEMORY;
884 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
886 RtlFreeHeap( GetProcessHeap(), 0, pointers );
887 return STATUS_NO_MEMORY;
890 for (i = 0; i < tls_module_count; i++)
892 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
893 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
895 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
896 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
897 (void *)dir->StartAddressOfRawData, data );
900 memcpy( data, (void *)dir->StartAddressOfRawData, size );
902 memset( data, 0, dir->SizeOfZeroFill );
903 data += dir->SizeOfZeroFill;
905 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
906 return STATUS_SUCCESS;
910 /*************************************************************************
913 static void call_tls_callbacks( HMODULE module, UINT reason )
915 const IMAGE_TLS_DIRECTORY *dir;
916 const PIMAGE_TLS_CALLBACK *callback;
919 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
920 if (!dir || !dir->AddressOfCallBacks) return;
922 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
925 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
926 GetCurrentThreadId(), *callback, module, reason_names[reason] );
929 (*callback)( module, reason, NULL );
934 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
935 GetCurrentThreadId(), callback, module, reason_names[reason] );
940 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
941 GetCurrentThreadId(), *callback, module, reason_names[reason] );
946 /*************************************************************************
949 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
952 NTSTATUS status = STATUS_SUCCESS;
953 DLLENTRYPROC entry = wm->ldr.EntryPoint;
954 void *module = wm->ldr.BaseAddress;
957 /* Skip calls for modules loaded with special load flags */
959 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
960 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
961 if (!entry) return STATUS_SUCCESS;
965 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
966 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
967 mod_name[len / sizeof(WCHAR)] = 0;
968 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
969 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
970 reason_names[reason], lpReserved );
972 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
973 reason_names[reason], lpReserved );
977 retv = call_dll_entry_point( entry, module, reason, lpReserved );
979 status = STATUS_DLL_INIT_FAILED;
984 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
985 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
986 status = GetExceptionCode();
990 /* The state of the module list may have changed due to the call
991 to the dll. We cannot assume that this module has not been
994 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
995 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
996 reason_names[reason], lpReserved, retv );
997 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1003 /*************************************************************************
1006 * Send the process attach notification to all DLLs the given module
1007 * depends on (recursively). This is somewhat complicated due to the fact that
1009 * - we have to respect the module dependencies, i.e. modules implicitly
1010 * referenced by another module have to be initialized before the module
1011 * itself can be initialized
1013 * - the initialization routine of a DLL can itself call LoadLibrary,
1014 * thereby introducing a whole new set of dependencies (even involving
1015 * the 'old' modules) at any time during the whole process
1017 * (Note that this routine can be recursively entered not only directly
1018 * from itself, but also via LoadLibrary from one of the called initialization
1021 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1022 * the process *detach* notifications to be sent in the correct order.
1023 * This must not only take into account module dependencies, but also
1024 * 'hidden' dependencies created by modules calling LoadLibrary in their
1025 * attach notification routine.
1027 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1028 * list after the attach notification has returned. This implies that the
1029 * detach notifications are called in the reverse of the sequence the attach
1030 * notifications *returned*.
1032 * The loader_section must be locked while calling this function.
1034 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1036 NTSTATUS status = STATUS_SUCCESS;
1040 if (process_detaching) return status;
1042 /* prevent infinite recursion in case of cyclical dependencies */
1043 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1044 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1047 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1049 /* Tag current MODREF to prevent recursive loop */
1050 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1051 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1052 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1054 /* Recursively attach all DLLs this one depends on */
1055 for ( i = 0; i < wm->nDeps; i++ )
1057 if (!wm->deps[i]) continue;
1058 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1061 /* Call DLL entry point */
1062 if (status == STATUS_SUCCESS)
1064 WINE_MODREF *prev = current_modref;
1065 current_modref = wm;
1066 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1067 if (status == STATUS_SUCCESS)
1068 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1071 /* point to the name so LdrInitializeThunk can print it */
1072 last_failed_modref = wm;
1073 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1075 current_modref = prev;
1078 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1079 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1080 &wm->ldr.InInitializationOrderModuleList);
1082 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1083 /* Remove recursion flag */
1084 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1086 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1091 /**********************************************************************
1092 * attach_implicitly_loaded_dlls
1094 * Attach to the (builtin) dlls that have been implicitly loaded because
1095 * of a dependency at the Unix level, but not imported at the Win32 level.
1097 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1101 PLIST_ENTRY mark, entry;
1103 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1104 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1106 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1108 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1109 TRACE( "found implicitly loaded %s, attaching to it\n",
1110 debugstr_w(mod->BaseDllName.Buffer));
1111 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1112 break; /* restart the search from the start */
1114 if (entry == mark) break; /* nothing found */
1119 /*************************************************************************
1122 * Send DLL process detach notifications. See the comment about calling
1123 * sequence at process_attach. Unless the bForceDetach flag
1124 * is set, only DLLs with zero refcount are notified.
1126 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1128 PLIST_ENTRY mark, entry;
1131 RtlEnterCriticalSection( &loader_section );
1132 if (bForceDetach) process_detaching = 1;
1133 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1136 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1138 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1139 InInitializationOrderModuleList);
1140 /* Check whether to detach this DLL */
1141 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1143 if ( mod->LoadCount && !bForceDetach )
1146 /* Call detach notification */
1147 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1148 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1149 DLL_PROCESS_DETACH, lpReserved );
1151 /* Restart at head of WINE_MODREF list, as entries might have
1152 been added and/or removed while performing the call ... */
1155 } while (entry != mark);
1157 RtlLeaveCriticalSection( &loader_section );
1160 /*************************************************************************
1161 * MODULE_DllThreadAttach
1163 * Send DLL thread attach notifications. These are sent in the
1164 * reverse sequence of process detach notification.
1167 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1169 PLIST_ENTRY mark, entry;
1173 /* don't do any attach calls if process is exiting */
1174 if (process_detaching) return STATUS_SUCCESS;
1175 /* FIXME: there is still a race here */
1177 RtlEnterCriticalSection( &loader_section );
1179 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1181 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1182 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1184 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1185 InInitializationOrderModuleList);
1186 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1188 if ( mod->Flags & LDR_NO_DLL_CALLS )
1191 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1192 DLL_THREAD_ATTACH, lpReserved );
1196 RtlLeaveCriticalSection( &loader_section );
1200 /******************************************************************
1201 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1204 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1207 NTSTATUS ret = STATUS_SUCCESS;
1209 RtlEnterCriticalSection( &loader_section );
1211 wm = get_modref( hModule );
1212 if (!wm || wm->ldr.TlsIndex != -1)
1213 ret = STATUS_DLL_NOT_FOUND;
1215 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1217 RtlLeaveCriticalSection( &loader_section );
1222 /******************************************************************
1223 * LdrFindEntryForAddress (NTDLL.@)
1225 * The loader_section must be locked while calling this function
1227 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1229 PLIST_ENTRY mark, entry;
1232 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1233 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1235 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1236 if (mod->BaseAddress <= addr &&
1237 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1240 return STATUS_SUCCESS;
1242 if (mod->BaseAddress > addr) break;
1244 return STATUS_NO_MORE_ENTRIES;
1247 /******************************************************************
1248 * LdrLockLoaderLock (NTDLL.@)
1250 * Note: flags are not implemented.
1251 * Flag 0x01 is used to raise exceptions on errors.
1252 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1254 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1256 if (flags) FIXME( "flags %x not supported\n", flags );
1258 if (result) *result = 1;
1259 if (!magic) return STATUS_INVALID_PARAMETER_3;
1260 RtlEnterCriticalSection( &loader_section );
1261 *magic = GetCurrentThreadId();
1262 return STATUS_SUCCESS;
1266 /******************************************************************
1267 * LdrUnlockLoaderUnlock (NTDLL.@)
1269 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1273 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1274 RtlLeaveCriticalSection( &loader_section );
1276 return STATUS_SUCCESS;
1280 /******************************************************************
1281 * LdrGetProcedureAddress (NTDLL.@)
1283 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1284 ULONG ord, PVOID *address)
1286 IMAGE_EXPORT_DIRECTORY *exports;
1288 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1290 RtlEnterCriticalSection( &loader_section );
1292 /* check if the module itself is invalid to return the proper error */
1293 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1294 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1295 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1297 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1298 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1299 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1303 ret = STATUS_SUCCESS;
1307 RtlLeaveCriticalSection( &loader_section );
1312 /***********************************************************************
1315 * Check if a loaded native dll is a Wine fake dll.
1317 static BOOL is_fake_dll( HANDLE handle )
1319 static const char fakedll_signature[] = "Wine placeholder DLL";
1320 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1321 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1323 LARGE_INTEGER offset;
1325 offset.QuadPart = 0;
1326 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1327 if (io.Information < sizeof(buffer)) return FALSE;
1328 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1329 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1330 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1335 /***********************************************************************
1336 * get_builtin_fullname
1338 * Build the full pathname for a builtin dll.
1340 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1342 static const WCHAR soW[] = {'.','s','o',0};
1343 WCHAR *p, *fullname;
1344 size_t i, len = strlen(filename);
1346 /* check if path can correspond to the dll we have */
1347 if (path && (p = strrchrW( path, '\\' )))
1350 for (i = 0; i < len; i++)
1351 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1352 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1354 /* the filename matches, use path as the full path */
1356 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1358 memcpy( fullname, path, len * sizeof(WCHAR) );
1365 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1366 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1368 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1369 p = fullname + system_dir.Length / sizeof(WCHAR);
1370 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1371 ascii_to_unicode( p, filename, len + 1 );
1377 /***********************************************************************
1378 * load_builtin_callback
1380 * Load a library in memory; callback function for wine_dll_register
1382 static void load_builtin_callback( void *module, const char *filename )
1384 static const WCHAR emptyW[1];
1385 IMAGE_NT_HEADERS *nt;
1388 const WCHAR *load_path;
1392 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1395 if (!(nt = RtlImageNtHeader( module )))
1397 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1398 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1401 virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1402 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1403 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1405 /* create the MODREF */
1407 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1409 ERR( "can't load %s\n", filename );
1410 builtin_load_info->status = STATUS_NO_MEMORY;
1414 wm = alloc_module( module, fullname );
1415 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1418 ERR( "can't load %s\n", filename );
1419 builtin_load_info->status = STATUS_NO_MEMORY;
1422 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1424 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1425 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1427 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1433 load_path = builtin_load_info->load_path;
1434 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1435 if (!load_path) load_path = emptyW;
1436 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1438 /* the module has only be inserted in the load & memory order lists */
1439 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1440 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1441 /* FIXME: free the modref */
1442 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1447 builtin_load_info->wm = wm;
1448 TRACE( "loaded %s %p %p\n", filename, wm, module );
1450 /* send the DLL load event */
1452 SERVER_START_REQ( load_dll )
1455 req->base = wine_server_client_ptr( module );
1456 req->size = nt->OptionalHeader.SizeOfImage;
1457 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1458 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1459 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1460 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1461 wine_server_call( req );
1465 /* setup relay debugging entry points */
1466 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1470 /******************************************************************************
1471 * load_native_dll (internal)
1473 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1474 DWORD flags, WINE_MODREF** pwm )
1479 IMAGE_NT_HEADERS *nt;
1484 TRACE("Trying native dll %s\n", debugstr_w(name));
1487 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1488 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1489 if (status != STATUS_SUCCESS) return status;
1492 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1493 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1495 if (status != STATUS_SUCCESS) return status;
1497 /* create the MODREF */
1499 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1503 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1505 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1507 /* the module has only be inserted in the load & memory order lists */
1508 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1509 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1511 /* FIXME: there are several more dangling references
1512 * left. Including dlls loaded by this dll before the
1513 * failed one. Unrolling is rather difficult with the
1514 * current structure and we can leave them lying
1515 * around with no problems, so we don't care.
1516 * As these might reference our wm, we don't free it.
1522 /* send DLL load event */
1524 nt = RtlImageNtHeader( module );
1526 SERVER_START_REQ( load_dll )
1528 req->handle = wine_server_obj_handle( file );
1529 req->base = wine_server_client_ptr( module );
1530 req->size = nt->OptionalHeader.SizeOfImage;
1531 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1532 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1533 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1534 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1535 wine_server_call( req );
1539 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1541 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1543 wm->ldr.LoadCount = 1;
1545 return STATUS_SUCCESS;
1549 /***********************************************************************
1552 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1553 DWORD flags, WINE_MODREF** pwm )
1555 char error[256], dllname[MAX_PATH];
1556 const WCHAR *name, *p;
1558 void *handle = NULL;
1559 struct builtin_load_info info, *prev_info;
1561 /* Fix the name in case we have a full path and extension */
1563 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1564 if ((p = strrchrW( name, '/' ))) name = p + 1;
1566 /* load_library will modify info.status. Note also that load_library can be
1567 * called several times, if the .so file we're loading has dependencies.
1568 * info.status will gather all the errors we may get while loading all these
1571 info.load_path = load_path;
1572 info.filename = NULL;
1573 info.status = STATUS_SUCCESS;
1576 if (file) /* we have a real file, try to load it */
1578 UNICODE_STRING nt_name;
1579 ANSI_STRING unix_name;
1581 TRACE("Trying built-in %s\n", debugstr_w(path));
1583 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1584 return STATUS_DLL_NOT_FOUND;
1586 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1588 RtlFreeUnicodeString( &nt_name );
1589 return STATUS_DLL_NOT_FOUND;
1591 prev_info = builtin_load_info;
1592 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1593 builtin_load_info = &info;
1594 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1595 builtin_load_info = prev_info;
1596 RtlFreeUnicodeString( &nt_name );
1597 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1600 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1601 return STATUS_INVALID_IMAGE_FORMAT;
1608 TRACE("Trying built-in %s\n", debugstr_w(name));
1610 /* we don't want to depend on the current codepage here */
1611 len = strlenW( name ) + 1;
1612 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1613 for (i = 0; i < len; i++)
1615 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1616 dllname[i] = (char)name[i];
1617 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1620 prev_info = builtin_load_info;
1621 builtin_load_info = &info;
1622 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1623 builtin_load_info = prev_info;
1628 /* The file does not exist -> WARN() */
1629 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1630 return STATUS_DLL_NOT_FOUND;
1632 /* ERR() for all other errors (missing functions, ...) */
1633 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1634 return STATUS_PROCEDURE_NOT_FOUND;
1638 if (info.status != STATUS_SUCCESS)
1640 wine_dll_unload( handle );
1646 PLIST_ENTRY mark, entry;
1648 /* The constructor wasn't called, this means the .so is already
1649 * loaded under a different name. Try to find the wm for it. */
1651 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1652 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1654 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1655 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1657 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1658 TRACE( "Found %s at %p for builtin %s\n",
1659 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1663 wine_dll_unload( handle ); /* release the libdl refcount */
1664 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1665 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1669 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1670 info.wm->ldr.LoadCount = 1;
1671 info.wm->ldr.SectionHandle = handle;
1675 return STATUS_SUCCESS;
1679 /***********************************************************************
1682 * Find the full path (if any) of the dll from the activation context.
1684 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1686 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1687 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1689 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1690 ACTCTX_SECTION_KEYED_DATA data;
1691 UNICODE_STRING nameW;
1693 SIZE_T needed, size = 1024;
1696 RtlInitUnicodeString( &nameW, libname );
1697 data.cbSize = sizeof(data);
1698 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1699 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1701 if (status != STATUS_SUCCESS) return status;
1705 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1707 status = STATUS_NO_MEMORY;
1710 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1711 AssemblyDetailedInformationInActivationContext,
1712 info, size, &needed );
1713 if (status == STATUS_SUCCESS) break;
1714 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1715 RtlFreeHeap( GetProcessHeap(), 0, info );
1717 /* restart with larger buffer */
1720 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1722 status = STATUS_SXS_KEY_NOT_FOUND;
1726 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1728 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1731 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1733 /* manifest name does not match directory name, so it's not a global
1734 * windows/winsxs manifest; use the manifest directory name instead */
1735 dirlen = p - info->lpAssemblyManifestPath;
1736 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1737 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1739 status = STATUS_NO_MEMORY;
1742 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1744 strcpyW( p, libname );
1749 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1750 nameW.Length + 2*sizeof(WCHAR));
1752 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1754 status = STATUS_NO_MEMORY;
1757 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1758 p += windows_dir.Length / sizeof(WCHAR);
1759 memcpy( p, winsxsW, sizeof(winsxsW) );
1760 p += sizeof(winsxsW) / sizeof(WCHAR);
1761 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1762 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1764 strcpyW( p, libname );
1766 RtlFreeHeap( GetProcessHeap(), 0, info );
1767 RtlReleaseActivationContext( data.hActCtx );
1772 /***********************************************************************
1775 * Find the file (or already loaded module) for a given dll name.
1777 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1778 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1780 OBJECT_ATTRIBUTES attr;
1782 UNICODE_STRING nt_name;
1783 WCHAR *file_part, *ext, *dllname;
1786 /* first append .dll if needed */
1789 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1791 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1792 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1793 return STATUS_NO_MEMORY;
1794 strcpyW( dllname, libname );
1795 strcatW( dllname, dllW );
1799 nt_name.Buffer = NULL;
1801 if (!contains_path( libname ))
1804 WCHAR *fullname = NULL;
1806 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1808 status = find_actctx_dll( libname, &fullname );
1809 if (status == STATUS_SUCCESS)
1811 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1812 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1813 libname = dllname = fullname;
1815 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1817 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1822 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1824 /* we need to search for it */
1825 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1828 if (len >= *size) goto overflow;
1829 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1831 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1833 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1834 return STATUS_NO_MEMORY;
1836 attr.Length = sizeof(attr);
1837 attr.RootDirectory = 0;
1838 attr.Attributes = OBJ_CASE_INSENSITIVE;
1839 attr.ObjectName = &nt_name;
1840 attr.SecurityDescriptor = NULL;
1841 attr.SecurityQualityOfService = NULL;
1842 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1848 if (!contains_path( libname ))
1850 /* if libname doesn't contain a path at all, we simply return the name as is,
1851 * to be loaded as builtin */
1852 len = strlenW(libname) * sizeof(WCHAR);
1853 if (len >= *size) goto overflow;
1854 strcpyW( filename, libname );
1859 /* absolute path name, or relative path name but not found above */
1861 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1863 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1864 return STATUS_NO_MEMORY;
1866 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1867 if (len >= *size) goto overflow;
1868 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1869 if (!(*pwm = find_fullname_module( filename )) && handle)
1871 attr.Length = sizeof(attr);
1872 attr.RootDirectory = 0;
1873 attr.Attributes = OBJ_CASE_INSENSITIVE;
1874 attr.ObjectName = &nt_name;
1875 attr.SecurityDescriptor = NULL;
1876 attr.SecurityQualityOfService = NULL;
1877 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1880 RtlFreeUnicodeString( &nt_name );
1881 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1882 return STATUS_SUCCESS;
1885 RtlFreeUnicodeString( &nt_name );
1886 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1887 *size = len + sizeof(WCHAR);
1888 return STATUS_BUFFER_TOO_SMALL;
1892 /***********************************************************************
1893 * load_dll (internal)
1895 * Load a PE style module according to the load order.
1896 * The loader_section must be locked while calling this function.
1898 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1900 enum loadorder loadorder;
1904 WINE_MODREF *main_exe;
1908 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1912 size = sizeof(buffer);
1915 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1916 if (nts == STATUS_SUCCESS) break;
1917 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1918 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1919 /* grow the buffer and retry */
1920 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1923 if (*pwm) /* found already loaded module */
1925 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1927 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1929 TRACE("Found %s for %s at %p, count=%d\n",
1930 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1931 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1932 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1933 return STATUS_SUCCESS;
1936 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1937 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1939 if (handle && is_fake_dll( handle ))
1941 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1949 nts = STATUS_NO_MEMORY;
1952 nts = STATUS_DLL_NOT_FOUND;
1955 case LO_NATIVE_BUILTIN:
1956 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1959 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1960 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1961 /* not in PE format, maybe it's a builtin */
1962 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1964 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1965 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1968 case LO_BUILTIN_NATIVE:
1969 case LO_DEFAULT: /* default is builtin,native */
1970 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1971 if (!handle) break; /* nothing else we can try */
1972 /* file is not a builtin library, try without using the specified file */
1973 if (nts != STATUS_SUCCESS)
1974 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1975 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1976 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1978 /* stub-only dll, try native */
1979 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1980 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1981 nts = STATUS_DLL_NOT_FOUND;
1983 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1984 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1988 if (nts == STATUS_SUCCESS)
1990 /* Initialize DLL just loaded */
1991 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1992 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1993 (*pwm)->ldr.BaseAddress);
1994 if (handle) NtClose( handle );
1995 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1999 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2000 if (handle) NtClose( handle );
2001 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2005 /******************************************************************
2006 * LdrLoadDll (NTDLL.@)
2008 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2009 const UNICODE_STRING *libname, HMODULE* hModule)
2014 RtlEnterCriticalSection( &loader_section );
2016 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2017 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2019 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2021 nts = process_attach( wm, NULL );
2022 if (nts != STATUS_SUCCESS)
2024 LdrUnloadDll(wm->ldr.BaseAddress);
2028 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2030 RtlLeaveCriticalSection( &loader_section );
2035 /******************************************************************
2036 * LdrGetDllHandle (NTDLL.@)
2038 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2046 RtlEnterCriticalSection( &loader_section );
2048 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2051 size = sizeof(buffer);
2054 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2055 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2056 if (status != STATUS_BUFFER_TOO_SMALL) break;
2057 /* grow the buffer and retry */
2058 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2060 status = STATUS_NO_MEMORY;
2065 if (status == STATUS_SUCCESS)
2067 if (wm) *base = wm->ldr.BaseAddress;
2068 else status = STATUS_DLL_NOT_FOUND;
2071 RtlLeaveCriticalSection( &loader_section );
2072 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2077 /******************************************************************
2078 * LdrAddRefDll (NTDLL.@)
2080 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2082 NTSTATUS ret = STATUS_SUCCESS;
2085 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2087 RtlEnterCriticalSection( &loader_section );
2089 if ((wm = get_modref( module )))
2091 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2092 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2094 else ret = STATUS_INVALID_PARAMETER;
2096 RtlLeaveCriticalSection( &loader_section );
2101 /***********************************************************************
2102 * LdrProcessRelocationBlock (NTDLL.@)
2104 * Apply relocations to a given page of a mapped PE image.
2106 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2107 USHORT *relocs, INT_PTR delta )
2111 USHORT offset = *relocs & 0xfff;
2112 int type = *relocs >> 12;
2115 case IMAGE_REL_BASED_ABSOLUTE:
2118 case IMAGE_REL_BASED_HIGH:
2119 *(short *)((char *)page + offset) += HIWORD(delta);
2121 case IMAGE_REL_BASED_LOW:
2122 *(short *)((char *)page + offset) += LOWORD(delta);
2124 case IMAGE_REL_BASED_HIGHLOW:
2125 *(int *)((char *)page + offset) += delta;
2127 #elif defined(__x86_64__)
2128 case IMAGE_REL_BASED_DIR64:
2129 *(INT_PTR *)((char *)page + offset) += delta;
2133 FIXME("Unknown/unsupported fixup type %x.\n", type);
2138 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2142 /******************************************************************
2143 * LdrQueryProcessModuleInformation
2146 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2147 ULONG buf_size, ULONG* req_size)
2149 SYSTEM_MODULE* sm = &smi->Modules[0];
2150 ULONG size = sizeof(ULONG);
2151 NTSTATUS nts = STATUS_SUCCESS;
2154 PLIST_ENTRY mark, entry;
2158 smi->ModulesCount = 0;
2160 RtlEnterCriticalSection( &loader_section );
2161 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2162 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2164 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2165 size += sizeof(*sm);
2166 if (size <= buf_size)
2168 sm->Reserved1 = 0; /* FIXME */
2169 sm->Reserved2 = 0; /* FIXME */
2170 sm->ImageBaseAddress = mod->BaseAddress;
2171 sm->ImageSize = mod->SizeOfImage;
2172 sm->Flags = mod->Flags;
2174 sm->Rank = 0; /* FIXME */
2175 sm->Unknown = 0; /* FIXME */
2177 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2178 str.Buffer = (char*)sm->Name;
2179 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2180 ptr = strrchr(str.Buffer, '\\');
2181 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2183 smi->ModulesCount++;
2186 else nts = STATUS_INFO_LENGTH_MISMATCH;
2188 RtlLeaveCriticalSection( &loader_section );
2190 if (req_size) *req_size = size;
2196 /******************************************************************
2197 * RtlDllShutdownInProgress (NTDLL.@)
2199 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2201 return process_detaching;
2205 /******************************************************************
2206 * LdrShutdownProcess (NTDLL.@)
2209 void WINAPI LdrShutdownProcess(void)
2212 process_detach( TRUE, (LPVOID)1 );
2215 /******************************************************************
2216 * LdrShutdownThread (NTDLL.@)
2219 void WINAPI LdrShutdownThread(void)
2221 PLIST_ENTRY mark, entry;
2226 /* don't do any detach calls if process is exiting */
2227 if (process_detaching) return;
2228 /* FIXME: there is still a race here */
2230 RtlEnterCriticalSection( &loader_section );
2232 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2233 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2235 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2236 InInitializationOrderModuleList);
2237 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2239 if ( mod->Flags & LDR_NO_DLL_CALLS )
2242 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2243 DLL_THREAD_DETACH, NULL );
2246 RtlLeaveCriticalSection( &loader_section );
2247 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2251 /***********************************************************************
2255 static void free_modref( WINE_MODREF *wm )
2257 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2258 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2259 if (wm->ldr.InInitializationOrderModuleList.Flink)
2260 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2262 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2263 if (!TRACE_ON(module))
2264 TRACE_(loaddll)("Unloaded module %s : %s\n",
2265 debugstr_w(wm->ldr.FullDllName.Buffer),
2266 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2268 SERVER_START_REQ( unload_dll )
2270 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2271 wine_server_call( req );
2275 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2276 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2277 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2278 if (cached_modref == wm) cached_modref = NULL;
2279 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2280 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2281 RtlFreeHeap( GetProcessHeap(), 0, wm );
2284 /***********************************************************************
2285 * MODULE_FlushModrefs
2287 * Remove all unused modrefs and call the internal unloading routines
2288 * for the library type.
2290 * The loader_section must be locked while calling this function.
2292 static void MODULE_FlushModrefs(void)
2294 PLIST_ENTRY mark, entry, prev;
2298 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2299 for (entry = mark->Blink; entry != mark; entry = prev)
2301 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2302 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2303 prev = entry->Blink;
2304 if (!mod->LoadCount) free_modref( wm );
2307 /* check load order list too for modules that haven't been initialized yet */
2308 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2309 for (entry = mark->Blink; entry != mark; entry = prev)
2311 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2312 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2313 prev = entry->Blink;
2314 if (!mod->LoadCount) free_modref( wm );
2318 /***********************************************************************
2319 * MODULE_DecRefCount
2321 * The loader_section must be locked while calling this function.
2323 static void MODULE_DecRefCount( WINE_MODREF *wm )
2327 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2330 if ( wm->ldr.LoadCount <= 0 )
2333 --wm->ldr.LoadCount;
2334 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2336 if ( wm->ldr.LoadCount == 0 )
2338 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2340 for ( i = 0; i < wm->nDeps; i++ )
2342 MODULE_DecRefCount( wm->deps[i] );
2344 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2348 /******************************************************************
2349 * LdrUnloadDll (NTDLL.@)
2353 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2355 NTSTATUS retv = STATUS_SUCCESS;
2357 TRACE("(%p)\n", hModule);
2359 RtlEnterCriticalSection( &loader_section );
2361 /* if we're stopping the whole process (and forcing the removal of all
2362 * DLLs) the library will be freed anyway
2364 if (!process_detaching)
2369 if ((wm = get_modref( hModule )) != NULL)
2371 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2373 /* Recursively decrement reference counts */
2374 MODULE_DecRefCount( wm );
2376 /* Call process detach notifications */
2377 if ( free_lib_count <= 1 )
2379 process_detach( FALSE, NULL );
2380 MODULE_FlushModrefs();
2386 retv = STATUS_DLL_NOT_FOUND;
2391 RtlLeaveCriticalSection( &loader_section );
2396 /***********************************************************************
2397 * RtlImageNtHeader (NTDLL.@)
2399 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2401 IMAGE_NT_HEADERS *ret;
2405 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2408 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2410 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2411 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2423 /***********************************************************************
2424 * attach_process_dlls
2426 * Initial attach to all the dlls loaded by the process.
2428 static NTSTATUS attach_process_dlls( void *wm )
2432 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2434 RtlEnterCriticalSection( &loader_section );
2435 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2437 if (last_failed_modref)
2438 ERR( "%s failed to initialize, aborting\n",
2439 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2442 attach_implicitly_loaded_dlls( (LPVOID)1 );
2443 RtlLeaveCriticalSection( &loader_section );
2448 /***********************************************************************
2451 static void start_process( void *kernel_start )
2453 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2456 /******************************************************************
2457 * LdrInitializeThunk (NTDLL.@)
2460 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2461 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2466 PEB *peb = NtCurrentTeb()->Peb;
2467 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2469 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2471 /* allocate the modref for the main exe (if not already done) */
2472 wm = get_modref( peb->ImageBaseAddress );
2474 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2476 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2480 peb->LoaderLock = &loader_section;
2481 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2482 version_init( wm->ldr.FullDllName.Buffer );
2484 /* the main exe needs to be the first in the load order list */
2485 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2486 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2488 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2489 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2492 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2493 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2494 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2495 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2497 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2498 if (status != STATUS_SUCCESS) goto error;
2500 virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2501 virtual_clear_thread_stack();
2502 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2505 ERR( "Main exe initialization for %s failed, status %x\n",
2506 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2507 NtTerminateProcess( GetCurrentProcess(), status );
2511 /***********************************************************************
2512 * RtlImageDirectoryEntryToData (NTDLL.@)
2514 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2516 const IMAGE_NT_HEADERS *nt;
2519 if ((ULONG_PTR)module & 1) /* mapped as data file */
2521 module = (HMODULE)((ULONG_PTR)module & ~1);
2524 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2525 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2526 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2527 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2528 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2530 /* not mapped as image, need to find the section containing the virtual address */
2531 return RtlImageRvaToVa( nt, module, addr, NULL );
2535 /***********************************************************************
2536 * RtlImageRvaToSection (NTDLL.@)
2538 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2539 HMODULE module, DWORD rva )
2542 const IMAGE_SECTION_HEADER *sec;
2544 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2545 nt->FileHeader.SizeOfOptionalHeader);
2546 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2548 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2549 return (PIMAGE_SECTION_HEADER)sec;
2555 /***********************************************************************
2556 * RtlImageRvaToVa (NTDLL.@)
2558 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2559 DWORD rva, IMAGE_SECTION_HEADER **section )
2561 IMAGE_SECTION_HEADER *sec;
2563 if (section && *section) /* try this section first */
2566 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2569 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2571 if (section) *section = sec;
2572 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2576 /***********************************************************************
2577 * RtlPcToFileHeader (NTDLL.@)
2579 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2584 RtlEnterCriticalSection( &loader_section );
2585 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2586 RtlLeaveCriticalSection( &loader_section );
2592 /***********************************************************************
2593 * NtLoadDriver (NTDLL.@)
2594 * ZwLoadDriver (NTDLL.@)
2596 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2598 FIXME("(%p), stub!\n",DriverServiceName);
2599 return STATUS_NOT_IMPLEMENTED;
2603 /***********************************************************************
2604 * NtUnloadDriver (NTDLL.@)
2605 * ZwUnloadDriver (NTDLL.@)
2607 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2609 FIXME("(%p), stub!\n",DriverServiceName);
2610 return STATUS_NOT_IMPLEMENTED;
2614 /******************************************************************
2617 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2619 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2624 /******************************************************************
2625 * __wine_init_windows_dir (NTDLL.@)
2627 * Windows and system dir initialization once kernel32 has been loaded.
2629 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2631 PLIST_ENTRY mark, entry;
2634 RtlCreateUnicodeString( &windows_dir, windir );
2635 RtlCreateUnicodeString( &system_dir, sysdir );
2636 strcpyW( user_shared_data->NtSystemRoot, windir );
2638 /* prepend the system dir to the name of the already created modules */
2639 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2640 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2642 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2644 assert( mod->Flags & LDR_WINE_INTERNAL );
2646 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2647 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2648 if (!buffer) continue;
2649 strcpyW( buffer, system_dir.Buffer );
2650 p = buffer + strlenW( buffer );
2651 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2652 strcpyW( p, mod->FullDllName.Buffer );
2653 RtlInitUnicodeString( &mod->FullDllName, buffer );
2654 RtlInitUnicodeString( &mod->BaseDllName, p );
2659 /***********************************************************************
2660 * __wine_process_init
2662 void __wine_process_init(void)
2664 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2668 ANSI_STRING func_name;
2669 void (* DECLSPEC_NORETURN CDECL init_func)(void);
2670 extern mode_t FILE_umask;
2672 main_exe_file = thread_init();
2674 /* retrieve current umask */
2675 FILE_umask = umask(0777);
2676 umask( FILE_umask );
2678 /* setup the load callback and create ntdll modref */
2679 wine_dll_set_callback( load_builtin_callback );
2681 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2683 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2686 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2687 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2689 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2690 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2691 0, (void **)&init_func )) != STATUS_SUCCESS)
2693 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );