push 97f44e0adb27fff75ba63d8fb97c65db9edfbe82
[wine/hacks.git] / dlls / ntdll / loader.c
blobca1ebdd3608b87b5d1ba496cce1f810a942a2e17
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/pthread.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
43 #include "ntdll_misc.h"
44 #include "ddk/wdm.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module);
47 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 WINE_DECLARE_DEBUG_CHANNEL(snoop);
49 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
50 WINE_DECLARE_DEBUG_CHANNEL(imports);
52 /* we don't want to include winuser.h */
53 #define RT_MANIFEST ((ULONG_PTR)24)
54 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
56 extern struct wine_pthread_functions pthread_functions;
58 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
60 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
61 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
63 static const char * const reason_names[] =
65 "PROCESS_DETACH",
66 "PROCESS_ATTACH",
67 "THREAD_ATTACH",
68 "THREAD_DETACH",
69 NULL, NULL, NULL, NULL,
70 "WINE_PREATTACH"
73 static const WCHAR dllW[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
78 LDR_MODULE ldr;
79 int nDeps;
80 struct _wine_modref **deps;
81 } WINE_MODREF;
83 /* info about the current builtin dll load */
84 /* used to keep track of things across the register_dll constructor call */
85 struct builtin_load_info
87 const WCHAR *load_path;
88 const WCHAR *filename;
89 NTSTATUS status;
90 WINE_MODREF *wm;
93 static struct builtin_load_info default_load_info;
94 static struct builtin_load_info *builtin_load_info = &default_load_info;
96 static HANDLE main_exe_file;
97 static UINT tls_module_count; /* number of modules with TLS directory */
98 static UINT tls_total_size; /* total size of TLS storage */
99 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
101 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
102 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
104 static RTL_CRITICAL_SECTION loader_section;
105 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
107 0, 0, &loader_section,
108 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
109 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
111 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
113 static WINE_MODREF *cached_modref;
114 static WINE_MODREF *current_modref;
115 static WINE_MODREF *last_failed_modref;
117 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
118 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
119 DWORD exp_size, const char *name, int hint );
121 /* convert PE image VirtualAddress to Real Address */
122 static inline void *get_rva( HMODULE module, DWORD va )
124 return (void *)((char *)module + va);
127 /* check whether the file name contains a path */
128 static inline int contains_path( LPCWSTR name )
130 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
133 /* convert from straight ASCII to Unicode without depending on the current codepage */
134 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
136 while (len--) *dst++ = (unsigned char)*src++;
140 /*************************************************************************
141 * call_dll_entry_point
143 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
144 * their entry point, so we need a small asm wrapper.
146 #ifdef __i386__
147 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
148 __ASM_GLOBAL_FUNC(call_dll_entry_point,
149 "pushl %ebp\n\t"
150 "movl %esp,%ebp\n\t"
151 "pushl %ebx\n\t"
152 "subl $8,%esp\n\t"
153 "pushl 20(%ebp)\n\t"
154 "pushl 16(%ebp)\n\t"
155 "pushl 12(%ebp)\n\t"
156 "movl 8(%ebp),%eax\n\t"
157 "call *%eax\n\t"
158 "leal -4(%ebp),%esp\n\t"
159 "popl %ebx\n\t"
160 "popl %ebp\n\t"
161 "ret" )
162 #else /* __i386__ */
163 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
164 UINT reason, void *reserved )
166 return proc( module, reason, reserved );
168 #endif /* __i386__ */
171 #ifdef __i386__
172 /*************************************************************************
173 * stub_entry_point
175 * Entry point for stub functions.
177 static void stub_entry_point( const char *dll, const char *name, ... )
179 EXCEPTION_RECORD rec;
181 rec.ExceptionCode = EXCEPTION_WINE_STUB;
182 rec.ExceptionFlags = EH_NONCONTINUABLE;
183 rec.ExceptionRecord = NULL;
184 #ifdef __GNUC__
185 rec.ExceptionAddress = __builtin_return_address(0);
186 #else
187 rec.ExceptionAddress = *((void **)&dll - 1);
188 #endif
189 rec.NumberParameters = 2;
190 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
191 rec.ExceptionInformation[1] = (ULONG_PTR)name;
192 for (;;) RtlRaiseException( &rec );
196 #include "pshpack1.h"
197 struct stub
199 BYTE popl_eax; /* popl %eax */
200 BYTE pushl1; /* pushl $name */
201 const char *name;
202 BYTE pushl2; /* pushl $dll */
203 const char *dll;
204 BYTE pushl_eax; /* pushl %eax */
205 BYTE jmp; /* jmp stub_entry_point */
206 DWORD entry;
208 #include "poppack.h"
210 /*************************************************************************
211 * allocate_stub
213 * Allocate a stub entry point.
215 static ULONG_PTR allocate_stub( const char *dll, const char *name )
217 #define MAX_SIZE 65536
218 static struct stub *stubs;
219 static unsigned int nb_stubs;
220 struct stub *stub;
222 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
224 if (!stubs)
226 SIZE_T size = MAX_SIZE;
227 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
228 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
229 return 0xdeadbeef;
231 stub = &stubs[nb_stubs++];
232 stub->popl_eax = 0x58; /* popl %eax */
233 stub->pushl1 = 0x68; /* pushl $name */
234 stub->name = name;
235 stub->pushl2 = 0x68; /* pushl $dll */
236 stub->dll = dll;
237 stub->pushl_eax = 0x50; /* pushl %eax */
238 stub->jmp = 0xe9; /* jmp stub_entry_point */
239 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
240 return (ULONG_PTR)stub;
243 #else /* __i386__ */
244 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
245 #endif /* __i386__ */
248 /*************************************************************************
249 * get_modref
251 * Looks for the referenced HMODULE in the current process
252 * The loader_section must be locked while calling this function.
254 static WINE_MODREF *get_modref( HMODULE hmod )
256 PLIST_ENTRY mark, entry;
257 PLDR_MODULE mod;
259 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
261 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
262 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
264 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
265 if (mod->BaseAddress == hmod)
266 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
267 if (mod->BaseAddress > (void*)hmod) break;
269 return NULL;
273 /**********************************************************************
274 * find_basename_module
276 * Find a module from its base name.
277 * The loader_section must be locked while calling this function
279 static WINE_MODREF *find_basename_module( LPCWSTR name )
281 PLIST_ENTRY mark, entry;
283 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
284 return cached_modref;
286 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
287 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
289 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
290 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
292 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
293 return cached_modref;
296 return NULL;
300 /**********************************************************************
301 * find_fullname_module
303 * Find a module from its full path name.
304 * The loader_section must be locked while calling this function
306 static WINE_MODREF *find_fullname_module( LPCWSTR name )
308 PLIST_ENTRY mark, entry;
310 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
311 return cached_modref;
313 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
314 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
316 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
317 if (!strcmpiW( name, mod->FullDllName.Buffer ))
319 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
320 return cached_modref;
323 return NULL;
327 /*************************************************************************
328 * find_forwarded_export
330 * Find the final function pointer for a forwarded function.
331 * The loader_section must be locked while calling this function.
333 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
335 const IMAGE_EXPORT_DIRECTORY *exports;
336 DWORD exp_size;
337 WINE_MODREF *wm;
338 WCHAR mod_name[32];
339 const char *end = strrchr(forward, '.');
340 FARPROC proc = NULL;
342 if (!end) return NULL;
343 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
344 ascii_to_unicode( mod_name, forward, end - forward );
345 mod_name[end - forward] = 0;
346 if (!strchrW( mod_name, '.' ))
348 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
349 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
352 if (!(wm = find_basename_module( mod_name )))
354 ERR("module not found for forward '%s' used by %s\n",
355 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
356 return NULL;
358 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
359 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
360 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
362 if (!proc)
364 ERR("function not found for forward '%s' used by %s."
365 " If you are using builtin %s, try using the native one instead.\n",
366 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
367 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
369 return proc;
373 /*************************************************************************
374 * find_ordinal_export
376 * Find an exported function by ordinal.
377 * The exports base must have been subtracted from the ordinal already.
378 * The loader_section must be locked while calling this function.
380 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
381 DWORD exp_size, DWORD ordinal )
383 FARPROC proc;
384 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
386 if (ordinal >= exports->NumberOfFunctions)
388 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
389 return NULL;
391 if (!functions[ordinal]) return NULL;
393 proc = get_rva( module, functions[ordinal] );
395 /* if the address falls into the export dir, it's a forward */
396 if (((const char *)proc >= (const char *)exports) &&
397 ((const char *)proc < (const char *)exports + exp_size))
398 return find_forwarded_export( module, (const char *)proc );
400 if (TRACE_ON(snoop))
402 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
403 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
405 if (TRACE_ON(relay))
407 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
408 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
410 return proc;
414 /*************************************************************************
415 * find_named_export
417 * Find an exported function by name.
418 * The loader_section must be locked while calling this function.
420 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
421 DWORD exp_size, const char *name, int hint )
423 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
424 const DWORD *names = get_rva( module, exports->AddressOfNames );
425 int min = 0, max = exports->NumberOfNames - 1;
427 /* first check the hint */
428 if (hint >= 0 && hint <= max)
430 char *ename = get_rva( module, names[hint] );
431 if (!strcmp( ename, name ))
432 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
435 /* then do a binary search */
436 while (min <= max)
438 int res, pos = (min + max) / 2;
439 char *ename = get_rva( module, names[pos] );
440 if (!(res = strcmp( ename, name )))
441 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
442 if (res > 0) max = pos - 1;
443 else min = pos + 1;
445 return NULL;
450 /*************************************************************************
451 * import_dll
453 * Import the dll specified by the given import descriptor.
454 * The loader_section must be locked while calling this function.
456 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
458 NTSTATUS status;
459 WINE_MODREF *wmImp;
460 HMODULE imp_mod;
461 const IMAGE_EXPORT_DIRECTORY *exports;
462 DWORD exp_size;
463 const IMAGE_THUNK_DATA *import_list;
464 IMAGE_THUNK_DATA *thunk_list;
465 WCHAR buffer[32];
466 const char *name = get_rva( module, descr->Name );
467 DWORD len = strlen(name);
468 PVOID protect_base;
469 SIZE_T protect_size = 0;
470 DWORD protect_old;
472 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
473 if (descr->u.OriginalFirstThunk)
474 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
475 else
476 import_list = thunk_list;
478 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
480 if (len * sizeof(WCHAR) < sizeof(buffer))
482 ascii_to_unicode( buffer, name, len );
483 buffer[len] = 0;
484 status = load_dll( load_path, buffer, 0, &wmImp );
486 else /* need to allocate a larger buffer */
488 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
489 if (!ptr) return NULL;
490 ascii_to_unicode( ptr, name, len );
491 ptr[len] = 0;
492 status = load_dll( load_path, ptr, 0, &wmImp );
493 RtlFreeHeap( GetProcessHeap(), 0, ptr );
496 if (status)
498 if (status == STATUS_DLL_NOT_FOUND)
499 ERR("Library %s (which is needed by %s) not found\n",
500 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
501 else
502 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
503 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
504 return NULL;
507 /* unprotect the import address table since it can be located in
508 * readonly section */
509 while (import_list[protect_size].u1.Ordinal) protect_size++;
510 protect_base = thunk_list;
511 protect_size *= sizeof(*thunk_list);
512 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
513 &protect_size, PAGE_WRITECOPY, &protect_old );
515 imp_mod = wmImp->ldr.BaseAddress;
516 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
518 if (!exports)
520 /* set all imported function to deadbeef */
521 while (import_list->u1.Ordinal)
523 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
525 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
526 WARN("No implementation for %s.%d", name, ordinal );
527 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
529 else
531 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
532 WARN("No implementation for %s.%s", name, pe_name->Name );
533 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
535 WARN(" imported from %s, allocating stub %p\n",
536 debugstr_w(current_modref->ldr.FullDllName.Buffer),
537 (void *)thunk_list->u1.Function );
538 import_list++;
539 thunk_list++;
541 goto done;
544 while (import_list->u1.Ordinal)
546 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
548 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
550 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
551 ordinal - exports->Base );
552 if (!thunk_list->u1.Function)
554 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
555 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
556 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
557 (void *)thunk_list->u1.Function );
559 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
561 else /* import by name */
563 IMAGE_IMPORT_BY_NAME *pe_name;
564 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
565 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
566 (const char*)pe_name->Name, pe_name->Hint );
567 if (!thunk_list->u1.Function)
569 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
570 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
571 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
572 (void *)thunk_list->u1.Function );
574 TRACE_(imports)("--- %s %s.%d = %p\n",
575 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
577 import_list++;
578 thunk_list++;
581 done:
582 /* restore old protection of the import address table */
583 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
584 return wmImp;
588 /***********************************************************************
589 * create_module_activation_context
591 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
593 NTSTATUS status;
594 LDR_RESOURCE_INFO info;
595 const IMAGE_RESOURCE_DATA_ENTRY *entry;
597 info.Type = RT_MANIFEST;
598 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
599 info.Language = 0;
600 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
602 ACTCTXW ctx;
603 ctx.cbSize = sizeof(ctx);
604 ctx.lpSource = NULL;
605 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
606 ctx.hModule = module->BaseAddress;
607 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
608 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
610 return status;
614 /****************************************************************
615 * fixup_imports
617 * Fixup all imports of a given module.
618 * The loader_section must be locked while calling this function.
620 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
622 int i, nb_imports;
623 const IMAGE_IMPORT_DESCRIPTOR *imports;
624 WINE_MODREF *prev;
625 DWORD size;
626 NTSTATUS status;
627 ULONG_PTR cookie;
629 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
630 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
632 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
633 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
634 return STATUS_SUCCESS;
636 nb_imports = 0;
637 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
639 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
641 if (!create_module_activation_context( &wm->ldr ))
642 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
644 /* Allocate module dependency list */
645 wm->nDeps = nb_imports;
646 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
648 /* load the imported modules. They are automatically
649 * added to the modref list of the process.
651 prev = current_modref;
652 current_modref = wm;
653 status = STATUS_SUCCESS;
654 for (i = 0; i < nb_imports; i++)
656 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
657 status = STATUS_DLL_NOT_FOUND;
659 current_modref = prev;
660 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
661 return status;
665 /*************************************************************************
666 * alloc_module
668 * Allocate a WINE_MODREF structure and add it to the process list
669 * The loader_section must be locked while calling this function.
671 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
673 WINE_MODREF *wm;
674 const WCHAR *p;
675 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
676 PLIST_ENTRY entry, mark;
678 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
680 wm->nDeps = 0;
681 wm->deps = NULL;
683 wm->ldr.BaseAddress = hModule;
684 wm->ldr.EntryPoint = NULL;
685 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
686 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
687 wm->ldr.LoadCount = 1;
688 wm->ldr.TlsIndex = -1;
689 wm->ldr.SectionHandle = NULL;
690 wm->ldr.CheckSum = 0;
691 wm->ldr.TimeDateStamp = 0;
692 wm->ldr.ActivationContext = 0;
694 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
695 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
696 else p = wm->ldr.FullDllName.Buffer;
697 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
699 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
701 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
702 if (nt->OptionalHeader.AddressOfEntryPoint)
703 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
706 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
707 &wm->ldr.InLoadOrderModuleList);
709 /* insert module in MemoryList, sorted in increasing base addresses */
710 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
711 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
713 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
714 break;
716 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
717 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
718 wm->ldr.InMemoryOrderModuleList.Flink = entry;
719 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
721 /* wait until init is called for inserting into this list */
722 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
723 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
725 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
727 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
728 VIRTUAL_SetForceExec( TRUE );
730 return wm;
734 /*************************************************************************
735 * alloc_process_tls
737 * Allocate the process-wide structure for module TLS storage.
739 static NTSTATUS alloc_process_tls(void)
741 PLIST_ENTRY mark, entry;
742 PLDR_MODULE mod;
743 const IMAGE_TLS_DIRECTORY *dir;
744 ULONG size, i;
746 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
747 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
749 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
750 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
751 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
752 continue;
753 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
754 if (!size) continue;
755 tls_total_size += size;
756 tls_module_count++;
758 if (!tls_module_count) return STATUS_SUCCESS;
760 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
762 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
763 if (!tls_dirs) return STATUS_NO_MEMORY;
765 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
767 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
768 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
769 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
770 continue;
771 tls_dirs[i] = dir;
772 *(DWORD *)dir->AddressOfIndex = i;
773 mod->TlsIndex = i;
774 mod->LoadCount = -1; /* can't unload it */
775 i++;
777 return STATUS_SUCCESS;
781 /*************************************************************************
782 * alloc_thread_tls
784 * Allocate the per-thread structure for module TLS storage.
786 static NTSTATUS alloc_thread_tls(void)
788 void **pointers;
789 char *data;
790 UINT i;
792 if (!tls_module_count) return STATUS_SUCCESS;
794 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
795 tls_module_count * sizeof(*pointers) )))
796 return STATUS_NO_MEMORY;
798 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
800 RtlFreeHeap( GetProcessHeap(), 0, pointers );
801 return STATUS_NO_MEMORY;
804 for (i = 0; i < tls_module_count; i++)
806 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
807 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
809 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
810 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
811 (void *)dir->StartAddressOfRawData, data );
813 pointers[i] = data;
814 memcpy( data, (void *)dir->StartAddressOfRawData, size );
815 data += size;
816 memset( data, 0, dir->SizeOfZeroFill );
817 data += dir->SizeOfZeroFill;
819 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
820 return STATUS_SUCCESS;
824 /*************************************************************************
825 * call_tls_callbacks
827 static void call_tls_callbacks( HMODULE module, UINT reason )
829 const IMAGE_TLS_DIRECTORY *dir;
830 const PIMAGE_TLS_CALLBACK *callback;
831 ULONG dirsize;
833 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
834 if (!dir || !dir->AddressOfCallBacks) return;
836 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
838 if (TRACE_ON(relay))
839 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
840 GetCurrentThreadId(), *callback, module, reason_names[reason] );
841 __TRY
843 (*callback)( module, reason, NULL );
845 __EXCEPT(NULL)
847 if (TRACE_ON(relay))
848 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
849 GetCurrentThreadId(), callback, module, reason_names[reason] );
850 return;
852 __ENDTRY
853 if (TRACE_ON(relay))
854 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
855 GetCurrentThreadId(), *callback, module, reason_names[reason] );
860 /*************************************************************************
861 * MODULE_InitDLL
863 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
865 WCHAR mod_name[32];
866 BOOL retv = TRUE;
867 DLLENTRYPROC entry = wm->ldr.EntryPoint;
868 void *module = wm->ldr.BaseAddress;
870 /* Skip calls for modules loaded with special load flags */
872 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
873 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
874 if (!entry) return TRUE;
876 if (TRACE_ON(relay))
878 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
879 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
880 mod_name[len / sizeof(WCHAR)] = 0;
881 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
882 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
883 reason_names[reason], lpReserved );
885 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
886 reason_names[reason], lpReserved );
888 retv = call_dll_entry_point( entry, module, reason, lpReserved );
890 /* The state of the module list may have changed due to the call
891 to the dll. We cannot assume that this module has not been
892 deleted. */
893 if (TRACE_ON(relay))
894 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
895 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
896 reason_names[reason], lpReserved, retv );
897 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
899 return retv;
903 /*************************************************************************
904 * process_attach
906 * Send the process attach notification to all DLLs the given module
907 * depends on (recursively). This is somewhat complicated due to the fact that
909 * - we have to respect the module dependencies, i.e. modules implicitly
910 * referenced by another module have to be initialized before the module
911 * itself can be initialized
913 * - the initialization routine of a DLL can itself call LoadLibrary,
914 * thereby introducing a whole new set of dependencies (even involving
915 * the 'old' modules) at any time during the whole process
917 * (Note that this routine can be recursively entered not only directly
918 * from itself, but also via LoadLibrary from one of the called initialization
919 * routines.)
921 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
922 * the process *detach* notifications to be sent in the correct order.
923 * This must not only take into account module dependencies, but also
924 * 'hidden' dependencies created by modules calling LoadLibrary in their
925 * attach notification routine.
927 * The strategy is rather simple: we move a WINE_MODREF to the head of the
928 * list after the attach notification has returned. This implies that the
929 * detach notifications are called in the reverse of the sequence the attach
930 * notifications *returned*.
932 * The loader_section must be locked while calling this function.
934 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
936 NTSTATUS status = STATUS_SUCCESS;
937 ULONG_PTR cookie;
938 int i;
940 if (process_detaching) return status;
942 /* prevent infinite recursion in case of cyclical dependencies */
943 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
944 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
945 return status;
947 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
949 /* Tag current MODREF to prevent recursive loop */
950 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
951 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
952 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
954 /* Recursively attach all DLLs this one depends on */
955 for ( i = 0; i < wm->nDeps; i++ )
957 if (!wm->deps[i]) continue;
958 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
961 /* Call DLL entry point */
962 if (status == STATUS_SUCCESS)
964 WINE_MODREF *prev = current_modref;
965 current_modref = wm;
966 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
968 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
970 else
972 /* point to the name so LdrInitializeThunk can print it */
973 last_failed_modref = wm;
974 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
975 status = STATUS_DLL_INIT_FAILED;
977 current_modref = prev;
980 if (!wm->ldr.InInitializationOrderModuleList.Flink)
981 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
982 &wm->ldr.InInitializationOrderModuleList);
984 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
985 /* Remove recursion flag */
986 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
988 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
989 return status;
993 /**********************************************************************
994 * attach_implicitly_loaded_dlls
996 * Attach to the (builtin) dlls that have been implicitly loaded because
997 * of a dependency at the Unix level, but not imported at the Win32 level.
999 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1001 for (;;)
1003 PLIST_ENTRY mark, entry;
1005 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1006 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1008 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1010 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1011 TRACE( "found implicitly loaded %s, attaching to it\n",
1012 debugstr_w(mod->BaseDllName.Buffer));
1013 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1014 break; /* restart the search from the start */
1016 if (entry == mark) break; /* nothing found */
1021 /*************************************************************************
1022 * process_detach
1024 * Send DLL process detach notifications. See the comment about calling
1025 * sequence at process_attach. Unless the bForceDetach flag
1026 * is set, only DLLs with zero refcount are notified.
1028 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1030 PLIST_ENTRY mark, entry;
1031 PLDR_MODULE mod;
1033 RtlEnterCriticalSection( &loader_section );
1034 if (bForceDetach) process_detaching = 1;
1035 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1038 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1040 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1041 InInitializationOrderModuleList);
1042 /* Check whether to detach this DLL */
1043 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1044 continue;
1045 if ( mod->LoadCount && !bForceDetach )
1046 continue;
1048 /* Call detach notification */
1049 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1050 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1051 DLL_PROCESS_DETACH, lpReserved );
1053 /* Restart at head of WINE_MODREF list, as entries might have
1054 been added and/or removed while performing the call ... */
1055 break;
1057 } while (entry != mark);
1059 RtlLeaveCriticalSection( &loader_section );
1062 /*************************************************************************
1063 * MODULE_DllThreadAttach
1065 * Send DLL thread attach notifications. These are sent in the
1066 * reverse sequence of process detach notification.
1069 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1071 PLIST_ENTRY mark, entry;
1072 PLDR_MODULE mod;
1073 NTSTATUS status;
1075 /* don't do any attach calls if process is exiting */
1076 if (process_detaching) return STATUS_SUCCESS;
1077 /* FIXME: there is still a race here */
1079 RtlEnterCriticalSection( &loader_section );
1081 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1083 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1084 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1086 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1087 InInitializationOrderModuleList);
1088 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1089 continue;
1090 if ( mod->Flags & LDR_NO_DLL_CALLS )
1091 continue;
1093 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1094 DLL_THREAD_ATTACH, lpReserved );
1097 done:
1098 RtlLeaveCriticalSection( &loader_section );
1099 return status;
1102 /******************************************************************
1103 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1106 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1108 WINE_MODREF *wm;
1109 NTSTATUS ret = STATUS_SUCCESS;
1111 RtlEnterCriticalSection( &loader_section );
1113 wm = get_modref( hModule );
1114 if (!wm || wm->ldr.TlsIndex != -1)
1115 ret = STATUS_DLL_NOT_FOUND;
1116 else
1117 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1119 RtlLeaveCriticalSection( &loader_section );
1121 return ret;
1124 /******************************************************************
1125 * LdrFindEntryForAddress (NTDLL.@)
1127 * The loader_section must be locked while calling this function
1129 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1131 PLIST_ENTRY mark, entry;
1132 PLDR_MODULE mod;
1134 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1135 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1137 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1138 if ((const void *)mod->BaseAddress <= addr &&
1139 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1141 *pmod = mod;
1142 return STATUS_SUCCESS;
1144 if ((const void *)mod->BaseAddress > addr) break;
1146 return STATUS_NO_MORE_ENTRIES;
1149 /******************************************************************
1150 * LdrLockLoaderLock (NTDLL.@)
1152 * Note: flags are not implemented.
1153 * Flag 0x01 is used to raise exceptions on errors.
1154 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1156 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1158 if (flags) FIXME( "flags %x not supported\n", flags );
1160 if (result) *result = 1;
1161 if (!magic) return STATUS_INVALID_PARAMETER_3;
1162 RtlEnterCriticalSection( &loader_section );
1163 *magic = GetCurrentThreadId();
1164 return STATUS_SUCCESS;
1168 /******************************************************************
1169 * LdrUnlockLoaderUnlock (NTDLL.@)
1171 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1173 if (magic)
1175 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1176 RtlLeaveCriticalSection( &loader_section );
1178 return STATUS_SUCCESS;
1182 /******************************************************************
1183 * LdrGetProcedureAddress (NTDLL.@)
1185 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1186 ULONG ord, PVOID *address)
1188 IMAGE_EXPORT_DIRECTORY *exports;
1189 DWORD exp_size;
1190 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1192 RtlEnterCriticalSection( &loader_section );
1194 /* check if the module itself is invalid to return the proper error */
1195 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1196 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1197 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1199 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1200 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1201 if (proc)
1203 *address = proc;
1204 ret = STATUS_SUCCESS;
1208 RtlLeaveCriticalSection( &loader_section );
1209 return ret;
1213 /***********************************************************************
1214 * is_fake_dll
1216 * Check if a loaded native dll is a Wine fake dll.
1218 static BOOL is_fake_dll( const void *base )
1220 static const char fakedll_signature[] = "Wine placeholder DLL";
1221 const IMAGE_DOS_HEADER *dos = base;
1223 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1224 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1225 return FALSE;
1229 /***********************************************************************
1230 * get_builtin_fullname
1232 * Build the full pathname for a builtin dll.
1234 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1236 static const WCHAR soW[] = {'.','s','o',0};
1237 WCHAR *p, *fullname;
1238 size_t i, len = strlen(filename);
1240 /* check if path can correspond to the dll we have */
1241 if (path && (p = strrchrW( path, '\\' )))
1243 p++;
1244 for (i = 0; i < len; i++)
1245 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1246 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1248 /* the filename matches, use path as the full path */
1249 len += p - path;
1250 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1252 memcpy( fullname, path, len * sizeof(WCHAR) );
1253 fullname[len] = 0;
1255 return fullname;
1259 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1260 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1262 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1263 p = fullname + system_dir.Length / sizeof(WCHAR);
1264 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1265 ascii_to_unicode( p, filename, len + 1 );
1267 return fullname;
1271 /***********************************************************************
1272 * load_builtin_callback
1274 * Load a library in memory; callback function for wine_dll_register
1276 static void load_builtin_callback( void *module, const char *filename )
1278 static const WCHAR emptyW[1];
1279 void *addr;
1280 IMAGE_NT_HEADERS *nt;
1281 WINE_MODREF *wm;
1282 WCHAR *fullname;
1283 const WCHAR *load_path;
1284 SIZE_T size;
1286 if (!module)
1288 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1289 return;
1291 if (!(nt = RtlImageNtHeader( module )))
1293 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1294 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1295 return;
1297 addr = module;
1298 size = nt->OptionalHeader.SizeOfImage;
1299 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1300 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1301 /* create the MODREF */
1303 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1305 ERR( "can't load %s\n", filename );
1306 builtin_load_info->status = STATUS_NO_MEMORY;
1307 return;
1310 wm = alloc_module( module, fullname );
1311 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1312 if (!wm)
1314 ERR( "can't load %s\n", filename );
1315 builtin_load_info->status = STATUS_NO_MEMORY;
1316 return;
1318 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1320 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1321 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1323 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1325 else
1327 /* fixup imports */
1329 load_path = builtin_load_info->load_path;
1330 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1331 if (!load_path) load_path = emptyW;
1332 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1334 /* the module has only be inserted in the load & memory order lists */
1335 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1336 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1337 /* FIXME: free the modref */
1338 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1339 return;
1343 builtin_load_info->wm = wm;
1344 TRACE( "loaded %s %p %p\n", filename, wm, module );
1346 /* send the DLL load event */
1348 SERVER_START_REQ( load_dll )
1350 req->handle = 0;
1351 req->base = module;
1352 req->size = nt->OptionalHeader.SizeOfImage;
1353 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1354 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1355 req->name = &wm->ldr.FullDllName.Buffer;
1356 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1357 wine_server_call( req );
1359 SERVER_END_REQ;
1361 /* setup relay debugging entry points */
1362 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1366 /******************************************************************************
1367 * load_native_dll (internal)
1369 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1370 DWORD flags, WINE_MODREF** pwm )
1372 void *module;
1373 HANDLE mapping;
1374 OBJECT_ATTRIBUTES attr;
1375 LARGE_INTEGER size;
1376 IMAGE_NT_HEADERS *nt;
1377 SIZE_T len = 0;
1378 WINE_MODREF *wm;
1379 NTSTATUS status;
1381 TRACE("Trying native dll %s\n", debugstr_w(name));
1383 attr.Length = sizeof(attr);
1384 attr.RootDirectory = 0;
1385 attr.ObjectName = NULL;
1386 attr.Attributes = 0;
1387 attr.SecurityDescriptor = NULL;
1388 attr.SecurityQualityOfService = NULL;
1389 size.QuadPart = 0;
1391 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1392 &attr, &size, 0, SEC_IMAGE, file );
1393 if (status != STATUS_SUCCESS) return status;
1395 module = NULL;
1396 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1397 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1398 NtClose( mapping );
1399 if (status != STATUS_SUCCESS) return status;
1401 if (is_fake_dll( module ))
1403 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1404 NtUnmapViewOfSection( NtCurrentProcess(), module );
1405 return STATUS_DLL_NOT_FOUND;
1408 /* create the MODREF */
1410 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1412 /* fixup imports */
1414 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1416 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1418 /* the module has only be inserted in the load & memory order lists */
1419 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1420 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1422 /* FIXME: there are several more dangling references
1423 * left. Including dlls loaded by this dll before the
1424 * failed one. Unrolling is rather difficult with the
1425 * current structure and we can leave them lying
1426 * around with no problems, so we don't care.
1427 * As these might reference our wm, we don't free it.
1429 return status;
1433 /* send DLL load event */
1435 nt = RtlImageNtHeader( module );
1437 SERVER_START_REQ( load_dll )
1439 req->handle = file;
1440 req->base = module;
1441 req->size = nt->OptionalHeader.SizeOfImage;
1442 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1443 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1444 req->name = &wm->ldr.FullDllName.Buffer;
1445 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1446 wine_server_call( req );
1448 SERVER_END_REQ;
1450 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1452 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1454 wm->ldr.LoadCount = 1;
1455 *pwm = wm;
1456 return STATUS_SUCCESS;
1460 /***********************************************************************
1461 * load_builtin_dll
1463 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1464 DWORD flags, WINE_MODREF** pwm )
1466 char error[256], dllname[MAX_PATH];
1467 const WCHAR *name, *p;
1468 DWORD len, i;
1469 void *handle = NULL;
1470 struct builtin_load_info info, *prev_info;
1472 /* Fix the name in case we have a full path and extension */
1473 name = path;
1474 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1475 if ((p = strrchrW( name, '/' ))) name = p + 1;
1477 /* load_library will modify info.status. Note also that load_library can be
1478 * called several times, if the .so file we're loading has dependencies.
1479 * info.status will gather all the errors we may get while loading all these
1480 * libraries
1482 info.load_path = load_path;
1483 info.filename = NULL;
1484 info.status = STATUS_SUCCESS;
1485 info.wm = NULL;
1487 if (file) /* we have a real file, try to load it */
1489 UNICODE_STRING nt_name;
1490 ANSI_STRING unix_name;
1492 TRACE("Trying built-in %s\n", debugstr_w(path));
1494 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1495 return STATUS_DLL_NOT_FOUND;
1497 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1499 RtlFreeUnicodeString( &nt_name );
1500 return STATUS_DLL_NOT_FOUND;
1502 prev_info = builtin_load_info;
1503 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1504 builtin_load_info = &info;
1505 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1506 builtin_load_info = prev_info;
1507 RtlFreeUnicodeString( &nt_name );
1508 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1509 if (!handle)
1511 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1512 return STATUS_INVALID_IMAGE_FORMAT;
1515 else
1517 int file_exists;
1519 TRACE("Trying built-in %s\n", debugstr_w(name));
1521 /* we don't want to depend on the current codepage here */
1522 len = strlenW( name ) + 1;
1523 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1524 for (i = 0; i < len; i++)
1526 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1527 dllname[i] = (char)name[i];
1528 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1531 prev_info = builtin_load_info;
1532 builtin_load_info = &info;
1533 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1534 builtin_load_info = prev_info;
1535 if (!handle)
1537 if (!file_exists)
1539 /* The file does not exist -> WARN() */
1540 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1541 return STATUS_DLL_NOT_FOUND;
1543 /* ERR() for all other errors (missing functions, ...) */
1544 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1545 return STATUS_PROCEDURE_NOT_FOUND;
1549 if (info.status != STATUS_SUCCESS)
1551 wine_dll_unload( handle );
1552 return info.status;
1555 if (!info.wm)
1557 PLIST_ENTRY mark, entry;
1559 /* The constructor wasn't called, this means the .so is already
1560 * loaded under a different name. Try to find the wm for it. */
1562 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1563 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1565 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1566 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1568 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1569 TRACE( "Found %s at %p for builtin %s\n",
1570 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1571 break;
1574 wine_dll_unload( handle ); /* release the libdl refcount */
1575 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1576 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1578 else
1580 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1581 info.wm->ldr.LoadCount = 1;
1582 info.wm->ldr.SectionHandle = handle;
1585 *pwm = info.wm;
1586 return STATUS_SUCCESS;
1590 /***********************************************************************
1591 * find_actctx_dll
1593 * Find the full path (if any) of the dll from the activation context.
1595 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1597 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1598 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1600 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1601 ACTCTX_SECTION_KEYED_DATA data;
1602 UNICODE_STRING nameW;
1603 NTSTATUS status;
1604 SIZE_T needed, size = 1024;
1605 WCHAR *p;
1607 RtlInitUnicodeString( &nameW, libname );
1608 data.cbSize = sizeof(data);
1609 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1610 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1611 &nameW, &data );
1612 if (status != STATUS_SUCCESS) return status;
1614 for (;;)
1616 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1618 status = STATUS_NO_MEMORY;
1619 goto done;
1621 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1622 AssemblyDetailedInformationInActivationContext,
1623 info, size, &needed );
1624 if (status == STATUS_SUCCESS) break;
1625 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1626 RtlFreeHeap( GetProcessHeap(), 0, info );
1627 size = needed;
1628 /* restart with larger buffer */
1631 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1633 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1635 p++;
1636 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1638 /* manifest name does not match directory name, so it's not a global
1639 * windows/winsxs manifest; use the manifest directory name instead */
1640 dirlen = p - info->lpAssemblyManifestPath;
1641 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1642 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1644 status = STATUS_NO_MEMORY;
1645 goto done;
1647 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1648 p += dirlen;
1649 strcpyW( p, libname );
1650 goto done;
1654 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1655 nameW.Length + 2*sizeof(WCHAR));
1657 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1659 status = STATUS_NO_MEMORY;
1660 goto done;
1662 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1663 p += windows_dir.Length / sizeof(WCHAR);
1664 memcpy( p, winsxsW, sizeof(winsxsW) );
1665 p += sizeof(winsxsW) / sizeof(WCHAR);
1666 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1667 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1668 *p++ = '\\';
1669 strcpyW( p, libname );
1670 done:
1671 RtlFreeHeap( GetProcessHeap(), 0, info );
1672 RtlReleaseActivationContext( data.hActCtx );
1673 return status;
1677 /***********************************************************************
1678 * find_dll_file
1680 * Find the file (or already loaded module) for a given dll name.
1682 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1683 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1685 OBJECT_ATTRIBUTES attr;
1686 IO_STATUS_BLOCK io;
1687 UNICODE_STRING nt_name;
1688 WCHAR *file_part, *ext, *dllname;
1689 ULONG len;
1691 /* first append .dll if needed */
1693 dllname = NULL;
1694 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1696 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1697 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1698 return STATUS_NO_MEMORY;
1699 strcpyW( dllname, libname );
1700 strcatW( dllname, dllW );
1701 libname = dllname;
1704 nt_name.Buffer = NULL;
1706 if (!contains_path( libname ))
1708 NTSTATUS status;
1709 WCHAR *fullname = NULL;
1711 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1713 status = find_actctx_dll( libname, &fullname );
1714 if (status == STATUS_SUCCESS)
1716 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1717 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1718 libname = dllname = fullname;
1720 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1722 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1723 return status;
1727 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1729 /* we need to search for it */
1730 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1731 if (len)
1733 if (len >= *size) goto overflow;
1734 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1736 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1738 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1739 return STATUS_NO_MEMORY;
1741 attr.Length = sizeof(attr);
1742 attr.RootDirectory = 0;
1743 attr.Attributes = OBJ_CASE_INSENSITIVE;
1744 attr.ObjectName = &nt_name;
1745 attr.SecurityDescriptor = NULL;
1746 attr.SecurityQualityOfService = NULL;
1747 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1748 goto found;
1751 /* not found */
1753 if (!contains_path( libname ))
1755 /* if libname doesn't contain a path at all, we simply return the name as is,
1756 * to be loaded as builtin */
1757 len = strlenW(libname) * sizeof(WCHAR);
1758 if (len >= *size) goto overflow;
1759 strcpyW( filename, libname );
1760 goto found;
1764 /* absolute path name, or relative path name but not found above */
1766 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1768 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1769 return STATUS_NO_MEMORY;
1771 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1772 if (len >= *size) goto overflow;
1773 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1774 if (!(*pwm = find_fullname_module( filename )) && handle)
1776 attr.Length = sizeof(attr);
1777 attr.RootDirectory = 0;
1778 attr.Attributes = OBJ_CASE_INSENSITIVE;
1779 attr.ObjectName = &nt_name;
1780 attr.SecurityDescriptor = NULL;
1781 attr.SecurityQualityOfService = NULL;
1782 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1784 found:
1785 RtlFreeUnicodeString( &nt_name );
1786 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1787 return STATUS_SUCCESS;
1789 overflow:
1790 RtlFreeUnicodeString( &nt_name );
1791 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1792 *size = len + sizeof(WCHAR);
1793 return STATUS_BUFFER_TOO_SMALL;
1797 /***********************************************************************
1798 * load_dll (internal)
1800 * Load a PE style module according to the load order.
1801 * The loader_section must be locked while calling this function.
1803 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1805 enum loadorder loadorder;
1806 WCHAR buffer[32];
1807 WCHAR *filename;
1808 ULONG size;
1809 WINE_MODREF *main_exe;
1810 HANDLE handle = 0;
1811 NTSTATUS nts;
1813 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1815 filename = buffer;
1816 size = sizeof(buffer);
1817 for (;;)
1819 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1820 if (nts == STATUS_SUCCESS) break;
1821 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1822 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1823 /* grow the buffer and retry */
1824 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1827 if (*pwm) /* found already loaded module */
1829 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1831 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1833 TRACE("Found %s for %s at %p, count=%d\n",
1834 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1835 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1836 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1837 return STATUS_SUCCESS;
1840 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1841 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1843 switch(loadorder)
1845 case LO_INVALID:
1846 nts = STATUS_NO_MEMORY;
1847 break;
1848 case LO_DISABLED:
1849 nts = STATUS_DLL_NOT_FOUND;
1850 break;
1851 case LO_NATIVE:
1852 case LO_NATIVE_BUILTIN:
1853 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1854 else
1856 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1857 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1858 /* not in PE format, maybe it's a builtin */
1859 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1861 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1862 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1863 break;
1864 case LO_BUILTIN:
1865 case LO_BUILTIN_NATIVE:
1866 case LO_DEFAULT: /* default is builtin,native */
1867 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1868 if (!handle) break; /* nothing else we can try */
1869 /* file is not a builtin library, try without using the specified file */
1870 if (nts != STATUS_SUCCESS)
1871 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1872 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1873 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1875 /* stub-only dll, try native */
1876 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1877 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1878 nts = STATUS_DLL_NOT_FOUND;
1880 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1881 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1882 break;
1885 if (nts == STATUS_SUCCESS)
1887 /* Initialize DLL just loaded */
1888 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1889 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1890 (*pwm)->ldr.BaseAddress);
1891 if (handle) NtClose( handle );
1892 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1893 return nts;
1896 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1897 if (handle) NtClose( handle );
1898 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1899 return nts;
1902 /******************************************************************
1903 * LdrLoadDll (NTDLL.@)
1905 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1906 const UNICODE_STRING *libname, HMODULE* hModule)
1908 WINE_MODREF *wm;
1909 NTSTATUS nts;
1911 RtlEnterCriticalSection( &loader_section );
1913 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1914 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1916 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1918 nts = process_attach( wm, NULL );
1919 if (nts != STATUS_SUCCESS)
1921 LdrUnloadDll(wm->ldr.BaseAddress);
1922 wm = NULL;
1925 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1927 RtlLeaveCriticalSection( &loader_section );
1928 return nts;
1932 /******************************************************************
1933 * LdrGetDllHandle (NTDLL.@)
1935 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1937 NTSTATUS status;
1938 WCHAR buffer[128];
1939 WCHAR *filename;
1940 ULONG size;
1941 WINE_MODREF *wm;
1943 RtlEnterCriticalSection( &loader_section );
1945 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1947 filename = buffer;
1948 size = sizeof(buffer);
1949 for (;;)
1951 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1952 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1953 if (status != STATUS_BUFFER_TOO_SMALL) break;
1954 /* grow the buffer and retry */
1955 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1957 status = STATUS_NO_MEMORY;
1958 break;
1962 if (status == STATUS_SUCCESS)
1964 if (wm) *base = wm->ldr.BaseAddress;
1965 else status = STATUS_DLL_NOT_FOUND;
1968 RtlLeaveCriticalSection( &loader_section );
1969 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1970 return status;
1974 /******************************************************************
1975 * LdrAddRefDll (NTDLL.@)
1977 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1979 NTSTATUS ret = STATUS_SUCCESS;
1980 WINE_MODREF *wm;
1982 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
1984 RtlEnterCriticalSection( &loader_section );
1986 if ((wm = get_modref( module )))
1988 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
1989 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1991 else ret = STATUS_INVALID_PARAMETER;
1993 RtlLeaveCriticalSection( &loader_section );
1994 return ret;
1998 /******************************************************************
1999 * LdrQueryProcessModuleInformation
2002 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2003 ULONG buf_size, ULONG* req_size)
2005 SYSTEM_MODULE* sm = &smi->Modules[0];
2006 ULONG size = sizeof(ULONG);
2007 NTSTATUS nts = STATUS_SUCCESS;
2008 ANSI_STRING str;
2009 char* ptr;
2010 PLIST_ENTRY mark, entry;
2011 PLDR_MODULE mod;
2012 WORD id = 0;
2014 smi->ModulesCount = 0;
2016 RtlEnterCriticalSection( &loader_section );
2017 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2018 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2020 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2021 size += sizeof(*sm);
2022 if (size <= buf_size)
2024 sm->Reserved1 = 0; /* FIXME */
2025 sm->Reserved2 = 0; /* FIXME */
2026 sm->ImageBaseAddress = mod->BaseAddress;
2027 sm->ImageSize = mod->SizeOfImage;
2028 sm->Flags = mod->Flags;
2029 sm->Id = id++;
2030 sm->Rank = 0; /* FIXME */
2031 sm->Unknown = 0; /* FIXME */
2032 str.Length = 0;
2033 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2034 str.Buffer = (char*)sm->Name;
2035 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2036 ptr = strrchr(str.Buffer, '\\');
2037 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2039 smi->ModulesCount++;
2040 sm++;
2042 else nts = STATUS_INFO_LENGTH_MISMATCH;
2044 RtlLeaveCriticalSection( &loader_section );
2046 if (req_size) *req_size = size;
2048 return nts;
2052 /******************************************************************
2053 * RtlDllShutdownInProgress (NTDLL.@)
2055 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2057 return process_detaching;
2061 /******************************************************************
2062 * LdrShutdownProcess (NTDLL.@)
2065 void WINAPI LdrShutdownProcess(void)
2067 TRACE("()\n");
2068 process_detach( TRUE, (LPVOID)1 );
2071 /******************************************************************
2072 * LdrShutdownThread (NTDLL.@)
2075 void WINAPI LdrShutdownThread(void)
2077 PLIST_ENTRY mark, entry;
2078 PLDR_MODULE mod;
2080 TRACE("()\n");
2082 /* don't do any detach calls if process is exiting */
2083 if (process_detaching) return;
2084 /* FIXME: there is still a race here */
2086 RtlEnterCriticalSection( &loader_section );
2088 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2089 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2091 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2092 InInitializationOrderModuleList);
2093 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2094 continue;
2095 if ( mod->Flags & LDR_NO_DLL_CALLS )
2096 continue;
2098 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2099 DLL_THREAD_DETACH, NULL );
2102 RtlLeaveCriticalSection( &loader_section );
2103 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2107 /***********************************************************************
2108 * free_modref
2111 static void free_modref( WINE_MODREF *wm )
2113 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2114 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2115 if (wm->ldr.InInitializationOrderModuleList.Flink)
2116 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2118 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2119 if (!TRACE_ON(module))
2120 TRACE_(loaddll)("Unloaded module %s : %s\n",
2121 debugstr_w(wm->ldr.FullDllName.Buffer),
2122 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2124 SERVER_START_REQ( unload_dll )
2126 req->base = wm->ldr.BaseAddress;
2127 wine_server_call( req );
2129 SERVER_END_REQ;
2131 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2132 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2133 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2134 if (cached_modref == wm) cached_modref = NULL;
2135 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2136 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2137 RtlFreeHeap( GetProcessHeap(), 0, wm );
2140 /***********************************************************************
2141 * MODULE_FlushModrefs
2143 * Remove all unused modrefs and call the internal unloading routines
2144 * for the library type.
2146 * The loader_section must be locked while calling this function.
2148 static void MODULE_FlushModrefs(void)
2150 PLIST_ENTRY mark, entry, prev;
2151 PLDR_MODULE mod;
2152 WINE_MODREF*wm;
2154 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2155 for (entry = mark->Blink; entry != mark; entry = prev)
2157 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2158 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2159 prev = entry->Blink;
2160 if (!mod->LoadCount) free_modref( wm );
2163 /* check load order list too for modules that haven't been initialized yet */
2164 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2165 for (entry = mark->Blink; entry != mark; entry = prev)
2167 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2168 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2169 prev = entry->Blink;
2170 if (!mod->LoadCount) free_modref( wm );
2174 /***********************************************************************
2175 * MODULE_DecRefCount
2177 * The loader_section must be locked while calling this function.
2179 static void MODULE_DecRefCount( WINE_MODREF *wm )
2181 int i;
2183 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2184 return;
2186 if ( wm->ldr.LoadCount <= 0 )
2187 return;
2189 --wm->ldr.LoadCount;
2190 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2192 if ( wm->ldr.LoadCount == 0 )
2194 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2196 for ( i = 0; i < wm->nDeps; i++ )
2197 if ( wm->deps[i] )
2198 MODULE_DecRefCount( wm->deps[i] );
2200 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2204 /******************************************************************
2205 * LdrUnloadDll (NTDLL.@)
2209 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2211 NTSTATUS retv = STATUS_SUCCESS;
2213 TRACE("(%p)\n", hModule);
2215 RtlEnterCriticalSection( &loader_section );
2217 /* if we're stopping the whole process (and forcing the removal of all
2218 * DLLs) the library will be freed anyway
2220 if (!process_detaching)
2222 WINE_MODREF *wm;
2224 free_lib_count++;
2225 if ((wm = get_modref( hModule )) != NULL)
2227 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2229 /* Recursively decrement reference counts */
2230 MODULE_DecRefCount( wm );
2232 /* Call process detach notifications */
2233 if ( free_lib_count <= 1 )
2235 process_detach( FALSE, NULL );
2236 MODULE_FlushModrefs();
2239 TRACE("END\n");
2241 else
2242 retv = STATUS_DLL_NOT_FOUND;
2244 free_lib_count--;
2247 RtlLeaveCriticalSection( &loader_section );
2249 return retv;
2252 /***********************************************************************
2253 * RtlImageNtHeader (NTDLL.@)
2255 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2257 IMAGE_NT_HEADERS *ret;
2259 __TRY
2261 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2263 ret = NULL;
2264 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2266 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2267 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2270 __EXCEPT_PAGE_FAULT
2272 return NULL;
2274 __ENDTRY
2275 return ret;
2279 /******************************************************************
2280 * LdrInitializeThunk (NTDLL.@)
2283 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2285 NTSTATUS status;
2286 WINE_MODREF *wm;
2287 LPCWSTR load_path;
2288 PEB *peb = NtCurrentTeb()->Peb;
2289 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2291 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2293 /* allocate the modref for the main exe (if not already done) */
2294 wm = get_modref( peb->ImageBaseAddress );
2295 assert( wm );
2296 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2298 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2299 exit(1);
2302 peb->LoaderLock = &loader_section;
2303 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2304 version_init( wm->ldr.FullDllName.Buffer );
2306 /* the main exe needs to be the first in the load order list */
2307 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2308 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2310 status = server_init_process_done();
2311 if (status != STATUS_SUCCESS) goto error;
2313 RtlEnterCriticalSection( &loader_section );
2315 actctx_init();
2316 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2317 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2318 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2319 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2321 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2323 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2325 if (last_failed_modref)
2326 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2327 goto error;
2329 attach_implicitly_loaded_dlls( (LPVOID)1 );
2331 RtlLeaveCriticalSection( &loader_section );
2333 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2334 return;
2336 error:
2337 ERR( "Main exe initialization for %s failed, status %x\n",
2338 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2339 NtTerminateProcess( GetCurrentProcess(), status );
2343 /***********************************************************************
2344 * RtlImageDirectoryEntryToData (NTDLL.@)
2346 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2348 const IMAGE_NT_HEADERS *nt;
2349 DWORD addr;
2351 if ((ULONG_PTR)module & 1) /* mapped as data file */
2353 module = (HMODULE)((ULONG_PTR)module & ~1);
2354 image = FALSE;
2356 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2357 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2358 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2359 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2360 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2362 /* not mapped as image, need to find the section containing the virtual address */
2363 return RtlImageRvaToVa( nt, module, addr, NULL );
2367 /***********************************************************************
2368 * RtlImageRvaToSection (NTDLL.@)
2370 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2371 HMODULE module, DWORD rva )
2373 int i;
2374 const IMAGE_SECTION_HEADER *sec;
2376 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2377 nt->FileHeader.SizeOfOptionalHeader);
2378 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2380 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2381 return (PIMAGE_SECTION_HEADER)sec;
2383 return NULL;
2387 /***********************************************************************
2388 * RtlImageRvaToVa (NTDLL.@)
2390 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2391 DWORD rva, IMAGE_SECTION_HEADER **section )
2393 IMAGE_SECTION_HEADER *sec;
2395 if (section && *section) /* try this section first */
2397 sec = *section;
2398 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2399 goto found;
2401 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2402 found:
2403 if (section) *section = sec;
2404 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2408 /***********************************************************************
2409 * RtlPcToFileHeader (NTDLL.@)
2411 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2413 LDR_MODULE *module;
2414 PVOID ret = NULL;
2416 RtlEnterCriticalSection( &loader_section );
2417 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2418 RtlLeaveCriticalSection( &loader_section );
2419 *address = ret;
2420 return ret;
2424 /***********************************************************************
2425 * NtLoadDriver (NTDLL.@)
2426 * ZwLoadDriver (NTDLL.@)
2428 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2430 FIXME("(%p), stub!\n",DriverServiceName);
2431 return STATUS_NOT_IMPLEMENTED;
2435 /***********************************************************************
2436 * NtUnloadDriver (NTDLL.@)
2437 * ZwUnloadDriver (NTDLL.@)
2439 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2441 FIXME("(%p), stub!\n",DriverServiceName);
2442 return STATUS_NOT_IMPLEMENTED;
2446 /******************************************************************
2447 * DllMain (NTDLL.@)
2449 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2451 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2452 return TRUE;
2456 /******************************************************************
2457 * __wine_init_windows_dir (NTDLL.@)
2459 * Windows and system dir initialization once kernel32 has been loaded.
2461 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2463 PLIST_ENTRY mark, entry;
2464 LPWSTR buffer, p;
2466 RtlCreateUnicodeString( &windows_dir, windir );
2467 RtlCreateUnicodeString( &system_dir, sysdir );
2468 strcpyW( user_shared_data->NtSystemRoot, windir );
2470 /* prepend the system dir to the name of the already created modules */
2471 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2472 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2474 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2476 assert( mod->Flags & LDR_WINE_INTERNAL );
2478 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2479 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2480 if (!buffer) continue;
2481 strcpyW( buffer, system_dir.Buffer );
2482 p = buffer + strlenW( buffer );
2483 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2484 strcpyW( p, mod->FullDllName.Buffer );
2485 RtlInitUnicodeString( &mod->FullDllName, buffer );
2486 RtlInitUnicodeString( &mod->BaseDllName, p );
2491 /***********************************************************************
2492 * __wine_process_init
2494 void __wine_process_init(void)
2496 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2498 WINE_MODREF *wm;
2499 NTSTATUS status;
2500 ANSI_STRING func_name;
2501 void (* DECLSPEC_NORETURN init_func)(void);
2502 extern mode_t FILE_umask;
2504 main_exe_file = thread_init();
2506 /* retrieve current umask */
2507 FILE_umask = umask(0777);
2508 umask( FILE_umask );
2510 /* setup the load callback and create ntdll modref */
2511 wine_dll_set_callback( load_builtin_callback );
2513 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2515 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2516 exit(1);
2518 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2519 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2520 0, (void **)&init_func )) != STATUS_SUCCESS)
2522 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2523 exit(1);
2525 init_func();