msvcirt: Add implementation of streambuf::snextc.
[wine.git] / dlls / ntdll / loader.c
blob921bf57b07dd523f82247a7a372005ead9a9f21c
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 const 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++) if (!tls_dirs[i]) break;
777 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
778 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
779 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
781 if (i == tls_module_count)
783 UINT new_count = max( 32, tls_module_count * 2 );
785 if (!tls_dirs)
786 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
787 else
788 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
789 new_count * sizeof(*tls_dirs) );
790 if (!new_ptr) return -1;
792 /* resize the pointer block in all running threads */
793 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
795 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
796 void **old = teb->ThreadLocalStoragePointer;
797 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
799 if (!new) return -1;
800 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
801 teb->ThreadLocalStoragePointer = new;
802 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
803 /* FIXME: can't free old block here, should be freed at thread exit */
806 tls_dirs = new_ptr;
807 tls_module_count = new_count;
810 /* allocate the data block in all running threads */
811 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
813 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
815 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
816 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
817 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
819 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
820 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
822 RtlFreeHeap( GetProcessHeap(), 0,
823 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
826 *(DWORD *)dir->AddressOfIndex = i;
827 tls_dirs[i] = dir;
828 return i;
832 /*************************************************************************
833 * free_tls_slot
835 * Free the module TLS slot on unload.
836 * The loader_section must be locked while calling this function.
838 static void free_tls_slot( LDR_MODULE *mod )
840 ULONG i = (USHORT)mod->TlsIndex;
842 if (mod->TlsIndex == -1) return;
843 assert( i < tls_module_count );
844 tls_dirs[i] = NULL;
848 /****************************************************************
849 * fixup_imports
851 * Fixup all imports of a given module.
852 * The loader_section must be locked while calling this function.
854 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
856 int i, nb_imports;
857 const IMAGE_IMPORT_DESCRIPTOR *imports;
858 WINE_MODREF *prev;
859 DWORD size;
860 NTSTATUS status;
861 ULONG_PTR cookie;
863 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
864 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
866 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
868 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
869 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
870 return STATUS_SUCCESS;
872 nb_imports = 0;
873 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
875 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
877 if (!create_module_activation_context( &wm->ldr ))
878 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
880 /* Allocate module dependency list */
881 wm->nDeps = nb_imports;
882 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
884 /* load the imported modules. They are automatically
885 * added to the modref list of the process.
887 prev = current_modref;
888 current_modref = wm;
889 status = STATUS_SUCCESS;
890 for (i = 0; i < nb_imports; i++)
892 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
893 status = STATUS_DLL_NOT_FOUND;
895 current_modref = prev;
896 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
897 return status;
901 /*************************************************************************
902 * alloc_module
904 * Allocate a WINE_MODREF structure and add it to the process list
905 * The loader_section must be locked while calling this function.
907 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
909 WINE_MODREF *wm;
910 const WCHAR *p;
911 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
912 PLIST_ENTRY entry, mark;
914 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
916 wm->nDeps = 0;
917 wm->deps = NULL;
919 wm->ldr.BaseAddress = hModule;
920 wm->ldr.EntryPoint = NULL;
921 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
922 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
923 wm->ldr.TlsIndex = -1;
924 wm->ldr.LoadCount = 1;
925 wm->ldr.SectionHandle = NULL;
926 wm->ldr.CheckSum = 0;
927 wm->ldr.TimeDateStamp = 0;
928 wm->ldr.ActivationContext = 0;
930 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
931 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
932 else p = wm->ldr.FullDllName.Buffer;
933 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
935 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
937 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
938 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
939 if (nt->OptionalHeader.AddressOfEntryPoint)
940 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
943 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
944 &wm->ldr.InLoadOrderModuleList);
946 /* insert module in MemoryList, sorted in increasing base addresses */
947 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
948 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
950 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
951 break;
953 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
954 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
955 wm->ldr.InMemoryOrderModuleList.Flink = entry;
956 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
958 /* wait until init is called for inserting into this list */
959 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
960 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
962 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
964 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
965 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
966 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
968 return wm;
972 /*************************************************************************
973 * alloc_thread_tls
975 * Allocate the per-thread structure for module TLS storage.
977 static NTSTATUS alloc_thread_tls(void)
979 void **pointers;
980 UINT i, size;
982 if (!tls_module_count) return STATUS_SUCCESS;
984 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
985 tls_module_count * sizeof(*pointers) )))
986 return STATUS_NO_MEMORY;
988 for (i = 0; i < tls_module_count; i++)
990 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
992 if (!dir) continue;
993 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
994 if (!size && !dir->SizeOfZeroFill) continue;
996 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
998 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
999 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1000 return STATUS_NO_MEMORY;
1002 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1003 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1005 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1006 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1008 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1009 return STATUS_SUCCESS;
1013 /*************************************************************************
1014 * call_tls_callbacks
1016 static void call_tls_callbacks( HMODULE module, UINT reason )
1018 const IMAGE_TLS_DIRECTORY *dir;
1019 const PIMAGE_TLS_CALLBACK *callback;
1020 ULONG dirsize;
1022 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1023 if (!dir || !dir->AddressOfCallBacks) return;
1025 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1027 if (TRACE_ON(relay))
1028 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1029 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1030 __TRY
1032 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1034 __EXCEPT_ALL
1036 if (TRACE_ON(relay))
1037 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1038 GetCurrentThreadId(), callback, module, reason_names[reason] );
1039 return;
1041 __ENDTRY
1042 if (TRACE_ON(relay))
1043 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1044 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1049 /*************************************************************************
1050 * MODULE_InitDLL
1052 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1054 WCHAR mod_name[32];
1055 NTSTATUS status = STATUS_SUCCESS;
1056 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1057 void *module = wm->ldr.BaseAddress;
1058 BOOL retv = FALSE;
1060 /* Skip calls for modules loaded with special load flags */
1062 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1063 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1064 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1066 if (TRACE_ON(relay))
1068 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1069 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1070 mod_name[len / sizeof(WCHAR)] = 0;
1071 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1072 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1073 reason_names[reason], lpReserved );
1075 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1076 reason_names[reason], lpReserved );
1078 __TRY
1080 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1081 if (!retv)
1082 status = STATUS_DLL_INIT_FAILED;
1084 __EXCEPT_ALL
1086 if (TRACE_ON(relay))
1087 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1088 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1089 status = GetExceptionCode();
1091 __ENDTRY
1093 /* The state of the module list may have changed due to the call
1094 to the dll. We cannot assume that this module has not been
1095 deleted. */
1096 if (TRACE_ON(relay))
1097 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1098 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1099 reason_names[reason], lpReserved, retv );
1100 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1102 return status;
1106 /*************************************************************************
1107 * process_attach
1109 * Send the process attach notification to all DLLs the given module
1110 * depends on (recursively). This is somewhat complicated due to the fact that
1112 * - we have to respect the module dependencies, i.e. modules implicitly
1113 * referenced by another module have to be initialized before the module
1114 * itself can be initialized
1116 * - the initialization routine of a DLL can itself call LoadLibrary,
1117 * thereby introducing a whole new set of dependencies (even involving
1118 * the 'old' modules) at any time during the whole process
1120 * (Note that this routine can be recursively entered not only directly
1121 * from itself, but also via LoadLibrary from one of the called initialization
1122 * routines.)
1124 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1125 * the process *detach* notifications to be sent in the correct order.
1126 * This must not only take into account module dependencies, but also
1127 * 'hidden' dependencies created by modules calling LoadLibrary in their
1128 * attach notification routine.
1130 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1131 * list after the attach notification has returned. This implies that the
1132 * detach notifications are called in the reverse of the sequence the attach
1133 * notifications *returned*.
1135 * The loader_section must be locked while calling this function.
1137 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1139 NTSTATUS status = STATUS_SUCCESS;
1140 ULONG_PTR cookie;
1141 int i;
1143 if (process_detaching) return status;
1145 /* prevent infinite recursion in case of cyclical dependencies */
1146 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1147 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1148 return status;
1150 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1152 /* Tag current MODREF to prevent recursive loop */
1153 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1154 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1155 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1157 /* Recursively attach all DLLs this one depends on */
1158 for ( i = 0; i < wm->nDeps; i++ )
1160 if (!wm->deps[i]) continue;
1161 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1164 /* Call DLL entry point */
1165 if (status == STATUS_SUCCESS)
1167 WINE_MODREF *prev = current_modref;
1168 current_modref = wm;
1169 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1170 if (status == STATUS_SUCCESS)
1171 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1172 else
1174 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1175 /* point to the name so LdrInitializeThunk can print it */
1176 last_failed_modref = wm;
1177 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1179 current_modref = prev;
1182 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1183 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1184 &wm->ldr.InInitializationOrderModuleList);
1186 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1187 /* Remove recursion flag */
1188 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1190 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1191 return status;
1195 /**********************************************************************
1196 * attach_implicitly_loaded_dlls
1198 * Attach to the (builtin) dlls that have been implicitly loaded because
1199 * of a dependency at the Unix level, but not imported at the Win32 level.
1201 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1203 for (;;)
1205 PLIST_ENTRY mark, entry;
1207 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1208 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1210 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1212 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1213 TRACE( "found implicitly loaded %s, attaching to it\n",
1214 debugstr_w(mod->BaseDllName.Buffer));
1215 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1216 break; /* restart the search from the start */
1218 if (entry == mark) break; /* nothing found */
1223 /*************************************************************************
1224 * process_detach
1226 * Send DLL process detach notifications. See the comment about calling
1227 * sequence at process_attach.
1229 static void process_detach(void)
1231 PLIST_ENTRY mark, entry;
1232 PLDR_MODULE mod;
1234 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1237 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1239 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1240 InInitializationOrderModuleList);
1241 /* Check whether to detach this DLL */
1242 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1243 continue;
1244 if ( mod->LoadCount && !process_detaching )
1245 continue;
1247 /* Call detach notification */
1248 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1249 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1250 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1252 /* Restart at head of WINE_MODREF list, as entries might have
1253 been added and/or removed while performing the call ... */
1254 break;
1256 } while (entry != mark);
1259 /*************************************************************************
1260 * MODULE_DllThreadAttach
1262 * Send DLL thread attach notifications. These are sent in the
1263 * reverse sequence of process detach notification.
1266 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1268 PLIST_ENTRY mark, entry;
1269 PLDR_MODULE mod;
1270 NTSTATUS status;
1272 /* don't do any attach calls if process is exiting */
1273 if (process_detaching) return STATUS_SUCCESS;
1275 RtlEnterCriticalSection( &loader_section );
1277 RtlAcquirePebLock();
1278 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1279 RtlReleasePebLock();
1281 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1283 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1284 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1286 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1287 InInitializationOrderModuleList);
1288 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1289 continue;
1290 if ( mod->Flags & LDR_NO_DLL_CALLS )
1291 continue;
1293 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1294 DLL_THREAD_ATTACH, lpReserved );
1297 done:
1298 RtlLeaveCriticalSection( &loader_section );
1299 return status;
1302 /******************************************************************
1303 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1306 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1308 WINE_MODREF *wm;
1309 NTSTATUS ret = STATUS_SUCCESS;
1311 RtlEnterCriticalSection( &loader_section );
1313 wm = get_modref( hModule );
1314 if (!wm || wm->ldr.TlsIndex != -1)
1315 ret = STATUS_DLL_NOT_FOUND;
1316 else
1317 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1319 RtlLeaveCriticalSection( &loader_section );
1321 return ret;
1324 /******************************************************************
1325 * LdrFindEntryForAddress (NTDLL.@)
1327 * The loader_section must be locked while calling this function
1329 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1331 PLIST_ENTRY mark, entry;
1332 PLDR_MODULE mod;
1334 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1335 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1337 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1338 if (mod->BaseAddress <= addr &&
1339 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1341 *pmod = mod;
1342 return STATUS_SUCCESS;
1344 if (mod->BaseAddress > addr) break;
1346 return STATUS_NO_MORE_ENTRIES;
1349 /******************************************************************
1350 * LdrLockLoaderLock (NTDLL.@)
1352 * Note: some flags are not implemented.
1353 * Flag 0x01 is used to raise exceptions on errors.
1355 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1357 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1359 if (result) *result = 0;
1360 if (magic) *magic = 0;
1361 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1362 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1363 if (!magic) return STATUS_INVALID_PARAMETER_3;
1365 if (flags & 0x2)
1367 if (!RtlTryEnterCriticalSection( &loader_section ))
1369 *result = 2;
1370 return STATUS_SUCCESS;
1372 *result = 1;
1374 else
1376 RtlEnterCriticalSection( &loader_section );
1377 if (result) *result = 1;
1379 *magic = GetCurrentThreadId();
1380 return STATUS_SUCCESS;
1384 /******************************************************************
1385 * LdrUnlockLoaderUnlock (NTDLL.@)
1387 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1389 if (magic)
1391 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1392 RtlLeaveCriticalSection( &loader_section );
1394 return STATUS_SUCCESS;
1398 /******************************************************************
1399 * LdrGetProcedureAddress (NTDLL.@)
1401 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1402 ULONG ord, PVOID *address)
1404 IMAGE_EXPORT_DIRECTORY *exports;
1405 DWORD exp_size;
1406 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1408 RtlEnterCriticalSection( &loader_section );
1410 /* check if the module itself is invalid to return the proper error */
1411 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1412 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1413 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1415 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1416 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1417 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1418 if (proc)
1420 *address = proc;
1421 ret = STATUS_SUCCESS;
1425 RtlLeaveCriticalSection( &loader_section );
1426 return ret;
1430 /***********************************************************************
1431 * is_fake_dll
1433 * Check if a loaded native dll is a Wine fake dll.
1435 static BOOL is_fake_dll( HANDLE handle )
1437 static const char fakedll_signature[] = "Wine placeholder DLL";
1438 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1439 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1440 IO_STATUS_BLOCK io;
1441 LARGE_INTEGER offset;
1443 offset.QuadPart = 0;
1444 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1445 if (io.Information < sizeof(buffer)) return FALSE;
1446 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1447 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1448 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1449 return FALSE;
1453 /***********************************************************************
1454 * get_builtin_fullname
1456 * Build the full pathname for a builtin dll.
1458 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1460 static const WCHAR soW[] = {'.','s','o',0};
1461 WCHAR *p, *fullname;
1462 size_t i, len = strlen(filename);
1464 /* check if path can correspond to the dll we have */
1465 if (path && (p = strrchrW( path, '\\' )))
1467 p++;
1468 for (i = 0; i < len; i++)
1469 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1470 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1472 /* the filename matches, use path as the full path */
1473 len += p - path;
1474 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1476 memcpy( fullname, path, len * sizeof(WCHAR) );
1477 fullname[len] = 0;
1479 return fullname;
1483 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1484 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1486 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1487 p = fullname + system_dir.Length / sizeof(WCHAR);
1488 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1489 ascii_to_unicode( p, filename, len + 1 );
1491 return fullname;
1495 /*************************************************************************
1496 * is_16bit_builtin
1498 static BOOL is_16bit_builtin( HMODULE module )
1500 const IMAGE_EXPORT_DIRECTORY *exports;
1501 DWORD exp_size;
1503 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1504 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1505 return FALSE;
1507 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1511 /***********************************************************************
1512 * load_builtin_callback
1514 * Load a library in memory; callback function for wine_dll_register
1516 static void load_builtin_callback( void *module, const char *filename )
1518 static const WCHAR emptyW[1];
1519 IMAGE_NT_HEADERS *nt;
1520 WINE_MODREF *wm;
1521 WCHAR *fullname;
1522 const WCHAR *load_path;
1524 if (!module)
1526 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1527 return;
1529 if (!(nt = RtlImageNtHeader( module )))
1531 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1532 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1533 return;
1536 virtual_create_builtin_view( module );
1538 /* create the MODREF */
1540 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1542 ERR( "can't load %s\n", filename );
1543 builtin_load_info->status = STATUS_NO_MEMORY;
1544 return;
1547 wm = alloc_module( module, fullname );
1548 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1549 if (!wm)
1551 ERR( "can't load %s\n", filename );
1552 builtin_load_info->status = STATUS_NO_MEMORY;
1553 return;
1555 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1557 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1558 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1559 is_16bit_builtin( module ))
1561 /* fixup imports */
1563 load_path = builtin_load_info->load_path;
1564 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1565 if (!load_path) load_path = emptyW;
1566 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1568 /* the module has only be inserted in the load & memory order lists */
1569 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1570 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1571 /* FIXME: free the modref */
1572 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1573 return;
1577 builtin_load_info->wm = wm;
1578 TRACE( "loaded %s %p %p\n", filename, wm, module );
1580 /* send the DLL load event */
1582 SERVER_START_REQ( load_dll )
1584 req->mapping = 0;
1585 req->base = wine_server_client_ptr( module );
1586 req->size = nt->OptionalHeader.SizeOfImage;
1587 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1588 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1589 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1590 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1591 wine_server_call( req );
1593 SERVER_END_REQ;
1595 /* setup relay debugging entry points */
1596 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1600 /******************************************************************************
1601 * load_native_dll (internal)
1603 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1604 DWORD flags, WINE_MODREF** pwm )
1606 void *module;
1607 HANDLE mapping;
1608 LARGE_INTEGER size;
1609 IMAGE_NT_HEADERS *nt;
1610 SIZE_T len = 0;
1611 WINE_MODREF *wm;
1612 NTSTATUS status;
1614 TRACE("Trying native dll %s\n", debugstr_w(name));
1616 size.QuadPart = 0;
1617 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1618 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1619 if (status != STATUS_SUCCESS) return status;
1621 module = NULL;
1622 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1623 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1624 if (status < 0) goto done;
1626 /* create the MODREF */
1628 if (!(wm = alloc_module( module, name )))
1630 status = STATUS_NO_MEMORY;
1631 goto done;
1634 /* fixup imports */
1636 nt = RtlImageNtHeader( module );
1638 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1639 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1640 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1642 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1644 /* the module has only be inserted in the load & memory order lists */
1645 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1646 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1648 /* FIXME: there are several more dangling references
1649 * left. Including dlls loaded by this dll before the
1650 * failed one. Unrolling is rather difficult with the
1651 * current structure and we can leave them lying
1652 * around with no problems, so we don't care.
1653 * As these might reference our wm, we don't free it.
1655 goto done;
1659 /* send DLL load event */
1661 SERVER_START_REQ( load_dll )
1663 req->mapping = wine_server_obj_handle( mapping );
1664 req->base = wine_server_client_ptr( module );
1665 req->size = nt->OptionalHeader.SizeOfImage;
1666 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1667 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1668 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1669 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1670 wine_server_call( req );
1672 SERVER_END_REQ;
1674 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1676 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1678 wm->ldr.LoadCount = 1;
1679 *pwm = wm;
1680 status = STATUS_SUCCESS;
1681 done:
1682 NtClose( mapping );
1683 return status;
1687 /***********************************************************************
1688 * load_builtin_dll
1690 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1691 DWORD flags, WINE_MODREF** pwm )
1693 char error[256], dllname[MAX_PATH];
1694 const WCHAR *name, *p;
1695 DWORD len, i;
1696 void *handle = NULL;
1697 struct builtin_load_info info, *prev_info;
1699 /* Fix the name in case we have a full path and extension */
1700 name = path;
1701 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1702 if ((p = strrchrW( name, '/' ))) name = p + 1;
1704 /* load_library will modify info.status. Note also that load_library can be
1705 * called several times, if the .so file we're loading has dependencies.
1706 * info.status will gather all the errors we may get while loading all these
1707 * libraries
1709 info.load_path = load_path;
1710 info.filename = NULL;
1711 info.status = STATUS_SUCCESS;
1712 info.wm = NULL;
1714 if (file) /* we have a real file, try to load it */
1716 UNICODE_STRING nt_name;
1717 ANSI_STRING unix_name;
1719 TRACE("Trying built-in %s\n", debugstr_w(path));
1721 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1722 return STATUS_DLL_NOT_FOUND;
1724 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1726 RtlFreeUnicodeString( &nt_name );
1727 return STATUS_DLL_NOT_FOUND;
1729 prev_info = builtin_load_info;
1730 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1731 builtin_load_info = &info;
1732 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1733 builtin_load_info = prev_info;
1734 RtlFreeUnicodeString( &nt_name );
1735 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1736 if (!handle)
1738 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1739 return STATUS_INVALID_IMAGE_FORMAT;
1742 else
1744 int file_exists;
1746 TRACE("Trying built-in %s\n", debugstr_w(name));
1748 /* we don't want to depend on the current codepage here */
1749 len = strlenW( name ) + 1;
1750 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1751 for (i = 0; i < len; i++)
1753 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1754 dllname[i] = (char)name[i];
1755 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1758 prev_info = builtin_load_info;
1759 builtin_load_info = &info;
1760 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1761 builtin_load_info = prev_info;
1762 if (!handle)
1764 if (!file_exists)
1766 /* The file does not exist -> WARN() */
1767 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1768 return STATUS_DLL_NOT_FOUND;
1770 /* ERR() for all other errors (missing functions, ...) */
1771 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1772 return STATUS_PROCEDURE_NOT_FOUND;
1776 if (info.status != STATUS_SUCCESS)
1778 wine_dll_unload( handle );
1779 return info.status;
1782 if (!info.wm)
1784 PLIST_ENTRY mark, entry;
1786 /* The constructor wasn't called, this means the .so is already
1787 * loaded under a different name. Try to find the wm for it. */
1789 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1790 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1792 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1793 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1795 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1796 TRACE( "Found %s at %p for builtin %s\n",
1797 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1798 break;
1801 wine_dll_unload( handle ); /* release the libdl refcount */
1802 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1803 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1805 else
1807 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1808 info.wm->ldr.LoadCount = 1;
1809 info.wm->ldr.SectionHandle = handle;
1812 *pwm = info.wm;
1813 return STATUS_SUCCESS;
1817 /***********************************************************************
1818 * find_actctx_dll
1820 * Find the full path (if any) of the dll from the activation context.
1822 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1824 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1825 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1827 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1828 ACTCTX_SECTION_KEYED_DATA data;
1829 UNICODE_STRING nameW;
1830 NTSTATUS status;
1831 SIZE_T needed, size = 1024;
1832 WCHAR *p;
1834 RtlInitUnicodeString( &nameW, libname );
1835 data.cbSize = sizeof(data);
1836 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1837 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1838 &nameW, &data );
1839 if (status != STATUS_SUCCESS) return status;
1841 for (;;)
1843 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1845 status = STATUS_NO_MEMORY;
1846 goto done;
1848 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1849 AssemblyDetailedInformationInActivationContext,
1850 info, size, &needed );
1851 if (status == STATUS_SUCCESS) break;
1852 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1853 RtlFreeHeap( GetProcessHeap(), 0, info );
1854 size = needed;
1855 /* restart with larger buffer */
1858 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1860 status = STATUS_SXS_KEY_NOT_FOUND;
1861 goto done;
1864 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1866 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1868 p++;
1869 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1871 /* manifest name does not match directory name, so it's not a global
1872 * windows/winsxs manifest; use the manifest directory name instead */
1873 dirlen = p - info->lpAssemblyManifestPath;
1874 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1875 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1877 status = STATUS_NO_MEMORY;
1878 goto done;
1880 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1881 p += dirlen;
1882 strcpyW( p, libname );
1883 goto done;
1887 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1888 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1890 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1892 status = STATUS_NO_MEMORY;
1893 goto done;
1895 strcpyW( p, user_shared_data->NtSystemRoot );
1896 p += strlenW(p);
1897 memcpy( p, winsxsW, sizeof(winsxsW) );
1898 p += sizeof(winsxsW) / sizeof(WCHAR);
1899 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1900 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1901 *p++ = '\\';
1902 strcpyW( p, libname );
1903 done:
1904 RtlFreeHeap( GetProcessHeap(), 0, info );
1905 RtlReleaseActivationContext( data.hActCtx );
1906 return status;
1910 /***********************************************************************
1911 * find_dll_file
1913 * Find the file (or already loaded module) for a given dll name.
1915 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1916 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1918 OBJECT_ATTRIBUTES attr;
1919 IO_STATUS_BLOCK io;
1920 UNICODE_STRING nt_name;
1921 WCHAR *file_part, *ext, *dllname;
1922 ULONG len;
1924 /* first append .dll if needed */
1926 dllname = NULL;
1927 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1929 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1930 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1931 return STATUS_NO_MEMORY;
1932 strcpyW( dllname, libname );
1933 strcatW( dllname, dllW );
1934 libname = dllname;
1937 nt_name.Buffer = NULL;
1939 if (!contains_path( libname ))
1941 NTSTATUS status;
1942 WCHAR *fullname = NULL;
1944 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1946 status = find_actctx_dll( libname, &fullname );
1947 if (status == STATUS_SUCCESS)
1949 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1950 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1951 libname = dllname = fullname;
1953 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1955 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1956 return status;
1960 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1962 /* we need to search for it */
1963 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1964 if (len)
1966 if (len >= *size) goto overflow;
1967 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1969 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1971 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1972 return STATUS_NO_MEMORY;
1974 attr.Length = sizeof(attr);
1975 attr.RootDirectory = 0;
1976 attr.Attributes = OBJ_CASE_INSENSITIVE;
1977 attr.ObjectName = &nt_name;
1978 attr.SecurityDescriptor = NULL;
1979 attr.SecurityQualityOfService = NULL;
1980 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
1981 goto found;
1984 /* not found */
1986 if (!contains_path( libname ))
1988 /* if libname doesn't contain a path at all, we simply return the name as is,
1989 * to be loaded as builtin */
1990 len = strlenW(libname) * sizeof(WCHAR);
1991 if (len >= *size) goto overflow;
1992 strcpyW( filename, libname );
1993 goto found;
1997 /* absolute path name, or relative path name but not found above */
1999 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2001 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2002 return STATUS_NO_MEMORY;
2004 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2005 if (len >= *size) goto overflow;
2006 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2007 if (!(*pwm = find_fullname_module( filename )) && handle)
2009 attr.Length = sizeof(attr);
2010 attr.RootDirectory = 0;
2011 attr.Attributes = OBJ_CASE_INSENSITIVE;
2012 attr.ObjectName = &nt_name;
2013 attr.SecurityDescriptor = NULL;
2014 attr.SecurityQualityOfService = NULL;
2015 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2017 found:
2018 RtlFreeUnicodeString( &nt_name );
2019 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2020 return STATUS_SUCCESS;
2022 overflow:
2023 RtlFreeUnicodeString( &nt_name );
2024 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2025 *size = len + sizeof(WCHAR);
2026 return STATUS_BUFFER_TOO_SMALL;
2030 /***********************************************************************
2031 * load_dll (internal)
2033 * Load a PE style module according to the load order.
2034 * The loader_section must be locked while calling this function.
2036 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2038 enum loadorder loadorder;
2039 WCHAR buffer[32];
2040 WCHAR *filename;
2041 ULONG size;
2042 WINE_MODREF *main_exe;
2043 HANDLE handle = 0;
2044 NTSTATUS nts;
2046 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2048 *pwm = NULL;
2049 filename = buffer;
2050 size = sizeof(buffer);
2051 for (;;)
2053 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2054 if (nts == STATUS_SUCCESS) break;
2055 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2056 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2057 /* grow the buffer and retry */
2058 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2061 if (*pwm) /* found already loaded module */
2063 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2065 TRACE("Found %s for %s at %p, count=%d\n",
2066 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2067 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2068 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2069 return STATUS_SUCCESS;
2072 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2073 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2075 if (handle && is_fake_dll( handle ))
2077 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2078 NtClose( handle );
2079 handle = 0;
2082 switch(loadorder)
2084 case LO_INVALID:
2085 nts = STATUS_NO_MEMORY;
2086 break;
2087 case LO_DISABLED:
2088 nts = STATUS_DLL_NOT_FOUND;
2089 break;
2090 case LO_NATIVE:
2091 case LO_NATIVE_BUILTIN:
2092 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2093 else
2095 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2096 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2097 /* not in PE format, maybe it's a builtin */
2098 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2100 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2101 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2102 break;
2103 case LO_BUILTIN:
2104 case LO_BUILTIN_NATIVE:
2105 case LO_DEFAULT: /* default is builtin,native */
2106 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2107 if (!handle) break; /* nothing else we can try */
2108 /* file is not a builtin library, try without using the specified file */
2109 if (nts != STATUS_SUCCESS)
2110 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2111 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2112 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2114 /* stub-only dll, try native */
2115 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2116 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2117 nts = STATUS_DLL_NOT_FOUND;
2119 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2120 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2121 break;
2124 if (nts == STATUS_SUCCESS)
2126 /* Initialize DLL just loaded */
2127 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2128 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2129 (*pwm)->ldr.BaseAddress);
2130 if (handle) NtClose( handle );
2131 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2132 return nts;
2135 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2136 if (handle) NtClose( handle );
2137 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2138 return nts;
2141 /******************************************************************
2142 * LdrLoadDll (NTDLL.@)
2144 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2145 const UNICODE_STRING *libname, HMODULE* hModule)
2147 WINE_MODREF *wm;
2148 NTSTATUS nts;
2150 RtlEnterCriticalSection( &loader_section );
2152 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2153 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2155 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2157 nts = process_attach( wm, NULL );
2158 if (nts != STATUS_SUCCESS)
2160 LdrUnloadDll(wm->ldr.BaseAddress);
2161 wm = NULL;
2164 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2166 RtlLeaveCriticalSection( &loader_section );
2167 return nts;
2171 /******************************************************************
2172 * LdrGetDllHandle (NTDLL.@)
2174 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2176 NTSTATUS status;
2177 WCHAR buffer[128];
2178 WCHAR *filename;
2179 ULONG size;
2180 WINE_MODREF *wm;
2182 RtlEnterCriticalSection( &loader_section );
2184 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2186 filename = buffer;
2187 size = sizeof(buffer);
2188 for (;;)
2190 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2191 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2192 if (status != STATUS_BUFFER_TOO_SMALL) break;
2193 /* grow the buffer and retry */
2194 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2196 status = STATUS_NO_MEMORY;
2197 break;
2201 if (status == STATUS_SUCCESS)
2203 if (wm) *base = wm->ldr.BaseAddress;
2204 else status = STATUS_DLL_NOT_FOUND;
2207 RtlLeaveCriticalSection( &loader_section );
2208 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2209 return status;
2213 /******************************************************************
2214 * LdrAddRefDll (NTDLL.@)
2216 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2218 NTSTATUS ret = STATUS_SUCCESS;
2219 WINE_MODREF *wm;
2221 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2223 RtlEnterCriticalSection( &loader_section );
2225 if ((wm = get_modref( module )))
2227 if (flags & LDR_ADDREF_DLL_PIN)
2228 wm->ldr.LoadCount = -1;
2229 else
2230 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2231 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2233 else ret = STATUS_INVALID_PARAMETER;
2235 RtlLeaveCriticalSection( &loader_section );
2236 return ret;
2240 /***********************************************************************
2241 * LdrProcessRelocationBlock (NTDLL.@)
2243 * Apply relocations to a given page of a mapped PE image.
2245 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2246 USHORT *relocs, INT_PTR delta )
2248 while (count--)
2250 USHORT offset = *relocs & 0xfff;
2251 int type = *relocs >> 12;
2252 switch(type)
2254 case IMAGE_REL_BASED_ABSOLUTE:
2255 break;
2256 case IMAGE_REL_BASED_HIGH:
2257 *(short *)((char *)page + offset) += HIWORD(delta);
2258 break;
2259 case IMAGE_REL_BASED_LOW:
2260 *(short *)((char *)page + offset) += LOWORD(delta);
2261 break;
2262 case IMAGE_REL_BASED_HIGHLOW:
2263 *(int *)((char *)page + offset) += delta;
2264 break;
2265 #ifdef __x86_64__
2266 case IMAGE_REL_BASED_DIR64:
2267 *(INT_PTR *)((char *)page + offset) += delta;
2268 break;
2269 #elif defined(__arm__)
2270 case IMAGE_REL_BASED_THUMB_MOV32:
2272 DWORD inst = *(INT_PTR *)((char *)page + offset);
2273 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2274 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2275 DWORD hi_delta;
2277 if ((inst & 0x8000fbf0) != 0x0000f240)
2278 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2280 imm16 += LOWORD(delta);
2281 hi_delta = HIWORD(delta) + HIWORD(imm16);
2282 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2283 ((imm16 >> 12) & 0x000f) +
2284 ((imm16 << 20) & 0x70000000) +
2285 ((imm16 << 16) & 0xff0000);
2287 if (hi_delta != 0)
2289 inst = *(INT_PTR *)((char *)page + offset + 4);
2290 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2291 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2293 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2294 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2296 imm16 += hi_delta;
2297 if (imm16 > 0xffff)
2298 ERR("resulting immediate value won't fit: %08x\n", imm16);
2299 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2300 ((imm16 >> 1) & 0x0400) +
2301 ((imm16 >> 12) & 0x000f) +
2302 ((imm16 << 20) & 0x70000000) +
2303 ((imm16 << 16) & 0xff0000);
2306 break;
2307 #endif
2308 default:
2309 FIXME("Unknown/unsupported fixup type %x.\n", type);
2310 return NULL;
2312 relocs++;
2314 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2318 /******************************************************************
2319 * LdrQueryProcessModuleInformation
2322 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2323 ULONG buf_size, ULONG* req_size)
2325 SYSTEM_MODULE* sm = &smi->Modules[0];
2326 ULONG size = sizeof(ULONG);
2327 NTSTATUS nts = STATUS_SUCCESS;
2328 ANSI_STRING str;
2329 char* ptr;
2330 PLIST_ENTRY mark, entry;
2331 PLDR_MODULE mod;
2332 WORD id = 0;
2334 smi->ModulesCount = 0;
2336 RtlEnterCriticalSection( &loader_section );
2337 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2338 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2340 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2341 size += sizeof(*sm);
2342 if (size <= buf_size)
2344 sm->Reserved1 = 0; /* FIXME */
2345 sm->Reserved2 = 0; /* FIXME */
2346 sm->ImageBaseAddress = mod->BaseAddress;
2347 sm->ImageSize = mod->SizeOfImage;
2348 sm->Flags = mod->Flags;
2349 sm->Id = id++;
2350 sm->Rank = 0; /* FIXME */
2351 sm->Unknown = 0; /* FIXME */
2352 str.Length = 0;
2353 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2354 str.Buffer = (char*)sm->Name;
2355 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2356 ptr = strrchr(str.Buffer, '\\');
2357 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2359 smi->ModulesCount++;
2360 sm++;
2362 else nts = STATUS_INFO_LENGTH_MISMATCH;
2364 RtlLeaveCriticalSection( &loader_section );
2366 if (req_size) *req_size = size;
2368 return nts;
2372 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2374 NTSTATUS status;
2375 UNICODE_STRING str;
2376 ULONG size;
2377 WCHAR buffer[64];
2378 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2380 RtlInitUnicodeString( &str, name );
2382 size = sizeof(buffer) - sizeof(WCHAR);
2383 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2384 return status;
2386 if (info->Type != REG_DWORD)
2388 buffer[size / sizeof(WCHAR)] = 0;
2389 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2391 else memcpy( value, info->Data, sizeof(*value) );
2392 return status;
2395 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2396 void *data, ULONG in_size, ULONG *out_size )
2398 NTSTATUS status;
2399 UNICODE_STRING str;
2400 ULONG size;
2401 char *buffer;
2402 KEY_VALUE_PARTIAL_INFORMATION *info;
2403 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2405 RtlInitUnicodeString( &str, name );
2407 size = info_size + in_size;
2408 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2409 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2410 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2411 if (!status || status == STATUS_BUFFER_OVERFLOW)
2413 if (out_size) *out_size = info->DataLength;
2414 if (data && !status) memcpy( data, info->Data, info->DataLength );
2416 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2417 return status;
2421 /******************************************************************
2422 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2424 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2425 void *data, ULONG in_size, ULONG *out_size )
2427 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2428 'S','o','f','t','w','a','r','e','\\',
2429 'M','i','c','r','o','s','o','f','t','\\',
2430 'W','i','n','d','o','w','s',' ','N','T','\\',
2431 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2432 'I','m','a','g','e',' ','F','i','l','e',' ',
2433 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2434 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2435 OBJECT_ATTRIBUTES attr;
2436 UNICODE_STRING name_str;
2437 HANDLE hkey;
2438 NTSTATUS status;
2439 ULONG len;
2440 WCHAR *p;
2442 attr.Length = sizeof(attr);
2443 attr.RootDirectory = 0;
2444 attr.ObjectName = &name_str;
2445 attr.Attributes = OBJ_CASE_INSENSITIVE;
2446 attr.SecurityDescriptor = NULL;
2447 attr.SecurityQualityOfService = NULL;
2449 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2450 else p = key->Buffer;
2451 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2452 name_str.Buffer = path;
2453 name_str.Length = sizeof(optionsW) + len;
2454 name_str.MaximumLength = name_str.Length;
2455 memcpy( path, optionsW, sizeof(optionsW) );
2456 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2457 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2459 if (type == REG_DWORD)
2461 if (out_size) *out_size = sizeof(ULONG);
2462 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2463 else status = STATUS_BUFFER_OVERFLOW;
2465 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2467 NtClose( hkey );
2468 return status;
2472 /******************************************************************
2473 * RtlDllShutdownInProgress (NTDLL.@)
2475 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2477 return process_detaching;
2480 /****************************************************************************
2481 * LdrResolveDelayLoadedAPI (NTDLL.@)
2483 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2484 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2485 IMAGE_THUNK_DATA* addr, ULONG flags )
2487 IMAGE_THUNK_DATA *pIAT, *pINT;
2488 DELAYLOAD_INFO delayinfo;
2489 UNICODE_STRING mod;
2490 const CHAR* name;
2491 HMODULE *phmod;
2492 NTSTATUS nts;
2493 FARPROC fp;
2494 DWORD id;
2496 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2498 phmod = get_rva(base, desc->ModuleHandleRVA);
2499 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2500 pINT = get_rva(base, desc->ImportNameTableRVA);
2501 name = get_rva(base, desc->DllNameRVA);
2502 id = addr - pIAT;
2504 if (!*phmod)
2506 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2508 nts = STATUS_NO_MEMORY;
2509 goto fail;
2511 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2512 RtlFreeUnicodeString(&mod);
2513 if (nts) goto fail;
2516 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2517 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2518 else
2520 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2521 ANSI_STRING fnc;
2523 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2524 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2526 if (!nts)
2528 pIAT[id].u1.Function = (ULONG_PTR)fp;
2529 return fp;
2532 fail:
2533 delayinfo.Size = sizeof(delayinfo);
2534 delayinfo.DelayloadDescriptor = desc;
2535 delayinfo.ThunkAddress = addr;
2536 delayinfo.TargetDllName = name;
2537 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2538 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2539 delayinfo.TargetModuleBase = *phmod;
2540 delayinfo.Unused = NULL;
2541 delayinfo.LastError = nts;
2542 return dllhook(4, &delayinfo);
2545 /******************************************************************
2546 * LdrShutdownProcess (NTDLL.@)
2549 void WINAPI LdrShutdownProcess(void)
2551 TRACE("()\n");
2552 process_detaching = TRUE;
2553 process_detach();
2557 /******************************************************************
2558 * RtlExitUserProcess (NTDLL.@)
2560 void WINAPI RtlExitUserProcess( DWORD status )
2562 RtlEnterCriticalSection( &loader_section );
2563 RtlAcquirePebLock();
2564 NtTerminateProcess( 0, status );
2565 LdrShutdownProcess();
2566 NtTerminateProcess( GetCurrentProcess(), status );
2567 exit( status );
2570 /******************************************************************
2571 * LdrShutdownThread (NTDLL.@)
2574 void WINAPI LdrShutdownThread(void)
2576 PLIST_ENTRY mark, entry;
2577 PLDR_MODULE mod;
2578 UINT i;
2579 void **pointers;
2581 TRACE("()\n");
2583 /* don't do any detach calls if process is exiting */
2584 if (process_detaching) return;
2586 RtlEnterCriticalSection( &loader_section );
2588 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2589 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2591 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2592 InInitializationOrderModuleList);
2593 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2594 continue;
2595 if ( mod->Flags & LDR_NO_DLL_CALLS )
2596 continue;
2598 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2599 DLL_THREAD_DETACH, NULL );
2602 RtlAcquirePebLock();
2603 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2604 RtlReleasePebLock();
2606 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2608 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2609 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2611 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2612 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2613 RtlLeaveCriticalSection( &loader_section );
2617 /***********************************************************************
2618 * free_modref
2621 static void free_modref( WINE_MODREF *wm )
2623 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2624 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2625 if (wm->ldr.InInitializationOrderModuleList.Flink)
2626 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2628 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2629 if (!TRACE_ON(module))
2630 TRACE_(loaddll)("Unloaded module %s : %s\n",
2631 debugstr_w(wm->ldr.FullDllName.Buffer),
2632 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2634 SERVER_START_REQ( unload_dll )
2636 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2637 wine_server_call( req );
2639 SERVER_END_REQ;
2641 free_tls_slot( &wm->ldr );
2642 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2643 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2644 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2645 if (cached_modref == wm) cached_modref = NULL;
2646 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2647 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2648 RtlFreeHeap( GetProcessHeap(), 0, wm );
2651 /***********************************************************************
2652 * MODULE_FlushModrefs
2654 * Remove all unused modrefs and call the internal unloading routines
2655 * for the library type.
2657 * The loader_section must be locked while calling this function.
2659 static void MODULE_FlushModrefs(void)
2661 PLIST_ENTRY mark, entry, prev;
2662 PLDR_MODULE mod;
2663 WINE_MODREF*wm;
2665 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2666 for (entry = mark->Blink; entry != mark; entry = prev)
2668 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2669 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2670 prev = entry->Blink;
2671 if (!mod->LoadCount) free_modref( wm );
2674 /* check load order list too for modules that haven't been initialized yet */
2675 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2676 for (entry = mark->Blink; entry != mark; entry = prev)
2678 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2679 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2680 prev = entry->Blink;
2681 if (!mod->LoadCount) free_modref( wm );
2685 /***********************************************************************
2686 * MODULE_DecRefCount
2688 * The loader_section must be locked while calling this function.
2690 static void MODULE_DecRefCount( WINE_MODREF *wm )
2692 int i;
2694 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2695 return;
2697 if ( wm->ldr.LoadCount <= 0 )
2698 return;
2700 --wm->ldr.LoadCount;
2701 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2703 if ( wm->ldr.LoadCount == 0 )
2705 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2707 for ( i = 0; i < wm->nDeps; i++ )
2708 if ( wm->deps[i] )
2709 MODULE_DecRefCount( wm->deps[i] );
2711 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2715 /******************************************************************
2716 * LdrUnloadDll (NTDLL.@)
2720 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2722 WINE_MODREF *wm;
2723 NTSTATUS retv = STATUS_SUCCESS;
2725 if (process_detaching) return retv;
2727 TRACE("(%p)\n", hModule);
2729 RtlEnterCriticalSection( &loader_section );
2731 free_lib_count++;
2732 if ((wm = get_modref( hModule )) != NULL)
2734 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2736 /* Recursively decrement reference counts */
2737 MODULE_DecRefCount( wm );
2739 /* Call process detach notifications */
2740 if ( free_lib_count <= 1 )
2742 process_detach();
2743 MODULE_FlushModrefs();
2746 TRACE("END\n");
2748 else
2749 retv = STATUS_DLL_NOT_FOUND;
2751 free_lib_count--;
2753 RtlLeaveCriticalSection( &loader_section );
2755 return retv;
2758 /***********************************************************************
2759 * RtlImageNtHeader (NTDLL.@)
2761 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2763 IMAGE_NT_HEADERS *ret;
2765 __TRY
2767 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2769 ret = NULL;
2770 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2772 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2773 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2776 __EXCEPT_PAGE_FAULT
2778 return NULL;
2780 __ENDTRY
2781 return ret;
2785 /***********************************************************************
2786 * attach_process_dlls
2788 * Initial attach to all the dlls loaded by the process.
2790 static NTSTATUS attach_process_dlls( void *wm )
2792 NTSTATUS status;
2794 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2796 RtlEnterCriticalSection( &loader_section );
2797 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2799 if (last_failed_modref)
2800 ERR( "%s failed to initialize, aborting\n",
2801 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2802 return status;
2804 attach_implicitly_loaded_dlls( (LPVOID)1 );
2805 RtlLeaveCriticalSection( &loader_section );
2806 return status;
2810 /***********************************************************************
2811 * load_global_options
2813 static void load_global_options(void)
2815 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2816 'S','y','s','t','e','m','\\',
2817 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2818 'C','o','n','t','r','o','l','\\',
2819 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2820 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2821 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};
2822 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2823 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2824 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};
2825 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};
2827 OBJECT_ATTRIBUTES attr;
2828 UNICODE_STRING name_str;
2829 HANDLE hkey;
2830 ULONG value;
2832 attr.Length = sizeof(attr);
2833 attr.RootDirectory = 0;
2834 attr.ObjectName = &name_str;
2835 attr.Attributes = OBJ_CASE_INSENSITIVE;
2836 attr.SecurityDescriptor = NULL;
2837 attr.SecurityQualityOfService = NULL;
2838 RtlInitUnicodeString( &name_str, sessionW );
2840 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2842 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2844 query_dword_option( hkey, critsectW, &value );
2845 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2847 query_dword_option( hkey, heapresW, &value );
2848 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2850 query_dword_option( hkey, heapcommitW, &value );
2851 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2853 query_dword_option( hkey, decommittotalW, &value );
2854 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2856 query_dword_option( hkey, decommitfreeW, &value );
2857 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2859 NtClose( hkey );
2863 /***********************************************************************
2864 * start_process
2866 static void start_process( void *kernel_start )
2868 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2871 /******************************************************************
2872 * LdrInitializeThunk (NTDLL.@)
2875 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2876 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2878 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2879 NTSTATUS status;
2880 WINE_MODREF *wm;
2881 LPCWSTR load_path;
2882 PEB *peb = NtCurrentTeb()->Peb;
2884 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2886 /* allocate the modref for the main exe (if not already done) */
2887 wm = get_modref( peb->ImageBaseAddress );
2888 assert( wm );
2889 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2891 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2892 exit(1);
2895 peb->LoaderLock = &loader_section;
2896 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2897 if (!peb->ProcessParameters->WindowTitle.Buffer)
2898 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2899 version_init( wm->ldr.FullDllName.Buffer );
2900 virtual_set_large_address_space();
2902 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2903 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2905 /* the main exe needs to be the first in the load order list */
2906 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2907 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2909 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2910 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2912 actctx_init();
2913 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2914 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2915 heap_set_debug_flags( GetProcessHeap() );
2917 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2918 if (status != STATUS_SUCCESS) goto error;
2920 virtual_release_address_space();
2921 virtual_clear_thread_stack();
2922 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2924 error:
2925 ERR( "Main exe initialization for %s failed, status %x\n",
2926 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2927 NtTerminateProcess( GetCurrentProcess(), status );
2931 /***********************************************************************
2932 * RtlImageDirectoryEntryToData (NTDLL.@)
2934 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2936 const IMAGE_NT_HEADERS *nt;
2937 DWORD addr;
2939 if ((ULONG_PTR)module & 1) /* mapped as data file */
2941 module = (HMODULE)((ULONG_PTR)module & ~1);
2942 image = FALSE;
2944 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2945 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2947 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2949 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2950 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2951 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2952 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2954 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2956 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2958 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2959 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2960 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2961 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2963 else return NULL;
2965 /* not mapped as image, need to find the section containing the virtual address */
2966 return RtlImageRvaToVa( nt, module, addr, NULL );
2970 /***********************************************************************
2971 * RtlImageRvaToSection (NTDLL.@)
2973 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2974 HMODULE module, DWORD rva )
2976 int i;
2977 const IMAGE_SECTION_HEADER *sec;
2979 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2980 nt->FileHeader.SizeOfOptionalHeader);
2981 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2983 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2984 return (PIMAGE_SECTION_HEADER)sec;
2986 return NULL;
2990 /***********************************************************************
2991 * RtlImageRvaToVa (NTDLL.@)
2993 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2994 DWORD rva, IMAGE_SECTION_HEADER **section )
2996 IMAGE_SECTION_HEADER *sec;
2998 if (section && *section) /* try this section first */
3000 sec = *section;
3001 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3002 goto found;
3004 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3005 found:
3006 if (section) *section = sec;
3007 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3011 /***********************************************************************
3012 * RtlPcToFileHeader (NTDLL.@)
3014 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3016 LDR_MODULE *module;
3017 PVOID ret = NULL;
3019 RtlEnterCriticalSection( &loader_section );
3020 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3021 RtlLeaveCriticalSection( &loader_section );
3022 *address = ret;
3023 return ret;
3027 /***********************************************************************
3028 * NtLoadDriver (NTDLL.@)
3029 * ZwLoadDriver (NTDLL.@)
3031 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3033 FIXME("(%p), stub!\n",DriverServiceName);
3034 return STATUS_NOT_IMPLEMENTED;
3038 /***********************************************************************
3039 * NtUnloadDriver (NTDLL.@)
3040 * ZwUnloadDriver (NTDLL.@)
3042 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3044 FIXME("(%p), stub!\n",DriverServiceName);
3045 return STATUS_NOT_IMPLEMENTED;
3049 /******************************************************************
3050 * DllMain (NTDLL.@)
3052 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3054 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3055 return TRUE;
3059 /******************************************************************
3060 * __wine_init_windows_dir (NTDLL.@)
3062 * Windows and system dir initialization once kernel32 has been loaded.
3064 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3066 PLIST_ENTRY mark, entry;
3067 LPWSTR buffer, p;
3069 strcpyW( user_shared_data->NtSystemRoot, windir );
3070 DIR_init_windows_dir( windir, sysdir );
3072 /* prepend the system dir to the name of the already created modules */
3073 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3074 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3076 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3078 assert( mod->Flags & LDR_WINE_INTERNAL );
3080 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3081 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3082 if (!buffer) continue;
3083 strcpyW( buffer, system_dir.Buffer );
3084 p = buffer + strlenW( buffer );
3085 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3086 strcpyW( p, mod->FullDllName.Buffer );
3087 RtlInitUnicodeString( &mod->FullDllName, buffer );
3088 RtlInitUnicodeString( &mod->BaseDllName, p );
3093 /***********************************************************************
3094 * __wine_process_init
3096 void __wine_process_init(void)
3098 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3100 WINE_MODREF *wm;
3101 NTSTATUS status;
3102 ANSI_STRING func_name;
3103 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3105 main_exe_file = thread_init();
3107 /* retrieve current umask */
3108 FILE_umask = umask(0777);
3109 umask( FILE_umask );
3111 load_global_options();
3113 /* setup the load callback and create ntdll modref */
3114 wine_dll_set_callback( load_builtin_callback );
3116 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3118 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3119 exit(1);
3121 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3122 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3124 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3125 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3126 0, (void **)&init_func )) != STATUS_SUCCESS)
3128 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3129 exit(1);
3131 init_func();