ntdll: Enforce correct protection values in virtual memory functions.
[wine/wine64.git] / dlls / ntdll / loader.c
blobd3a006712db0a9af2498dc9bd5267be8d136df77
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>
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
29 #endif
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winnt.h"
38 #include "winternl.h"
40 #include "wine/exception.h"
41 #include "wine/library.h"
42 #include "wine/pthread.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45 #include "wine/server.h"
46 #include "ntdll_misc.h"
47 #include "ddk/wdm.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(module);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 WINE_DECLARE_DEBUG_CHANNEL(snoop);
52 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
53 WINE_DECLARE_DEBUG_CHANNEL(imports);
55 /* we don't want to include winuser.h */
56 #define RT_MANIFEST ((ULONG_PTR)24)
57 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
59 extern struct wine_pthread_functions pthread_functions;
61 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
63 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
64 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
66 static const char * const reason_names[] =
68 "PROCESS_DETACH",
69 "PROCESS_ATTACH",
70 "THREAD_ATTACH",
71 "THREAD_DETACH",
72 NULL, NULL, NULL, NULL,
73 "WINE_PREATTACH"
76 static const WCHAR dllW[] = {'.','d','l','l',0};
78 /* internal representation of 32bit modules. per process. */
79 typedef struct _wine_modref
81 LDR_MODULE ldr;
82 int nDeps;
83 struct _wine_modref **deps;
84 } WINE_MODREF;
86 /* info about the current builtin dll load */
87 /* used to keep track of things across the register_dll constructor call */
88 struct builtin_load_info
90 const WCHAR *load_path;
91 const WCHAR *filename;
92 NTSTATUS status;
93 WINE_MODREF *wm;
96 static struct builtin_load_info default_load_info;
97 static struct builtin_load_info *builtin_load_info = &default_load_info;
99 static HANDLE main_exe_file;
100 static UINT tls_module_count; /* number of modules with TLS directory */
101 static UINT tls_total_size; /* total size of TLS storage */
102 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
104 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
105 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
107 static RTL_CRITICAL_SECTION loader_section;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 0, 0, &loader_section,
111 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
114 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
116 static WINE_MODREF *cached_modref;
117 static WINE_MODREF *current_modref;
118 static WINE_MODREF *last_failed_modref;
120 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
121 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
122 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
123 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
125 /* convert PE image VirtualAddress to Real Address */
126 static inline void *get_rva( HMODULE module, DWORD va )
128 return (void *)((char *)module + va);
131 /* check whether the file name contains a path */
132 static inline int contains_path( LPCWSTR name )
134 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
137 /* convert from straight ASCII to Unicode without depending on the current codepage */
138 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
140 while (len--) *dst++ = (unsigned char)*src++;
144 /*************************************************************************
145 * call_dll_entry_point
147 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
148 * their entry point, so we need a small asm wrapper.
150 #ifdef __i386__
151 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
152 __ASM_GLOBAL_FUNC(call_dll_entry_point,
153 "pushl %ebp\n\t"
154 "movl %esp,%ebp\n\t"
155 "pushl %ebx\n\t"
156 "subl $8,%esp\n\t"
157 "pushl 20(%ebp)\n\t"
158 "pushl 16(%ebp)\n\t"
159 "pushl 12(%ebp)\n\t"
160 "movl 8(%ebp),%eax\n\t"
161 "call *%eax\n\t"
162 "leal -4(%ebp),%esp\n\t"
163 "popl %ebx\n\t"
164 "popl %ebp\n\t"
165 "ret" )
166 #else /* __i386__ */
167 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
168 UINT reason, void *reserved )
170 return proc( module, reason, reserved );
172 #endif /* __i386__ */
175 #ifdef __i386__
176 /*************************************************************************
177 * stub_entry_point
179 * Entry point for stub functions.
181 static void stub_entry_point( const char *dll, const char *name, ... )
183 EXCEPTION_RECORD rec;
185 rec.ExceptionCode = EXCEPTION_WINE_STUB;
186 rec.ExceptionFlags = EH_NONCONTINUABLE;
187 rec.ExceptionRecord = NULL;
188 #ifdef __GNUC__
189 rec.ExceptionAddress = __builtin_return_address(0);
190 #else
191 rec.ExceptionAddress = *((void **)&dll - 1);
192 #endif
193 rec.NumberParameters = 2;
194 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
195 rec.ExceptionInformation[1] = (ULONG_PTR)name;
196 for (;;) RtlRaiseException( &rec );
200 #include "pshpack1.h"
201 struct stub
203 BYTE popl_eax; /* popl %eax */
204 BYTE pushl1; /* pushl $name */
205 const char *name;
206 BYTE pushl2; /* pushl $dll */
207 const char *dll;
208 BYTE pushl_eax; /* pushl %eax */
209 BYTE jmp; /* jmp stub_entry_point */
210 DWORD entry;
212 #include "poppack.h"
214 /*************************************************************************
215 * allocate_stub
217 * Allocate a stub entry point.
219 static ULONG_PTR allocate_stub( const char *dll, const char *name )
221 #define MAX_SIZE 65536
222 static struct stub *stubs;
223 static unsigned int nb_stubs;
224 struct stub *stub;
226 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
228 if (!stubs)
230 SIZE_T size = MAX_SIZE;
231 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
232 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
233 return 0xdeadbeef;
235 stub = &stubs[nb_stubs++];
236 stub->popl_eax = 0x58; /* popl %eax */
237 stub->pushl1 = 0x68; /* pushl $name */
238 stub->name = name;
239 stub->pushl2 = 0x68; /* pushl $dll */
240 stub->dll = dll;
241 stub->pushl_eax = 0x50; /* pushl %eax */
242 stub->jmp = 0xe9; /* jmp stub_entry_point */
243 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
244 return (ULONG_PTR)stub;
247 #else /* __i386__ */
248 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
249 #endif /* __i386__ */
252 /*************************************************************************
253 * get_modref
255 * Looks for the referenced HMODULE in the current process
256 * The loader_section must be locked while calling this function.
258 static WINE_MODREF *get_modref( HMODULE hmod )
260 PLIST_ENTRY mark, entry;
261 PLDR_MODULE mod;
263 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
265 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
266 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
268 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
269 if (mod->BaseAddress == hmod)
270 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
271 if (mod->BaseAddress > (void*)hmod) break;
273 return NULL;
277 /**********************************************************************
278 * find_basename_module
280 * Find a module from its base name.
281 * The loader_section must be locked while calling this function
283 static WINE_MODREF *find_basename_module( LPCWSTR name )
285 PLIST_ENTRY mark, entry;
287 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
288 return cached_modref;
290 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
291 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
293 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
294 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
296 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
297 return cached_modref;
300 return NULL;
304 /**********************************************************************
305 * find_fullname_module
307 * Find a module from its full path name.
308 * The loader_section must be locked while calling this function
310 static WINE_MODREF *find_fullname_module( LPCWSTR name )
312 PLIST_ENTRY mark, entry;
314 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
315 return cached_modref;
317 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
318 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
320 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
321 if (!strcmpiW( name, mod->FullDllName.Buffer ))
323 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
324 return cached_modref;
327 return NULL;
331 /*************************************************************************
332 * find_forwarded_export
334 * Find the final function pointer for a forwarded function.
335 * The loader_section must be locked while calling this function.
337 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
339 const IMAGE_EXPORT_DIRECTORY *exports;
340 DWORD exp_size;
341 WINE_MODREF *wm;
342 WCHAR mod_name[32];
343 const char *end = strrchr(forward, '.');
344 FARPROC proc = NULL;
346 if (!end) return NULL;
347 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
348 ascii_to_unicode( mod_name, forward, end - forward );
349 mod_name[end - forward] = 0;
350 if (!strchrW( mod_name, '.' ))
352 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
353 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
356 if (!(wm = find_basename_module( mod_name )))
358 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
359 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
360 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
362 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
364 LdrUnloadDll( wm->ldr.BaseAddress );
365 wm = NULL;
369 if (!wm)
371 ERR( "module not found for forward '%s' used by %s\n",
372 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
373 return NULL;
376 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
377 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
378 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1, load_path );
380 if (!proc)
382 ERR("function not found for forward '%s' used by %s."
383 " If you are using builtin %s, try using the native one instead.\n",
384 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
385 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
387 return proc;
391 /*************************************************************************
392 * find_ordinal_export
394 * Find an exported function by ordinal.
395 * The exports base must have been subtracted from the ordinal already.
396 * The loader_section must be locked while calling this function.
398 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
399 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
401 FARPROC proc;
402 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
404 if (ordinal >= exports->NumberOfFunctions)
406 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
407 return NULL;
409 if (!functions[ordinal]) return NULL;
411 proc = get_rva( module, functions[ordinal] );
413 /* if the address falls into the export dir, it's a forward */
414 if (((const char *)proc >= (const char *)exports) &&
415 ((const char *)proc < (const char *)exports + exp_size))
416 return find_forwarded_export( module, (const char *)proc, load_path );
418 if (TRACE_ON(snoop))
420 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
421 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
423 if (TRACE_ON(relay))
425 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
426 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
428 return proc;
432 /*************************************************************************
433 * find_named_export
435 * Find an exported function by name.
436 * The loader_section must be locked while calling this function.
438 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
439 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
441 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
442 const DWORD *names = get_rva( module, exports->AddressOfNames );
443 int min = 0, max = exports->NumberOfNames - 1;
445 /* first check the hint */
446 if (hint >= 0 && hint <= max)
448 char *ename = get_rva( module, names[hint] );
449 if (!strcmp( ename, name ))
450 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
453 /* then do a binary search */
454 while (min <= max)
456 int res, pos = (min + max) / 2;
457 char *ename = get_rva( module, names[pos] );
458 if (!(res = strcmp( ename, name )))
459 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
460 if (res > 0) max = pos - 1;
461 else min = pos + 1;
463 return NULL;
468 /*************************************************************************
469 * import_dll
471 * Import the dll specified by the given import descriptor.
472 * The loader_section must be locked while calling this function.
474 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
476 NTSTATUS status;
477 WINE_MODREF *wmImp;
478 HMODULE imp_mod;
479 const IMAGE_EXPORT_DIRECTORY *exports;
480 DWORD exp_size;
481 const IMAGE_THUNK_DATA *import_list;
482 IMAGE_THUNK_DATA *thunk_list;
483 WCHAR buffer[32];
484 const char *name = get_rva( module, descr->Name );
485 DWORD len = strlen(name);
486 PVOID protect_base;
487 SIZE_T protect_size = 0;
488 DWORD protect_old;
490 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
491 if (descr->u.OriginalFirstThunk)
492 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
493 else
494 import_list = thunk_list;
496 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
498 if (len * sizeof(WCHAR) < sizeof(buffer))
500 ascii_to_unicode( buffer, name, len );
501 buffer[len] = 0;
502 status = load_dll( load_path, buffer, 0, &wmImp );
504 else /* need to allocate a larger buffer */
506 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
507 if (!ptr) return NULL;
508 ascii_to_unicode( ptr, name, len );
509 ptr[len] = 0;
510 status = load_dll( load_path, ptr, 0, &wmImp );
511 RtlFreeHeap( GetProcessHeap(), 0, ptr );
514 if (status)
516 if (status == STATUS_DLL_NOT_FOUND)
517 ERR("Library %s (which is needed by %s) not found\n",
518 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
519 else
520 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
521 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
522 return NULL;
525 /* unprotect the import address table since it can be located in
526 * readonly section */
527 while (import_list[protect_size].u1.Ordinal) protect_size++;
528 protect_base = thunk_list;
529 protect_size *= sizeof(*thunk_list);
530 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
531 &protect_size, PAGE_WRITECOPY, &protect_old );
533 imp_mod = wmImp->ldr.BaseAddress;
534 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
536 if (!exports)
538 /* set all imported function to deadbeef */
539 while (import_list->u1.Ordinal)
541 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
543 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
544 WARN("No implementation for %s.%d", name, ordinal );
545 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
547 else
549 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
550 WARN("No implementation for %s.%s", name, pe_name->Name );
551 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
553 WARN(" imported from %s, allocating stub %p\n",
554 debugstr_w(current_modref->ldr.FullDllName.Buffer),
555 (void *)thunk_list->u1.Function );
556 import_list++;
557 thunk_list++;
559 goto done;
562 while (import_list->u1.Ordinal)
564 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
566 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
568 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
569 ordinal - exports->Base, load_path );
570 if (!thunk_list->u1.Function)
572 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
573 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
574 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
575 (void *)thunk_list->u1.Function );
577 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
579 else /* import by name */
581 IMAGE_IMPORT_BY_NAME *pe_name;
582 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
583 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
584 (const char*)pe_name->Name,
585 pe_name->Hint, load_path );
586 if (!thunk_list->u1.Function)
588 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
589 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
590 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
591 (void *)thunk_list->u1.Function );
593 TRACE_(imports)("--- %s %s.%d = %p\n",
594 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
596 import_list++;
597 thunk_list++;
600 done:
601 /* restore old protection of the import address table */
602 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
603 return wmImp;
607 /***********************************************************************
608 * create_module_activation_context
610 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
612 NTSTATUS status;
613 LDR_RESOURCE_INFO info;
614 const IMAGE_RESOURCE_DATA_ENTRY *entry;
616 info.Type = RT_MANIFEST;
617 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
618 info.Language = 0;
619 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
621 ACTCTXW ctx;
622 ctx.cbSize = sizeof(ctx);
623 ctx.lpSource = NULL;
624 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
625 ctx.hModule = module->BaseAddress;
626 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
627 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
629 return status;
633 /****************************************************************
634 * fixup_imports
636 * Fixup all imports of a given module.
637 * The loader_section must be locked while calling this function.
639 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
641 int i, nb_imports;
642 const IMAGE_IMPORT_DESCRIPTOR *imports;
643 WINE_MODREF *prev;
644 DWORD size;
645 NTSTATUS status;
646 ULONG_PTR cookie;
648 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
649 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
651 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
652 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
653 return STATUS_SUCCESS;
655 nb_imports = 0;
656 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
658 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
660 if (!create_module_activation_context( &wm->ldr ))
661 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
663 /* Allocate module dependency list */
664 wm->nDeps = nb_imports;
665 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
667 /* load the imported modules. They are automatically
668 * added to the modref list of the process.
670 prev = current_modref;
671 current_modref = wm;
672 status = STATUS_SUCCESS;
673 for (i = 0; i < nb_imports; i++)
675 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
676 status = STATUS_DLL_NOT_FOUND;
678 current_modref = prev;
679 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
680 return status;
684 /*************************************************************************
685 * is_dll_native_subsystem
687 * Check if dll is a proper native driver.
688 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
689 * while being perfectly normal DLLs. This heuristic should catch such breakages.
691 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
693 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
694 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
695 const IMAGE_IMPORT_DESCRIPTOR *imports;
696 DWORD i, size;
697 WCHAR buffer[16];
699 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
700 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
702 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
703 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
705 for (i = 0; imports[i].Name; i++)
707 const char *name = get_rva( module, imports[i].Name );
708 DWORD len = strlen(name);
709 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
710 ascii_to_unicode( buffer, name, len + 1 );
711 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
713 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
714 return FALSE;
718 return TRUE;
722 /*************************************************************************
723 * alloc_module
725 * Allocate a WINE_MODREF structure and add it to the process list
726 * The loader_section must be locked while calling this function.
728 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
730 WINE_MODREF *wm;
731 const WCHAR *p;
732 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
733 PLIST_ENTRY entry, mark;
735 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
737 wm->nDeps = 0;
738 wm->deps = NULL;
740 wm->ldr.BaseAddress = hModule;
741 wm->ldr.EntryPoint = NULL;
742 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
743 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
744 wm->ldr.LoadCount = 1;
745 wm->ldr.TlsIndex = -1;
746 wm->ldr.SectionHandle = NULL;
747 wm->ldr.CheckSum = 0;
748 wm->ldr.TimeDateStamp = 0;
749 wm->ldr.ActivationContext = 0;
751 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
752 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
753 else p = wm->ldr.FullDllName.Buffer;
754 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
756 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
758 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
759 if (nt->OptionalHeader.AddressOfEntryPoint)
760 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
763 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
764 &wm->ldr.InLoadOrderModuleList);
766 /* insert module in MemoryList, sorted in increasing base addresses */
767 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
768 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
770 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
771 break;
773 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
774 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
775 wm->ldr.InMemoryOrderModuleList.Flink = entry;
776 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
778 /* wait until init is called for inserting into this list */
779 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
780 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
782 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
784 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
785 VIRTUAL_SetForceExec( TRUE );
787 return wm;
791 /*************************************************************************
792 * alloc_process_tls
794 * Allocate the process-wide structure for module TLS storage.
796 static NTSTATUS alloc_process_tls(void)
798 PLIST_ENTRY mark, entry;
799 PLDR_MODULE mod;
800 const IMAGE_TLS_DIRECTORY *dir;
801 ULONG size, i;
803 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
804 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
806 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
807 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
808 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
809 continue;
810 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
811 if (!size) continue;
812 tls_total_size += size;
813 tls_module_count++;
815 if (!tls_module_count) return STATUS_SUCCESS;
817 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
819 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
820 if (!tls_dirs) return STATUS_NO_MEMORY;
822 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
824 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
825 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
826 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
827 continue;
828 tls_dirs[i] = dir;
829 *(DWORD *)dir->AddressOfIndex = i;
830 mod->TlsIndex = i;
831 mod->LoadCount = -1; /* can't unload it */
832 i++;
834 return STATUS_SUCCESS;
838 /*************************************************************************
839 * alloc_thread_tls
841 * Allocate the per-thread structure for module TLS storage.
843 static NTSTATUS alloc_thread_tls(void)
845 void **pointers;
846 char *data;
847 UINT i;
849 if (!tls_module_count) return STATUS_SUCCESS;
851 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
852 tls_module_count * sizeof(*pointers) )))
853 return STATUS_NO_MEMORY;
855 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
857 RtlFreeHeap( GetProcessHeap(), 0, pointers );
858 return STATUS_NO_MEMORY;
861 for (i = 0; i < tls_module_count; i++)
863 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
864 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
866 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
867 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
868 (void *)dir->StartAddressOfRawData, data );
870 pointers[i] = data;
871 memcpy( data, (void *)dir->StartAddressOfRawData, size );
872 data += size;
873 memset( data, 0, dir->SizeOfZeroFill );
874 data += dir->SizeOfZeroFill;
876 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
877 return STATUS_SUCCESS;
881 /*************************************************************************
882 * call_tls_callbacks
884 static void call_tls_callbacks( HMODULE module, UINT reason )
886 const IMAGE_TLS_DIRECTORY *dir;
887 const PIMAGE_TLS_CALLBACK *callback;
888 ULONG dirsize;
890 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
891 if (!dir || !dir->AddressOfCallBacks) return;
893 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
895 if (TRACE_ON(relay))
896 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
897 GetCurrentThreadId(), *callback, module, reason_names[reason] );
898 __TRY
900 (*callback)( module, reason, NULL );
902 __EXCEPT_ALL
904 if (TRACE_ON(relay))
905 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
906 GetCurrentThreadId(), callback, module, reason_names[reason] );
907 return;
909 __ENDTRY
910 if (TRACE_ON(relay))
911 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
912 GetCurrentThreadId(), *callback, module, reason_names[reason] );
917 /*************************************************************************
918 * MODULE_InitDLL
920 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
922 WCHAR mod_name[32];
923 NTSTATUS status = STATUS_SUCCESS;
924 DLLENTRYPROC entry = wm->ldr.EntryPoint;
925 void *module = wm->ldr.BaseAddress;
926 BOOL retv = TRUE;
928 /* Skip calls for modules loaded with special load flags */
930 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
931 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
932 if (!entry) return STATUS_SUCCESS;
934 if (TRACE_ON(relay))
936 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
937 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
938 mod_name[len / sizeof(WCHAR)] = 0;
939 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
940 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
941 reason_names[reason], lpReserved );
943 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
944 reason_names[reason], lpReserved );
946 __TRY
948 retv = call_dll_entry_point( entry, module, reason, lpReserved );
949 if (!retv)
950 status = STATUS_DLL_INIT_FAILED;
952 __EXCEPT_ALL
954 if (TRACE_ON(relay))
955 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
956 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
957 status = GetExceptionCode();
959 __ENDTRY
961 /* The state of the module list may have changed due to the call
962 to the dll. We cannot assume that this module has not been
963 deleted. */
964 if (TRACE_ON(relay))
965 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
966 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
967 reason_names[reason], lpReserved, retv );
968 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
970 return status;
974 /*************************************************************************
975 * process_attach
977 * Send the process attach notification to all DLLs the given module
978 * depends on (recursively). This is somewhat complicated due to the fact that
980 * - we have to respect the module dependencies, i.e. modules implicitly
981 * referenced by another module have to be initialized before the module
982 * itself can be initialized
984 * - the initialization routine of a DLL can itself call LoadLibrary,
985 * thereby introducing a whole new set of dependencies (even involving
986 * the 'old' modules) at any time during the whole process
988 * (Note that this routine can be recursively entered not only directly
989 * from itself, but also via LoadLibrary from one of the called initialization
990 * routines.)
992 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
993 * the process *detach* notifications to be sent in the correct order.
994 * This must not only take into account module dependencies, but also
995 * 'hidden' dependencies created by modules calling LoadLibrary in their
996 * attach notification routine.
998 * The strategy is rather simple: we move a WINE_MODREF to the head of the
999 * list after the attach notification has returned. This implies that the
1000 * detach notifications are called in the reverse of the sequence the attach
1001 * notifications *returned*.
1003 * The loader_section must be locked while calling this function.
1005 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1007 NTSTATUS status = STATUS_SUCCESS;
1008 ULONG_PTR cookie;
1009 int i;
1011 if (process_detaching) return status;
1013 /* prevent infinite recursion in case of cyclical dependencies */
1014 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1015 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1016 return status;
1018 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1020 /* Tag current MODREF to prevent recursive loop */
1021 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1022 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1023 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1025 /* Recursively attach all DLLs this one depends on */
1026 for ( i = 0; i < wm->nDeps; i++ )
1028 if (!wm->deps[i]) continue;
1029 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1032 /* Call DLL entry point */
1033 if (status == STATUS_SUCCESS)
1035 WINE_MODREF *prev = current_modref;
1036 current_modref = wm;
1037 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1038 if (status == STATUS_SUCCESS)
1039 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1040 else
1042 /* point to the name so LdrInitializeThunk can print it */
1043 last_failed_modref = wm;
1044 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1046 current_modref = prev;
1049 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1050 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1051 &wm->ldr.InInitializationOrderModuleList);
1053 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1054 /* Remove recursion flag */
1055 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1057 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1058 return status;
1062 /**********************************************************************
1063 * attach_implicitly_loaded_dlls
1065 * Attach to the (builtin) dlls that have been implicitly loaded because
1066 * of a dependency at the Unix level, but not imported at the Win32 level.
1068 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1070 for (;;)
1072 PLIST_ENTRY mark, entry;
1074 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1075 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1077 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1079 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1080 TRACE( "found implicitly loaded %s, attaching to it\n",
1081 debugstr_w(mod->BaseDllName.Buffer));
1082 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1083 break; /* restart the search from the start */
1085 if (entry == mark) break; /* nothing found */
1090 /*************************************************************************
1091 * process_detach
1093 * Send DLL process detach notifications. See the comment about calling
1094 * sequence at process_attach. Unless the bForceDetach flag
1095 * is set, only DLLs with zero refcount are notified.
1097 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1099 PLIST_ENTRY mark, entry;
1100 PLDR_MODULE mod;
1102 RtlEnterCriticalSection( &loader_section );
1103 if (bForceDetach) process_detaching = 1;
1104 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1107 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1109 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1110 InInitializationOrderModuleList);
1111 /* Check whether to detach this DLL */
1112 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1113 continue;
1114 if ( mod->LoadCount && !bForceDetach )
1115 continue;
1117 /* Call detach notification */
1118 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1119 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1120 DLL_PROCESS_DETACH, lpReserved );
1122 /* Restart at head of WINE_MODREF list, as entries might have
1123 been added and/or removed while performing the call ... */
1124 break;
1126 } while (entry != mark);
1128 RtlLeaveCriticalSection( &loader_section );
1131 /*************************************************************************
1132 * MODULE_DllThreadAttach
1134 * Send DLL thread attach notifications. These are sent in the
1135 * reverse sequence of process detach notification.
1138 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1140 PLIST_ENTRY mark, entry;
1141 PLDR_MODULE mod;
1142 NTSTATUS status;
1144 /* don't do any attach calls if process is exiting */
1145 if (process_detaching) return STATUS_SUCCESS;
1146 /* FIXME: there is still a race here */
1148 RtlEnterCriticalSection( &loader_section );
1150 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1152 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1153 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1155 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1156 InInitializationOrderModuleList);
1157 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1158 continue;
1159 if ( mod->Flags & LDR_NO_DLL_CALLS )
1160 continue;
1162 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1163 DLL_THREAD_ATTACH, lpReserved );
1166 done:
1167 RtlLeaveCriticalSection( &loader_section );
1168 return status;
1171 /******************************************************************
1172 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1175 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1177 WINE_MODREF *wm;
1178 NTSTATUS ret = STATUS_SUCCESS;
1180 RtlEnterCriticalSection( &loader_section );
1182 wm = get_modref( hModule );
1183 if (!wm || wm->ldr.TlsIndex != -1)
1184 ret = STATUS_DLL_NOT_FOUND;
1185 else
1186 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1188 RtlLeaveCriticalSection( &loader_section );
1190 return ret;
1193 /******************************************************************
1194 * LdrFindEntryForAddress (NTDLL.@)
1196 * The loader_section must be locked while calling this function
1198 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1200 PLIST_ENTRY mark, entry;
1201 PLDR_MODULE mod;
1203 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1204 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1206 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1207 if ((const void *)mod->BaseAddress <= addr &&
1208 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1210 *pmod = mod;
1211 return STATUS_SUCCESS;
1213 if ((const void *)mod->BaseAddress > addr) break;
1215 return STATUS_NO_MORE_ENTRIES;
1218 /******************************************************************
1219 * LdrLockLoaderLock (NTDLL.@)
1221 * Note: flags are not implemented.
1222 * Flag 0x01 is used to raise exceptions on errors.
1223 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1225 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1227 if (flags) FIXME( "flags %x not supported\n", flags );
1229 if (result) *result = 1;
1230 if (!magic) return STATUS_INVALID_PARAMETER_3;
1231 RtlEnterCriticalSection( &loader_section );
1232 *magic = GetCurrentThreadId();
1233 return STATUS_SUCCESS;
1237 /******************************************************************
1238 * LdrUnlockLoaderUnlock (NTDLL.@)
1240 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1242 if (magic)
1244 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1245 RtlLeaveCriticalSection( &loader_section );
1247 return STATUS_SUCCESS;
1251 /******************************************************************
1252 * LdrGetProcedureAddress (NTDLL.@)
1254 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1255 ULONG ord, PVOID *address)
1257 IMAGE_EXPORT_DIRECTORY *exports;
1258 DWORD exp_size;
1259 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1261 RtlEnterCriticalSection( &loader_section );
1263 /* check if the module itself is invalid to return the proper error */
1264 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1265 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1266 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1268 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1269 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1270 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1271 if (proc)
1273 *address = proc;
1274 ret = STATUS_SUCCESS;
1278 RtlLeaveCriticalSection( &loader_section );
1279 return ret;
1283 /***********************************************************************
1284 * is_fake_dll
1286 * Check if a loaded native dll is a Wine fake dll.
1288 static BOOL is_fake_dll( HANDLE handle )
1290 static const char fakedll_signature[] = "Wine placeholder DLL";
1291 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1292 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1293 IO_STATUS_BLOCK io;
1294 LARGE_INTEGER offset;
1296 offset.QuadPart = 0;
1297 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1298 if (io.Information < sizeof(buffer)) return FALSE;
1299 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1300 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1301 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1302 return FALSE;
1306 /***********************************************************************
1307 * get_builtin_fullname
1309 * Build the full pathname for a builtin dll.
1311 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1313 static const WCHAR soW[] = {'.','s','o',0};
1314 WCHAR *p, *fullname;
1315 size_t i, len = strlen(filename);
1317 /* check if path can correspond to the dll we have */
1318 if (path && (p = strrchrW( path, '\\' )))
1320 p++;
1321 for (i = 0; i < len; i++)
1322 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1323 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1325 /* the filename matches, use path as the full path */
1326 len += p - path;
1327 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1329 memcpy( fullname, path, len * sizeof(WCHAR) );
1330 fullname[len] = 0;
1332 return fullname;
1336 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1337 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1339 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1340 p = fullname + system_dir.Length / sizeof(WCHAR);
1341 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1342 ascii_to_unicode( p, filename, len + 1 );
1344 return fullname;
1348 /***********************************************************************
1349 * load_builtin_callback
1351 * Load a library in memory; callback function for wine_dll_register
1353 static void load_builtin_callback( void *module, const char *filename )
1355 static const WCHAR emptyW[1];
1356 IMAGE_NT_HEADERS *nt;
1357 WINE_MODREF *wm;
1358 WCHAR *fullname;
1359 const WCHAR *load_path;
1361 if (!module)
1363 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1364 return;
1366 if (!(nt = RtlImageNtHeader( module )))
1368 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1369 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1370 return;
1372 virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1373 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1374 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1376 /* create the MODREF */
1378 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1380 ERR( "can't load %s\n", filename );
1381 builtin_load_info->status = STATUS_NO_MEMORY;
1382 return;
1385 wm = alloc_module( module, fullname );
1386 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1387 if (!wm)
1389 ERR( "can't load %s\n", filename );
1390 builtin_load_info->status = STATUS_NO_MEMORY;
1391 return;
1393 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1395 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1396 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1398 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1400 else
1402 /* fixup imports */
1404 load_path = builtin_load_info->load_path;
1405 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1406 if (!load_path) load_path = emptyW;
1407 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1409 /* the module has only be inserted in the load & memory order lists */
1410 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1411 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1412 /* FIXME: free the modref */
1413 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1414 return;
1418 builtin_load_info->wm = wm;
1419 TRACE( "loaded %s %p %p\n", filename, wm, module );
1421 /* send the DLL load event */
1423 SERVER_START_REQ( load_dll )
1425 req->handle = 0;
1426 req->base = module;
1427 req->size = nt->OptionalHeader.SizeOfImage;
1428 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1429 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1430 req->name = &wm->ldr.FullDllName.Buffer;
1431 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1432 wine_server_call( req );
1434 SERVER_END_REQ;
1436 /* setup relay debugging entry points */
1437 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1441 /******************************************************************************
1442 * load_native_dll (internal)
1444 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1445 DWORD flags, WINE_MODREF** pwm )
1447 void *module;
1448 HANDLE mapping;
1449 OBJECT_ATTRIBUTES attr;
1450 LARGE_INTEGER size;
1451 IMAGE_NT_HEADERS *nt;
1452 SIZE_T len = 0;
1453 WINE_MODREF *wm;
1454 NTSTATUS status;
1456 TRACE("Trying native dll %s\n", debugstr_w(name));
1458 attr.Length = sizeof(attr);
1459 attr.RootDirectory = 0;
1460 attr.ObjectName = NULL;
1461 attr.Attributes = 0;
1462 attr.SecurityDescriptor = NULL;
1463 attr.SecurityQualityOfService = NULL;
1464 size.QuadPart = 0;
1466 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1467 &attr, &size, PAGE_READONLY, SEC_IMAGE, file );
1468 if (status != STATUS_SUCCESS) return status;
1470 module = NULL;
1471 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1472 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1473 NtClose( mapping );
1474 if (status != STATUS_SUCCESS) return status;
1476 /* create the MODREF */
1478 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1480 /* fixup imports */
1482 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1484 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1486 /* the module has only be inserted in the load & memory order lists */
1487 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1488 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1490 /* FIXME: there are several more dangling references
1491 * left. Including dlls loaded by this dll before the
1492 * failed one. Unrolling is rather difficult with the
1493 * current structure and we can leave them lying
1494 * around with no problems, so we don't care.
1495 * As these might reference our wm, we don't free it.
1497 return status;
1501 /* send DLL load event */
1503 nt = RtlImageNtHeader( module );
1505 SERVER_START_REQ( load_dll )
1507 req->handle = wine_server_obj_handle( file );
1508 req->base = module;
1509 req->size = nt->OptionalHeader.SizeOfImage;
1510 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1511 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1512 req->name = &wm->ldr.FullDllName.Buffer;
1513 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1514 wine_server_call( req );
1516 SERVER_END_REQ;
1518 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1520 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1522 wm->ldr.LoadCount = 1;
1523 *pwm = wm;
1524 return STATUS_SUCCESS;
1528 /***********************************************************************
1529 * load_builtin_dll
1531 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1532 DWORD flags, WINE_MODREF** pwm )
1534 char error[256], dllname[MAX_PATH];
1535 const WCHAR *name, *p;
1536 DWORD len, i;
1537 void *handle = NULL;
1538 struct builtin_load_info info, *prev_info;
1540 /* Fix the name in case we have a full path and extension */
1541 name = path;
1542 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1543 if ((p = strrchrW( name, '/' ))) name = p + 1;
1545 /* load_library will modify info.status. Note also that load_library can be
1546 * called several times, if the .so file we're loading has dependencies.
1547 * info.status will gather all the errors we may get while loading all these
1548 * libraries
1550 info.load_path = load_path;
1551 info.filename = NULL;
1552 info.status = STATUS_SUCCESS;
1553 info.wm = NULL;
1555 if (file) /* we have a real file, try to load it */
1557 UNICODE_STRING nt_name;
1558 ANSI_STRING unix_name;
1560 TRACE("Trying built-in %s\n", debugstr_w(path));
1562 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1563 return STATUS_DLL_NOT_FOUND;
1565 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1567 RtlFreeUnicodeString( &nt_name );
1568 return STATUS_DLL_NOT_FOUND;
1570 prev_info = builtin_load_info;
1571 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1572 builtin_load_info = &info;
1573 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1574 builtin_load_info = prev_info;
1575 RtlFreeUnicodeString( &nt_name );
1576 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1577 if (!handle)
1579 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1580 return STATUS_INVALID_IMAGE_FORMAT;
1583 else
1585 int file_exists;
1587 TRACE("Trying built-in %s\n", debugstr_w(name));
1589 /* we don't want to depend on the current codepage here */
1590 len = strlenW( name ) + 1;
1591 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1592 for (i = 0; i < len; i++)
1594 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1595 dllname[i] = (char)name[i];
1596 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1599 prev_info = builtin_load_info;
1600 builtin_load_info = &info;
1601 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1602 builtin_load_info = prev_info;
1603 if (!handle)
1605 if (!file_exists)
1607 /* The file does not exist -> WARN() */
1608 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1609 return STATUS_DLL_NOT_FOUND;
1611 /* ERR() for all other errors (missing functions, ...) */
1612 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1613 return STATUS_PROCEDURE_NOT_FOUND;
1617 if (info.status != STATUS_SUCCESS)
1619 wine_dll_unload( handle );
1620 return info.status;
1623 if (!info.wm)
1625 PLIST_ENTRY mark, entry;
1627 /* The constructor wasn't called, this means the .so is already
1628 * loaded under a different name. Try to find the wm for it. */
1630 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1631 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1633 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1634 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1636 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1637 TRACE( "Found %s at %p for builtin %s\n",
1638 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1639 break;
1642 wine_dll_unload( handle ); /* release the libdl refcount */
1643 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1644 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1646 else
1648 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1649 info.wm->ldr.LoadCount = 1;
1650 info.wm->ldr.SectionHandle = handle;
1653 *pwm = info.wm;
1654 return STATUS_SUCCESS;
1658 /***********************************************************************
1659 * find_actctx_dll
1661 * Find the full path (if any) of the dll from the activation context.
1663 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1665 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1666 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1668 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1669 ACTCTX_SECTION_KEYED_DATA data;
1670 UNICODE_STRING nameW;
1671 NTSTATUS status;
1672 SIZE_T needed, size = 1024;
1673 WCHAR *p;
1675 RtlInitUnicodeString( &nameW, libname );
1676 data.cbSize = sizeof(data);
1677 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1678 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1679 &nameW, &data );
1680 if (status != STATUS_SUCCESS) return status;
1682 for (;;)
1684 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1686 status = STATUS_NO_MEMORY;
1687 goto done;
1689 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1690 AssemblyDetailedInformationInActivationContext,
1691 info, size, &needed );
1692 if (status == STATUS_SUCCESS) break;
1693 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1694 RtlFreeHeap( GetProcessHeap(), 0, info );
1695 size = needed;
1696 /* restart with larger buffer */
1699 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1701 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1703 p++;
1704 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1706 /* manifest name does not match directory name, so it's not a global
1707 * windows/winsxs manifest; use the manifest directory name instead */
1708 dirlen = p - info->lpAssemblyManifestPath;
1709 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1710 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1712 status = STATUS_NO_MEMORY;
1713 goto done;
1715 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1716 p += dirlen;
1717 strcpyW( p, libname );
1718 goto done;
1722 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1723 nameW.Length + 2*sizeof(WCHAR));
1725 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1727 status = STATUS_NO_MEMORY;
1728 goto done;
1730 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1731 p += windows_dir.Length / sizeof(WCHAR);
1732 memcpy( p, winsxsW, sizeof(winsxsW) );
1733 p += sizeof(winsxsW) / sizeof(WCHAR);
1734 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1735 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1736 *p++ = '\\';
1737 strcpyW( p, libname );
1738 done:
1739 RtlFreeHeap( GetProcessHeap(), 0, info );
1740 RtlReleaseActivationContext( data.hActCtx );
1741 return status;
1745 /***********************************************************************
1746 * find_dll_file
1748 * Find the file (or already loaded module) for a given dll name.
1750 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1751 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1753 OBJECT_ATTRIBUTES attr;
1754 IO_STATUS_BLOCK io;
1755 UNICODE_STRING nt_name;
1756 WCHAR *file_part, *ext, *dllname;
1757 ULONG len;
1759 /* first append .dll if needed */
1761 dllname = NULL;
1762 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1764 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1765 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1766 return STATUS_NO_MEMORY;
1767 strcpyW( dllname, libname );
1768 strcatW( dllname, dllW );
1769 libname = dllname;
1772 nt_name.Buffer = NULL;
1774 if (!contains_path( libname ))
1776 NTSTATUS status;
1777 WCHAR *fullname = NULL;
1779 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1781 status = find_actctx_dll( libname, &fullname );
1782 if (status == STATUS_SUCCESS)
1784 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1785 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1786 libname = dllname = fullname;
1788 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1790 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1791 return status;
1795 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1797 /* we need to search for it */
1798 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1799 if (len)
1801 if (len >= *size) goto overflow;
1802 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1804 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1806 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1807 return STATUS_NO_MEMORY;
1809 attr.Length = sizeof(attr);
1810 attr.RootDirectory = 0;
1811 attr.Attributes = OBJ_CASE_INSENSITIVE;
1812 attr.ObjectName = &nt_name;
1813 attr.SecurityDescriptor = NULL;
1814 attr.SecurityQualityOfService = NULL;
1815 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1816 goto found;
1819 /* not found */
1821 if (!contains_path( libname ))
1823 /* if libname doesn't contain a path at all, we simply return the name as is,
1824 * to be loaded as builtin */
1825 len = strlenW(libname) * sizeof(WCHAR);
1826 if (len >= *size) goto overflow;
1827 strcpyW( filename, libname );
1828 goto found;
1832 /* absolute path name, or relative path name but not found above */
1834 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1836 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1837 return STATUS_NO_MEMORY;
1839 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1840 if (len >= *size) goto overflow;
1841 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1842 if (!(*pwm = find_fullname_module( filename )) && handle)
1844 attr.Length = sizeof(attr);
1845 attr.RootDirectory = 0;
1846 attr.Attributes = OBJ_CASE_INSENSITIVE;
1847 attr.ObjectName = &nt_name;
1848 attr.SecurityDescriptor = NULL;
1849 attr.SecurityQualityOfService = NULL;
1850 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1852 found:
1853 RtlFreeUnicodeString( &nt_name );
1854 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1855 return STATUS_SUCCESS;
1857 overflow:
1858 RtlFreeUnicodeString( &nt_name );
1859 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1860 *size = len + sizeof(WCHAR);
1861 return STATUS_BUFFER_TOO_SMALL;
1865 /***********************************************************************
1866 * load_dll (internal)
1868 * Load a PE style module according to the load order.
1869 * The loader_section must be locked while calling this function.
1871 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1873 enum loadorder loadorder;
1874 WCHAR buffer[32];
1875 WCHAR *filename;
1876 ULONG size;
1877 WINE_MODREF *main_exe;
1878 HANDLE handle = 0;
1879 NTSTATUS nts;
1881 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1883 *pwm = NULL;
1884 filename = buffer;
1885 size = sizeof(buffer);
1886 for (;;)
1888 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1889 if (nts == STATUS_SUCCESS) break;
1890 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1891 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1892 /* grow the buffer and retry */
1893 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1896 if (*pwm) /* found already loaded module */
1898 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1900 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1902 TRACE("Found %s for %s at %p, count=%d\n",
1903 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1904 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1905 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1906 return STATUS_SUCCESS;
1909 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1910 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1912 if (handle && is_fake_dll( handle ))
1914 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1915 NtClose( handle );
1916 handle = 0;
1919 switch(loadorder)
1921 case LO_INVALID:
1922 nts = STATUS_NO_MEMORY;
1923 break;
1924 case LO_DISABLED:
1925 nts = STATUS_DLL_NOT_FOUND;
1926 break;
1927 case LO_NATIVE:
1928 case LO_NATIVE_BUILTIN:
1929 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1930 else
1932 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1933 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1934 /* not in PE format, maybe it's a builtin */
1935 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1937 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1938 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1939 break;
1940 case LO_BUILTIN:
1941 case LO_BUILTIN_NATIVE:
1942 case LO_DEFAULT: /* default is builtin,native */
1943 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1944 if (!handle) break; /* nothing else we can try */
1945 /* file is not a builtin library, try without using the specified file */
1946 if (nts != STATUS_SUCCESS)
1947 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1948 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1949 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1951 /* stub-only dll, try native */
1952 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1953 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1954 nts = STATUS_DLL_NOT_FOUND;
1956 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1957 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1958 break;
1961 if (nts == STATUS_SUCCESS)
1963 /* Initialize DLL just loaded */
1964 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1965 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1966 (*pwm)->ldr.BaseAddress);
1967 if (handle) NtClose( handle );
1968 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1969 return nts;
1972 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1973 if (handle) NtClose( handle );
1974 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1975 return nts;
1978 /******************************************************************
1979 * LdrLoadDll (NTDLL.@)
1981 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1982 const UNICODE_STRING *libname, HMODULE* hModule)
1984 WINE_MODREF *wm;
1985 NTSTATUS nts;
1987 RtlEnterCriticalSection( &loader_section );
1989 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1990 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1992 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1994 nts = process_attach( wm, NULL );
1995 if (nts != STATUS_SUCCESS)
1997 LdrUnloadDll(wm->ldr.BaseAddress);
1998 wm = NULL;
2001 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2003 RtlLeaveCriticalSection( &loader_section );
2004 return nts;
2008 /******************************************************************
2009 * LdrGetDllHandle (NTDLL.@)
2011 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2013 NTSTATUS status;
2014 WCHAR buffer[128];
2015 WCHAR *filename;
2016 ULONG size;
2017 WINE_MODREF *wm;
2019 RtlEnterCriticalSection( &loader_section );
2021 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2023 filename = buffer;
2024 size = sizeof(buffer);
2025 for (;;)
2027 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2028 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2029 if (status != STATUS_BUFFER_TOO_SMALL) break;
2030 /* grow the buffer and retry */
2031 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2033 status = STATUS_NO_MEMORY;
2034 break;
2038 if (status == STATUS_SUCCESS)
2040 if (wm) *base = wm->ldr.BaseAddress;
2041 else status = STATUS_DLL_NOT_FOUND;
2044 RtlLeaveCriticalSection( &loader_section );
2045 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2046 return status;
2050 /******************************************************************
2051 * LdrAddRefDll (NTDLL.@)
2053 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2055 NTSTATUS ret = STATUS_SUCCESS;
2056 WINE_MODREF *wm;
2058 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2060 RtlEnterCriticalSection( &loader_section );
2062 if ((wm = get_modref( module )))
2064 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2065 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2067 else ret = STATUS_INVALID_PARAMETER;
2069 RtlLeaveCriticalSection( &loader_section );
2070 return ret;
2074 /***********************************************************************
2075 * LdrProcessRelocationBlock (NTDLL.@)
2077 * Apply relocations to a given page of a mapped PE image.
2079 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2080 USHORT *relocs, INT delta )
2082 while (count--)
2084 USHORT offset = *relocs & 0xfff;
2085 int type = *relocs >> 12;
2086 switch(type)
2088 case IMAGE_REL_BASED_ABSOLUTE:
2089 break;
2090 case IMAGE_REL_BASED_HIGH:
2091 *(short *)((char *)page + offset) += HIWORD(delta);
2092 break;
2093 case IMAGE_REL_BASED_LOW:
2094 *(short *)((char *)page + offset) += LOWORD(delta);
2095 break;
2096 case IMAGE_REL_BASED_HIGHLOW:
2097 *(int *)((char *)page + offset) += delta;
2098 break;
2099 default:
2100 FIXME("Unknown/unsupported fixup type %x.\n", type);
2101 return NULL;
2103 relocs++;
2105 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2109 /******************************************************************
2110 * LdrQueryProcessModuleInformation
2113 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2114 ULONG buf_size, ULONG* req_size)
2116 SYSTEM_MODULE* sm = &smi->Modules[0];
2117 ULONG size = sizeof(ULONG);
2118 NTSTATUS nts = STATUS_SUCCESS;
2119 ANSI_STRING str;
2120 char* ptr;
2121 PLIST_ENTRY mark, entry;
2122 PLDR_MODULE mod;
2123 WORD id = 0;
2125 smi->ModulesCount = 0;
2127 RtlEnterCriticalSection( &loader_section );
2128 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2129 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2131 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2132 size += sizeof(*sm);
2133 if (size <= buf_size)
2135 sm->Reserved1 = 0; /* FIXME */
2136 sm->Reserved2 = 0; /* FIXME */
2137 sm->ImageBaseAddress = mod->BaseAddress;
2138 sm->ImageSize = mod->SizeOfImage;
2139 sm->Flags = mod->Flags;
2140 sm->Id = id++;
2141 sm->Rank = 0; /* FIXME */
2142 sm->Unknown = 0; /* FIXME */
2143 str.Length = 0;
2144 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2145 str.Buffer = (char*)sm->Name;
2146 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2147 ptr = strrchr(str.Buffer, '\\');
2148 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2150 smi->ModulesCount++;
2151 sm++;
2153 else nts = STATUS_INFO_LENGTH_MISMATCH;
2155 RtlLeaveCriticalSection( &loader_section );
2157 if (req_size) *req_size = size;
2159 return nts;
2163 /******************************************************************
2164 * RtlDllShutdownInProgress (NTDLL.@)
2166 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2168 return process_detaching;
2172 /******************************************************************
2173 * LdrShutdownProcess (NTDLL.@)
2176 void WINAPI LdrShutdownProcess(void)
2178 TRACE("()\n");
2179 process_detach( TRUE, (LPVOID)1 );
2182 /******************************************************************
2183 * LdrShutdownThread (NTDLL.@)
2186 void WINAPI LdrShutdownThread(void)
2188 PLIST_ENTRY mark, entry;
2189 PLDR_MODULE mod;
2191 TRACE("()\n");
2193 /* don't do any detach calls if process is exiting */
2194 if (process_detaching) return;
2195 /* FIXME: there is still a race here */
2197 RtlEnterCriticalSection( &loader_section );
2199 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2200 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2202 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2203 InInitializationOrderModuleList);
2204 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2205 continue;
2206 if ( mod->Flags & LDR_NO_DLL_CALLS )
2207 continue;
2209 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2210 DLL_THREAD_DETACH, NULL );
2213 RtlLeaveCriticalSection( &loader_section );
2214 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2218 /***********************************************************************
2219 * free_modref
2222 static void free_modref( WINE_MODREF *wm )
2224 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2225 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2226 if (wm->ldr.InInitializationOrderModuleList.Flink)
2227 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2229 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2230 if (!TRACE_ON(module))
2231 TRACE_(loaddll)("Unloaded module %s : %s\n",
2232 debugstr_w(wm->ldr.FullDllName.Buffer),
2233 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2235 SERVER_START_REQ( unload_dll )
2237 req->base = wm->ldr.BaseAddress;
2238 wine_server_call( req );
2240 SERVER_END_REQ;
2242 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2243 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2244 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2245 if (cached_modref == wm) cached_modref = NULL;
2246 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2247 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2248 RtlFreeHeap( GetProcessHeap(), 0, wm );
2251 /***********************************************************************
2252 * MODULE_FlushModrefs
2254 * Remove all unused modrefs and call the internal unloading routines
2255 * for the library type.
2257 * The loader_section must be locked while calling this function.
2259 static void MODULE_FlushModrefs(void)
2261 PLIST_ENTRY mark, entry, prev;
2262 PLDR_MODULE mod;
2263 WINE_MODREF*wm;
2265 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2266 for (entry = mark->Blink; entry != mark; entry = prev)
2268 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2269 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2270 prev = entry->Blink;
2271 if (!mod->LoadCount) free_modref( wm );
2274 /* check load order list too for modules that haven't been initialized yet */
2275 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2276 for (entry = mark->Blink; entry != mark; entry = prev)
2278 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2279 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2280 prev = entry->Blink;
2281 if (!mod->LoadCount) free_modref( wm );
2285 /***********************************************************************
2286 * MODULE_DecRefCount
2288 * The loader_section must be locked while calling this function.
2290 static void MODULE_DecRefCount( WINE_MODREF *wm )
2292 int i;
2294 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2295 return;
2297 if ( wm->ldr.LoadCount <= 0 )
2298 return;
2300 --wm->ldr.LoadCount;
2301 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2303 if ( wm->ldr.LoadCount == 0 )
2305 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2307 for ( i = 0; i < wm->nDeps; i++ )
2308 if ( wm->deps[i] )
2309 MODULE_DecRefCount( wm->deps[i] );
2311 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2315 /******************************************************************
2316 * LdrUnloadDll (NTDLL.@)
2320 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2322 NTSTATUS retv = STATUS_SUCCESS;
2324 TRACE("(%p)\n", hModule);
2326 RtlEnterCriticalSection( &loader_section );
2328 /* if we're stopping the whole process (and forcing the removal of all
2329 * DLLs) the library will be freed anyway
2331 if (!process_detaching)
2333 WINE_MODREF *wm;
2335 free_lib_count++;
2336 if ((wm = get_modref( hModule )) != NULL)
2338 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2340 /* Recursively decrement reference counts */
2341 MODULE_DecRefCount( wm );
2343 /* Call process detach notifications */
2344 if ( free_lib_count <= 1 )
2346 process_detach( FALSE, NULL );
2347 MODULE_FlushModrefs();
2350 TRACE("END\n");
2352 else
2353 retv = STATUS_DLL_NOT_FOUND;
2355 free_lib_count--;
2358 RtlLeaveCriticalSection( &loader_section );
2360 return retv;
2363 /***********************************************************************
2364 * RtlImageNtHeader (NTDLL.@)
2366 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2368 IMAGE_NT_HEADERS *ret;
2370 __TRY
2372 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2374 ret = NULL;
2375 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2377 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2378 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2381 __EXCEPT_PAGE_FAULT
2383 return NULL;
2385 __ENDTRY
2386 return ret;
2390 /***********************************************************************
2391 * attach_process_dlls
2393 * Initial attach to all the dlls loaded by the process.
2395 static NTSTATUS attach_process_dlls( void *wm )
2397 NTSTATUS status;
2399 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2401 RtlEnterCriticalSection( &loader_section );
2402 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2404 if (last_failed_modref)
2405 ERR( "%s failed to initialize, aborting\n",
2406 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2407 return status;
2409 attach_implicitly_loaded_dlls( (LPVOID)1 );
2410 RtlLeaveCriticalSection( &loader_section );
2411 return status;
2415 /******************************************************************
2416 * LdrInitializeThunk (NTDLL.@)
2419 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2421 NTSTATUS status;
2422 WINE_MODREF *wm;
2423 LPCWSTR load_path;
2424 SIZE_T stack_size;
2425 PEB *peb = NtCurrentTeb()->Peb;
2426 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2428 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2430 /* allocate the modref for the main exe (if not already done) */
2431 wm = get_modref( peb->ImageBaseAddress );
2432 assert( wm );
2433 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2435 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2436 exit(1);
2439 peb->LoaderLock = &loader_section;
2440 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2441 version_init( wm->ldr.FullDllName.Buffer );
2443 /* the main exe needs to be the first in the load order list */
2444 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2445 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2447 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
2448 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
2450 if ((status = virtual_alloc_thread_stack( NULL, stack_size )) != STATUS_SUCCESS) goto error;
2451 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2453 actctx_init();
2454 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2455 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2456 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2457 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2458 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2460 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2461 if (status != STATUS_SUCCESS) goto error;
2463 virtual_clear_thread_stack();
2464 return;
2466 error:
2467 ERR( "Main exe initialization for %s failed, status %x\n",
2468 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2469 NtTerminateProcess( GetCurrentProcess(), status );
2473 /***********************************************************************
2474 * RtlImageDirectoryEntryToData (NTDLL.@)
2476 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2478 const IMAGE_NT_HEADERS *nt;
2479 DWORD addr;
2481 if ((ULONG_PTR)module & 1) /* mapped as data file */
2483 module = (HMODULE)((ULONG_PTR)module & ~1);
2484 image = FALSE;
2486 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2487 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2488 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2489 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2490 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2492 /* not mapped as image, need to find the section containing the virtual address */
2493 return RtlImageRvaToVa( nt, module, addr, NULL );
2497 /***********************************************************************
2498 * RtlImageRvaToSection (NTDLL.@)
2500 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2501 HMODULE module, DWORD rva )
2503 int i;
2504 const IMAGE_SECTION_HEADER *sec;
2506 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2507 nt->FileHeader.SizeOfOptionalHeader);
2508 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2510 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2511 return (PIMAGE_SECTION_HEADER)sec;
2513 return NULL;
2517 /***********************************************************************
2518 * RtlImageRvaToVa (NTDLL.@)
2520 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2521 DWORD rva, IMAGE_SECTION_HEADER **section )
2523 IMAGE_SECTION_HEADER *sec;
2525 if (section && *section) /* try this section first */
2527 sec = *section;
2528 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2529 goto found;
2531 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2532 found:
2533 if (section) *section = sec;
2534 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2538 /***********************************************************************
2539 * RtlPcToFileHeader (NTDLL.@)
2541 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2543 LDR_MODULE *module;
2544 PVOID ret = NULL;
2546 RtlEnterCriticalSection( &loader_section );
2547 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2548 RtlLeaveCriticalSection( &loader_section );
2549 *address = ret;
2550 return ret;
2554 /***********************************************************************
2555 * NtLoadDriver (NTDLL.@)
2556 * ZwLoadDriver (NTDLL.@)
2558 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2560 FIXME("(%p), stub!\n",DriverServiceName);
2561 return STATUS_NOT_IMPLEMENTED;
2565 /***********************************************************************
2566 * NtUnloadDriver (NTDLL.@)
2567 * ZwUnloadDriver (NTDLL.@)
2569 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2571 FIXME("(%p), stub!\n",DriverServiceName);
2572 return STATUS_NOT_IMPLEMENTED;
2576 /******************************************************************
2577 * DllMain (NTDLL.@)
2579 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2581 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2582 return TRUE;
2586 /******************************************************************
2587 * __wine_init_windows_dir (NTDLL.@)
2589 * Windows and system dir initialization once kernel32 has been loaded.
2591 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2593 PLIST_ENTRY mark, entry;
2594 LPWSTR buffer, p;
2596 RtlCreateUnicodeString( &windows_dir, windir );
2597 RtlCreateUnicodeString( &system_dir, sysdir );
2598 strcpyW( user_shared_data->NtSystemRoot, windir );
2600 /* prepend the system dir to the name of the already created modules */
2601 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2602 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2604 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2606 assert( mod->Flags & LDR_WINE_INTERNAL );
2608 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2609 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2610 if (!buffer) continue;
2611 strcpyW( buffer, system_dir.Buffer );
2612 p = buffer + strlenW( buffer );
2613 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2614 strcpyW( p, mod->FullDllName.Buffer );
2615 RtlInitUnicodeString( &mod->FullDllName, buffer );
2616 RtlInitUnicodeString( &mod->BaseDllName, p );
2621 /***********************************************************************
2622 * __wine_process_init
2624 void __wine_process_init(void)
2626 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2628 WINE_MODREF *wm;
2629 NTSTATUS status;
2630 ANSI_STRING func_name;
2631 void (* DECLSPEC_NORETURN init_func)(void);
2632 extern mode_t FILE_umask;
2634 main_exe_file = thread_init();
2636 /* retrieve current umask */
2637 FILE_umask = umask(0777);
2638 umask( FILE_umask );
2640 /* setup the load callback and create ntdll modref */
2641 wine_dll_set_callback( load_builtin_callback );
2643 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2645 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2646 exit(1);
2648 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2649 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2651 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2652 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2653 0, (void **)&init_func )) != STATUS_SUCCESS)
2655 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2656 exit(1);
2658 init_func();