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
23 #include "wine/port.h"
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
35 #define WIN32_NO_STATUS
40 #include "wine/exception.h"
41 #include "wine/library.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
52 WINE_DECLARE_DEBUG_CHANNEL(imports);
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
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[] =
69 NULL, NULL, NULL, NULL,
73 static const WCHAR dllW[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
80 struct _wine_modref **deps;
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;
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 */
100 #define TLS_ALIGNMENT (2 * sizeof(void *))
101 #define TLS_ALIGN(size) (((size) + TLS_ALIGNMENT - 1) & ~(TLS_ALIGNMENT - 1))
103 static RTL_CRITICAL_SECTION loader_section;
104 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
106 0, 0, &loader_section,
107 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
108 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
110 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
112 static WINE_MODREF *cached_modref;
113 static WINE_MODREF *current_modref;
114 static WINE_MODREF *last_failed_modref;
116 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
117 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
118 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
119 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
120 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
121 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
123 /* convert PE image VirtualAddress to Real Address */
124 static inline void *get_rva( HMODULE module, DWORD va )
126 return (void *)((char *)module + va);
129 /* check whether the file name contains a path */
130 static inline int contains_path( LPCWSTR name )
132 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
135 /* convert from straight ASCII to Unicode without depending on the current codepage */
136 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
138 while (len--) *dst++ = (unsigned char)*src++;
142 /*************************************************************************
143 * call_dll_entry_point
145 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
146 * their entry point, so we need a small asm wrapper.
149 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
150 __ASM_GLOBAL_FUNC(call_dll_entry_point,
152 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
153 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
155 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
157 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
162 "movl 8(%ebp),%eax\n\t"
164 "leal -4(%ebp),%esp\n\t"
166 __ASM_CFI(".cfi_same_value %ebx\n\t")
168 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
169 __ASM_CFI(".cfi_same_value %ebp\n\t")
172 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
173 UINT reason, void *reserved )
175 return proc( module, reason, reserved );
177 #endif /* __i386__ */
180 #if defined(__i386__) || defined(__x86_64__)
181 /*************************************************************************
184 * Entry point for stub functions.
186 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
188 EXCEPTION_RECORD rec;
190 rec.ExceptionCode = EXCEPTION_WINE_STUB;
191 rec.ExceptionFlags = EH_NONCONTINUABLE;
192 rec.ExceptionRecord = NULL;
193 rec.ExceptionAddress = ret_addr;
194 rec.NumberParameters = 2;
195 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
196 rec.ExceptionInformation[1] = (ULONG_PTR)name;
197 for (;;) RtlRaiseException( &rec );
201 #include "pshpack1.h"
205 BYTE pushl1; /* pushl $name */
207 BYTE pushl2; /* pushl $dll */
209 BYTE call; /* call stub_entry_point */
215 BYTE movq_rdi[2]; /* movq $dll,%rdi */
217 BYTE movq_rsi[2]; /* movq $name,%rsi */
219 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
220 BYTE movq_rax[2]; /* movq $entry, %rax */
222 BYTE jmpq_rax[2]; /* jmp %rax */
227 /*************************************************************************
230 * Allocate a stub entry point.
232 static ULONG_PTR allocate_stub( const char *dll, const char *name )
234 #define MAX_SIZE 65536
235 static struct stub *stubs;
236 static unsigned int nb_stubs;
239 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
243 SIZE_T size = MAX_SIZE;
244 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
245 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
248 stub = &stubs[nb_stubs++];
250 stub->pushl1 = 0x68; /* pushl $name */
252 stub->pushl2 = 0x68; /* pushl $dll */
254 stub->call = 0xe8; /* call stub_entry_point */
255 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
257 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
258 stub->movq_rdi[1] = 0xbf;
260 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
261 stub->movq_rsi[1] = 0xbe;
263 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
264 stub->movq_rsp_rdx[1] = 0x8b;
265 stub->movq_rsp_rdx[2] = 0x14;
266 stub->movq_rsp_rdx[3] = 0x24;
267 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
268 stub->movq_rax[1] = 0xb8;
269 stub->entry = stub_entry_point;
270 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
271 stub->jmpq_rax[1] = 0xe0;
273 return (ULONG_PTR)stub;
277 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
278 #endif /* __i386__ */
281 /*************************************************************************
284 * Looks for the referenced HMODULE in the current process
285 * The loader_section must be locked while calling this function.
287 static WINE_MODREF *get_modref( HMODULE hmod )
289 PLIST_ENTRY mark, entry;
292 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
294 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
295 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
297 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
298 if (mod->BaseAddress == hmod)
299 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
300 if (mod->BaseAddress > (void*)hmod) break;
306 /**********************************************************************
307 * find_basename_module
309 * Find a module from its base name.
310 * The loader_section must be locked while calling this function
312 static WINE_MODREF *find_basename_module( LPCWSTR name )
314 PLIST_ENTRY mark, entry;
316 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
317 return cached_modref;
319 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
320 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
322 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
323 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
325 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
326 return cached_modref;
333 /**********************************************************************
334 * find_fullname_module
336 * Find a module from its full path name.
337 * The loader_section must be locked while calling this function
339 static WINE_MODREF *find_fullname_module( LPCWSTR name )
341 PLIST_ENTRY mark, entry;
343 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
344 return cached_modref;
346 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
347 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
349 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
350 if (!strcmpiW( name, mod->FullDllName.Buffer ))
352 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
353 return cached_modref;
360 /*************************************************************************
361 * find_forwarded_export
363 * Find the final function pointer for a forwarded function.
364 * The loader_section must be locked while calling this function.
366 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
368 const IMAGE_EXPORT_DIRECTORY *exports;
372 const char *end = strrchr(forward, '.');
375 if (!end) return NULL;
376 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
377 ascii_to_unicode( mod_name, forward, end - forward );
378 mod_name[end - forward] = 0;
379 if (!strchrW( mod_name, '.' ))
381 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
382 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
385 if (!(wm = find_basename_module( mod_name )))
387 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
388 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
389 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
391 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
393 LdrUnloadDll( wm->ldr.BaseAddress );
400 ERR( "module not found for forward '%s' used by %s\n",
401 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
405 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
406 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
408 const char *name = end + 1;
409 if (*name == '#') /* ordinal */
410 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
412 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
417 ERR("function not found for forward '%s' used by %s."
418 " If you are using builtin %s, try using the native one instead.\n",
419 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
420 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
426 /*************************************************************************
427 * find_ordinal_export
429 * Find an exported function by ordinal.
430 * The exports base must have been subtracted from the ordinal already.
431 * The loader_section must be locked while calling this function.
433 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
434 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
437 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
439 if (ordinal >= exports->NumberOfFunctions)
441 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
444 if (!functions[ordinal]) return NULL;
446 proc = get_rva( module, functions[ordinal] );
448 /* if the address falls into the export dir, it's a forward */
449 if (((const char *)proc >= (const char *)exports) &&
450 ((const char *)proc < (const char *)exports + exp_size))
451 return find_forwarded_export( module, (const char *)proc, load_path );
455 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
456 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
460 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
461 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
467 /*************************************************************************
470 * Find an exported function by name.
471 * The loader_section must be locked while calling this function.
473 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
474 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
476 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
477 const DWORD *names = get_rva( module, exports->AddressOfNames );
478 int min = 0, max = exports->NumberOfNames - 1;
480 /* first check the hint */
481 if (hint >= 0 && hint <= max)
483 char *ename = get_rva( module, names[hint] );
484 if (!strcmp( ename, name ))
485 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
488 /* then do a binary search */
491 int res, pos = (min + max) / 2;
492 char *ename = get_rva( module, names[pos] );
493 if (!(res = strcmp( ename, name )))
494 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
495 if (res > 0) max = pos - 1;
503 /*************************************************************************
506 * Import the dll specified by the given import descriptor.
507 * The loader_section must be locked while calling this function.
509 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
514 const IMAGE_EXPORT_DIRECTORY *exports;
516 const IMAGE_THUNK_DATA *import_list;
517 IMAGE_THUNK_DATA *thunk_list;
519 const char *name = get_rva( module, descr->Name );
520 DWORD len = strlen(name);
522 SIZE_T protect_size = 0;
525 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
526 if (descr->u.OriginalFirstThunk)
527 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
529 import_list = thunk_list;
531 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
533 if (len * sizeof(WCHAR) < sizeof(buffer))
535 ascii_to_unicode( buffer, name, len );
537 status = load_dll( load_path, buffer, 0, &wmImp );
539 else /* need to allocate a larger buffer */
541 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
542 if (!ptr) return NULL;
543 ascii_to_unicode( ptr, name, len );
545 status = load_dll( load_path, ptr, 0, &wmImp );
546 RtlFreeHeap( GetProcessHeap(), 0, ptr );
551 if (status == STATUS_DLL_NOT_FOUND)
552 ERR("Library %s (which is needed by %s) not found\n",
553 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
555 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
556 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
560 /* unprotect the import address table since it can be located in
561 * readonly section */
562 while (import_list[protect_size].u1.Ordinal) protect_size++;
563 protect_base = thunk_list;
564 protect_size *= sizeof(*thunk_list);
565 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
566 &protect_size, PAGE_WRITECOPY, &protect_old );
568 imp_mod = wmImp->ldr.BaseAddress;
569 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
573 /* set all imported function to deadbeef */
574 while (import_list->u1.Ordinal)
576 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
578 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
579 WARN("No implementation for %s.%d", name, ordinal );
580 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
584 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
585 WARN("No implementation for %s.%s", name, pe_name->Name );
586 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
588 WARN(" imported from %s, allocating stub %p\n",
589 debugstr_w(current_modref->ldr.FullDllName.Buffer),
590 (void *)thunk_list->u1.Function );
597 while (import_list->u1.Ordinal)
599 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
601 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
603 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
604 ordinal - exports->Base, load_path );
605 if (!thunk_list->u1.Function)
607 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
608 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
609 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
610 (void *)thunk_list->u1.Function );
612 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
614 else /* import by name */
616 IMAGE_IMPORT_BY_NAME *pe_name;
617 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
618 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
619 (const char*)pe_name->Name,
620 pe_name->Hint, load_path );
621 if (!thunk_list->u1.Function)
623 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
624 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
625 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
626 (void *)thunk_list->u1.Function );
628 TRACE_(imports)("--- %s %s.%d = %p\n",
629 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
636 /* restore old protection of the import address table */
637 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
642 /***********************************************************************
643 * create_module_activation_context
645 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
648 LDR_RESOURCE_INFO info;
649 const IMAGE_RESOURCE_DATA_ENTRY *entry;
651 info.Type = RT_MANIFEST;
652 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
654 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
657 ctx.cbSize = sizeof(ctx);
659 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
660 ctx.hModule = module->BaseAddress;
661 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
662 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
668 /****************************************************************
671 * Fixup all imports of a given module.
672 * The loader_section must be locked while calling this function.
674 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
677 const IMAGE_IMPORT_DESCRIPTOR *imports;
683 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
684 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
686 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
687 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
688 return STATUS_SUCCESS;
691 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
693 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
695 if (!create_module_activation_context( &wm->ldr ))
696 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
698 /* Allocate module dependency list */
699 wm->nDeps = nb_imports;
700 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
702 /* load the imported modules. They are automatically
703 * added to the modref list of the process.
705 prev = current_modref;
707 status = STATUS_SUCCESS;
708 for (i = 0; i < nb_imports; i++)
710 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
711 status = STATUS_DLL_NOT_FOUND;
713 current_modref = prev;
714 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
719 /*************************************************************************
720 * is_dll_native_subsystem
722 * Check if dll is a proper native driver.
723 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
724 * while being perfectly normal DLLs. This heuristic should catch such breakages.
726 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
728 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
729 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
730 const IMAGE_IMPORT_DESCRIPTOR *imports;
734 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
735 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
737 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
738 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
740 for (i = 0; imports[i].Name; i++)
742 const char *name = get_rva( module, imports[i].Name );
743 DWORD len = strlen(name);
744 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
745 ascii_to_unicode( buffer, name, len + 1 );
746 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
748 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
757 /*************************************************************************
760 * Allocate a WINE_MODREF structure and add it to the process list
761 * The loader_section must be locked while calling this function.
763 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
767 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
768 PLIST_ENTRY entry, mark;
770 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
775 wm->ldr.BaseAddress = hModule;
776 wm->ldr.EntryPoint = NULL;
777 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
778 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
779 wm->ldr.LoadCount = 1;
780 wm->ldr.TlsIndex = -1;
781 wm->ldr.SectionHandle = NULL;
782 wm->ldr.CheckSum = 0;
783 wm->ldr.TimeDateStamp = 0;
784 wm->ldr.ActivationContext = 0;
786 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
787 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
788 else p = wm->ldr.FullDllName.Buffer;
789 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
791 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
793 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
794 if (nt->OptionalHeader.AddressOfEntryPoint)
795 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
798 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
799 &wm->ldr.InLoadOrderModuleList);
801 /* insert module in MemoryList, sorted in increasing base addresses */
802 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
803 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
805 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
808 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
809 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
810 wm->ldr.InMemoryOrderModuleList.Flink = entry;
811 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
813 /* wait until init is called for inserting into this list */
814 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
815 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
817 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
819 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
820 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
821 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
827 /*************************************************************************
830 * Allocate the process-wide structure for module TLS storage.
832 static NTSTATUS alloc_process_tls(void)
834 PLIST_ENTRY mark, entry;
836 const IMAGE_TLS_DIRECTORY *dir;
839 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
840 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
842 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
843 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
844 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
846 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
847 if (!size && !dir->AddressOfCallBacks) continue;
848 tls_total_size += TLS_ALIGN(size);
851 if (!tls_module_count) return STATUS_SUCCESS;
853 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
855 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
856 if (!tls_dirs) return STATUS_NO_MEMORY;
858 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
860 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
861 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
862 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
865 *(DWORD *)dir->AddressOfIndex = i;
867 mod->LoadCount = -1; /* can't unload it */
870 return STATUS_SUCCESS;
874 /*************************************************************************
877 * Allocate the per-thread structure for module TLS storage.
879 static NTSTATUS alloc_thread_tls(void)
885 if (!tls_module_count) return STATUS_SUCCESS;
887 size = TLS_ALIGN( tls_module_count * sizeof(*pointers) );
888 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0, size + tls_total_size )))
889 return STATUS_NO_MEMORY;
890 data = (char *)pointers + size;
892 for (i = 0; i < tls_module_count; i++)
894 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
895 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
897 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
898 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
899 (void *)dir->StartAddressOfRawData, data );
902 memcpy( data, (void *)dir->StartAddressOfRawData, size );
903 memset( data + size, 0, dir->SizeOfZeroFill );
904 data += TLS_ALIGN( size + dir->SizeOfZeroFill );
906 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
907 return STATUS_SUCCESS;
911 /*************************************************************************
914 static void call_tls_callbacks( HMODULE module, UINT reason )
916 const IMAGE_TLS_DIRECTORY *dir;
917 const PIMAGE_TLS_CALLBACK *callback;
920 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
921 if (!dir || !dir->AddressOfCallBacks) return;
923 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
926 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
927 GetCurrentThreadId(), *callback, module, reason_names[reason] );
930 (*callback)( module, reason, NULL );
935 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
936 GetCurrentThreadId(), callback, module, reason_names[reason] );
941 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
942 GetCurrentThreadId(), *callback, module, reason_names[reason] );
947 /*************************************************************************
950 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
953 NTSTATUS status = STATUS_SUCCESS;
954 DLLENTRYPROC entry = wm->ldr.EntryPoint;
955 void *module = wm->ldr.BaseAddress;
958 /* Skip calls for modules loaded with special load flags */
960 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
961 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
962 if (!entry) return STATUS_SUCCESS;
966 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
967 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
968 mod_name[len / sizeof(WCHAR)] = 0;
969 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
970 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
971 reason_names[reason], lpReserved );
973 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
974 reason_names[reason], lpReserved );
978 retv = call_dll_entry_point( entry, module, reason, lpReserved );
980 status = STATUS_DLL_INIT_FAILED;
985 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
986 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
987 status = GetExceptionCode();
991 /* The state of the module list may have changed due to the call
992 to the dll. We cannot assume that this module has not been
995 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
996 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
997 reason_names[reason], lpReserved, retv );
998 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1004 /*************************************************************************
1007 * Send the process attach notification to all DLLs the given module
1008 * depends on (recursively). This is somewhat complicated due to the fact that
1010 * - we have to respect the module dependencies, i.e. modules implicitly
1011 * referenced by another module have to be initialized before the module
1012 * itself can be initialized
1014 * - the initialization routine of a DLL can itself call LoadLibrary,
1015 * thereby introducing a whole new set of dependencies (even involving
1016 * the 'old' modules) at any time during the whole process
1018 * (Note that this routine can be recursively entered not only directly
1019 * from itself, but also via LoadLibrary from one of the called initialization
1022 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1023 * the process *detach* notifications to be sent in the correct order.
1024 * This must not only take into account module dependencies, but also
1025 * 'hidden' dependencies created by modules calling LoadLibrary in their
1026 * attach notification routine.
1028 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1029 * list after the attach notification has returned. This implies that the
1030 * detach notifications are called in the reverse of the sequence the attach
1031 * notifications *returned*.
1033 * The loader_section must be locked while calling this function.
1035 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1037 NTSTATUS status = STATUS_SUCCESS;
1041 if (process_detaching) return status;
1043 /* prevent infinite recursion in case of cyclical dependencies */
1044 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1045 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1048 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1050 /* Tag current MODREF to prevent recursive loop */
1051 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1052 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1053 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1055 /* Recursively attach all DLLs this one depends on */
1056 for ( i = 0; i < wm->nDeps; i++ )
1058 if (!wm->deps[i]) continue;
1059 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1062 /* Call DLL entry point */
1063 if (status == STATUS_SUCCESS)
1065 WINE_MODREF *prev = current_modref;
1066 current_modref = wm;
1067 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1068 if (status == STATUS_SUCCESS)
1069 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1072 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1073 /* point to the name so LdrInitializeThunk can print it */
1074 last_failed_modref = wm;
1075 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1077 current_modref = prev;
1080 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1081 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1082 &wm->ldr.InInitializationOrderModuleList);
1084 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1085 /* Remove recursion flag */
1086 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1088 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1093 /**********************************************************************
1094 * attach_implicitly_loaded_dlls
1096 * Attach to the (builtin) dlls that have been implicitly loaded because
1097 * of a dependency at the Unix level, but not imported at the Win32 level.
1099 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1103 PLIST_ENTRY mark, entry;
1105 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1106 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1108 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1110 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1111 TRACE( "found implicitly loaded %s, attaching to it\n",
1112 debugstr_w(mod->BaseDllName.Buffer));
1113 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1114 break; /* restart the search from the start */
1116 if (entry == mark) break; /* nothing found */
1121 /*************************************************************************
1124 * Send DLL process detach notifications. See the comment about calling
1125 * sequence at process_attach. Unless the bForceDetach flag
1126 * is set, only DLLs with zero refcount are notified.
1128 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1130 PLIST_ENTRY mark, entry;
1133 RtlEnterCriticalSection( &loader_section );
1134 if (bForceDetach) process_detaching = 1;
1135 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1138 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1140 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1141 InInitializationOrderModuleList);
1142 /* Check whether to detach this DLL */
1143 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1145 if ( mod->LoadCount && !bForceDetach )
1148 /* Call detach notification */
1149 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1150 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1151 DLL_PROCESS_DETACH, lpReserved );
1153 /* Restart at head of WINE_MODREF list, as entries might have
1154 been added and/or removed while performing the call ... */
1157 } while (entry != mark);
1159 RtlLeaveCriticalSection( &loader_section );
1162 /*************************************************************************
1163 * MODULE_DllThreadAttach
1165 * Send DLL thread attach notifications. These are sent in the
1166 * reverse sequence of process detach notification.
1169 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1171 PLIST_ENTRY mark, entry;
1175 /* don't do any attach calls if process is exiting */
1176 if (process_detaching) return STATUS_SUCCESS;
1177 /* FIXME: there is still a race here */
1179 RtlEnterCriticalSection( &loader_section );
1181 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1183 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1184 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1186 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1187 InInitializationOrderModuleList);
1188 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1190 if ( mod->Flags & LDR_NO_DLL_CALLS )
1193 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1194 DLL_THREAD_ATTACH, lpReserved );
1198 RtlLeaveCriticalSection( &loader_section );
1202 /******************************************************************
1203 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1206 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1209 NTSTATUS ret = STATUS_SUCCESS;
1211 RtlEnterCriticalSection( &loader_section );
1213 wm = get_modref( hModule );
1214 if (!wm || wm->ldr.TlsIndex != -1)
1215 ret = STATUS_DLL_NOT_FOUND;
1217 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1219 RtlLeaveCriticalSection( &loader_section );
1224 /******************************************************************
1225 * LdrFindEntryForAddress (NTDLL.@)
1227 * The loader_section must be locked while calling this function
1229 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1231 PLIST_ENTRY mark, entry;
1234 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1235 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1237 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1238 if (mod->BaseAddress <= addr &&
1239 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1242 return STATUS_SUCCESS;
1244 if (mod->BaseAddress > addr) break;
1246 return STATUS_NO_MORE_ENTRIES;
1249 /******************************************************************
1250 * LdrLockLoaderLock (NTDLL.@)
1252 * Note: flags are not implemented.
1253 * Flag 0x01 is used to raise exceptions on errors.
1254 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1256 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1258 if (flags) FIXME( "flags %x not supported\n", flags );
1260 if (result) *result = 1;
1261 if (!magic) return STATUS_INVALID_PARAMETER_3;
1262 RtlEnterCriticalSection( &loader_section );
1263 *magic = GetCurrentThreadId();
1264 return STATUS_SUCCESS;
1268 /******************************************************************
1269 * LdrUnlockLoaderUnlock (NTDLL.@)
1271 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1275 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1276 RtlLeaveCriticalSection( &loader_section );
1278 return STATUS_SUCCESS;
1282 /******************************************************************
1283 * LdrGetProcedureAddress (NTDLL.@)
1285 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1286 ULONG ord, PVOID *address)
1288 IMAGE_EXPORT_DIRECTORY *exports;
1290 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1292 RtlEnterCriticalSection( &loader_section );
1294 /* check if the module itself is invalid to return the proper error */
1295 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1296 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1297 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1299 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1300 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1301 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1305 ret = STATUS_SUCCESS;
1309 RtlLeaveCriticalSection( &loader_section );
1314 /***********************************************************************
1317 * Check if a loaded native dll is a Wine fake dll.
1319 static BOOL is_fake_dll( HANDLE handle )
1321 static const char fakedll_signature[] = "Wine placeholder DLL";
1322 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1323 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1325 LARGE_INTEGER offset;
1327 offset.QuadPart = 0;
1328 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1329 if (io.Information < sizeof(buffer)) return FALSE;
1330 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1331 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1332 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1337 /***********************************************************************
1338 * get_builtin_fullname
1340 * Build the full pathname for a builtin dll.
1342 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1344 static const WCHAR soW[] = {'.','s','o',0};
1345 WCHAR *p, *fullname;
1346 size_t i, len = strlen(filename);
1348 /* check if path can correspond to the dll we have */
1349 if (path && (p = strrchrW( path, '\\' )))
1352 for (i = 0; i < len; i++)
1353 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1354 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1356 /* the filename matches, use path as the full path */
1358 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1360 memcpy( fullname, path, len * sizeof(WCHAR) );
1367 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1368 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1370 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1371 p = fullname + system_dir.Length / sizeof(WCHAR);
1372 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1373 ascii_to_unicode( p, filename, len + 1 );
1379 /***********************************************************************
1380 * load_builtin_callback
1382 * Load a library in memory; callback function for wine_dll_register
1384 static void load_builtin_callback( void *module, const char *filename )
1386 static const WCHAR emptyW[1];
1387 IMAGE_NT_HEADERS *nt;
1390 const WCHAR *load_path;
1394 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1397 if (!(nt = RtlImageNtHeader( module )))
1399 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1400 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1404 virtual_create_builtin_view( module );
1406 /* create the MODREF */
1408 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1410 ERR( "can't load %s\n", filename );
1411 builtin_load_info->status = STATUS_NO_MEMORY;
1415 wm = alloc_module( module, fullname );
1416 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1419 ERR( "can't load %s\n", filename );
1420 builtin_load_info->status = STATUS_NO_MEMORY;
1423 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1425 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1426 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1428 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1434 load_path = builtin_load_info->load_path;
1435 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1436 if (!load_path) load_path = emptyW;
1437 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1439 /* the module has only be inserted in the load & memory order lists */
1440 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1441 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1442 /* FIXME: free the modref */
1443 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1448 builtin_load_info->wm = wm;
1449 TRACE( "loaded %s %p %p\n", filename, wm, module );
1451 /* send the DLL load event */
1453 SERVER_START_REQ( load_dll )
1456 req->base = wine_server_client_ptr( module );
1457 req->size = nt->OptionalHeader.SizeOfImage;
1458 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1459 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1460 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1461 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1462 wine_server_call( req );
1466 /* setup relay debugging entry points */
1467 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1471 /******************************************************************************
1472 * load_native_dll (internal)
1474 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1475 DWORD flags, WINE_MODREF** pwm )
1480 IMAGE_NT_HEADERS *nt;
1485 TRACE("Trying native dll %s\n", debugstr_w(name));
1488 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1489 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1490 if (status != STATUS_SUCCESS) return status;
1493 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1494 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1495 if (status < 0) goto done;
1497 /* create the MODREF */
1499 if (!(wm = alloc_module( module, name )))
1501 status = STATUS_NO_MEMORY;
1507 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1509 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1511 /* the module has only be inserted in the load & memory order lists */
1512 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1513 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1515 /* FIXME: there are several more dangling references
1516 * left. Including dlls loaded by this dll before the
1517 * failed one. Unrolling is rather difficult with the
1518 * current structure and we can leave them lying
1519 * around with no problems, so we don't care.
1520 * As these might reference our wm, we don't free it.
1526 /* send DLL load event */
1528 nt = RtlImageNtHeader( module );
1530 SERVER_START_REQ( load_dll )
1532 req->mapping = wine_server_obj_handle( mapping );
1533 req->base = wine_server_client_ptr( module );
1534 req->size = nt->OptionalHeader.SizeOfImage;
1535 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1536 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1537 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1538 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1539 wine_server_call( req );
1543 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1545 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1547 wm->ldr.LoadCount = 1;
1549 status = STATUS_SUCCESS;
1556 /***********************************************************************
1559 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1560 DWORD flags, WINE_MODREF** pwm )
1562 char error[256], dllname[MAX_PATH];
1563 const WCHAR *name, *p;
1565 void *handle = NULL;
1566 struct builtin_load_info info, *prev_info;
1568 /* Fix the name in case we have a full path and extension */
1570 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1571 if ((p = strrchrW( name, '/' ))) name = p + 1;
1573 /* load_library will modify info.status. Note also that load_library can be
1574 * called several times, if the .so file we're loading has dependencies.
1575 * info.status will gather all the errors we may get while loading all these
1578 info.load_path = load_path;
1579 info.filename = NULL;
1580 info.status = STATUS_SUCCESS;
1583 if (file) /* we have a real file, try to load it */
1585 UNICODE_STRING nt_name;
1586 ANSI_STRING unix_name;
1588 TRACE("Trying built-in %s\n", debugstr_w(path));
1590 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1591 return STATUS_DLL_NOT_FOUND;
1593 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1595 RtlFreeUnicodeString( &nt_name );
1596 return STATUS_DLL_NOT_FOUND;
1598 prev_info = builtin_load_info;
1599 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1600 builtin_load_info = &info;
1601 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1602 builtin_load_info = prev_info;
1603 RtlFreeUnicodeString( &nt_name );
1604 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1607 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1608 return STATUS_INVALID_IMAGE_FORMAT;
1615 TRACE("Trying built-in %s\n", debugstr_w(name));
1617 /* we don't want to depend on the current codepage here */
1618 len = strlenW( name ) + 1;
1619 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1620 for (i = 0; i < len; i++)
1622 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1623 dllname[i] = (char)name[i];
1624 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1627 prev_info = builtin_load_info;
1628 builtin_load_info = &info;
1629 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1630 builtin_load_info = prev_info;
1635 /* The file does not exist -> WARN() */
1636 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1637 return STATUS_DLL_NOT_FOUND;
1639 /* ERR() for all other errors (missing functions, ...) */
1640 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1641 return STATUS_PROCEDURE_NOT_FOUND;
1645 if (info.status != STATUS_SUCCESS)
1647 wine_dll_unload( handle );
1653 PLIST_ENTRY mark, entry;
1655 /* The constructor wasn't called, this means the .so is already
1656 * loaded under a different name. Try to find the wm for it. */
1658 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1659 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1661 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1662 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1664 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1665 TRACE( "Found %s at %p for builtin %s\n",
1666 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1670 wine_dll_unload( handle ); /* release the libdl refcount */
1671 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1672 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1676 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1677 info.wm->ldr.LoadCount = 1;
1678 info.wm->ldr.SectionHandle = handle;
1682 return STATUS_SUCCESS;
1686 /***********************************************************************
1689 * Find the full path (if any) of the dll from the activation context.
1691 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1693 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1694 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1696 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1697 ACTCTX_SECTION_KEYED_DATA data;
1698 UNICODE_STRING nameW;
1700 SIZE_T needed, size = 1024;
1703 RtlInitUnicodeString( &nameW, libname );
1704 data.cbSize = sizeof(data);
1705 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1706 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1708 if (status != STATUS_SUCCESS) return status;
1712 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1714 status = STATUS_NO_MEMORY;
1717 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1718 AssemblyDetailedInformationInActivationContext,
1719 info, size, &needed );
1720 if (status == STATUS_SUCCESS) break;
1721 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1722 RtlFreeHeap( GetProcessHeap(), 0, info );
1724 /* restart with larger buffer */
1727 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1729 status = STATUS_SXS_KEY_NOT_FOUND;
1733 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1735 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1738 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1740 /* manifest name does not match directory name, so it's not a global
1741 * windows/winsxs manifest; use the manifest directory name instead */
1742 dirlen = p - info->lpAssemblyManifestPath;
1743 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1744 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1746 status = STATUS_NO_MEMORY;
1749 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1751 strcpyW( p, libname );
1756 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1757 nameW.Length + 2*sizeof(WCHAR));
1759 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1761 status = STATUS_NO_MEMORY;
1764 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1765 p += windows_dir.Length / sizeof(WCHAR);
1766 memcpy( p, winsxsW, sizeof(winsxsW) );
1767 p += sizeof(winsxsW) / sizeof(WCHAR);
1768 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1769 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1771 strcpyW( p, libname );
1773 RtlFreeHeap( GetProcessHeap(), 0, info );
1774 RtlReleaseActivationContext( data.hActCtx );
1779 /***********************************************************************
1782 * Find the file (or already loaded module) for a given dll name.
1784 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1785 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1787 OBJECT_ATTRIBUTES attr;
1789 UNICODE_STRING nt_name;
1790 WCHAR *file_part, *ext, *dllname;
1793 /* first append .dll if needed */
1796 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1798 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1799 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1800 return STATUS_NO_MEMORY;
1801 strcpyW( dllname, libname );
1802 strcatW( dllname, dllW );
1806 nt_name.Buffer = NULL;
1808 if (!contains_path( libname ))
1811 WCHAR *fullname = NULL;
1813 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1815 status = find_actctx_dll( libname, &fullname );
1816 if (status == STATUS_SUCCESS)
1818 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1819 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1820 libname = dllname = fullname;
1822 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1824 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1829 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1831 /* we need to search for it */
1832 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1835 if (len >= *size) goto overflow;
1836 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1838 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1840 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1841 return STATUS_NO_MEMORY;
1843 attr.Length = sizeof(attr);
1844 attr.RootDirectory = 0;
1845 attr.Attributes = OBJ_CASE_INSENSITIVE;
1846 attr.ObjectName = &nt_name;
1847 attr.SecurityDescriptor = NULL;
1848 attr.SecurityQualityOfService = NULL;
1849 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1855 if (!contains_path( libname ))
1857 /* if libname doesn't contain a path at all, we simply return the name as is,
1858 * to be loaded as builtin */
1859 len = strlenW(libname) * sizeof(WCHAR);
1860 if (len >= *size) goto overflow;
1861 strcpyW( filename, libname );
1866 /* absolute path name, or relative path name but not found above */
1868 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1870 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1871 return STATUS_NO_MEMORY;
1873 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1874 if (len >= *size) goto overflow;
1875 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1876 if (!(*pwm = find_fullname_module( filename )) && handle)
1878 attr.Length = sizeof(attr);
1879 attr.RootDirectory = 0;
1880 attr.Attributes = OBJ_CASE_INSENSITIVE;
1881 attr.ObjectName = &nt_name;
1882 attr.SecurityDescriptor = NULL;
1883 attr.SecurityQualityOfService = NULL;
1884 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1887 RtlFreeUnicodeString( &nt_name );
1888 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1889 return STATUS_SUCCESS;
1892 RtlFreeUnicodeString( &nt_name );
1893 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1894 *size = len + sizeof(WCHAR);
1895 return STATUS_BUFFER_TOO_SMALL;
1899 /***********************************************************************
1900 * load_dll (internal)
1902 * Load a PE style module according to the load order.
1903 * The loader_section must be locked while calling this function.
1905 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1907 enum loadorder loadorder;
1911 WINE_MODREF *main_exe;
1915 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1919 size = sizeof(buffer);
1922 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1923 if (nts == STATUS_SUCCESS) break;
1924 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1925 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1926 /* grow the buffer and retry */
1927 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1930 if (*pwm) /* found already loaded module */
1932 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1934 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1936 TRACE("Found %s for %s at %p, count=%d\n",
1937 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1938 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1939 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1940 return STATUS_SUCCESS;
1943 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1944 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1946 if (handle && is_fake_dll( handle ))
1948 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1956 nts = STATUS_NO_MEMORY;
1959 nts = STATUS_DLL_NOT_FOUND;
1962 case LO_NATIVE_BUILTIN:
1963 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1966 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1967 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1968 /* not in PE format, maybe it's a builtin */
1969 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1971 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1972 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1975 case LO_BUILTIN_NATIVE:
1976 case LO_DEFAULT: /* default is builtin,native */
1977 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1978 if (!handle) break; /* nothing else we can try */
1979 /* file is not a builtin library, try without using the specified file */
1980 if (nts != STATUS_SUCCESS)
1981 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1982 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1983 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1985 /* stub-only dll, try native */
1986 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1987 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1988 nts = STATUS_DLL_NOT_FOUND;
1990 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1991 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1995 if (nts == STATUS_SUCCESS)
1997 /* Initialize DLL just loaded */
1998 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1999 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2000 (*pwm)->ldr.BaseAddress);
2001 if (handle) NtClose( handle );
2002 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2006 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2007 if (handle) NtClose( handle );
2008 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2012 /******************************************************************
2013 * LdrLoadDll (NTDLL.@)
2015 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2016 const UNICODE_STRING *libname, HMODULE* hModule)
2021 RtlEnterCriticalSection( &loader_section );
2023 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2024 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2026 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2028 nts = process_attach( wm, NULL );
2029 if (nts != STATUS_SUCCESS)
2031 LdrUnloadDll(wm->ldr.BaseAddress);
2035 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2037 RtlLeaveCriticalSection( &loader_section );
2042 /******************************************************************
2043 * LdrGetDllHandle (NTDLL.@)
2045 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2053 RtlEnterCriticalSection( &loader_section );
2055 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2058 size = sizeof(buffer);
2061 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2062 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2063 if (status != STATUS_BUFFER_TOO_SMALL) break;
2064 /* grow the buffer and retry */
2065 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2067 status = STATUS_NO_MEMORY;
2072 if (status == STATUS_SUCCESS)
2074 if (wm) *base = wm->ldr.BaseAddress;
2075 else status = STATUS_DLL_NOT_FOUND;
2078 RtlLeaveCriticalSection( &loader_section );
2079 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2084 /******************************************************************
2085 * LdrAddRefDll (NTDLL.@)
2087 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2089 NTSTATUS ret = STATUS_SUCCESS;
2092 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2094 RtlEnterCriticalSection( &loader_section );
2096 if ((wm = get_modref( module )))
2098 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2099 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2101 else ret = STATUS_INVALID_PARAMETER;
2103 RtlLeaveCriticalSection( &loader_section );
2108 /***********************************************************************
2109 * LdrProcessRelocationBlock (NTDLL.@)
2111 * Apply relocations to a given page of a mapped PE image.
2113 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2114 USHORT *relocs, INT_PTR delta )
2118 USHORT offset = *relocs & 0xfff;
2119 int type = *relocs >> 12;
2122 case IMAGE_REL_BASED_ABSOLUTE:
2124 case IMAGE_REL_BASED_HIGH:
2125 *(short *)((char *)page + offset) += HIWORD(delta);
2127 case IMAGE_REL_BASED_LOW:
2128 *(short *)((char *)page + offset) += LOWORD(delta);
2130 case IMAGE_REL_BASED_HIGHLOW:
2131 *(int *)((char *)page + offset) += delta;
2134 case IMAGE_REL_BASED_DIR64:
2135 *(INT_PTR *)((char *)page + offset) += delta;
2139 FIXME("Unknown/unsupported fixup type %x.\n", type);
2144 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2148 /******************************************************************
2149 * LdrQueryProcessModuleInformation
2152 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2153 ULONG buf_size, ULONG* req_size)
2155 SYSTEM_MODULE* sm = &smi->Modules[0];
2156 ULONG size = sizeof(ULONG);
2157 NTSTATUS nts = STATUS_SUCCESS;
2160 PLIST_ENTRY mark, entry;
2164 smi->ModulesCount = 0;
2166 RtlEnterCriticalSection( &loader_section );
2167 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2168 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2170 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2171 size += sizeof(*sm);
2172 if (size <= buf_size)
2174 sm->Reserved1 = 0; /* FIXME */
2175 sm->Reserved2 = 0; /* FIXME */
2176 sm->ImageBaseAddress = mod->BaseAddress;
2177 sm->ImageSize = mod->SizeOfImage;
2178 sm->Flags = mod->Flags;
2180 sm->Rank = 0; /* FIXME */
2181 sm->Unknown = 0; /* FIXME */
2183 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2184 str.Buffer = (char*)sm->Name;
2185 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2186 ptr = strrchr(str.Buffer, '\\');
2187 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2189 smi->ModulesCount++;
2192 else nts = STATUS_INFO_LENGTH_MISMATCH;
2194 RtlLeaveCriticalSection( &loader_section );
2196 if (req_size) *req_size = size;
2202 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2208 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2210 RtlInitUnicodeString( &str, name );
2212 size = sizeof(buffer) - sizeof(WCHAR);
2213 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2216 if (info->Type != REG_DWORD)
2218 buffer[size / sizeof(WCHAR)] = 0;
2219 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2221 else memcpy( value, info->Data, sizeof(*value) );
2225 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2226 void *data, ULONG in_size, ULONG *out_size )
2232 KEY_VALUE_PARTIAL_INFORMATION *info;
2233 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2235 RtlInitUnicodeString( &str, name );
2237 size = info_size + in_size;
2238 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2239 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2240 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2241 if (!status || status == STATUS_BUFFER_OVERFLOW)
2243 if (out_size) *out_size = info->DataLength;
2244 if (data && !status) memcpy( data, info->Data, info->DataLength );
2246 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2251 /******************************************************************
2252 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2254 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2255 void *data, ULONG in_size, ULONG *out_size )
2257 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2258 'S','o','f','t','w','a','r','e','\\',
2259 'M','i','c','r','o','s','o','f','t','\\',
2260 'W','i','n','d','o','w','s',' ','N','T','\\',
2261 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2262 'I','m','a','g','e',' ','F','i','l','e',' ',
2263 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2264 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2265 OBJECT_ATTRIBUTES attr;
2266 UNICODE_STRING name_str;
2272 attr.Length = sizeof(attr);
2273 attr.RootDirectory = 0;
2274 attr.ObjectName = &name_str;
2275 attr.Attributes = OBJ_CASE_INSENSITIVE;
2276 attr.SecurityDescriptor = NULL;
2277 attr.SecurityQualityOfService = NULL;
2279 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2280 else p = key->Buffer;
2281 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2282 name_str.Buffer = path;
2283 name_str.Length = sizeof(optionsW) + len;
2284 name_str.MaximumLength = name_str.Length;
2285 memcpy( path, optionsW, sizeof(optionsW) );
2286 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2287 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2289 if (type == REG_DWORD)
2291 if (out_size) *out_size = sizeof(ULONG);
2292 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2293 else status = STATUS_BUFFER_OVERFLOW;
2295 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2302 /******************************************************************
2303 * RtlDllShutdownInProgress (NTDLL.@)
2305 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2307 return process_detaching;
2311 /******************************************************************
2312 * LdrShutdownProcess (NTDLL.@)
2315 void WINAPI LdrShutdownProcess(void)
2318 process_detach( TRUE, (LPVOID)1 );
2321 /******************************************************************
2322 * LdrShutdownThread (NTDLL.@)
2325 void WINAPI LdrShutdownThread(void)
2327 PLIST_ENTRY mark, entry;
2332 /* don't do any detach calls if process is exiting */
2333 if (process_detaching) return;
2334 /* FIXME: there is still a race here */
2336 RtlEnterCriticalSection( &loader_section );
2338 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2339 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2341 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2342 InInitializationOrderModuleList);
2343 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2345 if ( mod->Flags & LDR_NO_DLL_CALLS )
2348 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2349 DLL_THREAD_DETACH, NULL );
2352 RtlLeaveCriticalSection( &loader_section );
2353 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2357 /***********************************************************************
2361 static void free_modref( WINE_MODREF *wm )
2363 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2364 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2365 if (wm->ldr.InInitializationOrderModuleList.Flink)
2366 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2368 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2369 if (!TRACE_ON(module))
2370 TRACE_(loaddll)("Unloaded module %s : %s\n",
2371 debugstr_w(wm->ldr.FullDllName.Buffer),
2372 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2374 SERVER_START_REQ( unload_dll )
2376 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2377 wine_server_call( req );
2381 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2382 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2383 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2384 if (cached_modref == wm) cached_modref = NULL;
2385 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2386 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2387 RtlFreeHeap( GetProcessHeap(), 0, wm );
2390 /***********************************************************************
2391 * MODULE_FlushModrefs
2393 * Remove all unused modrefs and call the internal unloading routines
2394 * for the library type.
2396 * The loader_section must be locked while calling this function.
2398 static void MODULE_FlushModrefs(void)
2400 PLIST_ENTRY mark, entry, prev;
2404 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2405 for (entry = mark->Blink; entry != mark; entry = prev)
2407 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2408 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2409 prev = entry->Blink;
2410 if (!mod->LoadCount) free_modref( wm );
2413 /* check load order list too for modules that haven't been initialized yet */
2414 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2415 for (entry = mark->Blink; entry != mark; entry = prev)
2417 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2418 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2419 prev = entry->Blink;
2420 if (!mod->LoadCount) free_modref( wm );
2424 /***********************************************************************
2425 * MODULE_DecRefCount
2427 * The loader_section must be locked while calling this function.
2429 static void MODULE_DecRefCount( WINE_MODREF *wm )
2433 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2436 if ( wm->ldr.LoadCount <= 0 )
2439 --wm->ldr.LoadCount;
2440 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2442 if ( wm->ldr.LoadCount == 0 )
2444 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2446 for ( i = 0; i < wm->nDeps; i++ )
2448 MODULE_DecRefCount( wm->deps[i] );
2450 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2454 /******************************************************************
2455 * LdrUnloadDll (NTDLL.@)
2459 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2461 NTSTATUS retv = STATUS_SUCCESS;
2463 TRACE("(%p)\n", hModule);
2465 RtlEnterCriticalSection( &loader_section );
2467 /* if we're stopping the whole process (and forcing the removal of all
2468 * DLLs) the library will be freed anyway
2470 if (!process_detaching)
2475 if ((wm = get_modref( hModule )) != NULL)
2477 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2479 /* Recursively decrement reference counts */
2480 MODULE_DecRefCount( wm );
2482 /* Call process detach notifications */
2483 if ( free_lib_count <= 1 )
2485 process_detach( FALSE, NULL );
2486 MODULE_FlushModrefs();
2492 retv = STATUS_DLL_NOT_FOUND;
2497 RtlLeaveCriticalSection( &loader_section );
2502 /***********************************************************************
2503 * RtlImageNtHeader (NTDLL.@)
2505 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2507 IMAGE_NT_HEADERS *ret;
2511 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2514 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2516 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2517 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2529 /***********************************************************************
2530 * attach_process_dlls
2532 * Initial attach to all the dlls loaded by the process.
2534 static NTSTATUS attach_process_dlls( void *wm )
2538 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2540 RtlEnterCriticalSection( &loader_section );
2541 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2543 if (last_failed_modref)
2544 ERR( "%s failed to initialize, aborting\n",
2545 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2548 attach_implicitly_loaded_dlls( (LPVOID)1 );
2549 RtlLeaveCriticalSection( &loader_section );
2554 /***********************************************************************
2555 * load_global_options
2557 static void load_global_options(void)
2559 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2560 'S','y','s','t','e','m','\\',
2561 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2562 'C','o','n','t','r','o','l','\\',
2563 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2564 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2565 static const WCHAR critsectW[] = {'C','r','i','t','i','c','a','l','S','e','c','t','i','o','n','T','i','m','e','o','u','t',0};
2566 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2567 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2568 static const WCHAR decommittotalW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','T','o','t','a','l','F','r','e','e','T','h','r','e','s','h','o','l','d',0};
2569 static const WCHAR decommitfreeW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','F','r','e','e','B','l','o','c','k','T','h','r','e','s','h','o','l','d',0};
2571 OBJECT_ATTRIBUTES attr;
2572 UNICODE_STRING name_str;
2576 attr.Length = sizeof(attr);
2577 attr.RootDirectory = 0;
2578 attr.ObjectName = &name_str;
2579 attr.Attributes = OBJ_CASE_INSENSITIVE;
2580 attr.SecurityDescriptor = NULL;
2581 attr.SecurityQualityOfService = NULL;
2582 RtlInitUnicodeString( &name_str, sessionW );
2584 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2586 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2588 query_dword_option( hkey, critsectW, &value );
2589 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2591 query_dword_option( hkey, heapresW, &value );
2592 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2594 query_dword_option( hkey, heapcommitW, &value );
2595 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2597 query_dword_option( hkey, decommittotalW, &value );
2598 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2600 query_dword_option( hkey, decommitfreeW, &value );
2601 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2607 /***********************************************************************
2610 static void start_process( void *kernel_start )
2612 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2615 /******************************************************************
2616 * LdrInitializeThunk (NTDLL.@)
2619 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2620 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2622 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2626 PEB *peb = NtCurrentTeb()->Peb;
2627 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2629 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2631 /* allocate the modref for the main exe (if not already done) */
2632 wm = get_modref( peb->ImageBaseAddress );
2634 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2636 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2640 peb->LoaderLock = &loader_section;
2641 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2642 if (!peb->ProcessParameters->WindowTitle.Buffer)
2643 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2644 version_init( wm->ldr.FullDllName.Buffer );
2646 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2647 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2649 /* the main exe needs to be the first in the load order list */
2650 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2651 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2653 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2654 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2657 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2658 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2659 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2660 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2661 heap_set_debug_flags( GetProcessHeap() );
2663 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2664 if (status != STATUS_SUCCESS) goto error;
2666 virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2667 virtual_clear_thread_stack();
2668 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2671 ERR( "Main exe initialization for %s failed, status %x\n",
2672 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2673 NtTerminateProcess( GetCurrentProcess(), status );
2677 /***********************************************************************
2678 * RtlImageDirectoryEntryToData (NTDLL.@)
2680 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2682 const IMAGE_NT_HEADERS *nt;
2685 if ((ULONG_PTR)module & 1) /* mapped as data file */
2687 module = (HMODULE)((ULONG_PTR)module & ~1);
2690 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2691 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2693 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2695 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2696 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2697 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2698 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2700 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2702 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2704 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2705 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2706 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2707 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2711 /* not mapped as image, need to find the section containing the virtual address */
2712 return RtlImageRvaToVa( nt, module, addr, NULL );
2716 /***********************************************************************
2717 * RtlImageRvaToSection (NTDLL.@)
2719 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2720 HMODULE module, DWORD rva )
2723 const IMAGE_SECTION_HEADER *sec;
2725 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2726 nt->FileHeader.SizeOfOptionalHeader);
2727 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2729 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2730 return (PIMAGE_SECTION_HEADER)sec;
2736 /***********************************************************************
2737 * RtlImageRvaToVa (NTDLL.@)
2739 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2740 DWORD rva, IMAGE_SECTION_HEADER **section )
2742 IMAGE_SECTION_HEADER *sec;
2744 if (section && *section) /* try this section first */
2747 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2750 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2752 if (section) *section = sec;
2753 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2757 /***********************************************************************
2758 * RtlPcToFileHeader (NTDLL.@)
2760 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2765 RtlEnterCriticalSection( &loader_section );
2766 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2767 RtlLeaveCriticalSection( &loader_section );
2773 /***********************************************************************
2774 * NtLoadDriver (NTDLL.@)
2775 * ZwLoadDriver (NTDLL.@)
2777 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2779 FIXME("(%p), stub!\n",DriverServiceName);
2780 return STATUS_NOT_IMPLEMENTED;
2784 /***********************************************************************
2785 * NtUnloadDriver (NTDLL.@)
2786 * ZwUnloadDriver (NTDLL.@)
2788 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2790 FIXME("(%p), stub!\n",DriverServiceName);
2791 return STATUS_NOT_IMPLEMENTED;
2795 /******************************************************************
2798 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2800 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2805 /******************************************************************
2806 * __wine_init_windows_dir (NTDLL.@)
2808 * Windows and system dir initialization once kernel32 has been loaded.
2810 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2812 PLIST_ENTRY mark, entry;
2815 DIR_init_windows_dir( windir, sysdir );
2816 strcpyW( user_shared_data->NtSystemRoot, windir );
2818 /* prepend the system dir to the name of the already created modules */
2819 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2820 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2822 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2824 assert( mod->Flags & LDR_WINE_INTERNAL );
2826 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2827 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2828 if (!buffer) continue;
2829 strcpyW( buffer, system_dir.Buffer );
2830 p = buffer + strlenW( buffer );
2831 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2832 strcpyW( p, mod->FullDllName.Buffer );
2833 RtlInitUnicodeString( &mod->FullDllName, buffer );
2834 RtlInitUnicodeString( &mod->BaseDllName, p );
2839 /***********************************************************************
2840 * __wine_process_init
2842 void __wine_process_init(void)
2844 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2848 ANSI_STRING func_name;
2849 void (* DECLSPEC_NORETURN CDECL init_func)(void);
2850 extern mode_t FILE_umask;
2852 main_exe_file = thread_init();
2854 /* retrieve current umask */
2855 FILE_umask = umask(0777);
2856 umask( FILE_umask );
2858 load_global_options();
2860 /* setup the load callback and create ntdll modref */
2861 wine_dll_set_callback( load_builtin_callback );
2863 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2865 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2868 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2869 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2871 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2872 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2873 0, (void **)&init_func )) != STATUS_SUCCESS)
2875 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );