wined3d: Allow to apply extension emulation wrappers independently.
[wine.git] / dlls / ntdll / loader.c
blobbef0ab1e503e9ed2ce385eb75a16eded00be757c
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 #include "ntstatus.h"
32 #define WIN32_NO_STATUS
33 #define NONAMELESSUNION
34 #include "windef.h"
35 #include "winnt.h"
36 #include "winternl.h"
37 #include "delayloadhandler.h"
39 #include "wine/exception.h"
40 #include "wine/library.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
44 #include "ntdll_misc.h"
45 #include "ddk/wdm.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 WINE_DECLARE_DEBUG_CHANNEL(snoop);
50 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
51 WINE_DECLARE_DEBUG_CHANNEL(imports);
53 /* we don't want to include winuser.h */
54 #define RT_MANIFEST ((ULONG_PTR)24)
55 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
57 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
59 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
60 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
62 static const char * const reason_names[] =
64 "PROCESS_DETACH",
65 "PROCESS_ATTACH",
66 "THREAD_ATTACH",
67 "THREAD_DETACH",
68 NULL, NULL, NULL, NULL,
69 "WINE_PREATTACH"
72 static const WCHAR dllW[] = {'.','d','l','l',0};
74 /* internal representation of 32bit modules. per process. */
75 typedef struct _wine_modref
77 LDR_MODULE ldr;
78 int nDeps;
79 struct _wine_modref **deps;
80 } WINE_MODREF;
82 /* info about the current builtin dll load */
83 /* used to keep track of things across the register_dll constructor call */
84 struct builtin_load_info
86 const WCHAR *load_path;
87 const WCHAR *filename;
88 NTSTATUS status;
89 WINE_MODREF *wm;
92 static struct builtin_load_info default_load_info;
93 static struct builtin_load_info *builtin_load_info = &default_load_info;
95 static HANDLE main_exe_file;
96 static UINT tls_module_count; /* number of modules with TLS directory */
97 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
98 LIST_ENTRY tls_links = { &tls_links, &tls_links };
100 static RTL_CRITICAL_SECTION loader_section;
101 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
103 0, 0, &loader_section,
104 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
105 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
107 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
109 static WINE_MODREF *cached_modref;
110 static WINE_MODREF *current_modref;
111 static WINE_MODREF *last_failed_modref;
113 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
114 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
115 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
116 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
117 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
118 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
120 /* convert PE image VirtualAddress to Real Address */
121 static inline void *get_rva( HMODULE module, DWORD va )
123 return (void *)((char *)module + va);
126 /* check whether the file name contains a path */
127 static inline BOOL contains_path( LPCWSTR name )
129 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
132 /* convert from straight ASCII to Unicode without depending on the current codepage */
133 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
135 while (len--) *dst++ = (unsigned char)*src++;
139 /*************************************************************************
140 * call_dll_entry_point
142 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
143 * their entry point, so we need a small asm wrapper. Testing indicates
144 * that only modifying esi leads to a crash, so use this one to backup
145 * ebp while running the dll entry proc.
147 #ifdef __i386__
148 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
149 __ASM_GLOBAL_FUNC(call_dll_entry_point,
150 "pushl %ebp\n\t"
151 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
152 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
153 "movl %esp,%ebp\n\t"
154 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
155 "pushl %ebx\n\t"
156 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
157 "pushl %esi\n\t"
158 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
159 "pushl %edi\n\t"
160 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
161 "movl %ebp,%esi\n\t"
162 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
163 "pushl 20(%ebp)\n\t"
164 "pushl 16(%ebp)\n\t"
165 "pushl 12(%ebp)\n\t"
166 "movl 8(%ebp),%eax\n\t"
167 "call *%eax\n\t"
168 "movl %esi,%ebp\n\t"
169 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
170 "leal -12(%ebp),%esp\n\t"
171 "popl %edi\n\t"
172 __ASM_CFI(".cfi_same_value %edi\n\t")
173 "popl %esi\n\t"
174 __ASM_CFI(".cfi_same_value %esi\n\t")
175 "popl %ebx\n\t"
176 __ASM_CFI(".cfi_same_value %ebx\n\t")
177 "popl %ebp\n\t"
178 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
179 __ASM_CFI(".cfi_same_value %ebp\n\t")
180 "ret" )
181 #else /* __i386__ */
182 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
183 UINT reason, void *reserved )
185 return proc( module, reason, reserved );
187 #endif /* __i386__ */
190 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
191 /*************************************************************************
192 * stub_entry_point
194 * Entry point for stub functions.
196 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
198 EXCEPTION_RECORD rec;
200 rec.ExceptionCode = EXCEPTION_WINE_STUB;
201 rec.ExceptionFlags = EH_NONCONTINUABLE;
202 rec.ExceptionRecord = NULL;
203 rec.ExceptionAddress = ret_addr;
204 rec.NumberParameters = 2;
205 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
206 rec.ExceptionInformation[1] = (ULONG_PTR)name;
207 for (;;) RtlRaiseException( &rec );
211 #include "pshpack1.h"
212 #ifdef __i386__
213 struct stub
215 BYTE pushl1; /* pushl $name */
216 const char *name;
217 BYTE pushl2; /* pushl $dll */
218 const char *dll;
219 BYTE call; /* call stub_entry_point */
220 DWORD entry;
222 #elif defined(__arm__)
223 struct stub
225 BYTE ldr_r0[4]; /* ldr r0, $dll */
226 BYTE mov_pc_pc1[4]; /* mov pc,pc */
227 const char *dll;
228 BYTE ldr_r1[4]; /* ldr r1, $name */
229 BYTE mov_pc_pc2[4]; /* mov pc,pc */
230 const char *name;
231 BYTE mov_r2_lr[4]; /* mov r2, lr */
232 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #-4] */
233 const void* entry;
235 #else
236 struct stub
238 BYTE movq_rdi[2]; /* movq $dll,%rdi */
239 const char *dll;
240 BYTE movq_rsi[2]; /* movq $name,%rsi */
241 const char *name;
242 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
243 BYTE movq_rax[2]; /* movq $entry, %rax */
244 const void* entry;
245 BYTE jmpq_rax[2]; /* jmp %rax */
247 #endif
248 #include "poppack.h"
250 /*************************************************************************
251 * allocate_stub
253 * Allocate a stub entry point.
255 static ULONG_PTR allocate_stub( const char *dll, const char *name )
257 #define MAX_SIZE 65536
258 static struct stub *stubs;
259 static unsigned int nb_stubs;
260 struct stub *stub;
262 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
264 if (!stubs)
266 SIZE_T size = MAX_SIZE;
267 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
268 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
269 return 0xdeadbeef;
271 stub = &stubs[nb_stubs++];
272 #ifdef __i386__
273 stub->pushl1 = 0x68; /* pushl $name */
274 stub->name = name;
275 stub->pushl2 = 0x68; /* pushl $dll */
276 stub->dll = dll;
277 stub->call = 0xe8; /* call stub_entry_point */
278 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
279 #elif defined(__arm__)
280 stub->ldr_r0[0] = 0x00; /* ldr r0, $dll */
281 stub->ldr_r0[1] = 0x00;
282 stub->ldr_r0[2] = 0x9f;
283 stub->ldr_r0[3] = 0xe5;
284 stub->mov_pc_pc1[0] = 0x0f; /* mov pc,pc */
285 stub->mov_pc_pc1[1] = 0xf0;
286 stub->mov_pc_pc1[2] = 0xa0;
287 stub->mov_pc_pc1[3] = 0xe1;
288 stub->dll = dll;
289 stub->ldr_r1[0] = 0x00; /* ldr r1, $name */
290 stub->ldr_r1[1] = 0x10;
291 stub->ldr_r1[2] = 0x9f;
292 stub->ldr_r1[3] = 0xe5;
293 stub->mov_pc_pc2[0] = 0x0f; /* mov pc,pc */
294 stub->mov_pc_pc2[1] = 0xf0;
295 stub->mov_pc_pc2[2] = 0xa0;
296 stub->mov_pc_pc2[3] = 0xe1;
297 stub->name = name;
298 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
299 stub->mov_r2_lr[1] = 0x20;
300 stub->mov_r2_lr[2] = 0xa0;
301 stub->mov_r2_lr[3] = 0xe1;
302 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #-4] */
303 stub->ldr_pc_pc[1] = 0xf0;
304 stub->ldr_pc_pc[2] = 0x1f;
305 stub->ldr_pc_pc[3] = 0xe5;
306 stub->entry = stub_entry_point;
307 #else
308 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
309 stub->movq_rdi[1] = 0xbf;
310 stub->dll = dll;
311 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
312 stub->movq_rsi[1] = 0xbe;
313 stub->name = name;
314 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
315 stub->movq_rsp_rdx[1] = 0x8b;
316 stub->movq_rsp_rdx[2] = 0x14;
317 stub->movq_rsp_rdx[3] = 0x24;
318 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
319 stub->movq_rax[1] = 0xb8;
320 stub->entry = stub_entry_point;
321 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
322 stub->jmpq_rax[1] = 0xe0;
323 #endif
324 return (ULONG_PTR)stub;
327 #else /* __i386__ */
328 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
329 #endif /* __i386__ */
332 /*************************************************************************
333 * get_modref
335 * Looks for the referenced HMODULE in the current process
336 * The loader_section must be locked while calling this function.
338 static WINE_MODREF *get_modref( HMODULE hmod )
340 PLIST_ENTRY mark, entry;
341 PLDR_MODULE mod;
343 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
345 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
346 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
348 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
349 if (mod->BaseAddress == hmod)
350 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
351 if (mod->BaseAddress > (void*)hmod) break;
353 return NULL;
357 /**********************************************************************
358 * find_basename_module
360 * Find a module from its base name.
361 * The loader_section must be locked while calling this function
363 static WINE_MODREF *find_basename_module( LPCWSTR name )
365 PLIST_ENTRY mark, entry;
367 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
368 return cached_modref;
370 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
371 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
373 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
374 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
376 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
377 return cached_modref;
380 return NULL;
384 /**********************************************************************
385 * find_fullname_module
387 * Find a module from its full path name.
388 * The loader_section must be locked while calling this function
390 static WINE_MODREF *find_fullname_module( LPCWSTR name )
392 PLIST_ENTRY mark, entry;
394 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
395 return cached_modref;
397 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
398 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
400 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
401 if (!strcmpiW( name, mod->FullDllName.Buffer ))
403 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
404 return cached_modref;
407 return NULL;
411 /*************************************************************************
412 * find_forwarded_export
414 * Find the final function pointer for a forwarded function.
415 * The loader_section must be locked while calling this function.
417 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
419 const IMAGE_EXPORT_DIRECTORY *exports;
420 DWORD exp_size;
421 WINE_MODREF *wm;
422 WCHAR mod_name[32];
423 const char *end = strrchr(forward, '.');
424 FARPROC proc = NULL;
426 if (!end) return NULL;
427 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
428 ascii_to_unicode( mod_name, forward, end - forward );
429 mod_name[end - forward] = 0;
430 if (!strchrW( mod_name, '.' ))
432 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
433 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
436 if (!(wm = find_basename_module( mod_name )))
438 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
439 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
440 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
442 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
444 LdrUnloadDll( wm->ldr.BaseAddress );
445 wm = NULL;
449 if (!wm)
451 ERR( "module not found for forward '%s' used by %s\n",
452 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
453 return NULL;
456 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
457 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
459 const char *name = end + 1;
460 if (*name == '#') /* ordinal */
461 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
462 else
463 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
466 if (!proc)
468 ERR("function not found for forward '%s' used by %s."
469 " If you are using builtin %s, try using the native one instead.\n",
470 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
471 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
473 return proc;
477 /*************************************************************************
478 * find_ordinal_export
480 * Find an exported function by ordinal.
481 * The exports base must have been subtracted from the ordinal already.
482 * The loader_section must be locked while calling this function.
484 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
485 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
487 FARPROC proc;
488 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
490 if (ordinal >= exports->NumberOfFunctions)
492 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
493 return NULL;
495 if (!functions[ordinal]) return NULL;
497 proc = get_rva( module, functions[ordinal] );
499 /* if the address falls into the export dir, it's a forward */
500 if (((const char *)proc >= (const char *)exports) &&
501 ((const char *)proc < (const char *)exports + exp_size))
502 return find_forwarded_export( module, (const char *)proc, load_path );
504 if (TRACE_ON(snoop))
506 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
507 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
509 if (TRACE_ON(relay))
511 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
512 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
514 return proc;
518 /*************************************************************************
519 * find_named_export
521 * Find an exported function by name.
522 * The loader_section must be locked while calling this function.
524 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
525 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
527 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
528 const DWORD *names = get_rva( module, exports->AddressOfNames );
529 int min = 0, max = exports->NumberOfNames - 1;
531 /* first check the hint */
532 if (hint >= 0 && hint <= max)
534 char *ename = get_rva( module, names[hint] );
535 if (!strcmp( ename, name ))
536 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
539 /* then do a binary search */
540 while (min <= max)
542 int res, pos = (min + max) / 2;
543 char *ename = get_rva( module, names[pos] );
544 if (!(res = strcmp( ename, name )))
545 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
546 if (res > 0) max = pos - 1;
547 else min = pos + 1;
549 return NULL;
554 /*************************************************************************
555 * import_dll
557 * Import the dll specified by the given import descriptor.
558 * The loader_section must be locked while calling this function.
560 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
562 NTSTATUS status;
563 WINE_MODREF *wmImp;
564 HMODULE imp_mod;
565 const IMAGE_EXPORT_DIRECTORY *exports;
566 DWORD exp_size;
567 const IMAGE_THUNK_DATA *import_list;
568 IMAGE_THUNK_DATA *thunk_list;
569 WCHAR buffer[32];
570 const char *name = get_rva( module, descr->Name );
571 DWORD len = strlen(name);
572 PVOID protect_base;
573 SIZE_T protect_size = 0;
574 DWORD protect_old;
576 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
577 if (descr->u.OriginalFirstThunk)
578 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
579 else
580 import_list = thunk_list;
582 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
584 if (len * sizeof(WCHAR) < sizeof(buffer))
586 ascii_to_unicode( buffer, name, len );
587 buffer[len] = 0;
588 status = load_dll( load_path, buffer, 0, &wmImp );
590 else /* need to allocate a larger buffer */
592 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
593 if (!ptr) return NULL;
594 ascii_to_unicode( ptr, name, len );
595 ptr[len] = 0;
596 status = load_dll( load_path, ptr, 0, &wmImp );
597 RtlFreeHeap( GetProcessHeap(), 0, ptr );
600 if (status)
602 if (status == STATUS_DLL_NOT_FOUND)
603 ERR("Library %s (which is needed by %s) not found\n",
604 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
605 else
606 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
607 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
608 return NULL;
611 /* unprotect the import address table since it can be located in
612 * readonly section */
613 while (import_list[protect_size].u1.Ordinal) protect_size++;
614 protect_base = thunk_list;
615 protect_size *= sizeof(*thunk_list);
616 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
617 &protect_size, PAGE_READWRITE, &protect_old );
619 imp_mod = wmImp->ldr.BaseAddress;
620 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
622 if (!exports)
624 /* set all imported function to deadbeef */
625 while (import_list->u1.Ordinal)
627 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
629 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
630 WARN("No implementation for %s.%d", name, ordinal );
631 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
633 else
635 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
636 WARN("No implementation for %s.%s", name, pe_name->Name );
637 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
639 WARN(" imported from %s, allocating stub %p\n",
640 debugstr_w(current_modref->ldr.FullDllName.Buffer),
641 (void *)thunk_list->u1.Function );
642 import_list++;
643 thunk_list++;
645 goto done;
648 while (import_list->u1.Ordinal)
650 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
652 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
654 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
655 ordinal - exports->Base, load_path );
656 if (!thunk_list->u1.Function)
658 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
659 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
660 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
661 (void *)thunk_list->u1.Function );
663 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
665 else /* import by name */
667 IMAGE_IMPORT_BY_NAME *pe_name;
668 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
669 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
670 (const char*)pe_name->Name,
671 pe_name->Hint, load_path );
672 if (!thunk_list->u1.Function)
674 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
675 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
676 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
677 (void *)thunk_list->u1.Function );
679 TRACE_(imports)("--- %s %s.%d = %p\n",
680 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
682 import_list++;
683 thunk_list++;
686 done:
687 /* restore old protection of the import address table */
688 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
689 return wmImp;
693 /***********************************************************************
694 * create_module_activation_context
696 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
698 NTSTATUS status;
699 LDR_RESOURCE_INFO info;
700 const IMAGE_RESOURCE_DATA_ENTRY *entry;
702 info.Type = RT_MANIFEST;
703 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
704 info.Language = 0;
705 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
707 ACTCTXW ctx;
708 ctx.cbSize = sizeof(ctx);
709 ctx.lpSource = NULL;
710 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
711 ctx.hModule = module->BaseAddress;
712 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
713 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
715 return status;
719 /*************************************************************************
720 * is_dll_native_subsystem
722 * Check if dll is a proper native driver.
723 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
724 * while being perfectly normal DLLs. This heuristic should catch such breakages.
726 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
728 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
729 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
730 const IMAGE_IMPORT_DESCRIPTOR *imports;
731 DWORD i, size;
732 WCHAR buffer[16];
734 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
735 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
737 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
738 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
740 for (i = 0; imports[i].Name; i++)
742 const char *name = get_rva( module, imports[i].Name );
743 DWORD len = strlen(name);
744 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
745 ascii_to_unicode( buffer, name, len + 1 );
746 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
748 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
749 return FALSE;
753 return TRUE;
756 /*************************************************************************
757 * alloc_tls_slot
759 * Allocate a TLS slot for a newly-loaded module.
760 * The loader_section must be locked while calling this function.
762 static SHORT alloc_tls_slot( LDR_MODULE *mod )
764 const IMAGE_TLS_DIRECTORY *dir;
765 ULONG i, size;
766 void *new_ptr;
767 LIST_ENTRY *entry;
769 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
770 return -1;
772 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
773 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
775 for (i = 0; i < tls_module_count; i++)
777 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
778 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
779 break;
782 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
783 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
784 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
786 if (i == tls_module_count)
788 UINT new_count = max( 32, tls_module_count * 2 );
790 if (!tls_dirs)
791 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
792 else
793 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
794 new_count * sizeof(*tls_dirs) );
795 if (!new_ptr) return -1;
797 /* resize the pointer block in all running threads */
798 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
800 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
801 void **old = teb->ThreadLocalStoragePointer;
802 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
804 if (!new) return -1;
805 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
806 teb->ThreadLocalStoragePointer = new;
807 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
808 /* FIXME: can't free old block here, should be freed at thread exit */
811 tls_dirs = new_ptr;
812 tls_module_count = new_count;
815 /* allocate the data block in all running threads */
816 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
818 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
820 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
821 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
822 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
824 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
825 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
827 RtlFreeHeap( GetProcessHeap(), 0,
828 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
831 *(DWORD *)dir->AddressOfIndex = i;
832 tls_dirs[i] = *dir;
833 return i;
837 /*************************************************************************
838 * free_tls_slot
840 * Free the module TLS slot on unload.
841 * The loader_section must be locked while calling this function.
843 static void free_tls_slot( LDR_MODULE *mod )
845 ULONG i = (USHORT)mod->TlsIndex;
847 if (mod->TlsIndex == -1) return;
848 assert( i < tls_module_count );
849 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
853 /****************************************************************
854 * fixup_imports
856 * Fixup all imports of a given module.
857 * The loader_section must be locked while calling this function.
859 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
861 int i, nb_imports;
862 const IMAGE_IMPORT_DESCRIPTOR *imports;
863 WINE_MODREF *prev;
864 DWORD size;
865 NTSTATUS status;
866 ULONG_PTR cookie;
868 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
869 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
871 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
873 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
874 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
875 return STATUS_SUCCESS;
877 nb_imports = 0;
878 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
880 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
882 if (!create_module_activation_context( &wm->ldr ))
883 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
885 /* Allocate module dependency list */
886 wm->nDeps = nb_imports;
887 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
889 /* load the imported modules. They are automatically
890 * added to the modref list of the process.
892 prev = current_modref;
893 current_modref = wm;
894 status = STATUS_SUCCESS;
895 for (i = 0; i < nb_imports; i++)
897 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
898 status = STATUS_DLL_NOT_FOUND;
900 current_modref = prev;
901 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
902 return status;
906 /*************************************************************************
907 * alloc_module
909 * Allocate a WINE_MODREF structure and add it to the process list
910 * The loader_section must be locked while calling this function.
912 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
914 WINE_MODREF *wm;
915 const WCHAR *p;
916 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
917 PLIST_ENTRY entry, mark;
919 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
921 wm->nDeps = 0;
922 wm->deps = NULL;
924 wm->ldr.BaseAddress = hModule;
925 wm->ldr.EntryPoint = NULL;
926 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
927 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
928 wm->ldr.TlsIndex = -1;
929 wm->ldr.LoadCount = 1;
930 wm->ldr.SectionHandle = NULL;
931 wm->ldr.CheckSum = 0;
932 wm->ldr.TimeDateStamp = 0;
933 wm->ldr.ActivationContext = 0;
935 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
936 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
937 else p = wm->ldr.FullDllName.Buffer;
938 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
940 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
942 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
943 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
944 if (nt->OptionalHeader.AddressOfEntryPoint)
945 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
948 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
949 &wm->ldr.InLoadOrderModuleList);
951 /* insert module in MemoryList, sorted in increasing base addresses */
952 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
953 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
955 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
956 break;
958 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
959 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
960 wm->ldr.InMemoryOrderModuleList.Flink = entry;
961 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
963 /* wait until init is called for inserting into this list */
964 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
965 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
967 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
969 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
970 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
971 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
973 return wm;
977 /*************************************************************************
978 * alloc_thread_tls
980 * Allocate the per-thread structure for module TLS storage.
982 static NTSTATUS alloc_thread_tls(void)
984 void **pointers;
985 UINT i, size;
987 if (!tls_module_count) return STATUS_SUCCESS;
989 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
990 tls_module_count * sizeof(*pointers) )))
991 return STATUS_NO_MEMORY;
993 for (i = 0; i < tls_module_count; i++)
995 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
997 if (!dir) continue;
998 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
999 if (!size && !dir->SizeOfZeroFill) continue;
1001 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1003 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1004 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1005 return STATUS_NO_MEMORY;
1007 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1008 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1010 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1011 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1013 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1014 return STATUS_SUCCESS;
1018 /*************************************************************************
1019 * call_tls_callbacks
1021 static void call_tls_callbacks( HMODULE module, UINT reason )
1023 const IMAGE_TLS_DIRECTORY *dir;
1024 const PIMAGE_TLS_CALLBACK *callback;
1025 ULONG dirsize;
1027 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1028 if (!dir || !dir->AddressOfCallBacks) return;
1030 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1032 if (TRACE_ON(relay))
1033 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1034 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1035 __TRY
1037 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1039 __EXCEPT_ALL
1041 if (TRACE_ON(relay))
1042 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1043 GetCurrentThreadId(), callback, module, reason_names[reason] );
1044 return;
1046 __ENDTRY
1047 if (TRACE_ON(relay))
1048 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1049 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1054 /*************************************************************************
1055 * MODULE_InitDLL
1057 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1059 WCHAR mod_name[32];
1060 NTSTATUS status = STATUS_SUCCESS;
1061 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1062 void *module = wm->ldr.BaseAddress;
1063 BOOL retv = FALSE;
1065 /* Skip calls for modules loaded with special load flags */
1067 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1068 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1069 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1071 if (TRACE_ON(relay))
1073 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1074 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1075 mod_name[len / sizeof(WCHAR)] = 0;
1076 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1077 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1078 reason_names[reason], lpReserved );
1080 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1081 reason_names[reason], lpReserved );
1083 __TRY
1085 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1086 if (!retv)
1087 status = STATUS_DLL_INIT_FAILED;
1089 __EXCEPT_ALL
1091 if (TRACE_ON(relay))
1092 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1093 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1094 status = GetExceptionCode();
1096 __ENDTRY
1098 /* The state of the module list may have changed due to the call
1099 to the dll. We cannot assume that this module has not been
1100 deleted. */
1101 if (TRACE_ON(relay))
1102 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1103 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1104 reason_names[reason], lpReserved, retv );
1105 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1107 return status;
1111 /*************************************************************************
1112 * process_attach
1114 * Send the process attach notification to all DLLs the given module
1115 * depends on (recursively). This is somewhat complicated due to the fact that
1117 * - we have to respect the module dependencies, i.e. modules implicitly
1118 * referenced by another module have to be initialized before the module
1119 * itself can be initialized
1121 * - the initialization routine of a DLL can itself call LoadLibrary,
1122 * thereby introducing a whole new set of dependencies (even involving
1123 * the 'old' modules) at any time during the whole process
1125 * (Note that this routine can be recursively entered not only directly
1126 * from itself, but also via LoadLibrary from one of the called initialization
1127 * routines.)
1129 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1130 * the process *detach* notifications to be sent in the correct order.
1131 * This must not only take into account module dependencies, but also
1132 * 'hidden' dependencies created by modules calling LoadLibrary in their
1133 * attach notification routine.
1135 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1136 * list after the attach notification has returned. This implies that the
1137 * detach notifications are called in the reverse of the sequence the attach
1138 * notifications *returned*.
1140 * The loader_section must be locked while calling this function.
1142 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1144 NTSTATUS status = STATUS_SUCCESS;
1145 ULONG_PTR cookie;
1146 int i;
1148 if (process_detaching) return status;
1150 /* prevent infinite recursion in case of cyclical dependencies */
1151 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1152 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1153 return status;
1155 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1157 /* Tag current MODREF to prevent recursive loop */
1158 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1159 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1160 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1162 /* Recursively attach all DLLs this one depends on */
1163 for ( i = 0; i < wm->nDeps; i++ )
1165 if (!wm->deps[i]) continue;
1166 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1169 /* Call DLL entry point */
1170 if (status == STATUS_SUCCESS)
1172 WINE_MODREF *prev = current_modref;
1173 current_modref = wm;
1174 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1175 if (status == STATUS_SUCCESS)
1176 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1177 else
1179 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1180 /* point to the name so LdrInitializeThunk can print it */
1181 last_failed_modref = wm;
1182 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1184 current_modref = prev;
1187 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1188 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1189 &wm->ldr.InInitializationOrderModuleList);
1191 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1192 /* Remove recursion flag */
1193 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1195 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1196 return status;
1200 /**********************************************************************
1201 * attach_implicitly_loaded_dlls
1203 * Attach to the (builtin) dlls that have been implicitly loaded because
1204 * of a dependency at the Unix level, but not imported at the Win32 level.
1206 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1208 for (;;)
1210 PLIST_ENTRY mark, entry;
1212 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1213 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1215 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1217 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1218 TRACE( "found implicitly loaded %s, attaching to it\n",
1219 debugstr_w(mod->BaseDllName.Buffer));
1220 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1221 break; /* restart the search from the start */
1223 if (entry == mark) break; /* nothing found */
1228 /*************************************************************************
1229 * process_detach
1231 * Send DLL process detach notifications. See the comment about calling
1232 * sequence at process_attach.
1234 static void process_detach(void)
1236 PLIST_ENTRY mark, entry;
1237 PLDR_MODULE mod;
1239 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1242 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1244 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1245 InInitializationOrderModuleList);
1246 /* Check whether to detach this DLL */
1247 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1248 continue;
1249 if ( mod->LoadCount && !process_detaching )
1250 continue;
1252 /* Call detach notification */
1253 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1254 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1255 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1257 /* Restart at head of WINE_MODREF list, as entries might have
1258 been added and/or removed while performing the call ... */
1259 break;
1261 } while (entry != mark);
1264 /*************************************************************************
1265 * MODULE_DllThreadAttach
1267 * Send DLL thread attach notifications. These are sent in the
1268 * reverse sequence of process detach notification.
1271 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1273 PLIST_ENTRY mark, entry;
1274 PLDR_MODULE mod;
1275 NTSTATUS status;
1277 /* don't do any attach calls if process is exiting */
1278 if (process_detaching) return STATUS_SUCCESS;
1280 RtlEnterCriticalSection( &loader_section );
1282 RtlAcquirePebLock();
1283 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1284 RtlReleasePebLock();
1286 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1288 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1289 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1291 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1292 InInitializationOrderModuleList);
1293 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1294 continue;
1295 if ( mod->Flags & LDR_NO_DLL_CALLS )
1296 continue;
1298 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1299 DLL_THREAD_ATTACH, lpReserved );
1302 done:
1303 RtlLeaveCriticalSection( &loader_section );
1304 return status;
1307 /******************************************************************
1308 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1311 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1313 WINE_MODREF *wm;
1314 NTSTATUS ret = STATUS_SUCCESS;
1316 RtlEnterCriticalSection( &loader_section );
1318 wm = get_modref( hModule );
1319 if (!wm || wm->ldr.TlsIndex != -1)
1320 ret = STATUS_DLL_NOT_FOUND;
1321 else
1322 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1324 RtlLeaveCriticalSection( &loader_section );
1326 return ret;
1329 /******************************************************************
1330 * LdrFindEntryForAddress (NTDLL.@)
1332 * The loader_section must be locked while calling this function
1334 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1336 PLIST_ENTRY mark, entry;
1337 PLDR_MODULE mod;
1339 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1340 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1342 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1343 if (mod->BaseAddress <= addr &&
1344 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1346 *pmod = mod;
1347 return STATUS_SUCCESS;
1349 if (mod->BaseAddress > addr) break;
1351 return STATUS_NO_MORE_ENTRIES;
1354 /******************************************************************
1355 * LdrLockLoaderLock (NTDLL.@)
1357 * Note: some flags are not implemented.
1358 * Flag 0x01 is used to raise exceptions on errors.
1360 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1362 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1364 if (result) *result = 0;
1365 if (magic) *magic = 0;
1366 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1367 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1368 if (!magic) return STATUS_INVALID_PARAMETER_3;
1370 if (flags & 0x2)
1372 if (!RtlTryEnterCriticalSection( &loader_section ))
1374 *result = 2;
1375 return STATUS_SUCCESS;
1377 *result = 1;
1379 else
1381 RtlEnterCriticalSection( &loader_section );
1382 if (result) *result = 1;
1384 *magic = GetCurrentThreadId();
1385 return STATUS_SUCCESS;
1389 /******************************************************************
1390 * LdrUnlockLoaderUnlock (NTDLL.@)
1392 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1394 if (magic)
1396 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1397 RtlLeaveCriticalSection( &loader_section );
1399 return STATUS_SUCCESS;
1403 /******************************************************************
1404 * LdrGetProcedureAddress (NTDLL.@)
1406 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1407 ULONG ord, PVOID *address)
1409 IMAGE_EXPORT_DIRECTORY *exports;
1410 DWORD exp_size;
1411 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1413 RtlEnterCriticalSection( &loader_section );
1415 /* check if the module itself is invalid to return the proper error */
1416 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1417 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1418 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1420 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1421 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1422 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1423 if (proc)
1425 *address = proc;
1426 ret = STATUS_SUCCESS;
1430 RtlLeaveCriticalSection( &loader_section );
1431 return ret;
1435 /***********************************************************************
1436 * is_fake_dll
1438 * Check if a loaded native dll is a Wine fake dll.
1440 static BOOL is_fake_dll( HANDLE handle )
1442 static const char fakedll_signature[] = "Wine placeholder DLL";
1443 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1444 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1445 IO_STATUS_BLOCK io;
1446 LARGE_INTEGER offset;
1448 offset.QuadPart = 0;
1449 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1450 if (io.Information < sizeof(buffer)) return FALSE;
1451 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1452 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1453 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1454 return FALSE;
1458 /***********************************************************************
1459 * get_builtin_fullname
1461 * Build the full pathname for a builtin dll.
1463 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1465 static const WCHAR soW[] = {'.','s','o',0};
1466 WCHAR *p, *fullname;
1467 size_t i, len = strlen(filename);
1469 /* check if path can correspond to the dll we have */
1470 if (path && (p = strrchrW( path, '\\' )))
1472 p++;
1473 for (i = 0; i < len; i++)
1474 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1475 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1477 /* the filename matches, use path as the full path */
1478 len += p - path;
1479 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1481 memcpy( fullname, path, len * sizeof(WCHAR) );
1482 fullname[len] = 0;
1484 return fullname;
1488 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1489 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1491 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1492 p = fullname + system_dir.Length / sizeof(WCHAR);
1493 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1494 ascii_to_unicode( p, filename, len + 1 );
1496 return fullname;
1500 /*************************************************************************
1501 * is_16bit_builtin
1503 static BOOL is_16bit_builtin( HMODULE module )
1505 const IMAGE_EXPORT_DIRECTORY *exports;
1506 DWORD exp_size;
1508 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1509 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1510 return FALSE;
1512 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1516 /***********************************************************************
1517 * load_builtin_callback
1519 * Load a library in memory; callback function for wine_dll_register
1521 static void load_builtin_callback( void *module, const char *filename )
1523 static const WCHAR emptyW[1];
1524 IMAGE_NT_HEADERS *nt;
1525 WINE_MODREF *wm;
1526 WCHAR *fullname;
1527 const WCHAR *load_path;
1529 if (!module)
1531 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1532 return;
1534 if (!(nt = RtlImageNtHeader( module )))
1536 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1537 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1538 return;
1541 virtual_create_builtin_view( module );
1543 /* create the MODREF */
1545 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1547 ERR( "can't load %s\n", filename );
1548 builtin_load_info->status = STATUS_NO_MEMORY;
1549 return;
1552 wm = alloc_module( module, fullname );
1553 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1554 if (!wm)
1556 ERR( "can't load %s\n", filename );
1557 builtin_load_info->status = STATUS_NO_MEMORY;
1558 return;
1560 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1562 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1563 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1564 is_16bit_builtin( module ))
1566 /* fixup imports */
1568 load_path = builtin_load_info->load_path;
1569 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1570 if (!load_path) load_path = emptyW;
1571 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1573 /* the module has only be inserted in the load & memory order lists */
1574 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1575 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1576 /* FIXME: free the modref */
1577 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1578 return;
1582 builtin_load_info->wm = wm;
1583 TRACE( "loaded %s %p %p\n", filename, wm, module );
1585 /* send the DLL load event */
1587 SERVER_START_REQ( load_dll )
1589 req->mapping = 0;
1590 req->base = wine_server_client_ptr( module );
1591 req->size = nt->OptionalHeader.SizeOfImage;
1592 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1593 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1594 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1595 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1596 wine_server_call( req );
1598 SERVER_END_REQ;
1600 /* setup relay debugging entry points */
1601 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1605 /******************************************************************************
1606 * load_native_dll (internal)
1608 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1609 DWORD flags, WINE_MODREF** pwm )
1611 void *module;
1612 HANDLE mapping;
1613 LARGE_INTEGER size;
1614 IMAGE_NT_HEADERS *nt;
1615 SIZE_T len = 0;
1616 WINE_MODREF *wm;
1617 NTSTATUS status;
1619 TRACE("Trying native dll %s\n", debugstr_w(name));
1621 size.QuadPart = 0;
1622 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1623 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1624 if (status != STATUS_SUCCESS) return status;
1626 module = NULL;
1627 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1628 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1629 if (status < 0) goto done;
1631 /* create the MODREF */
1633 if (!(wm = alloc_module( module, name )))
1635 status = STATUS_NO_MEMORY;
1636 goto done;
1639 /* fixup imports */
1641 nt = RtlImageNtHeader( module );
1643 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1644 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1645 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1647 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1649 /* the module has only be inserted in the load & memory order lists */
1650 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1651 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1653 /* FIXME: there are several more dangling references
1654 * left. Including dlls loaded by this dll before the
1655 * failed one. Unrolling is rather difficult with the
1656 * current structure and we can leave them lying
1657 * around with no problems, so we don't care.
1658 * As these might reference our wm, we don't free it.
1660 goto done;
1664 /* send DLL load event */
1666 SERVER_START_REQ( load_dll )
1668 req->mapping = wine_server_obj_handle( mapping );
1669 req->base = wine_server_client_ptr( module );
1670 req->size = nt->OptionalHeader.SizeOfImage;
1671 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1672 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1673 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1674 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1675 wine_server_call( req );
1677 SERVER_END_REQ;
1679 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1681 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1683 wm->ldr.LoadCount = 1;
1684 *pwm = wm;
1685 status = STATUS_SUCCESS;
1686 done:
1687 NtClose( mapping );
1688 return status;
1692 /***********************************************************************
1693 * load_builtin_dll
1695 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1696 DWORD flags, WINE_MODREF** pwm )
1698 char error[256], dllname[MAX_PATH];
1699 const WCHAR *name, *p;
1700 DWORD len, i;
1701 void *handle = NULL;
1702 struct builtin_load_info info, *prev_info;
1704 /* Fix the name in case we have a full path and extension */
1705 name = path;
1706 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1707 if ((p = strrchrW( name, '/' ))) name = p + 1;
1709 /* load_library will modify info.status. Note also that load_library can be
1710 * called several times, if the .so file we're loading has dependencies.
1711 * info.status will gather all the errors we may get while loading all these
1712 * libraries
1714 info.load_path = load_path;
1715 info.filename = NULL;
1716 info.status = STATUS_SUCCESS;
1717 info.wm = NULL;
1719 if (file) /* we have a real file, try to load it */
1721 UNICODE_STRING nt_name;
1722 ANSI_STRING unix_name;
1724 TRACE("Trying built-in %s\n", debugstr_w(path));
1726 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1727 return STATUS_DLL_NOT_FOUND;
1729 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1731 RtlFreeUnicodeString( &nt_name );
1732 return STATUS_DLL_NOT_FOUND;
1734 prev_info = builtin_load_info;
1735 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1736 builtin_load_info = &info;
1737 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1738 builtin_load_info = prev_info;
1739 RtlFreeUnicodeString( &nt_name );
1740 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1741 if (!handle)
1743 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1744 return STATUS_INVALID_IMAGE_FORMAT;
1747 else
1749 int file_exists;
1751 TRACE("Trying built-in %s\n", debugstr_w(name));
1753 /* we don't want to depend on the current codepage here */
1754 len = strlenW( name ) + 1;
1755 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1756 for (i = 0; i < len; i++)
1758 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1759 dllname[i] = (char)name[i];
1760 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1763 prev_info = builtin_load_info;
1764 builtin_load_info = &info;
1765 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1766 builtin_load_info = prev_info;
1767 if (!handle)
1769 if (!file_exists)
1771 /* The file does not exist -> WARN() */
1772 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1773 return STATUS_DLL_NOT_FOUND;
1775 /* ERR() for all other errors (missing functions, ...) */
1776 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1777 return STATUS_PROCEDURE_NOT_FOUND;
1781 if (info.status != STATUS_SUCCESS)
1783 wine_dll_unload( handle );
1784 return info.status;
1787 if (!info.wm)
1789 PLIST_ENTRY mark, entry;
1791 /* The constructor wasn't called, this means the .so is already
1792 * loaded under a different name. Try to find the wm for it. */
1794 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1795 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1797 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1798 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1800 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1801 TRACE( "Found %s at %p for builtin %s\n",
1802 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1803 break;
1806 wine_dll_unload( handle ); /* release the libdl refcount */
1807 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1808 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1810 else
1812 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1813 info.wm->ldr.LoadCount = 1;
1814 info.wm->ldr.SectionHandle = handle;
1817 *pwm = info.wm;
1818 return STATUS_SUCCESS;
1822 /***********************************************************************
1823 * find_actctx_dll
1825 * Find the full path (if any) of the dll from the activation context.
1827 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1829 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1830 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1832 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1833 ACTCTX_SECTION_KEYED_DATA data;
1834 UNICODE_STRING nameW;
1835 NTSTATUS status;
1836 SIZE_T needed, size = 1024;
1837 WCHAR *p;
1839 RtlInitUnicodeString( &nameW, libname );
1840 data.cbSize = sizeof(data);
1841 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1842 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1843 &nameW, &data );
1844 if (status != STATUS_SUCCESS) return status;
1846 for (;;)
1848 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1850 status = STATUS_NO_MEMORY;
1851 goto done;
1853 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1854 AssemblyDetailedInformationInActivationContext,
1855 info, size, &needed );
1856 if (status == STATUS_SUCCESS) break;
1857 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1858 RtlFreeHeap( GetProcessHeap(), 0, info );
1859 size = needed;
1860 /* restart with larger buffer */
1863 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1865 status = STATUS_SXS_KEY_NOT_FOUND;
1866 goto done;
1869 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1871 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1873 p++;
1874 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1876 /* manifest name does not match directory name, so it's not a global
1877 * windows/winsxs manifest; use the manifest directory name instead */
1878 dirlen = p - info->lpAssemblyManifestPath;
1879 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1880 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1882 status = STATUS_NO_MEMORY;
1883 goto done;
1885 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1886 p += dirlen;
1887 strcpyW( p, libname );
1888 goto done;
1892 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1893 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1895 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1897 status = STATUS_NO_MEMORY;
1898 goto done;
1900 strcpyW( p, user_shared_data->NtSystemRoot );
1901 p += strlenW(p);
1902 memcpy( p, winsxsW, sizeof(winsxsW) );
1903 p += sizeof(winsxsW) / sizeof(WCHAR);
1904 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1905 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1906 *p++ = '\\';
1907 strcpyW( p, libname );
1908 done:
1909 RtlFreeHeap( GetProcessHeap(), 0, info );
1910 RtlReleaseActivationContext( data.hActCtx );
1911 return status;
1915 /***********************************************************************
1916 * find_dll_file
1918 * Find the file (or already loaded module) for a given dll name.
1920 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1921 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1923 OBJECT_ATTRIBUTES attr;
1924 IO_STATUS_BLOCK io;
1925 UNICODE_STRING nt_name;
1926 WCHAR *file_part, *ext, *dllname;
1927 ULONG len;
1929 /* first append .dll if needed */
1931 dllname = NULL;
1932 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1934 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1935 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1936 return STATUS_NO_MEMORY;
1937 strcpyW( dllname, libname );
1938 strcatW( dllname, dllW );
1939 libname = dllname;
1942 nt_name.Buffer = NULL;
1944 if (!contains_path( libname ))
1946 NTSTATUS status;
1947 WCHAR *fullname = NULL;
1949 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1951 status = find_actctx_dll( libname, &fullname );
1952 if (status == STATUS_SUCCESS)
1954 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1955 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1956 libname = dllname = fullname;
1958 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1960 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1961 return status;
1965 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1967 /* we need to search for it */
1968 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1969 if (len)
1971 if (len >= *size) goto overflow;
1972 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1974 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1976 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1977 return STATUS_NO_MEMORY;
1979 attr.Length = sizeof(attr);
1980 attr.RootDirectory = 0;
1981 attr.Attributes = OBJ_CASE_INSENSITIVE;
1982 attr.ObjectName = &nt_name;
1983 attr.SecurityDescriptor = NULL;
1984 attr.SecurityQualityOfService = NULL;
1985 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
1986 goto found;
1989 /* not found */
1991 if (!contains_path( libname ))
1993 /* if libname doesn't contain a path at all, we simply return the name as is,
1994 * to be loaded as builtin */
1995 len = strlenW(libname) * sizeof(WCHAR);
1996 if (len >= *size) goto overflow;
1997 strcpyW( filename, libname );
1998 goto found;
2002 /* absolute path name, or relative path name but not found above */
2004 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2006 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2007 return STATUS_NO_MEMORY;
2009 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2010 if (len >= *size) goto overflow;
2011 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2012 if (!(*pwm = find_fullname_module( filename )) && handle)
2014 attr.Length = sizeof(attr);
2015 attr.RootDirectory = 0;
2016 attr.Attributes = OBJ_CASE_INSENSITIVE;
2017 attr.ObjectName = &nt_name;
2018 attr.SecurityDescriptor = NULL;
2019 attr.SecurityQualityOfService = NULL;
2020 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2022 found:
2023 RtlFreeUnicodeString( &nt_name );
2024 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2025 return STATUS_SUCCESS;
2027 overflow:
2028 RtlFreeUnicodeString( &nt_name );
2029 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2030 *size = len + sizeof(WCHAR);
2031 return STATUS_BUFFER_TOO_SMALL;
2035 /***********************************************************************
2036 * load_dll (internal)
2038 * Load a PE style module according to the load order.
2039 * The loader_section must be locked while calling this function.
2041 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2043 enum loadorder loadorder;
2044 WCHAR buffer[32];
2045 WCHAR *filename;
2046 ULONG size;
2047 WINE_MODREF *main_exe;
2048 HANDLE handle = 0;
2049 NTSTATUS nts;
2051 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2053 *pwm = NULL;
2054 filename = buffer;
2055 size = sizeof(buffer);
2056 for (;;)
2058 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2059 if (nts == STATUS_SUCCESS) break;
2060 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2061 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2062 /* grow the buffer and retry */
2063 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2066 if (*pwm) /* found already loaded module */
2068 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2070 TRACE("Found %s for %s at %p, count=%d\n",
2071 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2072 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2073 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2074 return STATUS_SUCCESS;
2077 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2078 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2080 if (handle && is_fake_dll( handle ))
2082 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2083 NtClose( handle );
2084 handle = 0;
2087 switch(loadorder)
2089 case LO_INVALID:
2090 nts = STATUS_NO_MEMORY;
2091 break;
2092 case LO_DISABLED:
2093 nts = STATUS_DLL_NOT_FOUND;
2094 break;
2095 case LO_NATIVE:
2096 case LO_NATIVE_BUILTIN:
2097 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2098 else
2100 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2101 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2102 /* not in PE format, maybe it's a builtin */
2103 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2105 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2106 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2107 break;
2108 case LO_BUILTIN:
2109 case LO_BUILTIN_NATIVE:
2110 case LO_DEFAULT: /* default is builtin,native */
2111 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2112 if (!handle) break; /* nothing else we can try */
2113 /* file is not a builtin library, try without using the specified file */
2114 if (nts != STATUS_SUCCESS)
2115 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2116 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2117 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2119 /* stub-only dll, try native */
2120 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2121 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2122 nts = STATUS_DLL_NOT_FOUND;
2124 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2125 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2126 break;
2129 if (nts == STATUS_SUCCESS)
2131 /* Initialize DLL just loaded */
2132 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2133 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2134 (*pwm)->ldr.BaseAddress);
2135 if (handle) NtClose( handle );
2136 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2137 return nts;
2140 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2141 if (handle) NtClose( handle );
2142 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2143 return nts;
2146 /******************************************************************
2147 * LdrLoadDll (NTDLL.@)
2149 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2150 const UNICODE_STRING *libname, HMODULE* hModule)
2152 WINE_MODREF *wm;
2153 NTSTATUS nts;
2155 RtlEnterCriticalSection( &loader_section );
2157 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2158 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2160 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2162 nts = process_attach( wm, NULL );
2163 if (nts != STATUS_SUCCESS)
2165 LdrUnloadDll(wm->ldr.BaseAddress);
2166 wm = NULL;
2169 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2171 RtlLeaveCriticalSection( &loader_section );
2172 return nts;
2176 /******************************************************************
2177 * LdrGetDllHandle (NTDLL.@)
2179 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2181 NTSTATUS status;
2182 WCHAR buffer[128];
2183 WCHAR *filename;
2184 ULONG size;
2185 WINE_MODREF *wm;
2187 RtlEnterCriticalSection( &loader_section );
2189 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2191 filename = buffer;
2192 size = sizeof(buffer);
2193 for (;;)
2195 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2196 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2197 if (status != STATUS_BUFFER_TOO_SMALL) break;
2198 /* grow the buffer and retry */
2199 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2201 status = STATUS_NO_MEMORY;
2202 break;
2206 if (status == STATUS_SUCCESS)
2208 if (wm) *base = wm->ldr.BaseAddress;
2209 else status = STATUS_DLL_NOT_FOUND;
2212 RtlLeaveCriticalSection( &loader_section );
2213 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2214 return status;
2218 /******************************************************************
2219 * LdrAddRefDll (NTDLL.@)
2221 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2223 NTSTATUS ret = STATUS_SUCCESS;
2224 WINE_MODREF *wm;
2226 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2228 RtlEnterCriticalSection( &loader_section );
2230 if ((wm = get_modref( module )))
2232 if (flags & LDR_ADDREF_DLL_PIN)
2233 wm->ldr.LoadCount = -1;
2234 else
2235 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2236 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2238 else ret = STATUS_INVALID_PARAMETER;
2240 RtlLeaveCriticalSection( &loader_section );
2241 return ret;
2245 /***********************************************************************
2246 * LdrProcessRelocationBlock (NTDLL.@)
2248 * Apply relocations to a given page of a mapped PE image.
2250 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2251 USHORT *relocs, INT_PTR delta )
2253 while (count--)
2255 USHORT offset = *relocs & 0xfff;
2256 int type = *relocs >> 12;
2257 switch(type)
2259 case IMAGE_REL_BASED_ABSOLUTE:
2260 break;
2261 case IMAGE_REL_BASED_HIGH:
2262 *(short *)((char *)page + offset) += HIWORD(delta);
2263 break;
2264 case IMAGE_REL_BASED_LOW:
2265 *(short *)((char *)page + offset) += LOWORD(delta);
2266 break;
2267 case IMAGE_REL_BASED_HIGHLOW:
2268 *(int *)((char *)page + offset) += delta;
2269 break;
2270 #ifdef __x86_64__
2271 case IMAGE_REL_BASED_DIR64:
2272 *(INT_PTR *)((char *)page + offset) += delta;
2273 break;
2274 #elif defined(__arm__)
2275 case IMAGE_REL_BASED_THUMB_MOV32:
2277 DWORD inst = *(INT_PTR *)((char *)page + offset);
2278 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2279 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2280 DWORD hi_delta;
2282 if ((inst & 0x8000fbf0) != 0x0000f240)
2283 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2285 imm16 += LOWORD(delta);
2286 hi_delta = HIWORD(delta) + HIWORD(imm16);
2287 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2288 ((imm16 >> 12) & 0x000f) +
2289 ((imm16 << 20) & 0x70000000) +
2290 ((imm16 << 16) & 0xff0000);
2292 if (hi_delta != 0)
2294 inst = *(INT_PTR *)((char *)page + offset + 4);
2295 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2296 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2298 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2299 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2301 imm16 += hi_delta;
2302 if (imm16 > 0xffff)
2303 ERR("resulting immediate value won't fit: %08x\n", imm16);
2304 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2305 ((imm16 >> 1) & 0x0400) +
2306 ((imm16 >> 12) & 0x000f) +
2307 ((imm16 << 20) & 0x70000000) +
2308 ((imm16 << 16) & 0xff0000);
2311 break;
2312 #endif
2313 default:
2314 FIXME("Unknown/unsupported fixup type %x.\n", type);
2315 return NULL;
2317 relocs++;
2319 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2323 /******************************************************************
2324 * LdrQueryProcessModuleInformation
2327 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2328 ULONG buf_size, ULONG* req_size)
2330 SYSTEM_MODULE* sm = &smi->Modules[0];
2331 ULONG size = sizeof(ULONG);
2332 NTSTATUS nts = STATUS_SUCCESS;
2333 ANSI_STRING str;
2334 char* ptr;
2335 PLIST_ENTRY mark, entry;
2336 PLDR_MODULE mod;
2337 WORD id = 0;
2339 smi->ModulesCount = 0;
2341 RtlEnterCriticalSection( &loader_section );
2342 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2343 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2345 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2346 size += sizeof(*sm);
2347 if (size <= buf_size)
2349 sm->Reserved1 = 0; /* FIXME */
2350 sm->Reserved2 = 0; /* FIXME */
2351 sm->ImageBaseAddress = mod->BaseAddress;
2352 sm->ImageSize = mod->SizeOfImage;
2353 sm->Flags = mod->Flags;
2354 sm->Id = id++;
2355 sm->Rank = 0; /* FIXME */
2356 sm->Unknown = 0; /* FIXME */
2357 str.Length = 0;
2358 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2359 str.Buffer = (char*)sm->Name;
2360 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2361 ptr = strrchr(str.Buffer, '\\');
2362 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2364 smi->ModulesCount++;
2365 sm++;
2367 else nts = STATUS_INFO_LENGTH_MISMATCH;
2369 RtlLeaveCriticalSection( &loader_section );
2371 if (req_size) *req_size = size;
2373 return nts;
2377 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2379 NTSTATUS status;
2380 UNICODE_STRING str;
2381 ULONG size;
2382 WCHAR buffer[64];
2383 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2385 RtlInitUnicodeString( &str, name );
2387 size = sizeof(buffer) - sizeof(WCHAR);
2388 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2389 return status;
2391 if (info->Type != REG_DWORD)
2393 buffer[size / sizeof(WCHAR)] = 0;
2394 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2396 else memcpy( value, info->Data, sizeof(*value) );
2397 return status;
2400 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2401 void *data, ULONG in_size, ULONG *out_size )
2403 NTSTATUS status;
2404 UNICODE_STRING str;
2405 ULONG size;
2406 char *buffer;
2407 KEY_VALUE_PARTIAL_INFORMATION *info;
2408 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2410 RtlInitUnicodeString( &str, name );
2412 size = info_size + in_size;
2413 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2414 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2415 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2416 if (!status || status == STATUS_BUFFER_OVERFLOW)
2418 if (out_size) *out_size = info->DataLength;
2419 if (data && !status) memcpy( data, info->Data, info->DataLength );
2421 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2422 return status;
2426 /******************************************************************
2427 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2429 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2430 void *data, ULONG in_size, ULONG *out_size )
2432 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2433 'S','o','f','t','w','a','r','e','\\',
2434 'M','i','c','r','o','s','o','f','t','\\',
2435 'W','i','n','d','o','w','s',' ','N','T','\\',
2436 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2437 'I','m','a','g','e',' ','F','i','l','e',' ',
2438 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2439 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2440 OBJECT_ATTRIBUTES attr;
2441 UNICODE_STRING name_str;
2442 HANDLE hkey;
2443 NTSTATUS status;
2444 ULONG len;
2445 WCHAR *p;
2447 attr.Length = sizeof(attr);
2448 attr.RootDirectory = 0;
2449 attr.ObjectName = &name_str;
2450 attr.Attributes = OBJ_CASE_INSENSITIVE;
2451 attr.SecurityDescriptor = NULL;
2452 attr.SecurityQualityOfService = NULL;
2454 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2455 else p = key->Buffer;
2456 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2457 name_str.Buffer = path;
2458 name_str.Length = sizeof(optionsW) + len;
2459 name_str.MaximumLength = name_str.Length;
2460 memcpy( path, optionsW, sizeof(optionsW) );
2461 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2462 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2464 if (type == REG_DWORD)
2466 if (out_size) *out_size = sizeof(ULONG);
2467 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2468 else status = STATUS_BUFFER_OVERFLOW;
2470 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2472 NtClose( hkey );
2473 return status;
2477 /******************************************************************
2478 * RtlDllShutdownInProgress (NTDLL.@)
2480 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2482 return process_detaching;
2485 /****************************************************************************
2486 * LdrResolveDelayLoadedAPI (NTDLL.@)
2488 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2489 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2490 IMAGE_THUNK_DATA* addr, ULONG flags )
2492 IMAGE_THUNK_DATA *pIAT, *pINT;
2493 DELAYLOAD_INFO delayinfo;
2494 UNICODE_STRING mod;
2495 const CHAR* name;
2496 HMODULE *phmod;
2497 NTSTATUS nts;
2498 FARPROC fp;
2499 DWORD id;
2501 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2503 phmod = get_rva(base, desc->ModuleHandleRVA);
2504 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2505 pINT = get_rva(base, desc->ImportNameTableRVA);
2506 name = get_rva(base, desc->DllNameRVA);
2507 id = addr - pIAT;
2509 if (!*phmod)
2511 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2513 nts = STATUS_NO_MEMORY;
2514 goto fail;
2516 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2517 RtlFreeUnicodeString(&mod);
2518 if (nts) goto fail;
2521 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2522 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2523 else
2525 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2526 ANSI_STRING fnc;
2528 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2529 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2531 if (!nts)
2533 pIAT[id].u1.Function = (ULONG_PTR)fp;
2534 return fp;
2537 fail:
2538 delayinfo.Size = sizeof(delayinfo);
2539 delayinfo.DelayloadDescriptor = desc;
2540 delayinfo.ThunkAddress = addr;
2541 delayinfo.TargetDllName = name;
2542 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2543 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2544 delayinfo.TargetModuleBase = *phmod;
2545 delayinfo.Unused = NULL;
2546 delayinfo.LastError = nts;
2547 return dllhook(4, &delayinfo);
2550 /******************************************************************
2551 * LdrShutdownProcess (NTDLL.@)
2554 void WINAPI LdrShutdownProcess(void)
2556 TRACE("()\n");
2557 process_detaching = TRUE;
2558 process_detach();
2562 /******************************************************************
2563 * RtlExitUserProcess (NTDLL.@)
2565 void WINAPI RtlExitUserProcess( DWORD status )
2567 RtlEnterCriticalSection( &loader_section );
2568 RtlAcquirePebLock();
2569 NtTerminateProcess( 0, status );
2570 LdrShutdownProcess();
2571 NtTerminateProcess( GetCurrentProcess(), status );
2572 exit( status );
2575 /******************************************************************
2576 * LdrShutdownThread (NTDLL.@)
2579 void WINAPI LdrShutdownThread(void)
2581 PLIST_ENTRY mark, entry;
2582 PLDR_MODULE mod;
2583 UINT i;
2584 void **pointers;
2586 TRACE("()\n");
2588 /* don't do any detach calls if process is exiting */
2589 if (process_detaching) return;
2591 RtlEnterCriticalSection( &loader_section );
2593 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2594 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2596 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2597 InInitializationOrderModuleList);
2598 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2599 continue;
2600 if ( mod->Flags & LDR_NO_DLL_CALLS )
2601 continue;
2603 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2604 DLL_THREAD_DETACH, NULL );
2607 RtlAcquirePebLock();
2608 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2609 RtlReleasePebLock();
2611 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2613 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2614 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2616 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2617 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2618 RtlLeaveCriticalSection( &loader_section );
2622 /***********************************************************************
2623 * free_modref
2626 static void free_modref( WINE_MODREF *wm )
2628 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2629 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2630 if (wm->ldr.InInitializationOrderModuleList.Flink)
2631 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2633 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2634 if (!TRACE_ON(module))
2635 TRACE_(loaddll)("Unloaded module %s : %s\n",
2636 debugstr_w(wm->ldr.FullDllName.Buffer),
2637 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2639 SERVER_START_REQ( unload_dll )
2641 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2642 wine_server_call( req );
2644 SERVER_END_REQ;
2646 free_tls_slot( &wm->ldr );
2647 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2648 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2649 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2650 if (cached_modref == wm) cached_modref = NULL;
2651 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2652 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2653 RtlFreeHeap( GetProcessHeap(), 0, wm );
2656 /***********************************************************************
2657 * MODULE_FlushModrefs
2659 * Remove all unused modrefs and call the internal unloading routines
2660 * for the library type.
2662 * The loader_section must be locked while calling this function.
2664 static void MODULE_FlushModrefs(void)
2666 PLIST_ENTRY mark, entry, prev;
2667 PLDR_MODULE mod;
2668 WINE_MODREF*wm;
2670 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2671 for (entry = mark->Blink; entry != mark; entry = prev)
2673 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2674 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2675 prev = entry->Blink;
2676 if (!mod->LoadCount) free_modref( wm );
2679 /* check load order list too for modules that haven't been initialized yet */
2680 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2681 for (entry = mark->Blink; entry != mark; entry = prev)
2683 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2684 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2685 prev = entry->Blink;
2686 if (!mod->LoadCount) free_modref( wm );
2690 /***********************************************************************
2691 * MODULE_DecRefCount
2693 * The loader_section must be locked while calling this function.
2695 static void MODULE_DecRefCount( WINE_MODREF *wm )
2697 int i;
2699 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2700 return;
2702 if ( wm->ldr.LoadCount <= 0 )
2703 return;
2705 --wm->ldr.LoadCount;
2706 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2708 if ( wm->ldr.LoadCount == 0 )
2710 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2712 for ( i = 0; i < wm->nDeps; i++ )
2713 if ( wm->deps[i] )
2714 MODULE_DecRefCount( wm->deps[i] );
2716 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2720 /******************************************************************
2721 * LdrUnloadDll (NTDLL.@)
2725 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2727 WINE_MODREF *wm;
2728 NTSTATUS retv = STATUS_SUCCESS;
2730 if (process_detaching) return retv;
2732 TRACE("(%p)\n", hModule);
2734 RtlEnterCriticalSection( &loader_section );
2736 free_lib_count++;
2737 if ((wm = get_modref( hModule )) != NULL)
2739 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2741 /* Recursively decrement reference counts */
2742 MODULE_DecRefCount( wm );
2744 /* Call process detach notifications */
2745 if ( free_lib_count <= 1 )
2747 process_detach();
2748 MODULE_FlushModrefs();
2751 TRACE("END\n");
2753 else
2754 retv = STATUS_DLL_NOT_FOUND;
2756 free_lib_count--;
2758 RtlLeaveCriticalSection( &loader_section );
2760 return retv;
2763 /***********************************************************************
2764 * RtlImageNtHeader (NTDLL.@)
2766 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2768 IMAGE_NT_HEADERS *ret;
2770 __TRY
2772 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2774 ret = NULL;
2775 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2777 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2778 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2781 __EXCEPT_PAGE_FAULT
2783 return NULL;
2785 __ENDTRY
2786 return ret;
2790 /***********************************************************************
2791 * attach_process_dlls
2793 * Initial attach to all the dlls loaded by the process.
2795 static NTSTATUS attach_process_dlls( void *wm )
2797 NTSTATUS status;
2799 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2801 RtlEnterCriticalSection( &loader_section );
2802 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2804 if (last_failed_modref)
2805 ERR( "%s failed to initialize, aborting\n",
2806 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2807 return status;
2809 attach_implicitly_loaded_dlls( (LPVOID)1 );
2810 RtlLeaveCriticalSection( &loader_section );
2811 return status;
2815 /***********************************************************************
2816 * load_global_options
2818 static void load_global_options(void)
2820 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2821 'S','y','s','t','e','m','\\',
2822 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2823 'C','o','n','t','r','o','l','\\',
2824 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2825 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2826 static const WCHAR critsectW[] = {'C','r','i','t','i','c','a','l','S','e','c','t','i','o','n','T','i','m','e','o','u','t',0};
2827 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2828 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2829 static const WCHAR decommittotalW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','T','o','t','a','l','F','r','e','e','T','h','r','e','s','h','o','l','d',0};
2830 static const WCHAR decommitfreeW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','F','r','e','e','B','l','o','c','k','T','h','r','e','s','h','o','l','d',0};
2832 OBJECT_ATTRIBUTES attr;
2833 UNICODE_STRING name_str;
2834 HANDLE hkey;
2835 ULONG value;
2837 attr.Length = sizeof(attr);
2838 attr.RootDirectory = 0;
2839 attr.ObjectName = &name_str;
2840 attr.Attributes = OBJ_CASE_INSENSITIVE;
2841 attr.SecurityDescriptor = NULL;
2842 attr.SecurityQualityOfService = NULL;
2843 RtlInitUnicodeString( &name_str, sessionW );
2845 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2847 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2849 query_dword_option( hkey, critsectW, &value );
2850 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2852 query_dword_option( hkey, heapresW, &value );
2853 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2855 query_dword_option( hkey, heapcommitW, &value );
2856 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2858 query_dword_option( hkey, decommittotalW, &value );
2859 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2861 query_dword_option( hkey, decommitfreeW, &value );
2862 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2864 NtClose( hkey );
2868 /***********************************************************************
2869 * start_process
2871 static void start_process( void *kernel_start )
2873 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2876 /******************************************************************
2877 * LdrInitializeThunk (NTDLL.@)
2880 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2881 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2883 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2884 NTSTATUS status;
2885 WINE_MODREF *wm;
2886 LPCWSTR load_path;
2887 PEB *peb = NtCurrentTeb()->Peb;
2889 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2891 /* allocate the modref for the main exe (if not already done) */
2892 wm = get_modref( peb->ImageBaseAddress );
2893 assert( wm );
2894 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2896 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2897 exit(1);
2900 peb->LoaderLock = &loader_section;
2901 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2902 if (!peb->ProcessParameters->WindowTitle.Buffer)
2903 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2904 version_init( wm->ldr.FullDllName.Buffer );
2905 virtual_set_large_address_space();
2907 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2908 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2910 /* the main exe needs to be the first in the load order list */
2911 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2912 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2914 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2915 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2917 actctx_init();
2918 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2919 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2920 heap_set_debug_flags( GetProcessHeap() );
2922 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2923 if (status != STATUS_SUCCESS) goto error;
2925 virtual_release_address_space();
2926 virtual_clear_thread_stack();
2927 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2929 error:
2930 ERR( "Main exe initialization for %s failed, status %x\n",
2931 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2932 NtTerminateProcess( GetCurrentProcess(), status );
2936 /***********************************************************************
2937 * RtlImageDirectoryEntryToData (NTDLL.@)
2939 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2941 const IMAGE_NT_HEADERS *nt;
2942 DWORD addr;
2944 if ((ULONG_PTR)module & 1) /* mapped as data file */
2946 module = (HMODULE)((ULONG_PTR)module & ~1);
2947 image = FALSE;
2949 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2950 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2952 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2954 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2955 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2956 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2957 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2959 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2961 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2963 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2964 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2965 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2966 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2968 else return NULL;
2970 /* not mapped as image, need to find the section containing the virtual address */
2971 return RtlImageRvaToVa( nt, module, addr, NULL );
2975 /***********************************************************************
2976 * RtlImageRvaToSection (NTDLL.@)
2978 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2979 HMODULE module, DWORD rva )
2981 int i;
2982 const IMAGE_SECTION_HEADER *sec;
2984 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2985 nt->FileHeader.SizeOfOptionalHeader);
2986 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2988 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2989 return (PIMAGE_SECTION_HEADER)sec;
2991 return NULL;
2995 /***********************************************************************
2996 * RtlImageRvaToVa (NTDLL.@)
2998 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2999 DWORD rva, IMAGE_SECTION_HEADER **section )
3001 IMAGE_SECTION_HEADER *sec;
3003 if (section && *section) /* try this section first */
3005 sec = *section;
3006 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3007 goto found;
3009 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3010 found:
3011 if (section) *section = sec;
3012 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3016 /***********************************************************************
3017 * RtlPcToFileHeader (NTDLL.@)
3019 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3021 LDR_MODULE *module;
3022 PVOID ret = NULL;
3024 RtlEnterCriticalSection( &loader_section );
3025 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3026 RtlLeaveCriticalSection( &loader_section );
3027 *address = ret;
3028 return ret;
3032 /***********************************************************************
3033 * NtLoadDriver (NTDLL.@)
3034 * ZwLoadDriver (NTDLL.@)
3036 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3038 FIXME("(%p), stub!\n",DriverServiceName);
3039 return STATUS_NOT_IMPLEMENTED;
3043 /***********************************************************************
3044 * NtUnloadDriver (NTDLL.@)
3045 * ZwUnloadDriver (NTDLL.@)
3047 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3049 FIXME("(%p), stub!\n",DriverServiceName);
3050 return STATUS_NOT_IMPLEMENTED;
3054 /******************************************************************
3055 * DllMain (NTDLL.@)
3057 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3059 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3060 return TRUE;
3064 /******************************************************************
3065 * __wine_init_windows_dir (NTDLL.@)
3067 * Windows and system dir initialization once kernel32 has been loaded.
3069 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3071 PLIST_ENTRY mark, entry;
3072 LPWSTR buffer, p;
3074 strcpyW( user_shared_data->NtSystemRoot, windir );
3075 DIR_init_windows_dir( windir, sysdir );
3077 /* prepend the system dir to the name of the already created modules */
3078 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3079 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3081 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3083 assert( mod->Flags & LDR_WINE_INTERNAL );
3085 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3086 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3087 if (!buffer) continue;
3088 strcpyW( buffer, system_dir.Buffer );
3089 p = buffer + strlenW( buffer );
3090 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3091 strcpyW( p, mod->FullDllName.Buffer );
3092 RtlInitUnicodeString( &mod->FullDllName, buffer );
3093 RtlInitUnicodeString( &mod->BaseDllName, p );
3098 /***********************************************************************
3099 * __wine_process_init
3101 void __wine_process_init(void)
3103 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3105 WINE_MODREF *wm;
3106 NTSTATUS status;
3107 ANSI_STRING func_name;
3108 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3110 main_exe_file = thread_init();
3112 /* retrieve current umask */
3113 FILE_umask = umask(0777);
3114 umask( FILE_umask );
3116 load_global_options();
3118 /* setup the load callback and create ntdll modref */
3119 wine_dll_set_callback( load_builtin_callback );
3121 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3123 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3124 exit(1);
3126 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3127 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3129 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3130 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3131 0, (void **)&init_func )) != STATUS_SUCCESS)
3133 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3134 exit(1);
3136 init_func();