ntdll: Store the windows directory too.
[wine.git] / dlls / ntdll / loader.c
blobca06e8931ac301d71a2a47c14c023a83647d0eea
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 "wine/library.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41 #include "wine/server.h"
42 #include "ntdll_misc.h"
43 #include "ddk/wdm.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 windows_dir = { 0, 0, NULL }; /* windows directory */
95 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
97 static RTL_CRITICAL_SECTION loader_section;
98 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
100 0, 0, &loader_section,
101 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
102 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
104 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
106 static WINE_MODREF *cached_modref;
107 static WINE_MODREF *current_modref;
108 static WINE_MODREF *last_failed_modref;
110 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
111 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
112 DWORD exp_size, const char *name, int hint );
114 /* convert PE image VirtualAddress to Real Address */
115 static inline void *get_rva( HMODULE module, DWORD va )
117 return (void *)((char *)module + va);
120 /* check whether the file name contains a path */
121 static inline int contains_path( LPCWSTR name )
123 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
126 /* convert from straight ASCII to Unicode without depending on the current codepage */
127 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
129 while (len--) *dst++ = (unsigned char)*src++;
133 /*************************************************************************
134 * call_dll_entry_point
136 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
137 * their entry point, so we need a small asm wrapper.
139 #ifdef __i386__
140 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
141 __ASM_GLOBAL_FUNC(call_dll_entry_point,
142 "pushl %ebp\n\t"
143 "movl %esp,%ebp\n\t"
144 "pushl %ebx\n\t"
145 "subl $8,%esp\n\t"
146 "pushl 20(%ebp)\n\t"
147 "pushl 16(%ebp)\n\t"
148 "pushl 12(%ebp)\n\t"
149 "movl 8(%ebp),%eax\n\t"
150 "call *%eax\n\t"
151 "leal -4(%ebp),%esp\n\t"
152 "popl %ebx\n\t"
153 "popl %ebp\n\t"
154 "ret" )
155 #else /* __i386__ */
156 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
157 UINT reason, void *reserved )
159 return proc( module, reason, reserved );
161 #endif /* __i386__ */
164 #ifdef __i386__
165 /*************************************************************************
166 * stub_entry_point
168 * Entry point for stub functions.
170 static void stub_entry_point( const char *dll, const char *name, ... )
172 EXCEPTION_RECORD rec;
174 rec.ExceptionCode = EXCEPTION_WINE_STUB;
175 rec.ExceptionFlags = EH_NONCONTINUABLE;
176 rec.ExceptionRecord = NULL;
177 #ifdef __GNUC__
178 rec.ExceptionAddress = __builtin_return_address(0);
179 #else
180 rec.ExceptionAddress = *((void **)&dll - 1);
181 #endif
182 rec.NumberParameters = 2;
183 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
184 rec.ExceptionInformation[1] = (ULONG_PTR)name;
185 for (;;) RtlRaiseException( &rec );
189 #include "pshpack1.h"
190 struct stub
192 BYTE popl_eax; /* popl %eax */
193 BYTE pushl1; /* pushl $name */
194 const char *name;
195 BYTE pushl2; /* pushl $dll */
196 const char *dll;
197 BYTE pushl_eax; /* pushl %eax */
198 BYTE jmp; /* jmp stub_entry_point */
199 DWORD entry;
201 #include "poppack.h"
203 /*************************************************************************
204 * allocate_stub
206 * Allocate a stub entry point.
208 static ULONG_PTR allocate_stub( const char *dll, const char *name )
210 #define MAX_SIZE 65536
211 static struct stub *stubs;
212 static unsigned int nb_stubs;
213 struct stub *stub;
215 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
217 if (!stubs)
219 SIZE_T size = MAX_SIZE;
220 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
221 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
222 return 0xdeadbeef;
224 stub = &stubs[nb_stubs++];
225 stub->popl_eax = 0x58; /* popl %eax */
226 stub->pushl1 = 0x68; /* pushl $name */
227 stub->name = name;
228 stub->pushl2 = 0x68; /* pushl $dll */
229 stub->dll = dll;
230 stub->pushl_eax = 0x50; /* pushl %eax */
231 stub->jmp = 0xe9; /* jmp stub_entry_point */
232 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
233 return (ULONG_PTR)stub;
236 #else /* __i386__ */
237 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
238 #endif /* __i386__ */
241 /*************************************************************************
242 * get_modref
244 * Looks for the referenced HMODULE in the current process
245 * The loader_section must be locked while calling this function.
247 static WINE_MODREF *get_modref( HMODULE hmod )
249 PLIST_ENTRY mark, entry;
250 PLDR_MODULE mod;
252 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
254 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
255 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
257 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
258 if (mod->BaseAddress == hmod)
259 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
260 if (mod->BaseAddress > (void*)hmod) break;
262 return NULL;
266 /**********************************************************************
267 * find_basename_module
269 * Find a module from its base name.
270 * The loader_section must be locked while calling this function
272 static WINE_MODREF *find_basename_module( LPCWSTR name )
274 PLIST_ENTRY mark, entry;
276 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
277 return cached_modref;
279 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
280 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
282 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
283 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
285 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
286 return cached_modref;
289 return NULL;
293 /**********************************************************************
294 * find_fullname_module
296 * Find a module from its full path name.
297 * The loader_section must be locked while calling this function
299 static WINE_MODREF *find_fullname_module( LPCWSTR name )
301 PLIST_ENTRY mark, entry;
303 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
304 return cached_modref;
306 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
307 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
309 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
310 if (!strcmpiW( name, mod->FullDllName.Buffer ))
312 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
313 return cached_modref;
316 return NULL;
320 /*************************************************************************
321 * find_forwarded_export
323 * Find the final function pointer for a forwarded function.
324 * The loader_section must be locked while calling this function.
326 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
328 const IMAGE_EXPORT_DIRECTORY *exports;
329 DWORD exp_size;
330 WINE_MODREF *wm;
331 WCHAR mod_name[32];
332 const char *end = strrchr(forward, '.');
333 FARPROC proc = NULL;
335 if (!end) return NULL;
336 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
337 ascii_to_unicode( mod_name, forward, end - forward );
338 mod_name[end - forward] = 0;
339 if (!strchrW( mod_name, '.' ))
341 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
342 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
345 if (!(wm = find_basename_module( mod_name )))
347 ERR("module not found for forward '%s' used by %s\n",
348 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
349 return NULL;
351 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
352 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
353 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
355 if (!proc)
357 ERR("function not found for forward '%s' used by %s."
358 " If you are using builtin %s, try using the native one instead.\n",
359 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
360 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
362 return proc;
366 /*************************************************************************
367 * find_ordinal_export
369 * Find an exported function by ordinal.
370 * The exports base must have been subtracted from the ordinal already.
371 * The loader_section must be locked while calling this function.
373 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
374 DWORD exp_size, DWORD ordinal )
376 FARPROC proc;
377 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
379 if (ordinal >= exports->NumberOfFunctions)
381 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
382 return NULL;
384 if (!functions[ordinal]) return NULL;
386 proc = get_rva( module, functions[ordinal] );
388 /* if the address falls into the export dir, it's a forward */
389 if (((const char *)proc >= (const char *)exports) &&
390 ((const char *)proc < (const char *)exports + exp_size))
391 return find_forwarded_export( module, (const char *)proc );
393 if (TRACE_ON(snoop))
395 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
396 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
398 if (TRACE_ON(relay))
400 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
401 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
403 return proc;
407 /*************************************************************************
408 * find_named_export
410 * Find an exported function by name.
411 * The loader_section must be locked while calling this function.
413 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
414 DWORD exp_size, const char *name, int hint )
416 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
417 const DWORD *names = get_rva( module, exports->AddressOfNames );
418 int min = 0, max = exports->NumberOfNames - 1;
420 /* first check the hint */
421 if (hint >= 0 && hint <= max)
423 char *ename = get_rva( module, names[hint] );
424 if (!strcmp( ename, name ))
425 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
428 /* then do a binary search */
429 while (min <= max)
431 int res, pos = (min + max) / 2;
432 char *ename = get_rva( module, names[pos] );
433 if (!(res = strcmp( ename, name )))
434 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
435 if (res > 0) max = pos - 1;
436 else min = pos + 1;
438 return NULL;
443 /*************************************************************************
444 * import_dll
446 * Import the dll specified by the given import descriptor.
447 * The loader_section must be locked while calling this function.
449 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
451 NTSTATUS status;
452 WINE_MODREF *wmImp;
453 HMODULE imp_mod;
454 const IMAGE_EXPORT_DIRECTORY *exports;
455 DWORD exp_size;
456 const IMAGE_THUNK_DATA *import_list;
457 IMAGE_THUNK_DATA *thunk_list;
458 WCHAR buffer[32];
459 const char *name = get_rva( module, descr->Name );
460 DWORD len = strlen(name);
461 PVOID protect_base;
462 SIZE_T protect_size = 0;
463 DWORD protect_old;
465 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
466 if (descr->u.OriginalFirstThunk)
467 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
468 else
469 import_list = thunk_list;
471 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
473 if (len * sizeof(WCHAR) < sizeof(buffer))
475 ascii_to_unicode( buffer, name, len );
476 buffer[len] = 0;
477 status = load_dll( load_path, buffer, 0, &wmImp );
479 else /* need to allocate a larger buffer */
481 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
482 if (!ptr) return NULL;
483 ascii_to_unicode( ptr, name, len );
484 ptr[len] = 0;
485 status = load_dll( load_path, ptr, 0, &wmImp );
486 RtlFreeHeap( GetProcessHeap(), 0, ptr );
489 if (status)
491 if (status == STATUS_DLL_NOT_FOUND)
492 ERR("Library %s (which is needed by %s) not found\n",
493 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
494 else
495 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
496 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
497 return NULL;
500 /* unprotect the import address table since it can be located in
501 * readonly section */
502 while (import_list[protect_size].u1.Ordinal) protect_size++;
503 protect_base = thunk_list;
504 protect_size *= sizeof(*thunk_list);
505 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
506 &protect_size, PAGE_WRITECOPY, &protect_old );
508 imp_mod = wmImp->ldr.BaseAddress;
509 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
511 if (!exports)
513 /* set all imported function to deadbeef */
514 while (import_list->u1.Ordinal)
516 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
518 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
519 WARN("No implementation for %s.%d", name, ordinal );
520 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
522 else
524 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
525 WARN("No implementation for %s.%s", name, pe_name->Name );
526 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
528 WARN(" imported from %s, allocating stub %p\n",
529 debugstr_w(current_modref->ldr.FullDllName.Buffer),
530 (void *)thunk_list->u1.Function );
531 import_list++;
532 thunk_list++;
534 goto done;
537 while (import_list->u1.Ordinal)
539 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
541 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
543 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
544 ordinal - exports->Base );
545 if (!thunk_list->u1.Function)
547 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
548 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
549 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
550 (void *)thunk_list->u1.Function );
552 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
554 else /* import by name */
556 IMAGE_IMPORT_BY_NAME *pe_name;
557 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
558 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
559 (const char*)pe_name->Name, pe_name->Hint );
560 if (!thunk_list->u1.Function)
562 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
563 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
564 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
565 (void *)thunk_list->u1.Function );
567 TRACE_(imports)("--- %s %s.%d = %p\n",
568 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
570 import_list++;
571 thunk_list++;
574 done:
575 /* restore old protection of the import address table */
576 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
577 return wmImp;
581 /****************************************************************
582 * fixup_imports
584 * Fixup all imports of a given module.
585 * The loader_section must be locked while calling this function.
587 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
589 int i, nb_imports;
590 const IMAGE_IMPORT_DESCRIPTOR *imports;
591 WINE_MODREF *prev;
592 DWORD size;
593 NTSTATUS status;
595 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
596 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
598 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
599 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
600 return STATUS_SUCCESS;
602 nb_imports = 0;
603 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
605 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
607 /* Allocate module dependency list */
608 wm->nDeps = nb_imports;
609 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
611 /* load the imported modules. They are automatically
612 * added to the modref list of the process.
614 prev = current_modref;
615 current_modref = wm;
616 status = STATUS_SUCCESS;
617 for (i = 0; i < nb_imports; i++)
619 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
620 status = STATUS_DLL_NOT_FOUND;
622 current_modref = prev;
623 return status;
627 /*************************************************************************
628 * alloc_module
630 * Allocate a WINE_MODREF structure and add it to the process list
631 * The loader_section must be locked while calling this function.
633 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
635 WINE_MODREF *wm;
636 const WCHAR *p;
637 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
638 PLIST_ENTRY entry, mark;
640 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
642 wm->nDeps = 0;
643 wm->deps = NULL;
645 wm->ldr.BaseAddress = hModule;
646 wm->ldr.EntryPoint = NULL;
647 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
648 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
649 wm->ldr.LoadCount = 1;
650 wm->ldr.TlsIndex = -1;
651 wm->ldr.SectionHandle = NULL;
652 wm->ldr.CheckSum = 0;
653 wm->ldr.TimeDateStamp = 0;
655 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
656 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
657 else p = wm->ldr.FullDllName.Buffer;
658 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
660 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
662 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
663 if (nt->OptionalHeader.AddressOfEntryPoint)
664 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
667 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
668 &wm->ldr.InLoadOrderModuleList);
670 /* insert module in MemoryList, sorted in increasing base addresses */
671 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
672 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
674 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
675 break;
677 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
678 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
679 wm->ldr.InMemoryOrderModuleList.Flink = entry;
680 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
682 /* wait until init is called for inserting into this list */
683 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
684 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
686 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
688 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
689 VIRTUAL_SetForceExec( TRUE );
691 return wm;
695 /*************************************************************************
696 * alloc_process_tls
698 * Allocate the process-wide structure for module TLS storage.
700 static NTSTATUS alloc_process_tls(void)
702 PLIST_ENTRY mark, entry;
703 PLDR_MODULE mod;
704 const IMAGE_TLS_DIRECTORY *dir;
705 ULONG size, i;
707 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
708 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
710 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
711 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
712 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
713 continue;
714 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
715 if (!size) continue;
716 tls_total_size += size;
717 tls_module_count++;
719 if (!tls_module_count) return STATUS_SUCCESS;
721 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
723 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
724 if (!tls_dirs) return STATUS_NO_MEMORY;
726 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
728 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
729 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
730 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
731 continue;
732 tls_dirs[i] = dir;
733 *(DWORD *)dir->AddressOfIndex = i;
734 mod->TlsIndex = i;
735 mod->LoadCount = -1; /* can't unload it */
736 i++;
738 return STATUS_SUCCESS;
742 /*************************************************************************
743 * alloc_thread_tls
745 * Allocate the per-thread structure for module TLS storage.
747 static NTSTATUS alloc_thread_tls(void)
749 void **pointers;
750 char *data;
751 UINT i;
753 if (!tls_module_count) return STATUS_SUCCESS;
755 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
756 tls_module_count * sizeof(*pointers) )))
757 return STATUS_NO_MEMORY;
759 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
761 RtlFreeHeap( GetProcessHeap(), 0, pointers );
762 return STATUS_NO_MEMORY;
765 for (i = 0; i < tls_module_count; i++)
767 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
768 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
770 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
771 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
772 (void *)dir->StartAddressOfRawData, data );
774 pointers[i] = data;
775 memcpy( data, (void *)dir->StartAddressOfRawData, size );
776 data += size;
777 memset( data, 0, dir->SizeOfZeroFill );
778 data += dir->SizeOfZeroFill;
780 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
781 return STATUS_SUCCESS;
785 /*************************************************************************
786 * call_tls_callbacks
788 static void call_tls_callbacks( HMODULE module, UINT reason )
790 const IMAGE_TLS_DIRECTORY *dir;
791 const PIMAGE_TLS_CALLBACK *callback;
792 ULONG dirsize;
794 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
795 if (!dir || !dir->AddressOfCallBacks) return;
797 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
799 if (TRACE_ON(relay))
800 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
801 GetCurrentThreadId(), *callback, module, reason_names[reason] );
802 __TRY
804 (*callback)( module, reason, NULL );
806 __EXCEPT(NULL)
808 if (TRACE_ON(relay))
809 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
810 GetCurrentThreadId(), callback, module, reason_names[reason] );
811 return;
813 __ENDTRY
814 if (TRACE_ON(relay))
815 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
816 GetCurrentThreadId(), *callback, module, reason_names[reason] );
821 /*************************************************************************
822 * MODULE_InitDLL
824 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
826 WCHAR mod_name[32];
827 BOOL retv = TRUE;
828 DLLENTRYPROC entry = wm->ldr.EntryPoint;
829 void *module = wm->ldr.BaseAddress;
831 /* Skip calls for modules loaded with special load flags */
833 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
834 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
835 if (!entry) return TRUE;
837 if (TRACE_ON(relay))
839 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
840 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
841 mod_name[len / sizeof(WCHAR)] = 0;
842 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
843 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
844 reason_names[reason], lpReserved );
846 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
847 reason_names[reason], lpReserved );
849 retv = call_dll_entry_point( entry, module, reason, lpReserved );
851 /* The state of the module list may have changed due to the call
852 to the dll. We cannot assume that this module has not been
853 deleted. */
854 if (TRACE_ON(relay))
855 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
856 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
857 reason_names[reason], lpReserved, retv );
858 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
860 return retv;
864 /*************************************************************************
865 * process_attach
867 * Send the process attach notification to all DLLs the given module
868 * depends on (recursively). This is somewhat complicated due to the fact that
870 * - we have to respect the module dependencies, i.e. modules implicitly
871 * referenced by another module have to be initialized before the module
872 * itself can be initialized
874 * - the initialization routine of a DLL can itself call LoadLibrary,
875 * thereby introducing a whole new set of dependencies (even involving
876 * the 'old' modules) at any time during the whole process
878 * (Note that this routine can be recursively entered not only directly
879 * from itself, but also via LoadLibrary from one of the called initialization
880 * routines.)
882 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
883 * the process *detach* notifications to be sent in the correct order.
884 * This must not only take into account module dependencies, but also
885 * 'hidden' dependencies created by modules calling LoadLibrary in their
886 * attach notification routine.
888 * The strategy is rather simple: we move a WINE_MODREF to the head of the
889 * list after the attach notification has returned. This implies that the
890 * detach notifications are called in the reverse of the sequence the attach
891 * notifications *returned*.
893 * The loader_section must be locked while calling this function.
895 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
897 NTSTATUS status = STATUS_SUCCESS;
898 int i;
900 if (process_detaching) return status;
902 /* prevent infinite recursion in case of cyclical dependencies */
903 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
904 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
905 return status;
907 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
909 /* Tag current MODREF to prevent recursive loop */
910 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
912 /* Recursively attach all DLLs this one depends on */
913 for ( i = 0; i < wm->nDeps; i++ )
915 if (!wm->deps[i]) continue;
916 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
919 /* Call DLL entry point */
920 if (status == STATUS_SUCCESS)
922 WINE_MODREF *prev = current_modref;
923 current_modref = wm;
924 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
926 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
928 else
930 /* point to the name so LdrInitializeThunk can print it */
931 last_failed_modref = wm;
932 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
933 status = STATUS_DLL_INIT_FAILED;
935 current_modref = prev;
938 if (!wm->ldr.InInitializationOrderModuleList.Flink)
939 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
940 &wm->ldr.InInitializationOrderModuleList);
942 /* Remove recursion flag */
943 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
945 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
946 return status;
950 /**********************************************************************
951 * attach_implicitly_loaded_dlls
953 * Attach to the (builtin) dlls that have been implicitly loaded because
954 * of a dependency at the Unix level, but not imported at the Win32 level.
956 static void attach_implicitly_loaded_dlls( LPVOID reserved )
958 for (;;)
960 PLIST_ENTRY mark, entry;
962 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
963 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
965 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
967 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
968 TRACE( "found implicitly loaded %s, attaching to it\n",
969 debugstr_w(mod->BaseDllName.Buffer));
970 mod->LoadCount = -1; /* we can't unload it anyway */
971 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
972 break; /* restart the search from the start */
974 if (entry == mark) break; /* nothing found */
979 /*************************************************************************
980 * process_detach
982 * Send DLL process detach notifications. See the comment about calling
983 * sequence at process_attach. Unless the bForceDetach flag
984 * is set, only DLLs with zero refcount are notified.
986 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
988 PLIST_ENTRY mark, entry;
989 PLDR_MODULE mod;
991 RtlEnterCriticalSection( &loader_section );
992 if (bForceDetach) process_detaching = 1;
993 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
996 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
998 mod = CONTAINING_RECORD(entry, LDR_MODULE,
999 InInitializationOrderModuleList);
1000 /* Check whether to detach this DLL */
1001 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1002 continue;
1003 if ( mod->LoadCount && !bForceDetach )
1004 continue;
1006 /* Call detach notification */
1007 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1008 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1009 DLL_PROCESS_DETACH, lpReserved );
1011 /* Restart at head of WINE_MODREF list, as entries might have
1012 been added and/or removed while performing the call ... */
1013 break;
1015 } while (entry != mark);
1017 RtlLeaveCriticalSection( &loader_section );
1020 /*************************************************************************
1021 * MODULE_DllThreadAttach
1023 * Send DLL thread attach notifications. These are sent in the
1024 * reverse sequence of process detach notification.
1027 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1029 PLIST_ENTRY mark, entry;
1030 PLDR_MODULE mod;
1031 NTSTATUS status;
1033 /* don't do any attach calls if process is exiting */
1034 if (process_detaching) return STATUS_SUCCESS;
1035 /* FIXME: there is still a race here */
1037 RtlEnterCriticalSection( &loader_section );
1039 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1041 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1042 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1044 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1045 InInitializationOrderModuleList);
1046 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1047 continue;
1048 if ( mod->Flags & LDR_NO_DLL_CALLS )
1049 continue;
1051 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1052 DLL_THREAD_ATTACH, lpReserved );
1055 done:
1056 RtlLeaveCriticalSection( &loader_section );
1057 return status;
1060 /******************************************************************
1061 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1064 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1066 WINE_MODREF *wm;
1067 NTSTATUS ret = STATUS_SUCCESS;
1069 RtlEnterCriticalSection( &loader_section );
1071 wm = get_modref( hModule );
1072 if (!wm || wm->ldr.TlsIndex != -1)
1073 ret = STATUS_DLL_NOT_FOUND;
1074 else
1075 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1077 RtlLeaveCriticalSection( &loader_section );
1079 return ret;
1082 /******************************************************************
1083 * LdrFindEntryForAddress (NTDLL.@)
1085 * The loader_section must be locked while calling this function
1087 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1089 PLIST_ENTRY mark, entry;
1090 PLDR_MODULE mod;
1092 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1093 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1095 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1096 if ((const void *)mod->BaseAddress <= addr &&
1097 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1099 *pmod = mod;
1100 return STATUS_SUCCESS;
1102 if ((const void *)mod->BaseAddress > addr) break;
1104 return STATUS_NO_MORE_ENTRIES;
1107 /******************************************************************
1108 * LdrLockLoaderLock (NTDLL.@)
1110 * Note: flags are not implemented.
1111 * Flag 0x01 is used to raise exceptions on errors.
1112 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1114 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1116 if (flags) FIXME( "flags %x not supported\n", flags );
1118 if (result) *result = 1;
1119 if (!magic) return STATUS_INVALID_PARAMETER_3;
1120 RtlEnterCriticalSection( &loader_section );
1121 *magic = GetCurrentThreadId();
1122 return STATUS_SUCCESS;
1126 /******************************************************************
1127 * LdrUnlockLoaderUnlock (NTDLL.@)
1129 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1131 if (magic)
1133 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1134 RtlLeaveCriticalSection( &loader_section );
1136 return STATUS_SUCCESS;
1140 /******************************************************************
1141 * LdrGetProcedureAddress (NTDLL.@)
1143 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1144 ULONG ord, PVOID *address)
1146 IMAGE_EXPORT_DIRECTORY *exports;
1147 DWORD exp_size;
1148 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1150 RtlEnterCriticalSection( &loader_section );
1152 /* check if the module itself is invalid to return the proper error */
1153 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1154 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1155 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1157 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1158 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1159 if (proc)
1161 *address = proc;
1162 ret = STATUS_SUCCESS;
1166 RtlLeaveCriticalSection( &loader_section );
1167 return ret;
1171 /***********************************************************************
1172 * is_fake_dll
1174 * Check if a loaded native dll is a Wine fake dll.
1176 static BOOL is_fake_dll( const void *base )
1178 static const char fakedll_signature[] = "Wine placeholder DLL";
1179 const IMAGE_DOS_HEADER *dos = base;
1181 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1182 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1183 return FALSE;
1187 /***********************************************************************
1188 * get_builtin_fullname
1190 * Build the full pathname for a builtin dll.
1192 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1194 static const WCHAR soW[] = {'.','s','o',0};
1195 WCHAR *p, *fullname;
1196 size_t i, len = strlen(filename);
1198 /* check if path can correspond to the dll we have */
1199 if (path && (p = strrchrW( path, '\\' )))
1201 p++;
1202 for (i = 0; i < len; i++)
1203 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1204 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1206 /* the filename matches, use path as the full path */
1207 len += p - path;
1208 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1210 memcpy( fullname, path, len * sizeof(WCHAR) );
1211 fullname[len] = 0;
1213 return fullname;
1217 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1218 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1220 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1221 p = fullname + system_dir.Length / sizeof(WCHAR);
1222 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1223 ascii_to_unicode( p, filename, len + 1 );
1225 return fullname;
1229 /***********************************************************************
1230 * load_builtin_callback
1232 * Load a library in memory; callback function for wine_dll_register
1234 static void load_builtin_callback( void *module, const char *filename )
1236 static const WCHAR emptyW[1];
1237 void *addr;
1238 IMAGE_NT_HEADERS *nt;
1239 WINE_MODREF *wm;
1240 WCHAR *fullname;
1241 const WCHAR *load_path;
1242 SIZE_T size;
1244 if (!module)
1246 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1247 return;
1249 if (!(nt = RtlImageNtHeader( module )))
1251 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1252 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1253 return;
1255 addr = module;
1256 size = nt->OptionalHeader.SizeOfImage;
1257 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1258 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1259 /* create the MODREF */
1261 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1263 ERR( "can't load %s\n", filename );
1264 builtin_load_info->status = STATUS_NO_MEMORY;
1265 return;
1268 wm = alloc_module( module, fullname );
1269 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1270 if (!wm)
1272 ERR( "can't load %s\n", filename );
1273 builtin_load_info->status = STATUS_NO_MEMORY;
1274 return;
1276 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1278 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1279 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1281 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1283 else
1285 /* fixup imports */
1287 load_path = builtin_load_info->load_path;
1288 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1289 if (!load_path) load_path = emptyW;
1290 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1292 /* the module has only be inserted in the load & memory order lists */
1293 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1294 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1295 /* FIXME: free the modref */
1296 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1297 return;
1301 builtin_load_info->wm = wm;
1302 TRACE( "loaded %s %p %p\n", filename, wm, module );
1304 /* send the DLL load event */
1306 SERVER_START_REQ( load_dll )
1308 req->handle = 0;
1309 req->base = module;
1310 req->size = nt->OptionalHeader.SizeOfImage;
1311 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1312 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1313 req->name = &wm->ldr.FullDllName.Buffer;
1314 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1315 wine_server_call( req );
1317 SERVER_END_REQ;
1319 /* setup relay debugging entry points */
1320 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1324 /******************************************************************************
1325 * load_native_dll (internal)
1327 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1328 DWORD flags, WINE_MODREF** pwm )
1330 void *module;
1331 HANDLE mapping;
1332 OBJECT_ATTRIBUTES attr;
1333 LARGE_INTEGER size;
1334 IMAGE_NT_HEADERS *nt;
1335 SIZE_T len = 0;
1336 WINE_MODREF *wm;
1337 NTSTATUS status;
1339 TRACE("Trying native dll %s\n", debugstr_w(name));
1341 attr.Length = sizeof(attr);
1342 attr.RootDirectory = 0;
1343 attr.ObjectName = NULL;
1344 attr.Attributes = 0;
1345 attr.SecurityDescriptor = NULL;
1346 attr.SecurityQualityOfService = NULL;
1347 size.QuadPart = 0;
1349 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1350 &attr, &size, 0, SEC_IMAGE, file );
1351 if (status != STATUS_SUCCESS) return status;
1353 module = NULL;
1354 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1355 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1356 NtClose( mapping );
1357 if (status != STATUS_SUCCESS) return status;
1359 if (is_fake_dll( module ))
1361 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1362 NtUnmapViewOfSection( NtCurrentProcess(), module );
1363 return STATUS_DLL_NOT_FOUND;
1366 /* create the MODREF */
1368 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1370 /* fixup imports */
1372 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1374 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1376 /* the module has only be inserted in the load & memory order lists */
1377 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1378 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1380 /* FIXME: there are several more dangling references
1381 * left. Including dlls loaded by this dll before the
1382 * failed one. Unrolling is rather difficult with the
1383 * current structure and we can leave them lying
1384 * around with no problems, so we don't care.
1385 * As these might reference our wm, we don't free it.
1387 return status;
1391 /* send DLL load event */
1393 nt = RtlImageNtHeader( module );
1395 SERVER_START_REQ( load_dll )
1397 req->handle = file;
1398 req->base = module;
1399 req->size = nt->OptionalHeader.SizeOfImage;
1400 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1401 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1402 req->name = &wm->ldr.FullDllName.Buffer;
1403 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1404 wine_server_call( req );
1406 SERVER_END_REQ;
1408 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1410 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1412 wm->ldr.LoadCount = 1;
1413 *pwm = wm;
1414 return STATUS_SUCCESS;
1418 /***********************************************************************
1419 * load_builtin_dll
1421 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1422 DWORD flags, WINE_MODREF** pwm )
1424 char error[256], dllname[MAX_PATH];
1425 const WCHAR *name, *p;
1426 DWORD len, i;
1427 void *handle = NULL;
1428 struct builtin_load_info info, *prev_info;
1430 /* Fix the name in case we have a full path and extension */
1431 name = path;
1432 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1433 if ((p = strrchrW( name, '/' ))) name = p + 1;
1435 /* load_library will modify info.status. Note also that load_library can be
1436 * called several times, if the .so file we're loading has dependencies.
1437 * info.status will gather all the errors we may get while loading all these
1438 * libraries
1440 info.load_path = load_path;
1441 info.filename = NULL;
1442 info.status = STATUS_SUCCESS;
1443 info.wm = NULL;
1445 if (file) /* we have a real file, try to load it */
1447 UNICODE_STRING nt_name;
1448 ANSI_STRING unix_name;
1450 TRACE("Trying built-in %s\n", debugstr_w(path));
1452 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1453 return STATUS_DLL_NOT_FOUND;
1455 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1457 RtlFreeUnicodeString( &nt_name );
1458 return STATUS_DLL_NOT_FOUND;
1460 prev_info = builtin_load_info;
1461 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1462 builtin_load_info = &info;
1463 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1464 builtin_load_info = prev_info;
1465 RtlFreeUnicodeString( &nt_name );
1466 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1467 if (!handle)
1469 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1470 return STATUS_INVALID_IMAGE_FORMAT;
1473 else
1475 int file_exists;
1477 TRACE("Trying built-in %s\n", debugstr_w(name));
1479 /* we don't want to depend on the current codepage here */
1480 len = strlenW( name ) + 1;
1481 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1482 for (i = 0; i < len; i++)
1484 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1485 dllname[i] = (char)name[i];
1486 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1489 prev_info = builtin_load_info;
1490 builtin_load_info = &info;
1491 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1492 builtin_load_info = prev_info;
1493 if (!handle)
1495 if (!file_exists)
1497 /* The file does not exist -> WARN() */
1498 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1499 return STATUS_DLL_NOT_FOUND;
1501 /* ERR() for all other errors (missing functions, ...) */
1502 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1503 return STATUS_PROCEDURE_NOT_FOUND;
1507 if (info.status != STATUS_SUCCESS)
1509 wine_dll_unload( handle );
1510 return info.status;
1513 if (!info.wm)
1515 PLIST_ENTRY mark, entry;
1517 /* The constructor wasn't called, this means the .so is already
1518 * loaded under a different name. Try to find the wm for it. */
1520 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1521 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1523 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1524 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1526 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1527 TRACE( "Found already loaded module %s for builtin %s\n",
1528 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1529 break;
1532 wine_dll_unload( handle ); /* release the libdl refcount */
1533 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1534 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1536 else
1538 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1539 info.wm->ldr.LoadCount = 1;
1540 info.wm->ldr.SectionHandle = handle;
1543 *pwm = info.wm;
1544 return STATUS_SUCCESS;
1548 /***********************************************************************
1549 * find_dll_file
1551 * Find the file (or already loaded module) for a given dll name.
1553 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1554 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1556 OBJECT_ATTRIBUTES attr;
1557 IO_STATUS_BLOCK io;
1558 UNICODE_STRING nt_name;
1559 WCHAR *file_part, *ext, *dllname;
1560 ULONG len;
1562 /* first append .dll if needed */
1564 dllname = NULL;
1565 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1567 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1568 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1569 return STATUS_NO_MEMORY;
1570 strcpyW( dllname, libname );
1571 strcatW( dllname, dllW );
1572 libname = dllname;
1575 nt_name.Buffer = NULL;
1577 if (!contains_path( libname ))
1579 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1582 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1584 /* we need to search for it */
1585 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1586 if (len)
1588 if (len >= *size) goto overflow;
1589 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1591 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1593 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1594 return STATUS_NO_MEMORY;
1596 attr.Length = sizeof(attr);
1597 attr.RootDirectory = 0;
1598 attr.Attributes = OBJ_CASE_INSENSITIVE;
1599 attr.ObjectName = &nt_name;
1600 attr.SecurityDescriptor = NULL;
1601 attr.SecurityQualityOfService = NULL;
1602 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1603 goto found;
1606 /* not found */
1608 if (!contains_path( libname ))
1610 /* if libname doesn't contain a path at all, we simply return the name as is,
1611 * to be loaded as builtin */
1612 len = strlenW(libname) * sizeof(WCHAR);
1613 if (len >= *size) goto overflow;
1614 strcpyW( filename, libname );
1615 goto found;
1619 /* absolute path name, or relative path name but not found above */
1621 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1623 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1624 return STATUS_NO_MEMORY;
1626 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1627 if (len >= *size) goto overflow;
1628 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1629 if (!(*pwm = find_fullname_module( filename )) && handle)
1631 attr.Length = sizeof(attr);
1632 attr.RootDirectory = 0;
1633 attr.Attributes = OBJ_CASE_INSENSITIVE;
1634 attr.ObjectName = &nt_name;
1635 attr.SecurityDescriptor = NULL;
1636 attr.SecurityQualityOfService = NULL;
1637 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1639 found:
1640 RtlFreeUnicodeString( &nt_name );
1641 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1642 return STATUS_SUCCESS;
1644 overflow:
1645 RtlFreeUnicodeString( &nt_name );
1646 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1647 *size = len + sizeof(WCHAR);
1648 return STATUS_BUFFER_TOO_SMALL;
1652 /***********************************************************************
1653 * load_dll (internal)
1655 * Load a PE style module according to the load order.
1656 * The loader_section must be locked while calling this function.
1658 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1660 enum loadorder loadorder;
1661 WCHAR buffer[32];
1662 WCHAR *filename;
1663 ULONG size;
1664 WINE_MODREF *main_exe;
1665 HANDLE handle = 0;
1666 NTSTATUS nts;
1668 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1670 filename = buffer;
1671 size = sizeof(buffer);
1672 for (;;)
1674 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1675 if (nts == STATUS_SUCCESS) break;
1676 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1677 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1678 /* grow the buffer and retry */
1679 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1682 if (*pwm) /* found already loaded module */
1684 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1686 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1688 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1689 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1690 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1691 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1692 return STATUS_SUCCESS;
1695 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1696 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1698 switch(loadorder)
1700 case LO_INVALID:
1701 nts = STATUS_NO_MEMORY;
1702 break;
1703 case LO_DISABLED:
1704 nts = STATUS_DLL_NOT_FOUND;
1705 break;
1706 case LO_NATIVE:
1707 case LO_NATIVE_BUILTIN:
1708 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1709 else
1711 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1712 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1713 /* not in PE format, maybe it's a builtin */
1714 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1716 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1717 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1718 break;
1719 case LO_BUILTIN:
1720 case LO_BUILTIN_NATIVE:
1721 case LO_DEFAULT: /* default is builtin,native */
1722 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1723 if (!handle) break; /* nothing else we can try */
1724 /* file is not a builtin library, try without using the specified file */
1725 if (nts != STATUS_SUCCESS)
1726 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1727 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1728 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1730 /* stub-only dll, try native */
1731 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1732 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1733 nts = STATUS_DLL_NOT_FOUND;
1735 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1736 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1737 break;
1740 if (nts == STATUS_SUCCESS)
1742 /* Initialize DLL just loaded */
1743 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1744 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1745 (*pwm)->ldr.BaseAddress);
1746 if (handle) NtClose( handle );
1747 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1748 return nts;
1751 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1752 if (handle) NtClose( handle );
1753 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1754 return nts;
1757 /******************************************************************
1758 * LdrLoadDll (NTDLL.@)
1760 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1761 const UNICODE_STRING *libname, HMODULE* hModule)
1763 WINE_MODREF *wm;
1764 NTSTATUS nts;
1766 RtlEnterCriticalSection( &loader_section );
1768 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1769 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1771 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1773 nts = process_attach( wm, NULL );
1774 if (nts != STATUS_SUCCESS)
1776 LdrUnloadDll(wm->ldr.BaseAddress);
1777 wm = NULL;
1780 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1782 RtlLeaveCriticalSection( &loader_section );
1783 return nts;
1787 /******************************************************************
1788 * LdrGetDllHandle (NTDLL.@)
1790 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1792 NTSTATUS status;
1793 WCHAR buffer[128];
1794 WCHAR *filename;
1795 ULONG size;
1796 WINE_MODREF *wm;
1798 RtlEnterCriticalSection( &loader_section );
1800 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1802 filename = buffer;
1803 size = sizeof(buffer);
1804 for (;;)
1806 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1807 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1808 if (status != STATUS_BUFFER_TOO_SMALL) break;
1809 /* grow the buffer and retry */
1810 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1812 status = STATUS_NO_MEMORY;
1813 break;
1817 if (status == STATUS_SUCCESS)
1819 if (wm) *base = wm->ldr.BaseAddress;
1820 else status = STATUS_DLL_NOT_FOUND;
1823 RtlLeaveCriticalSection( &loader_section );
1824 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1825 return status;
1829 /******************************************************************
1830 * LdrAddRefDll (NTDLL.@)
1832 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1834 NTSTATUS ret = STATUS_SUCCESS;
1835 WINE_MODREF *wm;
1837 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
1839 RtlEnterCriticalSection( &loader_section );
1841 if ((wm = get_modref( module )))
1843 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
1844 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1846 else ret = STATUS_INVALID_PARAMETER;
1848 RtlLeaveCriticalSection( &loader_section );
1849 return ret;
1853 /******************************************************************
1854 * LdrQueryProcessModuleInformation
1857 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1858 ULONG buf_size, ULONG* req_size)
1860 SYSTEM_MODULE* sm = &smi->Modules[0];
1861 ULONG size = sizeof(ULONG);
1862 NTSTATUS nts = STATUS_SUCCESS;
1863 ANSI_STRING str;
1864 char* ptr;
1865 PLIST_ENTRY mark, entry;
1866 PLDR_MODULE mod;
1867 WORD id = 0;
1869 smi->ModulesCount = 0;
1871 RtlEnterCriticalSection( &loader_section );
1872 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1873 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1875 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1876 size += sizeof(*sm);
1877 if (size <= buf_size)
1879 sm->Reserved1 = 0; /* FIXME */
1880 sm->Reserved2 = 0; /* FIXME */
1881 sm->ImageBaseAddress = mod->BaseAddress;
1882 sm->ImageSize = mod->SizeOfImage;
1883 sm->Flags = mod->Flags;
1884 sm->Id = id++;
1885 sm->Rank = 0; /* FIXME */
1886 sm->Unknown = 0; /* FIXME */
1887 str.Length = 0;
1888 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1889 str.Buffer = (char*)sm->Name;
1890 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1891 ptr = strrchr(str.Buffer, '\\');
1892 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1894 smi->ModulesCount++;
1895 sm++;
1897 else nts = STATUS_INFO_LENGTH_MISMATCH;
1899 RtlLeaveCriticalSection( &loader_section );
1901 if (req_size) *req_size = size;
1903 return nts;
1907 /******************************************************************
1908 * RtlDllShutdownInProgress (NTDLL.@)
1910 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
1912 return process_detaching;
1916 /******************************************************************
1917 * LdrShutdownProcess (NTDLL.@)
1920 void WINAPI LdrShutdownProcess(void)
1922 TRACE("()\n");
1923 process_detach( TRUE, (LPVOID)1 );
1926 /******************************************************************
1927 * LdrShutdownThread (NTDLL.@)
1930 void WINAPI LdrShutdownThread(void)
1932 PLIST_ENTRY mark, entry;
1933 PLDR_MODULE mod;
1935 TRACE("()\n");
1937 /* don't do any detach calls if process is exiting */
1938 if (process_detaching) return;
1939 /* FIXME: there is still a race here */
1941 RtlEnterCriticalSection( &loader_section );
1943 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1944 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1946 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1947 InInitializationOrderModuleList);
1948 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1949 continue;
1950 if ( mod->Flags & LDR_NO_DLL_CALLS )
1951 continue;
1953 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1954 DLL_THREAD_DETACH, NULL );
1957 RtlLeaveCriticalSection( &loader_section );
1958 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
1962 /***********************************************************************
1963 * free_modref
1966 static void free_modref( WINE_MODREF *wm )
1968 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1969 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1970 if (wm->ldr.InInitializationOrderModuleList.Flink)
1971 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
1973 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
1974 if (!TRACE_ON(module))
1975 TRACE_(loaddll)("Unloaded module %s : %s\n",
1976 debugstr_w(wm->ldr.FullDllName.Buffer),
1977 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1979 SERVER_START_REQ( unload_dll )
1981 req->base = wm->ldr.BaseAddress;
1982 wine_server_call( req );
1984 SERVER_END_REQ;
1986 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
1987 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1988 if (cached_modref == wm) cached_modref = NULL;
1989 RtlFreeUnicodeString( &wm->ldr.FullDllName );
1990 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1991 RtlFreeHeap( GetProcessHeap(), 0, wm );
1994 /***********************************************************************
1995 * MODULE_FlushModrefs
1997 * Remove all unused modrefs and call the internal unloading routines
1998 * for the library type.
2000 * The loader_section must be locked while calling this function.
2002 static void MODULE_FlushModrefs(void)
2004 PLIST_ENTRY mark, entry, prev;
2005 PLDR_MODULE mod;
2006 WINE_MODREF*wm;
2008 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2009 for (entry = mark->Blink; entry != mark; entry = prev)
2011 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2012 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2013 prev = entry->Blink;
2014 if (!mod->LoadCount) free_modref( wm );
2017 /* check load order list too for modules that haven't been initialized yet */
2018 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2019 for (entry = mark->Blink; entry != mark; entry = prev)
2021 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2022 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2023 prev = entry->Blink;
2024 if (!mod->LoadCount) free_modref( wm );
2028 /***********************************************************************
2029 * MODULE_DecRefCount
2031 * The loader_section must be locked while calling this function.
2033 static void MODULE_DecRefCount( WINE_MODREF *wm )
2035 int i;
2037 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2038 return;
2040 if ( wm->ldr.LoadCount <= 0 )
2041 return;
2043 --wm->ldr.LoadCount;
2044 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2046 if ( wm->ldr.LoadCount == 0 )
2048 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2050 for ( i = 0; i < wm->nDeps; i++ )
2051 if ( wm->deps[i] )
2052 MODULE_DecRefCount( wm->deps[i] );
2054 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2058 /******************************************************************
2059 * LdrUnloadDll (NTDLL.@)
2063 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2065 NTSTATUS retv = STATUS_SUCCESS;
2067 TRACE("(%p)\n", hModule);
2069 RtlEnterCriticalSection( &loader_section );
2071 /* if we're stopping the whole process (and forcing the removal of all
2072 * DLLs) the library will be freed anyway
2074 if (!process_detaching)
2076 WINE_MODREF *wm;
2078 free_lib_count++;
2079 if ((wm = get_modref( hModule )) != NULL)
2081 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2083 /* Recursively decrement reference counts */
2084 MODULE_DecRefCount( wm );
2086 /* Call process detach notifications */
2087 if ( free_lib_count <= 1 )
2089 process_detach( FALSE, NULL );
2090 MODULE_FlushModrefs();
2093 TRACE("END\n");
2095 else
2096 retv = STATUS_DLL_NOT_FOUND;
2098 free_lib_count--;
2101 RtlLeaveCriticalSection( &loader_section );
2103 return retv;
2106 /***********************************************************************
2107 * RtlImageNtHeader (NTDLL.@)
2109 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2111 IMAGE_NT_HEADERS *ret;
2113 __TRY
2115 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2117 ret = NULL;
2118 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2120 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2121 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2124 __EXCEPT_PAGE_FAULT
2126 return NULL;
2128 __ENDTRY
2129 return ret;
2133 /******************************************************************
2134 * LdrInitializeThunk (NTDLL.@)
2137 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2139 NTSTATUS status;
2140 WINE_MODREF *wm;
2141 LPCWSTR load_path;
2142 PEB *peb = NtCurrentTeb()->Peb;
2143 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2145 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2147 /* allocate the modref for the main exe (if not already done) */
2148 wm = get_modref( peb->ImageBaseAddress );
2149 assert( wm );
2150 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2152 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2153 exit(1);
2155 wm->ldr.LoadCount = -1; /* can't unload main exe */
2157 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2158 version_init( wm->ldr.FullDllName.Buffer );
2160 /* the main exe needs to be the first in the load order list */
2161 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2162 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2164 status = server_init_process_done();
2165 if (status != STATUS_SUCCESS) goto error;
2167 RtlEnterCriticalSection( &loader_section );
2169 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2170 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2171 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2172 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2173 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2175 if (last_failed_modref)
2176 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2177 goto error;
2179 attach_implicitly_loaded_dlls( (LPVOID)1 );
2181 RtlLeaveCriticalSection( &loader_section );
2183 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2184 return;
2186 error:
2187 ERR( "Main exe initialization for %s failed, status %x\n",
2188 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2189 exit(1);
2193 /***********************************************************************
2194 * RtlImageDirectoryEntryToData (NTDLL.@)
2196 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2198 const IMAGE_NT_HEADERS *nt;
2199 DWORD addr;
2201 if ((ULONG_PTR)module & 1) /* mapped as data file */
2203 module = (HMODULE)((ULONG_PTR)module & ~1);
2204 image = FALSE;
2206 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2207 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2208 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2209 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2210 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2212 /* not mapped as image, need to find the section containing the virtual address */
2213 return RtlImageRvaToVa( nt, module, addr, NULL );
2217 /***********************************************************************
2218 * RtlImageRvaToSection (NTDLL.@)
2220 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2221 HMODULE module, DWORD rva )
2223 int i;
2224 const IMAGE_SECTION_HEADER *sec;
2226 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2227 nt->FileHeader.SizeOfOptionalHeader);
2228 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2230 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2231 return (PIMAGE_SECTION_HEADER)sec;
2233 return NULL;
2237 /***********************************************************************
2238 * RtlImageRvaToVa (NTDLL.@)
2240 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2241 DWORD rva, IMAGE_SECTION_HEADER **section )
2243 IMAGE_SECTION_HEADER *sec;
2245 if (section && *section) /* try this section first */
2247 sec = *section;
2248 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2249 goto found;
2251 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2252 found:
2253 if (section) *section = sec;
2254 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2258 /***********************************************************************
2259 * RtlPcToFileHeader (NTDLL.@)
2261 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2263 LDR_MODULE *module;
2264 PVOID ret = NULL;
2266 RtlEnterCriticalSection( &loader_section );
2267 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2268 RtlLeaveCriticalSection( &loader_section );
2269 *address = ret;
2270 return ret;
2274 /***********************************************************************
2275 * NtLoadDriver (NTDLL.@)
2276 * ZwLoadDriver (NTDLL.@)
2278 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2280 FIXME("(%p), stub!\n",DriverServiceName);
2281 return STATUS_NOT_IMPLEMENTED;
2285 /***********************************************************************
2286 * NtUnloadDriver (NTDLL.@)
2287 * ZwUnloadDriver (NTDLL.@)
2289 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2291 FIXME("(%p), stub!\n",DriverServiceName);
2292 return STATUS_NOT_IMPLEMENTED;
2296 /******************************************************************
2297 * DllMain (NTDLL.@)
2299 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2301 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2302 return TRUE;
2306 /******************************************************************
2307 * __wine_init_windows_dir (NTDLL.@)
2309 * Windows and system dir initialization once kernel32 has been loaded.
2311 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2313 PLIST_ENTRY mark, entry;
2314 LPWSTR buffer, p;
2316 RtlCreateUnicodeString( &windows_dir, windir );
2317 RtlCreateUnicodeString( &system_dir, sysdir );
2318 strcpyW( user_shared_data->NtSystemRoot, windir );
2320 /* prepend the system dir to the name of the already created modules */
2321 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2322 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2324 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2326 assert( mod->Flags & LDR_WINE_INTERNAL );
2328 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2329 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2330 if (!buffer) continue;
2331 strcpyW( buffer, system_dir.Buffer );
2332 p = buffer + strlenW( buffer );
2333 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2334 strcpyW( p, mod->FullDllName.Buffer );
2335 RtlInitUnicodeString( &mod->FullDllName, buffer );
2336 RtlInitUnicodeString( &mod->BaseDllName, p );
2341 /***********************************************************************
2342 * __wine_process_init
2344 void __wine_process_init(void)
2346 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2348 WINE_MODREF *wm;
2349 NTSTATUS status;
2350 ANSI_STRING func_name;
2351 void (* DECLSPEC_NORETURN init_func)(void);
2352 extern mode_t FILE_umask;
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 %x\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 %x\n", status );
2373 exit(1);
2375 init_func();