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/pthread.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45 #include "wine/server.h"
46 #include "ntdll_misc.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(module);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 WINE_DECLARE_DEBUG_CHANNEL(snoop);
52 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
53 WINE_DECLARE_DEBUG_CHANNEL(imports);
55 /* we don't want to include winuser.h */
56 #define RT_MANIFEST ((ULONG_PTR)24)
57 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
59 extern struct wine_pthread_functions pthread_functions;
61 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
63 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
64 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
66 static const char * const reason_names[] =
72 NULL, NULL, NULL, NULL,
76 static const WCHAR dllW[] = {'.','d','l','l',0};
78 /* internal representation of 32bit modules. per process. */
79 typedef struct _wine_modref
83 struct _wine_modref **deps;
86 /* info about the current builtin dll load */
87 /* used to keep track of things across the register_dll constructor call */
88 struct builtin_load_info
90 const WCHAR *load_path;
91 const WCHAR *filename;
96 static struct builtin_load_info default_load_info;
97 static struct builtin_load_info *builtin_load_info = &default_load_info;
99 static HANDLE main_exe_file;
100 static UINT tls_module_count; /* number of modules with TLS directory */
101 static UINT tls_total_size; /* total size of TLS storage */
102 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
104 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
105 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
107 static RTL_CRITICAL_SECTION loader_section;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 0, 0, &loader_section,
111 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
114 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
116 static WINE_MODREF *cached_modref;
117 static WINE_MODREF *current_modref;
118 static WINE_MODREF *last_failed_modref;
120 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
121 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
122 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
123 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
125 /* convert PE image VirtualAddress to Real Address */
126 static inline void *get_rva( HMODULE module, DWORD va )
128 return (void *)((char *)module + va);
131 /* check whether the file name contains a path */
132 static inline int contains_path( LPCWSTR name )
134 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
137 /* convert from straight ASCII to Unicode without depending on the current codepage */
138 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
140 while (len--) *dst++ = (unsigned char)*src++;
144 /*************************************************************************
145 * call_dll_entry_point
147 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
148 * their entry point, so we need a small asm wrapper.
151 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
152 __ASM_GLOBAL_FUNC(call_dll_entry_point,
160 "movl 8(%ebp),%eax\n\t"
162 "leal -4(%ebp),%esp\n\t"
167 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
168 UINT reason, void *reserved )
170 return proc( module, reason, reserved );
172 #endif /* __i386__ */
176 /*************************************************************************
179 * Entry point for stub functions.
181 static void stub_entry_point( const char *dll, const char *name, ... )
183 EXCEPTION_RECORD rec;
185 rec.ExceptionCode = EXCEPTION_WINE_STUB;
186 rec.ExceptionFlags = EH_NONCONTINUABLE;
187 rec.ExceptionRecord = NULL;
189 rec.ExceptionAddress = __builtin_return_address(0);
191 rec.ExceptionAddress = *((void **)&dll - 1);
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"
203 BYTE popl_eax; /* popl %eax */
204 BYTE pushl1; /* pushl $name */
206 BYTE pushl2; /* pushl $dll */
208 BYTE pushl_eax; /* pushl %eax */
209 BYTE jmp; /* jmp stub_entry_point */
214 /*************************************************************************
217 * Allocate a stub entry point.
219 static ULONG_PTR allocate_stub( const char *dll, const char *name )
221 #define MAX_SIZE 65536
222 static struct stub *stubs;
223 static unsigned int nb_stubs;
226 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
230 SIZE_T size = MAX_SIZE;
231 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
232 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
235 stub = &stubs[nb_stubs++];
236 stub->popl_eax = 0x58; /* popl %eax */
237 stub->pushl1 = 0x68; /* pushl $name */
239 stub->pushl2 = 0x68; /* pushl $dll */
241 stub->pushl_eax = 0x50; /* pushl %eax */
242 stub->jmp = 0xe9; /* jmp stub_entry_point */
243 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
244 return (ULONG_PTR)stub;
248 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
249 #endif /* __i386__ */
252 /*************************************************************************
255 * Looks for the referenced HMODULE in the current process
256 * The loader_section must be locked while calling this function.
258 static WINE_MODREF *get_modref( HMODULE hmod )
260 PLIST_ENTRY mark, entry;
263 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
265 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
266 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
268 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
269 if (mod->BaseAddress == hmod)
270 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
271 if (mod->BaseAddress > (void*)hmod) break;
277 /**********************************************************************
278 * find_basename_module
280 * Find a module from its base name.
281 * The loader_section must be locked while calling this function
283 static WINE_MODREF *find_basename_module( LPCWSTR name )
285 PLIST_ENTRY mark, entry;
287 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
288 return cached_modref;
290 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
291 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
293 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
294 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
296 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
297 return cached_modref;
304 /**********************************************************************
305 * find_fullname_module
307 * Find a module from its full path name.
308 * The loader_section must be locked while calling this function
310 static WINE_MODREF *find_fullname_module( LPCWSTR name )
312 PLIST_ENTRY mark, entry;
314 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
315 return cached_modref;
317 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
318 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
320 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
321 if (!strcmpiW( name, mod->FullDllName.Buffer ))
323 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
324 return cached_modref;
331 /*************************************************************************
332 * find_forwarded_export
334 * Find the final function pointer for a forwarded function.
335 * The loader_section must be locked while calling this function.
337 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
339 const IMAGE_EXPORT_DIRECTORY *exports;
343 const char *end = strrchr(forward, '.');
346 if (!end) return NULL;
347 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
348 ascii_to_unicode( mod_name, forward, end - forward );
349 mod_name[end - forward] = 0;
350 if (!strchrW( mod_name, '.' ))
352 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
353 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
356 if (!(wm = find_basename_module( mod_name )))
358 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
359 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
360 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
362 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
364 LdrUnloadDll( wm->ldr.BaseAddress );
371 ERR( "module not found for forward '%s' used by %s\n",
372 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
376 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
377 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
378 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1, load_path );
382 ERR("function not found for forward '%s' used by %s."
383 " If you are using builtin %s, try using the native one instead.\n",
384 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
385 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
391 /*************************************************************************
392 * find_ordinal_export
394 * Find an exported function by ordinal.
395 * The exports base must have been subtracted from the ordinal already.
396 * The loader_section must be locked while calling this function.
398 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
399 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
402 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
404 if (ordinal >= exports->NumberOfFunctions)
406 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
409 if (!functions[ordinal]) return NULL;
411 proc = get_rva( module, functions[ordinal] );
413 /* if the address falls into the export dir, it's a forward */
414 if (((const char *)proc >= (const char *)exports) &&
415 ((const char *)proc < (const char *)exports + exp_size))
416 return find_forwarded_export( module, (const char *)proc, load_path );
420 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
421 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
425 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
426 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
432 /*************************************************************************
435 * Find an exported function by name.
436 * The loader_section must be locked while calling this function.
438 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
439 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
441 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
442 const DWORD *names = get_rva( module, exports->AddressOfNames );
443 int min = 0, max = exports->NumberOfNames - 1;
445 /* first check the hint */
446 if (hint >= 0 && hint <= max)
448 char *ename = get_rva( module, names[hint] );
449 if (!strcmp( ename, name ))
450 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
453 /* then do a binary search */
456 int res, pos = (min + max) / 2;
457 char *ename = get_rva( module, names[pos] );
458 if (!(res = strcmp( ename, name )))
459 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
460 if (res > 0) max = pos - 1;
468 /*************************************************************************
471 * Import the dll specified by the given import descriptor.
472 * The loader_section must be locked while calling this function.
474 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
479 const IMAGE_EXPORT_DIRECTORY *exports;
481 const IMAGE_THUNK_DATA *import_list;
482 IMAGE_THUNK_DATA *thunk_list;
484 const char *name = get_rva( module, descr->Name );
485 DWORD len = strlen(name);
487 SIZE_T protect_size = 0;
490 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
491 if (descr->u.OriginalFirstThunk)
492 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
494 import_list = thunk_list;
496 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
498 if (len * sizeof(WCHAR) < sizeof(buffer))
500 ascii_to_unicode( buffer, name, len );
502 status = load_dll( load_path, buffer, 0, &wmImp );
504 else /* need to allocate a larger buffer */
506 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
507 if (!ptr) return NULL;
508 ascii_to_unicode( ptr, name, len );
510 status = load_dll( load_path, ptr, 0, &wmImp );
511 RtlFreeHeap( GetProcessHeap(), 0, ptr );
516 if (status == STATUS_DLL_NOT_FOUND)
517 ERR("Library %s (which is needed by %s) not found\n",
518 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
520 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
521 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
525 /* unprotect the import address table since it can be located in
526 * readonly section */
527 while (import_list[protect_size].u1.Ordinal) protect_size++;
528 protect_base = thunk_list;
529 protect_size *= sizeof(*thunk_list);
530 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
531 &protect_size, PAGE_WRITECOPY, &protect_old );
533 imp_mod = wmImp->ldr.BaseAddress;
534 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
538 /* set all imported function to deadbeef */
539 while (import_list->u1.Ordinal)
541 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
543 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
544 WARN("No implementation for %s.%d", name, ordinal );
545 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
549 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
550 WARN("No implementation for %s.%s", name, pe_name->Name );
551 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
553 WARN(" imported from %s, allocating stub %p\n",
554 debugstr_w(current_modref->ldr.FullDllName.Buffer),
555 (void *)thunk_list->u1.Function );
562 while (import_list->u1.Ordinal)
564 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
566 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
568 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
569 ordinal - exports->Base, load_path );
570 if (!thunk_list->u1.Function)
572 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
573 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
574 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
575 (void *)thunk_list->u1.Function );
577 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
579 else /* import by name */
581 IMAGE_IMPORT_BY_NAME *pe_name;
582 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
583 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
584 (const char*)pe_name->Name,
585 pe_name->Hint, load_path );
586 if (!thunk_list->u1.Function)
588 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
589 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
590 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
591 (void *)thunk_list->u1.Function );
593 TRACE_(imports)("--- %s %s.%d = %p\n",
594 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
601 /* restore old protection of the import address table */
602 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
607 /***********************************************************************
608 * create_module_activation_context
610 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
613 LDR_RESOURCE_INFO info;
614 const IMAGE_RESOURCE_DATA_ENTRY *entry;
616 info.Type = RT_MANIFEST;
617 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
619 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
622 ctx.cbSize = sizeof(ctx);
624 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
625 ctx.hModule = module->BaseAddress;
626 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
627 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
633 /****************************************************************
636 * Fixup all imports of a given module.
637 * The loader_section must be locked while calling this function.
639 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
642 const IMAGE_IMPORT_DESCRIPTOR *imports;
648 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
649 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
651 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
652 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
653 return STATUS_SUCCESS;
656 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
658 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
660 if (!create_module_activation_context( &wm->ldr ))
661 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
663 /* Allocate module dependency list */
664 wm->nDeps = nb_imports;
665 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
667 /* load the imported modules. They are automatically
668 * added to the modref list of the process.
670 prev = current_modref;
672 status = STATUS_SUCCESS;
673 for (i = 0; i < nb_imports; i++)
675 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
676 status = STATUS_DLL_NOT_FOUND;
678 current_modref = prev;
679 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
684 /*************************************************************************
687 * Allocate a WINE_MODREF structure and add it to the process list
688 * The loader_section must be locked while calling this function.
690 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
694 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
695 PLIST_ENTRY entry, mark;
697 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
702 wm->ldr.BaseAddress = hModule;
703 wm->ldr.EntryPoint = NULL;
704 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
705 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
706 wm->ldr.LoadCount = 1;
707 wm->ldr.TlsIndex = -1;
708 wm->ldr.SectionHandle = NULL;
709 wm->ldr.CheckSum = 0;
710 wm->ldr.TimeDateStamp = 0;
711 wm->ldr.ActivationContext = 0;
713 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
714 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
715 else p = wm->ldr.FullDllName.Buffer;
716 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
718 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE &&
719 (nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
721 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
722 if (nt->OptionalHeader.AddressOfEntryPoint)
723 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
726 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
727 &wm->ldr.InLoadOrderModuleList);
729 /* insert module in MemoryList, sorted in increasing base addresses */
730 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
731 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
733 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
736 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
737 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
738 wm->ldr.InMemoryOrderModuleList.Flink = entry;
739 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
741 /* wait until init is called for inserting into this list */
742 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
743 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
745 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
747 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
748 VIRTUAL_SetForceExec( TRUE );
754 /*************************************************************************
757 * Allocate the process-wide structure for module TLS storage.
759 static NTSTATUS alloc_process_tls(void)
761 PLIST_ENTRY mark, entry;
763 const IMAGE_TLS_DIRECTORY *dir;
766 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
767 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
769 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
770 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
771 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
773 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
775 tls_total_size += size;
778 if (!tls_module_count) return STATUS_SUCCESS;
780 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
782 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
783 if (!tls_dirs) return STATUS_NO_MEMORY;
785 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
787 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
788 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
789 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
792 *(DWORD *)dir->AddressOfIndex = i;
794 mod->LoadCount = -1; /* can't unload it */
797 return STATUS_SUCCESS;
801 /*************************************************************************
804 * Allocate the per-thread structure for module TLS storage.
806 static NTSTATUS alloc_thread_tls(void)
812 if (!tls_module_count) return STATUS_SUCCESS;
814 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
815 tls_module_count * sizeof(*pointers) )))
816 return STATUS_NO_MEMORY;
818 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
820 RtlFreeHeap( GetProcessHeap(), 0, pointers );
821 return STATUS_NO_MEMORY;
824 for (i = 0; i < tls_module_count; i++)
826 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
827 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
829 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
830 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
831 (void *)dir->StartAddressOfRawData, data );
834 memcpy( data, (void *)dir->StartAddressOfRawData, size );
836 memset( data, 0, dir->SizeOfZeroFill );
837 data += dir->SizeOfZeroFill;
839 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
840 return STATUS_SUCCESS;
844 /*************************************************************************
847 static void call_tls_callbacks( HMODULE module, UINT reason )
849 const IMAGE_TLS_DIRECTORY *dir;
850 const PIMAGE_TLS_CALLBACK *callback;
853 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
854 if (!dir || !dir->AddressOfCallBacks) return;
856 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
859 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
860 GetCurrentThreadId(), *callback, module, reason_names[reason] );
863 (*callback)( module, reason, NULL );
868 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
869 GetCurrentThreadId(), callback, module, reason_names[reason] );
874 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
875 GetCurrentThreadId(), *callback, module, reason_names[reason] );
880 /*************************************************************************
883 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
886 NTSTATUS status = STATUS_SUCCESS;
887 DLLENTRYPROC entry = wm->ldr.EntryPoint;
888 void *module = wm->ldr.BaseAddress;
891 /* Skip calls for modules loaded with special load flags */
893 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
894 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
895 if (!entry) return STATUS_SUCCESS;
899 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
900 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
901 mod_name[len / sizeof(WCHAR)] = 0;
902 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
903 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
904 reason_names[reason], lpReserved );
906 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
907 reason_names[reason], lpReserved );
911 retv = call_dll_entry_point( entry, module, reason, lpReserved );
913 status = STATUS_DLL_INIT_FAILED;
918 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
919 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
920 status = GetExceptionCode();
924 /* The state of the module list may have changed due to the call
925 to the dll. We cannot assume that this module has not been
928 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
929 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
930 reason_names[reason], lpReserved, retv );
931 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
937 /*************************************************************************
940 * Send the process attach notification to all DLLs the given module
941 * depends on (recursively). This is somewhat complicated due to the fact that
943 * - we have to respect the module dependencies, i.e. modules implicitly
944 * referenced by another module have to be initialized before the module
945 * itself can be initialized
947 * - the initialization routine of a DLL can itself call LoadLibrary,
948 * thereby introducing a whole new set of dependencies (even involving
949 * the 'old' modules) at any time during the whole process
951 * (Note that this routine can be recursively entered not only directly
952 * from itself, but also via LoadLibrary from one of the called initialization
955 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
956 * the process *detach* notifications to be sent in the correct order.
957 * This must not only take into account module dependencies, but also
958 * 'hidden' dependencies created by modules calling LoadLibrary in their
959 * attach notification routine.
961 * The strategy is rather simple: we move a WINE_MODREF to the head of the
962 * list after the attach notification has returned. This implies that the
963 * detach notifications are called in the reverse of the sequence the attach
964 * notifications *returned*.
966 * The loader_section must be locked while calling this function.
968 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
970 NTSTATUS status = STATUS_SUCCESS;
974 if (process_detaching) return status;
976 /* prevent infinite recursion in case of cyclical dependencies */
977 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
978 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
981 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
983 /* Tag current MODREF to prevent recursive loop */
984 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
985 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
986 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
988 /* Recursively attach all DLLs this one depends on */
989 for ( i = 0; i < wm->nDeps; i++ )
991 if (!wm->deps[i]) continue;
992 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
995 /* Call DLL entry point */
996 if (status == STATUS_SUCCESS)
998 WINE_MODREF *prev = current_modref;
1000 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1001 if (status == STATUS_SUCCESS)
1002 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1005 /* point to the name so LdrInitializeThunk can print it */
1006 last_failed_modref = wm;
1007 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1009 current_modref = prev;
1012 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1013 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1014 &wm->ldr.InInitializationOrderModuleList);
1016 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1017 /* Remove recursion flag */
1018 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1020 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1025 /**********************************************************************
1026 * attach_implicitly_loaded_dlls
1028 * Attach to the (builtin) dlls that have been implicitly loaded because
1029 * of a dependency at the Unix level, but not imported at the Win32 level.
1031 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1035 PLIST_ENTRY mark, entry;
1037 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1038 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1040 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1042 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1043 TRACE( "found implicitly loaded %s, attaching to it\n",
1044 debugstr_w(mod->BaseDllName.Buffer));
1045 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1046 break; /* restart the search from the start */
1048 if (entry == mark) break; /* nothing found */
1053 /*************************************************************************
1056 * Send DLL process detach notifications. See the comment about calling
1057 * sequence at process_attach. Unless the bForceDetach flag
1058 * is set, only DLLs with zero refcount are notified.
1060 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1062 PLIST_ENTRY mark, entry;
1065 RtlEnterCriticalSection( &loader_section );
1066 if (bForceDetach) process_detaching = 1;
1067 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1070 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1072 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1073 InInitializationOrderModuleList);
1074 /* Check whether to detach this DLL */
1075 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1077 if ( mod->LoadCount && !bForceDetach )
1080 /* Call detach notification */
1081 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1082 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1083 DLL_PROCESS_DETACH, lpReserved );
1085 /* Restart at head of WINE_MODREF list, as entries might have
1086 been added and/or removed while performing the call ... */
1089 } while (entry != mark);
1091 RtlLeaveCriticalSection( &loader_section );
1094 /*************************************************************************
1095 * MODULE_DllThreadAttach
1097 * Send DLL thread attach notifications. These are sent in the
1098 * reverse sequence of process detach notification.
1101 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1103 PLIST_ENTRY mark, entry;
1107 /* don't do any attach calls if process is exiting */
1108 if (process_detaching) return STATUS_SUCCESS;
1109 /* FIXME: there is still a race here */
1111 RtlEnterCriticalSection( &loader_section );
1113 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1115 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1116 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1118 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1119 InInitializationOrderModuleList);
1120 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1122 if ( mod->Flags & LDR_NO_DLL_CALLS )
1125 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1126 DLL_THREAD_ATTACH, lpReserved );
1130 RtlLeaveCriticalSection( &loader_section );
1134 /******************************************************************
1135 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1138 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1141 NTSTATUS ret = STATUS_SUCCESS;
1143 RtlEnterCriticalSection( &loader_section );
1145 wm = get_modref( hModule );
1146 if (!wm || wm->ldr.TlsIndex != -1)
1147 ret = STATUS_DLL_NOT_FOUND;
1149 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1151 RtlLeaveCriticalSection( &loader_section );
1156 /******************************************************************
1157 * LdrFindEntryForAddress (NTDLL.@)
1159 * The loader_section must be locked while calling this function
1161 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1163 PLIST_ENTRY mark, entry;
1166 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1167 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1169 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1170 if ((const void *)mod->BaseAddress <= addr &&
1171 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1174 return STATUS_SUCCESS;
1176 if ((const void *)mod->BaseAddress > addr) break;
1178 return STATUS_NO_MORE_ENTRIES;
1181 /******************************************************************
1182 * LdrLockLoaderLock (NTDLL.@)
1184 * Note: flags are not implemented.
1185 * Flag 0x01 is used to raise exceptions on errors.
1186 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1188 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1190 if (flags) FIXME( "flags %x not supported\n", flags );
1192 if (result) *result = 1;
1193 if (!magic) return STATUS_INVALID_PARAMETER_3;
1194 RtlEnterCriticalSection( &loader_section );
1195 *magic = GetCurrentThreadId();
1196 return STATUS_SUCCESS;
1200 /******************************************************************
1201 * LdrUnlockLoaderUnlock (NTDLL.@)
1203 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1207 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1208 RtlLeaveCriticalSection( &loader_section );
1210 return STATUS_SUCCESS;
1214 /******************************************************************
1215 * LdrGetProcedureAddress (NTDLL.@)
1217 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1218 ULONG ord, PVOID *address)
1220 IMAGE_EXPORT_DIRECTORY *exports;
1222 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1224 RtlEnterCriticalSection( &loader_section );
1226 /* check if the module itself is invalid to return the proper error */
1227 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1228 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1229 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1231 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1232 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1233 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1237 ret = STATUS_SUCCESS;
1241 RtlLeaveCriticalSection( &loader_section );
1246 /***********************************************************************
1249 * Check if a loaded native dll is a Wine fake dll.
1251 static BOOL is_fake_dll( HANDLE handle )
1253 static const char fakedll_signature[] = "Wine placeholder DLL";
1254 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1255 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1257 LARGE_INTEGER offset;
1259 offset.QuadPart = 0;
1260 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1261 if (io.Information < sizeof(buffer)) return FALSE;
1262 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1263 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1264 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1269 /***********************************************************************
1270 * get_builtin_fullname
1272 * Build the full pathname for a builtin dll.
1274 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1276 static const WCHAR soW[] = {'.','s','o',0};
1277 WCHAR *p, *fullname;
1278 size_t i, len = strlen(filename);
1280 /* check if path can correspond to the dll we have */
1281 if (path && (p = strrchrW( path, '\\' )))
1284 for (i = 0; i < len; i++)
1285 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1286 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1288 /* the filename matches, use path as the full path */
1290 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1292 memcpy( fullname, path, len * sizeof(WCHAR) );
1299 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1300 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1302 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1303 p = fullname + system_dir.Length / sizeof(WCHAR);
1304 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1305 ascii_to_unicode( p, filename, len + 1 );
1311 /***********************************************************************
1312 * load_builtin_callback
1314 * Load a library in memory; callback function for wine_dll_register
1316 static void load_builtin_callback( void *module, const char *filename )
1318 static const WCHAR emptyW[1];
1319 IMAGE_NT_HEADERS *nt;
1322 const WCHAR *load_path;
1326 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1329 if (!(nt = RtlImageNtHeader( module )))
1331 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1332 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1335 virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1336 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1337 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1339 /* create the MODREF */
1341 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1343 ERR( "can't load %s\n", filename );
1344 builtin_load_info->status = STATUS_NO_MEMORY;
1348 wm = alloc_module( module, fullname );
1349 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1352 ERR( "can't load %s\n", filename );
1353 builtin_load_info->status = STATUS_NO_MEMORY;
1356 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1358 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1359 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1361 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1367 load_path = builtin_load_info->load_path;
1368 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1369 if (!load_path) load_path = emptyW;
1370 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1372 /* the module has only be inserted in the load & memory order lists */
1373 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1374 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1375 /* FIXME: free the modref */
1376 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1381 builtin_load_info->wm = wm;
1382 TRACE( "loaded %s %p %p\n", filename, wm, module );
1384 /* send the DLL load event */
1386 SERVER_START_REQ( load_dll )
1390 req->size = nt->OptionalHeader.SizeOfImage;
1391 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1392 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1393 req->name = &wm->ldr.FullDllName.Buffer;
1394 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1395 wine_server_call( req );
1399 /* setup relay debugging entry points */
1400 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1404 /******************************************************************************
1405 * load_native_dll (internal)
1407 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1408 DWORD flags, WINE_MODREF** pwm )
1412 OBJECT_ATTRIBUTES attr;
1414 IMAGE_NT_HEADERS *nt;
1419 TRACE("Trying native dll %s\n", debugstr_w(name));
1421 attr.Length = sizeof(attr);
1422 attr.RootDirectory = 0;
1423 attr.ObjectName = NULL;
1424 attr.Attributes = 0;
1425 attr.SecurityDescriptor = NULL;
1426 attr.SecurityQualityOfService = NULL;
1429 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1430 &attr, &size, 0, SEC_IMAGE, file );
1431 if (status != STATUS_SUCCESS) return status;
1434 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1435 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1437 if (status != STATUS_SUCCESS) return status;
1439 /* create the MODREF */
1441 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1445 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1447 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1449 /* the module has only be inserted in the load & memory order lists */
1450 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1451 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1453 /* FIXME: there are several more dangling references
1454 * left. Including dlls loaded by this dll before the
1455 * failed one. Unrolling is rather difficult with the
1456 * current structure and we can leave them lying
1457 * around with no problems, so we don't care.
1458 * As these might reference our wm, we don't free it.
1464 /* send DLL load event */
1466 nt = RtlImageNtHeader( module );
1468 SERVER_START_REQ( load_dll )
1470 req->handle = wine_server_obj_handle( file );
1472 req->size = nt->OptionalHeader.SizeOfImage;
1473 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1474 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1475 req->name = &wm->ldr.FullDllName.Buffer;
1476 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1477 wine_server_call( req );
1481 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1483 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1485 wm->ldr.LoadCount = 1;
1487 return STATUS_SUCCESS;
1491 /***********************************************************************
1494 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1495 DWORD flags, WINE_MODREF** pwm )
1497 char error[256], dllname[MAX_PATH];
1498 const WCHAR *name, *p;
1500 void *handle = NULL;
1501 struct builtin_load_info info, *prev_info;
1503 /* Fix the name in case we have a full path and extension */
1505 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1506 if ((p = strrchrW( name, '/' ))) name = p + 1;
1508 /* load_library will modify info.status. Note also that load_library can be
1509 * called several times, if the .so file we're loading has dependencies.
1510 * info.status will gather all the errors we may get while loading all these
1513 info.load_path = load_path;
1514 info.filename = NULL;
1515 info.status = STATUS_SUCCESS;
1518 if (file) /* we have a real file, try to load it */
1520 UNICODE_STRING nt_name;
1521 ANSI_STRING unix_name;
1523 TRACE("Trying built-in %s\n", debugstr_w(path));
1525 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1526 return STATUS_DLL_NOT_FOUND;
1528 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1530 RtlFreeUnicodeString( &nt_name );
1531 return STATUS_DLL_NOT_FOUND;
1533 prev_info = builtin_load_info;
1534 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1535 builtin_load_info = &info;
1536 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1537 builtin_load_info = prev_info;
1538 RtlFreeUnicodeString( &nt_name );
1539 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1542 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1543 return STATUS_INVALID_IMAGE_FORMAT;
1550 TRACE("Trying built-in %s\n", debugstr_w(name));
1552 /* we don't want to depend on the current codepage here */
1553 len = strlenW( name ) + 1;
1554 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1555 for (i = 0; i < len; i++)
1557 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1558 dllname[i] = (char)name[i];
1559 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1562 prev_info = builtin_load_info;
1563 builtin_load_info = &info;
1564 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1565 builtin_load_info = prev_info;
1570 /* The file does not exist -> WARN() */
1571 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1572 return STATUS_DLL_NOT_FOUND;
1574 /* ERR() for all other errors (missing functions, ...) */
1575 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1576 return STATUS_PROCEDURE_NOT_FOUND;
1580 if (info.status != STATUS_SUCCESS)
1582 wine_dll_unload( handle );
1588 PLIST_ENTRY mark, entry;
1590 /* The constructor wasn't called, this means the .so is already
1591 * loaded under a different name. Try to find the wm for it. */
1593 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1594 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1596 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1597 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1599 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1600 TRACE( "Found %s at %p for builtin %s\n",
1601 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1605 wine_dll_unload( handle ); /* release the libdl refcount */
1606 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1607 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1611 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1612 info.wm->ldr.LoadCount = 1;
1613 info.wm->ldr.SectionHandle = handle;
1617 return STATUS_SUCCESS;
1621 /***********************************************************************
1624 * Find the full path (if any) of the dll from the activation context.
1626 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1628 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1629 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1631 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1632 ACTCTX_SECTION_KEYED_DATA data;
1633 UNICODE_STRING nameW;
1635 SIZE_T needed, size = 1024;
1638 RtlInitUnicodeString( &nameW, libname );
1639 data.cbSize = sizeof(data);
1640 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1641 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1643 if (status != STATUS_SUCCESS) return status;
1647 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1649 status = STATUS_NO_MEMORY;
1652 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1653 AssemblyDetailedInformationInActivationContext,
1654 info, size, &needed );
1655 if (status == STATUS_SUCCESS) break;
1656 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1657 RtlFreeHeap( GetProcessHeap(), 0, info );
1659 /* restart with larger buffer */
1662 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1664 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1667 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1669 /* manifest name does not match directory name, so it's not a global
1670 * windows/winsxs manifest; use the manifest directory name instead */
1671 dirlen = p - info->lpAssemblyManifestPath;
1672 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1673 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1675 status = STATUS_NO_MEMORY;
1678 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1680 strcpyW( p, libname );
1685 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1686 nameW.Length + 2*sizeof(WCHAR));
1688 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1690 status = STATUS_NO_MEMORY;
1693 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1694 p += windows_dir.Length / sizeof(WCHAR);
1695 memcpy( p, winsxsW, sizeof(winsxsW) );
1696 p += sizeof(winsxsW) / sizeof(WCHAR);
1697 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1698 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1700 strcpyW( p, libname );
1702 RtlFreeHeap( GetProcessHeap(), 0, info );
1703 RtlReleaseActivationContext( data.hActCtx );
1708 /***********************************************************************
1711 * Find the file (or already loaded module) for a given dll name.
1713 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1714 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1716 OBJECT_ATTRIBUTES attr;
1718 UNICODE_STRING nt_name;
1719 WCHAR *file_part, *ext, *dllname;
1722 /* first append .dll if needed */
1725 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1727 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1728 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1729 return STATUS_NO_MEMORY;
1730 strcpyW( dllname, libname );
1731 strcatW( dllname, dllW );
1735 nt_name.Buffer = NULL;
1737 if (!contains_path( libname ))
1740 WCHAR *fullname = NULL;
1742 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1744 status = find_actctx_dll( libname, &fullname );
1745 if (status == STATUS_SUCCESS)
1747 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1748 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1749 libname = dllname = fullname;
1751 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1753 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1758 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1760 /* we need to search for it */
1761 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1764 if (len >= *size) goto overflow;
1765 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1767 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1769 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1770 return STATUS_NO_MEMORY;
1772 attr.Length = sizeof(attr);
1773 attr.RootDirectory = 0;
1774 attr.Attributes = OBJ_CASE_INSENSITIVE;
1775 attr.ObjectName = &nt_name;
1776 attr.SecurityDescriptor = NULL;
1777 attr.SecurityQualityOfService = NULL;
1778 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1784 if (!contains_path( libname ))
1786 /* if libname doesn't contain a path at all, we simply return the name as is,
1787 * to be loaded as builtin */
1788 len = strlenW(libname) * sizeof(WCHAR);
1789 if (len >= *size) goto overflow;
1790 strcpyW( filename, libname );
1795 /* absolute path name, or relative path name but not found above */
1797 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1799 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1800 return STATUS_NO_MEMORY;
1802 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1803 if (len >= *size) goto overflow;
1804 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1805 if (!(*pwm = find_fullname_module( filename )) && handle)
1807 attr.Length = sizeof(attr);
1808 attr.RootDirectory = 0;
1809 attr.Attributes = OBJ_CASE_INSENSITIVE;
1810 attr.ObjectName = &nt_name;
1811 attr.SecurityDescriptor = NULL;
1812 attr.SecurityQualityOfService = NULL;
1813 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1816 RtlFreeUnicodeString( &nt_name );
1817 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1818 return STATUS_SUCCESS;
1821 RtlFreeUnicodeString( &nt_name );
1822 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1823 *size = len + sizeof(WCHAR);
1824 return STATUS_BUFFER_TOO_SMALL;
1828 /***********************************************************************
1829 * load_dll (internal)
1831 * Load a PE style module according to the load order.
1832 * The loader_section must be locked while calling this function.
1834 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1836 enum loadorder loadorder;
1840 WINE_MODREF *main_exe;
1844 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1848 size = sizeof(buffer);
1851 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1852 if (nts == STATUS_SUCCESS) break;
1853 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1854 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1855 /* grow the buffer and retry */
1856 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1859 if (*pwm) /* found already loaded module */
1861 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1863 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1865 TRACE("Found %s for %s at %p, count=%d\n",
1866 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1867 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1868 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1869 return STATUS_SUCCESS;
1872 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1873 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1875 if (handle && is_fake_dll( handle ))
1877 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1885 nts = STATUS_NO_MEMORY;
1888 nts = STATUS_DLL_NOT_FOUND;
1891 case LO_NATIVE_BUILTIN:
1892 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1895 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1896 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1897 /* not in PE format, maybe it's a builtin */
1898 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1900 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1901 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1904 case LO_BUILTIN_NATIVE:
1905 case LO_DEFAULT: /* default is builtin,native */
1906 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1907 if (!handle) break; /* nothing else we can try */
1908 /* file is not a builtin library, try without using the specified file */
1909 if (nts != STATUS_SUCCESS)
1910 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1911 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1912 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1914 /* stub-only dll, try native */
1915 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1916 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1917 nts = STATUS_DLL_NOT_FOUND;
1919 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1920 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1924 if (nts == STATUS_SUCCESS)
1926 /* Initialize DLL just loaded */
1927 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1928 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1929 (*pwm)->ldr.BaseAddress);
1930 if (handle) NtClose( handle );
1931 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1935 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1936 if (handle) NtClose( handle );
1937 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1941 /******************************************************************
1942 * LdrLoadDll (NTDLL.@)
1944 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1945 const UNICODE_STRING *libname, HMODULE* hModule)
1950 RtlEnterCriticalSection( &loader_section );
1952 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1953 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1955 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1957 nts = process_attach( wm, NULL );
1958 if (nts != STATUS_SUCCESS)
1960 LdrUnloadDll(wm->ldr.BaseAddress);
1964 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1966 RtlLeaveCriticalSection( &loader_section );
1971 /******************************************************************
1972 * LdrGetDllHandle (NTDLL.@)
1974 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1982 RtlEnterCriticalSection( &loader_section );
1984 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1987 size = sizeof(buffer);
1990 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1991 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1992 if (status != STATUS_BUFFER_TOO_SMALL) break;
1993 /* grow the buffer and retry */
1994 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1996 status = STATUS_NO_MEMORY;
2001 if (status == STATUS_SUCCESS)
2003 if (wm) *base = wm->ldr.BaseAddress;
2004 else status = STATUS_DLL_NOT_FOUND;
2007 RtlLeaveCriticalSection( &loader_section );
2008 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2013 /******************************************************************
2014 * LdrAddRefDll (NTDLL.@)
2016 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2018 NTSTATUS ret = STATUS_SUCCESS;
2021 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2023 RtlEnterCriticalSection( &loader_section );
2025 if ((wm = get_modref( module )))
2027 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2028 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2030 else ret = STATUS_INVALID_PARAMETER;
2032 RtlLeaveCriticalSection( &loader_section );
2037 /***********************************************************************
2038 * LdrProcessRelocationBlock (NTDLL.@)
2040 * Apply relocations to a given page of a mapped PE image.
2042 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2043 USHORT *relocs, INT delta )
2047 USHORT offset = *relocs & 0xfff;
2048 int type = *relocs >> 12;
2051 case IMAGE_REL_BASED_ABSOLUTE:
2053 case IMAGE_REL_BASED_HIGH:
2054 *(short *)((char *)page + offset) += HIWORD(delta);
2056 case IMAGE_REL_BASED_LOW:
2057 *(short *)((char *)page + offset) += LOWORD(delta);
2059 case IMAGE_REL_BASED_HIGHLOW:
2060 *(int *)((char *)page + offset) += delta;
2063 FIXME("Unknown/unsupported fixup type %x.\n", type);
2068 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2072 /******************************************************************
2073 * LdrQueryProcessModuleInformation
2076 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2077 ULONG buf_size, ULONG* req_size)
2079 SYSTEM_MODULE* sm = &smi->Modules[0];
2080 ULONG size = sizeof(ULONG);
2081 NTSTATUS nts = STATUS_SUCCESS;
2084 PLIST_ENTRY mark, entry;
2088 smi->ModulesCount = 0;
2090 RtlEnterCriticalSection( &loader_section );
2091 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2092 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2094 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2095 size += sizeof(*sm);
2096 if (size <= buf_size)
2098 sm->Reserved1 = 0; /* FIXME */
2099 sm->Reserved2 = 0; /* FIXME */
2100 sm->ImageBaseAddress = mod->BaseAddress;
2101 sm->ImageSize = mod->SizeOfImage;
2102 sm->Flags = mod->Flags;
2104 sm->Rank = 0; /* FIXME */
2105 sm->Unknown = 0; /* FIXME */
2107 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2108 str.Buffer = (char*)sm->Name;
2109 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2110 ptr = strrchr(str.Buffer, '\\');
2111 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2113 smi->ModulesCount++;
2116 else nts = STATUS_INFO_LENGTH_MISMATCH;
2118 RtlLeaveCriticalSection( &loader_section );
2120 if (req_size) *req_size = size;
2126 /******************************************************************
2127 * RtlDllShutdownInProgress (NTDLL.@)
2129 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2131 return process_detaching;
2135 /******************************************************************
2136 * LdrShutdownProcess (NTDLL.@)
2139 void WINAPI LdrShutdownProcess(void)
2142 process_detach( TRUE, (LPVOID)1 );
2145 /******************************************************************
2146 * LdrShutdownThread (NTDLL.@)
2149 void WINAPI LdrShutdownThread(void)
2151 PLIST_ENTRY mark, entry;
2156 /* don't do any detach calls if process is exiting */
2157 if (process_detaching) return;
2158 /* FIXME: there is still a race here */
2160 RtlEnterCriticalSection( &loader_section );
2162 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2163 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2165 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2166 InInitializationOrderModuleList);
2167 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2169 if ( mod->Flags & LDR_NO_DLL_CALLS )
2172 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2173 DLL_THREAD_DETACH, NULL );
2176 RtlLeaveCriticalSection( &loader_section );
2177 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2181 /***********************************************************************
2185 static void free_modref( WINE_MODREF *wm )
2187 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2188 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2189 if (wm->ldr.InInitializationOrderModuleList.Flink)
2190 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2192 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2193 if (!TRACE_ON(module))
2194 TRACE_(loaddll)("Unloaded module %s : %s\n",
2195 debugstr_w(wm->ldr.FullDllName.Buffer),
2196 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2198 SERVER_START_REQ( unload_dll )
2200 req->base = wm->ldr.BaseAddress;
2201 wine_server_call( req );
2205 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2206 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2207 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2208 if (cached_modref == wm) cached_modref = NULL;
2209 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2210 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2211 RtlFreeHeap( GetProcessHeap(), 0, wm );
2214 /***********************************************************************
2215 * MODULE_FlushModrefs
2217 * Remove all unused modrefs and call the internal unloading routines
2218 * for the library type.
2220 * The loader_section must be locked while calling this function.
2222 static void MODULE_FlushModrefs(void)
2224 PLIST_ENTRY mark, entry, prev;
2228 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2229 for (entry = mark->Blink; entry != mark; entry = prev)
2231 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2232 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2233 prev = entry->Blink;
2234 if (!mod->LoadCount) free_modref( wm );
2237 /* check load order list too for modules that haven't been initialized yet */
2238 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2239 for (entry = mark->Blink; entry != mark; entry = prev)
2241 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2242 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2243 prev = entry->Blink;
2244 if (!mod->LoadCount) free_modref( wm );
2248 /***********************************************************************
2249 * MODULE_DecRefCount
2251 * The loader_section must be locked while calling this function.
2253 static void MODULE_DecRefCount( WINE_MODREF *wm )
2257 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2260 if ( wm->ldr.LoadCount <= 0 )
2263 --wm->ldr.LoadCount;
2264 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2266 if ( wm->ldr.LoadCount == 0 )
2268 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2270 for ( i = 0; i < wm->nDeps; i++ )
2272 MODULE_DecRefCount( wm->deps[i] );
2274 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2278 /******************************************************************
2279 * LdrUnloadDll (NTDLL.@)
2283 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2285 NTSTATUS retv = STATUS_SUCCESS;
2287 TRACE("(%p)\n", hModule);
2289 RtlEnterCriticalSection( &loader_section );
2291 /* if we're stopping the whole process (and forcing the removal of all
2292 * DLLs) the library will be freed anyway
2294 if (!process_detaching)
2299 if ((wm = get_modref( hModule )) != NULL)
2301 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2303 /* Recursively decrement reference counts */
2304 MODULE_DecRefCount( wm );
2306 /* Call process detach notifications */
2307 if ( free_lib_count <= 1 )
2309 process_detach( FALSE, NULL );
2310 MODULE_FlushModrefs();
2316 retv = STATUS_DLL_NOT_FOUND;
2321 RtlLeaveCriticalSection( &loader_section );
2326 /***********************************************************************
2327 * RtlImageNtHeader (NTDLL.@)
2329 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2331 IMAGE_NT_HEADERS *ret;
2335 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2338 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2340 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2341 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2353 /***********************************************************************
2354 * attach_process_dlls
2356 * Initial attach to all the dlls loaded by the process.
2358 static NTSTATUS attach_process_dlls( void *wm )
2362 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2364 RtlEnterCriticalSection( &loader_section );
2365 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2367 if (last_failed_modref)
2368 ERR( "%s failed to initialize, aborting\n",
2369 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2372 attach_implicitly_loaded_dlls( (LPVOID)1 );
2373 RtlLeaveCriticalSection( &loader_section );
2378 /******************************************************************
2379 * LdrInitializeThunk (NTDLL.@)
2382 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2388 PEB *peb = NtCurrentTeb()->Peb;
2389 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2391 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2393 /* allocate the modref for the main exe (if not already done) */
2394 wm = get_modref( peb->ImageBaseAddress );
2396 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2398 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2402 peb->LoaderLock = &loader_section;
2403 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2404 version_init( wm->ldr.FullDllName.Buffer );
2406 /* the main exe needs to be the first in the load order list */
2407 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2408 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2410 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
2411 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
2413 if ((status = virtual_alloc_thread_stack( NULL, stack_size )) != STATUS_SUCCESS) goto error;
2414 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2417 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2418 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2419 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2420 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2421 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2423 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2424 if (status != STATUS_SUCCESS) goto error;
2426 virtual_clear_thread_stack();
2430 ERR( "Main exe initialization for %s failed, status %x\n",
2431 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2432 NtTerminateProcess( GetCurrentProcess(), status );
2436 /***********************************************************************
2437 * RtlImageDirectoryEntryToData (NTDLL.@)
2439 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2441 const IMAGE_NT_HEADERS *nt;
2444 if ((ULONG_PTR)module & 1) /* mapped as data file */
2446 module = (HMODULE)((ULONG_PTR)module & ~1);
2449 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2450 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2451 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2452 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2453 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2455 /* not mapped as image, need to find the section containing the virtual address */
2456 return RtlImageRvaToVa( nt, module, addr, NULL );
2460 /***********************************************************************
2461 * RtlImageRvaToSection (NTDLL.@)
2463 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2464 HMODULE module, DWORD rva )
2467 const IMAGE_SECTION_HEADER *sec;
2469 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2470 nt->FileHeader.SizeOfOptionalHeader);
2471 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2473 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2474 return (PIMAGE_SECTION_HEADER)sec;
2480 /***********************************************************************
2481 * RtlImageRvaToVa (NTDLL.@)
2483 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2484 DWORD rva, IMAGE_SECTION_HEADER **section )
2486 IMAGE_SECTION_HEADER *sec;
2488 if (section && *section) /* try this section first */
2491 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2494 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2496 if (section) *section = sec;
2497 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2501 /***********************************************************************
2502 * RtlPcToFileHeader (NTDLL.@)
2504 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2509 RtlEnterCriticalSection( &loader_section );
2510 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2511 RtlLeaveCriticalSection( &loader_section );
2517 /***********************************************************************
2518 * NtLoadDriver (NTDLL.@)
2519 * ZwLoadDriver (NTDLL.@)
2521 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2523 FIXME("(%p), stub!\n",DriverServiceName);
2524 return STATUS_NOT_IMPLEMENTED;
2528 /***********************************************************************
2529 * NtUnloadDriver (NTDLL.@)
2530 * ZwUnloadDriver (NTDLL.@)
2532 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2534 FIXME("(%p), stub!\n",DriverServiceName);
2535 return STATUS_NOT_IMPLEMENTED;
2539 /******************************************************************
2542 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2544 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2549 /******************************************************************
2550 * __wine_init_windows_dir (NTDLL.@)
2552 * Windows and system dir initialization once kernel32 has been loaded.
2554 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2556 PLIST_ENTRY mark, entry;
2559 RtlCreateUnicodeString( &windows_dir, windir );
2560 RtlCreateUnicodeString( &system_dir, sysdir );
2561 strcpyW( user_shared_data->NtSystemRoot, windir );
2563 /* prepend the system dir to the name of the already created modules */
2564 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2565 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2567 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2569 assert( mod->Flags & LDR_WINE_INTERNAL );
2571 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2572 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2573 if (!buffer) continue;
2574 strcpyW( buffer, system_dir.Buffer );
2575 p = buffer + strlenW( buffer );
2576 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2577 strcpyW( p, mod->FullDllName.Buffer );
2578 RtlInitUnicodeString( &mod->FullDllName, buffer );
2579 RtlInitUnicodeString( &mod->BaseDllName, p );
2584 /***********************************************************************
2585 * __wine_process_init
2587 void __wine_process_init(void)
2589 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2593 ANSI_STRING func_name;
2594 void (* DECLSPEC_NORETURN init_func)(void);
2595 extern mode_t FILE_umask;
2597 main_exe_file = thread_init();
2599 /* retrieve current umask */
2600 FILE_umask = umask(0777);
2601 umask( FILE_umask );
2603 /* setup the load callback and create ntdll modref */
2604 wine_dll_set_callback( load_builtin_callback );
2606 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2608 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2611 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2612 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2614 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2615 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2616 0, (void **)&init_func )) != STATUS_SUCCESS)
2618 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );