wined3d: Move the GL info structure into the adapter.
[wine/hacks.git] / dlls / ntdll / loader.c
blob05538a0b8d4dab3533fb0a2cb5ba741e23e8a647
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 NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
119 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
120 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
122 /* convert PE image VirtualAddress to Real Address */
123 static inline void *get_rva( HMODULE module, DWORD va )
125 return (void *)((char *)module + va);
128 /* check whether the file name contains a path */
129 static inline int contains_path( LPCWSTR name )
131 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
134 /* convert from straight ASCII to Unicode without depending on the current codepage */
135 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
137 while (len--) *dst++ = (unsigned char)*src++;
141 /*************************************************************************
142 * call_dll_entry_point
144 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
145 * their entry point, so we need a small asm wrapper.
147 #ifdef __i386__
148 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
149 __ASM_GLOBAL_FUNC(call_dll_entry_point,
150 "pushl %ebp\n\t"
151 "movl %esp,%ebp\n\t"
152 "pushl %ebx\n\t"
153 "subl $8,%esp\n\t"
154 "pushl 20(%ebp)\n\t"
155 "pushl 16(%ebp)\n\t"
156 "pushl 12(%ebp)\n\t"
157 "movl 8(%ebp),%eax\n\t"
158 "call *%eax\n\t"
159 "leal -4(%ebp),%esp\n\t"
160 "popl %ebx\n\t"
161 "popl %ebp\n\t"
162 "ret" )
163 #else /* __i386__ */
164 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
165 UINT reason, void *reserved )
167 return proc( module, reason, reserved );
169 #endif /* __i386__ */
172 #ifdef __i386__
173 /*************************************************************************
174 * stub_entry_point
176 * Entry point for stub functions.
178 static void stub_entry_point( const char *dll, const char *name, ... )
180 EXCEPTION_RECORD rec;
182 rec.ExceptionCode = EXCEPTION_WINE_STUB;
183 rec.ExceptionFlags = EH_NONCONTINUABLE;
184 rec.ExceptionRecord = NULL;
185 #ifdef __GNUC__
186 rec.ExceptionAddress = __builtin_return_address(0);
187 #else
188 rec.ExceptionAddress = *((void **)&dll - 1);
189 #endif
190 rec.NumberParameters = 2;
191 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
192 rec.ExceptionInformation[1] = (ULONG_PTR)name;
193 for (;;) RtlRaiseException( &rec );
197 #include "pshpack1.h"
198 struct stub
200 BYTE popl_eax; /* popl %eax */
201 BYTE pushl1; /* pushl $name */
202 const char *name;
203 BYTE pushl2; /* pushl $dll */
204 const char *dll;
205 BYTE pushl_eax; /* pushl %eax */
206 BYTE jmp; /* jmp stub_entry_point */
207 DWORD entry;
209 #include "poppack.h"
211 /*************************************************************************
212 * allocate_stub
214 * Allocate a stub entry point.
216 static ULONG_PTR allocate_stub( const char *dll, const char *name )
218 #define MAX_SIZE 65536
219 static struct stub *stubs;
220 static unsigned int nb_stubs;
221 struct stub *stub;
223 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
225 if (!stubs)
227 SIZE_T size = MAX_SIZE;
228 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
229 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
230 return 0xdeadbeef;
232 stub = &stubs[nb_stubs++];
233 stub->popl_eax = 0x58; /* popl %eax */
234 stub->pushl1 = 0x68; /* pushl $name */
235 stub->name = name;
236 stub->pushl2 = 0x68; /* pushl $dll */
237 stub->dll = dll;
238 stub->pushl_eax = 0x50; /* pushl %eax */
239 stub->jmp = 0xe9; /* jmp stub_entry_point */
240 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
241 return (ULONG_PTR)stub;
244 #else /* __i386__ */
245 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
246 #endif /* __i386__ */
249 /*************************************************************************
250 * get_modref
252 * Looks for the referenced HMODULE in the current process
253 * The loader_section must be locked while calling this function.
255 static WINE_MODREF *get_modref( HMODULE hmod )
257 PLIST_ENTRY mark, entry;
258 PLDR_MODULE mod;
260 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
262 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
263 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
265 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
266 if (mod->BaseAddress == hmod)
267 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
268 if (mod->BaseAddress > (void*)hmod) break;
270 return NULL;
274 /**********************************************************************
275 * find_basename_module
277 * Find a module from its base name.
278 * The loader_section must be locked while calling this function
280 static WINE_MODREF *find_basename_module( LPCWSTR name )
282 PLIST_ENTRY mark, entry;
284 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
285 return cached_modref;
287 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
288 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
290 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
291 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
293 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
294 return cached_modref;
297 return NULL;
301 /**********************************************************************
302 * find_fullname_module
304 * Find a module from its full path name.
305 * The loader_section must be locked while calling this function
307 static WINE_MODREF *find_fullname_module( LPCWSTR name )
309 PLIST_ENTRY mark, entry;
311 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
312 return cached_modref;
314 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
315 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
317 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
318 if (!strcmpiW( name, mod->FullDllName.Buffer ))
320 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
321 return cached_modref;
324 return NULL;
328 /*************************************************************************
329 * find_forwarded_export
331 * Find the final function pointer for a forwarded function.
332 * The loader_section must be locked while calling this function.
334 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
336 const IMAGE_EXPORT_DIRECTORY *exports;
337 DWORD exp_size;
338 WINE_MODREF *wm;
339 WCHAR mod_name[32];
340 const char *end = strrchr(forward, '.');
341 FARPROC proc = NULL;
343 if (!end) return NULL;
344 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
345 ascii_to_unicode( mod_name, forward, end - forward );
346 mod_name[end - forward] = 0;
347 if (!strchrW( mod_name, '.' ))
349 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
350 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
353 if (!(wm = find_basename_module( mod_name )))
355 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
356 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
357 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
359 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
361 LdrUnloadDll( wm->ldr.BaseAddress );
362 wm = NULL;
366 if (!wm)
368 ERR( "module not found for forward '%s' used by %s\n",
369 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
370 return NULL;
373 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
374 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
375 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1, load_path );
377 if (!proc)
379 ERR("function not found for forward '%s' used by %s."
380 " If you are using builtin %s, try using the native one instead.\n",
381 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
382 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
384 return proc;
388 /*************************************************************************
389 * find_ordinal_export
391 * Find an exported function by ordinal.
392 * The exports base must have been subtracted from the ordinal already.
393 * The loader_section must be locked while calling this function.
395 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
396 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
398 FARPROC proc;
399 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
401 if (ordinal >= exports->NumberOfFunctions)
403 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
404 return NULL;
406 if (!functions[ordinal]) return NULL;
408 proc = get_rva( module, functions[ordinal] );
410 /* if the address falls into the export dir, it's a forward */
411 if (((const char *)proc >= (const char *)exports) &&
412 ((const char *)proc < (const char *)exports + exp_size))
413 return find_forwarded_export( module, (const char *)proc, load_path );
415 if (TRACE_ON(snoop))
417 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
418 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
420 if (TRACE_ON(relay))
422 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
423 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
425 return proc;
429 /*************************************************************************
430 * find_named_export
432 * Find an exported function by name.
433 * The loader_section must be locked while calling this function.
435 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
436 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
438 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
439 const DWORD *names = get_rva( module, exports->AddressOfNames );
440 int min = 0, max = exports->NumberOfNames - 1;
442 /* first check the hint */
443 if (hint >= 0 && hint <= max)
445 char *ename = get_rva( module, names[hint] );
446 if (!strcmp( ename, name ))
447 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
450 /* then do a binary search */
451 while (min <= max)
453 int res, pos = (min + max) / 2;
454 char *ename = get_rva( module, names[pos] );
455 if (!(res = strcmp( ename, name )))
456 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
457 if (res > 0) max = pos - 1;
458 else min = pos + 1;
460 return NULL;
465 /*************************************************************************
466 * import_dll
468 * Import the dll specified by the given import descriptor.
469 * The loader_section must be locked while calling this function.
471 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
473 NTSTATUS status;
474 WINE_MODREF *wmImp;
475 HMODULE imp_mod;
476 const IMAGE_EXPORT_DIRECTORY *exports;
477 DWORD exp_size;
478 const IMAGE_THUNK_DATA *import_list;
479 IMAGE_THUNK_DATA *thunk_list;
480 WCHAR buffer[32];
481 const char *name = get_rva( module, descr->Name );
482 DWORD len = strlen(name);
483 PVOID protect_base;
484 SIZE_T protect_size = 0;
485 DWORD protect_old;
487 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
488 if (descr->u.OriginalFirstThunk)
489 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
490 else
491 import_list = thunk_list;
493 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
495 if (len * sizeof(WCHAR) < sizeof(buffer))
497 ascii_to_unicode( buffer, name, len );
498 buffer[len] = 0;
499 status = load_dll( load_path, buffer, 0, &wmImp );
501 else /* need to allocate a larger buffer */
503 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
504 if (!ptr) return NULL;
505 ascii_to_unicode( ptr, name, len );
506 ptr[len] = 0;
507 status = load_dll( load_path, ptr, 0, &wmImp );
508 RtlFreeHeap( GetProcessHeap(), 0, ptr );
511 if (status)
513 if (status == STATUS_DLL_NOT_FOUND)
514 ERR("Library %s (which is needed by %s) not found\n",
515 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
516 else
517 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
518 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
519 return NULL;
522 /* unprotect the import address table since it can be located in
523 * readonly section */
524 while (import_list[protect_size].u1.Ordinal) protect_size++;
525 protect_base = thunk_list;
526 protect_size *= sizeof(*thunk_list);
527 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
528 &protect_size, PAGE_WRITECOPY, &protect_old );
530 imp_mod = wmImp->ldr.BaseAddress;
531 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
533 if (!exports)
535 /* set all imported function to deadbeef */
536 while (import_list->u1.Ordinal)
538 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
540 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
541 WARN("No implementation for %s.%d", name, ordinal );
542 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
544 else
546 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
547 WARN("No implementation for %s.%s", name, pe_name->Name );
548 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
550 WARN(" imported from %s, allocating stub %p\n",
551 debugstr_w(current_modref->ldr.FullDllName.Buffer),
552 (void *)thunk_list->u1.Function );
553 import_list++;
554 thunk_list++;
556 goto done;
559 while (import_list->u1.Ordinal)
561 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
563 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
565 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
566 ordinal - exports->Base, load_path );
567 if (!thunk_list->u1.Function)
569 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
570 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
571 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
572 (void *)thunk_list->u1.Function );
574 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
576 else /* import by name */
578 IMAGE_IMPORT_BY_NAME *pe_name;
579 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
580 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
581 (const char*)pe_name->Name,
582 pe_name->Hint, load_path );
583 if (!thunk_list->u1.Function)
585 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
586 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
587 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
588 (void *)thunk_list->u1.Function );
590 TRACE_(imports)("--- %s %s.%d = %p\n",
591 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
593 import_list++;
594 thunk_list++;
597 done:
598 /* restore old protection of the import address table */
599 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
600 return wmImp;
604 /***********************************************************************
605 * create_module_activation_context
607 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
609 NTSTATUS status;
610 LDR_RESOURCE_INFO info;
611 const IMAGE_RESOURCE_DATA_ENTRY *entry;
613 info.Type = RT_MANIFEST;
614 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
615 info.Language = 0;
616 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
618 ACTCTXW ctx;
619 ctx.cbSize = sizeof(ctx);
620 ctx.lpSource = NULL;
621 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
622 ctx.hModule = module->BaseAddress;
623 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
624 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
626 return status;
630 /****************************************************************
631 * fixup_imports
633 * Fixup all imports of a given module.
634 * The loader_section must be locked while calling this function.
636 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
638 int i, nb_imports;
639 const IMAGE_IMPORT_DESCRIPTOR *imports;
640 WINE_MODREF *prev;
641 DWORD size;
642 NTSTATUS status;
643 ULONG_PTR cookie;
645 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
646 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
648 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
649 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
650 return STATUS_SUCCESS;
652 nb_imports = 0;
653 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
655 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
657 if (!create_module_activation_context( &wm->ldr ))
658 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
660 /* Allocate module dependency list */
661 wm->nDeps = nb_imports;
662 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
664 /* load the imported modules. They are automatically
665 * added to the modref list of the process.
667 prev = current_modref;
668 current_modref = wm;
669 status = STATUS_SUCCESS;
670 for (i = 0; i < nb_imports; i++)
672 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
673 status = STATUS_DLL_NOT_FOUND;
675 current_modref = prev;
676 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
677 return status;
681 /*************************************************************************
682 * alloc_module
684 * Allocate a WINE_MODREF structure and add it to the process list
685 * The loader_section must be locked while calling this function.
687 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
689 WINE_MODREF *wm;
690 const WCHAR *p;
691 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
692 PLIST_ENTRY entry, mark;
694 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
696 wm->nDeps = 0;
697 wm->deps = NULL;
699 wm->ldr.BaseAddress = hModule;
700 wm->ldr.EntryPoint = NULL;
701 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
702 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
703 wm->ldr.LoadCount = 1;
704 wm->ldr.TlsIndex = -1;
705 wm->ldr.SectionHandle = NULL;
706 wm->ldr.CheckSum = 0;
707 wm->ldr.TimeDateStamp = 0;
708 wm->ldr.ActivationContext = 0;
710 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
711 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
712 else p = wm->ldr.FullDllName.Buffer;
713 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
715 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
717 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
718 if (nt->OptionalHeader.AddressOfEntryPoint)
719 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
722 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
723 &wm->ldr.InLoadOrderModuleList);
725 /* insert module in MemoryList, sorted in increasing base addresses */
726 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
727 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
729 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
730 break;
732 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
733 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
734 wm->ldr.InMemoryOrderModuleList.Flink = entry;
735 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
737 /* wait until init is called for inserting into this list */
738 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
739 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
741 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
743 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
744 VIRTUAL_SetForceExec( TRUE );
746 return wm;
750 /*************************************************************************
751 * alloc_process_tls
753 * Allocate the process-wide structure for module TLS storage.
755 static NTSTATUS alloc_process_tls(void)
757 PLIST_ENTRY mark, entry;
758 PLDR_MODULE mod;
759 const IMAGE_TLS_DIRECTORY *dir;
760 ULONG size, i;
762 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
763 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
765 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
766 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
767 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
768 continue;
769 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
770 if (!size) continue;
771 tls_total_size += size;
772 tls_module_count++;
774 if (!tls_module_count) return STATUS_SUCCESS;
776 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
778 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
779 if (!tls_dirs) return STATUS_NO_MEMORY;
781 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
783 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
784 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
785 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
786 continue;
787 tls_dirs[i] = dir;
788 *(DWORD *)dir->AddressOfIndex = i;
789 mod->TlsIndex = i;
790 mod->LoadCount = -1; /* can't unload it */
791 i++;
793 return STATUS_SUCCESS;
797 /*************************************************************************
798 * alloc_thread_tls
800 * Allocate the per-thread structure for module TLS storage.
802 static NTSTATUS alloc_thread_tls(void)
804 void **pointers;
805 char *data;
806 UINT i;
808 if (!tls_module_count) return STATUS_SUCCESS;
810 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
811 tls_module_count * sizeof(*pointers) )))
812 return STATUS_NO_MEMORY;
814 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
816 RtlFreeHeap( GetProcessHeap(), 0, pointers );
817 return STATUS_NO_MEMORY;
820 for (i = 0; i < tls_module_count; i++)
822 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
823 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
825 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
826 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
827 (void *)dir->StartAddressOfRawData, data );
829 pointers[i] = data;
830 memcpy( data, (void *)dir->StartAddressOfRawData, size );
831 data += size;
832 memset( data, 0, dir->SizeOfZeroFill );
833 data += dir->SizeOfZeroFill;
835 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
836 return STATUS_SUCCESS;
840 /*************************************************************************
841 * call_tls_callbacks
843 static void call_tls_callbacks( HMODULE module, UINT reason )
845 const IMAGE_TLS_DIRECTORY *dir;
846 const PIMAGE_TLS_CALLBACK *callback;
847 ULONG dirsize;
849 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
850 if (!dir || !dir->AddressOfCallBacks) return;
852 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
854 if (TRACE_ON(relay))
855 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
856 GetCurrentThreadId(), *callback, module, reason_names[reason] );
857 __TRY
859 (*callback)( module, reason, NULL );
861 __EXCEPT(NULL)
863 if (TRACE_ON(relay))
864 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
865 GetCurrentThreadId(), callback, module, reason_names[reason] );
866 return;
868 __ENDTRY
869 if (TRACE_ON(relay))
870 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
871 GetCurrentThreadId(), *callback, module, reason_names[reason] );
876 /*************************************************************************
877 * MODULE_InitDLL
879 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
881 WCHAR mod_name[32];
882 BOOL retv = TRUE;
883 DLLENTRYPROC entry = wm->ldr.EntryPoint;
884 void *module = wm->ldr.BaseAddress;
886 /* Skip calls for modules loaded with special load flags */
888 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
889 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
890 if (!entry) return TRUE;
892 if (TRACE_ON(relay))
894 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
895 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
896 mod_name[len / sizeof(WCHAR)] = 0;
897 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
898 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
899 reason_names[reason], lpReserved );
901 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
902 reason_names[reason], lpReserved );
904 retv = call_dll_entry_point( entry, module, reason, lpReserved );
906 /* The state of the module list may have changed due to the call
907 to the dll. We cannot assume that this module has not been
908 deleted. */
909 if (TRACE_ON(relay))
910 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
911 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
912 reason_names[reason], lpReserved, retv );
913 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
915 return retv;
919 /*************************************************************************
920 * process_attach
922 * Send the process attach notification to all DLLs the given module
923 * depends on (recursively). This is somewhat complicated due to the fact that
925 * - we have to respect the module dependencies, i.e. modules implicitly
926 * referenced by another module have to be initialized before the module
927 * itself can be initialized
929 * - the initialization routine of a DLL can itself call LoadLibrary,
930 * thereby introducing a whole new set of dependencies (even involving
931 * the 'old' modules) at any time during the whole process
933 * (Note that this routine can be recursively entered not only directly
934 * from itself, but also via LoadLibrary from one of the called initialization
935 * routines.)
937 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
938 * the process *detach* notifications to be sent in the correct order.
939 * This must not only take into account module dependencies, but also
940 * 'hidden' dependencies created by modules calling LoadLibrary in their
941 * attach notification routine.
943 * The strategy is rather simple: we move a WINE_MODREF to the head of the
944 * list after the attach notification has returned. This implies that the
945 * detach notifications are called in the reverse of the sequence the attach
946 * notifications *returned*.
948 * The loader_section must be locked while calling this function.
950 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
952 NTSTATUS status = STATUS_SUCCESS;
953 ULONG_PTR cookie;
954 int i;
956 if (process_detaching) return status;
958 /* prevent infinite recursion in case of cyclical dependencies */
959 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
960 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
961 return status;
963 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
965 /* Tag current MODREF to prevent recursive loop */
966 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
967 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
968 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
970 /* Recursively attach all DLLs this one depends on */
971 for ( i = 0; i < wm->nDeps; i++ )
973 if (!wm->deps[i]) continue;
974 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
977 /* Call DLL entry point */
978 if (status == STATUS_SUCCESS)
980 WINE_MODREF *prev = current_modref;
981 current_modref = wm;
982 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
984 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
986 else
988 /* point to the name so LdrInitializeThunk can print it */
989 last_failed_modref = wm;
990 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
991 status = STATUS_DLL_INIT_FAILED;
993 current_modref = prev;
996 if (!wm->ldr.InInitializationOrderModuleList.Flink)
997 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
998 &wm->ldr.InInitializationOrderModuleList);
1000 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1001 /* Remove recursion flag */
1002 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1004 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1005 return status;
1009 /**********************************************************************
1010 * attach_implicitly_loaded_dlls
1012 * Attach to the (builtin) dlls that have been implicitly loaded because
1013 * of a dependency at the Unix level, but not imported at the Win32 level.
1015 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1017 for (;;)
1019 PLIST_ENTRY mark, entry;
1021 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1022 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1024 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1026 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1027 TRACE( "found implicitly loaded %s, attaching to it\n",
1028 debugstr_w(mod->BaseDllName.Buffer));
1029 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1030 break; /* restart the search from the start */
1032 if (entry == mark) break; /* nothing found */
1037 /*************************************************************************
1038 * process_detach
1040 * Send DLL process detach notifications. See the comment about calling
1041 * sequence at process_attach. Unless the bForceDetach flag
1042 * is set, only DLLs with zero refcount are notified.
1044 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1046 PLIST_ENTRY mark, entry;
1047 PLDR_MODULE mod;
1049 RtlEnterCriticalSection( &loader_section );
1050 if (bForceDetach) process_detaching = 1;
1051 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1054 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1056 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1057 InInitializationOrderModuleList);
1058 /* Check whether to detach this DLL */
1059 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1060 continue;
1061 if ( mod->LoadCount && !bForceDetach )
1062 continue;
1064 /* Call detach notification */
1065 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1066 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1067 DLL_PROCESS_DETACH, lpReserved );
1069 /* Restart at head of WINE_MODREF list, as entries might have
1070 been added and/or removed while performing the call ... */
1071 break;
1073 } while (entry != mark);
1075 RtlLeaveCriticalSection( &loader_section );
1078 /*************************************************************************
1079 * MODULE_DllThreadAttach
1081 * Send DLL thread attach notifications. These are sent in the
1082 * reverse sequence of process detach notification.
1085 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1087 PLIST_ENTRY mark, entry;
1088 PLDR_MODULE mod;
1089 NTSTATUS status;
1091 /* don't do any attach calls if process is exiting */
1092 if (process_detaching) return STATUS_SUCCESS;
1093 /* FIXME: there is still a race here */
1095 RtlEnterCriticalSection( &loader_section );
1097 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1099 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1100 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1102 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1103 InInitializationOrderModuleList);
1104 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1105 continue;
1106 if ( mod->Flags & LDR_NO_DLL_CALLS )
1107 continue;
1109 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1110 DLL_THREAD_ATTACH, lpReserved );
1113 done:
1114 RtlLeaveCriticalSection( &loader_section );
1115 return status;
1118 /******************************************************************
1119 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1122 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1124 WINE_MODREF *wm;
1125 NTSTATUS ret = STATUS_SUCCESS;
1127 RtlEnterCriticalSection( &loader_section );
1129 wm = get_modref( hModule );
1130 if (!wm || wm->ldr.TlsIndex != -1)
1131 ret = STATUS_DLL_NOT_FOUND;
1132 else
1133 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1135 RtlLeaveCriticalSection( &loader_section );
1137 return ret;
1140 /******************************************************************
1141 * LdrFindEntryForAddress (NTDLL.@)
1143 * The loader_section must be locked while calling this function
1145 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1147 PLIST_ENTRY mark, entry;
1148 PLDR_MODULE mod;
1150 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1151 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1153 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1154 if ((const void *)mod->BaseAddress <= addr &&
1155 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1157 *pmod = mod;
1158 return STATUS_SUCCESS;
1160 if ((const void *)mod->BaseAddress > addr) break;
1162 return STATUS_NO_MORE_ENTRIES;
1165 /******************************************************************
1166 * LdrLockLoaderLock (NTDLL.@)
1168 * Note: flags are not implemented.
1169 * Flag 0x01 is used to raise exceptions on errors.
1170 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1172 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1174 if (flags) FIXME( "flags %x not supported\n", flags );
1176 if (result) *result = 1;
1177 if (!magic) return STATUS_INVALID_PARAMETER_3;
1178 RtlEnterCriticalSection( &loader_section );
1179 *magic = GetCurrentThreadId();
1180 return STATUS_SUCCESS;
1184 /******************************************************************
1185 * LdrUnlockLoaderUnlock (NTDLL.@)
1187 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1189 if (magic)
1191 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1192 RtlLeaveCriticalSection( &loader_section );
1194 return STATUS_SUCCESS;
1198 /******************************************************************
1199 * LdrGetProcedureAddress (NTDLL.@)
1201 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1202 ULONG ord, PVOID *address)
1204 IMAGE_EXPORT_DIRECTORY *exports;
1205 DWORD exp_size;
1206 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1208 RtlEnterCriticalSection( &loader_section );
1210 /* check if the module itself is invalid to return the proper error */
1211 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1212 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1213 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1215 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1216 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1217 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1218 if (proc)
1220 *address = proc;
1221 ret = STATUS_SUCCESS;
1225 RtlLeaveCriticalSection( &loader_section );
1226 return ret;
1230 /***********************************************************************
1231 * is_fake_dll
1233 * Check if a loaded native dll is a Wine fake dll.
1235 static BOOL is_fake_dll( const void *base )
1237 static const char fakedll_signature[] = "Wine placeholder DLL";
1238 const IMAGE_DOS_HEADER *dos = base;
1240 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1241 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1242 return FALSE;
1246 /***********************************************************************
1247 * get_builtin_fullname
1249 * Build the full pathname for a builtin dll.
1251 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1253 static const WCHAR soW[] = {'.','s','o',0};
1254 WCHAR *p, *fullname;
1255 size_t i, len = strlen(filename);
1257 /* check if path can correspond to the dll we have */
1258 if (path && (p = strrchrW( path, '\\' )))
1260 p++;
1261 for (i = 0; i < len; i++)
1262 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1263 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1265 /* the filename matches, use path as the full path */
1266 len += p - path;
1267 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1269 memcpy( fullname, path, len * sizeof(WCHAR) );
1270 fullname[len] = 0;
1272 return fullname;
1276 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1277 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1279 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1280 p = fullname + system_dir.Length / sizeof(WCHAR);
1281 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1282 ascii_to_unicode( p, filename, len + 1 );
1284 return fullname;
1288 /***********************************************************************
1289 * load_builtin_callback
1291 * Load a library in memory; callback function for wine_dll_register
1293 static void load_builtin_callback( void *module, const char *filename )
1295 static const WCHAR emptyW[1];
1296 void *addr;
1297 IMAGE_NT_HEADERS *nt;
1298 WINE_MODREF *wm;
1299 WCHAR *fullname;
1300 const WCHAR *load_path;
1301 SIZE_T size;
1303 if (!module)
1305 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1306 return;
1308 if (!(nt = RtlImageNtHeader( module )))
1310 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1311 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1312 return;
1314 addr = module;
1315 size = nt->OptionalHeader.SizeOfImage;
1316 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1317 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1318 /* create the MODREF */
1320 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1322 ERR( "can't load %s\n", filename );
1323 builtin_load_info->status = STATUS_NO_MEMORY;
1324 return;
1327 wm = alloc_module( module, fullname );
1328 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1329 if (!wm)
1331 ERR( "can't load %s\n", filename );
1332 builtin_load_info->status = STATUS_NO_MEMORY;
1333 return;
1335 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1337 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1338 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1340 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1342 else
1344 /* fixup imports */
1346 load_path = builtin_load_info->load_path;
1347 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1348 if (!load_path) load_path = emptyW;
1349 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1351 /* the module has only be inserted in the load & memory order lists */
1352 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1353 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1354 /* FIXME: free the modref */
1355 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1356 return;
1360 builtin_load_info->wm = wm;
1361 TRACE( "loaded %s %p %p\n", filename, wm, module );
1363 /* send the DLL load event */
1365 SERVER_START_REQ( load_dll )
1367 req->handle = 0;
1368 req->base = module;
1369 req->size = nt->OptionalHeader.SizeOfImage;
1370 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1371 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1372 req->name = &wm->ldr.FullDllName.Buffer;
1373 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1374 wine_server_call( req );
1376 SERVER_END_REQ;
1378 /* setup relay debugging entry points */
1379 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1383 /******************************************************************************
1384 * load_native_dll (internal)
1386 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1387 DWORD flags, WINE_MODREF** pwm )
1389 void *module;
1390 HANDLE mapping;
1391 OBJECT_ATTRIBUTES attr;
1392 LARGE_INTEGER size;
1393 IMAGE_NT_HEADERS *nt;
1394 SIZE_T len = 0;
1395 WINE_MODREF *wm;
1396 NTSTATUS status;
1398 TRACE("Trying native dll %s\n", debugstr_w(name));
1400 attr.Length = sizeof(attr);
1401 attr.RootDirectory = 0;
1402 attr.ObjectName = NULL;
1403 attr.Attributes = 0;
1404 attr.SecurityDescriptor = NULL;
1405 attr.SecurityQualityOfService = NULL;
1406 size.QuadPart = 0;
1408 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1409 &attr, &size, 0, SEC_IMAGE, file );
1410 if (status != STATUS_SUCCESS) return status;
1412 module = NULL;
1413 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1414 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1415 NtClose( mapping );
1416 if (status != STATUS_SUCCESS) return status;
1418 if (is_fake_dll( module ))
1420 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name) );
1421 NtUnmapViewOfSection( NtCurrentProcess(), module );
1422 return STATUS_DLL_NOT_FOUND;
1425 /* create the MODREF */
1427 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1429 /* fixup imports */
1431 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1433 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1435 /* the module has only be inserted in the load & memory order lists */
1436 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1437 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1439 /* FIXME: there are several more dangling references
1440 * left. Including dlls loaded by this dll before the
1441 * failed one. Unrolling is rather difficult with the
1442 * current structure and we can leave them lying
1443 * around with no problems, so we don't care.
1444 * As these might reference our wm, we don't free it.
1446 return status;
1450 /* send DLL load event */
1452 nt = RtlImageNtHeader( module );
1454 SERVER_START_REQ( load_dll )
1456 req->handle = file;
1457 req->base = module;
1458 req->size = nt->OptionalHeader.SizeOfImage;
1459 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1460 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1461 req->name = &wm->ldr.FullDllName.Buffer;
1462 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1463 wine_server_call( req );
1465 SERVER_END_REQ;
1467 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1469 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1471 wm->ldr.LoadCount = 1;
1472 *pwm = wm;
1473 return STATUS_SUCCESS;
1477 /***********************************************************************
1478 * load_builtin_dll
1480 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1481 DWORD flags, WINE_MODREF** pwm )
1483 char error[256], dllname[MAX_PATH];
1484 const WCHAR *name, *p;
1485 DWORD len, i;
1486 void *handle = NULL;
1487 struct builtin_load_info info, *prev_info;
1489 /* Fix the name in case we have a full path and extension */
1490 name = path;
1491 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1492 if ((p = strrchrW( name, '/' ))) name = p + 1;
1494 /* load_library will modify info.status. Note also that load_library can be
1495 * called several times, if the .so file we're loading has dependencies.
1496 * info.status will gather all the errors we may get while loading all these
1497 * libraries
1499 info.load_path = load_path;
1500 info.filename = NULL;
1501 info.status = STATUS_SUCCESS;
1502 info.wm = NULL;
1504 if (file) /* we have a real file, try to load it */
1506 UNICODE_STRING nt_name;
1507 ANSI_STRING unix_name;
1509 TRACE("Trying built-in %s\n", debugstr_w(path));
1511 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1512 return STATUS_DLL_NOT_FOUND;
1514 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1516 RtlFreeUnicodeString( &nt_name );
1517 return STATUS_DLL_NOT_FOUND;
1519 prev_info = builtin_load_info;
1520 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1521 builtin_load_info = &info;
1522 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1523 builtin_load_info = prev_info;
1524 RtlFreeUnicodeString( &nt_name );
1525 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1526 if (!handle)
1528 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1529 return STATUS_INVALID_IMAGE_FORMAT;
1532 else
1534 int file_exists;
1536 TRACE("Trying built-in %s\n", debugstr_w(name));
1538 /* we don't want to depend on the current codepage here */
1539 len = strlenW( name ) + 1;
1540 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1541 for (i = 0; i < len; i++)
1543 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1544 dllname[i] = (char)name[i];
1545 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1548 prev_info = builtin_load_info;
1549 builtin_load_info = &info;
1550 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1551 builtin_load_info = prev_info;
1552 if (!handle)
1554 if (!file_exists)
1556 /* The file does not exist -> WARN() */
1557 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1558 return STATUS_DLL_NOT_FOUND;
1560 /* ERR() for all other errors (missing functions, ...) */
1561 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1562 return STATUS_PROCEDURE_NOT_FOUND;
1566 if (info.status != STATUS_SUCCESS)
1568 wine_dll_unload( handle );
1569 return info.status;
1572 if (!info.wm)
1574 PLIST_ENTRY mark, entry;
1576 /* The constructor wasn't called, this means the .so is already
1577 * loaded under a different name. Try to find the wm for it. */
1579 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1580 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1582 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1583 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1585 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1586 TRACE( "Found %s at %p for builtin %s\n",
1587 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1588 break;
1591 wine_dll_unload( handle ); /* release the libdl refcount */
1592 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1593 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1595 else
1597 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1598 info.wm->ldr.LoadCount = 1;
1599 info.wm->ldr.SectionHandle = handle;
1602 *pwm = info.wm;
1603 return STATUS_SUCCESS;
1607 /***********************************************************************
1608 * find_actctx_dll
1610 * Find the full path (if any) of the dll from the activation context.
1612 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1614 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1615 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1617 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1618 ACTCTX_SECTION_KEYED_DATA data;
1619 UNICODE_STRING nameW;
1620 NTSTATUS status;
1621 SIZE_T needed, size = 1024;
1622 WCHAR *p;
1624 RtlInitUnicodeString( &nameW, libname );
1625 data.cbSize = sizeof(data);
1626 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1627 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1628 &nameW, &data );
1629 if (status != STATUS_SUCCESS) return status;
1631 for (;;)
1633 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1635 status = STATUS_NO_MEMORY;
1636 goto done;
1638 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1639 AssemblyDetailedInformationInActivationContext,
1640 info, size, &needed );
1641 if (status == STATUS_SUCCESS) break;
1642 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1643 RtlFreeHeap( GetProcessHeap(), 0, info );
1644 size = needed;
1645 /* restart with larger buffer */
1648 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1650 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1652 p++;
1653 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1655 /* manifest name does not match directory name, so it's not a global
1656 * windows/winsxs manifest; use the manifest directory name instead */
1657 dirlen = p - info->lpAssemblyManifestPath;
1658 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1659 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1661 status = STATUS_NO_MEMORY;
1662 goto done;
1664 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1665 p += dirlen;
1666 strcpyW( p, libname );
1667 goto done;
1671 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1672 nameW.Length + 2*sizeof(WCHAR));
1674 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1676 status = STATUS_NO_MEMORY;
1677 goto done;
1679 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1680 p += windows_dir.Length / sizeof(WCHAR);
1681 memcpy( p, winsxsW, sizeof(winsxsW) );
1682 p += sizeof(winsxsW) / sizeof(WCHAR);
1683 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1684 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1685 *p++ = '\\';
1686 strcpyW( p, libname );
1687 done:
1688 RtlFreeHeap( GetProcessHeap(), 0, info );
1689 RtlReleaseActivationContext( data.hActCtx );
1690 return status;
1694 /***********************************************************************
1695 * find_dll_file
1697 * Find the file (or already loaded module) for a given dll name.
1699 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1700 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1702 OBJECT_ATTRIBUTES attr;
1703 IO_STATUS_BLOCK io;
1704 UNICODE_STRING nt_name;
1705 WCHAR *file_part, *ext, *dllname;
1706 ULONG len;
1708 /* first append .dll if needed */
1710 dllname = NULL;
1711 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1713 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1714 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1715 return STATUS_NO_MEMORY;
1716 strcpyW( dllname, libname );
1717 strcatW( dllname, dllW );
1718 libname = dllname;
1721 nt_name.Buffer = NULL;
1723 if (!contains_path( libname ))
1725 NTSTATUS status;
1726 WCHAR *fullname = NULL;
1728 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1730 status = find_actctx_dll( libname, &fullname );
1731 if (status == STATUS_SUCCESS)
1733 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1734 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1735 libname = dllname = fullname;
1737 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1739 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1740 return status;
1744 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1746 /* we need to search for it */
1747 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1748 if (len)
1750 if (len >= *size) goto overflow;
1751 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1753 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1755 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1756 return STATUS_NO_MEMORY;
1758 attr.Length = sizeof(attr);
1759 attr.RootDirectory = 0;
1760 attr.Attributes = OBJ_CASE_INSENSITIVE;
1761 attr.ObjectName = &nt_name;
1762 attr.SecurityDescriptor = NULL;
1763 attr.SecurityQualityOfService = NULL;
1764 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1765 goto found;
1768 /* not found */
1770 if (!contains_path( libname ))
1772 /* if libname doesn't contain a path at all, we simply return the name as is,
1773 * to be loaded as builtin */
1774 len = strlenW(libname) * sizeof(WCHAR);
1775 if (len >= *size) goto overflow;
1776 strcpyW( filename, libname );
1777 goto found;
1781 /* absolute path name, or relative path name but not found above */
1783 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1785 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1786 return STATUS_NO_MEMORY;
1788 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1789 if (len >= *size) goto overflow;
1790 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1791 if (!(*pwm = find_fullname_module( filename )) && handle)
1793 attr.Length = sizeof(attr);
1794 attr.RootDirectory = 0;
1795 attr.Attributes = OBJ_CASE_INSENSITIVE;
1796 attr.ObjectName = &nt_name;
1797 attr.SecurityDescriptor = NULL;
1798 attr.SecurityQualityOfService = NULL;
1799 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1801 found:
1802 RtlFreeUnicodeString( &nt_name );
1803 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1804 return STATUS_SUCCESS;
1806 overflow:
1807 RtlFreeUnicodeString( &nt_name );
1808 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1809 *size = len + sizeof(WCHAR);
1810 return STATUS_BUFFER_TOO_SMALL;
1814 /***********************************************************************
1815 * load_dll (internal)
1817 * Load a PE style module according to the load order.
1818 * The loader_section must be locked while calling this function.
1820 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1822 enum loadorder loadorder;
1823 WCHAR buffer[32];
1824 WCHAR *filename;
1825 ULONG size;
1826 WINE_MODREF *main_exe;
1827 HANDLE handle = 0;
1828 NTSTATUS nts;
1830 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1832 *pwm = NULL;
1833 filename = buffer;
1834 size = sizeof(buffer);
1835 for (;;)
1837 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1838 if (nts == STATUS_SUCCESS) break;
1839 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1840 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1841 /* grow the buffer and retry */
1842 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1845 if (*pwm) /* found already loaded module */
1847 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1849 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1851 TRACE("Found %s for %s at %p, count=%d\n",
1852 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1853 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1854 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1855 return STATUS_SUCCESS;
1858 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1859 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1861 switch(loadorder)
1863 case LO_INVALID:
1864 nts = STATUS_NO_MEMORY;
1865 break;
1866 case LO_DISABLED:
1867 nts = STATUS_DLL_NOT_FOUND;
1868 break;
1869 case LO_NATIVE:
1870 case LO_NATIVE_BUILTIN:
1871 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1872 else
1874 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1875 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1876 /* not in PE format, maybe it's a builtin */
1877 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1879 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1880 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1881 break;
1882 case LO_BUILTIN:
1883 case LO_BUILTIN_NATIVE:
1884 case LO_DEFAULT: /* default is builtin,native */
1885 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1886 if (!handle) break; /* nothing else we can try */
1887 /* file is not a builtin library, try without using the specified file */
1888 if (nts != STATUS_SUCCESS)
1889 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1890 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1891 !MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ))
1893 /* stub-only dll, try native */
1894 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1895 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1896 nts = STATUS_DLL_NOT_FOUND;
1898 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1899 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1900 break;
1903 if (nts == STATUS_SUCCESS)
1905 /* Initialize DLL just loaded */
1906 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1907 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1908 (*pwm)->ldr.BaseAddress);
1909 if (handle) NtClose( handle );
1910 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1911 return nts;
1914 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1915 if (handle) NtClose( handle );
1916 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1917 return nts;
1920 /******************************************************************
1921 * LdrLoadDll (NTDLL.@)
1923 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1924 const UNICODE_STRING *libname, HMODULE* hModule)
1926 WINE_MODREF *wm;
1927 NTSTATUS nts;
1929 RtlEnterCriticalSection( &loader_section );
1931 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1932 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1934 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1936 nts = process_attach( wm, NULL );
1937 if (nts != STATUS_SUCCESS)
1939 LdrUnloadDll(wm->ldr.BaseAddress);
1940 wm = NULL;
1943 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1945 RtlLeaveCriticalSection( &loader_section );
1946 return nts;
1950 /******************************************************************
1951 * LdrGetDllHandle (NTDLL.@)
1953 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1955 NTSTATUS status;
1956 WCHAR buffer[128];
1957 WCHAR *filename;
1958 ULONG size;
1959 WINE_MODREF *wm;
1961 RtlEnterCriticalSection( &loader_section );
1963 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1965 filename = buffer;
1966 size = sizeof(buffer);
1967 for (;;)
1969 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1970 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1971 if (status != STATUS_BUFFER_TOO_SMALL) break;
1972 /* grow the buffer and retry */
1973 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1975 status = STATUS_NO_MEMORY;
1976 break;
1980 if (status == STATUS_SUCCESS)
1982 if (wm) *base = wm->ldr.BaseAddress;
1983 else status = STATUS_DLL_NOT_FOUND;
1986 RtlLeaveCriticalSection( &loader_section );
1987 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
1988 return status;
1992 /******************************************************************
1993 * LdrAddRefDll (NTDLL.@)
1995 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
1997 NTSTATUS ret = STATUS_SUCCESS;
1998 WINE_MODREF *wm;
2000 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2002 RtlEnterCriticalSection( &loader_section );
2004 if ((wm = get_modref( module )))
2006 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2007 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2009 else ret = STATUS_INVALID_PARAMETER;
2011 RtlLeaveCriticalSection( &loader_section );
2012 return ret;
2016 /******************************************************************
2017 * LdrQueryProcessModuleInformation
2020 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2021 ULONG buf_size, ULONG* req_size)
2023 SYSTEM_MODULE* sm = &smi->Modules[0];
2024 ULONG size = sizeof(ULONG);
2025 NTSTATUS nts = STATUS_SUCCESS;
2026 ANSI_STRING str;
2027 char* ptr;
2028 PLIST_ENTRY mark, entry;
2029 PLDR_MODULE mod;
2030 WORD id = 0;
2032 smi->ModulesCount = 0;
2034 RtlEnterCriticalSection( &loader_section );
2035 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2036 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2038 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2039 size += sizeof(*sm);
2040 if (size <= buf_size)
2042 sm->Reserved1 = 0; /* FIXME */
2043 sm->Reserved2 = 0; /* FIXME */
2044 sm->ImageBaseAddress = mod->BaseAddress;
2045 sm->ImageSize = mod->SizeOfImage;
2046 sm->Flags = mod->Flags;
2047 sm->Id = id++;
2048 sm->Rank = 0; /* FIXME */
2049 sm->Unknown = 0; /* FIXME */
2050 str.Length = 0;
2051 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2052 str.Buffer = (char*)sm->Name;
2053 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2054 ptr = strrchr(str.Buffer, '\\');
2055 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2057 smi->ModulesCount++;
2058 sm++;
2060 else nts = STATUS_INFO_LENGTH_MISMATCH;
2062 RtlLeaveCriticalSection( &loader_section );
2064 if (req_size) *req_size = size;
2066 return nts;
2070 /******************************************************************
2071 * RtlDllShutdownInProgress (NTDLL.@)
2073 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2075 return process_detaching;
2079 /******************************************************************
2080 * LdrShutdownProcess (NTDLL.@)
2083 void WINAPI LdrShutdownProcess(void)
2085 TRACE("()\n");
2086 process_detach( TRUE, (LPVOID)1 );
2089 /******************************************************************
2090 * LdrShutdownThread (NTDLL.@)
2093 void WINAPI LdrShutdownThread(void)
2095 PLIST_ENTRY mark, entry;
2096 PLDR_MODULE mod;
2098 TRACE("()\n");
2100 /* don't do any detach calls if process is exiting */
2101 if (process_detaching) return;
2102 /* FIXME: there is still a race here */
2104 RtlEnterCriticalSection( &loader_section );
2106 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2107 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2109 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2110 InInitializationOrderModuleList);
2111 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2112 continue;
2113 if ( mod->Flags & LDR_NO_DLL_CALLS )
2114 continue;
2116 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2117 DLL_THREAD_DETACH, NULL );
2120 RtlLeaveCriticalSection( &loader_section );
2121 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2125 /***********************************************************************
2126 * free_modref
2129 static void free_modref( WINE_MODREF *wm )
2131 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2132 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2133 if (wm->ldr.InInitializationOrderModuleList.Flink)
2134 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2136 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2137 if (!TRACE_ON(module))
2138 TRACE_(loaddll)("Unloaded module %s : %s\n",
2139 debugstr_w(wm->ldr.FullDllName.Buffer),
2140 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2142 SERVER_START_REQ( unload_dll )
2144 req->base = wm->ldr.BaseAddress;
2145 wine_server_call( req );
2147 SERVER_END_REQ;
2149 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2150 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2151 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2152 if (cached_modref == wm) cached_modref = NULL;
2153 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2154 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2155 RtlFreeHeap( GetProcessHeap(), 0, wm );
2158 /***********************************************************************
2159 * MODULE_FlushModrefs
2161 * Remove all unused modrefs and call the internal unloading routines
2162 * for the library type.
2164 * The loader_section must be locked while calling this function.
2166 static void MODULE_FlushModrefs(void)
2168 PLIST_ENTRY mark, entry, prev;
2169 PLDR_MODULE mod;
2170 WINE_MODREF*wm;
2172 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2173 for (entry = mark->Blink; entry != mark; entry = prev)
2175 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2176 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2177 prev = entry->Blink;
2178 if (!mod->LoadCount) free_modref( wm );
2181 /* check load order list too for modules that haven't been initialized yet */
2182 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2183 for (entry = mark->Blink; entry != mark; entry = prev)
2185 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2186 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2187 prev = entry->Blink;
2188 if (!mod->LoadCount) free_modref( wm );
2192 /***********************************************************************
2193 * MODULE_DecRefCount
2195 * The loader_section must be locked while calling this function.
2197 static void MODULE_DecRefCount( WINE_MODREF *wm )
2199 int i;
2201 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2202 return;
2204 if ( wm->ldr.LoadCount <= 0 )
2205 return;
2207 --wm->ldr.LoadCount;
2208 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2210 if ( wm->ldr.LoadCount == 0 )
2212 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2214 for ( i = 0; i < wm->nDeps; i++ )
2215 if ( wm->deps[i] )
2216 MODULE_DecRefCount( wm->deps[i] );
2218 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2222 /******************************************************************
2223 * LdrUnloadDll (NTDLL.@)
2227 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2229 NTSTATUS retv = STATUS_SUCCESS;
2231 TRACE("(%p)\n", hModule);
2233 RtlEnterCriticalSection( &loader_section );
2235 /* if we're stopping the whole process (and forcing the removal of all
2236 * DLLs) the library will be freed anyway
2238 if (!process_detaching)
2240 WINE_MODREF *wm;
2242 free_lib_count++;
2243 if ((wm = get_modref( hModule )) != NULL)
2245 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2247 /* Recursively decrement reference counts */
2248 MODULE_DecRefCount( wm );
2250 /* Call process detach notifications */
2251 if ( free_lib_count <= 1 )
2253 process_detach( FALSE, NULL );
2254 MODULE_FlushModrefs();
2257 TRACE("END\n");
2259 else
2260 retv = STATUS_DLL_NOT_FOUND;
2262 free_lib_count--;
2265 RtlLeaveCriticalSection( &loader_section );
2267 return retv;
2270 /***********************************************************************
2271 * RtlImageNtHeader (NTDLL.@)
2273 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2275 IMAGE_NT_HEADERS *ret;
2277 __TRY
2279 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2281 ret = NULL;
2282 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2284 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2285 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2288 __EXCEPT_PAGE_FAULT
2290 return NULL;
2292 __ENDTRY
2293 return ret;
2297 /******************************************************************
2298 * LdrInitializeThunk (NTDLL.@)
2301 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2303 NTSTATUS status;
2304 WINE_MODREF *wm;
2305 LPCWSTR load_path;
2306 PEB *peb = NtCurrentTeb()->Peb;
2307 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2309 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2311 /* allocate the modref for the main exe (if not already done) */
2312 wm = get_modref( peb->ImageBaseAddress );
2313 assert( wm );
2314 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2316 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2317 exit(1);
2320 peb->LoaderLock = &loader_section;
2321 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2322 version_init( wm->ldr.FullDllName.Buffer );
2324 /* the main exe needs to be the first in the load order list */
2325 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2326 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2328 status = server_init_process_done();
2329 if (status != STATUS_SUCCESS) goto error;
2331 RtlEnterCriticalSection( &loader_section );
2333 actctx_init();
2334 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2335 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2336 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2337 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2339 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2341 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2343 if (last_failed_modref)
2344 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2345 goto error;
2347 attach_implicitly_loaded_dlls( (LPVOID)1 );
2349 RtlLeaveCriticalSection( &loader_section );
2351 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2352 return;
2354 error:
2355 ERR( "Main exe initialization for %s failed, status %x\n",
2356 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2357 NtTerminateProcess( GetCurrentProcess(), status );
2361 /***********************************************************************
2362 * RtlImageDirectoryEntryToData (NTDLL.@)
2364 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2366 const IMAGE_NT_HEADERS *nt;
2367 DWORD addr;
2369 if ((ULONG_PTR)module & 1) /* mapped as data file */
2371 module = (HMODULE)((ULONG_PTR)module & ~1);
2372 image = FALSE;
2374 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2375 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2376 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2377 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2378 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2380 /* not mapped as image, need to find the section containing the virtual address */
2381 return RtlImageRvaToVa( nt, module, addr, NULL );
2385 /***********************************************************************
2386 * RtlImageRvaToSection (NTDLL.@)
2388 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2389 HMODULE module, DWORD rva )
2391 int i;
2392 const IMAGE_SECTION_HEADER *sec;
2394 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2395 nt->FileHeader.SizeOfOptionalHeader);
2396 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2398 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2399 return (PIMAGE_SECTION_HEADER)sec;
2401 return NULL;
2405 /***********************************************************************
2406 * RtlImageRvaToVa (NTDLL.@)
2408 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2409 DWORD rva, IMAGE_SECTION_HEADER **section )
2411 IMAGE_SECTION_HEADER *sec;
2413 if (section && *section) /* try this section first */
2415 sec = *section;
2416 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2417 goto found;
2419 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2420 found:
2421 if (section) *section = sec;
2422 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2426 /***********************************************************************
2427 * RtlPcToFileHeader (NTDLL.@)
2429 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2431 LDR_MODULE *module;
2432 PVOID ret = NULL;
2434 RtlEnterCriticalSection( &loader_section );
2435 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2436 RtlLeaveCriticalSection( &loader_section );
2437 *address = ret;
2438 return ret;
2442 /***********************************************************************
2443 * NtLoadDriver (NTDLL.@)
2444 * ZwLoadDriver (NTDLL.@)
2446 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2448 FIXME("(%p), stub!\n",DriverServiceName);
2449 return STATUS_NOT_IMPLEMENTED;
2453 /***********************************************************************
2454 * NtUnloadDriver (NTDLL.@)
2455 * ZwUnloadDriver (NTDLL.@)
2457 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2459 FIXME("(%p), stub!\n",DriverServiceName);
2460 return STATUS_NOT_IMPLEMENTED;
2464 /******************************************************************
2465 * DllMain (NTDLL.@)
2467 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2469 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2470 return TRUE;
2474 /******************************************************************
2475 * __wine_init_windows_dir (NTDLL.@)
2477 * Windows and system dir initialization once kernel32 has been loaded.
2479 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2481 PLIST_ENTRY mark, entry;
2482 LPWSTR buffer, p;
2484 RtlCreateUnicodeString( &windows_dir, windir );
2485 RtlCreateUnicodeString( &system_dir, sysdir );
2486 strcpyW( user_shared_data->NtSystemRoot, windir );
2488 /* prepend the system dir to the name of the already created modules */
2489 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2490 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2492 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2494 assert( mod->Flags & LDR_WINE_INTERNAL );
2496 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2497 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2498 if (!buffer) continue;
2499 strcpyW( buffer, system_dir.Buffer );
2500 p = buffer + strlenW( buffer );
2501 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2502 strcpyW( p, mod->FullDllName.Buffer );
2503 RtlInitUnicodeString( &mod->FullDllName, buffer );
2504 RtlInitUnicodeString( &mod->BaseDllName, p );
2509 /***********************************************************************
2510 * __wine_process_init
2512 void __wine_process_init(void)
2514 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2516 WINE_MODREF *wm;
2517 NTSTATUS status;
2518 ANSI_STRING func_name;
2519 void (* DECLSPEC_NORETURN init_func)(void);
2520 extern mode_t FILE_umask;
2522 main_exe_file = thread_init();
2524 /* retrieve current umask */
2525 FILE_umask = umask(0777);
2526 umask( FILE_umask );
2528 /* setup the load callback and create ntdll modref */
2529 wine_dll_set_callback( load_builtin_callback );
2531 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2533 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2534 exit(1);
2536 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2537 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2538 0, (void **)&init_func )) != STATUS_SUCCESS)
2540 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2541 exit(1);
2543 init_func();