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"
39 #include "wine/library.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
43 #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 inline static void *get_rva( HMODULE module, DWORD va )
116 return (void *)((char *)module + va);
119 /* check whether the file name contains a path */
120 inline static 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 inline static 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 = strchr(forward, '.');
334 if (!end) return NULL;
335 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
336 ascii_to_unicode( mod_name, forward, end - forward );
337 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
339 if (!(wm = find_basename_module( mod_name )))
341 ERR("module not found for forward '%s' used by %s\n",
342 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
345 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
346 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
347 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
351 ERR("function not found for forward '%s' used by %s."
352 " If you are using builtin %s, try using the native one instead.\n",
353 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
354 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
360 /*************************************************************************
361 * find_ordinal_export
363 * Find an exported function by ordinal.
364 * The exports base must have been subtracted from the ordinal already.
365 * The loader_section must be locked while calling this function.
367 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
368 DWORD exp_size, DWORD ordinal )
371 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
373 if (ordinal >= exports->NumberOfFunctions)
375 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
378 if (!functions[ordinal]) return NULL;
380 proc = get_rva( module, functions[ordinal] );
382 /* if the address falls into the export dir, it's a forward */
383 if (((const char *)proc >= (const char *)exports) &&
384 ((const char *)proc < (const char *)exports + exp_size))
385 return find_forwarded_export( module, (const char *)proc );
389 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
390 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
394 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
395 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
401 /*************************************************************************
404 * Find an exported function by name.
405 * The loader_section must be locked while calling this function.
407 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
408 DWORD exp_size, const char *name, int hint )
410 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
411 const DWORD *names = get_rva( module, exports->AddressOfNames );
412 int min = 0, max = exports->NumberOfNames - 1;
414 /* first check the hint */
415 if (hint >= 0 && hint <= max)
417 char *ename = get_rva( module, names[hint] );
418 if (!strcmp( ename, name ))
419 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
422 /* then do a binary search */
425 int res, pos = (min + max) / 2;
426 char *ename = get_rva( module, names[pos] );
427 if (!(res = strcmp( ename, name )))
428 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
429 if (res > 0) max = pos - 1;
437 /*************************************************************************
440 * Import the dll specified by the given import descriptor.
441 * The loader_section must be locked while calling this function.
443 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
448 const IMAGE_EXPORT_DIRECTORY *exports;
450 const IMAGE_THUNK_DATA *import_list;
451 IMAGE_THUNK_DATA *thunk_list;
453 const char *name = get_rva( module, descr->Name );
454 DWORD len = strlen(name);
456 SIZE_T protect_size = 0;
459 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
460 if (descr->u.OriginalFirstThunk)
461 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
463 import_list = thunk_list;
465 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
467 if (len * sizeof(WCHAR) < sizeof(buffer))
469 ascii_to_unicode( buffer, name, len );
471 status = load_dll( load_path, buffer, 0, &wmImp );
473 else /* need to allocate a larger buffer */
475 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
476 if (!ptr) return NULL;
477 ascii_to_unicode( ptr, name, len );
479 status = load_dll( load_path, ptr, 0, &wmImp );
480 RtlFreeHeap( GetProcessHeap(), 0, ptr );
485 if (status == STATUS_DLL_NOT_FOUND)
486 ERR("Library %s (which is needed by %s) not found\n",
487 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
489 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
490 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
494 /* unprotect the import address table since it can be located in
495 * readonly section */
496 while (import_list[protect_size].u1.Ordinal) protect_size++;
497 protect_base = thunk_list;
498 protect_size *= sizeof(*thunk_list);
499 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
500 &protect_size, PAGE_WRITECOPY, &protect_old );
502 imp_mod = wmImp->ldr.BaseAddress;
503 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
507 /* set all imported function to deadbeef */
508 while (import_list->u1.Ordinal)
510 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
512 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
513 WARN("No implementation for %s.%d", name, ordinal );
514 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
518 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
519 WARN("No implementation for %s.%s", name, pe_name->Name );
520 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
522 WARN(" imported from %s, allocating stub %p\n",
523 debugstr_w(current_modref->ldr.FullDllName.Buffer),
524 (void *)thunk_list->u1.Function );
531 while (import_list->u1.Ordinal)
533 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
535 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
537 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
538 ordinal - exports->Base );
539 if (!thunk_list->u1.Function)
541 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
542 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
543 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
544 (void *)thunk_list->u1.Function );
546 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
548 else /* import by name */
550 IMAGE_IMPORT_BY_NAME *pe_name;
551 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
552 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
553 (const char*)pe_name->Name, pe_name->Hint );
554 if (!thunk_list->u1.Function)
556 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
557 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
558 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
559 (void *)thunk_list->u1.Function );
561 TRACE_(imports)("--- %s %s.%d = %p\n",
562 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
569 /* restore old protection of the import address table */
570 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
575 /****************************************************************
578 * Fixup all imports of a given module.
579 * The loader_section must be locked while calling this function.
581 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
584 const IMAGE_IMPORT_DESCRIPTOR *imports;
589 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
590 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
592 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
593 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
594 return STATUS_SUCCESS;
597 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
599 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
601 /* Allocate module dependency list */
602 wm->nDeps = nb_imports;
603 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
605 /* load the imported modules. They are automatically
606 * added to the modref list of the process.
608 prev = current_modref;
610 status = STATUS_SUCCESS;
611 for (i = 0; i < nb_imports; i++)
613 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
614 status = STATUS_DLL_NOT_FOUND;
616 current_modref = prev;
621 /*************************************************************************
624 * Allocate a WINE_MODREF structure and add it to the process list
625 * The loader_section must be locked while calling this function.
627 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
631 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
632 PLIST_ENTRY entry, mark;
634 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
639 wm->ldr.BaseAddress = hModule;
640 wm->ldr.EntryPoint = NULL;
641 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
642 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
643 wm->ldr.LoadCount = 1;
644 wm->ldr.TlsIndex = -1;
645 wm->ldr.SectionHandle = NULL;
646 wm->ldr.CheckSum = 0;
647 wm->ldr.TimeDateStamp = 0;
649 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
650 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
651 else p = wm->ldr.FullDllName.Buffer;
652 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
654 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
656 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
657 if (nt->OptionalHeader.AddressOfEntryPoint)
658 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
661 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
662 &wm->ldr.InLoadOrderModuleList);
664 /* insert module in MemoryList, sorted in increasing base addresses */
665 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
666 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
668 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
671 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
672 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
673 wm->ldr.InMemoryOrderModuleList.Flink = entry;
674 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
676 /* wait until init is called for inserting into this list */
677 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
678 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
683 /*************************************************************************
686 * Allocate the process-wide structure for module TLS storage.
688 static NTSTATUS alloc_process_tls(void)
690 PLIST_ENTRY mark, entry;
692 const IMAGE_TLS_DIRECTORY *dir;
695 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
696 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
698 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
699 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
700 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
702 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
704 tls_total_size += size;
707 if (!tls_module_count) return STATUS_SUCCESS;
709 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
711 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
712 if (!tls_dirs) return STATUS_NO_MEMORY;
714 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
716 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
717 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
718 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
721 *(DWORD *)dir->AddressOfIndex = i;
723 mod->LoadCount = -1; /* can't unload it */
726 return STATUS_SUCCESS;
730 /*************************************************************************
733 * Allocate the per-thread structure for module TLS storage.
735 static NTSTATUS alloc_thread_tls(void)
741 if (!tls_module_count) return STATUS_SUCCESS;
743 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
744 tls_module_count * sizeof(*pointers) )))
745 return STATUS_NO_MEMORY;
747 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
749 RtlFreeHeap( GetProcessHeap(), 0, pointers );
750 return STATUS_NO_MEMORY;
753 for (i = 0; i < tls_module_count; i++)
755 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
756 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
758 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
759 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
760 (void *)dir->StartAddressOfRawData, data );
763 memcpy( data, (void *)dir->StartAddressOfRawData, size );
765 memset( data, 0, dir->SizeOfZeroFill );
766 data += dir->SizeOfZeroFill;
768 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
769 return STATUS_SUCCESS;
773 /*************************************************************************
776 static void call_tls_callbacks( HMODULE module, UINT reason )
778 const IMAGE_TLS_DIRECTORY *dir;
779 const PIMAGE_TLS_CALLBACK *callback;
782 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
783 if (!dir || !dir->AddressOfCallBacks) return;
785 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
788 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
789 GetCurrentThreadId(), *callback, module, reason_names[reason] );
790 (*callback)( module, reason, NULL );
792 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
793 GetCurrentThreadId(), *callback, module, reason_names[reason] );
798 /*************************************************************************
801 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
805 DLLENTRYPROC entry = wm->ldr.EntryPoint;
806 void *module = wm->ldr.BaseAddress;
808 /* Skip calls for modules loaded with special load flags */
810 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
811 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
812 if (!entry) return TRUE;
816 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
817 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
818 mod_name[len / sizeof(WCHAR)] = 0;
819 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
820 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
821 reason_names[reason], lpReserved );
823 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
824 reason_names[reason], lpReserved );
826 retv = call_dll_entry_point( entry, module, reason, lpReserved );
828 /* The state of the module list may have changed due to the call
829 to the dll. We cannot assume that this module has not been
832 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
833 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
834 reason_names[reason], lpReserved, retv );
835 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
841 /*************************************************************************
844 * Send the process attach notification to all DLLs the given module
845 * depends on (recursively). This is somewhat complicated due to the fact that
847 * - we have to respect the module dependencies, i.e. modules implicitly
848 * referenced by another module have to be initialized before the module
849 * itself can be initialized
851 * - the initialization routine of a DLL can itself call LoadLibrary,
852 * thereby introducing a whole new set of dependencies (even involving
853 * the 'old' modules) at any time during the whole process
855 * (Note that this routine can be recursively entered not only directly
856 * from itself, but also via LoadLibrary from one of the called initialization
859 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
860 * the process *detach* notifications to be sent in the correct order.
861 * This must not only take into account module dependencies, but also
862 * 'hidden' dependencies created by modules calling LoadLibrary in their
863 * attach notification routine.
865 * The strategy is rather simple: we move a WINE_MODREF to the head of the
866 * list after the attach notification has returned. This implies that the
867 * detach notifications are called in the reverse of the sequence the attach
868 * notifications *returned*.
870 * The loader_section must be locked while calling this function.
872 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
874 NTSTATUS status = STATUS_SUCCESS;
877 if (process_detaching) return status;
879 /* prevent infinite recursion in case of cyclical dependencies */
880 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
881 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
884 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
886 /* Tag current MODREF to prevent recursive loop */
887 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
889 /* Recursively attach all DLLs this one depends on */
890 for ( i = 0; i < wm->nDeps; i++ )
892 if (!wm->deps[i]) continue;
893 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
896 /* Call DLL entry point */
897 if (status == STATUS_SUCCESS)
899 WINE_MODREF *prev = current_modref;
901 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
903 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
907 /* point to the name so LdrInitializeThunk can print it */
908 last_failed_modref = wm;
909 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
910 status = STATUS_DLL_INIT_FAILED;
912 current_modref = prev;
915 if (!wm->ldr.InInitializationOrderModuleList.Flink)
916 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
917 &wm->ldr.InInitializationOrderModuleList);
919 /* Remove recursion flag */
920 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
922 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
927 /**********************************************************************
928 * attach_implicitly_loaded_dlls
930 * Attach to the (builtin) dlls that have been implicitly loaded because
931 * of a dependency at the Unix level, but not imported at the Win32 level.
933 static void attach_implicitly_loaded_dlls( LPVOID reserved )
937 PLIST_ENTRY mark, entry;
939 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
940 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
942 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
944 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
945 TRACE( "found implicitly loaded %s, attaching to it\n",
946 debugstr_w(mod->BaseDllName.Buffer));
947 mod->LoadCount = -1; /* we can't unload it anyway */
948 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
949 break; /* restart the search from the start */
951 if (entry == mark) break; /* nothing found */
956 /*************************************************************************
959 * Send DLL process detach notifications. See the comment about calling
960 * sequence at process_attach. Unless the bForceDetach flag
961 * is set, only DLLs with zero refcount are notified.
963 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
965 PLIST_ENTRY mark, entry;
968 RtlEnterCriticalSection( &loader_section );
969 if (bForceDetach) process_detaching = 1;
970 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
973 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
975 mod = CONTAINING_RECORD(entry, LDR_MODULE,
976 InInitializationOrderModuleList);
977 /* Check whether to detach this DLL */
978 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
980 if ( mod->LoadCount && !bForceDetach )
983 /* Call detach notification */
984 mod->Flags &= ~LDR_PROCESS_ATTACHED;
985 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
986 DLL_PROCESS_DETACH, lpReserved );
988 /* Restart at head of WINE_MODREF list, as entries might have
989 been added and/or removed while performing the call ... */
992 } while (entry != mark);
994 RtlLeaveCriticalSection( &loader_section );
997 /*************************************************************************
998 * MODULE_DllThreadAttach
1000 * Send DLL thread attach notifications. These are sent in the
1001 * reverse sequence of process detach notification.
1004 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1006 PLIST_ENTRY mark, entry;
1010 /* don't do any attach calls if process is exiting */
1011 if (process_detaching) return STATUS_SUCCESS;
1012 /* FIXME: there is still a race here */
1014 RtlEnterCriticalSection( &loader_section );
1016 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1018 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1019 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1021 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1022 InInitializationOrderModuleList);
1023 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1025 if ( mod->Flags & LDR_NO_DLL_CALLS )
1028 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1029 DLL_THREAD_ATTACH, lpReserved );
1033 RtlLeaveCriticalSection( &loader_section );
1037 /******************************************************************
1038 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1041 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1044 NTSTATUS ret = STATUS_SUCCESS;
1046 RtlEnterCriticalSection( &loader_section );
1048 wm = get_modref( hModule );
1049 if (!wm || wm->ldr.TlsIndex != -1)
1050 ret = STATUS_DLL_NOT_FOUND;
1052 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1054 RtlLeaveCriticalSection( &loader_section );
1059 /******************************************************************
1060 * LdrFindEntryForAddress (NTDLL.@)
1062 * The loader_section must be locked while calling this function
1064 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1066 PLIST_ENTRY mark, entry;
1069 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1070 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1072 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1073 if ((const void *)mod->BaseAddress <= addr &&
1074 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1077 return STATUS_SUCCESS;
1079 if ((const void *)mod->BaseAddress > addr) break;
1081 return STATUS_NO_MORE_ENTRIES;
1084 /******************************************************************
1085 * LdrLockLoaderLock (NTDLL.@)
1087 * Note: flags are not implemented.
1088 * Flag 0x01 is used to raise exceptions on errors.
1089 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1091 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1093 if (flags) FIXME( "flags %x not supported\n", flags );
1095 if (result) *result = 1;
1096 if (!magic) return STATUS_INVALID_PARAMETER_3;
1097 RtlEnterCriticalSection( &loader_section );
1098 *magic = GetCurrentThreadId();
1099 return STATUS_SUCCESS;
1103 /******************************************************************
1104 * LdrUnlockLoaderUnlock (NTDLL.@)
1106 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1110 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1111 RtlLeaveCriticalSection( &loader_section );
1113 return STATUS_SUCCESS;
1117 /******************************************************************
1118 * LdrGetDllHandle (NTDLL.@)
1120 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
1122 NTSTATUS status = STATUS_DLL_NOT_FOUND;
1123 WCHAR dllname[MAX_PATH+4], *p;
1125 PLIST_ENTRY mark, entry;
1128 if (x != 0 || y != 0)
1129 FIXME("Unknown behavior, please report\n");
1131 /* Append .DLL to name if no extension present */
1132 if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
1134 if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
1135 strcpyW( dllname, name->Buffer );
1136 strcatW( dllname, dllW );
1137 RtlInitUnicodeString( &str, dllname );
1141 RtlEnterCriticalSection( &loader_section );
1145 if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
1146 RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
1148 *base = cached_modref->ldr.BaseAddress;
1149 status = STATUS_SUCCESS;
1154 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1155 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1157 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1159 if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
1160 RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
1162 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1163 *base = mod->BaseAddress;
1164 status = STATUS_SUCCESS;
1169 RtlLeaveCriticalSection( &loader_section );
1170 TRACE("%x %x %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1175 /******************************************************************
1176 * LdrGetProcedureAddress (NTDLL.@)
1178 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1179 ULONG ord, PVOID *address)
1181 IMAGE_EXPORT_DIRECTORY *exports;
1183 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1185 RtlEnterCriticalSection( &loader_section );
1187 /* check if the module itself is invalid to return the proper error */
1188 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1189 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1190 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1192 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1193 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1197 ret = STATUS_SUCCESS;
1201 RtlLeaveCriticalSection( &loader_section );
1206 /***********************************************************************
1209 * Check if a loaded native dll is a Wine fake dll.
1211 static BOOL is_fake_dll( const void *base )
1213 static const char fakedll_signature[] = "Wine placeholder DLL";
1214 const IMAGE_DOS_HEADER *dos = base;
1216 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1217 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1222 /***********************************************************************
1223 * get_builtin_fullname
1225 * Build the full pathname for a builtin dll.
1227 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1229 static const WCHAR soW[] = {'.','s','o',0};
1230 WCHAR *p, *fullname;
1231 size_t i, len = strlen(filename);
1233 /* check if path can correspond to the dll we have */
1234 if (path && (p = strrchrW( path, '\\' )))
1237 for (i = 0; i < len; i++)
1238 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1239 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1241 /* the filename matches, use path as the full path */
1243 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1245 memcpy( fullname, path, len * sizeof(WCHAR) );
1252 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1253 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1255 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1256 p = fullname + system_dir.Length / sizeof(WCHAR);
1257 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1258 ascii_to_unicode( p, filename, len + 1 );
1264 /***********************************************************************
1265 * load_builtin_callback
1267 * Load a library in memory; callback function for wine_dll_register
1269 static void load_builtin_callback( void *module, const char *filename )
1271 static const WCHAR emptyW[1];
1273 IMAGE_NT_HEADERS *nt;
1276 const WCHAR *load_path;
1281 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1284 if (!(nt = RtlImageNtHeader( module )))
1286 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1287 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1291 size = nt->OptionalHeader.SizeOfImage;
1292 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1293 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1294 /* create the MODREF */
1296 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1298 ERR( "can't load %s\n", filename );
1299 builtin_load_info->status = STATUS_NO_MEMORY;
1303 wm = alloc_module( module, fullname );
1304 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1307 ERR( "can't load %s\n", filename );
1308 builtin_load_info->status = STATUS_NO_MEMORY;
1311 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1313 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1314 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1316 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1322 load_path = builtin_load_info->load_path;
1323 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1324 if (!load_path) load_path = emptyW;
1325 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1327 /* the module has only be inserted in the load & memory order lists */
1328 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1329 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1330 /* FIXME: free the modref */
1331 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1336 builtin_load_info->wm = wm;
1337 TRACE( "loaded %s %p %p\n", filename, wm, module );
1339 /* send the DLL load event */
1341 SERVER_START_REQ( load_dll )
1345 req->size = nt->OptionalHeader.SizeOfImage;
1346 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1347 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1348 req->name = &wm->ldr.FullDllName.Buffer;
1349 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1350 wine_server_call( req );
1354 /* setup relay debugging entry points */
1355 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1359 /******************************************************************************
1360 * load_native_dll (internal)
1362 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1363 DWORD flags, WINE_MODREF** pwm )
1367 OBJECT_ATTRIBUTES attr;
1369 IMAGE_NT_HEADERS *nt;
1374 TRACE("Trying native dll %s\n", debugstr_w(name));
1376 attr.Length = sizeof(attr);
1377 attr.RootDirectory = 0;
1378 attr.ObjectName = NULL;
1379 attr.Attributes = 0;
1380 attr.SecurityDescriptor = NULL;
1381 attr.SecurityQualityOfService = NULL;
1384 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1385 &attr, &size, 0, SEC_IMAGE, file );
1386 if (status != STATUS_SUCCESS) return status;
1389 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1390 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1392 if (status != STATUS_SUCCESS) return status;
1394 if (is_fake_dll( module ))
1396 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1397 NtUnmapViewOfSection( NtCurrentProcess(), module );
1398 return STATUS_DLL_NOT_FOUND;
1401 /* create the MODREF */
1403 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1407 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1409 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1411 /* the module has only be inserted in the load & memory order lists */
1412 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1413 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1415 /* FIXME: there are several more dangling references
1416 * left. Including dlls loaded by this dll before the
1417 * failed one. Unrolling is rather difficult with the
1418 * current structure and we can leave them lying
1419 * around with no problems, so we don't care.
1420 * As these might reference our wm, we don't free it.
1426 /* send DLL load event */
1428 nt = RtlImageNtHeader( module );
1430 /* don't keep the file open if the mapping is from removable media */
1431 if (!VIRTUAL_HasMapping( module )) file = 0;
1433 SERVER_START_REQ( load_dll )
1437 req->size = nt->OptionalHeader.SizeOfImage;
1438 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1439 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1440 req->name = &wm->ldr.FullDllName.Buffer;
1441 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1442 wine_server_call( req );
1446 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1448 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1450 wm->ldr.LoadCount = 1;
1452 return STATUS_SUCCESS;
1456 /***********************************************************************
1459 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1460 DWORD flags, WINE_MODREF** pwm )
1462 char error[256], dllname[MAX_PATH];
1463 const WCHAR *name, *p;
1465 void *handle = NULL;
1466 struct builtin_load_info info, *prev_info;
1468 /* Fix the name in case we have a full path and extension */
1470 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1471 if ((p = strrchrW( name, '/' ))) name = p + 1;
1473 /* load_library will modify info.status. Note also that load_library can be
1474 * called several times, if the .so file we're loading has dependencies.
1475 * info.status will gather all the errors we may get while loading all these
1478 info.load_path = load_path;
1479 info.filename = NULL;
1480 info.status = STATUS_SUCCESS;
1483 if (file) /* we have a real file, try to load it */
1485 UNICODE_STRING nt_name;
1486 ANSI_STRING unix_name;
1488 TRACE("Trying built-in %s\n", debugstr_w(path));
1490 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1491 return STATUS_DLL_NOT_FOUND;
1493 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1495 RtlFreeUnicodeString( &nt_name );
1496 return STATUS_DLL_NOT_FOUND;
1498 prev_info = builtin_load_info;
1499 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1500 builtin_load_info = &info;
1501 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1502 builtin_load_info = prev_info;
1503 RtlFreeUnicodeString( &nt_name );
1504 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1507 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1508 return STATUS_INVALID_IMAGE_FORMAT;
1515 TRACE("Trying built-in %s\n", debugstr_w(name));
1517 /* we don't want to depend on the current codepage here */
1518 len = strlenW( name ) + 1;
1519 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1520 for (i = 0; i < len; i++)
1522 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1523 dllname[i] = (char)name[i];
1524 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1527 prev_info = builtin_load_info;
1528 builtin_load_info = &info;
1529 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1530 builtin_load_info = prev_info;
1535 /* The file does not exist -> WARN() */
1536 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1537 return STATUS_DLL_NOT_FOUND;
1539 /* ERR() for all other errors (missing functions, ...) */
1540 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1541 return STATUS_PROCEDURE_NOT_FOUND;
1545 if (info.status != STATUS_SUCCESS) return info.status;
1549 PLIST_ENTRY mark, entry;
1551 /* The constructor wasn't called, this means the .so is already
1552 * loaded under a different name. Try to find the wm for it. */
1554 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1555 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1557 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1558 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1560 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1561 TRACE( "Found already loaded module %s for builtin %s\n",
1562 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1566 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1567 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1571 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1572 info.wm->ldr.LoadCount = 1;
1573 info.wm->ldr.SectionHandle = handle;
1577 return STATUS_SUCCESS;
1581 /***********************************************************************
1584 * Find the file (or already loaded module) for a given dll name.
1586 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1587 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1589 OBJECT_ATTRIBUTES attr;
1591 UNICODE_STRING nt_name;
1592 WCHAR *file_part, *ext, *dllname;
1595 /* first append .dll if needed */
1598 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1600 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1601 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1602 return STATUS_NO_MEMORY;
1603 strcpyW( dllname, libname );
1604 strcatW( dllname, dllW );
1608 nt_name.Buffer = NULL;
1610 if (!contains_path( libname ))
1612 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1615 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1617 /* we need to search for it */
1618 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1621 if (len >= *size) goto overflow;
1622 if ((*pwm = find_fullname_module( filename )) != NULL) goto found;
1624 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1626 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1627 return STATUS_NO_MEMORY;
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;
1641 if (!contains_path( libname ))
1643 /* if libname doesn't contain a path at all, we simply return the name as is,
1644 * to be loaded as builtin */
1645 len = strlenW(libname) * sizeof(WCHAR);
1646 if (len >= *size) goto overflow;
1647 strcpyW( filename, libname );
1652 /* absolute path name, or relative path name but not found above */
1654 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1656 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1657 return STATUS_NO_MEMORY;
1659 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1660 if (len >= *size) goto overflow;
1661 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1662 if (!(*pwm = find_fullname_module( filename )))
1664 attr.Length = sizeof(attr);
1665 attr.RootDirectory = 0;
1666 attr.Attributes = OBJ_CASE_INSENSITIVE;
1667 attr.ObjectName = &nt_name;
1668 attr.SecurityDescriptor = NULL;
1669 attr.SecurityQualityOfService = NULL;
1670 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1673 RtlFreeUnicodeString( &nt_name );
1674 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1675 return STATUS_SUCCESS;
1678 RtlFreeUnicodeString( &nt_name );
1679 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1680 *size = len + sizeof(WCHAR);
1681 return STATUS_BUFFER_TOO_SMALL;
1685 /***********************************************************************
1686 * load_dll (internal)
1688 * Load a PE style module according to the load order.
1689 * The loader_section must be locked while calling this function.
1691 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1693 enum loadorder loadorder;
1697 WINE_MODREF *main_exe;
1701 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1704 size = sizeof(buffer);
1707 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1708 if (nts == STATUS_SUCCESS) break;
1709 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1710 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1711 /* grow the buffer and retry */
1712 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1715 if (*pwm) /* found already loaded module */
1717 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1719 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1721 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1722 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1723 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1724 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1725 return STATUS_SUCCESS;
1728 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1729 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1734 nts = STATUS_NO_MEMORY;
1737 nts = STATUS_DLL_NOT_FOUND;
1740 case LO_NATIVE_BUILTIN:
1741 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1744 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1745 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1746 /* not in PE format, maybe it's a builtin */
1747 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1749 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1750 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1753 case LO_BUILTIN_NATIVE:
1754 case LO_DEFAULT: /* default is builtin,native */
1755 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1756 if (!handle) break; /* nothing else we can try */
1757 /* file is not a builtin library, try without using the specified file */
1758 if (nts != STATUS_SUCCESS)
1759 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1760 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1761 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1763 /* stub-only dll, try native */
1764 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1765 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1766 nts = STATUS_DLL_NOT_FOUND;
1768 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1769 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1773 if (nts == STATUS_SUCCESS)
1775 /* Initialize DLL just loaded */
1776 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1777 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1778 (*pwm)->ldr.BaseAddress);
1779 if (handle) NtClose( handle );
1780 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1784 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1785 if (handle) NtClose( handle );
1786 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1790 /******************************************************************
1791 * LdrLoadDll (NTDLL.@)
1793 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1794 const UNICODE_STRING *libname, HMODULE* hModule)
1799 RtlEnterCriticalSection( &loader_section );
1801 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1802 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1804 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1806 nts = process_attach( wm, NULL );
1807 if (nts != STATUS_SUCCESS)
1809 LdrUnloadDll(wm->ldr.BaseAddress);
1813 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1815 RtlLeaveCriticalSection( &loader_section );
1819 /******************************************************************
1820 * LdrQueryProcessModuleInformation
1823 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1824 ULONG buf_size, ULONG* req_size)
1826 SYSTEM_MODULE* sm = &smi->Modules[0];
1827 ULONG size = sizeof(ULONG);
1828 NTSTATUS nts = STATUS_SUCCESS;
1831 PLIST_ENTRY mark, entry;
1834 smi->ModulesCount = 0;
1836 RtlEnterCriticalSection( &loader_section );
1837 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1838 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1840 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1841 size += sizeof(*sm);
1842 if (size <= buf_size)
1844 sm->Reserved1 = 0; /* FIXME */
1845 sm->Reserved2 = 0; /* FIXME */
1846 sm->ImageBaseAddress = mod->BaseAddress;
1847 sm->ImageSize = mod->SizeOfImage;
1848 sm->Flags = mod->Flags;
1849 sm->Id = 0; /* FIXME */
1850 sm->Rank = 0; /* FIXME */
1851 sm->Unknown = 0; /* FIXME */
1853 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1854 str.Buffer = (char*)sm->Name;
1855 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1856 ptr = strrchr(str.Buffer, '\\');
1857 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1859 smi->ModulesCount++;
1862 else nts = STATUS_INFO_LENGTH_MISMATCH;
1864 RtlLeaveCriticalSection( &loader_section );
1866 if (req_size) *req_size = size;
1871 /******************************************************************
1872 * LdrShutdownProcess (NTDLL.@)
1875 void WINAPI LdrShutdownProcess(void)
1878 process_detach( TRUE, (LPVOID)1 );
1881 /******************************************************************
1882 * LdrShutdownThread (NTDLL.@)
1885 void WINAPI LdrShutdownThread(void)
1887 PLIST_ENTRY mark, entry;
1892 /* don't do any detach calls if process is exiting */
1893 if (process_detaching) return;
1894 /* FIXME: there is still a race here */
1896 RtlEnterCriticalSection( &loader_section );
1898 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1899 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1901 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1902 InInitializationOrderModuleList);
1903 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1905 if ( mod->Flags & LDR_NO_DLL_CALLS )
1908 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1909 DLL_THREAD_DETACH, NULL );
1912 RtlLeaveCriticalSection( &loader_section );
1913 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
1917 /***********************************************************************
1921 static void free_modref( WINE_MODREF *wm )
1923 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1924 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1925 if (wm->ldr.InInitializationOrderModuleList.Flink)
1926 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
1928 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
1929 if (!TRACE_ON(module))
1930 TRACE_(loaddll)("Unloaded module %s : %s\n",
1931 debugstr_w(wm->ldr.FullDllName.Buffer),
1932 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1934 SERVER_START_REQ( unload_dll )
1936 req->base = wm->ldr.BaseAddress;
1937 wine_server_call( req );
1941 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
1942 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1943 if (cached_modref == wm) cached_modref = NULL;
1944 RtlFreeUnicodeString( &wm->ldr.FullDllName );
1945 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1946 RtlFreeHeap( GetProcessHeap(), 0, wm );
1949 /***********************************************************************
1950 * MODULE_FlushModrefs
1952 * Remove all unused modrefs and call the internal unloading routines
1953 * for the library type.
1955 * The loader_section must be locked while calling this function.
1957 static void MODULE_FlushModrefs(void)
1959 PLIST_ENTRY mark, entry, prev;
1963 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1964 for (entry = mark->Blink; entry != mark; entry = prev)
1966 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
1967 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1968 prev = entry->Blink;
1969 if (!mod->LoadCount) free_modref( wm );
1972 /* check load order list too for modules that haven't been initialized yet */
1973 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1974 for (entry = mark->Blink; entry != mark; entry = prev)
1976 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1977 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1978 prev = entry->Blink;
1979 if (!mod->LoadCount) free_modref( wm );
1983 /***********************************************************************
1984 * MODULE_DecRefCount
1986 * The loader_section must be locked while calling this function.
1988 static void MODULE_DecRefCount( WINE_MODREF *wm )
1992 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1995 if ( wm->ldr.LoadCount <= 0 )
1998 --wm->ldr.LoadCount;
1999 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2001 if ( wm->ldr.LoadCount == 0 )
2003 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2005 for ( i = 0; i < wm->nDeps; i++ )
2007 MODULE_DecRefCount( wm->deps[i] );
2009 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2013 /******************************************************************
2014 * LdrUnloadDll (NTDLL.@)
2018 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2020 NTSTATUS retv = STATUS_SUCCESS;
2022 TRACE("(%p)\n", hModule);
2024 RtlEnterCriticalSection( &loader_section );
2026 /* if we're stopping the whole process (and forcing the removal of all
2027 * DLLs) the library will be freed anyway
2029 if (!process_detaching)
2034 if ((wm = get_modref( hModule )) != NULL)
2036 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2038 /* Recursively decrement reference counts */
2039 MODULE_DecRefCount( wm );
2041 /* Call process detach notifications */
2042 if ( free_lib_count <= 1 )
2044 process_detach( FALSE, NULL );
2045 MODULE_FlushModrefs();
2051 retv = STATUS_DLL_NOT_FOUND;
2056 RtlLeaveCriticalSection( &loader_section );
2061 /***********************************************************************
2062 * RtlImageNtHeader (NTDLL.@)
2064 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2066 IMAGE_NT_HEADERS *ret;
2070 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2073 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2075 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2076 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2088 /******************************************************************
2089 * LdrInitializeThunk (NTDLL.@)
2092 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2097 PEB *peb = NtCurrentTeb()->Peb;
2098 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2100 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2102 /* allocate the modref for the main exe (if not already done) */
2103 wm = get_modref( peb->ImageBaseAddress );
2105 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2107 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2110 wm->ldr.LoadCount = -1; /* can't unload main exe */
2112 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2113 version_init( wm->ldr.FullDllName.Buffer );
2115 /* the main exe needs to be the first in the load order list */
2116 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2117 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2119 /* Install signal handlers; this cannot be done before, since we cannot
2120 * send exceptions to the debugger before the create process event that
2121 * is sent by REQ_INIT_PROCESS_DONE.
2122 * We do need the handlers in place by the time the request is over, so
2123 * we set them up here. If we segfault between here and the server call
2124 * something is very wrong... */
2125 if (!SIGNAL_Init()) exit(1);
2127 /* Signal the parent process to continue */
2128 SERVER_START_REQ( init_process_done )
2130 req->module = peb->ImageBaseAddress;
2131 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
2132 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
2133 status = wine_server_call( req );
2137 if (status != STATUS_SUCCESS) goto error;
2139 RtlEnterCriticalSection( &loader_section );
2141 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2142 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2143 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2144 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2145 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2147 if (last_failed_modref)
2148 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2151 attach_implicitly_loaded_dlls( (LPVOID)1 );
2153 RtlLeaveCriticalSection( &loader_section );
2155 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2159 ERR( "Main exe initialization for %s failed, status %x\n",
2160 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2165 /***********************************************************************
2166 * RtlImageDirectoryEntryToData (NTDLL.@)
2168 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2170 const IMAGE_NT_HEADERS *nt;
2173 if ((ULONG_PTR)module & 1) /* mapped as data file */
2175 module = (HMODULE)((ULONG_PTR)module & ~1);
2178 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2179 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2180 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2181 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2182 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2184 /* not mapped as image, need to find the section containing the virtual address */
2185 return RtlImageRvaToVa( nt, module, addr, NULL );
2189 /***********************************************************************
2190 * RtlImageRvaToSection (NTDLL.@)
2192 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2193 HMODULE module, DWORD rva )
2196 const IMAGE_SECTION_HEADER *sec;
2198 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2199 nt->FileHeader.SizeOfOptionalHeader);
2200 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2202 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2203 return (PIMAGE_SECTION_HEADER)sec;
2209 /***********************************************************************
2210 * RtlImageRvaToVa (NTDLL.@)
2212 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2213 DWORD rva, IMAGE_SECTION_HEADER **section )
2215 IMAGE_SECTION_HEADER *sec;
2217 if (section && *section) /* try this section first */
2220 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2223 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2225 if (section) *section = sec;
2226 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2230 /***********************************************************************
2231 * RtlPcToFileHeader (NTDLL.@)
2233 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2238 RtlEnterCriticalSection( &loader_section );
2239 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2240 RtlLeaveCriticalSection( &loader_section );
2246 /***********************************************************************
2247 * NtLoadDriver (NTDLL.@)
2248 * ZwLoadDriver (NTDLL.@)
2250 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2252 FIXME("(%p), stub!\n",DriverServiceName);
2253 return STATUS_NOT_IMPLEMENTED;
2257 /***********************************************************************
2258 * NtUnloadDriver (NTDLL.@)
2259 * ZwUnloadDriver (NTDLL.@)
2261 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2263 FIXME("(%p), stub!\n",DriverServiceName);
2264 return STATUS_NOT_IMPLEMENTED;
2268 /******************************************************************
2271 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2273 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2278 /******************************************************************
2279 * __wine_init_windows_dir (NTDLL.@)
2281 * Windows and system dir initialization once kernel32 has been loaded.
2283 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2285 PLIST_ENTRY mark, entry;
2288 RtlCreateUnicodeString( &system_dir, sysdir );
2290 /* prepend the system dir to the name of the already created modules */
2291 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2292 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2294 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2296 assert( mod->Flags & LDR_WINE_INTERNAL );
2298 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2299 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2300 if (!buffer) continue;
2301 strcpyW( buffer, system_dir.Buffer );
2302 p = buffer + strlenW( buffer );
2303 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2304 strcpyW( p, mod->FullDllName.Buffer );
2305 RtlInitUnicodeString( &mod->FullDllName, buffer );
2306 RtlInitUnicodeString( &mod->BaseDllName, p );
2311 /***********************************************************************
2312 * check_command_line
2314 * Check if command line is one that needs to be handled specially.
2316 static void check_command_line( int argc, char *argv[] )
2318 static const char version[] = PACKAGE_STRING "\n";
2319 static const char usage[] =
2320 "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n"
2321 " wine --help Display this help and exit\n"
2322 " wine --version Output version information and exit\n";
2326 write( 2, usage, sizeof(usage) - 1 );
2329 if (!strcmp( argv[1], "--help" ))
2331 write( 1, usage, sizeof(usage) - 1 );
2334 if (!strcmp( argv[1], "--version" ))
2336 write( 1, version, sizeof(version) - 1 );
2342 /***********************************************************************
2343 * __wine_process_init
2345 void __wine_process_init(void)
2347 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2351 ANSI_STRING func_name;
2352 void (* DECLSPEC_NORETURN init_func)(void);
2353 extern mode_t FILE_umask;
2355 check_command_line( __wine_main_argc, __wine_main_argv );
2356 main_exe_file = thread_init();
2358 /* retrieve current umask */
2359 FILE_umask = umask(0777);
2360 umask( FILE_umask );
2362 /* setup the load callback and create ntdll modref */
2363 wine_dll_set_callback( load_builtin_callback );
2365 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2367 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2370 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2371 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2372 0, (void **)&init_func )) != STATUS_SUCCESS)
2374 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );