wined3d: Report post pixelshader blending on WINED3DFMT_A16B16G16R16F.
[wine/gsoc_dplay.git] / dlls / ntdll / loader.c
blobc05e01fcf22eba925bb7ff8241f3df982b621403
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 * alloc_module
687 * Allocate a WINE_MODREF structure and add it to the process list
688 * The loader_section must be locked while calling this function.
690 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
692 WINE_MODREF *wm;
693 const WCHAR *p;
694 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
695 PLIST_ENTRY entry, mark;
697 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
699 wm->nDeps = 0;
700 wm->deps = NULL;
702 wm->ldr.BaseAddress = hModule;
703 wm->ldr.EntryPoint = NULL;
704 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
705 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
706 wm->ldr.LoadCount = 1;
707 wm->ldr.TlsIndex = -1;
708 wm->ldr.SectionHandle = NULL;
709 wm->ldr.CheckSum = 0;
710 wm->ldr.TimeDateStamp = 0;
711 wm->ldr.ActivationContext = 0;
713 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
714 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
715 else p = wm->ldr.FullDllName.Buffer;
716 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
718 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
720 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
721 if (nt->OptionalHeader.AddressOfEntryPoint)
722 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
725 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
726 &wm->ldr.InLoadOrderModuleList);
728 /* insert module in MemoryList, sorted in increasing base addresses */
729 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
730 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
732 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
733 break;
735 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
736 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
737 wm->ldr.InMemoryOrderModuleList.Flink = entry;
738 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
740 /* wait until init is called for inserting into this list */
741 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
742 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
744 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
746 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
747 VIRTUAL_SetForceExec( TRUE );
749 return wm;
753 /*************************************************************************
754 * alloc_process_tls
756 * Allocate the process-wide structure for module TLS storage.
758 static NTSTATUS alloc_process_tls(void)
760 PLIST_ENTRY mark, entry;
761 PLDR_MODULE mod;
762 const IMAGE_TLS_DIRECTORY *dir;
763 ULONG size, i;
765 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
766 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
768 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
769 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
770 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
771 continue;
772 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
773 if (!size) continue;
774 tls_total_size += size;
775 tls_module_count++;
777 if (!tls_module_count) return STATUS_SUCCESS;
779 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
781 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
782 if (!tls_dirs) return STATUS_NO_MEMORY;
784 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
786 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
787 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
788 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
789 continue;
790 tls_dirs[i] = dir;
791 *(DWORD *)dir->AddressOfIndex = i;
792 mod->TlsIndex = i;
793 mod->LoadCount = -1; /* can't unload it */
794 i++;
796 return STATUS_SUCCESS;
800 /*************************************************************************
801 * alloc_thread_tls
803 * Allocate the per-thread structure for module TLS storage.
805 static NTSTATUS alloc_thread_tls(void)
807 void **pointers;
808 char *data;
809 UINT i;
811 if (!tls_module_count) return STATUS_SUCCESS;
813 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
814 tls_module_count * sizeof(*pointers) )))
815 return STATUS_NO_MEMORY;
817 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
819 RtlFreeHeap( GetProcessHeap(), 0, pointers );
820 return STATUS_NO_MEMORY;
823 for (i = 0; i < tls_module_count; i++)
825 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
826 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
828 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
829 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
830 (void *)dir->StartAddressOfRawData, data );
832 pointers[i] = data;
833 memcpy( data, (void *)dir->StartAddressOfRawData, size );
834 data += size;
835 memset( data, 0, dir->SizeOfZeroFill );
836 data += dir->SizeOfZeroFill;
838 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
839 return STATUS_SUCCESS;
843 /*************************************************************************
844 * call_tls_callbacks
846 static void call_tls_callbacks( HMODULE module, UINT reason )
848 const IMAGE_TLS_DIRECTORY *dir;
849 const PIMAGE_TLS_CALLBACK *callback;
850 ULONG dirsize;
852 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
853 if (!dir || !dir->AddressOfCallBacks) return;
855 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
857 if (TRACE_ON(relay))
858 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
859 GetCurrentThreadId(), *callback, module, reason_names[reason] );
860 __TRY
862 (*callback)( module, reason, NULL );
864 __EXCEPT_ALL
866 if (TRACE_ON(relay))
867 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
868 GetCurrentThreadId(), callback, module, reason_names[reason] );
869 return;
871 __ENDTRY
872 if (TRACE_ON(relay))
873 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
874 GetCurrentThreadId(), *callback, module, reason_names[reason] );
879 /*************************************************************************
880 * MODULE_InitDLL
882 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
884 WCHAR mod_name[32];
885 NTSTATUS status = STATUS_SUCCESS;
886 DLLENTRYPROC entry = wm->ldr.EntryPoint;
887 void *module = wm->ldr.BaseAddress;
888 BOOL retv = TRUE;
890 /* Skip calls for modules loaded with special load flags */
892 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
893 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
894 if (!entry) return STATUS_SUCCESS;
896 if (TRACE_ON(relay))
898 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
899 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
900 mod_name[len / sizeof(WCHAR)] = 0;
901 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
902 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
903 reason_names[reason], lpReserved );
905 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
906 reason_names[reason], lpReserved );
908 __TRY
910 retv = call_dll_entry_point( entry, module, reason, lpReserved );
911 if (!retv)
912 status = STATUS_DLL_INIT_FAILED;
914 __EXCEPT_ALL
916 if (TRACE_ON(relay))
917 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
918 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
919 status = GetExceptionCode();
921 __ENDTRY
923 /* The state of the module list may have changed due to the call
924 to the dll. We cannot assume that this module has not been
925 deleted. */
926 if (TRACE_ON(relay))
927 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
928 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
929 reason_names[reason], lpReserved, retv );
930 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
932 return status;
936 /*************************************************************************
937 * process_attach
939 * Send the process attach notification to all DLLs the given module
940 * depends on (recursively). This is somewhat complicated due to the fact that
942 * - we have to respect the module dependencies, i.e. modules implicitly
943 * referenced by another module have to be initialized before the module
944 * itself can be initialized
946 * - the initialization routine of a DLL can itself call LoadLibrary,
947 * thereby introducing a whole new set of dependencies (even involving
948 * the 'old' modules) at any time during the whole process
950 * (Note that this routine can be recursively entered not only directly
951 * from itself, but also via LoadLibrary from one of the called initialization
952 * routines.)
954 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
955 * the process *detach* notifications to be sent in the correct order.
956 * This must not only take into account module dependencies, but also
957 * 'hidden' dependencies created by modules calling LoadLibrary in their
958 * attach notification routine.
960 * The strategy is rather simple: we move a WINE_MODREF to the head of the
961 * list after the attach notification has returned. This implies that the
962 * detach notifications are called in the reverse of the sequence the attach
963 * notifications *returned*.
965 * The loader_section must be locked while calling this function.
967 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
969 NTSTATUS status = STATUS_SUCCESS;
970 ULONG_PTR cookie;
971 int i;
973 if (process_detaching) return status;
975 /* prevent infinite recursion in case of cyclical dependencies */
976 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
977 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
978 return status;
980 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
982 /* Tag current MODREF to prevent recursive loop */
983 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
984 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
985 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
987 /* Recursively attach all DLLs this one depends on */
988 for ( i = 0; i < wm->nDeps; i++ )
990 if (!wm->deps[i]) continue;
991 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
994 /* Call DLL entry point */
995 if (status == STATUS_SUCCESS)
997 WINE_MODREF *prev = current_modref;
998 current_modref = wm;
999 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1000 if (status == STATUS_SUCCESS)
1001 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1002 else
1004 /* point to the name so LdrInitializeThunk can print it */
1005 last_failed_modref = wm;
1006 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1008 current_modref = prev;
1011 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1012 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1013 &wm->ldr.InInitializationOrderModuleList);
1015 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1016 /* Remove recursion flag */
1017 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1019 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1020 return status;
1024 /**********************************************************************
1025 * attach_implicitly_loaded_dlls
1027 * Attach to the (builtin) dlls that have been implicitly loaded because
1028 * of a dependency at the Unix level, but not imported at the Win32 level.
1030 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1032 for (;;)
1034 PLIST_ENTRY mark, entry;
1036 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1037 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1039 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1041 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1042 TRACE( "found implicitly loaded %s, attaching to it\n",
1043 debugstr_w(mod->BaseDllName.Buffer));
1044 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1045 break; /* restart the search from the start */
1047 if (entry == mark) break; /* nothing found */
1052 /*************************************************************************
1053 * process_detach
1055 * Send DLL process detach notifications. See the comment about calling
1056 * sequence at process_attach. Unless the bForceDetach flag
1057 * is set, only DLLs with zero refcount are notified.
1059 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1061 PLIST_ENTRY mark, entry;
1062 PLDR_MODULE mod;
1064 RtlEnterCriticalSection( &loader_section );
1065 if (bForceDetach) process_detaching = 1;
1066 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1069 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1071 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1072 InInitializationOrderModuleList);
1073 /* Check whether to detach this DLL */
1074 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1075 continue;
1076 if ( mod->LoadCount && !bForceDetach )
1077 continue;
1079 /* Call detach notification */
1080 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1081 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1082 DLL_PROCESS_DETACH, lpReserved );
1084 /* Restart at head of WINE_MODREF list, as entries might have
1085 been added and/or removed while performing the call ... */
1086 break;
1088 } while (entry != mark);
1090 RtlLeaveCriticalSection( &loader_section );
1093 /*************************************************************************
1094 * MODULE_DllThreadAttach
1096 * Send DLL thread attach notifications. These are sent in the
1097 * reverse sequence of process detach notification.
1100 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1102 PLIST_ENTRY mark, entry;
1103 PLDR_MODULE mod;
1104 NTSTATUS status;
1106 /* don't do any attach calls if process is exiting */
1107 if (process_detaching) return STATUS_SUCCESS;
1108 /* FIXME: there is still a race here */
1110 RtlEnterCriticalSection( &loader_section );
1112 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1114 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1115 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1117 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1118 InInitializationOrderModuleList);
1119 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1120 continue;
1121 if ( mod->Flags & LDR_NO_DLL_CALLS )
1122 continue;
1124 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1125 DLL_THREAD_ATTACH, lpReserved );
1128 done:
1129 RtlLeaveCriticalSection( &loader_section );
1130 return status;
1133 /******************************************************************
1134 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1137 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1139 WINE_MODREF *wm;
1140 NTSTATUS ret = STATUS_SUCCESS;
1142 RtlEnterCriticalSection( &loader_section );
1144 wm = get_modref( hModule );
1145 if (!wm || wm->ldr.TlsIndex != -1)
1146 ret = STATUS_DLL_NOT_FOUND;
1147 else
1148 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1150 RtlLeaveCriticalSection( &loader_section );
1152 return ret;
1155 /******************************************************************
1156 * LdrFindEntryForAddress (NTDLL.@)
1158 * The loader_section must be locked while calling this function
1160 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1162 PLIST_ENTRY mark, entry;
1163 PLDR_MODULE mod;
1165 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1166 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1168 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1169 if ((const void *)mod->BaseAddress <= addr &&
1170 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1172 *pmod = mod;
1173 return STATUS_SUCCESS;
1175 if ((const void *)mod->BaseAddress > addr) break;
1177 return STATUS_NO_MORE_ENTRIES;
1180 /******************************************************************
1181 * LdrLockLoaderLock (NTDLL.@)
1183 * Note: flags are not implemented.
1184 * Flag 0x01 is used to raise exceptions on errors.
1185 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1187 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1189 if (flags) FIXME( "flags %x not supported\n", flags );
1191 if (result) *result = 1;
1192 if (!magic) return STATUS_INVALID_PARAMETER_3;
1193 RtlEnterCriticalSection( &loader_section );
1194 *magic = GetCurrentThreadId();
1195 return STATUS_SUCCESS;
1199 /******************************************************************
1200 * LdrUnlockLoaderUnlock (NTDLL.@)
1202 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1204 if (magic)
1206 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1207 RtlLeaveCriticalSection( &loader_section );
1209 return STATUS_SUCCESS;
1213 /******************************************************************
1214 * LdrGetProcedureAddress (NTDLL.@)
1216 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1217 ULONG ord, PVOID *address)
1219 IMAGE_EXPORT_DIRECTORY *exports;
1220 DWORD exp_size;
1221 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1223 RtlEnterCriticalSection( &loader_section );
1225 /* check if the module itself is invalid to return the proper error */
1226 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1227 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1228 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1230 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1231 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1232 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1233 if (proc)
1235 *address = proc;
1236 ret = STATUS_SUCCESS;
1240 RtlLeaveCriticalSection( &loader_section );
1241 return ret;
1245 /***********************************************************************
1246 * is_fake_dll
1248 * Check if a loaded native dll is a Wine fake dll.
1250 static BOOL is_fake_dll( HANDLE handle )
1252 static const char fakedll_signature[] = "Wine placeholder DLL";
1253 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1254 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1255 IO_STATUS_BLOCK io;
1256 LARGE_INTEGER offset;
1258 offset.QuadPart = 0;
1259 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1260 if (io.Information < sizeof(buffer)) return FALSE;
1261 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1262 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1263 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1264 return FALSE;
1268 /***********************************************************************
1269 * get_builtin_fullname
1271 * Build the full pathname for a builtin dll.
1273 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1275 static const WCHAR soW[] = {'.','s','o',0};
1276 WCHAR *p, *fullname;
1277 size_t i, len = strlen(filename);
1279 /* check if path can correspond to the dll we have */
1280 if (path && (p = strrchrW( path, '\\' )))
1282 p++;
1283 for (i = 0; i < len; i++)
1284 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1285 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1287 /* the filename matches, use path as the full path */
1288 len += p - path;
1289 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1291 memcpy( fullname, path, len * sizeof(WCHAR) );
1292 fullname[len] = 0;
1294 return fullname;
1298 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1299 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1301 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1302 p = fullname + system_dir.Length / sizeof(WCHAR);
1303 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1304 ascii_to_unicode( p, filename, len + 1 );
1306 return fullname;
1310 /***********************************************************************
1311 * load_builtin_callback
1313 * Load a library in memory; callback function for wine_dll_register
1315 static void load_builtin_callback( void *module, const char *filename )
1317 static const WCHAR emptyW[1];
1318 void *addr;
1319 IMAGE_NT_HEADERS *nt;
1320 WINE_MODREF *wm;
1321 WCHAR *fullname;
1322 const WCHAR *load_path;
1323 SIZE_T size;
1325 if (!module)
1327 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1328 return;
1330 if (!(nt = RtlImageNtHeader( module )))
1332 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1333 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1334 return;
1336 addr = module;
1337 size = nt->OptionalHeader.SizeOfImage;
1338 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1339 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1340 /* create the MODREF */
1342 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1344 ERR( "can't load %s\n", filename );
1345 builtin_load_info->status = STATUS_NO_MEMORY;
1346 return;
1349 wm = alloc_module( module, fullname );
1350 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1351 if (!wm)
1353 ERR( "can't load %s\n", filename );
1354 builtin_load_info->status = STATUS_NO_MEMORY;
1355 return;
1357 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1359 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1360 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1362 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1364 else
1366 /* fixup imports */
1368 load_path = builtin_load_info->load_path;
1369 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1370 if (!load_path) load_path = emptyW;
1371 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1373 /* the module has only be inserted in the load & memory order lists */
1374 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1375 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1376 /* FIXME: free the modref */
1377 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1378 return;
1382 builtin_load_info->wm = wm;
1383 TRACE( "loaded %s %p %p\n", filename, wm, module );
1385 /* send the DLL load event */
1387 SERVER_START_REQ( load_dll )
1389 req->handle = 0;
1390 req->base = module;
1391 req->size = nt->OptionalHeader.SizeOfImage;
1392 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1393 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1394 req->name = &wm->ldr.FullDllName.Buffer;
1395 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1396 wine_server_call( req );
1398 SERVER_END_REQ;
1400 /* setup relay debugging entry points */
1401 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1405 /******************************************************************************
1406 * load_native_dll (internal)
1408 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1409 DWORD flags, WINE_MODREF** pwm )
1411 void *module;
1412 HANDLE mapping;
1413 OBJECT_ATTRIBUTES attr;
1414 LARGE_INTEGER size;
1415 IMAGE_NT_HEADERS *nt;
1416 SIZE_T len = 0;
1417 WINE_MODREF *wm;
1418 NTSTATUS status;
1420 TRACE("Trying native dll %s\n", debugstr_w(name));
1422 attr.Length = sizeof(attr);
1423 attr.RootDirectory = 0;
1424 attr.ObjectName = NULL;
1425 attr.Attributes = 0;
1426 attr.SecurityDescriptor = NULL;
1427 attr.SecurityQualityOfService = NULL;
1428 size.QuadPart = 0;
1430 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1431 &attr, &size, 0, SEC_IMAGE, file );
1432 if (status != STATUS_SUCCESS) return status;
1434 module = NULL;
1435 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1436 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1437 NtClose( mapping );
1438 if (status != STATUS_SUCCESS) return status;
1440 /* create the MODREF */
1442 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1444 /* fixup imports */
1446 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1448 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1450 /* the module has only be inserted in the load & memory order lists */
1451 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1452 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1454 /* FIXME: there are several more dangling references
1455 * left. Including dlls loaded by this dll before the
1456 * failed one. Unrolling is rather difficult with the
1457 * current structure and we can leave them lying
1458 * around with no problems, so we don't care.
1459 * As these might reference our wm, we don't free it.
1461 return status;
1465 /* send DLL load event */
1467 nt = RtlImageNtHeader( module );
1469 SERVER_START_REQ( load_dll )
1471 req->handle = file;
1472 req->base = module;
1473 req->size = nt->OptionalHeader.SizeOfImage;
1474 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1475 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1476 req->name = &wm->ldr.FullDllName.Buffer;
1477 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1478 wine_server_call( req );
1480 SERVER_END_REQ;
1482 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1484 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1486 wm->ldr.LoadCount = 1;
1487 *pwm = wm;
1488 return STATUS_SUCCESS;
1492 /***********************************************************************
1493 * load_builtin_dll
1495 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1496 DWORD flags, WINE_MODREF** pwm )
1498 char error[256], dllname[MAX_PATH];
1499 const WCHAR *name, *p;
1500 DWORD len, i;
1501 void *handle = NULL;
1502 struct builtin_load_info info, *prev_info;
1504 /* Fix the name in case we have a full path and extension */
1505 name = path;
1506 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1507 if ((p = strrchrW( name, '/' ))) name = p + 1;
1509 /* load_library will modify info.status. Note also that load_library can be
1510 * called several times, if the .so file we're loading has dependencies.
1511 * info.status will gather all the errors we may get while loading all these
1512 * libraries
1514 info.load_path = load_path;
1515 info.filename = NULL;
1516 info.status = STATUS_SUCCESS;
1517 info.wm = NULL;
1519 if (file) /* we have a real file, try to load it */
1521 UNICODE_STRING nt_name;
1522 ANSI_STRING unix_name;
1524 TRACE("Trying built-in %s\n", debugstr_w(path));
1526 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1527 return STATUS_DLL_NOT_FOUND;
1529 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1531 RtlFreeUnicodeString( &nt_name );
1532 return STATUS_DLL_NOT_FOUND;
1534 prev_info = builtin_load_info;
1535 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1536 builtin_load_info = &info;
1537 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1538 builtin_load_info = prev_info;
1539 RtlFreeUnicodeString( &nt_name );
1540 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1541 if (!handle)
1543 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1544 return STATUS_INVALID_IMAGE_FORMAT;
1547 else
1549 int file_exists;
1551 TRACE("Trying built-in %s\n", debugstr_w(name));
1553 /* we don't want to depend on the current codepage here */
1554 len = strlenW( name ) + 1;
1555 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1556 for (i = 0; i < len; i++)
1558 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1559 dllname[i] = (char)name[i];
1560 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1563 prev_info = builtin_load_info;
1564 builtin_load_info = &info;
1565 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1566 builtin_load_info = prev_info;
1567 if (!handle)
1569 if (!file_exists)
1571 /* The file does not exist -> WARN() */
1572 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1573 return STATUS_DLL_NOT_FOUND;
1575 /* ERR() for all other errors (missing functions, ...) */
1576 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1577 return STATUS_PROCEDURE_NOT_FOUND;
1581 if (info.status != STATUS_SUCCESS)
1583 wine_dll_unload( handle );
1584 return info.status;
1587 if (!info.wm)
1589 PLIST_ENTRY mark, entry;
1591 /* The constructor wasn't called, this means the .so is already
1592 * loaded under a different name. Try to find the wm for it. */
1594 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1595 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1597 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1598 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1600 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1601 TRACE( "Found %s at %p for builtin %s\n",
1602 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1603 break;
1606 wine_dll_unload( handle ); /* release the libdl refcount */
1607 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1608 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1610 else
1612 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1613 info.wm->ldr.LoadCount = 1;
1614 info.wm->ldr.SectionHandle = handle;
1617 *pwm = info.wm;
1618 return STATUS_SUCCESS;
1622 /***********************************************************************
1623 * find_actctx_dll
1625 * Find the full path (if any) of the dll from the activation context.
1627 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1629 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1630 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1632 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1633 ACTCTX_SECTION_KEYED_DATA data;
1634 UNICODE_STRING nameW;
1635 NTSTATUS status;
1636 SIZE_T needed, size = 1024;
1637 WCHAR *p;
1639 RtlInitUnicodeString( &nameW, libname );
1640 data.cbSize = sizeof(data);
1641 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1642 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1643 &nameW, &data );
1644 if (status != STATUS_SUCCESS) return status;
1646 for (;;)
1648 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1650 status = STATUS_NO_MEMORY;
1651 goto done;
1653 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1654 AssemblyDetailedInformationInActivationContext,
1655 info, size, &needed );
1656 if (status == STATUS_SUCCESS) break;
1657 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1658 RtlFreeHeap( GetProcessHeap(), 0, info );
1659 size = needed;
1660 /* restart with larger buffer */
1663 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1665 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1667 p++;
1668 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1670 /* manifest name does not match directory name, so it's not a global
1671 * windows/winsxs manifest; use the manifest directory name instead */
1672 dirlen = p - info->lpAssemblyManifestPath;
1673 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1674 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1676 status = STATUS_NO_MEMORY;
1677 goto done;
1679 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1680 p += dirlen;
1681 strcpyW( p, libname );
1682 goto done;
1686 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1687 nameW.Length + 2*sizeof(WCHAR));
1689 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1691 status = STATUS_NO_MEMORY;
1692 goto done;
1694 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1695 p += windows_dir.Length / sizeof(WCHAR);
1696 memcpy( p, winsxsW, sizeof(winsxsW) );
1697 p += sizeof(winsxsW) / sizeof(WCHAR);
1698 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1699 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1700 *p++ = '\\';
1701 strcpyW( p, libname );
1702 done:
1703 RtlFreeHeap( GetProcessHeap(), 0, info );
1704 RtlReleaseActivationContext( data.hActCtx );
1705 return status;
1709 /***********************************************************************
1710 * find_dll_file
1712 * Find the file (or already loaded module) for a given dll name.
1714 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1715 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1717 OBJECT_ATTRIBUTES attr;
1718 IO_STATUS_BLOCK io;
1719 UNICODE_STRING nt_name;
1720 WCHAR *file_part, *ext, *dllname;
1721 ULONG len;
1723 /* first append .dll if needed */
1725 dllname = NULL;
1726 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1728 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1729 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1730 return STATUS_NO_MEMORY;
1731 strcpyW( dllname, libname );
1732 strcatW( dllname, dllW );
1733 libname = dllname;
1736 nt_name.Buffer = NULL;
1738 if (!contains_path( libname ))
1740 NTSTATUS status;
1741 WCHAR *fullname = NULL;
1743 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1745 status = find_actctx_dll( libname, &fullname );
1746 if (status == STATUS_SUCCESS)
1748 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1749 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1750 libname = dllname = fullname;
1752 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1754 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1755 return status;
1759 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1761 /* we need to search for it */
1762 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1763 if (len)
1765 if (len >= *size) goto overflow;
1766 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1768 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1770 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1771 return STATUS_NO_MEMORY;
1773 attr.Length = sizeof(attr);
1774 attr.RootDirectory = 0;
1775 attr.Attributes = OBJ_CASE_INSENSITIVE;
1776 attr.ObjectName = &nt_name;
1777 attr.SecurityDescriptor = NULL;
1778 attr.SecurityQualityOfService = NULL;
1779 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1780 goto found;
1783 /* not found */
1785 if (!contains_path( libname ))
1787 /* if libname doesn't contain a path at all, we simply return the name as is,
1788 * to be loaded as builtin */
1789 len = strlenW(libname) * sizeof(WCHAR);
1790 if (len >= *size) goto overflow;
1791 strcpyW( filename, libname );
1792 goto found;
1796 /* absolute path name, or relative path name but not found above */
1798 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1800 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1801 return STATUS_NO_MEMORY;
1803 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1804 if (len >= *size) goto overflow;
1805 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1806 if (!(*pwm = find_fullname_module( filename )) && handle)
1808 attr.Length = sizeof(attr);
1809 attr.RootDirectory = 0;
1810 attr.Attributes = OBJ_CASE_INSENSITIVE;
1811 attr.ObjectName = &nt_name;
1812 attr.SecurityDescriptor = NULL;
1813 attr.SecurityQualityOfService = NULL;
1814 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1816 found:
1817 RtlFreeUnicodeString( &nt_name );
1818 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1819 return STATUS_SUCCESS;
1821 overflow:
1822 RtlFreeUnicodeString( &nt_name );
1823 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1824 *size = len + sizeof(WCHAR);
1825 return STATUS_BUFFER_TOO_SMALL;
1829 /***********************************************************************
1830 * load_dll (internal)
1832 * Load a PE style module according to the load order.
1833 * The loader_section must be locked while calling this function.
1835 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1837 enum loadorder loadorder;
1838 WCHAR buffer[32];
1839 WCHAR *filename;
1840 ULONG size;
1841 WINE_MODREF *main_exe;
1842 HANDLE handle = 0;
1843 NTSTATUS nts;
1845 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1847 *pwm = NULL;
1848 filename = buffer;
1849 size = sizeof(buffer);
1850 for (;;)
1852 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1853 if (nts == STATUS_SUCCESS) break;
1854 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1855 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1856 /* grow the buffer and retry */
1857 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1860 if (*pwm) /* found already loaded module */
1862 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1864 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1866 TRACE("Found %s for %s at %p, count=%d\n",
1867 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1868 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1869 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1870 return STATUS_SUCCESS;
1873 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1874 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1876 if (handle && is_fake_dll( handle ))
1878 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1879 NtClose( handle );
1880 handle = 0;
1883 switch(loadorder)
1885 case LO_INVALID:
1886 nts = STATUS_NO_MEMORY;
1887 break;
1888 case LO_DISABLED:
1889 nts = STATUS_DLL_NOT_FOUND;
1890 break;
1891 case LO_NATIVE:
1892 case LO_NATIVE_BUILTIN:
1893 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1894 else
1896 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1897 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1898 /* not in PE format, maybe it's a builtin */
1899 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1901 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1902 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1903 break;
1904 case LO_BUILTIN:
1905 case LO_BUILTIN_NATIVE:
1906 case LO_DEFAULT: /* default is builtin,native */
1907 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1908 if (!handle) break; /* nothing else we can try */
1909 /* file is not a builtin library, try without using the specified file */
1910 if (nts != STATUS_SUCCESS)
1911 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1912 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1913 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1915 /* stub-only dll, try native */
1916 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1917 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1918 nts = STATUS_DLL_NOT_FOUND;
1920 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1921 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1922 break;
1925 if (nts == STATUS_SUCCESS)
1927 /* Initialize DLL just loaded */
1928 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1929 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1930 (*pwm)->ldr.BaseAddress);
1931 if (handle) NtClose( handle );
1932 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1933 return nts;
1936 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1937 if (handle) NtClose( handle );
1938 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1939 return nts;
1942 /******************************************************************
1943 * LdrLoadDll (NTDLL.@)
1945 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1946 const UNICODE_STRING *libname, HMODULE* hModule)
1948 WINE_MODREF *wm;
1949 NTSTATUS nts;
1951 RtlEnterCriticalSection( &loader_section );
1953 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1954 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1956 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1958 nts = process_attach( wm, NULL );
1959 if (nts != STATUS_SUCCESS)
1961 LdrUnloadDll(wm->ldr.BaseAddress);
1962 wm = NULL;
1965 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1967 RtlLeaveCriticalSection( &loader_section );
1968 return nts;
1972 /******************************************************************
1973 * LdrGetDllHandle (NTDLL.@)
1975 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1977 NTSTATUS status;
1978 WCHAR buffer[128];
1979 WCHAR *filename;
1980 ULONG size;
1981 WINE_MODREF *wm;
1983 RtlEnterCriticalSection( &loader_section );
1985 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1987 filename = buffer;
1988 size = sizeof(buffer);
1989 for (;;)
1991 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1992 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1993 if (status != STATUS_BUFFER_TOO_SMALL) break;
1994 /* grow the buffer and retry */
1995 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1997 status = STATUS_NO_MEMORY;
1998 break;
2002 if (status == STATUS_SUCCESS)
2004 if (wm) *base = wm->ldr.BaseAddress;
2005 else status = STATUS_DLL_NOT_FOUND;
2008 RtlLeaveCriticalSection( &loader_section );
2009 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2010 return status;
2014 /******************************************************************
2015 * LdrAddRefDll (NTDLL.@)
2017 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2019 NTSTATUS ret = STATUS_SUCCESS;
2020 WINE_MODREF *wm;
2022 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2024 RtlEnterCriticalSection( &loader_section );
2026 if ((wm = get_modref( module )))
2028 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2029 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2031 else ret = STATUS_INVALID_PARAMETER;
2033 RtlLeaveCriticalSection( &loader_section );
2034 return ret;
2038 /***********************************************************************
2039 * LdrProcessRelocationBlock (NTDLL.@)
2041 * Apply relocations to a given page of a mapped PE image.
2043 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2044 USHORT *relocs, INT delta )
2046 while (count--)
2048 USHORT offset = *relocs & 0xfff;
2049 int type = *relocs >> 12;
2050 switch(type)
2052 case IMAGE_REL_BASED_ABSOLUTE:
2053 break;
2054 case IMAGE_REL_BASED_HIGH:
2055 *(short *)((char *)page + offset) += HIWORD(delta);
2056 break;
2057 case IMAGE_REL_BASED_LOW:
2058 *(short *)((char *)page + offset) += LOWORD(delta);
2059 break;
2060 case IMAGE_REL_BASED_HIGHLOW:
2061 *(int *)((char *)page + offset) += delta;
2062 break;
2063 default:
2064 FIXME("Unknown/unsupported fixup type %x.\n", type);
2065 return NULL;
2067 relocs++;
2069 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2073 /******************************************************************
2074 * LdrQueryProcessModuleInformation
2077 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2078 ULONG buf_size, ULONG* req_size)
2080 SYSTEM_MODULE* sm = &smi->Modules[0];
2081 ULONG size = sizeof(ULONG);
2082 NTSTATUS nts = STATUS_SUCCESS;
2083 ANSI_STRING str;
2084 char* ptr;
2085 PLIST_ENTRY mark, entry;
2086 PLDR_MODULE mod;
2087 WORD id = 0;
2089 smi->ModulesCount = 0;
2091 RtlEnterCriticalSection( &loader_section );
2092 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2093 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2095 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2096 size += sizeof(*sm);
2097 if (size <= buf_size)
2099 sm->Reserved1 = 0; /* FIXME */
2100 sm->Reserved2 = 0; /* FIXME */
2101 sm->ImageBaseAddress = mod->BaseAddress;
2102 sm->ImageSize = mod->SizeOfImage;
2103 sm->Flags = mod->Flags;
2104 sm->Id = id++;
2105 sm->Rank = 0; /* FIXME */
2106 sm->Unknown = 0; /* FIXME */
2107 str.Length = 0;
2108 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2109 str.Buffer = (char*)sm->Name;
2110 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2111 ptr = strrchr(str.Buffer, '\\');
2112 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2114 smi->ModulesCount++;
2115 sm++;
2117 else nts = STATUS_INFO_LENGTH_MISMATCH;
2119 RtlLeaveCriticalSection( &loader_section );
2121 if (req_size) *req_size = size;
2123 return nts;
2127 /******************************************************************
2128 * RtlDllShutdownInProgress (NTDLL.@)
2130 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2132 return process_detaching;
2136 /******************************************************************
2137 * LdrShutdownProcess (NTDLL.@)
2140 void WINAPI LdrShutdownProcess(void)
2142 TRACE("()\n");
2143 process_detach( TRUE, (LPVOID)1 );
2146 /******************************************************************
2147 * LdrShutdownThread (NTDLL.@)
2150 void WINAPI LdrShutdownThread(void)
2152 PLIST_ENTRY mark, entry;
2153 PLDR_MODULE mod;
2155 TRACE("()\n");
2157 /* don't do any detach calls if process is exiting */
2158 if (process_detaching) return;
2159 /* FIXME: there is still a race here */
2161 RtlEnterCriticalSection( &loader_section );
2163 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2164 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2166 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2167 InInitializationOrderModuleList);
2168 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2169 continue;
2170 if ( mod->Flags & LDR_NO_DLL_CALLS )
2171 continue;
2173 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2174 DLL_THREAD_DETACH, NULL );
2177 RtlLeaveCriticalSection( &loader_section );
2178 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2182 /***********************************************************************
2183 * free_modref
2186 static void free_modref( WINE_MODREF *wm )
2188 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2189 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2190 if (wm->ldr.InInitializationOrderModuleList.Flink)
2191 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2193 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2194 if (!TRACE_ON(module))
2195 TRACE_(loaddll)("Unloaded module %s : %s\n",
2196 debugstr_w(wm->ldr.FullDllName.Buffer),
2197 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2199 SERVER_START_REQ( unload_dll )
2201 req->base = wm->ldr.BaseAddress;
2202 wine_server_call( req );
2204 SERVER_END_REQ;
2206 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2207 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2208 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2209 if (cached_modref == wm) cached_modref = NULL;
2210 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2211 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2212 RtlFreeHeap( GetProcessHeap(), 0, wm );
2215 /***********************************************************************
2216 * MODULE_FlushModrefs
2218 * Remove all unused modrefs and call the internal unloading routines
2219 * for the library type.
2221 * The loader_section must be locked while calling this function.
2223 static void MODULE_FlushModrefs(void)
2225 PLIST_ENTRY mark, entry, prev;
2226 PLDR_MODULE mod;
2227 WINE_MODREF*wm;
2229 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2230 for (entry = mark->Blink; entry != mark; entry = prev)
2232 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2233 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2234 prev = entry->Blink;
2235 if (!mod->LoadCount) free_modref( wm );
2238 /* check load order list too for modules that haven't been initialized yet */
2239 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2240 for (entry = mark->Blink; entry != mark; entry = prev)
2242 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2243 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2244 prev = entry->Blink;
2245 if (!mod->LoadCount) free_modref( wm );
2249 /***********************************************************************
2250 * MODULE_DecRefCount
2252 * The loader_section must be locked while calling this function.
2254 static void MODULE_DecRefCount( WINE_MODREF *wm )
2256 int i;
2258 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2259 return;
2261 if ( wm->ldr.LoadCount <= 0 )
2262 return;
2264 --wm->ldr.LoadCount;
2265 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2267 if ( wm->ldr.LoadCount == 0 )
2269 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2271 for ( i = 0; i < wm->nDeps; i++ )
2272 if ( wm->deps[i] )
2273 MODULE_DecRefCount( wm->deps[i] );
2275 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2279 /******************************************************************
2280 * LdrUnloadDll (NTDLL.@)
2284 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2286 NTSTATUS retv = STATUS_SUCCESS;
2288 TRACE("(%p)\n", hModule);
2290 RtlEnterCriticalSection( &loader_section );
2292 /* if we're stopping the whole process (and forcing the removal of all
2293 * DLLs) the library will be freed anyway
2295 if (!process_detaching)
2297 WINE_MODREF *wm;
2299 free_lib_count++;
2300 if ((wm = get_modref( hModule )) != NULL)
2302 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2304 /* Recursively decrement reference counts */
2305 MODULE_DecRefCount( wm );
2307 /* Call process detach notifications */
2308 if ( free_lib_count <= 1 )
2310 process_detach( FALSE, NULL );
2311 MODULE_FlushModrefs();
2314 TRACE("END\n");
2316 else
2317 retv = STATUS_DLL_NOT_FOUND;
2319 free_lib_count--;
2322 RtlLeaveCriticalSection( &loader_section );
2324 return retv;
2327 /***********************************************************************
2328 * RtlImageNtHeader (NTDLL.@)
2330 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2332 IMAGE_NT_HEADERS *ret;
2334 __TRY
2336 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2338 ret = NULL;
2339 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2341 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2342 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2345 __EXCEPT_PAGE_FAULT
2347 return NULL;
2349 __ENDTRY
2350 return ret;
2354 /***********************************************************************
2355 * attach_process_dlls
2357 * Initial attach to all the dlls loaded by the process.
2359 static NTSTATUS attach_process_dlls( void *wm )
2361 NTSTATUS status;
2363 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2365 RtlEnterCriticalSection( &loader_section );
2366 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2368 if (last_failed_modref)
2369 ERR( "%s failed to initialize, aborting\n",
2370 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2371 return status;
2373 attach_implicitly_loaded_dlls( (LPVOID)1 );
2374 RtlLeaveCriticalSection( &loader_section );
2375 return status;
2379 /******************************************************************
2380 * LdrInitializeThunk (NTDLL.@)
2383 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2385 NTSTATUS status;
2386 WINE_MODREF *wm;
2387 LPCWSTR load_path;
2388 SIZE_T stack_size;
2389 PEB *peb = NtCurrentTeb()->Peb;
2390 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2392 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2394 /* allocate the modref for the main exe (if not already done) */
2395 wm = get_modref( peb->ImageBaseAddress );
2396 assert( wm );
2397 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2399 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2400 exit(1);
2403 peb->LoaderLock = &loader_section;
2404 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2405 version_init( wm->ldr.FullDllName.Buffer );
2407 /* the main exe needs to be the first in the load order list */
2408 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2409 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2411 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
2412 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
2414 if ((status = virtual_alloc_thread_stack( NULL, stack_size )) != STATUS_SUCCESS) goto error;
2415 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2417 actctx_init();
2418 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2419 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2420 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2421 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2423 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2424 if (status != STATUS_SUCCESS) goto error;
2426 /* clear the stack contents before calling the main entry point, some broken apps need that */
2427 wine_anon_mmap( NtCurrentTeb()->Tib.StackLimit,
2428 (char *)NtCurrentTeb()->Tib.StackBase - (char *)NtCurrentTeb()->Tib.StackLimit,
2429 PROT_READ | PROT_WRITE, MAP_FIXED );
2431 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2432 return;
2434 error:
2435 ERR( "Main exe initialization for %s failed, status %x\n",
2436 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2437 NtTerminateProcess( GetCurrentProcess(), status );
2441 /***********************************************************************
2442 * RtlImageDirectoryEntryToData (NTDLL.@)
2444 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2446 const IMAGE_NT_HEADERS *nt;
2447 DWORD addr;
2449 if ((ULONG_PTR)module & 1) /* mapped as data file */
2451 module = (HMODULE)((ULONG_PTR)module & ~1);
2452 image = FALSE;
2454 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2455 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2456 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2457 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2458 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2460 /* not mapped as image, need to find the section containing the virtual address */
2461 return RtlImageRvaToVa( nt, module, addr, NULL );
2465 /***********************************************************************
2466 * RtlImageRvaToSection (NTDLL.@)
2468 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2469 HMODULE module, DWORD rva )
2471 int i;
2472 const IMAGE_SECTION_HEADER *sec;
2474 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2475 nt->FileHeader.SizeOfOptionalHeader);
2476 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2478 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2479 return (PIMAGE_SECTION_HEADER)sec;
2481 return NULL;
2485 /***********************************************************************
2486 * RtlImageRvaToVa (NTDLL.@)
2488 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2489 DWORD rva, IMAGE_SECTION_HEADER **section )
2491 IMAGE_SECTION_HEADER *sec;
2493 if (section && *section) /* try this section first */
2495 sec = *section;
2496 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2497 goto found;
2499 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2500 found:
2501 if (section) *section = sec;
2502 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2506 /***********************************************************************
2507 * RtlPcToFileHeader (NTDLL.@)
2509 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2511 LDR_MODULE *module;
2512 PVOID ret = NULL;
2514 RtlEnterCriticalSection( &loader_section );
2515 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2516 RtlLeaveCriticalSection( &loader_section );
2517 *address = ret;
2518 return ret;
2522 /***********************************************************************
2523 * NtLoadDriver (NTDLL.@)
2524 * ZwLoadDriver (NTDLL.@)
2526 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2528 FIXME("(%p), stub!\n",DriverServiceName);
2529 return STATUS_NOT_IMPLEMENTED;
2533 /***********************************************************************
2534 * NtUnloadDriver (NTDLL.@)
2535 * ZwUnloadDriver (NTDLL.@)
2537 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2539 FIXME("(%p), stub!\n",DriverServiceName);
2540 return STATUS_NOT_IMPLEMENTED;
2544 /******************************************************************
2545 * DllMain (NTDLL.@)
2547 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2549 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2550 return TRUE;
2554 /******************************************************************
2555 * __wine_init_windows_dir (NTDLL.@)
2557 * Windows and system dir initialization once kernel32 has been loaded.
2559 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2561 PLIST_ENTRY mark, entry;
2562 LPWSTR buffer, p;
2564 RtlCreateUnicodeString( &windows_dir, windir );
2565 RtlCreateUnicodeString( &system_dir, sysdir );
2566 strcpyW( user_shared_data->NtSystemRoot, windir );
2568 /* prepend the system dir to the name of the already created modules */
2569 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2570 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2572 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2574 assert( mod->Flags & LDR_WINE_INTERNAL );
2576 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2577 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2578 if (!buffer) continue;
2579 strcpyW( buffer, system_dir.Buffer );
2580 p = buffer + strlenW( buffer );
2581 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2582 strcpyW( p, mod->FullDllName.Buffer );
2583 RtlInitUnicodeString( &mod->FullDllName, buffer );
2584 RtlInitUnicodeString( &mod->BaseDllName, p );
2589 /***********************************************************************
2590 * __wine_process_init
2592 void __wine_process_init(void)
2594 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2596 WINE_MODREF *wm;
2597 NTSTATUS status;
2598 ANSI_STRING func_name;
2599 void (* DECLSPEC_NORETURN init_func)(void);
2600 extern mode_t FILE_umask;
2602 main_exe_file = thread_init();
2604 /* retrieve current umask */
2605 FILE_umask = umask(0777);
2606 umask( FILE_umask );
2608 /* setup the load callback and create ntdll modref */
2609 wine_dll_set_callback( load_builtin_callback );
2611 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2613 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2614 exit(1);
2616 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2617 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2619 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2620 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2621 0, (void **)&init_func )) != STATUS_SUCCESS)
2623 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2624 exit(1);
2626 init_func();