ntdll: Use activation contexts information to load dlls (based on a patch by Jacek...
[wine/multimedia.git] / dlls / ntdll / loader.c
blob5ed7df94abe7f16dc4eab9ad0db10f18473d637f
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 /* we don't want to include winuser.h */
52 #define RT_MANIFEST ((ULONG_PTR)24)
53 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
55 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
57 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
58 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
60 static const char * const reason_names[] =
62 "PROCESS_DETACH",
63 "PROCESS_ATTACH",
64 "THREAD_ATTACH",
65 "THREAD_DETACH",
66 NULL, NULL, NULL, NULL,
67 "WINE_PREATTACH"
70 static const WCHAR dllW[] = {'.','d','l','l',0};
72 /* internal representation of 32bit modules. per process. */
73 typedef struct _wine_modref
75 LDR_MODULE ldr;
76 int nDeps;
77 struct _wine_modref **deps;
78 } WINE_MODREF;
80 /* info about the current builtin dll load */
81 /* used to keep track of things across the register_dll constructor call */
82 struct builtin_load_info
84 const WCHAR *load_path;
85 const WCHAR *filename;
86 NTSTATUS status;
87 WINE_MODREF *wm;
90 static struct builtin_load_info default_load_info;
91 static struct builtin_load_info *builtin_load_info = &default_load_info;
93 static HANDLE main_exe_file;
94 static UINT tls_module_count; /* number of modules with TLS directory */
95 static UINT tls_total_size; /* total size of TLS storage */
96 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
98 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
99 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
101 static RTL_CRITICAL_SECTION loader_section;
102 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
104 0, 0, &loader_section,
105 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
106 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
108 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
110 static WINE_MODREF *cached_modref;
111 static WINE_MODREF *current_modref;
112 static WINE_MODREF *last_failed_modref;
114 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
115 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
116 DWORD exp_size, const char *name, int hint );
118 /* convert PE image VirtualAddress to Real Address */
119 static inline void *get_rva( HMODULE module, DWORD va )
121 return (void *)((char *)module + va);
124 /* check whether the file name contains a path */
125 static inline int contains_path( LPCWSTR name )
127 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
130 /* convert from straight ASCII to Unicode without depending on the current codepage */
131 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
133 while (len--) *dst++ = (unsigned char)*src++;
137 /*************************************************************************
138 * call_dll_entry_point
140 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
141 * their entry point, so we need a small asm wrapper.
143 #ifdef __i386__
144 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
145 __ASM_GLOBAL_FUNC(call_dll_entry_point,
146 "pushl %ebp\n\t"
147 "movl %esp,%ebp\n\t"
148 "pushl %ebx\n\t"
149 "subl $8,%esp\n\t"
150 "pushl 20(%ebp)\n\t"
151 "pushl 16(%ebp)\n\t"
152 "pushl 12(%ebp)\n\t"
153 "movl 8(%ebp),%eax\n\t"
154 "call *%eax\n\t"
155 "leal -4(%ebp),%esp\n\t"
156 "popl %ebx\n\t"
157 "popl %ebp\n\t"
158 "ret" )
159 #else /* __i386__ */
160 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
161 UINT reason, void *reserved )
163 return proc( module, reason, reserved );
165 #endif /* __i386__ */
168 #ifdef __i386__
169 /*************************************************************************
170 * stub_entry_point
172 * Entry point for stub functions.
174 static void stub_entry_point( const char *dll, const char *name, ... )
176 EXCEPTION_RECORD rec;
178 rec.ExceptionCode = EXCEPTION_WINE_STUB;
179 rec.ExceptionFlags = EH_NONCONTINUABLE;
180 rec.ExceptionRecord = NULL;
181 #ifdef __GNUC__
182 rec.ExceptionAddress = __builtin_return_address(0);
183 #else
184 rec.ExceptionAddress = *((void **)&dll - 1);
185 #endif
186 rec.NumberParameters = 2;
187 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
188 rec.ExceptionInformation[1] = (ULONG_PTR)name;
189 for (;;) RtlRaiseException( &rec );
193 #include "pshpack1.h"
194 struct stub
196 BYTE popl_eax; /* popl %eax */
197 BYTE pushl1; /* pushl $name */
198 const char *name;
199 BYTE pushl2; /* pushl $dll */
200 const char *dll;
201 BYTE pushl_eax; /* pushl %eax */
202 BYTE jmp; /* jmp stub_entry_point */
203 DWORD entry;
205 #include "poppack.h"
207 /*************************************************************************
208 * allocate_stub
210 * Allocate a stub entry point.
212 static ULONG_PTR allocate_stub( const char *dll, const char *name )
214 #define MAX_SIZE 65536
215 static struct stub *stubs;
216 static unsigned int nb_stubs;
217 struct stub *stub;
219 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
221 if (!stubs)
223 SIZE_T size = MAX_SIZE;
224 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
225 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
226 return 0xdeadbeef;
228 stub = &stubs[nb_stubs++];
229 stub->popl_eax = 0x58; /* popl %eax */
230 stub->pushl1 = 0x68; /* pushl $name */
231 stub->name = name;
232 stub->pushl2 = 0x68; /* pushl $dll */
233 stub->dll = dll;
234 stub->pushl_eax = 0x50; /* pushl %eax */
235 stub->jmp = 0xe9; /* jmp stub_entry_point */
236 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
237 return (ULONG_PTR)stub;
240 #else /* __i386__ */
241 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
242 #endif /* __i386__ */
245 /*************************************************************************
246 * get_modref
248 * Looks for the referenced HMODULE in the current process
249 * The loader_section must be locked while calling this function.
251 static WINE_MODREF *get_modref( HMODULE hmod )
253 PLIST_ENTRY mark, entry;
254 PLDR_MODULE mod;
256 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
258 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
259 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
261 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
262 if (mod->BaseAddress == hmod)
263 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
264 if (mod->BaseAddress > (void*)hmod) break;
266 return NULL;
270 /**********************************************************************
271 * find_basename_module
273 * Find a module from its base name.
274 * The loader_section must be locked while calling this function
276 static WINE_MODREF *find_basename_module( LPCWSTR name )
278 PLIST_ENTRY mark, entry;
280 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
281 return cached_modref;
283 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
284 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
286 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
287 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
289 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
290 return cached_modref;
293 return NULL;
297 /**********************************************************************
298 * find_fullname_module
300 * Find a module from its full path name.
301 * The loader_section must be locked while calling this function
303 static WINE_MODREF *find_fullname_module( LPCWSTR name )
305 PLIST_ENTRY mark, entry;
307 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
308 return cached_modref;
310 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
311 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
313 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
314 if (!strcmpiW( name, mod->FullDllName.Buffer ))
316 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
317 return cached_modref;
320 return NULL;
324 /*************************************************************************
325 * find_forwarded_export
327 * Find the final function pointer for a forwarded function.
328 * The loader_section must be locked while calling this function.
330 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
332 const IMAGE_EXPORT_DIRECTORY *exports;
333 DWORD exp_size;
334 WINE_MODREF *wm;
335 WCHAR mod_name[32];
336 const char *end = strrchr(forward, '.');
337 FARPROC proc = NULL;
339 if (!end) return NULL;
340 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
341 ascii_to_unicode( mod_name, forward, end - forward );
342 mod_name[end - forward] = 0;
343 if (!strchrW( mod_name, '.' ))
345 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
346 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
349 if (!(wm = find_basename_module( mod_name )))
351 ERR("module not found for forward '%s' used by %s\n",
352 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
353 return NULL;
355 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
356 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
357 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
359 if (!proc)
361 ERR("function not found for forward '%s' used by %s."
362 " If you are using builtin %s, try using the native one instead.\n",
363 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
364 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
366 return proc;
370 /*************************************************************************
371 * find_ordinal_export
373 * Find an exported function by ordinal.
374 * The exports base must have been subtracted from the ordinal already.
375 * The loader_section must be locked while calling this function.
377 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
378 DWORD exp_size, DWORD ordinal )
380 FARPROC proc;
381 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
383 if (ordinal >= exports->NumberOfFunctions)
385 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
386 return NULL;
388 if (!functions[ordinal]) return NULL;
390 proc = get_rva( module, functions[ordinal] );
392 /* if the address falls into the export dir, it's a forward */
393 if (((const char *)proc >= (const char *)exports) &&
394 ((const char *)proc < (const char *)exports + exp_size))
395 return find_forwarded_export( module, (const char *)proc );
397 if (TRACE_ON(snoop))
399 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
400 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
402 if (TRACE_ON(relay))
404 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
405 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
407 return proc;
411 /*************************************************************************
412 * find_named_export
414 * Find an exported function by name.
415 * The loader_section must be locked while calling this function.
417 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
418 DWORD exp_size, const char *name, int hint )
420 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
421 const DWORD *names = get_rva( module, exports->AddressOfNames );
422 int min = 0, max = exports->NumberOfNames - 1;
424 /* first check the hint */
425 if (hint >= 0 && hint <= max)
427 char *ename = get_rva( module, names[hint] );
428 if (!strcmp( ename, name ))
429 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
432 /* then do a binary search */
433 while (min <= max)
435 int res, pos = (min + max) / 2;
436 char *ename = get_rva( module, names[pos] );
437 if (!(res = strcmp( ename, name )))
438 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
439 if (res > 0) max = pos - 1;
440 else min = pos + 1;
442 return NULL;
447 /*************************************************************************
448 * import_dll
450 * Import the dll specified by the given import descriptor.
451 * The loader_section must be locked while calling this function.
453 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
455 NTSTATUS status;
456 WINE_MODREF *wmImp;
457 HMODULE imp_mod;
458 const IMAGE_EXPORT_DIRECTORY *exports;
459 DWORD exp_size;
460 const IMAGE_THUNK_DATA *import_list;
461 IMAGE_THUNK_DATA *thunk_list;
462 WCHAR buffer[32];
463 const char *name = get_rva( module, descr->Name );
464 DWORD len = strlen(name);
465 PVOID protect_base;
466 SIZE_T protect_size = 0;
467 DWORD protect_old;
469 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
470 if (descr->u.OriginalFirstThunk)
471 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
472 else
473 import_list = thunk_list;
475 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
477 if (len * sizeof(WCHAR) < sizeof(buffer))
479 ascii_to_unicode( buffer, name, len );
480 buffer[len] = 0;
481 status = load_dll( load_path, buffer, 0, &wmImp );
483 else /* need to allocate a larger buffer */
485 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
486 if (!ptr) return NULL;
487 ascii_to_unicode( ptr, name, len );
488 ptr[len] = 0;
489 status = load_dll( load_path, ptr, 0, &wmImp );
490 RtlFreeHeap( GetProcessHeap(), 0, ptr );
493 if (status)
495 if (status == STATUS_DLL_NOT_FOUND)
496 ERR("Library %s (which is needed by %s) not found\n",
497 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
498 else
499 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
500 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
501 return NULL;
504 /* unprotect the import address table since it can be located in
505 * readonly section */
506 while (import_list[protect_size].u1.Ordinal) protect_size++;
507 protect_base = thunk_list;
508 protect_size *= sizeof(*thunk_list);
509 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
510 &protect_size, PAGE_WRITECOPY, &protect_old );
512 imp_mod = wmImp->ldr.BaseAddress;
513 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
515 if (!exports)
517 /* set all imported function to deadbeef */
518 while (import_list->u1.Ordinal)
520 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
522 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
523 WARN("No implementation for %s.%d", name, ordinal );
524 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
526 else
528 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
529 WARN("No implementation for %s.%s", name, pe_name->Name );
530 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
532 WARN(" imported from %s, allocating stub %p\n",
533 debugstr_w(current_modref->ldr.FullDllName.Buffer),
534 (void *)thunk_list->u1.Function );
535 import_list++;
536 thunk_list++;
538 goto done;
541 while (import_list->u1.Ordinal)
543 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
545 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
547 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
548 ordinal - exports->Base );
549 if (!thunk_list->u1.Function)
551 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
552 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
553 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
554 (void *)thunk_list->u1.Function );
556 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
558 else /* import by name */
560 IMAGE_IMPORT_BY_NAME *pe_name;
561 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
562 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
563 (const char*)pe_name->Name, pe_name->Hint );
564 if (!thunk_list->u1.Function)
566 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
567 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
568 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
569 (void *)thunk_list->u1.Function );
571 TRACE_(imports)("--- %s %s.%d = %p\n",
572 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
574 import_list++;
575 thunk_list++;
578 done:
579 /* restore old protection of the import address table */
580 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
581 return wmImp;
585 /***********************************************************************
586 * create_module_activation_context
588 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
590 NTSTATUS status;
591 LDR_RESOURCE_INFO info;
592 const IMAGE_RESOURCE_DATA_ENTRY *entry;
594 info.Type = RT_MANIFEST;
595 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
596 info.Language = 0;
597 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
599 ACTCTXW ctx;
600 ctx.cbSize = sizeof(ctx);
601 ctx.lpSource = NULL;
602 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
603 ctx.hModule = module->BaseAddress;
604 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
605 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
607 return status;
611 /****************************************************************
612 * fixup_imports
614 * Fixup all imports of a given module.
615 * The loader_section must be locked while calling this function.
617 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
619 int i, nb_imports;
620 const IMAGE_IMPORT_DESCRIPTOR *imports;
621 WINE_MODREF *prev;
622 DWORD size;
623 NTSTATUS status;
625 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
626 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
627 create_module_activation_context( &wm->ldr );
629 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
630 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
631 return STATUS_SUCCESS;
633 nb_imports = 0;
634 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
636 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
638 /* Allocate module dependency list */
639 wm->nDeps = nb_imports;
640 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
642 /* load the imported modules. They are automatically
643 * added to the modref list of the process.
645 prev = current_modref;
646 current_modref = wm;
647 status = STATUS_SUCCESS;
648 for (i = 0; i < nb_imports; i++)
650 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
651 status = STATUS_DLL_NOT_FOUND;
653 current_modref = prev;
654 return status;
658 /*************************************************************************
659 * alloc_module
661 * Allocate a WINE_MODREF structure and add it to the process list
662 * The loader_section must be locked while calling this function.
664 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
666 WINE_MODREF *wm;
667 const WCHAR *p;
668 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
669 PLIST_ENTRY entry, mark;
671 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
673 wm->nDeps = 0;
674 wm->deps = NULL;
676 wm->ldr.BaseAddress = hModule;
677 wm->ldr.EntryPoint = NULL;
678 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
679 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
680 wm->ldr.LoadCount = 1;
681 wm->ldr.TlsIndex = -1;
682 wm->ldr.SectionHandle = NULL;
683 wm->ldr.CheckSum = 0;
684 wm->ldr.TimeDateStamp = 0;
685 wm->ldr.ActivationContext = 0;
687 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
688 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
689 else p = wm->ldr.FullDllName.Buffer;
690 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
692 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
694 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
695 if (nt->OptionalHeader.AddressOfEntryPoint)
696 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
699 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
700 &wm->ldr.InLoadOrderModuleList);
702 /* insert module in MemoryList, sorted in increasing base addresses */
703 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
704 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
706 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
707 break;
709 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
710 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
711 wm->ldr.InMemoryOrderModuleList.Flink = entry;
712 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
714 /* wait until init is called for inserting into this list */
715 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
716 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
718 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
720 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
721 VIRTUAL_SetForceExec( TRUE );
723 return wm;
727 /*************************************************************************
728 * alloc_process_tls
730 * Allocate the process-wide structure for module TLS storage.
732 static NTSTATUS alloc_process_tls(void)
734 PLIST_ENTRY mark, entry;
735 PLDR_MODULE mod;
736 const IMAGE_TLS_DIRECTORY *dir;
737 ULONG size, i;
739 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
740 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
742 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
743 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
744 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
745 continue;
746 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
747 if (!size) continue;
748 tls_total_size += size;
749 tls_module_count++;
751 if (!tls_module_count) return STATUS_SUCCESS;
753 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
755 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
756 if (!tls_dirs) return STATUS_NO_MEMORY;
758 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
760 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
761 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
762 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
763 continue;
764 tls_dirs[i] = dir;
765 *(DWORD *)dir->AddressOfIndex = i;
766 mod->TlsIndex = i;
767 mod->LoadCount = -1; /* can't unload it */
768 i++;
770 return STATUS_SUCCESS;
774 /*************************************************************************
775 * alloc_thread_tls
777 * Allocate the per-thread structure for module TLS storage.
779 static NTSTATUS alloc_thread_tls(void)
781 void **pointers;
782 char *data;
783 UINT i;
785 if (!tls_module_count) return STATUS_SUCCESS;
787 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
788 tls_module_count * sizeof(*pointers) )))
789 return STATUS_NO_MEMORY;
791 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
793 RtlFreeHeap( GetProcessHeap(), 0, pointers );
794 return STATUS_NO_MEMORY;
797 for (i = 0; i < tls_module_count; i++)
799 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
800 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
802 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
803 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
804 (void *)dir->StartAddressOfRawData, data );
806 pointers[i] = data;
807 memcpy( data, (void *)dir->StartAddressOfRawData, size );
808 data += size;
809 memset( data, 0, dir->SizeOfZeroFill );
810 data += dir->SizeOfZeroFill;
812 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
813 return STATUS_SUCCESS;
817 /*************************************************************************
818 * call_tls_callbacks
820 static void call_tls_callbacks( HMODULE module, UINT reason )
822 const IMAGE_TLS_DIRECTORY *dir;
823 const PIMAGE_TLS_CALLBACK *callback;
824 ULONG dirsize;
826 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
827 if (!dir || !dir->AddressOfCallBacks) return;
829 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
831 if (TRACE_ON(relay))
832 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
833 GetCurrentThreadId(), *callback, module, reason_names[reason] );
834 __TRY
836 (*callback)( module, reason, NULL );
838 __EXCEPT(NULL)
840 if (TRACE_ON(relay))
841 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
842 GetCurrentThreadId(), callback, module, reason_names[reason] );
843 return;
845 __ENDTRY
846 if (TRACE_ON(relay))
847 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
848 GetCurrentThreadId(), *callback, module, reason_names[reason] );
853 /*************************************************************************
854 * MODULE_InitDLL
856 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
858 WCHAR mod_name[32];
859 BOOL retv = TRUE;
860 DLLENTRYPROC entry = wm->ldr.EntryPoint;
861 void *module = wm->ldr.BaseAddress;
863 /* Skip calls for modules loaded with special load flags */
865 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
866 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
867 if (!entry) return TRUE;
869 if (TRACE_ON(relay))
871 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
872 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
873 mod_name[len / sizeof(WCHAR)] = 0;
874 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
875 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
876 reason_names[reason], lpReserved );
878 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
879 reason_names[reason], lpReserved );
881 retv = call_dll_entry_point( entry, module, reason, lpReserved );
883 /* The state of the module list may have changed due to the call
884 to the dll. We cannot assume that this module has not been
885 deleted. */
886 if (TRACE_ON(relay))
887 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
888 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
889 reason_names[reason], lpReserved, retv );
890 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
892 return retv;
896 /*************************************************************************
897 * process_attach
899 * Send the process attach notification to all DLLs the given module
900 * depends on (recursively). This is somewhat complicated due to the fact that
902 * - we have to respect the module dependencies, i.e. modules implicitly
903 * referenced by another module have to be initialized before the module
904 * itself can be initialized
906 * - the initialization routine of a DLL can itself call LoadLibrary,
907 * thereby introducing a whole new set of dependencies (even involving
908 * the 'old' modules) at any time during the whole process
910 * (Note that this routine can be recursively entered not only directly
911 * from itself, but also via LoadLibrary from one of the called initialization
912 * routines.)
914 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
915 * the process *detach* notifications to be sent in the correct order.
916 * This must not only take into account module dependencies, but also
917 * 'hidden' dependencies created by modules calling LoadLibrary in their
918 * attach notification routine.
920 * The strategy is rather simple: we move a WINE_MODREF to the head of the
921 * list after the attach notification has returned. This implies that the
922 * detach notifications are called in the reverse of the sequence the attach
923 * notifications *returned*.
925 * The loader_section must be locked while calling this function.
927 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
929 NTSTATUS status = STATUS_SUCCESS;
930 int i;
932 if (process_detaching) return status;
934 /* prevent infinite recursion in case of cyclical dependencies */
935 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
936 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
937 return status;
939 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
941 /* Tag current MODREF to prevent recursive loop */
942 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
944 /* Recursively attach all DLLs this one depends on */
945 for ( i = 0; i < wm->nDeps; i++ )
947 if (!wm->deps[i]) continue;
948 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
951 /* Call DLL entry point */
952 if (status == STATUS_SUCCESS)
954 WINE_MODREF *prev = current_modref;
955 current_modref = wm;
956 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
958 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
960 else
962 /* point to the name so LdrInitializeThunk can print it */
963 last_failed_modref = wm;
964 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
965 status = STATUS_DLL_INIT_FAILED;
967 current_modref = prev;
970 if (!wm->ldr.InInitializationOrderModuleList.Flink)
971 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
972 &wm->ldr.InInitializationOrderModuleList);
974 /* Remove recursion flag */
975 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
977 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
978 return status;
982 /**********************************************************************
983 * attach_implicitly_loaded_dlls
985 * Attach to the (builtin) dlls that have been implicitly loaded because
986 * of a dependency at the Unix level, but not imported at the Win32 level.
988 static void attach_implicitly_loaded_dlls( LPVOID reserved )
990 for (;;)
992 PLIST_ENTRY mark, entry;
994 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
995 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
997 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
999 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1000 TRACE( "found implicitly loaded %s, attaching to it\n",
1001 debugstr_w(mod->BaseDllName.Buffer));
1002 mod->LoadCount = -1; /* we can't unload it anyway */
1003 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1004 break; /* restart the search from the start */
1006 if (entry == mark) break; /* nothing found */
1011 /*************************************************************************
1012 * process_detach
1014 * Send DLL process detach notifications. See the comment about calling
1015 * sequence at process_attach. Unless the bForceDetach flag
1016 * is set, only DLLs with zero refcount are notified.
1018 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1020 PLIST_ENTRY mark, entry;
1021 PLDR_MODULE mod;
1023 RtlEnterCriticalSection( &loader_section );
1024 if (bForceDetach) process_detaching = 1;
1025 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1028 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1030 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1031 InInitializationOrderModuleList);
1032 /* Check whether to detach this DLL */
1033 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1034 continue;
1035 if ( mod->LoadCount && !bForceDetach )
1036 continue;
1038 /* Call detach notification */
1039 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1040 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1041 DLL_PROCESS_DETACH, lpReserved );
1043 /* Restart at head of WINE_MODREF list, as entries might have
1044 been added and/or removed while performing the call ... */
1045 break;
1047 } while (entry != mark);
1049 RtlLeaveCriticalSection( &loader_section );
1052 /*************************************************************************
1053 * MODULE_DllThreadAttach
1055 * Send DLL thread attach notifications. These are sent in the
1056 * reverse sequence of process detach notification.
1059 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1061 PLIST_ENTRY mark, entry;
1062 PLDR_MODULE mod;
1063 NTSTATUS status;
1065 /* don't do any attach calls if process is exiting */
1066 if (process_detaching) return STATUS_SUCCESS;
1067 /* FIXME: there is still a race here */
1069 RtlEnterCriticalSection( &loader_section );
1071 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1073 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1074 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1076 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1077 InInitializationOrderModuleList);
1078 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1079 continue;
1080 if ( mod->Flags & LDR_NO_DLL_CALLS )
1081 continue;
1083 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1084 DLL_THREAD_ATTACH, lpReserved );
1087 done:
1088 RtlLeaveCriticalSection( &loader_section );
1089 return status;
1092 /******************************************************************
1093 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1096 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1098 WINE_MODREF *wm;
1099 NTSTATUS ret = STATUS_SUCCESS;
1101 RtlEnterCriticalSection( &loader_section );
1103 wm = get_modref( hModule );
1104 if (!wm || wm->ldr.TlsIndex != -1)
1105 ret = STATUS_DLL_NOT_FOUND;
1106 else
1107 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1109 RtlLeaveCriticalSection( &loader_section );
1111 return ret;
1114 /******************************************************************
1115 * LdrFindEntryForAddress (NTDLL.@)
1117 * The loader_section must be locked while calling this function
1119 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1121 PLIST_ENTRY mark, entry;
1122 PLDR_MODULE mod;
1124 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1125 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1127 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1128 if ((const void *)mod->BaseAddress <= addr &&
1129 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1131 *pmod = mod;
1132 return STATUS_SUCCESS;
1134 if ((const void *)mod->BaseAddress > addr) break;
1136 return STATUS_NO_MORE_ENTRIES;
1139 /******************************************************************
1140 * LdrLockLoaderLock (NTDLL.@)
1142 * Note: flags are not implemented.
1143 * Flag 0x01 is used to raise exceptions on errors.
1144 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1146 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1148 if (flags) FIXME( "flags %x not supported\n", flags );
1150 if (result) *result = 1;
1151 if (!magic) return STATUS_INVALID_PARAMETER_3;
1152 RtlEnterCriticalSection( &loader_section );
1153 *magic = GetCurrentThreadId();
1154 return STATUS_SUCCESS;
1158 /******************************************************************
1159 * LdrUnlockLoaderUnlock (NTDLL.@)
1161 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1163 if (magic)
1165 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1166 RtlLeaveCriticalSection( &loader_section );
1168 return STATUS_SUCCESS;
1172 /******************************************************************
1173 * LdrGetProcedureAddress (NTDLL.@)
1175 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1176 ULONG ord, PVOID *address)
1178 IMAGE_EXPORT_DIRECTORY *exports;
1179 DWORD exp_size;
1180 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1182 RtlEnterCriticalSection( &loader_section );
1184 /* check if the module itself is invalid to return the proper error */
1185 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1186 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1187 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1189 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1190 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1191 if (proc)
1193 *address = proc;
1194 ret = STATUS_SUCCESS;
1198 RtlLeaveCriticalSection( &loader_section );
1199 return ret;
1203 /***********************************************************************
1204 * is_fake_dll
1206 * Check if a loaded native dll is a Wine fake dll.
1208 static BOOL is_fake_dll( const void *base )
1210 static const char fakedll_signature[] = "Wine placeholder DLL";
1211 const IMAGE_DOS_HEADER *dos = base;
1213 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1214 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1215 return FALSE;
1219 /***********************************************************************
1220 * get_builtin_fullname
1222 * Build the full pathname for a builtin dll.
1224 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1226 static const WCHAR soW[] = {'.','s','o',0};
1227 WCHAR *p, *fullname;
1228 size_t i, len = strlen(filename);
1230 /* check if path can correspond to the dll we have */
1231 if (path && (p = strrchrW( path, '\\' )))
1233 p++;
1234 for (i = 0; i < len; i++)
1235 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1236 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1238 /* the filename matches, use path as the full path */
1239 len += p - path;
1240 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1242 memcpy( fullname, path, len * sizeof(WCHAR) );
1243 fullname[len] = 0;
1245 return fullname;
1249 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1250 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1252 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1253 p = fullname + system_dir.Length / sizeof(WCHAR);
1254 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1255 ascii_to_unicode( p, filename, len + 1 );
1257 return fullname;
1261 /***********************************************************************
1262 * load_builtin_callback
1264 * Load a library in memory; callback function for wine_dll_register
1266 static void load_builtin_callback( void *module, const char *filename )
1268 static const WCHAR emptyW[1];
1269 void *addr;
1270 IMAGE_NT_HEADERS *nt;
1271 WINE_MODREF *wm;
1272 WCHAR *fullname;
1273 const WCHAR *load_path;
1274 SIZE_T size;
1276 if (!module)
1278 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1279 return;
1281 if (!(nt = RtlImageNtHeader( module )))
1283 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1284 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1285 return;
1287 addr = module;
1288 size = nt->OptionalHeader.SizeOfImage;
1289 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1290 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1291 /* create the MODREF */
1293 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1295 ERR( "can't load %s\n", filename );
1296 builtin_load_info->status = STATUS_NO_MEMORY;
1297 return;
1300 wm = alloc_module( module, fullname );
1301 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1302 if (!wm)
1304 ERR( "can't load %s\n", filename );
1305 builtin_load_info->status = STATUS_NO_MEMORY;
1306 return;
1308 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1310 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1311 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1313 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1315 else
1317 /* fixup imports */
1319 load_path = builtin_load_info->load_path;
1320 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1321 if (!load_path) load_path = emptyW;
1322 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1324 /* the module has only be inserted in the load & memory order lists */
1325 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1326 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1327 /* FIXME: free the modref */
1328 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1329 return;
1333 builtin_load_info->wm = wm;
1334 TRACE( "loaded %s %p %p\n", filename, wm, module );
1336 /* send the DLL load event */
1338 SERVER_START_REQ( load_dll )
1340 req->handle = 0;
1341 req->base = module;
1342 req->size = nt->OptionalHeader.SizeOfImage;
1343 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1344 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1345 req->name = &wm->ldr.FullDllName.Buffer;
1346 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1347 wine_server_call( req );
1349 SERVER_END_REQ;
1351 /* setup relay debugging entry points */
1352 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1356 /******************************************************************************
1357 * load_native_dll (internal)
1359 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1360 DWORD flags, WINE_MODREF** pwm )
1362 void *module;
1363 HANDLE mapping;
1364 OBJECT_ATTRIBUTES attr;
1365 LARGE_INTEGER size;
1366 IMAGE_NT_HEADERS *nt;
1367 SIZE_T len = 0;
1368 WINE_MODREF *wm;
1369 NTSTATUS status;
1371 TRACE("Trying native dll %s\n", debugstr_w(name));
1373 attr.Length = sizeof(attr);
1374 attr.RootDirectory = 0;
1375 attr.ObjectName = NULL;
1376 attr.Attributes = 0;
1377 attr.SecurityDescriptor = NULL;
1378 attr.SecurityQualityOfService = NULL;
1379 size.QuadPart = 0;
1381 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1382 &attr, &size, 0, SEC_IMAGE, file );
1383 if (status != STATUS_SUCCESS) return status;
1385 module = NULL;
1386 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1387 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1388 NtClose( mapping );
1389 if (status != STATUS_SUCCESS) return status;
1391 if (is_fake_dll( module ))
1393 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1394 NtUnmapViewOfSection( NtCurrentProcess(), module );
1395 return STATUS_DLL_NOT_FOUND;
1398 /* create the MODREF */
1400 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1402 /* fixup imports */
1404 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1406 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1408 /* the module has only be inserted in the load & memory order lists */
1409 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1410 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1412 /* FIXME: there are several more dangling references
1413 * left. Including dlls loaded by this dll before the
1414 * failed one. Unrolling is rather difficult with the
1415 * current structure and we can leave them lying
1416 * around with no problems, so we don't care.
1417 * As these might reference our wm, we don't free it.
1419 return status;
1423 /* send DLL load event */
1425 nt = RtlImageNtHeader( module );
1427 SERVER_START_REQ( load_dll )
1429 req->handle = file;
1430 req->base = module;
1431 req->size = nt->OptionalHeader.SizeOfImage;
1432 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1433 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1434 req->name = &wm->ldr.FullDllName.Buffer;
1435 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1436 wine_server_call( req );
1438 SERVER_END_REQ;
1440 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1442 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1444 wm->ldr.LoadCount = 1;
1445 *pwm = wm;
1446 return STATUS_SUCCESS;
1450 /***********************************************************************
1451 * load_builtin_dll
1453 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1454 DWORD flags, WINE_MODREF** pwm )
1456 char error[256], dllname[MAX_PATH];
1457 const WCHAR *name, *p;
1458 DWORD len, i;
1459 void *handle = NULL;
1460 struct builtin_load_info info, *prev_info;
1462 /* Fix the name in case we have a full path and extension */
1463 name = path;
1464 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1465 if ((p = strrchrW( name, '/' ))) name = p + 1;
1467 /* load_library will modify info.status. Note also that load_library can be
1468 * called several times, if the .so file we're loading has dependencies.
1469 * info.status will gather all the errors we may get while loading all these
1470 * libraries
1472 info.load_path = load_path;
1473 info.filename = NULL;
1474 info.status = STATUS_SUCCESS;
1475 info.wm = NULL;
1477 if (file) /* we have a real file, try to load it */
1479 UNICODE_STRING nt_name;
1480 ANSI_STRING unix_name;
1482 TRACE("Trying built-in %s\n", debugstr_w(path));
1484 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1485 return STATUS_DLL_NOT_FOUND;
1487 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1489 RtlFreeUnicodeString( &nt_name );
1490 return STATUS_DLL_NOT_FOUND;
1492 prev_info = builtin_load_info;
1493 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1494 builtin_load_info = &info;
1495 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1496 builtin_load_info = prev_info;
1497 RtlFreeUnicodeString( &nt_name );
1498 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1499 if (!handle)
1501 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1502 return STATUS_INVALID_IMAGE_FORMAT;
1505 else
1507 int file_exists;
1509 TRACE("Trying built-in %s\n", debugstr_w(name));
1511 /* we don't want to depend on the current codepage here */
1512 len = strlenW( name ) + 1;
1513 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1514 for (i = 0; i < len; i++)
1516 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1517 dllname[i] = (char)name[i];
1518 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1521 prev_info = builtin_load_info;
1522 builtin_load_info = &info;
1523 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1524 builtin_load_info = prev_info;
1525 if (!handle)
1527 if (!file_exists)
1529 /* The file does not exist -> WARN() */
1530 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1531 return STATUS_DLL_NOT_FOUND;
1533 /* ERR() for all other errors (missing functions, ...) */
1534 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1535 return STATUS_PROCEDURE_NOT_FOUND;
1539 if (info.status != STATUS_SUCCESS)
1541 wine_dll_unload( handle );
1542 return info.status;
1545 if (!info.wm)
1547 PLIST_ENTRY mark, entry;
1549 /* The constructor wasn't called, this means the .so is already
1550 * loaded under a different name. Try to find the wm for it. */
1552 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1553 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1555 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1556 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1558 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1559 TRACE( "Found already loaded module %s for builtin %s\n",
1560 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1561 break;
1564 wine_dll_unload( handle ); /* release the libdl refcount */
1565 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1566 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1568 else
1570 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1571 info.wm->ldr.LoadCount = 1;
1572 info.wm->ldr.SectionHandle = handle;
1575 *pwm = info.wm;
1576 return STATUS_SUCCESS;
1580 /***********************************************************************
1581 * find_actctx_dll
1583 * Find the full path (if any) of the dll from the activation context.
1585 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1587 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1589 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1590 ACTCTX_SECTION_KEYED_DATA data;
1591 UNICODE_STRING nameW;
1592 NTSTATUS status;
1593 SIZE_T needed, size = 1024;
1594 WCHAR *p;
1596 RtlInitUnicodeString( &nameW, libname );
1597 data.cbSize = sizeof(data);
1598 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1599 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1600 &nameW, &data );
1601 if (status != STATUS_SUCCESS) return status;
1603 for (;;)
1605 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1607 status = STATUS_NO_MEMORY;
1608 goto done;
1610 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1611 AssemblyDetailedInformationInActivationContext,
1612 info, size, &needed );
1613 if (status == STATUS_SUCCESS) break;
1614 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1615 RtlFreeHeap( GetProcessHeap(), 0, info );
1616 size = needed;
1617 /* restart with larger buffer */
1620 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1621 nameW.Length + 2*sizeof(WCHAR));
1623 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1625 status = STATUS_NO_MEMORY;
1626 goto done;
1628 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1629 p += windows_dir.Length / sizeof(WCHAR);
1630 memcpy( p, winsxsW, sizeof(winsxsW) );
1631 p += sizeof(winsxsW) / sizeof(WCHAR);
1632 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1633 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1634 *p++ = '\\';
1635 strcpyW( p, libname );
1636 TRACE ("found %s for %s\n", debugstr_w(*fullname), debugstr_w(libname) );
1637 done:
1638 RtlFreeHeap( GetProcessHeap(), 0, info );
1639 RtlReleaseActivationContext( data.hActCtx );
1640 return status;
1644 /***********************************************************************
1645 * find_dll_file
1647 * Find the file (or already loaded module) for a given dll name.
1649 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1650 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1652 OBJECT_ATTRIBUTES attr;
1653 IO_STATUS_BLOCK io;
1654 UNICODE_STRING nt_name;
1655 WCHAR *file_part, *ext, *dllname;
1656 ULONG len;
1658 /* first append .dll if needed */
1660 dllname = NULL;
1661 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1663 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1664 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1665 return STATUS_NO_MEMORY;
1666 strcpyW( dllname, libname );
1667 strcatW( dllname, dllW );
1668 libname = dllname;
1671 nt_name.Buffer = NULL;
1673 if (!contains_path( libname ))
1675 NTSTATUS status;
1676 WCHAR *fullname;
1678 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1680 status = find_actctx_dll( libname, &fullname );
1681 if (status == STATUS_SUCCESS)
1683 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1684 libname = dllname = fullname;
1686 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1688 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1689 return status;
1693 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1695 /* we need to search for it */
1696 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1697 if (len)
1699 if (len >= *size) goto overflow;
1700 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1702 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1704 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1705 return STATUS_NO_MEMORY;
1707 attr.Length = sizeof(attr);
1708 attr.RootDirectory = 0;
1709 attr.Attributes = OBJ_CASE_INSENSITIVE;
1710 attr.ObjectName = &nt_name;
1711 attr.SecurityDescriptor = NULL;
1712 attr.SecurityQualityOfService = NULL;
1713 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1714 goto found;
1717 /* not found */
1719 if (!contains_path( libname ))
1721 /* if libname doesn't contain a path at all, we simply return the name as is,
1722 * to be loaded as builtin */
1723 len = strlenW(libname) * sizeof(WCHAR);
1724 if (len >= *size) goto overflow;
1725 strcpyW( filename, libname );
1726 goto found;
1730 /* absolute path name, or relative path name but not found above */
1732 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1734 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1735 return STATUS_NO_MEMORY;
1737 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1738 if (len >= *size) goto overflow;
1739 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1740 if (!(*pwm = find_fullname_module( filename )) && handle)
1742 attr.Length = sizeof(attr);
1743 attr.RootDirectory = 0;
1744 attr.Attributes = OBJ_CASE_INSENSITIVE;
1745 attr.ObjectName = &nt_name;
1746 attr.SecurityDescriptor = NULL;
1747 attr.SecurityQualityOfService = NULL;
1748 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1750 found:
1751 RtlFreeUnicodeString( &nt_name );
1752 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1753 return STATUS_SUCCESS;
1755 overflow:
1756 RtlFreeUnicodeString( &nt_name );
1757 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1758 *size = len + sizeof(WCHAR);
1759 return STATUS_BUFFER_TOO_SMALL;
1763 /***********************************************************************
1764 * load_dll (internal)
1766 * Load a PE style module according to the load order.
1767 * The loader_section must be locked while calling this function.
1769 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1771 enum loadorder loadorder;
1772 WCHAR buffer[32];
1773 WCHAR *filename;
1774 ULONG size;
1775 WINE_MODREF *main_exe;
1776 HANDLE handle = 0;
1777 NTSTATUS nts;
1779 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1781 filename = buffer;
1782 size = sizeof(buffer);
1783 for (;;)
1785 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1786 if (nts == STATUS_SUCCESS) break;
1787 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1788 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1789 /* grow the buffer and retry */
1790 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1793 if (*pwm) /* found already loaded module */
1795 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1797 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1799 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1800 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1801 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1802 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1803 return STATUS_SUCCESS;
1806 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1807 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1809 switch(loadorder)
1811 case LO_INVALID:
1812 nts = STATUS_NO_MEMORY;
1813 break;
1814 case LO_DISABLED:
1815 nts = STATUS_DLL_NOT_FOUND;
1816 break;
1817 case LO_NATIVE:
1818 case LO_NATIVE_BUILTIN:
1819 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1820 else
1822 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1823 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1824 /* not in PE format, maybe it's a builtin */
1825 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1827 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1828 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1829 break;
1830 case LO_BUILTIN:
1831 case LO_BUILTIN_NATIVE:
1832 case LO_DEFAULT: /* default is builtin,native */
1833 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1834 if (!handle) break; /* nothing else we can try */
1835 /* file is not a builtin library, try without using the specified file */
1836 if (nts != STATUS_SUCCESS)
1837 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1838 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1839 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1841 /* stub-only dll, try native */
1842 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1843 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1844 nts = STATUS_DLL_NOT_FOUND;
1846 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1847 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1848 break;
1851 if (nts == STATUS_SUCCESS)
1853 /* Initialize DLL just loaded */
1854 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1855 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1856 (*pwm)->ldr.BaseAddress);
1857 if (handle) NtClose( handle );
1858 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1859 return nts;
1862 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1863 if (handle) NtClose( handle );
1864 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1865 return nts;
1868 /******************************************************************
1869 * LdrLoadDll (NTDLL.@)
1871 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1872 const UNICODE_STRING *libname, HMODULE* hModule)
1874 WINE_MODREF *wm;
1875 NTSTATUS nts;
1877 RtlEnterCriticalSection( &loader_section );
1879 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1880 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1882 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1884 nts = process_attach( wm, NULL );
1885 if (nts != STATUS_SUCCESS)
1887 LdrUnloadDll(wm->ldr.BaseAddress);
1888 wm = NULL;
1891 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1893 RtlLeaveCriticalSection( &loader_section );
1894 return nts;
1898 /******************************************************************
1899 * LdrGetDllHandle (NTDLL.@)
1901 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1903 NTSTATUS status;
1904 WCHAR buffer[128];
1905 WCHAR *filename;
1906 ULONG size;
1907 WINE_MODREF *wm;
1909 RtlEnterCriticalSection( &loader_section );
1911 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1913 filename = buffer;
1914 size = sizeof(buffer);
1915 for (;;)
1917 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1918 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1919 if (status != STATUS_BUFFER_TOO_SMALL) break;
1920 /* grow the buffer and retry */
1921 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1923 status = STATUS_NO_MEMORY;
1924 break;
1928 if (status == STATUS_SUCCESS)
1930 if (wm) *base = wm->ldr.BaseAddress;
1931 else status = STATUS_DLL_NOT_FOUND;
1934 RtlLeaveCriticalSection( &loader_section );
1935 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1936 return status;
1940 /******************************************************************
1941 * LdrAddRefDll (NTDLL.@)
1943 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1945 NTSTATUS ret = STATUS_SUCCESS;
1946 WINE_MODREF *wm;
1948 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
1950 RtlEnterCriticalSection( &loader_section );
1952 if ((wm = get_modref( module )))
1954 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
1955 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1957 else ret = STATUS_INVALID_PARAMETER;
1959 RtlLeaveCriticalSection( &loader_section );
1960 return ret;
1964 /******************************************************************
1965 * LdrQueryProcessModuleInformation
1968 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1969 ULONG buf_size, ULONG* req_size)
1971 SYSTEM_MODULE* sm = &smi->Modules[0];
1972 ULONG size = sizeof(ULONG);
1973 NTSTATUS nts = STATUS_SUCCESS;
1974 ANSI_STRING str;
1975 char* ptr;
1976 PLIST_ENTRY mark, entry;
1977 PLDR_MODULE mod;
1978 WORD id = 0;
1980 smi->ModulesCount = 0;
1982 RtlEnterCriticalSection( &loader_section );
1983 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1984 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1986 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1987 size += sizeof(*sm);
1988 if (size <= buf_size)
1990 sm->Reserved1 = 0; /* FIXME */
1991 sm->Reserved2 = 0; /* FIXME */
1992 sm->ImageBaseAddress = mod->BaseAddress;
1993 sm->ImageSize = mod->SizeOfImage;
1994 sm->Flags = mod->Flags;
1995 sm->Id = id++;
1996 sm->Rank = 0; /* FIXME */
1997 sm->Unknown = 0; /* FIXME */
1998 str.Length = 0;
1999 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2000 str.Buffer = (char*)sm->Name;
2001 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2002 ptr = strrchr(str.Buffer, '\\');
2003 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2005 smi->ModulesCount++;
2006 sm++;
2008 else nts = STATUS_INFO_LENGTH_MISMATCH;
2010 RtlLeaveCriticalSection( &loader_section );
2012 if (req_size) *req_size = size;
2014 return nts;
2018 /******************************************************************
2019 * RtlDllShutdownInProgress (NTDLL.@)
2021 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2023 return process_detaching;
2027 /******************************************************************
2028 * LdrShutdownProcess (NTDLL.@)
2031 void WINAPI LdrShutdownProcess(void)
2033 TRACE("()\n");
2034 process_detach( TRUE, (LPVOID)1 );
2037 /******************************************************************
2038 * LdrShutdownThread (NTDLL.@)
2041 void WINAPI LdrShutdownThread(void)
2043 PLIST_ENTRY mark, entry;
2044 PLDR_MODULE mod;
2046 TRACE("()\n");
2048 /* don't do any detach calls if process is exiting */
2049 if (process_detaching) return;
2050 /* FIXME: there is still a race here */
2052 RtlEnterCriticalSection( &loader_section );
2054 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2055 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2057 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2058 InInitializationOrderModuleList);
2059 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2060 continue;
2061 if ( mod->Flags & LDR_NO_DLL_CALLS )
2062 continue;
2064 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2065 DLL_THREAD_DETACH, NULL );
2068 RtlLeaveCriticalSection( &loader_section );
2069 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2073 /***********************************************************************
2074 * free_modref
2077 static void free_modref( WINE_MODREF *wm )
2079 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2080 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2081 if (wm->ldr.InInitializationOrderModuleList.Flink)
2082 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2084 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2085 if (!TRACE_ON(module))
2086 TRACE_(loaddll)("Unloaded module %s : %s\n",
2087 debugstr_w(wm->ldr.FullDllName.Buffer),
2088 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2090 SERVER_START_REQ( unload_dll )
2092 req->base = wm->ldr.BaseAddress;
2093 wine_server_call( req );
2095 SERVER_END_REQ;
2097 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2098 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2099 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2100 if (cached_modref == wm) cached_modref = NULL;
2101 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2102 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2103 RtlFreeHeap( GetProcessHeap(), 0, wm );
2106 /***********************************************************************
2107 * MODULE_FlushModrefs
2109 * Remove all unused modrefs and call the internal unloading routines
2110 * for the library type.
2112 * The loader_section must be locked while calling this function.
2114 static void MODULE_FlushModrefs(void)
2116 PLIST_ENTRY mark, entry, prev;
2117 PLDR_MODULE mod;
2118 WINE_MODREF*wm;
2120 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2121 for (entry = mark->Blink; entry != mark; entry = prev)
2123 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2124 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2125 prev = entry->Blink;
2126 if (!mod->LoadCount) free_modref( wm );
2129 /* check load order list too for modules that haven't been initialized yet */
2130 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2131 for (entry = mark->Blink; entry != mark; entry = prev)
2133 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2134 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2135 prev = entry->Blink;
2136 if (!mod->LoadCount) free_modref( wm );
2140 /***********************************************************************
2141 * MODULE_DecRefCount
2143 * The loader_section must be locked while calling this function.
2145 static void MODULE_DecRefCount( WINE_MODREF *wm )
2147 int i;
2149 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2150 return;
2152 if ( wm->ldr.LoadCount <= 0 )
2153 return;
2155 --wm->ldr.LoadCount;
2156 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2158 if ( wm->ldr.LoadCount == 0 )
2160 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2162 for ( i = 0; i < wm->nDeps; i++ )
2163 if ( wm->deps[i] )
2164 MODULE_DecRefCount( wm->deps[i] );
2166 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2170 /******************************************************************
2171 * LdrUnloadDll (NTDLL.@)
2175 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2177 NTSTATUS retv = STATUS_SUCCESS;
2179 TRACE("(%p)\n", hModule);
2181 RtlEnterCriticalSection( &loader_section );
2183 /* if we're stopping the whole process (and forcing the removal of all
2184 * DLLs) the library will be freed anyway
2186 if (!process_detaching)
2188 WINE_MODREF *wm;
2190 free_lib_count++;
2191 if ((wm = get_modref( hModule )) != NULL)
2193 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2195 /* Recursively decrement reference counts */
2196 MODULE_DecRefCount( wm );
2198 /* Call process detach notifications */
2199 if ( free_lib_count <= 1 )
2201 process_detach( FALSE, NULL );
2202 MODULE_FlushModrefs();
2205 TRACE("END\n");
2207 else
2208 retv = STATUS_DLL_NOT_FOUND;
2210 free_lib_count--;
2213 RtlLeaveCriticalSection( &loader_section );
2215 return retv;
2218 /***********************************************************************
2219 * RtlImageNtHeader (NTDLL.@)
2221 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2223 IMAGE_NT_HEADERS *ret;
2225 __TRY
2227 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2229 ret = NULL;
2230 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2232 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2233 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2236 __EXCEPT_PAGE_FAULT
2238 return NULL;
2240 __ENDTRY
2241 return ret;
2245 /******************************************************************
2246 * LdrInitializeThunk (NTDLL.@)
2249 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2251 NTSTATUS status;
2252 WINE_MODREF *wm;
2253 LPCWSTR load_path;
2254 PEB *peb = NtCurrentTeb()->Peb;
2255 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2257 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2259 /* allocate the modref for the main exe (if not already done) */
2260 wm = get_modref( peb->ImageBaseAddress );
2261 assert( wm );
2262 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2264 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2265 exit(1);
2267 wm->ldr.LoadCount = -1; /* can't unload main exe */
2269 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2270 version_init( wm->ldr.FullDllName.Buffer );
2272 /* the main exe needs to be the first in the load order list */
2273 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2274 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2276 status = server_init_process_done();
2277 if (status != STATUS_SUCCESS) goto error;
2279 RtlEnterCriticalSection( &loader_section );
2281 actctx_init();
2282 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2283 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2284 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2285 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2286 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2288 if (last_failed_modref)
2289 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2290 goto error;
2292 attach_implicitly_loaded_dlls( (LPVOID)1 );
2294 RtlLeaveCriticalSection( &loader_section );
2296 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2297 return;
2299 error:
2300 ERR( "Main exe initialization for %s failed, status %x\n",
2301 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2302 exit(1);
2306 /***********************************************************************
2307 * RtlImageDirectoryEntryToData (NTDLL.@)
2309 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2311 const IMAGE_NT_HEADERS *nt;
2312 DWORD addr;
2314 if ((ULONG_PTR)module & 1) /* mapped as data file */
2316 module = (HMODULE)((ULONG_PTR)module & ~1);
2317 image = FALSE;
2319 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2320 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2321 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2322 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2323 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2325 /* not mapped as image, need to find the section containing the virtual address */
2326 return RtlImageRvaToVa( nt, module, addr, NULL );
2330 /***********************************************************************
2331 * RtlImageRvaToSection (NTDLL.@)
2333 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2334 HMODULE module, DWORD rva )
2336 int i;
2337 const IMAGE_SECTION_HEADER *sec;
2339 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2340 nt->FileHeader.SizeOfOptionalHeader);
2341 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2343 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2344 return (PIMAGE_SECTION_HEADER)sec;
2346 return NULL;
2350 /***********************************************************************
2351 * RtlImageRvaToVa (NTDLL.@)
2353 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2354 DWORD rva, IMAGE_SECTION_HEADER **section )
2356 IMAGE_SECTION_HEADER *sec;
2358 if (section && *section) /* try this section first */
2360 sec = *section;
2361 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2362 goto found;
2364 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2365 found:
2366 if (section) *section = sec;
2367 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2371 /***********************************************************************
2372 * RtlPcToFileHeader (NTDLL.@)
2374 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2376 LDR_MODULE *module;
2377 PVOID ret = NULL;
2379 RtlEnterCriticalSection( &loader_section );
2380 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2381 RtlLeaveCriticalSection( &loader_section );
2382 *address = ret;
2383 return ret;
2387 /***********************************************************************
2388 * NtLoadDriver (NTDLL.@)
2389 * ZwLoadDriver (NTDLL.@)
2391 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2393 FIXME("(%p), stub!\n",DriverServiceName);
2394 return STATUS_NOT_IMPLEMENTED;
2398 /***********************************************************************
2399 * NtUnloadDriver (NTDLL.@)
2400 * ZwUnloadDriver (NTDLL.@)
2402 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2404 FIXME("(%p), stub!\n",DriverServiceName);
2405 return STATUS_NOT_IMPLEMENTED;
2409 /******************************************************************
2410 * DllMain (NTDLL.@)
2412 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2414 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2415 return TRUE;
2419 /******************************************************************
2420 * __wine_init_windows_dir (NTDLL.@)
2422 * Windows and system dir initialization once kernel32 has been loaded.
2424 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2426 PLIST_ENTRY mark, entry;
2427 LPWSTR buffer, p;
2429 RtlCreateUnicodeString( &windows_dir, windir );
2430 RtlCreateUnicodeString( &system_dir, sysdir );
2431 strcpyW( user_shared_data->NtSystemRoot, windir );
2433 /* prepend the system dir to the name of the already created modules */
2434 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2435 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2437 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2439 assert( mod->Flags & LDR_WINE_INTERNAL );
2441 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2442 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2443 if (!buffer) continue;
2444 strcpyW( buffer, system_dir.Buffer );
2445 p = buffer + strlenW( buffer );
2446 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2447 strcpyW( p, mod->FullDllName.Buffer );
2448 RtlInitUnicodeString( &mod->FullDllName, buffer );
2449 RtlInitUnicodeString( &mod->BaseDllName, p );
2454 /***********************************************************************
2455 * __wine_process_init
2457 void __wine_process_init(void)
2459 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2461 WINE_MODREF *wm;
2462 NTSTATUS status;
2463 ANSI_STRING func_name;
2464 void (* DECLSPEC_NORETURN init_func)(void);
2465 extern mode_t FILE_umask;
2467 main_exe_file = thread_init();
2469 /* retrieve current umask */
2470 FILE_umask = umask(0777);
2471 umask( FILE_umask );
2473 /* setup the load callback and create ntdll modref */
2474 wine_dll_set_callback( load_builtin_callback );
2476 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2478 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2479 exit(1);
2481 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2482 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2483 0, (void **)&init_func )) != STATUS_SUCCESS)
2485 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2486 exit(1);
2488 init_func();