d3d: Remove AddRef from IWineD3DDevice_GetDepthStencilSurface.
[wine.git] / dlls / ntdll / loader.c
blob87767e574571a0db2fc853762c59c5c6e8215e67
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 SIZE_T 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 %d 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 %x).\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 %04x idx %d: %d/%d 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("%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 );
791 if (TRACE_ON(relay))
792 DPRINTF("%04x: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("%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
830 deleted. */
831 if (TRACE_ON(relay))
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 );
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 %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 )
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("%x %x %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;
1277 SIZE_T size;
1279 if (!module)
1281 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1282 return;
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;
1288 return;
1290 addr = module;
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;
1300 return;
1303 wm = alloc_module( module, fullname );
1304 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1305 if (!wm)
1307 ERR( "can't load %s\n", filename );
1308 builtin_load_info->status = STATUS_NO_MEMORY;
1309 return;
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;
1318 else
1320 /* fixup imports */
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;
1332 return;
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 )
1343 req->handle = 0;
1344 req->base = module;
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 );
1352 SERVER_END_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 )
1365 void *module;
1366 HANDLE mapping;
1367 OBJECT_ATTRIBUTES attr;
1368 LARGE_INTEGER size;
1369 IMAGE_NT_HEADERS *nt;
1370 SIZE_T len = 0;
1371 WINE_MODREF *wm;
1372 NTSTATUS status;
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;
1382 size.QuadPart = 0;
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;
1388 module = NULL;
1389 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1390 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1391 NtClose( mapping );
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;
1405 /* fixup imports */
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.
1422 return status;
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 )
1435 req->handle = file;
1436 req->base = module;
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 );
1444 SERVER_END_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;
1451 *pwm = wm;
1452 return STATUS_SUCCESS;
1456 /***********************************************************************
1457 * load_builtin_dll
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;
1464 DWORD len, i;
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 */
1469 name = path;
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
1476 * libraries
1478 info.load_path = load_path;
1479 info.filename = NULL;
1480 info.status = STATUS_SUCCESS;
1481 info.wm = NULL;
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 );
1505 if (!handle)
1507 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1508 return STATUS_INVALID_IMAGE_FORMAT;
1511 else
1513 int file_exists;
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;
1531 if (!handle)
1533 if (!file_exists)
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;
1547 if (!info.wm)
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) );
1563 break;
1566 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1567 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1569 else
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;
1576 *pwm = info.wm;
1577 return STATUS_SUCCESS;
1581 /***********************************************************************
1582 * find_dll_file
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;
1590 IO_STATUS_BLOCK io;
1591 UNICODE_STRING nt_name;
1592 WCHAR *file_part, *ext, *dllname;
1593 ULONG len;
1595 /* first append .dll if needed */
1597 dllname = NULL;
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 );
1605 libname = dllname;
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 );
1619 if (len)
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;
1636 goto found;
1639 /* not found */
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 );
1648 goto found;
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;
1672 found:
1673 RtlFreeUnicodeString( &nt_name );
1674 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1675 return STATUS_SUCCESS;
1677 overflow:
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;
1694 WCHAR buffer[32];
1695 WCHAR *filename;
1696 ULONG size;
1697 WINE_MODREF *main_exe;
1698 HANDLE handle = 0;
1699 NTSTATUS nts;
1701 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1703 filename = buffer;
1704 size = sizeof(buffer);
1705 for (;;)
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 );
1731 switch(loadorder)
1733 case LO_INVALID:
1734 nts = STATUS_NO_MEMORY;
1735 break;
1736 case LO_DISABLED:
1737 nts = STATUS_DLL_NOT_FOUND;
1738 break;
1739 case LO_NATIVE:
1740 case LO_NATIVE_BUILTIN:
1741 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1742 else
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 );
1751 break;
1752 case LO_BUILTIN:
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 );
1770 break;
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 );
1781 return nts;
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 );
1787 return nts;
1790 /******************************************************************
1791 * LdrLoadDll (NTDLL.@)
1793 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1794 const UNICODE_STRING *libname, HMODULE* hModule)
1796 WINE_MODREF *wm;
1797 NTSTATUS nts;
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);
1810 wm = NULL;
1813 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1815 RtlLeaveCriticalSection( &loader_section );
1816 return nts;
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;
1829 ANSI_STRING str;
1830 char* ptr;
1831 PLIST_ENTRY mark, entry;
1832 PLDR_MODULE mod;
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 */
1852 str.Length = 0;
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++;
1860 sm++;
1862 else nts = STATUS_INFO_LENGTH_MISMATCH;
1864 RtlLeaveCriticalSection( &loader_section );
1866 if (req_size) *req_size = size;
1868 return nts;
1872 /******************************************************************
1873 * RtlDllShutdownInProgress (NTDLL.@)
1875 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
1877 return process_detaching;
1881 /******************************************************************
1882 * LdrShutdownProcess (NTDLL.@)
1885 void WINAPI LdrShutdownProcess(void)
1887 TRACE("()\n");
1888 process_detach( TRUE, (LPVOID)1 );
1891 /******************************************************************
1892 * LdrShutdownThread (NTDLL.@)
1895 void WINAPI LdrShutdownThread(void)
1897 PLIST_ENTRY mark, entry;
1898 PLDR_MODULE mod;
1900 TRACE("()\n");
1902 /* don't do any detach calls if process is exiting */
1903 if (process_detaching) return;
1904 /* FIXME: there is still a race here */
1906 RtlEnterCriticalSection( &loader_section );
1908 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1909 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1911 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1912 InInitializationOrderModuleList);
1913 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1914 continue;
1915 if ( mod->Flags & LDR_NO_DLL_CALLS )
1916 continue;
1918 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1919 DLL_THREAD_DETACH, NULL );
1922 RtlLeaveCriticalSection( &loader_section );
1923 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
1927 /***********************************************************************
1928 * free_modref
1931 static void free_modref( WINE_MODREF *wm )
1933 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1934 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1935 if (wm->ldr.InInitializationOrderModuleList.Flink)
1936 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
1938 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
1939 if (!TRACE_ON(module))
1940 TRACE_(loaddll)("Unloaded module %s : %s\n",
1941 debugstr_w(wm->ldr.FullDllName.Buffer),
1942 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1944 SERVER_START_REQ( unload_dll )
1946 req->base = wm->ldr.BaseAddress;
1947 wine_server_call( req );
1949 SERVER_END_REQ;
1951 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
1952 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1953 if (cached_modref == wm) cached_modref = NULL;
1954 RtlFreeUnicodeString( &wm->ldr.FullDllName );
1955 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1956 RtlFreeHeap( GetProcessHeap(), 0, wm );
1959 /***********************************************************************
1960 * MODULE_FlushModrefs
1962 * Remove all unused modrefs and call the internal unloading routines
1963 * for the library type.
1965 * The loader_section must be locked while calling this function.
1967 static void MODULE_FlushModrefs(void)
1969 PLIST_ENTRY mark, entry, prev;
1970 PLDR_MODULE mod;
1971 WINE_MODREF*wm;
1973 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1974 for (entry = mark->Blink; entry != mark; entry = prev)
1976 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
1977 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1978 prev = entry->Blink;
1979 if (!mod->LoadCount) free_modref( wm );
1982 /* check load order list too for modules that haven't been initialized yet */
1983 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1984 for (entry = mark->Blink; entry != mark; entry = prev)
1986 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1987 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1988 prev = entry->Blink;
1989 if (!mod->LoadCount) free_modref( wm );
1993 /***********************************************************************
1994 * MODULE_DecRefCount
1996 * The loader_section must be locked while calling this function.
1998 static void MODULE_DecRefCount( WINE_MODREF *wm )
2000 int i;
2002 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2003 return;
2005 if ( wm->ldr.LoadCount <= 0 )
2006 return;
2008 --wm->ldr.LoadCount;
2009 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2011 if ( wm->ldr.LoadCount == 0 )
2013 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2015 for ( i = 0; i < wm->nDeps; i++ )
2016 if ( wm->deps[i] )
2017 MODULE_DecRefCount( wm->deps[i] );
2019 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2023 /******************************************************************
2024 * LdrUnloadDll (NTDLL.@)
2028 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2030 NTSTATUS retv = STATUS_SUCCESS;
2032 TRACE("(%p)\n", hModule);
2034 RtlEnterCriticalSection( &loader_section );
2036 /* if we're stopping the whole process (and forcing the removal of all
2037 * DLLs) the library will be freed anyway
2039 if (!process_detaching)
2041 WINE_MODREF *wm;
2043 free_lib_count++;
2044 if ((wm = get_modref( hModule )) != NULL)
2046 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2048 /* Recursively decrement reference counts */
2049 MODULE_DecRefCount( wm );
2051 /* Call process detach notifications */
2052 if ( free_lib_count <= 1 )
2054 process_detach( FALSE, NULL );
2055 MODULE_FlushModrefs();
2058 TRACE("END\n");
2060 else
2061 retv = STATUS_DLL_NOT_FOUND;
2063 free_lib_count--;
2066 RtlLeaveCriticalSection( &loader_section );
2068 return retv;
2071 /***********************************************************************
2072 * RtlImageNtHeader (NTDLL.@)
2074 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2076 IMAGE_NT_HEADERS *ret;
2078 __TRY
2080 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2082 ret = NULL;
2083 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2085 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2086 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2089 __EXCEPT_PAGE_FAULT
2091 return NULL;
2093 __ENDTRY
2094 return ret;
2098 /******************************************************************
2099 * LdrInitializeThunk (NTDLL.@)
2102 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2104 NTSTATUS status;
2105 WINE_MODREF *wm;
2106 LPCWSTR load_path;
2107 PEB *peb = NtCurrentTeb()->Peb;
2108 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2110 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2112 /* allocate the modref for the main exe (if not already done) */
2113 wm = get_modref( peb->ImageBaseAddress );
2114 assert( wm );
2115 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2117 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2118 exit(1);
2120 wm->ldr.LoadCount = -1; /* can't unload main exe */
2122 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2123 version_init( wm->ldr.FullDllName.Buffer );
2125 /* the main exe needs to be the first in the load order list */
2126 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2127 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2129 /* Install signal handlers; this cannot be done before, since we cannot
2130 * send exceptions to the debugger before the create process event that
2131 * is sent by REQ_INIT_PROCESS_DONE.
2132 * We do need the handlers in place by the time the request is over, so
2133 * we set them up here. If we segfault between here and the server call
2134 * something is very wrong... */
2135 if (!SIGNAL_Init()) exit(1);
2137 /* Signal the parent process to continue */
2138 SERVER_START_REQ( init_process_done )
2140 req->module = peb->ImageBaseAddress;
2141 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
2142 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
2143 status = wine_server_call( req );
2145 SERVER_END_REQ;
2147 if (status != STATUS_SUCCESS) goto error;
2149 RtlEnterCriticalSection( &loader_section );
2151 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2152 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2153 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2154 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2155 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2157 if (last_failed_modref)
2158 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2159 goto error;
2161 attach_implicitly_loaded_dlls( (LPVOID)1 );
2163 RtlLeaveCriticalSection( &loader_section );
2165 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2166 return;
2168 error:
2169 ERR( "Main exe initialization for %s failed, status %x\n",
2170 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2171 exit(1);
2175 /***********************************************************************
2176 * RtlImageDirectoryEntryToData (NTDLL.@)
2178 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2180 const IMAGE_NT_HEADERS *nt;
2181 DWORD addr;
2183 if ((ULONG_PTR)module & 1) /* mapped as data file */
2185 module = (HMODULE)((ULONG_PTR)module & ~1);
2186 image = FALSE;
2188 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2189 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2190 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2191 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2192 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2194 /* not mapped as image, need to find the section containing the virtual address */
2195 return RtlImageRvaToVa( nt, module, addr, NULL );
2199 /***********************************************************************
2200 * RtlImageRvaToSection (NTDLL.@)
2202 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2203 HMODULE module, DWORD rva )
2205 int i;
2206 const IMAGE_SECTION_HEADER *sec;
2208 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2209 nt->FileHeader.SizeOfOptionalHeader);
2210 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2212 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2213 return (PIMAGE_SECTION_HEADER)sec;
2215 return NULL;
2219 /***********************************************************************
2220 * RtlImageRvaToVa (NTDLL.@)
2222 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2223 DWORD rva, IMAGE_SECTION_HEADER **section )
2225 IMAGE_SECTION_HEADER *sec;
2227 if (section && *section) /* try this section first */
2229 sec = *section;
2230 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2231 goto found;
2233 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2234 found:
2235 if (section) *section = sec;
2236 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2240 /***********************************************************************
2241 * RtlPcToFileHeader (NTDLL.@)
2243 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2245 LDR_MODULE *module;
2246 PVOID ret = NULL;
2248 RtlEnterCriticalSection( &loader_section );
2249 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2250 RtlLeaveCriticalSection( &loader_section );
2251 *address = ret;
2252 return ret;
2256 /***********************************************************************
2257 * NtLoadDriver (NTDLL.@)
2258 * ZwLoadDriver (NTDLL.@)
2260 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2262 FIXME("(%p), stub!\n",DriverServiceName);
2263 return STATUS_NOT_IMPLEMENTED;
2267 /***********************************************************************
2268 * NtUnloadDriver (NTDLL.@)
2269 * ZwUnloadDriver (NTDLL.@)
2271 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2273 FIXME("(%p), stub!\n",DriverServiceName);
2274 return STATUS_NOT_IMPLEMENTED;
2278 /******************************************************************
2279 * DllMain (NTDLL.@)
2281 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2283 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2284 return TRUE;
2288 /******************************************************************
2289 * __wine_init_windows_dir (NTDLL.@)
2291 * Windows and system dir initialization once kernel32 has been loaded.
2293 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2295 PLIST_ENTRY mark, entry;
2296 LPWSTR buffer, p;
2298 RtlCreateUnicodeString( &system_dir, sysdir );
2300 /* prepend the system dir to the name of the already created modules */
2301 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2302 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2304 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2306 assert( mod->Flags & LDR_WINE_INTERNAL );
2308 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2309 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2310 if (!buffer) continue;
2311 strcpyW( buffer, system_dir.Buffer );
2312 p = buffer + strlenW( buffer );
2313 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2314 strcpyW( p, mod->FullDllName.Buffer );
2315 RtlInitUnicodeString( &mod->FullDllName, buffer );
2316 RtlInitUnicodeString( &mod->BaseDllName, p );
2321 /***********************************************************************
2322 * __wine_process_init
2324 void __wine_process_init(void)
2326 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2328 WINE_MODREF *wm;
2329 NTSTATUS status;
2330 ANSI_STRING func_name;
2331 void (* DECLSPEC_NORETURN init_func)(void);
2332 extern mode_t FILE_umask;
2334 main_exe_file = thread_init();
2336 /* retrieve current umask */
2337 FILE_umask = umask(0777);
2338 umask( FILE_umask );
2340 /* setup the load callback and create ntdll modref */
2341 wine_dll_set_callback( load_builtin_callback );
2343 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2345 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2346 exit(1);
2348 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2349 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2350 0, (void **)&init_func )) != STATUS_SUCCESS)
2352 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2353 exit(1);
2355 init_func();