push 9eb9af089d68d39110a91889d3a673043db63c4b
[wine/hacks.git] / dlls / ntdll / loader.c
blobeab7516de2581f46b188138c8fd48bcc95c25f80
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->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE &&
719 (nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
721 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
722 if (nt->OptionalHeader.AddressOfEntryPoint)
723 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
726 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
727 &wm->ldr.InLoadOrderModuleList);
729 /* insert module in MemoryList, sorted in increasing base addresses */
730 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
731 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
733 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
734 break;
736 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
737 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
738 wm->ldr.InMemoryOrderModuleList.Flink = entry;
739 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
741 /* wait until init is called for inserting into this list */
742 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
743 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
745 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
747 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
748 VIRTUAL_SetForceExec( TRUE );
750 return wm;
754 /*************************************************************************
755 * alloc_process_tls
757 * Allocate the process-wide structure for module TLS storage.
759 static NTSTATUS alloc_process_tls(void)
761 PLIST_ENTRY mark, entry;
762 PLDR_MODULE mod;
763 const IMAGE_TLS_DIRECTORY *dir;
764 ULONG size, i;
766 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
767 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
769 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
770 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
771 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
772 continue;
773 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
774 if (!size) continue;
775 tls_total_size += size;
776 tls_module_count++;
778 if (!tls_module_count) return STATUS_SUCCESS;
780 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
782 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
783 if (!tls_dirs) return STATUS_NO_MEMORY;
785 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
787 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
788 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
789 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
790 continue;
791 tls_dirs[i] = dir;
792 *(DWORD *)dir->AddressOfIndex = i;
793 mod->TlsIndex = i;
794 mod->LoadCount = -1; /* can't unload it */
795 i++;
797 return STATUS_SUCCESS;
801 /*************************************************************************
802 * alloc_thread_tls
804 * Allocate the per-thread structure for module TLS storage.
806 static NTSTATUS alloc_thread_tls(void)
808 void **pointers;
809 char *data;
810 UINT i;
812 if (!tls_module_count) return STATUS_SUCCESS;
814 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
815 tls_module_count * sizeof(*pointers) )))
816 return STATUS_NO_MEMORY;
818 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
820 RtlFreeHeap( GetProcessHeap(), 0, pointers );
821 return STATUS_NO_MEMORY;
824 for (i = 0; i < tls_module_count; i++)
826 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
827 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
829 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
830 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
831 (void *)dir->StartAddressOfRawData, data );
833 pointers[i] = data;
834 memcpy( data, (void *)dir->StartAddressOfRawData, size );
835 data += size;
836 memset( data, 0, dir->SizeOfZeroFill );
837 data += dir->SizeOfZeroFill;
839 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
840 return STATUS_SUCCESS;
844 /*************************************************************************
845 * call_tls_callbacks
847 static void call_tls_callbacks( HMODULE module, UINT reason )
849 const IMAGE_TLS_DIRECTORY *dir;
850 const PIMAGE_TLS_CALLBACK *callback;
851 ULONG dirsize;
853 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
854 if (!dir || !dir->AddressOfCallBacks) return;
856 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
858 if (TRACE_ON(relay))
859 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
860 GetCurrentThreadId(), *callback, module, reason_names[reason] );
861 __TRY
863 (*callback)( module, reason, NULL );
865 __EXCEPT_ALL
867 if (TRACE_ON(relay))
868 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
869 GetCurrentThreadId(), callback, module, reason_names[reason] );
870 return;
872 __ENDTRY
873 if (TRACE_ON(relay))
874 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
875 GetCurrentThreadId(), *callback, module, reason_names[reason] );
880 /*************************************************************************
881 * MODULE_InitDLL
883 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
885 WCHAR mod_name[32];
886 NTSTATUS status = STATUS_SUCCESS;
887 DLLENTRYPROC entry = wm->ldr.EntryPoint;
888 void *module = wm->ldr.BaseAddress;
889 BOOL retv = TRUE;
891 /* Skip calls for modules loaded with special load flags */
893 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
894 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
895 if (!entry) return STATUS_SUCCESS;
897 if (TRACE_ON(relay))
899 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
900 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
901 mod_name[len / sizeof(WCHAR)] = 0;
902 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
903 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
904 reason_names[reason], lpReserved );
906 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
907 reason_names[reason], lpReserved );
909 __TRY
911 retv = call_dll_entry_point( entry, module, reason, lpReserved );
912 if (!retv)
913 status = STATUS_DLL_INIT_FAILED;
915 __EXCEPT_ALL
917 if (TRACE_ON(relay))
918 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
919 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
920 status = GetExceptionCode();
922 __ENDTRY
924 /* The state of the module list may have changed due to the call
925 to the dll. We cannot assume that this module has not been
926 deleted. */
927 if (TRACE_ON(relay))
928 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
929 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
930 reason_names[reason], lpReserved, retv );
931 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
933 return status;
937 /*************************************************************************
938 * process_attach
940 * Send the process attach notification to all DLLs the given module
941 * depends on (recursively). This is somewhat complicated due to the fact that
943 * - we have to respect the module dependencies, i.e. modules implicitly
944 * referenced by another module have to be initialized before the module
945 * itself can be initialized
947 * - the initialization routine of a DLL can itself call LoadLibrary,
948 * thereby introducing a whole new set of dependencies (even involving
949 * the 'old' modules) at any time during the whole process
951 * (Note that this routine can be recursively entered not only directly
952 * from itself, but also via LoadLibrary from one of the called initialization
953 * routines.)
955 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
956 * the process *detach* notifications to be sent in the correct order.
957 * This must not only take into account module dependencies, but also
958 * 'hidden' dependencies created by modules calling LoadLibrary in their
959 * attach notification routine.
961 * The strategy is rather simple: we move a WINE_MODREF to the head of the
962 * list after the attach notification has returned. This implies that the
963 * detach notifications are called in the reverse of the sequence the attach
964 * notifications *returned*.
966 * The loader_section must be locked while calling this function.
968 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
970 NTSTATUS status = STATUS_SUCCESS;
971 ULONG_PTR cookie;
972 int i;
974 if (process_detaching) return status;
976 /* prevent infinite recursion in case of cyclical dependencies */
977 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
978 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
979 return status;
981 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
983 /* Tag current MODREF to prevent recursive loop */
984 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
985 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
986 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
988 /* Recursively attach all DLLs this one depends on */
989 for ( i = 0; i < wm->nDeps; i++ )
991 if (!wm->deps[i]) continue;
992 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
995 /* Call DLL entry point */
996 if (status == STATUS_SUCCESS)
998 WINE_MODREF *prev = current_modref;
999 current_modref = wm;
1000 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1001 if (status == STATUS_SUCCESS)
1002 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1003 else
1005 /* point to the name so LdrInitializeThunk can print it */
1006 last_failed_modref = wm;
1007 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1009 current_modref = prev;
1012 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1013 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1014 &wm->ldr.InInitializationOrderModuleList);
1016 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1017 /* Remove recursion flag */
1018 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1020 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1021 return status;
1025 /**********************************************************************
1026 * attach_implicitly_loaded_dlls
1028 * Attach to the (builtin) dlls that have been implicitly loaded because
1029 * of a dependency at the Unix level, but not imported at the Win32 level.
1031 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1033 for (;;)
1035 PLIST_ENTRY mark, entry;
1037 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1038 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1040 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1042 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1043 TRACE( "found implicitly loaded %s, attaching to it\n",
1044 debugstr_w(mod->BaseDllName.Buffer));
1045 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1046 break; /* restart the search from the start */
1048 if (entry == mark) break; /* nothing found */
1053 /*************************************************************************
1054 * process_detach
1056 * Send DLL process detach notifications. See the comment about calling
1057 * sequence at process_attach. Unless the bForceDetach flag
1058 * is set, only DLLs with zero refcount are notified.
1060 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1062 PLIST_ENTRY mark, entry;
1063 PLDR_MODULE mod;
1065 RtlEnterCriticalSection( &loader_section );
1066 if (bForceDetach) process_detaching = 1;
1067 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1070 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1072 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1073 InInitializationOrderModuleList);
1074 /* Check whether to detach this DLL */
1075 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1076 continue;
1077 if ( mod->LoadCount && !bForceDetach )
1078 continue;
1080 /* Call detach notification */
1081 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1082 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1083 DLL_PROCESS_DETACH, lpReserved );
1085 /* Restart at head of WINE_MODREF list, as entries might have
1086 been added and/or removed while performing the call ... */
1087 break;
1089 } while (entry != mark);
1091 RtlLeaveCriticalSection( &loader_section );
1094 /*************************************************************************
1095 * MODULE_DllThreadAttach
1097 * Send DLL thread attach notifications. These are sent in the
1098 * reverse sequence of process detach notification.
1101 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1103 PLIST_ENTRY mark, entry;
1104 PLDR_MODULE mod;
1105 NTSTATUS status;
1107 /* don't do any attach calls if process is exiting */
1108 if (process_detaching) return STATUS_SUCCESS;
1109 /* FIXME: there is still a race here */
1111 RtlEnterCriticalSection( &loader_section );
1113 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1115 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1116 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1118 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1119 InInitializationOrderModuleList);
1120 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1121 continue;
1122 if ( mod->Flags & LDR_NO_DLL_CALLS )
1123 continue;
1125 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1126 DLL_THREAD_ATTACH, lpReserved );
1129 done:
1130 RtlLeaveCriticalSection( &loader_section );
1131 return status;
1134 /******************************************************************
1135 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1138 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1140 WINE_MODREF *wm;
1141 NTSTATUS ret = STATUS_SUCCESS;
1143 RtlEnterCriticalSection( &loader_section );
1145 wm = get_modref( hModule );
1146 if (!wm || wm->ldr.TlsIndex != -1)
1147 ret = STATUS_DLL_NOT_FOUND;
1148 else
1149 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1151 RtlLeaveCriticalSection( &loader_section );
1153 return ret;
1156 /******************************************************************
1157 * LdrFindEntryForAddress (NTDLL.@)
1159 * The loader_section must be locked while calling this function
1161 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1163 PLIST_ENTRY mark, entry;
1164 PLDR_MODULE mod;
1166 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1167 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1169 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1170 if ((const void *)mod->BaseAddress <= addr &&
1171 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1173 *pmod = mod;
1174 return STATUS_SUCCESS;
1176 if ((const void *)mod->BaseAddress > addr) break;
1178 return STATUS_NO_MORE_ENTRIES;
1181 /******************************************************************
1182 * LdrLockLoaderLock (NTDLL.@)
1184 * Note: flags are not implemented.
1185 * Flag 0x01 is used to raise exceptions on errors.
1186 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1188 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1190 if (flags) FIXME( "flags %x not supported\n", flags );
1192 if (result) *result = 1;
1193 if (!magic) return STATUS_INVALID_PARAMETER_3;
1194 RtlEnterCriticalSection( &loader_section );
1195 *magic = GetCurrentThreadId();
1196 return STATUS_SUCCESS;
1200 /******************************************************************
1201 * LdrUnlockLoaderUnlock (NTDLL.@)
1203 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1205 if (magic)
1207 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1208 RtlLeaveCriticalSection( &loader_section );
1210 return STATUS_SUCCESS;
1214 /******************************************************************
1215 * LdrGetProcedureAddress (NTDLL.@)
1217 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1218 ULONG ord, PVOID *address)
1220 IMAGE_EXPORT_DIRECTORY *exports;
1221 DWORD exp_size;
1222 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1224 RtlEnterCriticalSection( &loader_section );
1226 /* check if the module itself is invalid to return the proper error */
1227 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1228 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1229 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1231 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1232 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1233 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1234 if (proc)
1236 *address = proc;
1237 ret = STATUS_SUCCESS;
1241 RtlLeaveCriticalSection( &loader_section );
1242 return ret;
1246 /***********************************************************************
1247 * is_fake_dll
1249 * Check if a loaded native dll is a Wine fake dll.
1251 static BOOL is_fake_dll( HANDLE handle )
1253 static const char fakedll_signature[] = "Wine placeholder DLL";
1254 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1255 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1256 IO_STATUS_BLOCK io;
1257 LARGE_INTEGER offset;
1259 offset.QuadPart = 0;
1260 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1261 if (io.Information < sizeof(buffer)) return FALSE;
1262 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1263 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1264 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1265 return FALSE;
1269 /***********************************************************************
1270 * get_builtin_fullname
1272 * Build the full pathname for a builtin dll.
1274 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1276 static const WCHAR soW[] = {'.','s','o',0};
1277 WCHAR *p, *fullname;
1278 size_t i, len = strlen(filename);
1280 /* check if path can correspond to the dll we have */
1281 if (path && (p = strrchrW( path, '\\' )))
1283 p++;
1284 for (i = 0; i < len; i++)
1285 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1286 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1288 /* the filename matches, use path as the full path */
1289 len += p - path;
1290 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1292 memcpy( fullname, path, len * sizeof(WCHAR) );
1293 fullname[len] = 0;
1295 return fullname;
1299 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1300 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1302 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1303 p = fullname + system_dir.Length / sizeof(WCHAR);
1304 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1305 ascii_to_unicode( p, filename, len + 1 );
1307 return fullname;
1311 /***********************************************************************
1312 * load_builtin_callback
1314 * Load a library in memory; callback function for wine_dll_register
1316 static void load_builtin_callback( void *module, const char *filename )
1318 static const WCHAR emptyW[1];
1319 void *addr;
1320 IMAGE_NT_HEADERS *nt;
1321 WINE_MODREF *wm;
1322 WCHAR *fullname;
1323 const WCHAR *load_path;
1324 SIZE_T size;
1326 if (!module)
1328 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1329 return;
1331 if (!(nt = RtlImageNtHeader( module )))
1333 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1334 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1335 return;
1337 addr = module;
1338 size = nt->OptionalHeader.SizeOfImage;
1339 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
1340 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1341 /* create the MODREF */
1343 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1345 ERR( "can't load %s\n", filename );
1346 builtin_load_info->status = STATUS_NO_MEMORY;
1347 return;
1350 wm = alloc_module( module, fullname );
1351 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1352 if (!wm)
1354 ERR( "can't load %s\n", filename );
1355 builtin_load_info->status = STATUS_NO_MEMORY;
1356 return;
1358 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1360 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1361 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1363 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1365 else
1367 /* fixup imports */
1369 load_path = builtin_load_info->load_path;
1370 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1371 if (!load_path) load_path = emptyW;
1372 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1374 /* the module has only be inserted in the load & memory order lists */
1375 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1376 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1377 /* FIXME: free the modref */
1378 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1379 return;
1383 builtin_load_info->wm = wm;
1384 TRACE( "loaded %s %p %p\n", filename, wm, module );
1386 /* send the DLL load event */
1388 SERVER_START_REQ( load_dll )
1390 req->handle = 0;
1391 req->base = module;
1392 req->size = nt->OptionalHeader.SizeOfImage;
1393 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1394 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1395 req->name = &wm->ldr.FullDllName.Buffer;
1396 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1397 wine_server_call( req );
1399 SERVER_END_REQ;
1401 /* setup relay debugging entry points */
1402 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1406 /******************************************************************************
1407 * load_native_dll (internal)
1409 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1410 DWORD flags, WINE_MODREF** pwm )
1412 void *module;
1413 HANDLE mapping;
1414 OBJECT_ATTRIBUTES attr;
1415 LARGE_INTEGER size;
1416 IMAGE_NT_HEADERS *nt;
1417 SIZE_T len = 0;
1418 WINE_MODREF *wm;
1419 NTSTATUS status;
1421 TRACE("Trying native dll %s\n", debugstr_w(name));
1423 attr.Length = sizeof(attr);
1424 attr.RootDirectory = 0;
1425 attr.ObjectName = NULL;
1426 attr.Attributes = 0;
1427 attr.SecurityDescriptor = NULL;
1428 attr.SecurityQualityOfService = NULL;
1429 size.QuadPart = 0;
1431 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1432 &attr, &size, 0, SEC_IMAGE, file );
1433 if (status != STATUS_SUCCESS) return status;
1435 module = NULL;
1436 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1437 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1438 NtClose( mapping );
1439 if (status != STATUS_SUCCESS) return status;
1441 /* create the MODREF */
1443 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1445 /* fixup imports */
1447 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1449 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1451 /* the module has only be inserted in the load & memory order lists */
1452 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1453 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1455 /* FIXME: there are several more dangling references
1456 * left. Including dlls loaded by this dll before the
1457 * failed one. Unrolling is rather difficult with the
1458 * current structure and we can leave them lying
1459 * around with no problems, so we don't care.
1460 * As these might reference our wm, we don't free it.
1462 return status;
1466 /* send DLL load event */
1468 nt = RtlImageNtHeader( module );
1470 SERVER_START_REQ( load_dll )
1472 req->handle = file;
1473 req->base = module;
1474 req->size = nt->OptionalHeader.SizeOfImage;
1475 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1476 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1477 req->name = &wm->ldr.FullDllName.Buffer;
1478 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1479 wine_server_call( req );
1481 SERVER_END_REQ;
1483 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1485 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1487 wm->ldr.LoadCount = 1;
1488 *pwm = wm;
1489 return STATUS_SUCCESS;
1493 /***********************************************************************
1494 * load_builtin_dll
1496 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1497 DWORD flags, WINE_MODREF** pwm )
1499 char error[256], dllname[MAX_PATH];
1500 const WCHAR *name, *p;
1501 DWORD len, i;
1502 void *handle = NULL;
1503 struct builtin_load_info info, *prev_info;
1505 /* Fix the name in case we have a full path and extension */
1506 name = path;
1507 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1508 if ((p = strrchrW( name, '/' ))) name = p + 1;
1510 /* load_library will modify info.status. Note also that load_library can be
1511 * called several times, if the .so file we're loading has dependencies.
1512 * info.status will gather all the errors we may get while loading all these
1513 * libraries
1515 info.load_path = load_path;
1516 info.filename = NULL;
1517 info.status = STATUS_SUCCESS;
1518 info.wm = NULL;
1520 if (file) /* we have a real file, try to load it */
1522 UNICODE_STRING nt_name;
1523 ANSI_STRING unix_name;
1525 TRACE("Trying built-in %s\n", debugstr_w(path));
1527 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1528 return STATUS_DLL_NOT_FOUND;
1530 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1532 RtlFreeUnicodeString( &nt_name );
1533 return STATUS_DLL_NOT_FOUND;
1535 prev_info = builtin_load_info;
1536 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1537 builtin_load_info = &info;
1538 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1539 builtin_load_info = prev_info;
1540 RtlFreeUnicodeString( &nt_name );
1541 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1542 if (!handle)
1544 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1545 return STATUS_INVALID_IMAGE_FORMAT;
1548 else
1550 int file_exists;
1552 TRACE("Trying built-in %s\n", debugstr_w(name));
1554 /* we don't want to depend on the current codepage here */
1555 len = strlenW( name ) + 1;
1556 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1557 for (i = 0; i < len; i++)
1559 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1560 dllname[i] = (char)name[i];
1561 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1564 prev_info = builtin_load_info;
1565 builtin_load_info = &info;
1566 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1567 builtin_load_info = prev_info;
1568 if (!handle)
1570 if (!file_exists)
1572 /* The file does not exist -> WARN() */
1573 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1574 return STATUS_DLL_NOT_FOUND;
1576 /* ERR() for all other errors (missing functions, ...) */
1577 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1578 return STATUS_PROCEDURE_NOT_FOUND;
1582 if (info.status != STATUS_SUCCESS)
1584 wine_dll_unload( handle );
1585 return info.status;
1588 if (!info.wm)
1590 PLIST_ENTRY mark, entry;
1592 /* The constructor wasn't called, this means the .so is already
1593 * loaded under a different name. Try to find the wm for it. */
1595 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1596 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1598 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1599 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1601 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1602 TRACE( "Found %s at %p for builtin %s\n",
1603 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1604 break;
1607 wine_dll_unload( handle ); /* release the libdl refcount */
1608 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1609 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1611 else
1613 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1614 info.wm->ldr.LoadCount = 1;
1615 info.wm->ldr.SectionHandle = handle;
1618 *pwm = info.wm;
1619 return STATUS_SUCCESS;
1623 /***********************************************************************
1624 * find_actctx_dll
1626 * Find the full path (if any) of the dll from the activation context.
1628 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1630 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1631 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1633 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1634 ACTCTX_SECTION_KEYED_DATA data;
1635 UNICODE_STRING nameW;
1636 NTSTATUS status;
1637 SIZE_T needed, size = 1024;
1638 WCHAR *p;
1640 RtlInitUnicodeString( &nameW, libname );
1641 data.cbSize = sizeof(data);
1642 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1643 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1644 &nameW, &data );
1645 if (status != STATUS_SUCCESS) return status;
1647 for (;;)
1649 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1651 status = STATUS_NO_MEMORY;
1652 goto done;
1654 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1655 AssemblyDetailedInformationInActivationContext,
1656 info, size, &needed );
1657 if (status == STATUS_SUCCESS) break;
1658 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1659 RtlFreeHeap( GetProcessHeap(), 0, info );
1660 size = needed;
1661 /* restart with larger buffer */
1664 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1666 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1668 p++;
1669 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1671 /* manifest name does not match directory name, so it's not a global
1672 * windows/winsxs manifest; use the manifest directory name instead */
1673 dirlen = p - info->lpAssemblyManifestPath;
1674 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1675 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1677 status = STATUS_NO_MEMORY;
1678 goto done;
1680 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1681 p += dirlen;
1682 strcpyW( p, libname );
1683 goto done;
1687 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1688 nameW.Length + 2*sizeof(WCHAR));
1690 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1692 status = STATUS_NO_MEMORY;
1693 goto done;
1695 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1696 p += windows_dir.Length / sizeof(WCHAR);
1697 memcpy( p, winsxsW, sizeof(winsxsW) );
1698 p += sizeof(winsxsW) / sizeof(WCHAR);
1699 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1700 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1701 *p++ = '\\';
1702 strcpyW( p, libname );
1703 done:
1704 RtlFreeHeap( GetProcessHeap(), 0, info );
1705 RtlReleaseActivationContext( data.hActCtx );
1706 return status;
1710 /***********************************************************************
1711 * find_dll_file
1713 * Find the file (or already loaded module) for a given dll name.
1715 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1716 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1718 OBJECT_ATTRIBUTES attr;
1719 IO_STATUS_BLOCK io;
1720 UNICODE_STRING nt_name;
1721 WCHAR *file_part, *ext, *dllname;
1722 ULONG len;
1724 /* first append .dll if needed */
1726 dllname = NULL;
1727 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1729 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1730 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1731 return STATUS_NO_MEMORY;
1732 strcpyW( dllname, libname );
1733 strcatW( dllname, dllW );
1734 libname = dllname;
1737 nt_name.Buffer = NULL;
1739 if (!contains_path( libname ))
1741 NTSTATUS status;
1742 WCHAR *fullname = NULL;
1744 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1746 status = find_actctx_dll( libname, &fullname );
1747 if (status == STATUS_SUCCESS)
1749 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1750 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1751 libname = dllname = fullname;
1753 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1755 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1756 return status;
1760 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1762 /* we need to search for it */
1763 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1764 if (len)
1766 if (len >= *size) goto overflow;
1767 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1769 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1771 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1772 return STATUS_NO_MEMORY;
1774 attr.Length = sizeof(attr);
1775 attr.RootDirectory = 0;
1776 attr.Attributes = OBJ_CASE_INSENSITIVE;
1777 attr.ObjectName = &nt_name;
1778 attr.SecurityDescriptor = NULL;
1779 attr.SecurityQualityOfService = NULL;
1780 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1781 goto found;
1784 /* not found */
1786 if (!contains_path( libname ))
1788 /* if libname doesn't contain a path at all, we simply return the name as is,
1789 * to be loaded as builtin */
1790 len = strlenW(libname) * sizeof(WCHAR);
1791 if (len >= *size) goto overflow;
1792 strcpyW( filename, libname );
1793 goto found;
1797 /* absolute path name, or relative path name but not found above */
1799 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1801 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1802 return STATUS_NO_MEMORY;
1804 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1805 if (len >= *size) goto overflow;
1806 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1807 if (!(*pwm = find_fullname_module( filename )) && handle)
1809 attr.Length = sizeof(attr);
1810 attr.RootDirectory = 0;
1811 attr.Attributes = OBJ_CASE_INSENSITIVE;
1812 attr.ObjectName = &nt_name;
1813 attr.SecurityDescriptor = NULL;
1814 attr.SecurityQualityOfService = NULL;
1815 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1817 found:
1818 RtlFreeUnicodeString( &nt_name );
1819 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1820 return STATUS_SUCCESS;
1822 overflow:
1823 RtlFreeUnicodeString( &nt_name );
1824 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1825 *size = len + sizeof(WCHAR);
1826 return STATUS_BUFFER_TOO_SMALL;
1830 /***********************************************************************
1831 * load_dll (internal)
1833 * Load a PE style module according to the load order.
1834 * The loader_section must be locked while calling this function.
1836 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1838 enum loadorder loadorder;
1839 WCHAR buffer[32];
1840 WCHAR *filename;
1841 ULONG size;
1842 WINE_MODREF *main_exe;
1843 HANDLE handle = 0;
1844 NTSTATUS nts;
1846 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1848 *pwm = NULL;
1849 filename = buffer;
1850 size = sizeof(buffer);
1851 for (;;)
1853 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1854 if (nts == STATUS_SUCCESS) break;
1855 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1856 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1857 /* grow the buffer and retry */
1858 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1861 if (*pwm) /* found already loaded module */
1863 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1865 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1867 TRACE("Found %s for %s at %p, count=%d\n",
1868 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1869 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1870 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1871 return STATUS_SUCCESS;
1874 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1875 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1877 if (handle && is_fake_dll( handle ))
1879 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1880 NtClose( handle );
1881 handle = 0;
1884 switch(loadorder)
1886 case LO_INVALID:
1887 nts = STATUS_NO_MEMORY;
1888 break;
1889 case LO_DISABLED:
1890 nts = STATUS_DLL_NOT_FOUND;
1891 break;
1892 case LO_NATIVE:
1893 case LO_NATIVE_BUILTIN:
1894 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1895 else
1897 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1898 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1899 /* not in PE format, maybe it's a builtin */
1900 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1902 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1903 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1904 break;
1905 case LO_BUILTIN:
1906 case LO_BUILTIN_NATIVE:
1907 case LO_DEFAULT: /* default is builtin,native */
1908 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1909 if (!handle) break; /* nothing else we can try */
1910 /* file is not a builtin library, try without using the specified file */
1911 if (nts != STATUS_SUCCESS)
1912 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1913 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1914 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1916 /* stub-only dll, try native */
1917 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1918 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1919 nts = STATUS_DLL_NOT_FOUND;
1921 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1922 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1923 break;
1926 if (nts == STATUS_SUCCESS)
1928 /* Initialize DLL just loaded */
1929 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1930 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1931 (*pwm)->ldr.BaseAddress);
1932 if (handle) NtClose( handle );
1933 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1934 return nts;
1937 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1938 if (handle) NtClose( handle );
1939 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1940 return nts;
1943 /******************************************************************
1944 * LdrLoadDll (NTDLL.@)
1946 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1947 const UNICODE_STRING *libname, HMODULE* hModule)
1949 WINE_MODREF *wm;
1950 NTSTATUS nts;
1952 RtlEnterCriticalSection( &loader_section );
1954 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1955 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1957 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1959 nts = process_attach( wm, NULL );
1960 if (nts != STATUS_SUCCESS)
1962 LdrUnloadDll(wm->ldr.BaseAddress);
1963 wm = NULL;
1966 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1968 RtlLeaveCriticalSection( &loader_section );
1969 return nts;
1973 /******************************************************************
1974 * LdrGetDllHandle (NTDLL.@)
1976 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
1978 NTSTATUS status;
1979 WCHAR buffer[128];
1980 WCHAR *filename;
1981 ULONG size;
1982 WINE_MODREF *wm;
1984 RtlEnterCriticalSection( &loader_section );
1986 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1988 filename = buffer;
1989 size = sizeof(buffer);
1990 for (;;)
1992 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
1993 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1994 if (status != STATUS_BUFFER_TOO_SMALL) break;
1995 /* grow the buffer and retry */
1996 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1998 status = STATUS_NO_MEMORY;
1999 break;
2003 if (status == STATUS_SUCCESS)
2005 if (wm) *base = wm->ldr.BaseAddress;
2006 else status = STATUS_DLL_NOT_FOUND;
2009 RtlLeaveCriticalSection( &loader_section );
2010 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2011 return status;
2015 /******************************************************************
2016 * LdrAddRefDll (NTDLL.@)
2018 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2020 NTSTATUS ret = STATUS_SUCCESS;
2021 WINE_MODREF *wm;
2023 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2025 RtlEnterCriticalSection( &loader_section );
2027 if ((wm = get_modref( module )))
2029 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2030 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2032 else ret = STATUS_INVALID_PARAMETER;
2034 RtlLeaveCriticalSection( &loader_section );
2035 return ret;
2039 /***********************************************************************
2040 * LdrProcessRelocationBlock (NTDLL.@)
2042 * Apply relocations to a given page of a mapped PE image.
2044 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2045 USHORT *relocs, INT delta )
2047 while (count--)
2049 USHORT offset = *relocs & 0xfff;
2050 int type = *relocs >> 12;
2051 switch(type)
2053 case IMAGE_REL_BASED_ABSOLUTE:
2054 break;
2055 case IMAGE_REL_BASED_HIGH:
2056 *(short *)((char *)page + offset) += HIWORD(delta);
2057 break;
2058 case IMAGE_REL_BASED_LOW:
2059 *(short *)((char *)page + offset) += LOWORD(delta);
2060 break;
2061 case IMAGE_REL_BASED_HIGHLOW:
2062 *(int *)((char *)page + offset) += delta;
2063 break;
2064 default:
2065 FIXME("Unknown/unsupported fixup type %x.\n", type);
2066 return NULL;
2068 relocs++;
2070 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2074 /******************************************************************
2075 * LdrQueryProcessModuleInformation
2078 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2079 ULONG buf_size, ULONG* req_size)
2081 SYSTEM_MODULE* sm = &smi->Modules[0];
2082 ULONG size = sizeof(ULONG);
2083 NTSTATUS nts = STATUS_SUCCESS;
2084 ANSI_STRING str;
2085 char* ptr;
2086 PLIST_ENTRY mark, entry;
2087 PLDR_MODULE mod;
2088 WORD id = 0;
2090 smi->ModulesCount = 0;
2092 RtlEnterCriticalSection( &loader_section );
2093 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2094 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2096 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2097 size += sizeof(*sm);
2098 if (size <= buf_size)
2100 sm->Reserved1 = 0; /* FIXME */
2101 sm->Reserved2 = 0; /* FIXME */
2102 sm->ImageBaseAddress = mod->BaseAddress;
2103 sm->ImageSize = mod->SizeOfImage;
2104 sm->Flags = mod->Flags;
2105 sm->Id = id++;
2106 sm->Rank = 0; /* FIXME */
2107 sm->Unknown = 0; /* FIXME */
2108 str.Length = 0;
2109 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2110 str.Buffer = (char*)sm->Name;
2111 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2112 ptr = strrchr(str.Buffer, '\\');
2113 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2115 smi->ModulesCount++;
2116 sm++;
2118 else nts = STATUS_INFO_LENGTH_MISMATCH;
2120 RtlLeaveCriticalSection( &loader_section );
2122 if (req_size) *req_size = size;
2124 return nts;
2128 /******************************************************************
2129 * RtlDllShutdownInProgress (NTDLL.@)
2131 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2133 return process_detaching;
2137 /******************************************************************
2138 * LdrShutdownProcess (NTDLL.@)
2141 void WINAPI LdrShutdownProcess(void)
2143 TRACE("()\n");
2144 process_detach( TRUE, (LPVOID)1 );
2147 /******************************************************************
2148 * LdrShutdownThread (NTDLL.@)
2151 void WINAPI LdrShutdownThread(void)
2153 PLIST_ENTRY mark, entry;
2154 PLDR_MODULE mod;
2156 TRACE("()\n");
2158 /* don't do any detach calls if process is exiting */
2159 if (process_detaching) return;
2160 /* FIXME: there is still a race here */
2162 RtlEnterCriticalSection( &loader_section );
2164 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2165 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2167 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2168 InInitializationOrderModuleList);
2169 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2170 continue;
2171 if ( mod->Flags & LDR_NO_DLL_CALLS )
2172 continue;
2174 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2175 DLL_THREAD_DETACH, NULL );
2178 RtlLeaveCriticalSection( &loader_section );
2179 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2183 /***********************************************************************
2184 * free_modref
2187 static void free_modref( WINE_MODREF *wm )
2189 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2190 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2191 if (wm->ldr.InInitializationOrderModuleList.Flink)
2192 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2194 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2195 if (!TRACE_ON(module))
2196 TRACE_(loaddll)("Unloaded module %s : %s\n",
2197 debugstr_w(wm->ldr.FullDllName.Buffer),
2198 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2200 SERVER_START_REQ( unload_dll )
2202 req->base = wm->ldr.BaseAddress;
2203 wine_server_call( req );
2205 SERVER_END_REQ;
2207 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2208 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2209 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2210 if (cached_modref == wm) cached_modref = NULL;
2211 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2212 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2213 RtlFreeHeap( GetProcessHeap(), 0, wm );
2216 /***********************************************************************
2217 * MODULE_FlushModrefs
2219 * Remove all unused modrefs and call the internal unloading routines
2220 * for the library type.
2222 * The loader_section must be locked while calling this function.
2224 static void MODULE_FlushModrefs(void)
2226 PLIST_ENTRY mark, entry, prev;
2227 PLDR_MODULE mod;
2228 WINE_MODREF*wm;
2230 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2231 for (entry = mark->Blink; entry != mark; entry = prev)
2233 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2234 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2235 prev = entry->Blink;
2236 if (!mod->LoadCount) free_modref( wm );
2239 /* check load order list too for modules that haven't been initialized yet */
2240 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2241 for (entry = mark->Blink; entry != mark; entry = prev)
2243 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2244 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2245 prev = entry->Blink;
2246 if (!mod->LoadCount) free_modref( wm );
2250 /***********************************************************************
2251 * MODULE_DecRefCount
2253 * The loader_section must be locked while calling this function.
2255 static void MODULE_DecRefCount( WINE_MODREF *wm )
2257 int i;
2259 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2260 return;
2262 if ( wm->ldr.LoadCount <= 0 )
2263 return;
2265 --wm->ldr.LoadCount;
2266 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2268 if ( wm->ldr.LoadCount == 0 )
2270 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2272 for ( i = 0; i < wm->nDeps; i++ )
2273 if ( wm->deps[i] )
2274 MODULE_DecRefCount( wm->deps[i] );
2276 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2280 /******************************************************************
2281 * LdrUnloadDll (NTDLL.@)
2285 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2287 NTSTATUS retv = STATUS_SUCCESS;
2289 TRACE("(%p)\n", hModule);
2291 RtlEnterCriticalSection( &loader_section );
2293 /* if we're stopping the whole process (and forcing the removal of all
2294 * DLLs) the library will be freed anyway
2296 if (!process_detaching)
2298 WINE_MODREF *wm;
2300 free_lib_count++;
2301 if ((wm = get_modref( hModule )) != NULL)
2303 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2305 /* Recursively decrement reference counts */
2306 MODULE_DecRefCount( wm );
2308 /* Call process detach notifications */
2309 if ( free_lib_count <= 1 )
2311 process_detach( FALSE, NULL );
2312 MODULE_FlushModrefs();
2315 TRACE("END\n");
2317 else
2318 retv = STATUS_DLL_NOT_FOUND;
2320 free_lib_count--;
2323 RtlLeaveCriticalSection( &loader_section );
2325 return retv;
2328 /***********************************************************************
2329 * RtlImageNtHeader (NTDLL.@)
2331 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2333 IMAGE_NT_HEADERS *ret;
2335 __TRY
2337 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2339 ret = NULL;
2340 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2342 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2343 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2346 __EXCEPT_PAGE_FAULT
2348 return NULL;
2350 __ENDTRY
2351 return ret;
2355 /***********************************************************************
2356 * attach_process_dlls
2358 * Initial attach to all the dlls loaded by the process.
2360 static NTSTATUS attach_process_dlls( void *wm )
2362 NTSTATUS status;
2364 pthread_functions.sigprocmask( SIG_UNBLOCK, &server_block_set, NULL );
2366 RtlEnterCriticalSection( &loader_section );
2367 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2369 if (last_failed_modref)
2370 ERR( "%s failed to initialize, aborting\n",
2371 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2372 return status;
2374 attach_implicitly_loaded_dlls( (LPVOID)1 );
2375 RtlLeaveCriticalSection( &loader_section );
2376 return status;
2380 /******************************************************************
2381 * LdrInitializeThunk (NTDLL.@)
2384 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2386 NTSTATUS status;
2387 WINE_MODREF *wm;
2388 LPCWSTR load_path;
2389 SIZE_T stack_size;
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 stack_size = max( nt->OptionalHeader.SizeOfStackReserve, nt->OptionalHeader.SizeOfStackCommit );
2413 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
2415 if ((status = virtual_alloc_thread_stack( NULL, stack_size )) != STATUS_SUCCESS) goto error;
2416 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2418 actctx_init();
2419 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2420 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2421 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2422 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2423 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2425 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2426 if (status != STATUS_SUCCESS) goto error;
2428 virtual_clear_thread_stack();
2429 return;
2431 error:
2432 ERR( "Main exe initialization for %s failed, status %x\n",
2433 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2434 NtTerminateProcess( GetCurrentProcess(), status );
2438 /***********************************************************************
2439 * RtlImageDirectoryEntryToData (NTDLL.@)
2441 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2443 const IMAGE_NT_HEADERS *nt;
2444 DWORD addr;
2446 if ((ULONG_PTR)module & 1) /* mapped as data file */
2448 module = (HMODULE)((ULONG_PTR)module & ~1);
2449 image = FALSE;
2451 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2452 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2453 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2454 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2455 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2457 /* not mapped as image, need to find the section containing the virtual address */
2458 return RtlImageRvaToVa( nt, module, addr, NULL );
2462 /***********************************************************************
2463 * RtlImageRvaToSection (NTDLL.@)
2465 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2466 HMODULE module, DWORD rva )
2468 int i;
2469 const IMAGE_SECTION_HEADER *sec;
2471 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2472 nt->FileHeader.SizeOfOptionalHeader);
2473 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2475 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2476 return (PIMAGE_SECTION_HEADER)sec;
2478 return NULL;
2482 /***********************************************************************
2483 * RtlImageRvaToVa (NTDLL.@)
2485 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2486 DWORD rva, IMAGE_SECTION_HEADER **section )
2488 IMAGE_SECTION_HEADER *sec;
2490 if (section && *section) /* try this section first */
2492 sec = *section;
2493 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2494 goto found;
2496 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2497 found:
2498 if (section) *section = sec;
2499 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2503 /***********************************************************************
2504 * RtlPcToFileHeader (NTDLL.@)
2506 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2508 LDR_MODULE *module;
2509 PVOID ret = NULL;
2511 RtlEnterCriticalSection( &loader_section );
2512 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2513 RtlLeaveCriticalSection( &loader_section );
2514 *address = ret;
2515 return ret;
2519 /***********************************************************************
2520 * NtLoadDriver (NTDLL.@)
2521 * ZwLoadDriver (NTDLL.@)
2523 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2525 FIXME("(%p), stub!\n",DriverServiceName);
2526 return STATUS_NOT_IMPLEMENTED;
2530 /***********************************************************************
2531 * NtUnloadDriver (NTDLL.@)
2532 * ZwUnloadDriver (NTDLL.@)
2534 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2536 FIXME("(%p), stub!\n",DriverServiceName);
2537 return STATUS_NOT_IMPLEMENTED;
2541 /******************************************************************
2542 * DllMain (NTDLL.@)
2544 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2546 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2547 return TRUE;
2551 /******************************************************************
2552 * __wine_init_windows_dir (NTDLL.@)
2554 * Windows and system dir initialization once kernel32 has been loaded.
2556 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2558 PLIST_ENTRY mark, entry;
2559 LPWSTR buffer, p;
2561 RtlCreateUnicodeString( &windows_dir, windir );
2562 RtlCreateUnicodeString( &system_dir, sysdir );
2563 strcpyW( user_shared_data->NtSystemRoot, windir );
2565 /* prepend the system dir to the name of the already created modules */
2566 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2567 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2569 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2571 assert( mod->Flags & LDR_WINE_INTERNAL );
2573 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2574 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2575 if (!buffer) continue;
2576 strcpyW( buffer, system_dir.Buffer );
2577 p = buffer + strlenW( buffer );
2578 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2579 strcpyW( p, mod->FullDllName.Buffer );
2580 RtlInitUnicodeString( &mod->FullDllName, buffer );
2581 RtlInitUnicodeString( &mod->BaseDllName, p );
2586 /***********************************************************************
2587 * __wine_process_init
2589 void __wine_process_init(void)
2591 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2593 WINE_MODREF *wm;
2594 NTSTATUS status;
2595 ANSI_STRING func_name;
2596 void (* DECLSPEC_NORETURN init_func)(void);
2597 extern mode_t FILE_umask;
2599 main_exe_file = thread_init();
2601 /* retrieve current umask */
2602 FILE_umask = umask(0777);
2603 umask( FILE_umask );
2605 /* setup the load callback and create ntdll modref */
2606 wine_dll_set_callback( load_builtin_callback );
2608 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2610 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2611 exit(1);
2613 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2614 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2616 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2617 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2618 0, (void **)&init_func )) != STATUS_SUCCESS)
2620 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2621 exit(1);
2623 init_func();