mshtml.idl: Added some missing attributes.
[wine.git] / dlls / ntdll / loader.c
blob44647daa1bd69bcea4e7758235e1eacddd112db0
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;
624 ULONG_PTR cookie;
626 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
627 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
628 if (!create_module_activation_context( &wm->ldr ))
629 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
631 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
632 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
633 return STATUS_SUCCESS;
635 nb_imports = 0;
636 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
638 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
640 /* Allocate module dependency list */
641 wm->nDeps = nb_imports;
642 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
644 /* load the imported modules. They are automatically
645 * added to the modref list of the process.
647 prev = current_modref;
648 current_modref = wm;
649 status = STATUS_SUCCESS;
650 for (i = 0; i < nb_imports; i++)
652 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
653 status = STATUS_DLL_NOT_FOUND;
655 current_modref = prev;
656 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
657 return status;
661 /*************************************************************************
662 * alloc_module
664 * Allocate a WINE_MODREF structure and add it to the process list
665 * The loader_section must be locked while calling this function.
667 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
669 WINE_MODREF *wm;
670 const WCHAR *p;
671 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
672 PLIST_ENTRY entry, mark;
674 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
676 wm->nDeps = 0;
677 wm->deps = NULL;
679 wm->ldr.BaseAddress = hModule;
680 wm->ldr.EntryPoint = NULL;
681 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
682 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
683 wm->ldr.LoadCount = 1;
684 wm->ldr.TlsIndex = -1;
685 wm->ldr.SectionHandle = NULL;
686 wm->ldr.CheckSum = 0;
687 wm->ldr.TimeDateStamp = 0;
688 wm->ldr.ActivationContext = 0;
690 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
691 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
692 else p = wm->ldr.FullDllName.Buffer;
693 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
695 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
697 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
698 if (nt->OptionalHeader.AddressOfEntryPoint)
699 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
702 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
703 &wm->ldr.InLoadOrderModuleList);
705 /* insert module in MemoryList, sorted in increasing base addresses */
706 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
707 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
709 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
710 break;
712 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
713 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
714 wm->ldr.InMemoryOrderModuleList.Flink = entry;
715 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
717 /* wait until init is called for inserting into this list */
718 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
719 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
721 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
723 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
724 VIRTUAL_SetForceExec( TRUE );
726 return wm;
730 /*************************************************************************
731 * alloc_process_tls
733 * Allocate the process-wide structure for module TLS storage.
735 static NTSTATUS alloc_process_tls(void)
737 PLIST_ENTRY mark, entry;
738 PLDR_MODULE mod;
739 const IMAGE_TLS_DIRECTORY *dir;
740 ULONG size, i;
742 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
743 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
745 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
746 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
747 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
748 continue;
749 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
750 if (!size) continue;
751 tls_total_size += size;
752 tls_module_count++;
754 if (!tls_module_count) return STATUS_SUCCESS;
756 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
758 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
759 if (!tls_dirs) return STATUS_NO_MEMORY;
761 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
763 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
764 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
765 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
766 continue;
767 tls_dirs[i] = dir;
768 *(DWORD *)dir->AddressOfIndex = i;
769 mod->TlsIndex = i;
770 mod->LoadCount = -1; /* can't unload it */
771 i++;
773 return STATUS_SUCCESS;
777 /*************************************************************************
778 * alloc_thread_tls
780 * Allocate the per-thread structure for module TLS storage.
782 static NTSTATUS alloc_thread_tls(void)
784 void **pointers;
785 char *data;
786 UINT i;
788 if (!tls_module_count) return STATUS_SUCCESS;
790 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
791 tls_module_count * sizeof(*pointers) )))
792 return STATUS_NO_MEMORY;
794 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
796 RtlFreeHeap( GetProcessHeap(), 0, pointers );
797 return STATUS_NO_MEMORY;
800 for (i = 0; i < tls_module_count; i++)
802 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
803 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
805 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
806 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
807 (void *)dir->StartAddressOfRawData, data );
809 pointers[i] = data;
810 memcpy( data, (void *)dir->StartAddressOfRawData, size );
811 data += size;
812 memset( data, 0, dir->SizeOfZeroFill );
813 data += dir->SizeOfZeroFill;
815 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
816 return STATUS_SUCCESS;
820 /*************************************************************************
821 * call_tls_callbacks
823 static void call_tls_callbacks( HMODULE module, UINT reason )
825 const IMAGE_TLS_DIRECTORY *dir;
826 const PIMAGE_TLS_CALLBACK *callback;
827 ULONG dirsize;
829 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
830 if (!dir || !dir->AddressOfCallBacks) return;
832 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
834 if (TRACE_ON(relay))
835 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
836 GetCurrentThreadId(), *callback, module, reason_names[reason] );
837 __TRY
839 (*callback)( module, reason, NULL );
841 __EXCEPT(NULL)
843 if (TRACE_ON(relay))
844 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
845 GetCurrentThreadId(), callback, module, reason_names[reason] );
846 return;
848 __ENDTRY
849 if (TRACE_ON(relay))
850 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
851 GetCurrentThreadId(), *callback, module, reason_names[reason] );
856 /*************************************************************************
857 * MODULE_InitDLL
859 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
861 WCHAR mod_name[32];
862 BOOL retv = TRUE;
863 DLLENTRYPROC entry = wm->ldr.EntryPoint;
864 void *module = wm->ldr.BaseAddress;
866 /* Skip calls for modules loaded with special load flags */
868 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
869 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
870 if (!entry) return TRUE;
872 if (TRACE_ON(relay))
874 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
875 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
876 mod_name[len / sizeof(WCHAR)] = 0;
877 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
878 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
879 reason_names[reason], lpReserved );
881 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
882 reason_names[reason], lpReserved );
884 retv = call_dll_entry_point( entry, module, reason, lpReserved );
886 /* The state of the module list may have changed due to the call
887 to the dll. We cannot assume that this module has not been
888 deleted. */
889 if (TRACE_ON(relay))
890 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
891 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
892 reason_names[reason], lpReserved, retv );
893 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
895 return retv;
899 /*************************************************************************
900 * process_attach
902 * Send the process attach notification to all DLLs the given module
903 * depends on (recursively). This is somewhat complicated due to the fact that
905 * - we have to respect the module dependencies, i.e. modules implicitly
906 * referenced by another module have to be initialized before the module
907 * itself can be initialized
909 * - the initialization routine of a DLL can itself call LoadLibrary,
910 * thereby introducing a whole new set of dependencies (even involving
911 * the 'old' modules) at any time during the whole process
913 * (Note that this routine can be recursively entered not only directly
914 * from itself, but also via LoadLibrary from one of the called initialization
915 * routines.)
917 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
918 * the process *detach* notifications to be sent in the correct order.
919 * This must not only take into account module dependencies, but also
920 * 'hidden' dependencies created by modules calling LoadLibrary in their
921 * attach notification routine.
923 * The strategy is rather simple: we move a WINE_MODREF to the head of the
924 * list after the attach notification has returned. This implies that the
925 * detach notifications are called in the reverse of the sequence the attach
926 * notifications *returned*.
928 * The loader_section must be locked while calling this function.
930 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
932 NTSTATUS status = STATUS_SUCCESS;
933 ULONG_PTR cookie;
934 int i;
936 if (process_detaching) return status;
938 /* prevent infinite recursion in case of cyclical dependencies */
939 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
940 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
941 return status;
943 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
945 /* Tag current MODREF to prevent recursive loop */
946 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
947 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
949 /* Recursively attach all DLLs this one depends on */
950 for ( i = 0; i < wm->nDeps; i++ )
952 if (!wm->deps[i]) continue;
953 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
956 /* Call DLL entry point */
957 if (status == STATUS_SUCCESS)
959 WINE_MODREF *prev = current_modref;
960 current_modref = wm;
961 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
963 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
965 else
967 /* point to the name so LdrInitializeThunk can print it */
968 last_failed_modref = wm;
969 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
970 status = STATUS_DLL_INIT_FAILED;
972 current_modref = prev;
975 if (!wm->ldr.InInitializationOrderModuleList.Flink)
976 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
977 &wm->ldr.InInitializationOrderModuleList);
979 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
980 /* Remove recursion flag */
981 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
983 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
984 return status;
988 /**********************************************************************
989 * attach_implicitly_loaded_dlls
991 * Attach to the (builtin) dlls that have been implicitly loaded because
992 * of a dependency at the Unix level, but not imported at the Win32 level.
994 static void attach_implicitly_loaded_dlls( LPVOID reserved )
996 for (;;)
998 PLIST_ENTRY mark, entry;
1000 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1001 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1003 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1005 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1006 TRACE( "found implicitly loaded %s, attaching to it\n",
1007 debugstr_w(mod->BaseDllName.Buffer));
1008 mod->LoadCount = -1; /* we can't unload it anyway */
1009 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1010 break; /* restart the search from the start */
1012 if (entry == mark) break; /* nothing found */
1017 /*************************************************************************
1018 * process_detach
1020 * Send DLL process detach notifications. See the comment about calling
1021 * sequence at process_attach. Unless the bForceDetach flag
1022 * is set, only DLLs with zero refcount are notified.
1024 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1026 PLIST_ENTRY mark, entry;
1027 PLDR_MODULE mod;
1029 RtlEnterCriticalSection( &loader_section );
1030 if (bForceDetach) process_detaching = 1;
1031 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1034 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1036 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1037 InInitializationOrderModuleList);
1038 /* Check whether to detach this DLL */
1039 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1040 continue;
1041 if ( mod->LoadCount && !bForceDetach )
1042 continue;
1044 /* Call detach notification */
1045 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1046 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1047 DLL_PROCESS_DETACH, lpReserved );
1049 /* Restart at head of WINE_MODREF list, as entries might have
1050 been added and/or removed while performing the call ... */
1051 break;
1053 } while (entry != mark);
1055 RtlLeaveCriticalSection( &loader_section );
1058 /*************************************************************************
1059 * MODULE_DllThreadAttach
1061 * Send DLL thread attach notifications. These are sent in the
1062 * reverse sequence of process detach notification.
1065 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1067 PLIST_ENTRY mark, entry;
1068 PLDR_MODULE mod;
1069 NTSTATUS status;
1071 /* don't do any attach calls if process is exiting */
1072 if (process_detaching) return STATUS_SUCCESS;
1073 /* FIXME: there is still a race here */
1075 RtlEnterCriticalSection( &loader_section );
1077 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1079 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1080 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1082 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1083 InInitializationOrderModuleList);
1084 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1085 continue;
1086 if ( mod->Flags & LDR_NO_DLL_CALLS )
1087 continue;
1089 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1090 DLL_THREAD_ATTACH, lpReserved );
1093 done:
1094 RtlLeaveCriticalSection( &loader_section );
1095 return status;
1098 /******************************************************************
1099 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1102 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1104 WINE_MODREF *wm;
1105 NTSTATUS ret = STATUS_SUCCESS;
1107 RtlEnterCriticalSection( &loader_section );
1109 wm = get_modref( hModule );
1110 if (!wm || wm->ldr.TlsIndex != -1)
1111 ret = STATUS_DLL_NOT_FOUND;
1112 else
1113 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1115 RtlLeaveCriticalSection( &loader_section );
1117 return ret;
1120 /******************************************************************
1121 * LdrFindEntryForAddress (NTDLL.@)
1123 * The loader_section must be locked while calling this function
1125 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1127 PLIST_ENTRY mark, entry;
1128 PLDR_MODULE mod;
1130 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1131 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1133 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1134 if ((const void *)mod->BaseAddress <= addr &&
1135 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1137 *pmod = mod;
1138 return STATUS_SUCCESS;
1140 if ((const void *)mod->BaseAddress > addr) break;
1142 return STATUS_NO_MORE_ENTRIES;
1145 /******************************************************************
1146 * LdrLockLoaderLock (NTDLL.@)
1148 * Note: flags are not implemented.
1149 * Flag 0x01 is used to raise exceptions on errors.
1150 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1152 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1154 if (flags) FIXME( "flags %x not supported\n", flags );
1156 if (result) *result = 1;
1157 if (!magic) return STATUS_INVALID_PARAMETER_3;
1158 RtlEnterCriticalSection( &loader_section );
1159 *magic = GetCurrentThreadId();
1160 return STATUS_SUCCESS;
1164 /******************************************************************
1165 * LdrUnlockLoaderUnlock (NTDLL.@)
1167 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1169 if (magic)
1171 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1172 RtlLeaveCriticalSection( &loader_section );
1174 return STATUS_SUCCESS;
1178 /******************************************************************
1179 * LdrGetProcedureAddress (NTDLL.@)
1181 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1182 ULONG ord, PVOID *address)
1184 IMAGE_EXPORT_DIRECTORY *exports;
1185 DWORD exp_size;
1186 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1188 RtlEnterCriticalSection( &loader_section );
1190 /* check if the module itself is invalid to return the proper error */
1191 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1192 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1193 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1195 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1196 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1197 if (proc)
1199 *address = proc;
1200 ret = STATUS_SUCCESS;
1204 RtlLeaveCriticalSection( &loader_section );
1205 return ret;
1209 /***********************************************************************
1210 * is_fake_dll
1212 * Check if a loaded native dll is a Wine fake dll.
1214 static BOOL is_fake_dll( const void *base )
1216 static const char fakedll_signature[] = "Wine placeholder DLL";
1217 const IMAGE_DOS_HEADER *dos = base;
1219 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1220 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1221 return FALSE;
1225 /***********************************************************************
1226 * get_builtin_fullname
1228 * Build the full pathname for a builtin dll.
1230 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1232 static const WCHAR soW[] = {'.','s','o',0};
1233 WCHAR *p, *fullname;
1234 size_t i, len = strlen(filename);
1236 /* check if path can correspond to the dll we have */
1237 if (path && (p = strrchrW( path, '\\' )))
1239 p++;
1240 for (i = 0; i < len; i++)
1241 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1242 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1244 /* the filename matches, use path as the full path */
1245 len += p - path;
1246 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1248 memcpy( fullname, path, len * sizeof(WCHAR) );
1249 fullname[len] = 0;
1251 return fullname;
1255 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1256 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1258 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1259 p = fullname + system_dir.Length / sizeof(WCHAR);
1260 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1261 ascii_to_unicode( p, filename, len + 1 );
1263 return fullname;
1267 /***********************************************************************
1268 * load_builtin_callback
1270 * Load a library in memory; callback function for wine_dll_register
1272 static void load_builtin_callback( void *module, const char *filename )
1274 static const WCHAR emptyW[1];
1275 void *addr;
1276 IMAGE_NT_HEADERS *nt;
1277 WINE_MODREF *wm;
1278 WCHAR *fullname;
1279 const WCHAR *load_path;
1280 SIZE_T size;
1282 if (!module)
1284 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1285 return;
1287 if (!(nt = RtlImageNtHeader( module )))
1289 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1290 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1291 return;
1293 addr = module;
1294 size = nt->OptionalHeader.SizeOfImage;
1295 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1296 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1297 /* create the MODREF */
1299 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1301 ERR( "can't load %s\n", filename );
1302 builtin_load_info->status = STATUS_NO_MEMORY;
1303 return;
1306 wm = alloc_module( module, fullname );
1307 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1308 if (!wm)
1310 ERR( "can't load %s\n", filename );
1311 builtin_load_info->status = STATUS_NO_MEMORY;
1312 return;
1314 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1316 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1317 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1319 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1321 else
1323 /* fixup imports */
1325 load_path = builtin_load_info->load_path;
1326 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1327 if (!load_path) load_path = emptyW;
1328 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1330 /* the module has only be inserted in the load & memory order lists */
1331 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1332 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1333 /* FIXME: free the modref */
1334 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1335 return;
1339 builtin_load_info->wm = wm;
1340 TRACE( "loaded %s %p %p\n", filename, wm, module );
1342 /* send the DLL load event */
1344 SERVER_START_REQ( load_dll )
1346 req->handle = 0;
1347 req->base = module;
1348 req->size = nt->OptionalHeader.SizeOfImage;
1349 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1350 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1351 req->name = &wm->ldr.FullDllName.Buffer;
1352 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1353 wine_server_call( req );
1355 SERVER_END_REQ;
1357 /* setup relay debugging entry points */
1358 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1362 /******************************************************************************
1363 * load_native_dll (internal)
1365 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1366 DWORD flags, WINE_MODREF** pwm )
1368 void *module;
1369 HANDLE mapping;
1370 OBJECT_ATTRIBUTES attr;
1371 LARGE_INTEGER size;
1372 IMAGE_NT_HEADERS *nt;
1373 SIZE_T len = 0;
1374 WINE_MODREF *wm;
1375 NTSTATUS status;
1377 TRACE("Trying native dll %s\n", debugstr_w(name));
1379 attr.Length = sizeof(attr);
1380 attr.RootDirectory = 0;
1381 attr.ObjectName = NULL;
1382 attr.Attributes = 0;
1383 attr.SecurityDescriptor = NULL;
1384 attr.SecurityQualityOfService = NULL;
1385 size.QuadPart = 0;
1387 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1388 &attr, &size, 0, SEC_IMAGE, file );
1389 if (status != STATUS_SUCCESS) return status;
1391 module = NULL;
1392 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1393 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1394 NtClose( mapping );
1395 if (status != STATUS_SUCCESS) return status;
1397 if (is_fake_dll( module ))
1399 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1400 NtUnmapViewOfSection( NtCurrentProcess(), module );
1401 return STATUS_DLL_NOT_FOUND;
1404 /* create the MODREF */
1406 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1408 /* fixup imports */
1410 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1412 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1414 /* the module has only be inserted in the load & memory order lists */
1415 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1416 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1418 /* FIXME: there are several more dangling references
1419 * left. Including dlls loaded by this dll before the
1420 * failed one. Unrolling is rather difficult with the
1421 * current structure and we can leave them lying
1422 * around with no problems, so we don't care.
1423 * As these might reference our wm, we don't free it.
1425 return status;
1429 /* send DLL load event */
1431 nt = RtlImageNtHeader( module );
1433 SERVER_START_REQ( load_dll )
1435 req->handle = file;
1436 req->base = module;
1437 req->size = nt->OptionalHeader.SizeOfImage;
1438 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1439 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1440 req->name = &wm->ldr.FullDllName.Buffer;
1441 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1442 wine_server_call( req );
1444 SERVER_END_REQ;
1446 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1448 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1450 wm->ldr.LoadCount = 1;
1451 *pwm = wm;
1452 return STATUS_SUCCESS;
1456 /***********************************************************************
1457 * load_builtin_dll
1459 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1460 DWORD flags, WINE_MODREF** pwm )
1462 char error[256], dllname[MAX_PATH];
1463 const WCHAR *name, *p;
1464 DWORD len, i;
1465 void *handle = NULL;
1466 struct builtin_load_info info, *prev_info;
1468 /* Fix the name in case we have a full path and extension */
1469 name = path;
1470 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1471 if ((p = strrchrW( name, '/' ))) name = p + 1;
1473 /* load_library will modify info.status. Note also that load_library can be
1474 * called several times, if the .so file we're loading has dependencies.
1475 * info.status will gather all the errors we may get while loading all these
1476 * libraries
1478 info.load_path = load_path;
1479 info.filename = NULL;
1480 info.status = STATUS_SUCCESS;
1481 info.wm = NULL;
1483 if (file) /* we have a real file, try to load it */
1485 UNICODE_STRING nt_name;
1486 ANSI_STRING unix_name;
1488 TRACE("Trying built-in %s\n", debugstr_w(path));
1490 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1491 return STATUS_DLL_NOT_FOUND;
1493 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1495 RtlFreeUnicodeString( &nt_name );
1496 return STATUS_DLL_NOT_FOUND;
1498 prev_info = builtin_load_info;
1499 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1500 builtin_load_info = &info;
1501 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1502 builtin_load_info = prev_info;
1503 RtlFreeUnicodeString( &nt_name );
1504 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1505 if (!handle)
1507 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1508 return STATUS_INVALID_IMAGE_FORMAT;
1511 else
1513 int file_exists;
1515 TRACE("Trying built-in %s\n", debugstr_w(name));
1517 /* we don't want to depend on the current codepage here */
1518 len = strlenW( name ) + 1;
1519 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1520 for (i = 0; i < len; i++)
1522 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1523 dllname[i] = (char)name[i];
1524 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1527 prev_info = builtin_load_info;
1528 builtin_load_info = &info;
1529 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1530 builtin_load_info = prev_info;
1531 if (!handle)
1533 if (!file_exists)
1535 /* The file does not exist -> WARN() */
1536 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1537 return STATUS_DLL_NOT_FOUND;
1539 /* ERR() for all other errors (missing functions, ...) */
1540 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1541 return STATUS_PROCEDURE_NOT_FOUND;
1545 if (info.status != STATUS_SUCCESS)
1547 wine_dll_unload( handle );
1548 return info.status;
1551 if (!info.wm)
1553 PLIST_ENTRY mark, entry;
1555 /* The constructor wasn't called, this means the .so is already
1556 * loaded under a different name. Try to find the wm for it. */
1558 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1559 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1561 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1562 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1564 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1565 TRACE( "Found already loaded module %s for builtin %s\n",
1566 debugstr_w(info.wm->ldr.FullDllName.Buffer), debugstr_w(path) );
1567 break;
1570 wine_dll_unload( handle ); /* release the libdl refcount */
1571 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1572 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1574 else
1576 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1577 info.wm->ldr.LoadCount = 1;
1578 info.wm->ldr.SectionHandle = handle;
1581 *pwm = info.wm;
1582 return STATUS_SUCCESS;
1586 /***********************************************************************
1587 * find_actctx_dll
1589 * Find the full path (if any) of the dll from the activation context.
1591 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1593 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1595 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1596 ACTCTX_SECTION_KEYED_DATA data;
1597 UNICODE_STRING nameW;
1598 NTSTATUS status;
1599 SIZE_T needed, size = 1024;
1600 WCHAR *p;
1602 RtlInitUnicodeString( &nameW, libname );
1603 data.cbSize = sizeof(data);
1604 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1605 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1606 &nameW, &data );
1607 if (status != STATUS_SUCCESS) return status;
1609 for (;;)
1611 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1613 status = STATUS_NO_MEMORY;
1614 goto done;
1616 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1617 AssemblyDetailedInformationInActivationContext,
1618 info, size, &needed );
1619 if (status == STATUS_SUCCESS) break;
1620 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1621 RtlFreeHeap( GetProcessHeap(), 0, info );
1622 size = needed;
1623 /* restart with larger buffer */
1626 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1627 nameW.Length + 2*sizeof(WCHAR));
1629 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1631 status = STATUS_NO_MEMORY;
1632 goto done;
1634 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1635 p += windows_dir.Length / sizeof(WCHAR);
1636 memcpy( p, winsxsW, sizeof(winsxsW) );
1637 p += sizeof(winsxsW) / sizeof(WCHAR);
1638 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1639 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1640 *p++ = '\\';
1641 strcpyW( p, libname );
1642 TRACE ("found %s for %s\n", debugstr_w(*fullname), debugstr_w(libname) );
1643 done:
1644 RtlFreeHeap( GetProcessHeap(), 0, info );
1645 RtlReleaseActivationContext( data.hActCtx );
1646 return status;
1650 /***********************************************************************
1651 * find_dll_file
1653 * Find the file (or already loaded module) for a given dll name.
1655 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1656 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1658 OBJECT_ATTRIBUTES attr;
1659 IO_STATUS_BLOCK io;
1660 UNICODE_STRING nt_name;
1661 WCHAR *file_part, *ext, *dllname;
1662 ULONG len;
1664 /* first append .dll if needed */
1666 dllname = NULL;
1667 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1669 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1670 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1671 return STATUS_NO_MEMORY;
1672 strcpyW( dllname, libname );
1673 strcatW( dllname, dllW );
1674 libname = dllname;
1677 nt_name.Buffer = NULL;
1679 if (!contains_path( libname ))
1681 NTSTATUS status;
1682 WCHAR *fullname;
1684 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1686 status = find_actctx_dll( libname, &fullname );
1687 if (status == STATUS_SUCCESS)
1689 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1690 libname = dllname = fullname;
1692 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1694 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1695 return status;
1699 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1701 /* we need to search for it */
1702 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1703 if (len)
1705 if (len >= *size) goto overflow;
1706 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1708 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1710 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1711 return STATUS_NO_MEMORY;
1713 attr.Length = sizeof(attr);
1714 attr.RootDirectory = 0;
1715 attr.Attributes = OBJ_CASE_INSENSITIVE;
1716 attr.ObjectName = &nt_name;
1717 attr.SecurityDescriptor = NULL;
1718 attr.SecurityQualityOfService = NULL;
1719 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1720 goto found;
1723 /* not found */
1725 if (!contains_path( libname ))
1727 /* if libname doesn't contain a path at all, we simply return the name as is,
1728 * to be loaded as builtin */
1729 len = strlenW(libname) * sizeof(WCHAR);
1730 if (len >= *size) goto overflow;
1731 strcpyW( filename, libname );
1732 goto found;
1736 /* absolute path name, or relative path name but not found above */
1738 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1740 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1741 return STATUS_NO_MEMORY;
1743 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1744 if (len >= *size) goto overflow;
1745 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1746 if (!(*pwm = find_fullname_module( filename )) && handle)
1748 attr.Length = sizeof(attr);
1749 attr.RootDirectory = 0;
1750 attr.Attributes = OBJ_CASE_INSENSITIVE;
1751 attr.ObjectName = &nt_name;
1752 attr.SecurityDescriptor = NULL;
1753 attr.SecurityQualityOfService = NULL;
1754 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1756 found:
1757 RtlFreeUnicodeString( &nt_name );
1758 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1759 return STATUS_SUCCESS;
1761 overflow:
1762 RtlFreeUnicodeString( &nt_name );
1763 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1764 *size = len + sizeof(WCHAR);
1765 return STATUS_BUFFER_TOO_SMALL;
1769 /***********************************************************************
1770 * load_dll (internal)
1772 * Load a PE style module according to the load order.
1773 * The loader_section must be locked while calling this function.
1775 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1777 enum loadorder loadorder;
1778 WCHAR buffer[32];
1779 WCHAR *filename;
1780 ULONG size;
1781 WINE_MODREF *main_exe;
1782 HANDLE handle = 0;
1783 NTSTATUS nts;
1785 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1787 filename = buffer;
1788 size = sizeof(buffer);
1789 for (;;)
1791 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1792 if (nts == STATUS_SUCCESS) break;
1793 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1794 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1795 /* grow the buffer and retry */
1796 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1799 if (*pwm) /* found already loaded module */
1801 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1803 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1805 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1806 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1807 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1808 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1809 return STATUS_SUCCESS;
1812 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1813 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1815 switch(loadorder)
1817 case LO_INVALID:
1818 nts = STATUS_NO_MEMORY;
1819 break;
1820 case LO_DISABLED:
1821 nts = STATUS_DLL_NOT_FOUND;
1822 break;
1823 case LO_NATIVE:
1824 case LO_NATIVE_BUILTIN:
1825 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1826 else
1828 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1829 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1830 /* not in PE format, maybe it's a builtin */
1831 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1833 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1834 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1835 break;
1836 case LO_BUILTIN:
1837 case LO_BUILTIN_NATIVE:
1838 case LO_DEFAULT: /* default is builtin,native */
1839 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1840 if (!handle) break; /* nothing else we can try */
1841 /* file is not a builtin library, try without using the specified file */
1842 if (nts != STATUS_SUCCESS)
1843 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1844 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1845 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1847 /* stub-only dll, try native */
1848 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1849 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1850 nts = STATUS_DLL_NOT_FOUND;
1852 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1853 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1854 break;
1857 if (nts == STATUS_SUCCESS)
1859 /* Initialize DLL just loaded */
1860 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1861 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1862 (*pwm)->ldr.BaseAddress);
1863 if (handle) NtClose( handle );
1864 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1865 return nts;
1868 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1869 if (handle) NtClose( handle );
1870 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1871 return nts;
1874 /******************************************************************
1875 * LdrLoadDll (NTDLL.@)
1877 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1878 const UNICODE_STRING *libname, HMODULE* hModule)
1880 WINE_MODREF *wm;
1881 NTSTATUS nts;
1883 RtlEnterCriticalSection( &loader_section );
1885 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1886 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1888 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1890 nts = process_attach( wm, NULL );
1891 if (nts != STATUS_SUCCESS)
1893 LdrUnloadDll(wm->ldr.BaseAddress);
1894 wm = NULL;
1897 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1899 RtlLeaveCriticalSection( &loader_section );
1900 return nts;
1904 /******************************************************************
1905 * LdrGetDllHandle (NTDLL.@)
1907 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1909 NTSTATUS status;
1910 WCHAR buffer[128];
1911 WCHAR *filename;
1912 ULONG size;
1913 WINE_MODREF *wm;
1915 RtlEnterCriticalSection( &loader_section );
1917 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1919 filename = buffer;
1920 size = sizeof(buffer);
1921 for (;;)
1923 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1924 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1925 if (status != STATUS_BUFFER_TOO_SMALL) break;
1926 /* grow the buffer and retry */
1927 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1929 status = STATUS_NO_MEMORY;
1930 break;
1934 if (status == STATUS_SUCCESS)
1936 if (wm) *base = wm->ldr.BaseAddress;
1937 else status = STATUS_DLL_NOT_FOUND;
1940 RtlLeaveCriticalSection( &loader_section );
1941 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1942 return status;
1946 /******************************************************************
1947 * LdrAddRefDll (NTDLL.@)
1949 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1951 NTSTATUS ret = STATUS_SUCCESS;
1952 WINE_MODREF *wm;
1954 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
1956 RtlEnterCriticalSection( &loader_section );
1958 if ((wm = get_modref( module )))
1960 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
1961 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1963 else ret = STATUS_INVALID_PARAMETER;
1965 RtlLeaveCriticalSection( &loader_section );
1966 return ret;
1970 /******************************************************************
1971 * LdrQueryProcessModuleInformation
1974 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1975 ULONG buf_size, ULONG* req_size)
1977 SYSTEM_MODULE* sm = &smi->Modules[0];
1978 ULONG size = sizeof(ULONG);
1979 NTSTATUS nts = STATUS_SUCCESS;
1980 ANSI_STRING str;
1981 char* ptr;
1982 PLIST_ENTRY mark, entry;
1983 PLDR_MODULE mod;
1984 WORD id = 0;
1986 smi->ModulesCount = 0;
1988 RtlEnterCriticalSection( &loader_section );
1989 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1990 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1992 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1993 size += sizeof(*sm);
1994 if (size <= buf_size)
1996 sm->Reserved1 = 0; /* FIXME */
1997 sm->Reserved2 = 0; /* FIXME */
1998 sm->ImageBaseAddress = mod->BaseAddress;
1999 sm->ImageSize = mod->SizeOfImage;
2000 sm->Flags = mod->Flags;
2001 sm->Id = id++;
2002 sm->Rank = 0; /* FIXME */
2003 sm->Unknown = 0; /* FIXME */
2004 str.Length = 0;
2005 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2006 str.Buffer = (char*)sm->Name;
2007 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2008 ptr = strrchr(str.Buffer, '\\');
2009 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2011 smi->ModulesCount++;
2012 sm++;
2014 else nts = STATUS_INFO_LENGTH_MISMATCH;
2016 RtlLeaveCriticalSection( &loader_section );
2018 if (req_size) *req_size = size;
2020 return nts;
2024 /******************************************************************
2025 * RtlDllShutdownInProgress (NTDLL.@)
2027 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2029 return process_detaching;
2033 /******************************************************************
2034 * LdrShutdownProcess (NTDLL.@)
2037 void WINAPI LdrShutdownProcess(void)
2039 TRACE("()\n");
2040 process_detach( TRUE, (LPVOID)1 );
2043 /******************************************************************
2044 * LdrShutdownThread (NTDLL.@)
2047 void WINAPI LdrShutdownThread(void)
2049 PLIST_ENTRY mark, entry;
2050 PLDR_MODULE mod;
2052 TRACE("()\n");
2054 /* don't do any detach calls if process is exiting */
2055 if (process_detaching) return;
2056 /* FIXME: there is still a race here */
2058 RtlEnterCriticalSection( &loader_section );
2060 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2061 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2063 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2064 InInitializationOrderModuleList);
2065 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2066 continue;
2067 if ( mod->Flags & LDR_NO_DLL_CALLS )
2068 continue;
2070 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2071 DLL_THREAD_DETACH, NULL );
2074 RtlLeaveCriticalSection( &loader_section );
2075 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2079 /***********************************************************************
2080 * free_modref
2083 static void free_modref( WINE_MODREF *wm )
2085 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2086 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2087 if (wm->ldr.InInitializationOrderModuleList.Flink)
2088 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2090 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2091 if (!TRACE_ON(module))
2092 TRACE_(loaddll)("Unloaded module %s : %s\n",
2093 debugstr_w(wm->ldr.FullDllName.Buffer),
2094 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2096 SERVER_START_REQ( unload_dll )
2098 req->base = wm->ldr.BaseAddress;
2099 wine_server_call( req );
2101 SERVER_END_REQ;
2103 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2104 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2105 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2106 if (cached_modref == wm) cached_modref = NULL;
2107 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2108 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2109 RtlFreeHeap( GetProcessHeap(), 0, wm );
2112 /***********************************************************************
2113 * MODULE_FlushModrefs
2115 * Remove all unused modrefs and call the internal unloading routines
2116 * for the library type.
2118 * The loader_section must be locked while calling this function.
2120 static void MODULE_FlushModrefs(void)
2122 PLIST_ENTRY mark, entry, prev;
2123 PLDR_MODULE mod;
2124 WINE_MODREF*wm;
2126 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2127 for (entry = mark->Blink; entry != mark; entry = prev)
2129 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2130 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2131 prev = entry->Blink;
2132 if (!mod->LoadCount) free_modref( wm );
2135 /* check load order list too for modules that haven't been initialized yet */
2136 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2137 for (entry = mark->Blink; entry != mark; entry = prev)
2139 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2140 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2141 prev = entry->Blink;
2142 if (!mod->LoadCount) free_modref( wm );
2146 /***********************************************************************
2147 * MODULE_DecRefCount
2149 * The loader_section must be locked while calling this function.
2151 static void MODULE_DecRefCount( WINE_MODREF *wm )
2153 int i;
2155 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2156 return;
2158 if ( wm->ldr.LoadCount <= 0 )
2159 return;
2161 --wm->ldr.LoadCount;
2162 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2164 if ( wm->ldr.LoadCount == 0 )
2166 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2168 for ( i = 0; i < wm->nDeps; i++ )
2169 if ( wm->deps[i] )
2170 MODULE_DecRefCount( wm->deps[i] );
2172 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2176 /******************************************************************
2177 * LdrUnloadDll (NTDLL.@)
2181 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2183 NTSTATUS retv = STATUS_SUCCESS;
2185 TRACE("(%p)\n", hModule);
2187 RtlEnterCriticalSection( &loader_section );
2189 /* if we're stopping the whole process (and forcing the removal of all
2190 * DLLs) the library will be freed anyway
2192 if (!process_detaching)
2194 WINE_MODREF *wm;
2196 free_lib_count++;
2197 if ((wm = get_modref( hModule )) != NULL)
2199 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2201 /* Recursively decrement reference counts */
2202 MODULE_DecRefCount( wm );
2204 /* Call process detach notifications */
2205 if ( free_lib_count <= 1 )
2207 process_detach( FALSE, NULL );
2208 MODULE_FlushModrefs();
2211 TRACE("END\n");
2213 else
2214 retv = STATUS_DLL_NOT_FOUND;
2216 free_lib_count--;
2219 RtlLeaveCriticalSection( &loader_section );
2221 return retv;
2224 /***********************************************************************
2225 * RtlImageNtHeader (NTDLL.@)
2227 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2229 IMAGE_NT_HEADERS *ret;
2231 __TRY
2233 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2235 ret = NULL;
2236 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2238 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2239 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2242 __EXCEPT_PAGE_FAULT
2244 return NULL;
2246 __ENDTRY
2247 return ret;
2251 /******************************************************************
2252 * LdrInitializeThunk (NTDLL.@)
2255 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2257 NTSTATUS status;
2258 WINE_MODREF *wm;
2259 LPCWSTR load_path;
2260 PEB *peb = NtCurrentTeb()->Peb;
2261 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2263 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2265 /* allocate the modref for the main exe (if not already done) */
2266 wm = get_modref( peb->ImageBaseAddress );
2267 assert( wm );
2268 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2270 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2271 exit(1);
2273 wm->ldr.LoadCount = -1; /* can't unload main exe */
2275 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2276 version_init( wm->ldr.FullDllName.Buffer );
2278 /* the main exe needs to be the first in the load order list */
2279 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2280 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2282 status = server_init_process_done();
2283 if (status != STATUS_SUCCESS) goto error;
2285 RtlEnterCriticalSection( &loader_section );
2287 actctx_init();
2288 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2289 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2290 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2291 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2292 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2294 if (last_failed_modref)
2295 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2296 goto error;
2298 attach_implicitly_loaded_dlls( (LPVOID)1 );
2300 RtlLeaveCriticalSection( &loader_section );
2302 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2303 return;
2305 error:
2306 ERR( "Main exe initialization for %s failed, status %x\n",
2307 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2308 exit(1);
2312 /***********************************************************************
2313 * RtlImageDirectoryEntryToData (NTDLL.@)
2315 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2317 const IMAGE_NT_HEADERS *nt;
2318 DWORD addr;
2320 if ((ULONG_PTR)module & 1) /* mapped as data file */
2322 module = (HMODULE)((ULONG_PTR)module & ~1);
2323 image = FALSE;
2325 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2326 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2327 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2328 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2329 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2331 /* not mapped as image, need to find the section containing the virtual address */
2332 return RtlImageRvaToVa( nt, module, addr, NULL );
2336 /***********************************************************************
2337 * RtlImageRvaToSection (NTDLL.@)
2339 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2340 HMODULE module, DWORD rva )
2342 int i;
2343 const IMAGE_SECTION_HEADER *sec;
2345 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2346 nt->FileHeader.SizeOfOptionalHeader);
2347 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2349 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2350 return (PIMAGE_SECTION_HEADER)sec;
2352 return NULL;
2356 /***********************************************************************
2357 * RtlImageRvaToVa (NTDLL.@)
2359 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2360 DWORD rva, IMAGE_SECTION_HEADER **section )
2362 IMAGE_SECTION_HEADER *sec;
2364 if (section && *section) /* try this section first */
2366 sec = *section;
2367 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2368 goto found;
2370 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2371 found:
2372 if (section) *section = sec;
2373 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2377 /***********************************************************************
2378 * RtlPcToFileHeader (NTDLL.@)
2380 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2382 LDR_MODULE *module;
2383 PVOID ret = NULL;
2385 RtlEnterCriticalSection( &loader_section );
2386 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2387 RtlLeaveCriticalSection( &loader_section );
2388 *address = ret;
2389 return ret;
2393 /***********************************************************************
2394 * NtLoadDriver (NTDLL.@)
2395 * ZwLoadDriver (NTDLL.@)
2397 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2399 FIXME("(%p), stub!\n",DriverServiceName);
2400 return STATUS_NOT_IMPLEMENTED;
2404 /***********************************************************************
2405 * NtUnloadDriver (NTDLL.@)
2406 * ZwUnloadDriver (NTDLL.@)
2408 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2410 FIXME("(%p), stub!\n",DriverServiceName);
2411 return STATUS_NOT_IMPLEMENTED;
2415 /******************************************************************
2416 * DllMain (NTDLL.@)
2418 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2420 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2421 return TRUE;
2425 /******************************************************************
2426 * __wine_init_windows_dir (NTDLL.@)
2428 * Windows and system dir initialization once kernel32 has been loaded.
2430 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2432 PLIST_ENTRY mark, entry;
2433 LPWSTR buffer, p;
2435 RtlCreateUnicodeString( &windows_dir, windir );
2436 RtlCreateUnicodeString( &system_dir, sysdir );
2437 strcpyW( user_shared_data->NtSystemRoot, windir );
2439 /* prepend the system dir to the name of the already created modules */
2440 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2441 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2443 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2445 assert( mod->Flags & LDR_WINE_INTERNAL );
2447 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2448 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2449 if (!buffer) continue;
2450 strcpyW( buffer, system_dir.Buffer );
2451 p = buffer + strlenW( buffer );
2452 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2453 strcpyW( p, mod->FullDllName.Buffer );
2454 RtlInitUnicodeString( &mod->FullDllName, buffer );
2455 RtlInitUnicodeString( &mod->BaseDllName, p );
2460 /***********************************************************************
2461 * __wine_process_init
2463 void __wine_process_init(void)
2465 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2467 WINE_MODREF *wm;
2468 NTSTATUS status;
2469 ANSI_STRING func_name;
2470 void (* DECLSPEC_NORETURN init_func)(void);
2471 extern mode_t FILE_umask;
2473 main_exe_file = thread_init();
2475 /* retrieve current umask */
2476 FILE_umask = umask(0777);
2477 umask( FILE_umask );
2479 /* setup the load callback and create ntdll modref */
2480 wine_dll_set_callback( load_builtin_callback );
2482 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2484 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2485 exit(1);
2487 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2488 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2489 0, (void **)&init_func )) != STATUS_SUCCESS)
2491 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2492 exit(1);
2494 init_func();