wined3d: Fix a typo.
[wine/hacks.git] / dlls / ntdll / loader.c
blob184f64f241a01638992c51674dedc71e039be3f6
1 /*
2 * Loader functions
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdarg.h>
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
31 #include "ntstatus.h"
32 #define WIN32_NO_STATUS
33 #include "windef.h"
34 #include "winnt.h"
35 #include "winternl.h"
37 #include "wine/exception.h"
38 #include "excpt.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[] =
58 "PROCESS_DETACH",
59 "PROCESS_ATTACH",
60 "THREAD_ATTACH",
61 "THREAD_DETACH",
62 NULL, NULL, NULL, NULL,
63 "WINE_PREATTACH"
66 static const WCHAR dllW[] = {'.','d','l','l',0};
68 /* internal representation of 32bit modules. per process. */
69 typedef struct _wine_modref
71 LDR_MODULE ldr;
72 int nDeps;
73 struct _wine_modref **deps;
74 } WINE_MODREF;
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;
82 NTSTATUS status;
83 WINE_MODREF *wm;
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.
138 #ifdef __i386__
139 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
140 __ASM_GLOBAL_FUNC(call_dll_entry_point,
141 "pushl %ebp\n\t"
142 "movl %esp,%ebp\n\t"
143 "pushl %ebx\n\t"
144 "subl $8,%esp\n\t"
145 "pushl 20(%ebp)\n\t"
146 "pushl 16(%ebp)\n\t"
147 "pushl 12(%ebp)\n\t"
148 "movl 8(%ebp),%eax\n\t"
149 "call *%eax\n\t"
150 "leal -4(%ebp),%esp\n\t"
151 "popl %ebx\n\t"
152 "popl %ebp\n\t"
153 "ret" );
154 #else /* __i386__ */
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__ */
163 #ifdef __i386__
164 /*************************************************************************
165 * stub_entry_point
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;
176 #ifdef __GNUC__
177 rec.ExceptionAddress = __builtin_return_address(0);
178 #else
179 rec.ExceptionAddress = *((void **)&dll - 1);
180 #endif
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"
189 struct stub
191 BYTE popl_eax; /* popl %eax */
192 BYTE pushl1; /* pushl $name */
193 const char *name;
194 BYTE pushl2; /* pushl $dll */
195 const char *dll;
196 BYTE pushl_eax; /* pushl %eax */
197 BYTE jmp; /* jmp stub_entry_point */
198 DWORD entry;
200 #include "poppack.h"
202 /*************************************************************************
203 * allocate_stub
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;
212 struct stub *stub;
214 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
216 if (!stubs)
218 ULONG size = MAX_SIZE;
219 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
220 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
221 return 0xdeadbeef;
223 stub = &stubs[nb_stubs++];
224 stub->popl_eax = 0x58; /* popl %eax */
225 stub->pushl1 = 0x68; /* pushl $name */
226 stub->name = name;
227 stub->pushl2 = 0x68; /* pushl $dll */
228 stub->dll = 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;
235 #else /* __i386__ */
236 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
237 #endif /* __i386__ */
240 /*************************************************************************
241 * get_modref
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;
249 PLDR_MODULE mod;
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;
261 return NULL;
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;
288 return NULL;
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;
315 return NULL;
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;
328 DWORD exp_size;
329 WINE_MODREF *wm;
330 WCHAR mod_name[32];
331 const char *end = strchr(forward, '.');
332 FARPROC proc = NULL;
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) );
343 return NULL;
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 );
349 if (!proc)
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) );
356 return proc;
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 )
370 FARPROC proc;
371 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
373 if (ordinal >= exports->NumberOfFunctions)
375 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
376 return NULL;
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 );
387 if (TRACE_ON(snoop))
389 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
390 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
392 if (TRACE_ON(relay))
394 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
395 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
397 return proc;
401 /*************************************************************************
402 * find_named_export
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 */
423 while (min <= max)
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;
430 else min = pos + 1;
432 return NULL;
437 /*************************************************************************
438 * import_dll
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 )
445 NTSTATUS status;
446 WINE_MODREF *wmImp;
447 HMODULE imp_mod;
448 const IMAGE_EXPORT_DIRECTORY *exports;
449 DWORD exp_size;
450 const IMAGE_THUNK_DATA *import_list;
451 IMAGE_THUNK_DATA *thunk_list;
452 WCHAR buffer[32];
453 const char *name = get_rva( module, descr->Name );
454 DWORD len = strlen(name);
455 PVOID protect_base;
456 SIZE_T protect_size = 0;
457 DWORD protect_old;
459 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
460 if (descr->u.OriginalFirstThunk)
461 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
462 else
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 );
470 buffer[len] = 0;
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 );
478 ptr[len] = 0;
479 status = load_dll( load_path, ptr, 0, &wmImp );
480 RtlFreeHeap( GetProcessHeap(), 0, ptr );
483 if (status)
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));
488 else
489 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
490 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
491 return NULL;
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 );
505 if (!exports)
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 );
516 else
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 );
525 import_list++;
526 thunk_list++;
528 goto done;
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);
564 import_list++;
565 thunk_list++;
568 done:
569 /* restore old protection of the import address table */
570 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
571 return wmImp;
575 /****************************************************************
576 * fixup_imports
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 )
583 int i, nb_imports;
584 const IMAGE_IMPORT_DESCRIPTOR *imports;
585 WINE_MODREF *prev;
586 DWORD size;
587 NTSTATUS status;
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;
596 nb_imports = 0;
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;
609 current_modref = wm;
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;
617 return status;
621 /*************************************************************************
622 * alloc_module
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 )
629 WINE_MODREF *wm;
630 const WCHAR *p;
631 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
632 PLIST_ENTRY entry, mark;
634 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
636 wm->nDeps = 0;
637 wm->deps = 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)
669 break;
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;
679 return wm;
683 /*************************************************************************
684 * alloc_process_tls
686 * Allocate the process-wide structure for module TLS storage.
688 static NTSTATUS alloc_process_tls(void)
690 PLIST_ENTRY mark, entry;
691 PLDR_MODULE mod;
692 const IMAGE_TLS_DIRECTORY *dir;
693 ULONG size, i;
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 )))
701 continue;
702 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
703 if (!size) continue;
704 tls_total_size += size;
705 tls_module_count++;
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 )))
719 continue;
720 tls_dirs[i] = dir;
721 *(DWORD *)dir->AddressOfIndex = i;
722 mod->TlsIndex = i;
723 mod->LoadCount = -1; /* can't unload it */
724 i++;
726 return STATUS_SUCCESS;
730 /*************************************************************************
731 * alloc_thread_tls
733 * Allocate the per-thread structure for module TLS storage.
735 static NTSTATUS alloc_thread_tls(void)
737 void **pointers;
738 char *data;
739 UINT i;
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 %04lx idx %d: %ld/%ld bytes from %p to %p\n",
759 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
760 (void *)dir->StartAddressOfRawData, data );
762 pointers[i] = data;
763 memcpy( data, (void *)dir->StartAddressOfRawData, size );
764 data += size;
765 memset( data, 0, dir->SizeOfZeroFill );
766 data += dir->SizeOfZeroFill;
768 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
769 return STATUS_SUCCESS;
773 /*************************************************************************
774 * call_tls_callbacks
776 static void call_tls_callbacks( HMODULE module, UINT reason )
778 const IMAGE_TLS_DIRECTORY *dir;
779 const PIMAGE_TLS_CALLBACK *callback;
780 ULONG dirsize;
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++)
787 if (TRACE_ON(relay))
788 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
789 GetCurrentThreadId(), *callback, module, reason_names[reason] );
790 (*callback)( module, reason, NULL );
791 if (TRACE_ON(relay))
792 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
793 GetCurrentThreadId(), *callback, module, reason_names[reason] );
798 /*************************************************************************
799 * MODULE_InitDLL
801 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
803 WCHAR mod_name[32];
804 BOOL retv = TRUE;
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;
814 if (TRACE_ON(relay))
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("%04lx: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
830 deleted. */
831 if (TRACE_ON(relay))
832 DPRINTF("%04lx: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 );
837 return retv;
841 /*************************************************************************
842 * process_attach
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
857 * routines.)
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;
875 int i;
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 ) )
882 return status;
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;
900 current_modref = wm;
901 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
903 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
905 else
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 );
923 return status;
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 )
935 for (;;)
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 /*************************************************************************
957 * process_detach
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;
966 PLDR_MODULE mod;
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) )
979 continue;
980 if ( mod->LoadCount && !bForceDetach )
981 continue;
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 ... */
990 break;
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;
1007 PLDR_MODULE mod;
1008 NTSTATUS status;
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) )
1024 continue;
1025 if ( mod->Flags & LDR_NO_DLL_CALLS )
1026 continue;
1028 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1029 DLL_THREAD_ATTACH, lpReserved );
1032 done:
1033 RtlLeaveCriticalSection( &loader_section );
1034 return status;
1037 /******************************************************************
1038 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1041 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1043 WINE_MODREF *wm;
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;
1051 else
1052 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1054 RtlLeaveCriticalSection( &loader_section );
1056 return ret;
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;
1067 PLDR_MODULE mod;
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)
1076 *pmod = mod;
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 %lx 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 )
1108 if (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;
1124 UNICODE_STRING str;
1125 PLIST_ENTRY mark, entry;
1126 PLDR_MODULE mod;
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 );
1138 name = &str;
1141 RtlEnterCriticalSection( &loader_section );
1143 if (cached_modref)
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;
1150 goto done;
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;
1165 break;
1168 done:
1169 RtlLeaveCriticalSection( &loader_section );
1170 TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1171 return status;
1175 /******************************************************************
1176 * LdrGetProcedureAddress (NTDLL.@)
1178 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1179 ULONG ord, PVOID *address)
1181 IMAGE_EXPORT_DIRECTORY *exports;
1182 DWORD exp_size;
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 );
1194 if (proc)
1196 *address = proc;
1197 ret = STATUS_SUCCESS;
1201 RtlLeaveCriticalSection( &loader_section );
1202 return ret;
1206 /***********************************************************************
1207 * is_fake_dll
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;
1218 return FALSE;
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, '\\' )))
1236 p++;
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 */
1242 len += p - path;
1243 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1245 memcpy( fullname, path, len * sizeof(WCHAR) );
1246 fullname[len] = 0;
1248 return fullname;
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 );
1260 return fullname;
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];
1272 void *addr;
1273 IMAGE_NT_HEADERS *nt;
1274 WINE_MODREF *wm;
1275 WCHAR *fullname;
1276 const WCHAR *load_path;
1278 if (!module)
1280 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1281 return;
1283 if (!(nt = RtlImageNtHeader( module )))
1285 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1286 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1287 return;
1289 addr = module;
1290 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &nt->OptionalHeader.SizeOfImage,
1291 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1292 /* create the MODREF */
1294 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1296 ERR( "can't load %s\n", filename );
1297 builtin_load_info->status = STATUS_NO_MEMORY;
1298 return;
1301 wm = alloc_module( module, fullname );
1302 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1303 if (!wm)
1305 ERR( "can't load %s\n", filename );
1306 builtin_load_info->status = STATUS_NO_MEMORY;
1307 return;
1309 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1311 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1312 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1314 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1316 else
1318 /* fixup imports */
1320 load_path = builtin_load_info->load_path;
1321 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1322 if (!load_path) load_path = emptyW;
1323 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1325 /* the module has only be inserted in the load & memory order lists */
1326 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1327 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1328 /* FIXME: free the modref */
1329 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1330 return;
1334 builtin_load_info->wm = wm;
1335 TRACE( "loaded %s %p %p\n", filename, wm, module );
1337 /* send the DLL load event */
1339 SERVER_START_REQ( load_dll )
1341 req->handle = 0;
1342 req->base = module;
1343 req->size = nt->OptionalHeader.SizeOfImage;
1344 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1345 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1346 req->name = &wm->ldr.FullDllName.Buffer;
1347 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1348 wine_server_call( req );
1350 SERVER_END_REQ;
1352 /* setup relay debugging entry points */
1353 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1357 /******************************************************************************
1358 * load_native_dll (internal)
1360 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1361 DWORD flags, WINE_MODREF** pwm )
1363 void *module;
1364 HANDLE mapping;
1365 OBJECT_ATTRIBUTES attr;
1366 LARGE_INTEGER size;
1367 IMAGE_NT_HEADERS *nt;
1368 SIZE_T len = 0;
1369 WINE_MODREF *wm;
1370 NTSTATUS status;
1372 TRACE("Trying native dll %s\n", debugstr_w(name));
1374 attr.Length = sizeof(attr);
1375 attr.RootDirectory = 0;
1376 attr.ObjectName = NULL;
1377 attr.Attributes = 0;
1378 attr.SecurityDescriptor = NULL;
1379 attr.SecurityQualityOfService = NULL;
1380 size.QuadPart = 0;
1382 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1383 &attr, &size, 0, SEC_IMAGE, file );
1384 if (status != STATUS_SUCCESS) return status;
1386 module = NULL;
1387 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1388 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1389 NtClose( mapping );
1390 if (status != STATUS_SUCCESS) return status;
1392 if (is_fake_dll( module ))
1394 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1395 NtUnmapViewOfSection( NtCurrentProcess(), module );
1396 return STATUS_DLL_NOT_FOUND;
1399 /* create the MODREF */
1401 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1403 /* fixup imports */
1405 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1407 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1409 /* the module has only be inserted in the load & memory order lists */
1410 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1411 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1413 /* FIXME: there are several more dangling references
1414 * left. Including dlls loaded by this dll before the
1415 * failed one. Unrolling is rather difficult with the
1416 * current structure and we can leave them lying
1417 * around with no problems, so we don't care.
1418 * As these might reference our wm, we don't free it.
1420 return status;
1424 /* send DLL load event */
1426 nt = RtlImageNtHeader( module );
1428 /* don't keep the file open if the mapping is from removable media */
1429 if (!VIRTUAL_HasMapping( module )) file = 0;
1431 SERVER_START_REQ( load_dll )
1433 req->handle = file;
1434 req->base = module;
1435 req->size = nt->OptionalHeader.SizeOfImage;
1436 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1437 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1438 req->name = &wm->ldr.FullDllName.Buffer;
1439 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1440 wine_server_call( req );
1442 SERVER_END_REQ;
1444 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1446 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1448 wm->ldr.LoadCount = 1;
1449 *pwm = wm;
1450 return STATUS_SUCCESS;
1454 /***********************************************************************
1455 * load_builtin_dll
1457 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1458 DWORD flags, WINE_MODREF** pwm )
1460 char error[256], dllname[MAX_PATH];
1461 const WCHAR *name, *p;
1462 DWORD len, i;
1463 void *handle = NULL;
1464 struct builtin_load_info info, *prev_info;
1466 /* Fix the name in case we have a full path and extension */
1467 name = path;
1468 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1469 if ((p = strrchrW( name, '/' ))) name = p + 1;
1471 /* load_library will modify info.status. Note also that load_library can be
1472 * called several times, if the .so file we're loading has dependencies.
1473 * info.status will gather all the errors we may get while loading all these
1474 * libraries
1476 info.load_path = load_path;
1477 info.filename = NULL;
1478 info.status = STATUS_SUCCESS;
1479 info.wm = NULL;
1481 if (file) /* we have a real file, try to load it */
1483 UNICODE_STRING nt_name;
1484 ANSI_STRING unix_name;
1486 TRACE("Trying built-in %s\n", debugstr_w(path));
1488 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1489 return STATUS_DLL_NOT_FOUND;
1491 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1493 RtlFreeUnicodeString( &nt_name );
1494 return STATUS_DLL_NOT_FOUND;
1496 prev_info = builtin_load_info;
1497 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1498 builtin_load_info = &info;
1499 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1500 builtin_load_info = prev_info;
1501 RtlFreeUnicodeString( &nt_name );
1502 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1503 if (!handle)
1505 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1506 return STATUS_INVALID_IMAGE_FORMAT;
1509 else
1511 int file_exists;
1513 TRACE("Trying built-in %s\n", debugstr_w(name));
1515 /* we don't want to depend on the current codepage here */
1516 len = strlenW( name ) + 1;
1517 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1518 for (i = 0; i < len; i++)
1520 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1521 dllname[i] = (char)name[i];
1522 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1525 prev_info = builtin_load_info;
1526 builtin_load_info = &info;
1527 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1528 builtin_load_info = prev_info;
1529 if (!handle)
1531 if (!file_exists)
1533 /* The file does not exist -> WARN() */
1534 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1535 return STATUS_DLL_NOT_FOUND;
1537 /* ERR() for all other errors (missing functions, ...) */
1538 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1539 return STATUS_PROCEDURE_NOT_FOUND;
1543 if (info.status != STATUS_SUCCESS) return info.status;
1545 if (!info.wm)
1547 PLIST_ENTRY mark, entry;
1549 /* The constructor wasn't called, this means the .so is already
1550 * loaded under a different name. Try to find the wm for it. */
1552 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1553 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1555 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1556 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1558 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1559 TRACE( "Found already loaded module %s for builtin %s\n",
1560 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1561 break;
1564 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1565 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1567 else
1569 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1570 info.wm->ldr.LoadCount = 1;
1571 info.wm->ldr.SectionHandle = handle;
1574 *pwm = info.wm;
1575 return STATUS_SUCCESS;
1579 /***********************************************************************
1580 * find_dll_file
1582 * Find the file (or already loaded module) for a given dll name.
1584 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1585 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1587 OBJECT_ATTRIBUTES attr;
1588 IO_STATUS_BLOCK io;
1589 UNICODE_STRING nt_name;
1590 WCHAR *file_part, *ext, *dllname;
1591 ULONG len;
1593 /* first append .dll if needed */
1595 dllname = NULL;
1596 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1598 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1599 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1600 return STATUS_NO_MEMORY;
1601 strcpyW( dllname, libname );
1602 strcatW( dllname, dllW );
1603 libname = dllname;
1606 nt_name.Buffer = NULL;
1608 if (!contains_path( libname ))
1610 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1613 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1615 /* we need to search for it */
1616 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1617 if (len)
1619 if (len >= *size) goto overflow;
1620 if ((*pwm = find_fullname_module( filename )) != NULL) goto found;
1622 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1624 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1625 return STATUS_NO_MEMORY;
1627 attr.Length = sizeof(attr);
1628 attr.RootDirectory = 0;
1629 attr.Attributes = OBJ_CASE_INSENSITIVE;
1630 attr.ObjectName = &nt_name;
1631 attr.SecurityDescriptor = NULL;
1632 attr.SecurityQualityOfService = NULL;
1633 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1634 goto found;
1637 /* not found */
1639 if (!contains_path( libname ))
1641 /* if libname doesn't contain a path at all, we simply return the name as is,
1642 * to be loaded as builtin */
1643 len = strlenW(libname) * sizeof(WCHAR);
1644 if (len >= *size) goto overflow;
1645 strcpyW( filename, libname );
1646 goto found;
1650 /* absolute path name, or relative path name but not found above */
1652 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1654 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1655 return STATUS_NO_MEMORY;
1657 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1658 if (len >= *size) goto overflow;
1659 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1660 if (!(*pwm = find_fullname_module( filename )))
1662 attr.Length = sizeof(attr);
1663 attr.RootDirectory = 0;
1664 attr.Attributes = OBJ_CASE_INSENSITIVE;
1665 attr.ObjectName = &nt_name;
1666 attr.SecurityDescriptor = NULL;
1667 attr.SecurityQualityOfService = NULL;
1668 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1670 found:
1671 RtlFreeUnicodeString( &nt_name );
1672 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1673 return STATUS_SUCCESS;
1675 overflow:
1676 RtlFreeUnicodeString( &nt_name );
1677 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1678 *size = len + sizeof(WCHAR);
1679 return STATUS_BUFFER_TOO_SMALL;
1683 /***********************************************************************
1684 * load_dll (internal)
1686 * Load a PE style module according to the load order.
1687 * The loader_section must be locked while calling this function.
1689 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1691 enum loadorder loadorder;
1692 WCHAR buffer[32];
1693 WCHAR *filename;
1694 ULONG size;
1695 WINE_MODREF *main_exe;
1696 HANDLE handle = 0;
1697 NTSTATUS nts;
1699 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1701 filename = buffer;
1702 size = sizeof(buffer);
1703 for (;;)
1705 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1706 if (nts == STATUS_SUCCESS) break;
1707 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1708 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1709 /* grow the buffer and retry */
1710 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1713 if (*pwm) /* found already loaded module */
1715 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1717 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1719 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1720 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1721 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1722 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1723 return STATUS_SUCCESS;
1726 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1727 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1729 switch(loadorder)
1731 case LO_INVALID:
1732 nts = STATUS_NO_MEMORY;
1733 break;
1734 case LO_DISABLED:
1735 nts = STATUS_DLL_NOT_FOUND;
1736 break;
1737 case LO_NATIVE:
1738 case LO_NATIVE_BUILTIN:
1739 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1740 else
1742 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1743 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1744 /* not in PE format, maybe it's a builtin */
1745 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1747 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1748 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1749 break;
1750 case LO_BUILTIN:
1751 case LO_BUILTIN_NATIVE:
1752 case LO_DEFAULT: /* default is builtin,native */
1753 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1754 if (!handle) break; /* nothing else we can try */
1755 /* file is not a builtin library, try without using the specified file */
1756 if (nts != STATUS_SUCCESS)
1757 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1758 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1759 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1761 /* stub-only dll, try native */
1762 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1763 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1764 nts = STATUS_DLL_NOT_FOUND;
1766 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1767 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1768 break;
1771 if (nts == STATUS_SUCCESS)
1773 /* Initialize DLL just loaded */
1774 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1775 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1776 (*pwm)->ldr.BaseAddress);
1777 if (handle) NtClose( handle );
1778 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1779 return nts;
1782 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1783 if (handle) NtClose( handle );
1784 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1785 return nts;
1788 /******************************************************************
1789 * LdrLoadDll (NTDLL.@)
1791 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1792 const UNICODE_STRING *libname, HMODULE* hModule)
1794 WINE_MODREF *wm;
1795 NTSTATUS nts;
1797 RtlEnterCriticalSection( &loader_section );
1799 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1800 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1802 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1804 nts = process_attach( wm, NULL );
1805 if (nts != STATUS_SUCCESS)
1807 LdrUnloadDll(wm->ldr.BaseAddress);
1808 wm = NULL;
1811 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1813 RtlLeaveCriticalSection( &loader_section );
1814 return nts;
1817 /******************************************************************
1818 * LdrQueryProcessModuleInformation
1821 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1822 ULONG buf_size, ULONG* req_size)
1824 SYSTEM_MODULE* sm = &smi->Modules[0];
1825 ULONG size = sizeof(ULONG);
1826 NTSTATUS nts = STATUS_SUCCESS;
1827 ANSI_STRING str;
1828 char* ptr;
1829 PLIST_ENTRY mark, entry;
1830 PLDR_MODULE mod;
1832 smi->ModulesCount = 0;
1834 RtlEnterCriticalSection( &loader_section );
1835 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1836 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1838 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1839 size += sizeof(*sm);
1840 if (size <= buf_size)
1842 sm->Reserved1 = 0; /* FIXME */
1843 sm->Reserved2 = 0; /* FIXME */
1844 sm->ImageBaseAddress = mod->BaseAddress;
1845 sm->ImageSize = mod->SizeOfImage;
1846 sm->Flags = mod->Flags;
1847 sm->Id = 0; /* FIXME */
1848 sm->Rank = 0; /* FIXME */
1849 sm->Unknown = 0; /* FIXME */
1850 str.Length = 0;
1851 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1852 str.Buffer = (char*)sm->Name;
1853 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1854 ptr = strrchr(str.Buffer, '\\');
1855 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1857 smi->ModulesCount++;
1858 sm++;
1860 else nts = STATUS_INFO_LENGTH_MISMATCH;
1862 RtlLeaveCriticalSection( &loader_section );
1864 if (req_size) *req_size = size;
1866 return nts;
1869 /******************************************************************
1870 * LdrShutdownProcess (NTDLL.@)
1873 void WINAPI LdrShutdownProcess(void)
1875 TRACE("()\n");
1876 process_detach( TRUE, (LPVOID)1 );
1879 /******************************************************************
1880 * LdrShutdownThread (NTDLL.@)
1883 void WINAPI LdrShutdownThread(void)
1885 PLIST_ENTRY mark, entry;
1886 PLDR_MODULE mod;
1888 TRACE("()\n");
1890 /* don't do any detach calls if process is exiting */
1891 if (process_detaching) return;
1892 /* FIXME: there is still a race here */
1894 RtlEnterCriticalSection( &loader_section );
1896 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1897 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1899 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1900 InInitializationOrderModuleList);
1901 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1902 continue;
1903 if ( mod->Flags & LDR_NO_DLL_CALLS )
1904 continue;
1906 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1907 DLL_THREAD_DETACH, NULL );
1910 RtlLeaveCriticalSection( &loader_section );
1911 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
1915 /***********************************************************************
1916 * free_modref
1919 static void free_modref( WINE_MODREF *wm )
1921 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1922 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1923 if (wm->ldr.InInitializationOrderModuleList.Flink)
1924 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
1926 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
1927 if (!TRACE_ON(module))
1928 TRACE_(loaddll)("Unloaded module %s : %s\n",
1929 debugstr_w(wm->ldr.FullDllName.Buffer),
1930 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1932 SERVER_START_REQ( unload_dll )
1934 req->base = wm->ldr.BaseAddress;
1935 wine_server_call( req );
1937 SERVER_END_REQ;
1939 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
1940 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1941 if (cached_modref == wm) cached_modref = NULL;
1942 RtlFreeUnicodeString( &wm->ldr.FullDllName );
1943 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1944 RtlFreeHeap( GetProcessHeap(), 0, wm );
1947 /***********************************************************************
1948 * MODULE_FlushModrefs
1950 * Remove all unused modrefs and call the internal unloading routines
1951 * for the library type.
1953 * The loader_section must be locked while calling this function.
1955 static void MODULE_FlushModrefs(void)
1957 PLIST_ENTRY mark, entry, prev;
1958 PLDR_MODULE mod;
1959 WINE_MODREF*wm;
1961 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1962 for (entry = mark->Blink; entry != mark; entry = prev)
1964 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
1965 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1966 prev = entry->Blink;
1967 if (!mod->LoadCount) free_modref( wm );
1970 /* check load order list too for modules that haven't been initialized yet */
1971 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1972 for (entry = mark->Blink; entry != mark; entry = prev)
1974 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1975 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1976 prev = entry->Blink;
1977 if (!mod->LoadCount) free_modref( wm );
1981 /***********************************************************************
1982 * MODULE_DecRefCount
1984 * The loader_section must be locked while calling this function.
1986 static void MODULE_DecRefCount( WINE_MODREF *wm )
1988 int i;
1990 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1991 return;
1993 if ( wm->ldr.LoadCount <= 0 )
1994 return;
1996 --wm->ldr.LoadCount;
1997 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1999 if ( wm->ldr.LoadCount == 0 )
2001 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2003 for ( i = 0; i < wm->nDeps; i++ )
2004 if ( wm->deps[i] )
2005 MODULE_DecRefCount( wm->deps[i] );
2007 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2011 /******************************************************************
2012 * LdrUnloadDll (NTDLL.@)
2016 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2018 NTSTATUS retv = STATUS_SUCCESS;
2020 TRACE("(%p)\n", hModule);
2022 RtlEnterCriticalSection( &loader_section );
2024 /* if we're stopping the whole process (and forcing the removal of all
2025 * DLLs) the library will be freed anyway
2027 if (!process_detaching)
2029 WINE_MODREF *wm;
2031 free_lib_count++;
2032 if ((wm = get_modref( hModule )) != NULL)
2034 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2036 /* Recursively decrement reference counts */
2037 MODULE_DecRefCount( wm );
2039 /* Call process detach notifications */
2040 if ( free_lib_count <= 1 )
2042 process_detach( FALSE, NULL );
2043 MODULE_FlushModrefs();
2046 TRACE("END\n");
2048 else
2049 retv = STATUS_DLL_NOT_FOUND;
2051 free_lib_count--;
2054 RtlLeaveCriticalSection( &loader_section );
2056 return retv;
2059 /***********************************************************************
2060 * RtlImageNtHeader (NTDLL.@)
2062 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2064 IMAGE_NT_HEADERS *ret;
2066 __TRY
2068 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2070 ret = NULL;
2071 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2073 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2074 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2077 __EXCEPT_PAGE_FAULT
2079 return NULL;
2081 __ENDTRY
2082 return ret;
2086 /******************************************************************
2087 * LdrInitializeThunk (NTDLL.@)
2090 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2092 NTSTATUS status;
2093 WINE_MODREF *wm;
2094 LPCWSTR load_path;
2095 PEB *peb = NtCurrentTeb()->Peb;
2096 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2098 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2100 /* allocate the modref for the main exe (if not already done) */
2101 wm = get_modref( peb->ImageBaseAddress );
2102 assert( wm );
2103 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2105 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2106 exit(1);
2108 wm->ldr.LoadCount = -1; /* can't unload main exe */
2110 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2111 version_init( wm->ldr.FullDllName.Buffer );
2113 /* the main exe needs to be the first in the load order list */
2114 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2115 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2117 /* Install signal handlers; this cannot be done before, since we cannot
2118 * send exceptions to the debugger before the create process event that
2119 * is sent by REQ_INIT_PROCESS_DONE.
2120 * We do need the handlers in place by the time the request is over, so
2121 * we set them up here. If we segfault between here and the server call
2122 * something is very wrong... */
2123 if (!SIGNAL_Init()) exit(1);
2125 /* Signal the parent process to continue */
2126 SERVER_START_REQ( init_process_done )
2128 req->module = peb->ImageBaseAddress;
2129 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
2130 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
2131 status = wine_server_call( req );
2133 SERVER_END_REQ;
2135 if (status != STATUS_SUCCESS) goto error;
2137 RtlEnterCriticalSection( &loader_section );
2139 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2140 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2141 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2142 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2143 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2145 if (last_failed_modref)
2146 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2147 goto error;
2149 attach_implicitly_loaded_dlls( (LPVOID)1 );
2151 RtlLeaveCriticalSection( &loader_section );
2153 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2154 return;
2156 error:
2157 ERR( "Main exe initialization for %s failed, status %lx\n",
2158 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2159 exit(1);
2163 /***********************************************************************
2164 * RtlImageDirectoryEntryToData (NTDLL.@)
2166 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2168 const IMAGE_NT_HEADERS *nt;
2169 DWORD addr;
2171 if ((ULONG_PTR)module & 1) /* mapped as data file */
2173 module = (HMODULE)((ULONG_PTR)module & ~1);
2174 image = FALSE;
2176 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2177 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2178 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2179 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2180 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2182 /* not mapped as image, need to find the section containing the virtual address */
2183 return RtlImageRvaToVa( nt, module, addr, NULL );
2187 /***********************************************************************
2188 * RtlImageRvaToSection (NTDLL.@)
2190 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2191 HMODULE module, DWORD rva )
2193 int i;
2194 const IMAGE_SECTION_HEADER *sec;
2196 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2197 nt->FileHeader.SizeOfOptionalHeader);
2198 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2200 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2201 return (PIMAGE_SECTION_HEADER)sec;
2203 return NULL;
2207 /***********************************************************************
2208 * RtlImageRvaToVa (NTDLL.@)
2210 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2211 DWORD rva, IMAGE_SECTION_HEADER **section )
2213 IMAGE_SECTION_HEADER *sec;
2215 if (section && *section) /* try this section first */
2217 sec = *section;
2218 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2219 goto found;
2221 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2222 found:
2223 if (section) *section = sec;
2224 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2228 /***********************************************************************
2229 * RtlPcToFileHeader (NTDLL.@)
2231 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2233 LDR_MODULE *module;
2234 PVOID ret = NULL;
2236 RtlEnterCriticalSection( &loader_section );
2237 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2238 RtlLeaveCriticalSection( &loader_section );
2239 *address = ret;
2240 return ret;
2244 /***********************************************************************
2245 * NtLoadDriver (NTDLL.@)
2246 * ZwLoadDriver (NTDLL.@)
2248 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2250 FIXME("(%p), stub!\n",DriverServiceName);
2251 return STATUS_NOT_IMPLEMENTED;
2255 /***********************************************************************
2256 * NtUnloadDriver (NTDLL.@)
2257 * ZwUnloadDriver (NTDLL.@)
2259 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2261 FIXME("(%p), stub!\n",DriverServiceName);
2262 return STATUS_NOT_IMPLEMENTED;
2266 /******************************************************************
2267 * DllMain (NTDLL.@)
2269 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2271 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2272 return TRUE;
2276 /******************************************************************
2277 * __wine_init_windows_dir (NTDLL.@)
2279 * Windows and system dir initialization once kernel32 has been loaded.
2281 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2283 PLIST_ENTRY mark, entry;
2284 LPWSTR buffer, p;
2286 RtlCreateUnicodeString( &system_dir, sysdir );
2288 /* prepend the system dir to the name of the already created modules */
2289 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2290 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2292 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2294 assert( mod->Flags & LDR_WINE_INTERNAL );
2296 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2297 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2298 if (!buffer) continue;
2299 strcpyW( buffer, system_dir.Buffer );
2300 p = buffer + strlenW( buffer );
2301 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2302 strcpyW( p, mod->FullDllName.Buffer );
2303 RtlInitUnicodeString( &mod->FullDllName, buffer );
2304 RtlInitUnicodeString( &mod->BaseDllName, p );
2309 /***********************************************************************
2310 * check_command_line
2312 * Check if command line is one that needs to be handled specially.
2314 static void check_command_line( int argc, char *argv[] )
2316 static const char version[] = PACKAGE_STRING "\n";
2317 static const char usage[] =
2318 "Usage: wine PROGRAM [ARGUMENTS...] Run the specified program\n"
2319 " wine --help Display this help and exit\n"
2320 " wine --version Output version information and exit\n";
2322 if (argc <= 1)
2324 write( 2, usage, sizeof(usage) - 1 );
2325 exit(1);
2327 if (!strcmp( argv[1], "--help" ))
2329 write( 1, usage, sizeof(usage) - 1 );
2330 exit(0);
2332 if (!strcmp( argv[1], "--version" ))
2334 write( 1, version, sizeof(version) - 1 );
2335 exit(0);
2340 /***********************************************************************
2341 * __wine_process_init
2343 void __wine_process_init(void)
2345 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2347 WINE_MODREF *wm;
2348 NTSTATUS status;
2349 ANSI_STRING func_name;
2350 void (* DECLSPEC_NORETURN init_func)(void);
2351 extern mode_t FILE_umask;
2353 check_command_line( __wine_main_argc, __wine_main_argv );
2354 main_exe_file = thread_init();
2356 /* retrieve current umask */
2357 FILE_umask = umask(0777);
2358 umask( FILE_umask );
2360 /* setup the load callback and create ntdll modref */
2361 wine_dll_set_callback( load_builtin_callback );
2363 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2365 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
2366 exit(1);
2368 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2369 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2370 0, (void **)&init_func )) != STATUS_SUCCESS)
2372 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );
2373 exit(1);
2375 init_func();