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"
44 WINE_DEFAULT_DEBUG_CHANNEL(module);
45 WINE_DECLARE_DEBUG_CHANNEL(relay);
46 WINE_DECLARE_DEBUG_CHANNEL(snoop);
47 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
48 WINE_DECLARE_DEBUG_CHANNEL(imports);
50 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
52 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
53 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
55 static const char * const reason_names[] =
61 NULL, NULL, NULL, NULL,
65 static const WCHAR dllW[] = {'.','d','l','l',0};
67 /* internal representation of 32bit modules. per process. */
68 typedef struct _wine_modref
72 struct _wine_modref **deps;
75 /* info about the current builtin dll load */
76 /* used to keep track of things across the register_dll constructor call */
77 struct builtin_load_info
79 const WCHAR *load_path;
80 const WCHAR *filename;
85 static struct builtin_load_info default_load_info;
86 static struct builtin_load_info *builtin_load_info = &default_load_info;
88 static HANDLE main_exe_file;
89 static UINT tls_module_count; /* number of modules with TLS directory */
90 static UINT tls_total_size; /* total size of TLS storage */
91 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
93 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
95 static RTL_CRITICAL_SECTION loader_section;
96 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
98 0, 0, &loader_section,
99 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
100 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
102 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
104 static WINE_MODREF *cached_modref;
105 static WINE_MODREF *current_modref;
106 static WINE_MODREF *last_failed_modref;
108 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
109 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
110 DWORD exp_size, const char *name, int hint );
112 /* convert PE image VirtualAddress to Real Address */
113 static inline void *get_rva( HMODULE module, DWORD va )
115 return (void *)((char *)module + va);
118 /* check whether the file name contains a path */
119 static inline int contains_path( LPCWSTR name )
121 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
124 /* convert from straight ASCII to Unicode without depending on the current codepage */
125 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
127 while (len--) *dst++ = (unsigned char)*src++;
131 /*************************************************************************
132 * call_dll_entry_point
134 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
135 * their entry point, so we need a small asm wrapper.
138 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
139 __ASM_GLOBAL_FUNC(call_dll_entry_point,
147 "movl 8(%ebp),%eax\n\t"
149 "leal -4(%ebp),%esp\n\t"
154 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
155 UINT reason, void *reserved )
157 return proc( module, reason, reserved );
159 #endif /* __i386__ */
163 /*************************************************************************
166 * Entry point for stub functions.
168 static void stub_entry_point( const char *dll, const char *name, ... )
170 EXCEPTION_RECORD rec;
172 rec.ExceptionCode = EXCEPTION_WINE_STUB;
173 rec.ExceptionFlags = EH_NONCONTINUABLE;
174 rec.ExceptionRecord = NULL;
176 rec.ExceptionAddress = __builtin_return_address(0);
178 rec.ExceptionAddress = *((void **)&dll - 1);
180 rec.NumberParameters = 2;
181 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
182 rec.ExceptionInformation[1] = (ULONG_PTR)name;
183 for (;;) RtlRaiseException( &rec );
187 #include "pshpack1.h"
190 BYTE popl_eax; /* popl %eax */
191 BYTE pushl1; /* pushl $name */
193 BYTE pushl2; /* pushl $dll */
195 BYTE pushl_eax; /* pushl %eax */
196 BYTE jmp; /* jmp stub_entry_point */
201 /*************************************************************************
204 * Allocate a stub entry point.
206 static ULONG_PTR allocate_stub( const char *dll, const char *name )
208 #define MAX_SIZE 65536
209 static struct stub *stubs;
210 static unsigned int nb_stubs;
213 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
217 SIZE_T size = MAX_SIZE;
218 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
219 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
222 stub = &stubs[nb_stubs++];
223 stub->popl_eax = 0x58; /* popl %eax */
224 stub->pushl1 = 0x68; /* pushl $name */
226 stub->pushl2 = 0x68; /* pushl $dll */
228 stub->pushl_eax = 0x50; /* pushl %eax */
229 stub->jmp = 0xe9; /* jmp stub_entry_point */
230 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
231 return (ULONG_PTR)stub;
235 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
236 #endif /* __i386__ */
239 /*************************************************************************
242 * Looks for the referenced HMODULE in the current process
243 * The loader_section must be locked while calling this function.
245 static WINE_MODREF *get_modref( HMODULE hmod )
247 PLIST_ENTRY mark, entry;
250 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
252 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
253 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
255 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
256 if (mod->BaseAddress == hmod)
257 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
258 if (mod->BaseAddress > (void*)hmod) break;
264 /**********************************************************************
265 * find_basename_module
267 * Find a module from its base name.
268 * The loader_section must be locked while calling this function
270 static WINE_MODREF *find_basename_module( LPCWSTR name )
272 PLIST_ENTRY mark, entry;
274 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
275 return cached_modref;
277 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
278 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
280 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
281 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
283 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
284 return cached_modref;
291 /**********************************************************************
292 * find_fullname_module
294 * Find a module from its full path name.
295 * The loader_section must be locked while calling this function
297 static WINE_MODREF *find_fullname_module( LPCWSTR name )
299 PLIST_ENTRY mark, entry;
301 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
302 return cached_modref;
304 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
305 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
307 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
308 if (!strcmpiW( name, mod->FullDllName.Buffer ))
310 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
311 return cached_modref;
318 /*************************************************************************
319 * find_forwarded_export
321 * Find the final function pointer for a forwarded function.
322 * The loader_section must be locked while calling this function.
324 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
326 const IMAGE_EXPORT_DIRECTORY *exports;
330 const char *end = strrchr(forward, '.');
333 if (!end) return NULL;
334 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
335 ascii_to_unicode( mod_name, forward, end - forward );
336 mod_name[end - forward] = 0;
337 if (!strchrW( mod_name, '.' ))
339 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
340 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
343 if (!(wm = find_basename_module( mod_name )))
345 ERR("module not found for forward '%s' used by %s\n",
346 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
349 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
350 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
351 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
355 ERR("function not found for forward '%s' used by %s."
356 " If you are using builtin %s, try using the native one instead.\n",
357 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
358 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
364 /*************************************************************************
365 * find_ordinal_export
367 * Find an exported function by ordinal.
368 * The exports base must have been subtracted from the ordinal already.
369 * The loader_section must be locked while calling this function.
371 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
372 DWORD exp_size, DWORD ordinal )
375 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
377 if (ordinal >= exports->NumberOfFunctions)
379 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
382 if (!functions[ordinal]) return NULL;
384 proc = get_rva( module, functions[ordinal] );
386 /* if the address falls into the export dir, it's a forward */
387 if (((const char *)proc >= (const char *)exports) &&
388 ((const char *)proc < (const char *)exports + exp_size))
389 return find_forwarded_export( module, (const char *)proc );
393 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
394 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
398 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
399 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
405 /*************************************************************************
408 * Find an exported function by name.
409 * The loader_section must be locked while calling this function.
411 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
412 DWORD exp_size, const char *name, int hint )
414 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
415 const DWORD *names = get_rva( module, exports->AddressOfNames );
416 int min = 0, max = exports->NumberOfNames - 1;
418 /* first check the hint */
419 if (hint >= 0 && hint <= max)
421 char *ename = get_rva( module, names[hint] );
422 if (!strcmp( ename, name ))
423 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
426 /* then do a binary search */
429 int res, pos = (min + max) / 2;
430 char *ename = get_rva( module, names[pos] );
431 if (!(res = strcmp( ename, name )))
432 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
433 if (res > 0) max = pos - 1;
441 /*************************************************************************
444 * Import the dll specified by the given import descriptor.
445 * The loader_section must be locked while calling this function.
447 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
452 const IMAGE_EXPORT_DIRECTORY *exports;
454 const IMAGE_THUNK_DATA *import_list;
455 IMAGE_THUNK_DATA *thunk_list;
457 const char *name = get_rva( module, descr->Name );
458 DWORD len = strlen(name);
460 SIZE_T protect_size = 0;
463 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
464 if (descr->u.OriginalFirstThunk)
465 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
467 import_list = thunk_list;
469 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
471 if (len * sizeof(WCHAR) < sizeof(buffer))
473 ascii_to_unicode( buffer, name, len );
475 status = load_dll( load_path, buffer, 0, &wmImp );
477 else /* need to allocate a larger buffer */
479 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
480 if (!ptr) return NULL;
481 ascii_to_unicode( ptr, name, len );
483 status = load_dll( load_path, ptr, 0, &wmImp );
484 RtlFreeHeap( GetProcessHeap(), 0, ptr );
489 if (status == STATUS_DLL_NOT_FOUND)
490 ERR("Library %s (which is needed by %s) not found\n",
491 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
493 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
494 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
498 /* unprotect the import address table since it can be located in
499 * readonly section */
500 while (import_list[protect_size].u1.Ordinal) protect_size++;
501 protect_base = thunk_list;
502 protect_size *= sizeof(*thunk_list);
503 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
504 &protect_size, PAGE_WRITECOPY, &protect_old );
506 imp_mod = wmImp->ldr.BaseAddress;
507 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
511 /* set all imported function to deadbeef */
512 while (import_list->u1.Ordinal)
514 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
516 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
517 WARN("No implementation for %s.%d", name, ordinal );
518 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
522 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
523 WARN("No implementation for %s.%s", name, pe_name->Name );
524 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
526 WARN(" imported from %s, allocating stub %p\n",
527 debugstr_w(current_modref->ldr.FullDllName.Buffer),
528 (void *)thunk_list->u1.Function );
535 while (import_list->u1.Ordinal)
537 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
539 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
541 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
542 ordinal - exports->Base );
543 if (!thunk_list->u1.Function)
545 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
546 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
547 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
548 (void *)thunk_list->u1.Function );
550 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
552 else /* import by name */
554 IMAGE_IMPORT_BY_NAME *pe_name;
555 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
556 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
557 (const char*)pe_name->Name, pe_name->Hint );
558 if (!thunk_list->u1.Function)
560 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
561 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
562 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
563 (void *)thunk_list->u1.Function );
565 TRACE_(imports)("--- %s %s.%d = %p\n",
566 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
573 /* restore old protection of the import address table */
574 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
579 /****************************************************************
582 * Fixup all imports of a given module.
583 * The loader_section must be locked while calling this function.
585 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
588 const IMAGE_IMPORT_DESCRIPTOR *imports;
593 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
594 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
596 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
597 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
598 return STATUS_SUCCESS;
601 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
603 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
605 /* Allocate module dependency list */
606 wm->nDeps = nb_imports;
607 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
609 /* load the imported modules. They are automatically
610 * added to the modref list of the process.
612 prev = current_modref;
614 status = STATUS_SUCCESS;
615 for (i = 0; i < nb_imports; i++)
617 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
618 status = STATUS_DLL_NOT_FOUND;
620 current_modref = prev;
625 /*************************************************************************
628 * Allocate a WINE_MODREF structure and add it to the process list
629 * The loader_section must be locked while calling this function.
631 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
635 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
636 PLIST_ENTRY entry, mark;
638 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
643 wm->ldr.BaseAddress = hModule;
644 wm->ldr.EntryPoint = NULL;
645 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
646 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
647 wm->ldr.LoadCount = 1;
648 wm->ldr.TlsIndex = -1;
649 wm->ldr.SectionHandle = NULL;
650 wm->ldr.CheckSum = 0;
651 wm->ldr.TimeDateStamp = 0;
653 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
654 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
655 else p = wm->ldr.FullDllName.Buffer;
656 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
658 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
660 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
661 if (nt->OptionalHeader.AddressOfEntryPoint)
662 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
665 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
666 &wm->ldr.InLoadOrderModuleList);
668 /* insert module in MemoryList, sorted in increasing base addresses */
669 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
670 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
672 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
675 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
676 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
677 wm->ldr.InMemoryOrderModuleList.Flink = entry;
678 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
680 /* wait until init is called for inserting into this list */
681 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
682 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
684 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
686 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
687 VIRTUAL_SetForceExec( TRUE );
693 /*************************************************************************
696 * Allocate the process-wide structure for module TLS storage.
698 static NTSTATUS alloc_process_tls(void)
700 PLIST_ENTRY mark, entry;
702 const IMAGE_TLS_DIRECTORY *dir;
705 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
706 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
708 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
709 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
710 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
712 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
714 tls_total_size += size;
717 if (!tls_module_count) return STATUS_SUCCESS;
719 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
721 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
722 if (!tls_dirs) return STATUS_NO_MEMORY;
724 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
726 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
727 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
728 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
731 *(DWORD *)dir->AddressOfIndex = i;
733 mod->LoadCount = -1; /* can't unload it */
736 return STATUS_SUCCESS;
740 /*************************************************************************
743 * Allocate the per-thread structure for module TLS storage.
745 static NTSTATUS alloc_thread_tls(void)
751 if (!tls_module_count) return STATUS_SUCCESS;
753 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
754 tls_module_count * sizeof(*pointers) )))
755 return STATUS_NO_MEMORY;
757 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
759 RtlFreeHeap( GetProcessHeap(), 0, pointers );
760 return STATUS_NO_MEMORY;
763 for (i = 0; i < tls_module_count; i++)
765 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
766 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
768 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
769 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
770 (void *)dir->StartAddressOfRawData, data );
773 memcpy( data, (void *)dir->StartAddressOfRawData, size );
775 memset( data, 0, dir->SizeOfZeroFill );
776 data += dir->SizeOfZeroFill;
778 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
779 return STATUS_SUCCESS;
783 /*************************************************************************
786 static void call_tls_callbacks( HMODULE module, UINT reason )
788 const IMAGE_TLS_DIRECTORY *dir;
789 const PIMAGE_TLS_CALLBACK *callback;
792 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
793 if (!dir || !dir->AddressOfCallBacks) return;
795 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
798 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
799 GetCurrentThreadId(), *callback, module, reason_names[reason] );
802 (*callback)( module, reason, NULL );
807 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
808 GetCurrentThreadId(), callback, module, reason_names[reason] );
813 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
814 GetCurrentThreadId(), *callback, module, reason_names[reason] );
819 /*************************************************************************
822 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
826 DLLENTRYPROC entry = wm->ldr.EntryPoint;
827 void *module = wm->ldr.BaseAddress;
829 /* Skip calls for modules loaded with special load flags */
831 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
832 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
833 if (!entry) return TRUE;
837 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
838 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
839 mod_name[len / sizeof(WCHAR)] = 0;
840 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
841 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
842 reason_names[reason], lpReserved );
844 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
845 reason_names[reason], lpReserved );
847 retv = call_dll_entry_point( entry, module, reason, lpReserved );
849 /* The state of the module list may have changed due to the call
850 to the dll. We cannot assume that this module has not been
853 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
854 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
855 reason_names[reason], lpReserved, retv );
856 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
862 /*************************************************************************
865 * Send the process attach notification to all DLLs the given module
866 * depends on (recursively). This is somewhat complicated due to the fact that
868 * - we have to respect the module dependencies, i.e. modules implicitly
869 * referenced by another module have to be initialized before the module
870 * itself can be initialized
872 * - the initialization routine of a DLL can itself call LoadLibrary,
873 * thereby introducing a whole new set of dependencies (even involving
874 * the 'old' modules) at any time during the whole process
876 * (Note that this routine can be recursively entered not only directly
877 * from itself, but also via LoadLibrary from one of the called initialization
880 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
881 * the process *detach* notifications to be sent in the correct order.
882 * This must not only take into account module dependencies, but also
883 * 'hidden' dependencies created by modules calling LoadLibrary in their
884 * attach notification routine.
886 * The strategy is rather simple: we move a WINE_MODREF to the head of the
887 * list after the attach notification has returned. This implies that the
888 * detach notifications are called in the reverse of the sequence the attach
889 * notifications *returned*.
891 * The loader_section must be locked while calling this function.
893 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
895 NTSTATUS status = STATUS_SUCCESS;
898 if (process_detaching) return status;
900 /* prevent infinite recursion in case of cyclical dependencies */
901 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
902 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
905 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
907 /* Tag current MODREF to prevent recursive loop */
908 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
910 /* Recursively attach all DLLs this one depends on */
911 for ( i = 0; i < wm->nDeps; i++ )
913 if (!wm->deps[i]) continue;
914 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
917 /* Call DLL entry point */
918 if (status == STATUS_SUCCESS)
920 WINE_MODREF *prev = current_modref;
922 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
924 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
928 /* point to the name so LdrInitializeThunk can print it */
929 last_failed_modref = wm;
930 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
931 status = STATUS_DLL_INIT_FAILED;
933 current_modref = prev;
936 if (!wm->ldr.InInitializationOrderModuleList.Flink)
937 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
938 &wm->ldr.InInitializationOrderModuleList);
940 /* Remove recursion flag */
941 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
943 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
948 /**********************************************************************
949 * attach_implicitly_loaded_dlls
951 * Attach to the (builtin) dlls that have been implicitly loaded because
952 * of a dependency at the Unix level, but not imported at the Win32 level.
954 static void attach_implicitly_loaded_dlls( LPVOID reserved )
958 PLIST_ENTRY mark, entry;
960 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
961 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
963 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
965 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
966 TRACE( "found implicitly loaded %s, attaching to it\n",
967 debugstr_w(mod->BaseDllName.Buffer));
968 mod->LoadCount = -1; /* we can't unload it anyway */
969 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
970 break; /* restart the search from the start */
972 if (entry == mark) break; /* nothing found */
977 /*************************************************************************
980 * Send DLL process detach notifications. See the comment about calling
981 * sequence at process_attach. Unless the bForceDetach flag
982 * is set, only DLLs with zero refcount are notified.
984 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
986 PLIST_ENTRY mark, entry;
989 RtlEnterCriticalSection( &loader_section );
990 if (bForceDetach) process_detaching = 1;
991 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
994 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
996 mod = CONTAINING_RECORD(entry, LDR_MODULE,
997 InInitializationOrderModuleList);
998 /* Check whether to detach this DLL */
999 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1001 if ( mod->LoadCount && !bForceDetach )
1004 /* Call detach notification */
1005 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1006 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1007 DLL_PROCESS_DETACH, lpReserved );
1009 /* Restart at head of WINE_MODREF list, as entries might have
1010 been added and/or removed while performing the call ... */
1013 } while (entry != mark);
1015 RtlLeaveCriticalSection( &loader_section );
1018 /*************************************************************************
1019 * MODULE_DllThreadAttach
1021 * Send DLL thread attach notifications. These are sent in the
1022 * reverse sequence of process detach notification.
1025 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1027 PLIST_ENTRY mark, entry;
1031 /* don't do any attach calls if process is exiting */
1032 if (process_detaching) return STATUS_SUCCESS;
1033 /* FIXME: there is still a race here */
1035 RtlEnterCriticalSection( &loader_section );
1037 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1039 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1040 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1042 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1043 InInitializationOrderModuleList);
1044 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1046 if ( mod->Flags & LDR_NO_DLL_CALLS )
1049 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1050 DLL_THREAD_ATTACH, lpReserved );
1054 RtlLeaveCriticalSection( &loader_section );
1058 /******************************************************************
1059 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1062 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1065 NTSTATUS ret = STATUS_SUCCESS;
1067 RtlEnterCriticalSection( &loader_section );
1069 wm = get_modref( hModule );
1070 if (!wm || wm->ldr.TlsIndex != -1)
1071 ret = STATUS_DLL_NOT_FOUND;
1073 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1075 RtlLeaveCriticalSection( &loader_section );
1080 /******************************************************************
1081 * LdrFindEntryForAddress (NTDLL.@)
1083 * The loader_section must be locked while calling this function
1085 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1087 PLIST_ENTRY mark, entry;
1090 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1091 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1093 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1094 if ((const void *)mod->BaseAddress <= addr &&
1095 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1098 return STATUS_SUCCESS;
1100 if ((const void *)mod->BaseAddress > addr) break;
1102 return STATUS_NO_MORE_ENTRIES;
1105 /******************************************************************
1106 * LdrLockLoaderLock (NTDLL.@)
1108 * Note: flags are not implemented.
1109 * Flag 0x01 is used to raise exceptions on errors.
1110 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1112 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1114 if (flags) FIXME( "flags %x not supported\n", flags );
1116 if (result) *result = 1;
1117 if (!magic) return STATUS_INVALID_PARAMETER_3;
1118 RtlEnterCriticalSection( &loader_section );
1119 *magic = GetCurrentThreadId();
1120 return STATUS_SUCCESS;
1124 /******************************************************************
1125 * LdrUnlockLoaderUnlock (NTDLL.@)
1127 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1131 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1132 RtlLeaveCriticalSection( &loader_section );
1134 return STATUS_SUCCESS;
1138 /******************************************************************
1139 * LdrGetProcedureAddress (NTDLL.@)
1141 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1142 ULONG ord, PVOID *address)
1144 IMAGE_EXPORT_DIRECTORY *exports;
1146 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1148 RtlEnterCriticalSection( &loader_section );
1150 /* check if the module itself is invalid to return the proper error */
1151 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1152 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1153 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1155 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1156 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1160 ret = STATUS_SUCCESS;
1164 RtlLeaveCriticalSection( &loader_section );
1169 /***********************************************************************
1172 * Check if a loaded native dll is a Wine fake dll.
1174 static BOOL is_fake_dll( const void *base )
1176 static const char fakedll_signature[] = "Wine placeholder DLL";
1177 const IMAGE_DOS_HEADER *dos = base;
1179 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1180 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1185 /***********************************************************************
1186 * get_builtin_fullname
1188 * Build the full pathname for a builtin dll.
1190 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1192 static const WCHAR soW[] = {'.','s','o',0};
1193 WCHAR *p, *fullname;
1194 size_t i, len = strlen(filename);
1196 /* check if path can correspond to the dll we have */
1197 if (path && (p = strrchrW( path, '\\' )))
1200 for (i = 0; i < len; i++)
1201 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1202 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1204 /* the filename matches, use path as the full path */
1206 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1208 memcpy( fullname, path, len * sizeof(WCHAR) );
1215 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1216 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1218 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1219 p = fullname + system_dir.Length / sizeof(WCHAR);
1220 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1221 ascii_to_unicode( p, filename, len + 1 );
1227 /***********************************************************************
1228 * load_builtin_callback
1230 * Load a library in memory; callback function for wine_dll_register
1232 static void load_builtin_callback( void *module, const char *filename )
1234 static const WCHAR emptyW[1];
1236 IMAGE_NT_HEADERS *nt;
1239 const WCHAR *load_path;
1244 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1247 if (!(nt = RtlImageNtHeader( module )))
1249 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1250 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1254 size = nt->OptionalHeader.SizeOfImage;
1255 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1256 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1257 /* create the MODREF */
1259 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1261 ERR( "can't load %s\n", filename );
1262 builtin_load_info->status = STATUS_NO_MEMORY;
1266 wm = alloc_module( module, fullname );
1267 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1270 ERR( "can't load %s\n", filename );
1271 builtin_load_info->status = STATUS_NO_MEMORY;
1274 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1276 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1277 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1279 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1285 load_path = builtin_load_info->load_path;
1286 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1287 if (!load_path) load_path = emptyW;
1288 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1290 /* the module has only be inserted in the load & memory order lists */
1291 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1292 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1293 /* FIXME: free the modref */
1294 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1299 builtin_load_info->wm = wm;
1300 TRACE( "loaded %s %p %p\n", filename, wm, module );
1302 /* send the DLL load event */
1304 SERVER_START_REQ( load_dll )
1308 req->size = nt->OptionalHeader.SizeOfImage;
1309 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1310 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1311 req->name = &wm->ldr.FullDllName.Buffer;
1312 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1313 wine_server_call( req );
1317 /* setup relay debugging entry points */
1318 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1322 /******************************************************************************
1323 * load_native_dll (internal)
1325 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1326 DWORD flags, WINE_MODREF** pwm )
1330 OBJECT_ATTRIBUTES attr;
1332 IMAGE_NT_HEADERS *nt;
1337 TRACE("Trying native dll %s\n", debugstr_w(name));
1339 attr.Length = sizeof(attr);
1340 attr.RootDirectory = 0;
1341 attr.ObjectName = NULL;
1342 attr.Attributes = 0;
1343 attr.SecurityDescriptor = NULL;
1344 attr.SecurityQualityOfService = NULL;
1347 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1348 &attr, &size, 0, SEC_IMAGE, file );
1349 if (status != STATUS_SUCCESS) return status;
1352 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1353 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1355 if (status != STATUS_SUCCESS) return status;
1357 if (is_fake_dll( module ))
1359 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1360 NtUnmapViewOfSection( NtCurrentProcess(), module );
1361 return STATUS_DLL_NOT_FOUND;
1364 /* create the MODREF */
1366 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1370 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1372 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1374 /* the module has only be inserted in the load & memory order lists */
1375 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1376 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1378 /* FIXME: there are several more dangling references
1379 * left. Including dlls loaded by this dll before the
1380 * failed one. Unrolling is rather difficult with the
1381 * current structure and we can leave them lying
1382 * around with no problems, so we don't care.
1383 * As these might reference our wm, we don't free it.
1389 /* send DLL load event */
1391 nt = RtlImageNtHeader( module );
1393 SERVER_START_REQ( load_dll )
1397 req->size = nt->OptionalHeader.SizeOfImage;
1398 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1399 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1400 req->name = &wm->ldr.FullDllName.Buffer;
1401 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1402 wine_server_call( req );
1406 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1408 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1410 wm->ldr.LoadCount = 1;
1412 return STATUS_SUCCESS;
1416 /***********************************************************************
1419 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1420 DWORD flags, WINE_MODREF** pwm )
1422 char error[256], dllname[MAX_PATH];
1423 const WCHAR *name, *p;
1425 void *handle = NULL;
1426 struct builtin_load_info info, *prev_info;
1428 /* Fix the name in case we have a full path and extension */
1430 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1431 if ((p = strrchrW( name, '/' ))) name = p + 1;
1433 /* load_library will modify info.status. Note also that load_library can be
1434 * called several times, if the .so file we're loading has dependencies.
1435 * info.status will gather all the errors we may get while loading all these
1438 info.load_path = load_path;
1439 info.filename = NULL;
1440 info.status = STATUS_SUCCESS;
1443 if (file) /* we have a real file, try to load it */
1445 UNICODE_STRING nt_name;
1446 ANSI_STRING unix_name;
1448 TRACE("Trying built-in %s\n", debugstr_w(path));
1450 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1451 return STATUS_DLL_NOT_FOUND;
1453 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1455 RtlFreeUnicodeString( &nt_name );
1456 return STATUS_DLL_NOT_FOUND;
1458 prev_info = builtin_load_info;
1459 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1460 builtin_load_info = &info;
1461 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1462 builtin_load_info = prev_info;
1463 RtlFreeUnicodeString( &nt_name );
1464 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1467 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1468 return STATUS_INVALID_IMAGE_FORMAT;
1475 TRACE("Trying built-in %s\n", debugstr_w(name));
1477 /* we don't want to depend on the current codepage here */
1478 len = strlenW( name ) + 1;
1479 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1480 for (i = 0; i < len; i++)
1482 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1483 dllname[i] = (char)name[i];
1484 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1487 prev_info = builtin_load_info;
1488 builtin_load_info = &info;
1489 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1490 builtin_load_info = prev_info;
1495 /* The file does not exist -> WARN() */
1496 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1497 return STATUS_DLL_NOT_FOUND;
1499 /* ERR() for all other errors (missing functions, ...) */
1500 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1501 return STATUS_PROCEDURE_NOT_FOUND;
1505 if (info.status != STATUS_SUCCESS)
1507 wine_dll_unload( handle );
1513 PLIST_ENTRY mark, entry;
1515 /* The constructor wasn't called, this means the .so is already
1516 * loaded under a different name. Try to find the wm for it. */
1518 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1519 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1521 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1522 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1524 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1525 TRACE( "Found already loaded module %s for builtin %s\n",
1526 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1530 wine_dll_unload( handle ); /* release the libdl refcount */
1531 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1532 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1536 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1537 info.wm->ldr.LoadCount = 1;
1538 info.wm->ldr.SectionHandle = handle;
1542 return STATUS_SUCCESS;
1546 /***********************************************************************
1549 * Find the file (or already loaded module) for a given dll name.
1551 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1552 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1554 OBJECT_ATTRIBUTES attr;
1556 UNICODE_STRING nt_name;
1557 WCHAR *file_part, *ext, *dllname;
1560 /* first append .dll if needed */
1563 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1565 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1566 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1567 return STATUS_NO_MEMORY;
1568 strcpyW( dllname, libname );
1569 strcatW( dllname, dllW );
1573 nt_name.Buffer = NULL;
1575 if (!contains_path( libname ))
1577 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1580 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1582 /* we need to search for it */
1583 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1586 if (len >= *size) goto overflow;
1587 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1589 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1591 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1592 return STATUS_NO_MEMORY;
1594 attr.Length = sizeof(attr);
1595 attr.RootDirectory = 0;
1596 attr.Attributes = OBJ_CASE_INSENSITIVE;
1597 attr.ObjectName = &nt_name;
1598 attr.SecurityDescriptor = NULL;
1599 attr.SecurityQualityOfService = NULL;
1600 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1606 if (!contains_path( libname ))
1608 /* if libname doesn't contain a path at all, we simply return the name as is,
1609 * to be loaded as builtin */
1610 len = strlenW(libname) * sizeof(WCHAR);
1611 if (len >= *size) goto overflow;
1612 strcpyW( filename, libname );
1617 /* absolute path name, or relative path name but not found above */
1619 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1621 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1622 return STATUS_NO_MEMORY;
1624 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1625 if (len >= *size) goto overflow;
1626 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1627 if (!(*pwm = find_fullname_module( filename )) && handle)
1629 attr.Length = sizeof(attr);
1630 attr.RootDirectory = 0;
1631 attr.Attributes = OBJ_CASE_INSENSITIVE;
1632 attr.ObjectName = &nt_name;
1633 attr.SecurityDescriptor = NULL;
1634 attr.SecurityQualityOfService = NULL;
1635 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1638 RtlFreeUnicodeString( &nt_name );
1639 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1640 return STATUS_SUCCESS;
1643 RtlFreeUnicodeString( &nt_name );
1644 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1645 *size = len + sizeof(WCHAR);
1646 return STATUS_BUFFER_TOO_SMALL;
1650 /***********************************************************************
1651 * load_dll (internal)
1653 * Load a PE style module according to the load order.
1654 * The loader_section must be locked while calling this function.
1656 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1658 enum loadorder loadorder;
1662 WINE_MODREF *main_exe;
1666 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1669 size = sizeof(buffer);
1672 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1673 if (nts == STATUS_SUCCESS) break;
1674 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1675 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1676 /* grow the buffer and retry */
1677 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1680 if (*pwm) /* found already loaded module */
1682 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1684 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1686 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1687 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1688 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1689 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1690 return STATUS_SUCCESS;
1693 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1694 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1699 nts = STATUS_NO_MEMORY;
1702 nts = STATUS_DLL_NOT_FOUND;
1705 case LO_NATIVE_BUILTIN:
1706 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1709 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1710 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1711 /* not in PE format, maybe it's a builtin */
1712 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1714 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1715 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1718 case LO_BUILTIN_NATIVE:
1719 case LO_DEFAULT: /* default is builtin,native */
1720 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1721 if (!handle) break; /* nothing else we can try */
1722 /* file is not a builtin library, try without using the specified file */
1723 if (nts != STATUS_SUCCESS)
1724 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1725 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1726 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1728 /* stub-only dll, try native */
1729 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1730 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1731 nts = STATUS_DLL_NOT_FOUND;
1733 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1734 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1738 if (nts == STATUS_SUCCESS)
1740 /* Initialize DLL just loaded */
1741 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1742 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1743 (*pwm)->ldr.BaseAddress);
1744 if (handle) NtClose( handle );
1745 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1749 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1750 if (handle) NtClose( handle );
1751 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1755 /******************************************************************
1756 * LdrLoadDll (NTDLL.@)
1758 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1759 const UNICODE_STRING *libname, HMODULE* hModule)
1764 RtlEnterCriticalSection( &loader_section );
1766 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1767 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1769 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1771 nts = process_attach( wm, NULL );
1772 if (nts != STATUS_SUCCESS)
1774 LdrUnloadDll(wm->ldr.BaseAddress);
1778 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1780 RtlLeaveCriticalSection( &loader_section );
1785 /******************************************************************
1786 * LdrGetDllHandle (NTDLL.@)
1788 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1796 RtlEnterCriticalSection( &loader_section );
1798 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1801 size = sizeof(buffer);
1804 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1805 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1806 if (status != STATUS_BUFFER_TOO_SMALL) break;
1807 /* grow the buffer and retry */
1808 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1811 if (status == STATUS_SUCCESS)
1813 if (wm) *base = wm->ldr.BaseAddress;
1814 else status = STATUS_DLL_NOT_FOUND;
1817 RtlLeaveCriticalSection( &loader_section );
1818 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1823 /******************************************************************
1824 * LdrAddRefDll (NTDLL.@)
1826 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1828 NTSTATUS ret = STATUS_SUCCESS;
1831 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
1833 RtlEnterCriticalSection( &loader_section );
1835 if ((wm = get_modref( module )))
1837 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
1838 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1840 else ret = STATUS_INVALID_PARAMETER;
1842 RtlLeaveCriticalSection( &loader_section );
1847 /******************************************************************
1848 * LdrQueryProcessModuleInformation
1851 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1852 ULONG buf_size, ULONG* req_size)
1854 SYSTEM_MODULE* sm = &smi->Modules[0];
1855 ULONG size = sizeof(ULONG);
1856 NTSTATUS nts = STATUS_SUCCESS;
1859 PLIST_ENTRY mark, entry;
1862 smi->ModulesCount = 0;
1864 RtlEnterCriticalSection( &loader_section );
1865 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1866 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1868 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1869 size += sizeof(*sm);
1870 if (size <= buf_size)
1872 sm->Reserved1 = 0; /* FIXME */
1873 sm->Reserved2 = 0; /* FIXME */
1874 sm->ImageBaseAddress = mod->BaseAddress;
1875 sm->ImageSize = mod->SizeOfImage;
1876 sm->Flags = mod->Flags;
1877 sm->Id = 0; /* FIXME */
1878 sm->Rank = 0; /* FIXME */
1879 sm->Unknown = 0; /* FIXME */
1881 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1882 str.Buffer = (char*)sm->Name;
1883 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1884 ptr = strrchr(str.Buffer, '\\');
1885 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1887 smi->ModulesCount++;
1890 else nts = STATUS_INFO_LENGTH_MISMATCH;
1892 RtlLeaveCriticalSection( &loader_section );
1894 if (req_size) *req_size = size;
1900 /******************************************************************
1901 * RtlDllShutdownInProgress (NTDLL.@)
1903 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
1905 return process_detaching;
1909 /******************************************************************
1910 * LdrShutdownProcess (NTDLL.@)
1913 void WINAPI LdrShutdownProcess(void)
1916 process_detach( TRUE, (LPVOID)1 );
1919 /******************************************************************
1920 * LdrShutdownThread (NTDLL.@)
1923 void WINAPI LdrShutdownThread(void)
1925 PLIST_ENTRY mark, entry;
1930 /* don't do any detach calls if process is exiting */
1931 if (process_detaching) return;
1932 /* FIXME: there is still a race here */
1934 RtlEnterCriticalSection( &loader_section );
1936 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1937 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1939 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1940 InInitializationOrderModuleList);
1941 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1943 if ( mod->Flags & LDR_NO_DLL_CALLS )
1946 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1947 DLL_THREAD_DETACH, NULL );
1950 RtlLeaveCriticalSection( &loader_section );
1951 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
1955 /***********************************************************************
1959 static void free_modref( WINE_MODREF *wm )
1961 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1962 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1963 if (wm->ldr.InInitializationOrderModuleList.Flink)
1964 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
1966 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
1967 if (!TRACE_ON(module))
1968 TRACE_(loaddll)("Unloaded module %s : %s\n",
1969 debugstr_w(wm->ldr.FullDllName.Buffer),
1970 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1972 SERVER_START_REQ( unload_dll )
1974 req->base = wm->ldr.BaseAddress;
1975 wine_server_call( req );
1979 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
1980 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1981 if (cached_modref == wm) cached_modref = NULL;
1982 RtlFreeUnicodeString( &wm->ldr.FullDllName );
1983 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1984 RtlFreeHeap( GetProcessHeap(), 0, wm );
1987 /***********************************************************************
1988 * MODULE_FlushModrefs
1990 * Remove all unused modrefs and call the internal unloading routines
1991 * for the library type.
1993 * The loader_section must be locked while calling this function.
1995 static void MODULE_FlushModrefs(void)
1997 PLIST_ENTRY mark, entry, prev;
2001 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2002 for (entry = mark->Blink; entry != mark; entry = prev)
2004 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2005 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2006 prev = entry->Blink;
2007 if (!mod->LoadCount) free_modref( wm );
2010 /* check load order list too for modules that haven't been initialized yet */
2011 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2012 for (entry = mark->Blink; entry != mark; entry = prev)
2014 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2015 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2016 prev = entry->Blink;
2017 if (!mod->LoadCount) free_modref( wm );
2021 /***********************************************************************
2022 * MODULE_DecRefCount
2024 * The loader_section must be locked while calling this function.
2026 static void MODULE_DecRefCount( WINE_MODREF *wm )
2030 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2033 if ( wm->ldr.LoadCount <= 0 )
2036 --wm->ldr.LoadCount;
2037 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2039 if ( wm->ldr.LoadCount == 0 )
2041 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2043 for ( i = 0; i < wm->nDeps; i++ )
2045 MODULE_DecRefCount( wm->deps[i] );
2047 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2051 /******************************************************************
2052 * LdrUnloadDll (NTDLL.@)
2056 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2058 NTSTATUS retv = STATUS_SUCCESS;
2060 TRACE("(%p)\n", hModule);
2062 RtlEnterCriticalSection( &loader_section );
2064 /* if we're stopping the whole process (and forcing the removal of all
2065 * DLLs) the library will be freed anyway
2067 if (!process_detaching)
2072 if ((wm = get_modref( hModule )) != NULL)
2074 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2076 /* Recursively decrement reference counts */
2077 MODULE_DecRefCount( wm );
2079 /* Call process detach notifications */
2080 if ( free_lib_count <= 1 )
2082 process_detach( FALSE, NULL );
2083 MODULE_FlushModrefs();
2089 retv = STATUS_DLL_NOT_FOUND;
2094 RtlLeaveCriticalSection( &loader_section );
2099 /***********************************************************************
2100 * RtlImageNtHeader (NTDLL.@)
2102 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2104 IMAGE_NT_HEADERS *ret;
2108 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2111 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2113 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2114 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2126 /******************************************************************
2127 * LdrInitializeThunk (NTDLL.@)
2130 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2135 PEB *peb = NtCurrentTeb()->Peb;
2136 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2138 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2140 /* allocate the modref for the main exe (if not already done) */
2141 wm = get_modref( peb->ImageBaseAddress );
2143 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2145 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2148 wm->ldr.LoadCount = -1; /* can't unload main exe */
2150 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2151 version_init( wm->ldr.FullDllName.Buffer );
2153 /* the main exe needs to be the first in the load order list */
2154 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2155 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2157 status = server_init_process_done();
2158 if (status != STATUS_SUCCESS) goto error;
2160 RtlEnterCriticalSection( &loader_section );
2162 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2163 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2164 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2165 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2166 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2168 if (last_failed_modref)
2169 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2172 attach_implicitly_loaded_dlls( (LPVOID)1 );
2174 RtlLeaveCriticalSection( &loader_section );
2176 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2180 ERR( "Main exe initialization for %s failed, status %x\n",
2181 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2186 /***********************************************************************
2187 * RtlImageDirectoryEntryToData (NTDLL.@)
2189 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2191 const IMAGE_NT_HEADERS *nt;
2194 if ((ULONG_PTR)module & 1) /* mapped as data file */
2196 module = (HMODULE)((ULONG_PTR)module & ~1);
2199 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2200 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2201 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2202 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2203 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2205 /* not mapped as image, need to find the section containing the virtual address */
2206 return RtlImageRvaToVa( nt, module, addr, NULL );
2210 /***********************************************************************
2211 * RtlImageRvaToSection (NTDLL.@)
2213 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2214 HMODULE module, DWORD rva )
2217 const IMAGE_SECTION_HEADER *sec;
2219 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2220 nt->FileHeader.SizeOfOptionalHeader);
2221 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2223 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2224 return (PIMAGE_SECTION_HEADER)sec;
2230 /***********************************************************************
2231 * RtlImageRvaToVa (NTDLL.@)
2233 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2234 DWORD rva, IMAGE_SECTION_HEADER **section )
2236 IMAGE_SECTION_HEADER *sec;
2238 if (section && *section) /* try this section first */
2241 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2244 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2246 if (section) *section = sec;
2247 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2251 /***********************************************************************
2252 * RtlPcToFileHeader (NTDLL.@)
2254 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2259 RtlEnterCriticalSection( &loader_section );
2260 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2261 RtlLeaveCriticalSection( &loader_section );
2267 /***********************************************************************
2268 * NtLoadDriver (NTDLL.@)
2269 * ZwLoadDriver (NTDLL.@)
2271 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2273 FIXME("(%p), stub!\n",DriverServiceName);
2274 return STATUS_NOT_IMPLEMENTED;
2278 /***********************************************************************
2279 * NtUnloadDriver (NTDLL.@)
2280 * ZwUnloadDriver (NTDLL.@)
2282 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2284 FIXME("(%p), stub!\n",DriverServiceName);
2285 return STATUS_NOT_IMPLEMENTED;
2289 /******************************************************************
2292 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2294 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2299 /******************************************************************
2300 * __wine_init_windows_dir (NTDLL.@)
2302 * Windows and system dir initialization once kernel32 has been loaded.
2304 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2306 PLIST_ENTRY mark, entry;
2309 RtlCreateUnicodeString( &system_dir, sysdir );
2311 /* prepend the system dir to the name of the already created modules */
2312 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2313 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2315 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2317 assert( mod->Flags & LDR_WINE_INTERNAL );
2319 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2320 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2321 if (!buffer) continue;
2322 strcpyW( buffer, system_dir.Buffer );
2323 p = buffer + strlenW( buffer );
2324 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2325 strcpyW( p, mod->FullDllName.Buffer );
2326 RtlInitUnicodeString( &mod->FullDllName, buffer );
2327 RtlInitUnicodeString( &mod->BaseDllName, p );
2332 /***********************************************************************
2333 * __wine_process_init
2335 void __wine_process_init(void)
2337 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2341 ANSI_STRING func_name;
2342 void (* DECLSPEC_NORETURN init_func)(void);
2343 extern mode_t FILE_umask;
2345 main_exe_file = thread_init();
2347 /* retrieve current umask */
2348 FILE_umask = umask(0777);
2349 umask( FILE_umask );
2351 /* setup the load callback and create ntdll modref */
2352 wine_dll_set_callback( load_builtin_callback );
2354 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2356 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2359 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2360 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2361 0, (void **)&init_func )) != STATUS_SUCCESS)
2363 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );