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"
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
32 #define WIN32_NO_STATUS
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41 #include "wine/server.h"
42 #include "ntdll_misc.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(module);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
47 WINE_DECLARE_DEBUG_CHANNEL(snoop);
48 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
49 WINE_DECLARE_DEBUG_CHANNEL(imports);
51 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
53 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
54 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
56 static const char * const reason_names[] =
62 NULL, NULL, NULL, NULL,
66 static const WCHAR dllW[] = {'.','d','l','l',0};
68 /* internal representation of 32bit modules. per process. */
69 typedef struct _wine_modref
73 struct _wine_modref **deps;
76 /* info about the current builtin dll load */
77 /* used to keep track of things across the register_dll constructor call */
78 struct builtin_load_info
80 const WCHAR *load_path;
81 const WCHAR *filename;
86 static struct builtin_load_info default_load_info;
87 static struct builtin_load_info *builtin_load_info = &default_load_info;
89 static HANDLE main_exe_file;
90 static UINT tls_module_count; /* number of modules with TLS directory */
91 static UINT tls_total_size; /* total size of TLS storage */
92 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
94 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
96 static RTL_CRITICAL_SECTION loader_section;
97 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
99 0, 0, &loader_section,
100 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
101 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
103 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
105 static WINE_MODREF *cached_modref;
106 static WINE_MODREF *current_modref;
107 static WINE_MODREF *last_failed_modref;
109 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
110 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
111 DWORD exp_size, const char *name, int hint );
113 /* convert PE image VirtualAddress to Real Address */
114 static inline void *get_rva( HMODULE module, DWORD va )
116 return (void *)((char *)module + va);
119 /* check whether the file name contains a path */
120 static inline int contains_path( LPCWSTR name )
122 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
125 /* convert from straight ASCII to Unicode without depending on the current codepage */
126 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
128 while (len--) *dst++ = (unsigned char)*src++;
132 /*************************************************************************
133 * call_dll_entry_point
135 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
136 * their entry point, so we need a small asm wrapper.
139 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
140 __ASM_GLOBAL_FUNC(call_dll_entry_point,
148 "movl 8(%ebp),%eax\n\t"
150 "leal -4(%ebp),%esp\n\t"
155 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
156 UINT reason, void *reserved )
158 return proc( module, reason, reserved );
160 #endif /* __i386__ */
164 /*************************************************************************
167 * Entry point for stub functions.
169 static void stub_entry_point( const char *dll, const char *name, ... )
171 EXCEPTION_RECORD rec;
173 rec.ExceptionCode = EXCEPTION_WINE_STUB;
174 rec.ExceptionFlags = EH_NONCONTINUABLE;
175 rec.ExceptionRecord = NULL;
177 rec.ExceptionAddress = __builtin_return_address(0);
179 rec.ExceptionAddress = *((void **)&dll - 1);
181 rec.NumberParameters = 2;
182 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
183 rec.ExceptionInformation[1] = (ULONG_PTR)name;
184 for (;;) RtlRaiseException( &rec );
188 #include "pshpack1.h"
191 BYTE popl_eax; /* popl %eax */
192 BYTE pushl1; /* pushl $name */
194 BYTE pushl2; /* pushl $dll */
196 BYTE pushl_eax; /* pushl %eax */
197 BYTE jmp; /* jmp stub_entry_point */
202 /*************************************************************************
205 * Allocate a stub entry point.
207 static ULONG_PTR allocate_stub( const char *dll, const char *name )
209 #define MAX_SIZE 65536
210 static struct stub *stubs;
211 static unsigned int nb_stubs;
214 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
218 SIZE_T size = MAX_SIZE;
219 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
220 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
223 stub = &stubs[nb_stubs++];
224 stub->popl_eax = 0x58; /* popl %eax */
225 stub->pushl1 = 0x68; /* pushl $name */
227 stub->pushl2 = 0x68; /* pushl $dll */
229 stub->pushl_eax = 0x50; /* pushl %eax */
230 stub->jmp = 0xe9; /* jmp stub_entry_point */
231 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
232 return (ULONG_PTR)stub;
236 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
237 #endif /* __i386__ */
240 /*************************************************************************
243 * Looks for the referenced HMODULE in the current process
244 * The loader_section must be locked while calling this function.
246 static WINE_MODREF *get_modref( HMODULE hmod )
248 PLIST_ENTRY mark, entry;
251 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
253 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
254 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
256 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
257 if (mod->BaseAddress == hmod)
258 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
259 if (mod->BaseAddress > (void*)hmod) break;
265 /**********************************************************************
266 * find_basename_module
268 * Find a module from its base name.
269 * The loader_section must be locked while calling this function
271 static WINE_MODREF *find_basename_module( LPCWSTR name )
273 PLIST_ENTRY mark, entry;
275 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
276 return cached_modref;
278 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
279 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
281 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
282 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
284 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
285 return cached_modref;
292 /**********************************************************************
293 * find_fullname_module
295 * Find a module from its full path name.
296 * The loader_section must be locked while calling this function
298 static WINE_MODREF *find_fullname_module( LPCWSTR name )
300 PLIST_ENTRY mark, entry;
302 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
303 return cached_modref;
305 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
306 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
308 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
309 if (!strcmpiW( name, mod->FullDllName.Buffer ))
311 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
312 return cached_modref;
319 /*************************************************************************
320 * find_forwarded_export
322 * Find the final function pointer for a forwarded function.
323 * The loader_section must be locked while calling this function.
325 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
327 const IMAGE_EXPORT_DIRECTORY *exports;
331 const char *end = strrchr(forward, '.');
334 if (!end) return NULL;
335 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
336 ascii_to_unicode( mod_name, forward, end - forward );
337 mod_name[end - forward] = 0;
338 if (!strchrW( mod_name, '.' ))
340 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
341 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
344 if (!(wm = find_basename_module( mod_name )))
346 ERR("module not found for forward '%s' used by %s\n",
347 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
350 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
351 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
352 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
356 ERR("function not found for forward '%s' used by %s."
357 " If you are using builtin %s, try using the native one instead.\n",
358 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
359 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
365 /*************************************************************************
366 * find_ordinal_export
368 * Find an exported function by ordinal.
369 * The exports base must have been subtracted from the ordinal already.
370 * The loader_section must be locked while calling this function.
372 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
373 DWORD exp_size, DWORD ordinal )
376 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
378 if (ordinal >= exports->NumberOfFunctions)
380 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
383 if (!functions[ordinal]) return NULL;
385 proc = get_rva( module, functions[ordinal] );
387 /* if the address falls into the export dir, it's a forward */
388 if (((const char *)proc >= (const char *)exports) &&
389 ((const char *)proc < (const char *)exports + exp_size))
390 return find_forwarded_export( module, (const char *)proc );
394 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
395 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
399 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
400 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
406 /*************************************************************************
409 * Find an exported function by name.
410 * The loader_section must be locked while calling this function.
412 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
413 DWORD exp_size, const char *name, int hint )
415 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
416 const DWORD *names = get_rva( module, exports->AddressOfNames );
417 int min = 0, max = exports->NumberOfNames - 1;
419 /* first check the hint */
420 if (hint >= 0 && hint <= max)
422 char *ename = get_rva( module, names[hint] );
423 if (!strcmp( ename, name ))
424 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
427 /* then do a binary search */
430 int res, pos = (min + max) / 2;
431 char *ename = get_rva( module, names[pos] );
432 if (!(res = strcmp( ename, name )))
433 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
434 if (res > 0) max = pos - 1;
442 /*************************************************************************
445 * Import the dll specified by the given import descriptor.
446 * The loader_section must be locked while calling this function.
448 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
453 const IMAGE_EXPORT_DIRECTORY *exports;
455 const IMAGE_THUNK_DATA *import_list;
456 IMAGE_THUNK_DATA *thunk_list;
458 const char *name = get_rva( module, descr->Name );
459 DWORD len = strlen(name);
461 SIZE_T protect_size = 0;
464 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
465 if (descr->u.OriginalFirstThunk)
466 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
468 import_list = thunk_list;
470 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
472 if (len * sizeof(WCHAR) < sizeof(buffer))
474 ascii_to_unicode( buffer, name, len );
476 status = load_dll( load_path, buffer, 0, &wmImp );
478 else /* need to allocate a larger buffer */
480 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
481 if (!ptr) return NULL;
482 ascii_to_unicode( ptr, name, len );
484 status = load_dll( load_path, ptr, 0, &wmImp );
485 RtlFreeHeap( GetProcessHeap(), 0, ptr );
490 if (status == STATUS_DLL_NOT_FOUND)
491 ERR("Library %s (which is needed by %s) not found\n",
492 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
494 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
495 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
499 /* unprotect the import address table since it can be located in
500 * readonly section */
501 while (import_list[protect_size].u1.Ordinal) protect_size++;
502 protect_base = thunk_list;
503 protect_size *= sizeof(*thunk_list);
504 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
505 &protect_size, PAGE_WRITECOPY, &protect_old );
507 imp_mod = wmImp->ldr.BaseAddress;
508 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
512 /* set all imported function to deadbeef */
513 while (import_list->u1.Ordinal)
515 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
517 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
518 WARN("No implementation for %s.%d", name, ordinal );
519 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
523 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
524 WARN("No implementation for %s.%s", name, pe_name->Name );
525 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
527 WARN(" imported from %s, allocating stub %p\n",
528 debugstr_w(current_modref->ldr.FullDllName.Buffer),
529 (void *)thunk_list->u1.Function );
536 while (import_list->u1.Ordinal)
538 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
540 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
542 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
543 ordinal - exports->Base );
544 if (!thunk_list->u1.Function)
546 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
547 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
548 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
549 (void *)thunk_list->u1.Function );
551 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
553 else /* import by name */
555 IMAGE_IMPORT_BY_NAME *pe_name;
556 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
557 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
558 (const char*)pe_name->Name, pe_name->Hint );
559 if (!thunk_list->u1.Function)
561 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
562 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
563 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
564 (void *)thunk_list->u1.Function );
566 TRACE_(imports)("--- %s %s.%d = %p\n",
567 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
574 /* restore old protection of the import address table */
575 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
580 /****************************************************************
583 * Fixup all imports of a given module.
584 * The loader_section must be locked while calling this function.
586 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
589 const IMAGE_IMPORT_DESCRIPTOR *imports;
594 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
595 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
597 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
598 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
599 return STATUS_SUCCESS;
602 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
604 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
606 /* Allocate module dependency list */
607 wm->nDeps = nb_imports;
608 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
610 /* load the imported modules. They are automatically
611 * added to the modref list of the process.
613 prev = current_modref;
615 status = STATUS_SUCCESS;
616 for (i = 0; i < nb_imports; i++)
618 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
619 status = STATUS_DLL_NOT_FOUND;
621 current_modref = prev;
626 /*************************************************************************
629 * Allocate a WINE_MODREF structure and add it to the process list
630 * The loader_section must be locked while calling this function.
632 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
636 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
637 PLIST_ENTRY entry, mark;
639 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
644 wm->ldr.BaseAddress = hModule;
645 wm->ldr.EntryPoint = NULL;
646 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
647 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
648 wm->ldr.LoadCount = 1;
649 wm->ldr.TlsIndex = -1;
650 wm->ldr.SectionHandle = NULL;
651 wm->ldr.CheckSum = 0;
652 wm->ldr.TimeDateStamp = 0;
654 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
655 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
656 else p = wm->ldr.FullDllName.Buffer;
657 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
659 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
661 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
662 if (nt->OptionalHeader.AddressOfEntryPoint)
663 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
666 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
667 &wm->ldr.InLoadOrderModuleList);
669 /* insert module in MemoryList, sorted in increasing base addresses */
670 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
671 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
673 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
676 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
677 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
678 wm->ldr.InMemoryOrderModuleList.Flink = entry;
679 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
681 /* wait until init is called for inserting into this list */
682 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
683 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
685 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
687 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
688 VIRTUAL_SetForceExec( TRUE );
694 /*************************************************************************
697 * Allocate the process-wide structure for module TLS storage.
699 static NTSTATUS alloc_process_tls(void)
701 PLIST_ENTRY mark, entry;
703 const IMAGE_TLS_DIRECTORY *dir;
706 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
707 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
709 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
710 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
711 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
713 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
715 tls_total_size += size;
718 if (!tls_module_count) return STATUS_SUCCESS;
720 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
722 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
723 if (!tls_dirs) return STATUS_NO_MEMORY;
725 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
727 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
728 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
729 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
732 *(DWORD *)dir->AddressOfIndex = i;
734 mod->LoadCount = -1; /* can't unload it */
737 return STATUS_SUCCESS;
741 /*************************************************************************
744 * Allocate the per-thread structure for module TLS storage.
746 static NTSTATUS alloc_thread_tls(void)
752 if (!tls_module_count) return STATUS_SUCCESS;
754 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
755 tls_module_count * sizeof(*pointers) )))
756 return STATUS_NO_MEMORY;
758 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
760 RtlFreeHeap( GetProcessHeap(), 0, pointers );
761 return STATUS_NO_MEMORY;
764 for (i = 0; i < tls_module_count; i++)
766 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
767 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
769 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
770 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
771 (void *)dir->StartAddressOfRawData, data );
774 memcpy( data, (void *)dir->StartAddressOfRawData, size );
776 memset( data, 0, dir->SizeOfZeroFill );
777 data += dir->SizeOfZeroFill;
779 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
780 return STATUS_SUCCESS;
784 /*************************************************************************
787 static void call_tls_callbacks( HMODULE module, UINT reason )
789 const IMAGE_TLS_DIRECTORY *dir;
790 const PIMAGE_TLS_CALLBACK *callback;
793 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
794 if (!dir || !dir->AddressOfCallBacks) return;
796 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
799 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
800 GetCurrentThreadId(), *callback, module, reason_names[reason] );
803 (*callback)( module, reason, NULL );
808 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
809 GetCurrentThreadId(), callback, module, reason_names[reason] );
814 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
815 GetCurrentThreadId(), *callback, module, reason_names[reason] );
820 /*************************************************************************
823 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
827 DLLENTRYPROC entry = wm->ldr.EntryPoint;
828 void *module = wm->ldr.BaseAddress;
830 /* Skip calls for modules loaded with special load flags */
832 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
833 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
834 if (!entry) return TRUE;
838 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
839 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
840 mod_name[len / sizeof(WCHAR)] = 0;
841 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
842 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
843 reason_names[reason], lpReserved );
845 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
846 reason_names[reason], lpReserved );
848 retv = call_dll_entry_point( entry, module, reason, lpReserved );
850 /* The state of the module list may have changed due to the call
851 to the dll. We cannot assume that this module has not been
854 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
855 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
856 reason_names[reason], lpReserved, retv );
857 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
863 /*************************************************************************
866 * Send the process attach notification to all DLLs the given module
867 * depends on (recursively). This is somewhat complicated due to the fact that
869 * - we have to respect the module dependencies, i.e. modules implicitly
870 * referenced by another module have to be initialized before the module
871 * itself can be initialized
873 * - the initialization routine of a DLL can itself call LoadLibrary,
874 * thereby introducing a whole new set of dependencies (even involving
875 * the 'old' modules) at any time during the whole process
877 * (Note that this routine can be recursively entered not only directly
878 * from itself, but also via LoadLibrary from one of the called initialization
881 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
882 * the process *detach* notifications to be sent in the correct order.
883 * This must not only take into account module dependencies, but also
884 * 'hidden' dependencies created by modules calling LoadLibrary in their
885 * attach notification routine.
887 * The strategy is rather simple: we move a WINE_MODREF to the head of the
888 * list after the attach notification has returned. This implies that the
889 * detach notifications are called in the reverse of the sequence the attach
890 * notifications *returned*.
892 * The loader_section must be locked while calling this function.
894 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
896 NTSTATUS status = STATUS_SUCCESS;
899 if (process_detaching) return status;
901 /* prevent infinite recursion in case of cyclical dependencies */
902 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
903 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
906 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
908 /* Tag current MODREF to prevent recursive loop */
909 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
911 /* Recursively attach all DLLs this one depends on */
912 for ( i = 0; i < wm->nDeps; i++ )
914 if (!wm->deps[i]) continue;
915 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
918 /* Call DLL entry point */
919 if (status == STATUS_SUCCESS)
921 WINE_MODREF *prev = current_modref;
923 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
925 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
929 /* point to the name so LdrInitializeThunk can print it */
930 last_failed_modref = wm;
931 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
932 status = STATUS_DLL_INIT_FAILED;
934 current_modref = prev;
937 if (!wm->ldr.InInitializationOrderModuleList.Flink)
938 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
939 &wm->ldr.InInitializationOrderModuleList);
941 /* Remove recursion flag */
942 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
944 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
949 /**********************************************************************
950 * attach_implicitly_loaded_dlls
952 * Attach to the (builtin) dlls that have been implicitly loaded because
953 * of a dependency at the Unix level, but not imported at the Win32 level.
955 static void attach_implicitly_loaded_dlls( LPVOID reserved )
959 PLIST_ENTRY mark, entry;
961 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
962 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
964 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
966 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
967 TRACE( "found implicitly loaded %s, attaching to it\n",
968 debugstr_w(mod->BaseDllName.Buffer));
969 mod->LoadCount = -1; /* we can't unload it anyway */
970 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
971 break; /* restart the search from the start */
973 if (entry == mark) break; /* nothing found */
978 /*************************************************************************
981 * Send DLL process detach notifications. See the comment about calling
982 * sequence at process_attach. Unless the bForceDetach flag
983 * is set, only DLLs with zero refcount are notified.
985 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
987 PLIST_ENTRY mark, entry;
990 RtlEnterCriticalSection( &loader_section );
991 if (bForceDetach) process_detaching = 1;
992 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
995 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
997 mod = CONTAINING_RECORD(entry, LDR_MODULE,
998 InInitializationOrderModuleList);
999 /* Check whether to detach this DLL */
1000 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1002 if ( mod->LoadCount && !bForceDetach )
1005 /* Call detach notification */
1006 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1007 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1008 DLL_PROCESS_DETACH, lpReserved );
1010 /* Restart at head of WINE_MODREF list, as entries might have
1011 been added and/or removed while performing the call ... */
1014 } while (entry != mark);
1016 RtlLeaveCriticalSection( &loader_section );
1019 /*************************************************************************
1020 * MODULE_DllThreadAttach
1022 * Send DLL thread attach notifications. These are sent in the
1023 * reverse sequence of process detach notification.
1026 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1028 PLIST_ENTRY mark, entry;
1032 /* don't do any attach calls if process is exiting */
1033 if (process_detaching) return STATUS_SUCCESS;
1034 /* FIXME: there is still a race here */
1036 RtlEnterCriticalSection( &loader_section );
1038 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1040 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1041 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1043 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1044 InInitializationOrderModuleList);
1045 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1047 if ( mod->Flags & LDR_NO_DLL_CALLS )
1050 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1051 DLL_THREAD_ATTACH, lpReserved );
1055 RtlLeaveCriticalSection( &loader_section );
1059 /******************************************************************
1060 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1063 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1066 NTSTATUS ret = STATUS_SUCCESS;
1068 RtlEnterCriticalSection( &loader_section );
1070 wm = get_modref( hModule );
1071 if (!wm || wm->ldr.TlsIndex != -1)
1072 ret = STATUS_DLL_NOT_FOUND;
1074 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1076 RtlLeaveCriticalSection( &loader_section );
1081 /******************************************************************
1082 * LdrFindEntryForAddress (NTDLL.@)
1084 * The loader_section must be locked while calling this function
1086 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1088 PLIST_ENTRY mark, entry;
1091 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1092 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1094 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1095 if ((const void *)mod->BaseAddress <= addr &&
1096 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1099 return STATUS_SUCCESS;
1101 if ((const void *)mod->BaseAddress > addr) break;
1103 return STATUS_NO_MORE_ENTRIES;
1106 /******************************************************************
1107 * LdrLockLoaderLock (NTDLL.@)
1109 * Note: flags are not implemented.
1110 * Flag 0x01 is used to raise exceptions on errors.
1111 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1113 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1115 if (flags) FIXME( "flags %x not supported\n", flags );
1117 if (result) *result = 1;
1118 if (!magic) return STATUS_INVALID_PARAMETER_3;
1119 RtlEnterCriticalSection( &loader_section );
1120 *magic = GetCurrentThreadId();
1121 return STATUS_SUCCESS;
1125 /******************************************************************
1126 * LdrUnlockLoaderUnlock (NTDLL.@)
1128 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1132 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1133 RtlLeaveCriticalSection( &loader_section );
1135 return STATUS_SUCCESS;
1139 /******************************************************************
1140 * LdrGetProcedureAddress (NTDLL.@)
1142 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1143 ULONG ord, PVOID *address)
1145 IMAGE_EXPORT_DIRECTORY *exports;
1147 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1149 RtlEnterCriticalSection( &loader_section );
1151 /* check if the module itself is invalid to return the proper error */
1152 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1153 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1154 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1156 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1157 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1161 ret = STATUS_SUCCESS;
1165 RtlLeaveCriticalSection( &loader_section );
1170 /***********************************************************************
1173 * Check if a loaded native dll is a Wine fake dll.
1175 static BOOL is_fake_dll( const void *base )
1177 static const char fakedll_signature[] = "Wine placeholder DLL";
1178 const IMAGE_DOS_HEADER *dos = base;
1180 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1181 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1186 /***********************************************************************
1187 * get_builtin_fullname
1189 * Build the full pathname for a builtin dll.
1191 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1193 static const WCHAR soW[] = {'.','s','o',0};
1194 WCHAR *p, *fullname;
1195 size_t i, len = strlen(filename);
1197 /* check if path can correspond to the dll we have */
1198 if (path && (p = strrchrW( path, '\\' )))
1201 for (i = 0; i < len; i++)
1202 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1203 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1205 /* the filename matches, use path as the full path */
1207 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1209 memcpy( fullname, path, len * sizeof(WCHAR) );
1216 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1217 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1219 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1220 p = fullname + system_dir.Length / sizeof(WCHAR);
1221 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1222 ascii_to_unicode( p, filename, len + 1 );
1228 /***********************************************************************
1229 * load_builtin_callback
1231 * Load a library in memory; callback function for wine_dll_register
1233 static void load_builtin_callback( void *module, const char *filename )
1235 static const WCHAR emptyW[1];
1237 IMAGE_NT_HEADERS *nt;
1240 const WCHAR *load_path;
1245 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1248 if (!(nt = RtlImageNtHeader( module )))
1250 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1251 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1255 size = nt->OptionalHeader.SizeOfImage;
1256 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1257 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1258 /* create the MODREF */
1260 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1262 ERR( "can't load %s\n", filename );
1263 builtin_load_info->status = STATUS_NO_MEMORY;
1267 wm = alloc_module( module, fullname );
1268 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1271 ERR( "can't load %s\n", filename );
1272 builtin_load_info->status = STATUS_NO_MEMORY;
1275 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1277 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1278 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1280 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1286 load_path = builtin_load_info->load_path;
1287 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1288 if (!load_path) load_path = emptyW;
1289 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1291 /* the module has only be inserted in the load & memory order lists */
1292 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1293 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1294 /* FIXME: free the modref */
1295 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1300 builtin_load_info->wm = wm;
1301 TRACE( "loaded %s %p %p\n", filename, wm, module );
1303 /* send the DLL load event */
1305 SERVER_START_REQ( load_dll )
1309 req->size = nt->OptionalHeader.SizeOfImage;
1310 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1311 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1312 req->name = &wm->ldr.FullDllName.Buffer;
1313 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1314 wine_server_call( req );
1318 /* setup relay debugging entry points */
1319 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1323 /******************************************************************************
1324 * load_native_dll (internal)
1326 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1327 DWORD flags, WINE_MODREF** pwm )
1331 OBJECT_ATTRIBUTES attr;
1333 IMAGE_NT_HEADERS *nt;
1338 TRACE("Trying native dll %s\n", debugstr_w(name));
1340 attr.Length = sizeof(attr);
1341 attr.RootDirectory = 0;
1342 attr.ObjectName = NULL;
1343 attr.Attributes = 0;
1344 attr.SecurityDescriptor = NULL;
1345 attr.SecurityQualityOfService = NULL;
1348 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1349 &attr, &size, 0, SEC_IMAGE, file );
1350 if (status != STATUS_SUCCESS) return status;
1353 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1354 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1356 if (status != STATUS_SUCCESS) return status;
1358 if (is_fake_dll( module ))
1360 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1361 NtUnmapViewOfSection( NtCurrentProcess(), module );
1362 return STATUS_DLL_NOT_FOUND;
1365 /* create the MODREF */
1367 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1371 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1373 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1375 /* the module has only be inserted in the load & memory order lists */
1376 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1377 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1379 /* FIXME: there are several more dangling references
1380 * left. Including dlls loaded by this dll before the
1381 * failed one. Unrolling is rather difficult with the
1382 * current structure and we can leave them lying
1383 * around with no problems, so we don't care.
1384 * As these might reference our wm, we don't free it.
1390 /* send DLL load event */
1392 nt = RtlImageNtHeader( module );
1394 SERVER_START_REQ( load_dll )
1398 req->size = nt->OptionalHeader.SizeOfImage;
1399 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1400 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1401 req->name = &wm->ldr.FullDllName.Buffer;
1402 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1403 wine_server_call( req );
1407 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1409 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1411 wm->ldr.LoadCount = 1;
1413 return STATUS_SUCCESS;
1417 /***********************************************************************
1420 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1421 DWORD flags, WINE_MODREF** pwm )
1423 char error[256], dllname[MAX_PATH];
1424 const WCHAR *name, *p;
1426 void *handle = NULL;
1427 struct builtin_load_info info, *prev_info;
1429 /* Fix the name in case we have a full path and extension */
1431 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1432 if ((p = strrchrW( name, '/' ))) name = p + 1;
1434 /* load_library will modify info.status. Note also that load_library can be
1435 * called several times, if the .so file we're loading has dependencies.
1436 * info.status will gather all the errors we may get while loading all these
1439 info.load_path = load_path;
1440 info.filename = NULL;
1441 info.status = STATUS_SUCCESS;
1444 if (file) /* we have a real file, try to load it */
1446 UNICODE_STRING nt_name;
1447 ANSI_STRING unix_name;
1449 TRACE("Trying built-in %s\n", debugstr_w(path));
1451 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1452 return STATUS_DLL_NOT_FOUND;
1454 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1456 RtlFreeUnicodeString( &nt_name );
1457 return STATUS_DLL_NOT_FOUND;
1459 prev_info = builtin_load_info;
1460 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1461 builtin_load_info = &info;
1462 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1463 builtin_load_info = prev_info;
1464 RtlFreeUnicodeString( &nt_name );
1465 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1468 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1469 return STATUS_INVALID_IMAGE_FORMAT;
1476 TRACE("Trying built-in %s\n", debugstr_w(name));
1478 /* we don't want to depend on the current codepage here */
1479 len = strlenW( name ) + 1;
1480 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1481 for (i = 0; i < len; i++)
1483 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1484 dllname[i] = (char)name[i];
1485 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1488 prev_info = builtin_load_info;
1489 builtin_load_info = &info;
1490 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1491 builtin_load_info = prev_info;
1496 /* The file does not exist -> WARN() */
1497 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1498 return STATUS_DLL_NOT_FOUND;
1500 /* ERR() for all other errors (missing functions, ...) */
1501 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1502 return STATUS_PROCEDURE_NOT_FOUND;
1506 if (info.status != STATUS_SUCCESS)
1508 wine_dll_unload( handle );
1514 PLIST_ENTRY mark, entry;
1516 /* The constructor wasn't called, this means the .so is already
1517 * loaded under a different name. Try to find the wm for it. */
1519 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1520 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1522 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1523 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1525 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1526 TRACE( "Found already loaded module %s for builtin %s\n",
1527 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1531 wine_dll_unload( handle ); /* release the libdl refcount */
1532 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1533 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1537 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1538 info.wm->ldr.LoadCount = 1;
1539 info.wm->ldr.SectionHandle = handle;
1543 return STATUS_SUCCESS;
1547 /***********************************************************************
1550 * Find the file (or already loaded module) for a given dll name.
1552 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1553 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1555 OBJECT_ATTRIBUTES attr;
1557 UNICODE_STRING nt_name;
1558 WCHAR *file_part, *ext, *dllname;
1561 /* first append .dll if needed */
1564 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1566 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1567 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1568 return STATUS_NO_MEMORY;
1569 strcpyW( dllname, libname );
1570 strcatW( dllname, dllW );
1574 nt_name.Buffer = NULL;
1576 if (!contains_path( libname ))
1578 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1581 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1583 /* we need to search for it */
1584 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1587 if (len >= *size) goto overflow;
1588 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1590 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1592 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1593 return STATUS_NO_MEMORY;
1595 attr.Length = sizeof(attr);
1596 attr.RootDirectory = 0;
1597 attr.Attributes = OBJ_CASE_INSENSITIVE;
1598 attr.ObjectName = &nt_name;
1599 attr.SecurityDescriptor = NULL;
1600 attr.SecurityQualityOfService = NULL;
1601 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1607 if (!contains_path( libname ))
1609 /* if libname doesn't contain a path at all, we simply return the name as is,
1610 * to be loaded as builtin */
1611 len = strlenW(libname) * sizeof(WCHAR);
1612 if (len >= *size) goto overflow;
1613 strcpyW( filename, libname );
1618 /* absolute path name, or relative path name but not found above */
1620 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1622 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1623 return STATUS_NO_MEMORY;
1625 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1626 if (len >= *size) goto overflow;
1627 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1628 if (!(*pwm = find_fullname_module( filename )) && handle)
1630 attr.Length = sizeof(attr);
1631 attr.RootDirectory = 0;
1632 attr.Attributes = OBJ_CASE_INSENSITIVE;
1633 attr.ObjectName = &nt_name;
1634 attr.SecurityDescriptor = NULL;
1635 attr.SecurityQualityOfService = NULL;
1636 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1639 RtlFreeUnicodeString( &nt_name );
1640 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1641 return STATUS_SUCCESS;
1644 RtlFreeUnicodeString( &nt_name );
1645 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1646 *size = len + sizeof(WCHAR);
1647 return STATUS_BUFFER_TOO_SMALL;
1651 /***********************************************************************
1652 * load_dll (internal)
1654 * Load a PE style module according to the load order.
1655 * The loader_section must be locked while calling this function.
1657 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1659 enum loadorder loadorder;
1663 WINE_MODREF *main_exe;
1667 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1670 size = sizeof(buffer);
1673 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1674 if (nts == STATUS_SUCCESS) break;
1675 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1676 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1677 /* grow the buffer and retry */
1678 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1681 if (*pwm) /* found already loaded module */
1683 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1685 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1687 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1688 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1689 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1690 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1691 return STATUS_SUCCESS;
1694 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1695 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1700 nts = STATUS_NO_MEMORY;
1703 nts = STATUS_DLL_NOT_FOUND;
1706 case LO_NATIVE_BUILTIN:
1707 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1710 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1711 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1712 /* not in PE format, maybe it's a builtin */
1713 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1715 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1716 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1719 case LO_BUILTIN_NATIVE:
1720 case LO_DEFAULT: /* default is builtin,native */
1721 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1722 if (!handle) break; /* nothing else we can try */
1723 /* file is not a builtin library, try without using the specified file */
1724 if (nts != STATUS_SUCCESS)
1725 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1726 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1727 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1729 /* stub-only dll, try native */
1730 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1731 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1732 nts = STATUS_DLL_NOT_FOUND;
1734 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1735 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1739 if (nts == STATUS_SUCCESS)
1741 /* Initialize DLL just loaded */
1742 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1743 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1744 (*pwm)->ldr.BaseAddress);
1745 if (handle) NtClose( handle );
1746 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1750 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1751 if (handle) NtClose( handle );
1752 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1756 /******************************************************************
1757 * LdrLoadDll (NTDLL.@)
1759 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1760 const UNICODE_STRING *libname, HMODULE* hModule)
1765 RtlEnterCriticalSection( &loader_section );
1767 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1768 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1770 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1772 nts = process_attach( wm, NULL );
1773 if (nts != STATUS_SUCCESS)
1775 LdrUnloadDll(wm->ldr.BaseAddress);
1779 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1781 RtlLeaveCriticalSection( &loader_section );
1786 /******************************************************************
1787 * LdrGetDllHandle (NTDLL.@)
1789 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1797 RtlEnterCriticalSection( &loader_section );
1799 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1802 size = sizeof(buffer);
1805 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1806 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1807 if (status != STATUS_BUFFER_TOO_SMALL) break;
1808 /* grow the buffer and retry */
1809 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1812 if (status == STATUS_SUCCESS)
1814 if (wm) *base = wm->ldr.BaseAddress;
1815 else status = STATUS_DLL_NOT_FOUND;
1818 RtlLeaveCriticalSection( &loader_section );
1819 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1824 /******************************************************************
1825 * LdrAddRefDll (NTDLL.@)
1827 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1829 NTSTATUS ret = STATUS_SUCCESS;
1832 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
1834 RtlEnterCriticalSection( &loader_section );
1836 if ((wm = get_modref( module )))
1838 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
1839 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1841 else ret = STATUS_INVALID_PARAMETER;
1843 RtlLeaveCriticalSection( &loader_section );
1848 /******************************************************************
1849 * LdrQueryProcessModuleInformation
1852 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1853 ULONG buf_size, ULONG* req_size)
1855 SYSTEM_MODULE* sm = &smi->Modules[0];
1856 ULONG size = sizeof(ULONG);
1857 NTSTATUS nts = STATUS_SUCCESS;
1860 PLIST_ENTRY mark, entry;
1863 smi->ModulesCount = 0;
1865 RtlEnterCriticalSection( &loader_section );
1866 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1867 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1869 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1870 size += sizeof(*sm);
1871 if (size <= buf_size)
1873 sm->Reserved1 = 0; /* FIXME */
1874 sm->Reserved2 = 0; /* FIXME */
1875 sm->ImageBaseAddress = mod->BaseAddress;
1876 sm->ImageSize = mod->SizeOfImage;
1877 sm->Flags = mod->Flags;
1878 sm->Id = 0; /* FIXME */
1879 sm->Rank = 0; /* FIXME */
1880 sm->Unknown = 0; /* FIXME */
1882 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1883 str.Buffer = (char*)sm->Name;
1884 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1885 ptr = strrchr(str.Buffer, '\\');
1886 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1888 smi->ModulesCount++;
1891 else nts = STATUS_INFO_LENGTH_MISMATCH;
1893 RtlLeaveCriticalSection( &loader_section );
1895 if (req_size) *req_size = size;
1901 /******************************************************************
1902 * RtlDllShutdownInProgress (NTDLL.@)
1904 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
1906 return process_detaching;
1910 /******************************************************************
1911 * LdrShutdownProcess (NTDLL.@)
1914 void WINAPI LdrShutdownProcess(void)
1917 process_detach( TRUE, (LPVOID)1 );
1920 /******************************************************************
1921 * LdrShutdownThread (NTDLL.@)
1924 void WINAPI LdrShutdownThread(void)
1926 PLIST_ENTRY mark, entry;
1931 /* don't do any detach calls if process is exiting */
1932 if (process_detaching) return;
1933 /* FIXME: there is still a race here */
1935 RtlEnterCriticalSection( &loader_section );
1937 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1938 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1940 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1941 InInitializationOrderModuleList);
1942 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1944 if ( mod->Flags & LDR_NO_DLL_CALLS )
1947 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1948 DLL_THREAD_DETACH, NULL );
1951 RtlLeaveCriticalSection( &loader_section );
1952 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
1956 /***********************************************************************
1960 static void free_modref( WINE_MODREF *wm )
1962 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1963 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1964 if (wm->ldr.InInitializationOrderModuleList.Flink)
1965 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
1967 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
1968 if (!TRACE_ON(module))
1969 TRACE_(loaddll)("Unloaded module %s : %s\n",
1970 debugstr_w(wm->ldr.FullDllName.Buffer),
1971 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1973 SERVER_START_REQ( unload_dll )
1975 req->base = wm->ldr.BaseAddress;
1976 wine_server_call( req );
1980 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
1981 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1982 if (cached_modref == wm) cached_modref = NULL;
1983 RtlFreeUnicodeString( &wm->ldr.FullDllName );
1984 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1985 RtlFreeHeap( GetProcessHeap(), 0, wm );
1988 /***********************************************************************
1989 * MODULE_FlushModrefs
1991 * Remove all unused modrefs and call the internal unloading routines
1992 * for the library type.
1994 * The loader_section must be locked while calling this function.
1996 static void MODULE_FlushModrefs(void)
1998 PLIST_ENTRY mark, entry, prev;
2002 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2003 for (entry = mark->Blink; entry != mark; entry = prev)
2005 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2006 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2007 prev = entry->Blink;
2008 if (!mod->LoadCount) free_modref( wm );
2011 /* check load order list too for modules that haven't been initialized yet */
2012 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2013 for (entry = mark->Blink; entry != mark; entry = prev)
2015 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2016 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2017 prev = entry->Blink;
2018 if (!mod->LoadCount) free_modref( wm );
2022 /***********************************************************************
2023 * MODULE_DecRefCount
2025 * The loader_section must be locked while calling this function.
2027 static void MODULE_DecRefCount( WINE_MODREF *wm )
2031 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2034 if ( wm->ldr.LoadCount <= 0 )
2037 --wm->ldr.LoadCount;
2038 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2040 if ( wm->ldr.LoadCount == 0 )
2042 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2044 for ( i = 0; i < wm->nDeps; i++ )
2046 MODULE_DecRefCount( wm->deps[i] );
2048 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2052 /******************************************************************
2053 * LdrUnloadDll (NTDLL.@)
2057 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2059 NTSTATUS retv = STATUS_SUCCESS;
2061 TRACE("(%p)\n", hModule);
2063 RtlEnterCriticalSection( &loader_section );
2065 /* if we're stopping the whole process (and forcing the removal of all
2066 * DLLs) the library will be freed anyway
2068 if (!process_detaching)
2073 if ((wm = get_modref( hModule )) != NULL)
2075 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2077 /* Recursively decrement reference counts */
2078 MODULE_DecRefCount( wm );
2080 /* Call process detach notifications */
2081 if ( free_lib_count <= 1 )
2083 process_detach( FALSE, NULL );
2084 MODULE_FlushModrefs();
2090 retv = STATUS_DLL_NOT_FOUND;
2095 RtlLeaveCriticalSection( &loader_section );
2100 /***********************************************************************
2101 * RtlImageNtHeader (NTDLL.@)
2103 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2105 IMAGE_NT_HEADERS *ret;
2109 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2112 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2114 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2115 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2127 /******************************************************************
2128 * LdrInitializeThunk (NTDLL.@)
2131 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2136 PEB *peb = NtCurrentTeb()->Peb;
2137 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2139 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2141 /* allocate the modref for the main exe (if not already done) */
2142 wm = get_modref( peb->ImageBaseAddress );
2144 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2146 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2149 wm->ldr.LoadCount = -1; /* can't unload main exe */
2151 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2152 version_init( wm->ldr.FullDllName.Buffer );
2154 /* the main exe needs to be the first in the load order list */
2155 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2156 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2158 status = server_init_process_done();
2159 if (status != STATUS_SUCCESS) goto error;
2161 RtlEnterCriticalSection( &loader_section );
2163 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2164 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2165 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2166 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2167 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2169 if (last_failed_modref)
2170 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2173 attach_implicitly_loaded_dlls( (LPVOID)1 );
2175 RtlLeaveCriticalSection( &loader_section );
2177 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2181 ERR( "Main exe initialization for %s failed, status %x\n",
2182 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2187 /***********************************************************************
2188 * RtlImageDirectoryEntryToData (NTDLL.@)
2190 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2192 const IMAGE_NT_HEADERS *nt;
2195 if ((ULONG_PTR)module & 1) /* mapped as data file */
2197 module = (HMODULE)((ULONG_PTR)module & ~1);
2200 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2201 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2202 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2203 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2204 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2206 /* not mapped as image, need to find the section containing the virtual address */
2207 return RtlImageRvaToVa( nt, module, addr, NULL );
2211 /***********************************************************************
2212 * RtlImageRvaToSection (NTDLL.@)
2214 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2215 HMODULE module, DWORD rva )
2218 const IMAGE_SECTION_HEADER *sec;
2220 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2221 nt->FileHeader.SizeOfOptionalHeader);
2222 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2224 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2225 return (PIMAGE_SECTION_HEADER)sec;
2231 /***********************************************************************
2232 * RtlImageRvaToVa (NTDLL.@)
2234 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2235 DWORD rva, IMAGE_SECTION_HEADER **section )
2237 IMAGE_SECTION_HEADER *sec;
2239 if (section && *section) /* try this section first */
2242 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2245 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2247 if (section) *section = sec;
2248 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2252 /***********************************************************************
2253 * RtlPcToFileHeader (NTDLL.@)
2255 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2260 RtlEnterCriticalSection( &loader_section );
2261 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2262 RtlLeaveCriticalSection( &loader_section );
2268 /***********************************************************************
2269 * NtLoadDriver (NTDLL.@)
2270 * ZwLoadDriver (NTDLL.@)
2272 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2274 FIXME("(%p), stub!\n",DriverServiceName);
2275 return STATUS_NOT_IMPLEMENTED;
2279 /***********************************************************************
2280 * NtUnloadDriver (NTDLL.@)
2281 * ZwUnloadDriver (NTDLL.@)
2283 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2285 FIXME("(%p), stub!\n",DriverServiceName);
2286 return STATUS_NOT_IMPLEMENTED;
2290 /******************************************************************
2293 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2295 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2300 /******************************************************************
2301 * __wine_init_windows_dir (NTDLL.@)
2303 * Windows and system dir initialization once kernel32 has been loaded.
2305 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2307 PLIST_ENTRY mark, entry;
2310 RtlCreateUnicodeString( &system_dir, sysdir );
2311 strcpyW( user_shared_data->NtSystemRoot, windir );
2313 /* prepend the system dir to the name of the already created modules */
2314 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2315 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2317 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2319 assert( mod->Flags & LDR_WINE_INTERNAL );
2321 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2322 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2323 if (!buffer) continue;
2324 strcpyW( buffer, system_dir.Buffer );
2325 p = buffer + strlenW( buffer );
2326 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2327 strcpyW( p, mod->FullDllName.Buffer );
2328 RtlInitUnicodeString( &mod->FullDllName, buffer );
2329 RtlInitUnicodeString( &mod->BaseDllName, p );
2334 /***********************************************************************
2335 * __wine_process_init
2337 void __wine_process_init(void)
2339 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2343 ANSI_STRING func_name;
2344 void (* DECLSPEC_NORETURN init_func)(void);
2345 extern mode_t FILE_umask;
2347 main_exe_file = thread_init();
2349 /* retrieve current umask */
2350 FILE_umask = umask(0777);
2351 umask( FILE_umask );
2353 /* setup the load callback and create ntdll modref */
2354 wine_dll_set_callback( load_builtin_callback );
2356 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2358 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2361 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2362 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2363 0, (void **)&init_func )) != STATUS_SUCCESS)
2365 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );