kernel32: Moved the allocation of the process stack to ntdll.
[wine.git] / dlls / ntdll / loader.c
blobf17c0c0e6b6fe4233c40e2dd90821dba13b52de4
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
30 #ifdef HAVE_VALGRIND_MEMCHECK_H
31 # include <valgrind/memcheck.h>
32 #endif
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
37 #include "ntstatus.h"
38 #define WIN32_NO_STATUS
39 #include "windef.h"
40 #include "winnt.h"
41 #include "winternl.h"
43 #include "wine/exception.h"
44 #include "wine/library.h"
45 #include "wine/pthread.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
48 #include "wine/server.h"
49 #include "ntdll_misc.h"
50 #include "ddk/wdm.h"
52 WINE_DEFAULT_DEBUG_CHANNEL(module);
53 WINE_DECLARE_DEBUG_CHANNEL(relay);
54 WINE_DECLARE_DEBUG_CHANNEL(snoop);
55 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
56 WINE_DECLARE_DEBUG_CHANNEL(imports);
58 /* we don't want to include winuser.h */
59 #define RT_MANIFEST ((ULONG_PTR)24)
60 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
62 extern struct wine_pthread_functions pthread_functions;
64 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
66 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
67 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
69 static const char * const reason_names[] =
71 "PROCESS_DETACH",
72 "PROCESS_ATTACH",
73 "THREAD_ATTACH",
74 "THREAD_DETACH",
75 NULL, NULL, NULL, NULL,
76 "WINE_PREATTACH"
79 static const WCHAR dllW[] = {'.','d','l','l',0};
81 /* internal representation of 32bit modules. per process. */
82 typedef struct _wine_modref
84 LDR_MODULE ldr;
85 int nDeps;
86 struct _wine_modref **deps;
87 } WINE_MODREF;
89 /* info about the current builtin dll load */
90 /* used to keep track of things across the register_dll constructor call */
91 struct builtin_load_info
93 const WCHAR *load_path;
94 const WCHAR *filename;
95 NTSTATUS status;
96 WINE_MODREF *wm;
99 static struct builtin_load_info default_load_info;
100 static struct builtin_load_info *builtin_load_info = &default_load_info;
102 static HANDLE main_exe_file;
103 static UINT tls_module_count; /* number of modules with TLS directory */
104 static UINT tls_total_size; /* total size of TLS storage */
105 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
107 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
108 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
110 static RTL_CRITICAL_SECTION loader_section;
111 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
113 0, 0, &loader_section,
114 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
115 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
117 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
119 static WINE_MODREF *cached_modref;
120 static WINE_MODREF *current_modref;
121 static WINE_MODREF *last_failed_modref;
123 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
124 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
125 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
126 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
128 /* convert PE image VirtualAddress to Real Address */
129 static inline void *get_rva( HMODULE module, DWORD va )
131 return (void *)((char *)module + va);
134 /* check whether the file name contains a path */
135 static inline int contains_path( LPCWSTR name )
137 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
140 /* convert from straight ASCII to Unicode without depending on the current codepage */
141 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
143 while (len--) *dst++ = (unsigned char)*src++;
147 /*************************************************************************
148 * call_dll_entry_point
150 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
151 * their entry point, so we need a small asm wrapper.
153 #ifdef __i386__
154 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
155 __ASM_GLOBAL_FUNC(call_dll_entry_point,
156 "pushl %ebp\n\t"
157 "movl %esp,%ebp\n\t"
158 "pushl %ebx\n\t"
159 "subl $8,%esp\n\t"
160 "pushl 20(%ebp)\n\t"
161 "pushl 16(%ebp)\n\t"
162 "pushl 12(%ebp)\n\t"
163 "movl 8(%ebp),%eax\n\t"
164 "call *%eax\n\t"
165 "leal -4(%ebp),%esp\n\t"
166 "popl %ebx\n\t"
167 "popl %ebp\n\t"
168 "ret" )
169 #else /* __i386__ */
170 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
171 UINT reason, void *reserved )
173 return proc( module, reason, reserved );
175 #endif /* __i386__ */
178 #ifdef __i386__
179 /*************************************************************************
180 * stub_entry_point
182 * Entry point for stub functions.
184 static void stub_entry_point( const char *dll, const char *name, ... )
186 EXCEPTION_RECORD rec;
188 rec.ExceptionCode = EXCEPTION_WINE_STUB;
189 rec.ExceptionFlags = EH_NONCONTINUABLE;
190 rec.ExceptionRecord = NULL;
191 #ifdef __GNUC__
192 rec.ExceptionAddress = __builtin_return_address(0);
193 #else
194 rec.ExceptionAddress = *((void **)&dll - 1);
195 #endif
196 rec.NumberParameters = 2;
197 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
198 rec.ExceptionInformation[1] = (ULONG_PTR)name;
199 for (;;) RtlRaiseException( &rec );
203 #include "pshpack1.h"
204 struct stub
206 BYTE popl_eax; /* popl %eax */
207 BYTE pushl1; /* pushl $name */
208 const char *name;
209 BYTE pushl2; /* pushl $dll */
210 const char *dll;
211 BYTE pushl_eax; /* pushl %eax */
212 BYTE jmp; /* jmp stub_entry_point */
213 DWORD entry;
215 #include "poppack.h"
217 /*************************************************************************
218 * allocate_stub
220 * Allocate a stub entry point.
222 static ULONG_PTR allocate_stub( const char *dll, const char *name )
224 #define MAX_SIZE 65536
225 static struct stub *stubs;
226 static unsigned int nb_stubs;
227 struct stub *stub;
229 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
231 if (!stubs)
233 SIZE_T size = MAX_SIZE;
234 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
235 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
236 return 0xdeadbeef;
238 stub = &stubs[nb_stubs++];
239 stub->popl_eax = 0x58; /* popl %eax */
240 stub->pushl1 = 0x68; /* pushl $name */
241 stub->name = name;
242 stub->pushl2 = 0x68; /* pushl $dll */
243 stub->dll = dll;
244 stub->pushl_eax = 0x50; /* pushl %eax */
245 stub->jmp = 0xe9; /* jmp stub_entry_point */
246 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
247 return (ULONG_PTR)stub;
250 #else /* __i386__ */
251 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
252 #endif /* __i386__ */
255 /*************************************************************************
256 * get_modref
258 * Looks for the referenced HMODULE in the current process
259 * The loader_section must be locked while calling this function.
261 static WINE_MODREF *get_modref( HMODULE hmod )
263 PLIST_ENTRY mark, entry;
264 PLDR_MODULE mod;
266 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
268 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
269 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
271 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
272 if (mod->BaseAddress == hmod)
273 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
274 if (mod->BaseAddress > (void*)hmod) break;
276 return NULL;
280 /**********************************************************************
281 * find_basename_module
283 * Find a module from its base name.
284 * The loader_section must be locked while calling this function
286 static WINE_MODREF *find_basename_module( LPCWSTR name )
288 PLIST_ENTRY mark, entry;
290 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
291 return cached_modref;
293 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
294 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
296 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
297 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
299 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
300 return cached_modref;
303 return NULL;
307 /**********************************************************************
308 * find_fullname_module
310 * Find a module from its full path name.
311 * The loader_section must be locked while calling this function
313 static WINE_MODREF *find_fullname_module( LPCWSTR name )
315 PLIST_ENTRY mark, entry;
317 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
318 return cached_modref;
320 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
321 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
323 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
324 if (!strcmpiW( name, mod->FullDllName.Buffer ))
326 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
327 return cached_modref;
330 return NULL;
334 /*************************************************************************
335 * find_forwarded_export
337 * Find the final function pointer for a forwarded function.
338 * The loader_section must be locked while calling this function.
340 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
342 const IMAGE_EXPORT_DIRECTORY *exports;
343 DWORD exp_size;
344 WINE_MODREF *wm;
345 WCHAR mod_name[32];
346 const char *end = strrchr(forward, '.');
347 FARPROC proc = NULL;
349 if (!end) return NULL;
350 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
351 ascii_to_unicode( mod_name, forward, end - forward );
352 mod_name[end - forward] = 0;
353 if (!strchrW( mod_name, '.' ))
355 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
356 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
359 if (!(wm = find_basename_module( mod_name )))
361 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
362 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
363 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
365 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
367 LdrUnloadDll( wm->ldr.BaseAddress );
368 wm = NULL;
372 if (!wm)
374 ERR( "module not found for forward '%s' used by %s\n",
375 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
376 return NULL;
379 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
380 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
381 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1, load_path );
383 if (!proc)
385 ERR("function not found for forward '%s' used by %s."
386 " If you are using builtin %s, try using the native one instead.\n",
387 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
388 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
390 return proc;
394 /*************************************************************************
395 * find_ordinal_export
397 * Find an exported function by ordinal.
398 * The exports base must have been subtracted from the ordinal already.
399 * The loader_section must be locked while calling this function.
401 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
402 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
404 FARPROC proc;
405 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
407 if (ordinal >= exports->NumberOfFunctions)
409 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
410 return NULL;
412 if (!functions[ordinal]) return NULL;
414 proc = get_rva( module, functions[ordinal] );
416 /* if the address falls into the export dir, it's a forward */
417 if (((const char *)proc >= (const char *)exports) &&
418 ((const char *)proc < (const char *)exports + exp_size))
419 return find_forwarded_export( module, (const char *)proc, load_path );
421 if (TRACE_ON(snoop))
423 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
424 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
426 if (TRACE_ON(relay))
428 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
429 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
431 return proc;
435 /*************************************************************************
436 * find_named_export
438 * Find an exported function by name.
439 * The loader_section must be locked while calling this function.
441 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
442 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
444 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
445 const DWORD *names = get_rva( module, exports->AddressOfNames );
446 int min = 0, max = exports->NumberOfNames - 1;
448 /* first check the hint */
449 if (hint >= 0 && hint <= max)
451 char *ename = get_rva( module, names[hint] );
452 if (!strcmp( ename, name ))
453 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
456 /* then do a binary search */
457 while (min <= max)
459 int res, pos = (min + max) / 2;
460 char *ename = get_rva( module, names[pos] );
461 if (!(res = strcmp( ename, name )))
462 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
463 if (res > 0) max = pos - 1;
464 else min = pos + 1;
466 return NULL;
471 /*************************************************************************
472 * import_dll
474 * Import the dll specified by the given import descriptor.
475 * The loader_section must be locked while calling this function.
477 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
479 NTSTATUS status;
480 WINE_MODREF *wmImp;
481 HMODULE imp_mod;
482 const IMAGE_EXPORT_DIRECTORY *exports;
483 DWORD exp_size;
484 const IMAGE_THUNK_DATA *import_list;
485 IMAGE_THUNK_DATA *thunk_list;
486 WCHAR buffer[32];
487 const char *name = get_rva( module, descr->Name );
488 DWORD len = strlen(name);
489 PVOID protect_base;
490 SIZE_T protect_size = 0;
491 DWORD protect_old;
493 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
494 if (descr->u.OriginalFirstThunk)
495 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
496 else
497 import_list = thunk_list;
499 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
501 if (len * sizeof(WCHAR) < sizeof(buffer))
503 ascii_to_unicode( buffer, name, len );
504 buffer[len] = 0;
505 status = load_dll( load_path, buffer, 0, &wmImp );
507 else /* need to allocate a larger buffer */
509 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
510 if (!ptr) return NULL;
511 ascii_to_unicode( ptr, name, len );
512 ptr[len] = 0;
513 status = load_dll( load_path, ptr, 0, &wmImp );
514 RtlFreeHeap( GetProcessHeap(), 0, ptr );
517 if (status)
519 if (status == STATUS_DLL_NOT_FOUND)
520 ERR("Library %s (which is needed by %s) not found\n",
521 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
522 else
523 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
524 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
525 return NULL;
528 /* unprotect the import address table since it can be located in
529 * readonly section */
530 while (import_list[protect_size].u1.Ordinal) protect_size++;
531 protect_base = thunk_list;
532 protect_size *= sizeof(*thunk_list);
533 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
534 &protect_size, PAGE_WRITECOPY, &protect_old );
536 imp_mod = wmImp->ldr.BaseAddress;
537 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
539 if (!exports)
541 /* set all imported function to deadbeef */
542 while (import_list->u1.Ordinal)
544 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
546 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
547 WARN("No implementation for %s.%d", name, ordinal );
548 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
550 else
552 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
553 WARN("No implementation for %s.%s", name, pe_name->Name );
554 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
556 WARN(" imported from %s, allocating stub %p\n",
557 debugstr_w(current_modref->ldr.FullDllName.Buffer),
558 (void *)thunk_list->u1.Function );
559 import_list++;
560 thunk_list++;
562 goto done;
565 while (import_list->u1.Ordinal)
567 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
569 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
571 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
572 ordinal - exports->Base, load_path );
573 if (!thunk_list->u1.Function)
575 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
576 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
577 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
578 (void *)thunk_list->u1.Function );
580 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
582 else /* import by name */
584 IMAGE_IMPORT_BY_NAME *pe_name;
585 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
586 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
587 (const char*)pe_name->Name,
588 pe_name->Hint, load_path );
589 if (!thunk_list->u1.Function)
591 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
592 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
593 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
594 (void *)thunk_list->u1.Function );
596 TRACE_(imports)("--- %s %s.%d = %p\n",
597 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
599 import_list++;
600 thunk_list++;
603 done:
604 /* restore old protection of the import address table */
605 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
606 return wmImp;
610 /***********************************************************************
611 * create_module_activation_context
613 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
615 NTSTATUS status;
616 LDR_RESOURCE_INFO info;
617 const IMAGE_RESOURCE_DATA_ENTRY *entry;
619 info.Type = RT_MANIFEST;
620 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
621 info.Language = 0;
622 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
624 ACTCTXW ctx;
625 ctx.cbSize = sizeof(ctx);
626 ctx.lpSource = NULL;
627 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
628 ctx.hModule = module->BaseAddress;
629 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
630 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
632 return status;
636 /****************************************************************
637 * fixup_imports
639 * Fixup all imports of a given module.
640 * The loader_section must be locked while calling this function.
642 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
644 int i, nb_imports;
645 const IMAGE_IMPORT_DESCRIPTOR *imports;
646 WINE_MODREF *prev;
647 DWORD size;
648 NTSTATUS status;
649 ULONG_PTR cookie;
651 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
652 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
654 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
655 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
656 return STATUS_SUCCESS;
658 nb_imports = 0;
659 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
661 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
663 if (!create_module_activation_context( &wm->ldr ))
664 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
666 /* Allocate module dependency list */
667 wm->nDeps = nb_imports;
668 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
670 /* load the imported modules. They are automatically
671 * added to the modref list of the process.
673 prev = current_modref;
674 current_modref = wm;
675 status = STATUS_SUCCESS;
676 for (i = 0; i < nb_imports; i++)
678 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
679 status = STATUS_DLL_NOT_FOUND;
681 current_modref = prev;
682 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
683 return status;
687 /*************************************************************************
688 * alloc_module
690 * Allocate a WINE_MODREF structure and add it to the process list
691 * The loader_section must be locked while calling this function.
693 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
695 WINE_MODREF *wm;
696 const WCHAR *p;
697 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
698 PLIST_ENTRY entry, mark;
700 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
702 wm->nDeps = 0;
703 wm->deps = NULL;
705 wm->ldr.BaseAddress = hModule;
706 wm->ldr.EntryPoint = NULL;
707 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
708 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
709 wm->ldr.LoadCount = 1;
710 wm->ldr.TlsIndex = -1;
711 wm->ldr.SectionHandle = NULL;
712 wm->ldr.CheckSum = 0;
713 wm->ldr.TimeDateStamp = 0;
714 wm->ldr.ActivationContext = 0;
716 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
717 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
718 else p = wm->ldr.FullDllName.Buffer;
719 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
721 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
723 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
724 if (nt->OptionalHeader.AddressOfEntryPoint)
725 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
728 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
729 &wm->ldr.InLoadOrderModuleList);
731 /* insert module in MemoryList, sorted in increasing base addresses */
732 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
733 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
735 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
736 break;
738 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
739 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
740 wm->ldr.InMemoryOrderModuleList.Flink = entry;
741 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
743 /* wait until init is called for inserting into this list */
744 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
745 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
747 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
749 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
750 VIRTUAL_SetForceExec( TRUE );
752 return wm;
756 /*************************************************************************
757 * alloc_process_tls
759 * Allocate the process-wide structure for module TLS storage.
761 static NTSTATUS alloc_process_tls(void)
763 PLIST_ENTRY mark, entry;
764 PLDR_MODULE mod;
765 const IMAGE_TLS_DIRECTORY *dir;
766 ULONG size, i;
768 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
769 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
771 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
772 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
773 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
774 continue;
775 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
776 if (!size) continue;
777 tls_total_size += size;
778 tls_module_count++;
780 if (!tls_module_count) return STATUS_SUCCESS;
782 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
784 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
785 if (!tls_dirs) return STATUS_NO_MEMORY;
787 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
789 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
790 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
791 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
792 continue;
793 tls_dirs[i] = dir;
794 *(DWORD *)dir->AddressOfIndex = i;
795 mod->TlsIndex = i;
796 mod->LoadCount = -1; /* can't unload it */
797 i++;
799 return STATUS_SUCCESS;
803 /*************************************************************************
804 * alloc_thread_tls
806 * Allocate the per-thread structure for module TLS storage.
808 static NTSTATUS alloc_thread_tls(void)
810 void **pointers;
811 char *data;
812 UINT i;
814 if (!tls_module_count) return STATUS_SUCCESS;
816 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
817 tls_module_count * sizeof(*pointers) )))
818 return STATUS_NO_MEMORY;
820 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
822 RtlFreeHeap( GetProcessHeap(), 0, pointers );
823 return STATUS_NO_MEMORY;
826 for (i = 0; i < tls_module_count; i++)
828 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
829 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
831 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
832 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
833 (void *)dir->StartAddressOfRawData, data );
835 pointers[i] = data;
836 memcpy( data, (void *)dir->StartAddressOfRawData, size );
837 data += size;
838 memset( data, 0, dir->SizeOfZeroFill );
839 data += dir->SizeOfZeroFill;
841 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
842 return STATUS_SUCCESS;
846 /*************************************************************************
847 * call_tls_callbacks
849 static void call_tls_callbacks( HMODULE module, UINT reason )
851 const IMAGE_TLS_DIRECTORY *dir;
852 const PIMAGE_TLS_CALLBACK *callback;
853 ULONG dirsize;
855 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
856 if (!dir || !dir->AddressOfCallBacks) return;
858 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
860 if (TRACE_ON(relay))
861 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
862 GetCurrentThreadId(), *callback, module, reason_names[reason] );
863 __TRY
865 (*callback)( module, reason, NULL );
867 __EXCEPT_ALL
869 if (TRACE_ON(relay))
870 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
871 GetCurrentThreadId(), callback, module, reason_names[reason] );
872 return;
874 __ENDTRY
875 if (TRACE_ON(relay))
876 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
877 GetCurrentThreadId(), *callback, module, reason_names[reason] );
882 /*************************************************************************
883 * MODULE_InitDLL
885 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
887 WCHAR mod_name[32];
888 NTSTATUS status = STATUS_SUCCESS;
889 DLLENTRYPROC entry = wm->ldr.EntryPoint;
890 void *module = wm->ldr.BaseAddress;
891 BOOL retv = TRUE;
893 /* Skip calls for modules loaded with special load flags */
895 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
896 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
897 if (!entry) return STATUS_SUCCESS;
899 if (TRACE_ON(relay))
901 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
902 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
903 mod_name[len / sizeof(WCHAR)] = 0;
904 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
905 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
906 reason_names[reason], lpReserved );
908 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
909 reason_names[reason], lpReserved );
911 __TRY
913 retv = call_dll_entry_point( entry, module, reason, lpReserved );
914 if (!retv)
915 status = STATUS_DLL_INIT_FAILED;
917 __EXCEPT_ALL
919 if (TRACE_ON(relay))
920 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
921 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
922 status = GetExceptionCode();
924 __ENDTRY
926 /* The state of the module list may have changed due to the call
927 to the dll. We cannot assume that this module has not been
928 deleted. */
929 if (TRACE_ON(relay))
930 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
931 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
932 reason_names[reason], lpReserved, retv );
933 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
935 return status;
939 /*************************************************************************
940 * process_attach
942 * Send the process attach notification to all DLLs the given module
943 * depends on (recursively). This is somewhat complicated due to the fact that
945 * - we have to respect the module dependencies, i.e. modules implicitly
946 * referenced by another module have to be initialized before the module
947 * itself can be initialized
949 * - the initialization routine of a DLL can itself call LoadLibrary,
950 * thereby introducing a whole new set of dependencies (even involving
951 * the 'old' modules) at any time during the whole process
953 * (Note that this routine can be recursively entered not only directly
954 * from itself, but also via LoadLibrary from one of the called initialization
955 * routines.)
957 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
958 * the process *detach* notifications to be sent in the correct order.
959 * This must not only take into account module dependencies, but also
960 * 'hidden' dependencies created by modules calling LoadLibrary in their
961 * attach notification routine.
963 * The strategy is rather simple: we move a WINE_MODREF to the head of the
964 * list after the attach notification has returned. This implies that the
965 * detach notifications are called in the reverse of the sequence the attach
966 * notifications *returned*.
968 * The loader_section must be locked while calling this function.
970 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
972 NTSTATUS status = STATUS_SUCCESS;
973 ULONG_PTR cookie;
974 int i;
976 if (process_detaching) return status;
978 /* prevent infinite recursion in case of cyclical dependencies */
979 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
980 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
981 return status;
983 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
985 /* Tag current MODREF to prevent recursive loop */
986 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
987 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
988 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
990 /* Recursively attach all DLLs this one depends on */
991 for ( i = 0; i < wm->nDeps; i++ )
993 if (!wm->deps[i]) continue;
994 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
997 /* Call DLL entry point */
998 if (status == STATUS_SUCCESS)
1000 WINE_MODREF *prev = current_modref;
1001 current_modref = wm;
1002 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1003 if (status == STATUS_SUCCESS)
1004 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1005 else
1007 /* point to the name so LdrInitializeThunk can print it */
1008 last_failed_modref = wm;
1009 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1011 current_modref = prev;
1014 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1015 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1016 &wm->ldr.InInitializationOrderModuleList);
1018 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1019 /* Remove recursion flag */
1020 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1022 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1023 return status;
1027 /**********************************************************************
1028 * attach_implicitly_loaded_dlls
1030 * Attach to the (builtin) dlls that have been implicitly loaded because
1031 * of a dependency at the Unix level, but not imported at the Win32 level.
1033 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1035 for (;;)
1037 PLIST_ENTRY mark, entry;
1039 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1040 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1042 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1044 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1045 TRACE( "found implicitly loaded %s, attaching to it\n",
1046 debugstr_w(mod->BaseDllName.Buffer));
1047 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1048 break; /* restart the search from the start */
1050 if (entry == mark) break; /* nothing found */
1055 /*************************************************************************
1056 * process_detach
1058 * Send DLL process detach notifications. See the comment about calling
1059 * sequence at process_attach. Unless the bForceDetach flag
1060 * is set, only DLLs with zero refcount are notified.
1062 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1064 PLIST_ENTRY mark, entry;
1065 PLDR_MODULE mod;
1067 RtlEnterCriticalSection( &loader_section );
1068 if (bForceDetach) process_detaching = 1;
1069 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1072 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1074 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1075 InInitializationOrderModuleList);
1076 /* Check whether to detach this DLL */
1077 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1078 continue;
1079 if ( mod->LoadCount && !bForceDetach )
1080 continue;
1082 /* Call detach notification */
1083 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1084 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1085 DLL_PROCESS_DETACH, lpReserved );
1087 /* Restart at head of WINE_MODREF list, as entries might have
1088 been added and/or removed while performing the call ... */
1089 break;
1091 } while (entry != mark);
1093 RtlLeaveCriticalSection( &loader_section );
1096 /*************************************************************************
1097 * MODULE_DllThreadAttach
1099 * Send DLL thread attach notifications. These are sent in the
1100 * reverse sequence of process detach notification.
1103 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1105 PLIST_ENTRY mark, entry;
1106 PLDR_MODULE mod;
1107 NTSTATUS status;
1109 /* don't do any attach calls if process is exiting */
1110 if (process_detaching) return STATUS_SUCCESS;
1111 /* FIXME: there is still a race here */
1113 RtlEnterCriticalSection( &loader_section );
1115 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1117 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1118 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1120 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1121 InInitializationOrderModuleList);
1122 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1123 continue;
1124 if ( mod->Flags & LDR_NO_DLL_CALLS )
1125 continue;
1127 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1128 DLL_THREAD_ATTACH, lpReserved );
1131 done:
1132 RtlLeaveCriticalSection( &loader_section );
1133 return status;
1136 /******************************************************************
1137 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1140 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1142 WINE_MODREF *wm;
1143 NTSTATUS ret = STATUS_SUCCESS;
1145 RtlEnterCriticalSection( &loader_section );
1147 wm = get_modref( hModule );
1148 if (!wm || wm->ldr.TlsIndex != -1)
1149 ret = STATUS_DLL_NOT_FOUND;
1150 else
1151 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1153 RtlLeaveCriticalSection( &loader_section );
1155 return ret;
1158 /******************************************************************
1159 * LdrFindEntryForAddress (NTDLL.@)
1161 * The loader_section must be locked while calling this function
1163 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1165 PLIST_ENTRY mark, entry;
1166 PLDR_MODULE mod;
1168 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1169 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1171 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1172 if ((const void *)mod->BaseAddress <= addr &&
1173 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1175 *pmod = mod;
1176 return STATUS_SUCCESS;
1178 if ((const void *)mod->BaseAddress > addr) break;
1180 return STATUS_NO_MORE_ENTRIES;
1183 /******************************************************************
1184 * LdrLockLoaderLock (NTDLL.@)
1186 * Note: flags are not implemented.
1187 * Flag 0x01 is used to raise exceptions on errors.
1188 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1190 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1192 if (flags) FIXME( "flags %x not supported\n", flags );
1194 if (result) *result = 1;
1195 if (!magic) return STATUS_INVALID_PARAMETER_3;
1196 RtlEnterCriticalSection( &loader_section );
1197 *magic = GetCurrentThreadId();
1198 return STATUS_SUCCESS;
1202 /******************************************************************
1203 * LdrUnlockLoaderUnlock (NTDLL.@)
1205 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1207 if (magic)
1209 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1210 RtlLeaveCriticalSection( &loader_section );
1212 return STATUS_SUCCESS;
1216 /******************************************************************
1217 * LdrGetProcedureAddress (NTDLL.@)
1219 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1220 ULONG ord, PVOID *address)
1222 IMAGE_EXPORT_DIRECTORY *exports;
1223 DWORD exp_size;
1224 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1226 RtlEnterCriticalSection( &loader_section );
1228 /* check if the module itself is invalid to return the proper error */
1229 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1230 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1231 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1233 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1234 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1235 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1236 if (proc)
1238 *address = proc;
1239 ret = STATUS_SUCCESS;
1243 RtlLeaveCriticalSection( &loader_section );
1244 return ret;
1248 /***********************************************************************
1249 * is_fake_dll
1251 * Check if a loaded native dll is a Wine fake dll.
1253 static BOOL is_fake_dll( HANDLE handle )
1255 static const char fakedll_signature[] = "Wine placeholder DLL";
1256 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1257 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1258 IO_STATUS_BLOCK io;
1259 LARGE_INTEGER offset;
1261 offset.QuadPart = 0;
1262 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1263 if (io.Information < sizeof(buffer)) return FALSE;
1264 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1265 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1266 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1267 return FALSE;
1271 /***********************************************************************
1272 * get_builtin_fullname
1274 * Build the full pathname for a builtin dll.
1276 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1278 static const WCHAR soW[] = {'.','s','o',0};
1279 WCHAR *p, *fullname;
1280 size_t i, len = strlen(filename);
1282 /* check if path can correspond to the dll we have */
1283 if (path && (p = strrchrW( path, '\\' )))
1285 p++;
1286 for (i = 0; i < len; i++)
1287 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1288 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1290 /* the filename matches, use path as the full path */
1291 len += p - path;
1292 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1294 memcpy( fullname, path, len * sizeof(WCHAR) );
1295 fullname[len] = 0;
1297 return fullname;
1301 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1302 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1304 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1305 p = fullname + system_dir.Length / sizeof(WCHAR);
1306 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1307 ascii_to_unicode( p, filename, len + 1 );
1309 return fullname;
1313 /***********************************************************************
1314 * load_builtin_callback
1316 * Load a library in memory; callback function for wine_dll_register
1318 static void load_builtin_callback( void *module, const char *filename )
1320 static const WCHAR emptyW[1];
1321 void *addr;
1322 IMAGE_NT_HEADERS *nt;
1323 WINE_MODREF *wm;
1324 WCHAR *fullname;
1325 const WCHAR *load_path;
1326 SIZE_T size;
1328 if (!module)
1330 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1331 return;
1333 if (!(nt = RtlImageNtHeader( module )))
1335 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1336 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1337 return;
1339 addr = module;
1340 size = nt->OptionalHeader.SizeOfImage;
1341 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1342 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1343 /* create the MODREF */
1345 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1347 ERR( "can't load %s\n", filename );
1348 builtin_load_info->status = STATUS_NO_MEMORY;
1349 return;
1352 wm = alloc_module( module, fullname );
1353 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1354 if (!wm)
1356 ERR( "can't load %s\n", filename );
1357 builtin_load_info->status = STATUS_NO_MEMORY;
1358 return;
1360 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1362 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1363 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1365 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1367 else
1369 /* fixup imports */
1371 load_path = builtin_load_info->load_path;
1372 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1373 if (!load_path) load_path = emptyW;
1374 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1376 /* the module has only be inserted in the load & memory order lists */
1377 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1378 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1379 /* FIXME: free the modref */
1380 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1381 return;
1385 builtin_load_info->wm = wm;
1386 TRACE( "loaded %s %p %p\n", filename, wm, module );
1388 /* send the DLL load event */
1390 SERVER_START_REQ( load_dll )
1392 req->handle = 0;
1393 req->base = module;
1394 req->size = nt->OptionalHeader.SizeOfImage;
1395 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1396 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1397 req->name = &wm->ldr.FullDllName.Buffer;
1398 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1399 wine_server_call( req );
1401 SERVER_END_REQ;
1403 /* setup relay debugging entry points */
1404 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1408 /******************************************************************************
1409 * load_native_dll (internal)
1411 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1412 DWORD flags, WINE_MODREF** pwm )
1414 void *module;
1415 HANDLE mapping;
1416 OBJECT_ATTRIBUTES attr;
1417 LARGE_INTEGER size;
1418 IMAGE_NT_HEADERS *nt;
1419 SIZE_T len = 0;
1420 WINE_MODREF *wm;
1421 NTSTATUS status;
1423 TRACE("Trying native dll %s\n", debugstr_w(name));
1425 attr.Length = sizeof(attr);
1426 attr.RootDirectory = 0;
1427 attr.ObjectName = NULL;
1428 attr.Attributes = 0;
1429 attr.SecurityDescriptor = NULL;
1430 attr.SecurityQualityOfService = NULL;
1431 size.QuadPart = 0;
1433 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1434 &attr, &size, 0, SEC_IMAGE, file );
1435 if (status != STATUS_SUCCESS) return status;
1437 module = NULL;
1438 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1439 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1440 NtClose( mapping );
1441 if (status != STATUS_SUCCESS) return status;
1443 /* create the MODREF */
1445 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1447 /* fixup imports */
1449 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1451 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1453 /* the module has only be inserted in the load & memory order lists */
1454 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1455 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1457 /* FIXME: there are several more dangling references
1458 * left. Including dlls loaded by this dll before the
1459 * failed one. Unrolling is rather difficult with the
1460 * current structure and we can leave them lying
1461 * around with no problems, so we don't care.
1462 * As these might reference our wm, we don't free it.
1464 return status;
1468 /* send DLL load event */
1470 nt = RtlImageNtHeader( module );
1472 SERVER_START_REQ( load_dll )
1474 req->handle = file;
1475 req->base = module;
1476 req->size = nt->OptionalHeader.SizeOfImage;
1477 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1478 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1479 req->name = &wm->ldr.FullDllName.Buffer;
1480 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1481 wine_server_call( req );
1483 SERVER_END_REQ;
1485 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1487 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1489 wm->ldr.LoadCount = 1;
1490 *pwm = wm;
1491 return STATUS_SUCCESS;
1495 /***********************************************************************
1496 * load_builtin_dll
1498 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1499 DWORD flags, WINE_MODREF** pwm )
1501 char error[256], dllname[MAX_PATH];
1502 const WCHAR *name, *p;
1503 DWORD len, i;
1504 void *handle = NULL;
1505 struct builtin_load_info info, *prev_info;
1507 /* Fix the name in case we have a full path and extension */
1508 name = path;
1509 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1510 if ((p = strrchrW( name, '/' ))) name = p + 1;
1512 /* load_library will modify info.status. Note also that load_library can be
1513 * called several times, if the .so file we're loading has dependencies.
1514 * info.status will gather all the errors we may get while loading all these
1515 * libraries
1517 info.load_path = load_path;
1518 info.filename = NULL;
1519 info.status = STATUS_SUCCESS;
1520 info.wm = NULL;
1522 if (file) /* we have a real file, try to load it */
1524 UNICODE_STRING nt_name;
1525 ANSI_STRING unix_name;
1527 TRACE("Trying built-in %s\n", debugstr_w(path));
1529 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1530 return STATUS_DLL_NOT_FOUND;
1532 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1534 RtlFreeUnicodeString( &nt_name );
1535 return STATUS_DLL_NOT_FOUND;
1537 prev_info = builtin_load_info;
1538 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1539 builtin_load_info = &info;
1540 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1541 builtin_load_info = prev_info;
1542 RtlFreeUnicodeString( &nt_name );
1543 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1544 if (!handle)
1546 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1547 return STATUS_INVALID_IMAGE_FORMAT;
1550 else
1552 int file_exists;
1554 TRACE("Trying built-in %s\n", debugstr_w(name));
1556 /* we don't want to depend on the current codepage here */
1557 len = strlenW( name ) + 1;
1558 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1559 for (i = 0; i < len; i++)
1561 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1562 dllname[i] = (char)name[i];
1563 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1566 prev_info = builtin_load_info;
1567 builtin_load_info = &info;
1568 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1569 builtin_load_info = prev_info;
1570 if (!handle)
1572 if (!file_exists)
1574 /* The file does not exist -> WARN() */
1575 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1576 return STATUS_DLL_NOT_FOUND;
1578 /* ERR() for all other errors (missing functions, ...) */
1579 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1580 return STATUS_PROCEDURE_NOT_FOUND;
1584 if (info.status != STATUS_SUCCESS)
1586 wine_dll_unload( handle );
1587 return info.status;
1590 if (!info.wm)
1592 PLIST_ENTRY mark, entry;
1594 /* The constructor wasn't called, this means the .so is already
1595 * loaded under a different name. Try to find the wm for it. */
1597 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1598 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1600 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1601 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1603 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1604 TRACE( "Found %s at %p for builtin %s\n",
1605 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1606 break;
1609 wine_dll_unload( handle ); /* release the libdl refcount */
1610 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1611 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1613 else
1615 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1616 info.wm->ldr.LoadCount = 1;
1617 info.wm->ldr.SectionHandle = handle;
1620 *pwm = info.wm;
1621 return STATUS_SUCCESS;
1625 /***********************************************************************
1626 * find_actctx_dll
1628 * Find the full path (if any) of the dll from the activation context.
1630 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1632 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1633 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1635 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1636 ACTCTX_SECTION_KEYED_DATA data;
1637 UNICODE_STRING nameW;
1638 NTSTATUS status;
1639 SIZE_T needed, size = 1024;
1640 WCHAR *p;
1642 RtlInitUnicodeString( &nameW, libname );
1643 data.cbSize = sizeof(data);
1644 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1645 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1646 &nameW, &data );
1647 if (status != STATUS_SUCCESS) return status;
1649 for (;;)
1651 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1653 status = STATUS_NO_MEMORY;
1654 goto done;
1656 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1657 AssemblyDetailedInformationInActivationContext,
1658 info, size, &needed );
1659 if (status == STATUS_SUCCESS) break;
1660 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1661 RtlFreeHeap( GetProcessHeap(), 0, info );
1662 size = needed;
1663 /* restart with larger buffer */
1666 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1668 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1670 p++;
1671 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1673 /* manifest name does not match directory name, so it's not a global
1674 * windows/winsxs manifest; use the manifest directory name instead */
1675 dirlen = p - info->lpAssemblyManifestPath;
1676 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1677 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1679 status = STATUS_NO_MEMORY;
1680 goto done;
1682 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1683 p += dirlen;
1684 strcpyW( p, libname );
1685 goto done;
1689 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1690 nameW.Length + 2*sizeof(WCHAR));
1692 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1694 status = STATUS_NO_MEMORY;
1695 goto done;
1697 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1698 p += windows_dir.Length / sizeof(WCHAR);
1699 memcpy( p, winsxsW, sizeof(winsxsW) );
1700 p += sizeof(winsxsW) / sizeof(WCHAR);
1701 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1702 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1703 *p++ = '\\';
1704 strcpyW( p, libname );
1705 done:
1706 RtlFreeHeap( GetProcessHeap(), 0, info );
1707 RtlReleaseActivationContext( data.hActCtx );
1708 return status;
1712 /***********************************************************************
1713 * find_dll_file
1715 * Find the file (or already loaded module) for a given dll name.
1717 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1718 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1720 OBJECT_ATTRIBUTES attr;
1721 IO_STATUS_BLOCK io;
1722 UNICODE_STRING nt_name;
1723 WCHAR *file_part, *ext, *dllname;
1724 ULONG len;
1726 /* first append .dll if needed */
1728 dllname = NULL;
1729 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1731 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1732 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1733 return STATUS_NO_MEMORY;
1734 strcpyW( dllname, libname );
1735 strcatW( dllname, dllW );
1736 libname = dllname;
1739 nt_name.Buffer = NULL;
1741 if (!contains_path( libname ))
1743 NTSTATUS status;
1744 WCHAR *fullname = NULL;
1746 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1748 status = find_actctx_dll( libname, &fullname );
1749 if (status == STATUS_SUCCESS)
1751 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1752 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1753 libname = dllname = fullname;
1755 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1757 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1758 return status;
1762 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1764 /* we need to search for it */
1765 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1766 if (len)
1768 if (len >= *size) goto overflow;
1769 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1771 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1773 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1774 return STATUS_NO_MEMORY;
1776 attr.Length = sizeof(attr);
1777 attr.RootDirectory = 0;
1778 attr.Attributes = OBJ_CASE_INSENSITIVE;
1779 attr.ObjectName = &nt_name;
1780 attr.SecurityDescriptor = NULL;
1781 attr.SecurityQualityOfService = NULL;
1782 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1783 goto found;
1786 /* not found */
1788 if (!contains_path( libname ))
1790 /* if libname doesn't contain a path at all, we simply return the name as is,
1791 * to be loaded as builtin */
1792 len = strlenW(libname) * sizeof(WCHAR);
1793 if (len >= *size) goto overflow;
1794 strcpyW( filename, libname );
1795 goto found;
1799 /* absolute path name, or relative path name but not found above */
1801 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1803 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1804 return STATUS_NO_MEMORY;
1806 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1807 if (len >= *size) goto overflow;
1808 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1809 if (!(*pwm = find_fullname_module( filename )) && handle)
1811 attr.Length = sizeof(attr);
1812 attr.RootDirectory = 0;
1813 attr.Attributes = OBJ_CASE_INSENSITIVE;
1814 attr.ObjectName = &nt_name;
1815 attr.SecurityDescriptor = NULL;
1816 attr.SecurityQualityOfService = NULL;
1817 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1819 found:
1820 RtlFreeUnicodeString( &nt_name );
1821 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1822 return STATUS_SUCCESS;
1824 overflow:
1825 RtlFreeUnicodeString( &nt_name );
1826 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1827 *size = len + sizeof(WCHAR);
1828 return STATUS_BUFFER_TOO_SMALL;
1832 /***********************************************************************
1833 * load_dll (internal)
1835 * Load a PE style module according to the load order.
1836 * The loader_section must be locked while calling this function.
1838 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1840 enum loadorder loadorder;
1841 WCHAR buffer[32];
1842 WCHAR *filename;
1843 ULONG size;
1844 WINE_MODREF *main_exe;
1845 HANDLE handle = 0;
1846 NTSTATUS nts;
1848 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1850 *pwm = NULL;
1851 filename = buffer;
1852 size = sizeof(buffer);
1853 for (;;)
1855 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1856 if (nts == STATUS_SUCCESS) break;
1857 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1858 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1859 /* grow the buffer and retry */
1860 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1863 if (*pwm) /* found already loaded module */
1865 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1867 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1869 TRACE("Found %s for %s at %p, count=%d\n",
1870 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1871 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1872 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1873 return STATUS_SUCCESS;
1876 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1877 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1879 if (handle && is_fake_dll( handle ))
1881 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1882 NtClose( handle );
1883 handle = 0;
1886 switch(loadorder)
1888 case LO_INVALID:
1889 nts = STATUS_NO_MEMORY;
1890 break;
1891 case LO_DISABLED:
1892 nts = STATUS_DLL_NOT_FOUND;
1893 break;
1894 case LO_NATIVE:
1895 case LO_NATIVE_BUILTIN:
1896 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1897 else
1899 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1900 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1901 /* not in PE format, maybe it's a builtin */
1902 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1904 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1905 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1906 break;
1907 case LO_BUILTIN:
1908 case LO_BUILTIN_NATIVE:
1909 case LO_DEFAULT: /* default is builtin,native */
1910 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1911 if (!handle) break; /* nothing else we can try */
1912 /* file is not a builtin library, try without using the specified file */
1913 if (nts != STATUS_SUCCESS)
1914 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1915 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1916 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1918 /* stub-only dll, try native */
1919 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1920 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1921 nts = STATUS_DLL_NOT_FOUND;
1923 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1924 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1925 break;
1928 if (nts == STATUS_SUCCESS)
1930 /* Initialize DLL just loaded */
1931 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1932 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1933 (*pwm)->ldr.BaseAddress);
1934 if (handle) NtClose( handle );
1935 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1936 return nts;
1939 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1940 if (handle) NtClose( handle );
1941 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1942 return nts;
1945 /******************************************************************
1946 * LdrLoadDll (NTDLL.@)
1948 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1949 const UNICODE_STRING *libname, HMODULE* hModule)
1951 WINE_MODREF *wm;
1952 NTSTATUS nts;
1954 RtlEnterCriticalSection( &loader_section );
1956 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1957 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1959 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1961 nts = process_attach( wm, NULL );
1962 if (nts != STATUS_SUCCESS)
1964 LdrUnloadDll(wm->ldr.BaseAddress);
1965 wm = NULL;
1968 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1970 RtlLeaveCriticalSection( &loader_section );
1971 return nts;
1975 /******************************************************************
1976 * LdrGetDllHandle (NTDLL.@)
1978 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1980 NTSTATUS status;
1981 WCHAR buffer[128];
1982 WCHAR *filename;
1983 ULONG size;
1984 WINE_MODREF *wm;
1986 RtlEnterCriticalSection( &loader_section );
1988 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1990 filename = buffer;
1991 size = sizeof(buffer);
1992 for (;;)
1994 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1995 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1996 if (status != STATUS_BUFFER_TOO_SMALL) break;
1997 /* grow the buffer and retry */
1998 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2000 status = STATUS_NO_MEMORY;
2001 break;
2005 if (status == STATUS_SUCCESS)
2007 if (wm) *base = wm->ldr.BaseAddress;
2008 else status = STATUS_DLL_NOT_FOUND;
2011 RtlLeaveCriticalSection( &loader_section );
2012 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2013 return status;
2017 /******************************************************************
2018 * LdrAddRefDll (NTDLL.@)
2020 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2022 NTSTATUS ret = STATUS_SUCCESS;
2023 WINE_MODREF *wm;
2025 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2027 RtlEnterCriticalSection( &loader_section );
2029 if ((wm = get_modref( module )))
2031 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2032 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2034 else ret = STATUS_INVALID_PARAMETER;
2036 RtlLeaveCriticalSection( &loader_section );
2037 return ret;
2041 /******************************************************************
2042 * LdrQueryProcessModuleInformation
2045 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2046 ULONG buf_size, ULONG* req_size)
2048 SYSTEM_MODULE* sm = &smi->Modules[0];
2049 ULONG size = sizeof(ULONG);
2050 NTSTATUS nts = STATUS_SUCCESS;
2051 ANSI_STRING str;
2052 char* ptr;
2053 PLIST_ENTRY mark, entry;
2054 PLDR_MODULE mod;
2055 WORD id = 0;
2057 smi->ModulesCount = 0;
2059 RtlEnterCriticalSection( &loader_section );
2060 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2061 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2063 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2064 size += sizeof(*sm);
2065 if (size <= buf_size)
2067 sm->Reserved1 = 0; /* FIXME */
2068 sm->Reserved2 = 0; /* FIXME */
2069 sm->ImageBaseAddress = mod->BaseAddress;
2070 sm->ImageSize = mod->SizeOfImage;
2071 sm->Flags = mod->Flags;
2072 sm->Id = id++;
2073 sm->Rank = 0; /* FIXME */
2074 sm->Unknown = 0; /* FIXME */
2075 str.Length = 0;
2076 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2077 str.Buffer = (char*)sm->Name;
2078 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2079 ptr = strrchr(str.Buffer, '\\');
2080 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2082 smi->ModulesCount++;
2083 sm++;
2085 else nts = STATUS_INFO_LENGTH_MISMATCH;
2087 RtlLeaveCriticalSection( &loader_section );
2089 if (req_size) *req_size = size;
2091 return nts;
2095 /******************************************************************
2096 * RtlDllShutdownInProgress (NTDLL.@)
2098 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2100 return process_detaching;
2104 /******************************************************************
2105 * LdrShutdownProcess (NTDLL.@)
2108 void WINAPI LdrShutdownProcess(void)
2110 TRACE("()\n");
2111 process_detach( TRUE, (LPVOID)1 );
2114 /******************************************************************
2115 * LdrShutdownThread (NTDLL.@)
2118 void WINAPI LdrShutdownThread(void)
2120 PLIST_ENTRY mark, entry;
2121 PLDR_MODULE mod;
2123 TRACE("()\n");
2125 /* don't do any detach calls if process is exiting */
2126 if (process_detaching) return;
2127 /* FIXME: there is still a race here */
2129 RtlEnterCriticalSection( &loader_section );
2131 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2132 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2134 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2135 InInitializationOrderModuleList);
2136 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2137 continue;
2138 if ( mod->Flags & LDR_NO_DLL_CALLS )
2139 continue;
2141 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2142 DLL_THREAD_DETACH, NULL );
2145 RtlLeaveCriticalSection( &loader_section );
2146 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2150 /***********************************************************************
2151 * free_modref
2154 static void free_modref( WINE_MODREF *wm )
2156 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2157 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2158 if (wm->ldr.InInitializationOrderModuleList.Flink)
2159 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2161 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2162 if (!TRACE_ON(module))
2163 TRACE_(loaddll)("Unloaded module %s : %s\n",
2164 debugstr_w(wm->ldr.FullDllName.Buffer),
2165 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2167 SERVER_START_REQ( unload_dll )
2169 req->base = wm->ldr.BaseAddress;
2170 wine_server_call( req );
2172 SERVER_END_REQ;
2174 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2175 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2176 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2177 if (cached_modref == wm) cached_modref = NULL;
2178 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2179 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2180 RtlFreeHeap( GetProcessHeap(), 0, wm );
2183 /***********************************************************************
2184 * MODULE_FlushModrefs
2186 * Remove all unused modrefs and call the internal unloading routines
2187 * for the library type.
2189 * The loader_section must be locked while calling this function.
2191 static void MODULE_FlushModrefs(void)
2193 PLIST_ENTRY mark, entry, prev;
2194 PLDR_MODULE mod;
2195 WINE_MODREF*wm;
2197 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2198 for (entry = mark->Blink; entry != mark; entry = prev)
2200 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2201 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2202 prev = entry->Blink;
2203 if (!mod->LoadCount) free_modref( wm );
2206 /* check load order list too for modules that haven't been initialized yet */
2207 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2208 for (entry = mark->Blink; entry != mark; entry = prev)
2210 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2211 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2212 prev = entry->Blink;
2213 if (!mod->LoadCount) free_modref( wm );
2217 /***********************************************************************
2218 * MODULE_DecRefCount
2220 * The loader_section must be locked while calling this function.
2222 static void MODULE_DecRefCount( WINE_MODREF *wm )
2224 int i;
2226 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2227 return;
2229 if ( wm->ldr.LoadCount <= 0 )
2230 return;
2232 --wm->ldr.LoadCount;
2233 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2235 if ( wm->ldr.LoadCount == 0 )
2237 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2239 for ( i = 0; i < wm->nDeps; i++ )
2240 if ( wm->deps[i] )
2241 MODULE_DecRefCount( wm->deps[i] );
2243 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2247 /******************************************************************
2248 * LdrUnloadDll (NTDLL.@)
2252 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2254 NTSTATUS retv = STATUS_SUCCESS;
2256 TRACE("(%p)\n", hModule);
2258 RtlEnterCriticalSection( &loader_section );
2260 /* if we're stopping the whole process (and forcing the removal of all
2261 * DLLs) the library will be freed anyway
2263 if (!process_detaching)
2265 WINE_MODREF *wm;
2267 free_lib_count++;
2268 if ((wm = get_modref( hModule )) != NULL)
2270 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2272 /* Recursively decrement reference counts */
2273 MODULE_DecRefCount( wm );
2275 /* Call process detach notifications */
2276 if ( free_lib_count <= 1 )
2278 process_detach( FALSE, NULL );
2279 MODULE_FlushModrefs();
2282 TRACE("END\n");
2284 else
2285 retv = STATUS_DLL_NOT_FOUND;
2287 free_lib_count--;
2290 RtlLeaveCriticalSection( &loader_section );
2292 return retv;
2295 /***********************************************************************
2296 * RtlImageNtHeader (NTDLL.@)
2298 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2300 IMAGE_NT_HEADERS *ret;
2302 __TRY
2304 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2306 ret = NULL;
2307 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2309 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2310 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2313 __EXCEPT_PAGE_FAULT
2315 return NULL;
2317 __ENDTRY
2318 return ret;
2322 /***********************************************************************
2323 * alloc_process_stack
2325 * Allocate the stack of new process.
2327 static NTSTATUS alloc_process_stack( IMAGE_NT_HEADERS *nt )
2329 NTSTATUS status;
2330 void *base = NULL;
2331 SIZE_T stack_size, page_size = getpagesize();
2333 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
2334 stack_size += page_size; /* for the guard page */
2335 stack_size = (stack_size + 0xffff) & ~0xffff; /* round to 64K boundary */
2336 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
2338 if ((status = NtAllocateVirtualMemory( GetCurrentProcess(), &base, 16, &stack_size,
2339 MEM_COMMIT, PAGE_READWRITE )))
2340 return status;
2342 /* note: limit is lower than base since the stack grows down */
2343 NtCurrentTeb()->DeallocationStack = base;
2344 NtCurrentTeb()->Tib.StackBase = (char *)base + stack_size;
2345 NtCurrentTeb()->Tib.StackLimit = (char *)base + page_size;
2347 #ifdef VALGRIND_STACK_REGISTER
2348 /* no need to de-register the stack as it's the one of the main thread */
2349 VALGRIND_STACK_REGISTER(NtCurrentTeb()->Tib.StackLimit, NtCurrentTeb()->Tib.StackBase);
2350 #endif
2352 /* setup guard page */
2353 NtProtectVirtualMemory( GetCurrentProcess(), &base, &page_size, PAGE_NOACCESS, NULL );
2354 return STATUS_SUCCESS;
2358 /***********************************************************************
2359 * attach_process_dlls
2361 * Initial attach to all the dlls loaded by the process.
2363 static NTSTATUS attach_process_dlls( void *wm )
2365 NTSTATUS status;
2367 RtlEnterCriticalSection( &loader_section );
2368 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2370 if (last_failed_modref)
2371 ERR( "%s failed to initialize, aborting\n",
2372 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2373 return status;
2375 attach_implicitly_loaded_dlls( (LPVOID)1 );
2376 RtlLeaveCriticalSection( &loader_section );
2377 return status;
2381 /******************************************************************
2382 * LdrInitializeThunk (NTDLL.@)
2385 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2387 NTSTATUS status;
2388 WINE_MODREF *wm;
2389 LPCWSTR load_path;
2390 PEB *peb = NtCurrentTeb()->Peb;
2391 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2393 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2395 /* allocate the modref for the main exe (if not already done) */
2396 wm = get_modref( peb->ImageBaseAddress );
2397 assert( wm );
2398 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2400 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2401 exit(1);
2404 peb->LoaderLock = &loader_section;
2405 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2406 version_init( wm->ldr.FullDllName.Buffer );
2408 /* the main exe needs to be the first in the load order list */
2409 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2410 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2412 if ((status = alloc_process_stack( nt )) != STATUS_SUCCESS) goto error;
2413 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2415 actctx_init();
2416 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2417 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2418 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2419 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2421 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2423 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2424 if (status != STATUS_SUCCESS) goto error;
2426 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2427 return;
2429 error:
2430 ERR( "Main exe initialization for %s failed, status %x\n",
2431 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2432 NtTerminateProcess( GetCurrentProcess(), status );
2436 /***********************************************************************
2437 * RtlImageDirectoryEntryToData (NTDLL.@)
2439 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2441 const IMAGE_NT_HEADERS *nt;
2442 DWORD addr;
2444 if ((ULONG_PTR)module & 1) /* mapped as data file */
2446 module = (HMODULE)((ULONG_PTR)module & ~1);
2447 image = FALSE;
2449 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2450 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2451 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2452 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2453 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2455 /* not mapped as image, need to find the section containing the virtual address */
2456 return RtlImageRvaToVa( nt, module, addr, NULL );
2460 /***********************************************************************
2461 * RtlImageRvaToSection (NTDLL.@)
2463 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2464 HMODULE module, DWORD rva )
2466 int i;
2467 const IMAGE_SECTION_HEADER *sec;
2469 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2470 nt->FileHeader.SizeOfOptionalHeader);
2471 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2473 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2474 return (PIMAGE_SECTION_HEADER)sec;
2476 return NULL;
2480 /***********************************************************************
2481 * RtlImageRvaToVa (NTDLL.@)
2483 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2484 DWORD rva, IMAGE_SECTION_HEADER **section )
2486 IMAGE_SECTION_HEADER *sec;
2488 if (section && *section) /* try this section first */
2490 sec = *section;
2491 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2492 goto found;
2494 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2495 found:
2496 if (section) *section = sec;
2497 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2501 /***********************************************************************
2502 * RtlPcToFileHeader (NTDLL.@)
2504 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2506 LDR_MODULE *module;
2507 PVOID ret = NULL;
2509 RtlEnterCriticalSection( &loader_section );
2510 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2511 RtlLeaveCriticalSection( &loader_section );
2512 *address = ret;
2513 return ret;
2517 /***********************************************************************
2518 * NtLoadDriver (NTDLL.@)
2519 * ZwLoadDriver (NTDLL.@)
2521 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2523 FIXME("(%p), stub!\n",DriverServiceName);
2524 return STATUS_NOT_IMPLEMENTED;
2528 /***********************************************************************
2529 * NtUnloadDriver (NTDLL.@)
2530 * ZwUnloadDriver (NTDLL.@)
2532 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2534 FIXME("(%p), stub!\n",DriverServiceName);
2535 return STATUS_NOT_IMPLEMENTED;
2539 /******************************************************************
2540 * DllMain (NTDLL.@)
2542 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2544 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2545 return TRUE;
2549 /******************************************************************
2550 * __wine_init_windows_dir (NTDLL.@)
2552 * Windows and system dir initialization once kernel32 has been loaded.
2554 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2556 PLIST_ENTRY mark, entry;
2557 LPWSTR buffer, p;
2559 RtlCreateUnicodeString( &windows_dir, windir );
2560 RtlCreateUnicodeString( &system_dir, sysdir );
2561 strcpyW( user_shared_data->NtSystemRoot, windir );
2563 /* prepend the system dir to the name of the already created modules */
2564 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2565 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2567 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2569 assert( mod->Flags & LDR_WINE_INTERNAL );
2571 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2572 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2573 if (!buffer) continue;
2574 strcpyW( buffer, system_dir.Buffer );
2575 p = buffer + strlenW( buffer );
2576 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2577 strcpyW( p, mod->FullDllName.Buffer );
2578 RtlInitUnicodeString( &mod->FullDllName, buffer );
2579 RtlInitUnicodeString( &mod->BaseDllName, p );
2584 /***********************************************************************
2585 * __wine_process_init
2587 void __wine_process_init(void)
2589 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2591 WINE_MODREF *wm;
2592 NTSTATUS status;
2593 ANSI_STRING func_name;
2594 void (* DECLSPEC_NORETURN init_func)(void);
2595 extern mode_t FILE_umask;
2597 main_exe_file = thread_init();
2599 /* retrieve current umask */
2600 FILE_umask = umask(0777);
2601 umask( FILE_umask );
2603 /* setup the load callback and create ntdll modref */
2604 wine_dll_set_callback( load_builtin_callback );
2606 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2608 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2609 exit(1);
2611 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2612 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2614 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2615 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2616 0, (void **)&init_func )) != STATUS_SUCCESS)
2618 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2619 exit(1);
2621 init_func();