d3d8: Get rid of the format switching code in d3d8_device_CopyRects().
[wine.git] / dlls / ntdll / loader.c
blob18ae29c72d3531e924f92a64a375e199951fa981
1 /*
2 * Loader functions
4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdarg.h>
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
29 #endif
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winnt.h"
38 #include "winternl.h"
39 #include "delayloadhandler.h"
41 #include "wine/exception.h"
42 #include "wine/library.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45 #include "wine/server.h"
46 #include "ntdll_misc.h"
47 #include "ddk/wdm.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(module);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
51 WINE_DECLARE_DEBUG_CHANNEL(snoop);
52 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
53 WINE_DECLARE_DEBUG_CHANNEL(imports);
55 /* we don't want to include winuser.h */
56 #define RT_MANIFEST ((ULONG_PTR)24)
57 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
59 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
61 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
62 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
64 static const char * const reason_names[] =
66 "PROCESS_DETACH",
67 "PROCESS_ATTACH",
68 "THREAD_ATTACH",
69 "THREAD_DETACH",
70 NULL, NULL, NULL, NULL,
71 "WINE_PREATTACH"
74 static const WCHAR dllW[] = {'.','d','l','l',0};
76 /* internal representation of 32bit modules. per process. */
77 typedef struct _wine_modref
79 LDR_MODULE ldr;
80 int nDeps;
81 struct _wine_modref **deps;
82 } WINE_MODREF;
84 /* info about the current builtin dll load */
85 /* used to keep track of things across the register_dll constructor call */
86 struct builtin_load_info
88 const WCHAR *load_path;
89 const WCHAR *filename;
90 NTSTATUS status;
91 WINE_MODREF *wm;
94 static struct builtin_load_info default_load_info;
95 static struct builtin_load_info *builtin_load_info = &default_load_info;
97 static HANDLE main_exe_file;
98 static UINT tls_module_count; /* number of modules with TLS directory */
99 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
100 LIST_ENTRY tls_links = { &tls_links, &tls_links };
102 static RTL_CRITICAL_SECTION loader_section;
103 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
105 0, 0, &loader_section,
106 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
107 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
109 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
111 static WINE_MODREF *cached_modref;
112 static WINE_MODREF *current_modref;
113 static WINE_MODREF *last_failed_modref;
115 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
116 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
117 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
118 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
119 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
120 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
122 /* convert PE image VirtualAddress to Real Address */
123 static inline void *get_rva( HMODULE module, DWORD va )
125 return (void *)((char *)module + va);
128 /* check whether the file name contains a path */
129 static inline BOOL contains_path( LPCWSTR name )
131 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
134 /* convert from straight ASCII to Unicode without depending on the current codepage */
135 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
137 while (len--) *dst++ = (unsigned char)*src++;
141 /*************************************************************************
142 * call_dll_entry_point
144 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
145 * their entry point, so we need a small asm wrapper. Testing indicates
146 * that only modifying esi leads to a crash, so use this one to backup
147 * ebp while running the dll entry proc.
149 #ifdef __i386__
150 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
151 __ASM_GLOBAL_FUNC(call_dll_entry_point,
152 "pushl %ebp\n\t"
153 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
154 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
155 "movl %esp,%ebp\n\t"
156 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
157 "pushl %ebx\n\t"
158 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
159 "pushl %esi\n\t"
160 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
161 "pushl %edi\n\t"
162 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
163 "movl %ebp,%esi\n\t"
164 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
165 "pushl 20(%ebp)\n\t"
166 "pushl 16(%ebp)\n\t"
167 "pushl 12(%ebp)\n\t"
168 "movl 8(%ebp),%eax\n\t"
169 "call *%eax\n\t"
170 "movl %esi,%ebp\n\t"
171 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
172 "leal -12(%ebp),%esp\n\t"
173 "popl %edi\n\t"
174 __ASM_CFI(".cfi_same_value %edi\n\t")
175 "popl %esi\n\t"
176 __ASM_CFI(".cfi_same_value %esi\n\t")
177 "popl %ebx\n\t"
178 __ASM_CFI(".cfi_same_value %ebx\n\t")
179 "popl %ebp\n\t"
180 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
181 __ASM_CFI(".cfi_same_value %ebp\n\t")
182 "ret" )
183 #else /* __i386__ */
184 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
185 UINT reason, void *reserved )
187 return proc( module, reason, reserved );
189 #endif /* __i386__ */
192 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
193 /*************************************************************************
194 * stub_entry_point
196 * Entry point for stub functions.
198 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
200 EXCEPTION_RECORD rec;
202 rec.ExceptionCode = EXCEPTION_WINE_STUB;
203 rec.ExceptionFlags = EH_NONCONTINUABLE;
204 rec.ExceptionRecord = NULL;
205 rec.ExceptionAddress = ret_addr;
206 rec.NumberParameters = 2;
207 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
208 rec.ExceptionInformation[1] = (ULONG_PTR)name;
209 for (;;) RtlRaiseException( &rec );
213 #include "pshpack1.h"
214 #ifdef __i386__
215 struct stub
217 BYTE pushl1; /* pushl $name */
218 const char *name;
219 BYTE pushl2; /* pushl $dll */
220 const char *dll;
221 BYTE call; /* call stub_entry_point */
222 DWORD entry;
224 #elif defined(__arm__)
225 struct stub
227 BYTE ldr_r0[4]; /* ldr r0, $dll */
228 BYTE mov_pc_pc1[4]; /* mov pc,pc */
229 const char *dll;
230 BYTE ldr_r1[4]; /* ldr r1, $name */
231 BYTE mov_pc_pc2[4]; /* mov pc,pc */
232 const char *name;
233 BYTE mov_r2_lr[4]; /* mov r2, lr */
234 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #-4] */
235 const void* entry;
237 #else
238 struct stub
240 BYTE movq_rdi[2]; /* movq $dll,%rdi */
241 const char *dll;
242 BYTE movq_rsi[2]; /* movq $name,%rsi */
243 const char *name;
244 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
245 BYTE movq_rax[2]; /* movq $entry, %rax */
246 const void* entry;
247 BYTE jmpq_rax[2]; /* jmp %rax */
249 #endif
250 #include "poppack.h"
252 /*************************************************************************
253 * allocate_stub
255 * Allocate a stub entry point.
257 static ULONG_PTR allocate_stub( const char *dll, const char *name )
259 #define MAX_SIZE 65536
260 static struct stub *stubs;
261 static unsigned int nb_stubs;
262 struct stub *stub;
264 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
266 if (!stubs)
268 SIZE_T size = MAX_SIZE;
269 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
270 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
271 return 0xdeadbeef;
273 stub = &stubs[nb_stubs++];
274 #ifdef __i386__
275 stub->pushl1 = 0x68; /* pushl $name */
276 stub->name = name;
277 stub->pushl2 = 0x68; /* pushl $dll */
278 stub->dll = dll;
279 stub->call = 0xe8; /* call stub_entry_point */
280 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
281 #elif defined(__arm__)
282 stub->ldr_r0[0] = 0x00; /* ldr r0, $dll */
283 stub->ldr_r0[1] = 0x00;
284 stub->ldr_r0[2] = 0x9f;
285 stub->ldr_r0[3] = 0xe5;
286 stub->mov_pc_pc1[0] = 0x0f; /* mov pc,pc */
287 stub->mov_pc_pc1[1] = 0xf0;
288 stub->mov_pc_pc1[2] = 0xa0;
289 stub->mov_pc_pc1[3] = 0xe1;
290 stub->dll = dll;
291 stub->ldr_r1[0] = 0x00; /* ldr r1, $name */
292 stub->ldr_r1[1] = 0x10;
293 stub->ldr_r1[2] = 0x9f;
294 stub->ldr_r1[3] = 0xe5;
295 stub->mov_pc_pc2[0] = 0x0f; /* mov pc,pc */
296 stub->mov_pc_pc2[1] = 0xf0;
297 stub->mov_pc_pc2[2] = 0xa0;
298 stub->mov_pc_pc2[3] = 0xe1;
299 stub->name = name;
300 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
301 stub->mov_r2_lr[1] = 0x20;
302 stub->mov_r2_lr[2] = 0xa0;
303 stub->mov_r2_lr[3] = 0xe1;
304 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #-4] */
305 stub->ldr_pc_pc[1] = 0xf0;
306 stub->ldr_pc_pc[2] = 0x1f;
307 stub->ldr_pc_pc[3] = 0xe5;
308 stub->entry = stub_entry_point;
309 #else
310 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
311 stub->movq_rdi[1] = 0xbf;
312 stub->dll = dll;
313 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
314 stub->movq_rsi[1] = 0xbe;
315 stub->name = name;
316 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
317 stub->movq_rsp_rdx[1] = 0x8b;
318 stub->movq_rsp_rdx[2] = 0x14;
319 stub->movq_rsp_rdx[3] = 0x24;
320 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
321 stub->movq_rax[1] = 0xb8;
322 stub->entry = stub_entry_point;
323 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
324 stub->jmpq_rax[1] = 0xe0;
325 #endif
326 return (ULONG_PTR)stub;
329 #else /* __i386__ */
330 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
331 #endif /* __i386__ */
334 /*************************************************************************
335 * get_modref
337 * Looks for the referenced HMODULE in the current process
338 * The loader_section must be locked while calling this function.
340 static WINE_MODREF *get_modref( HMODULE hmod )
342 PLIST_ENTRY mark, entry;
343 PLDR_MODULE mod;
345 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
347 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
348 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
350 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
351 if (mod->BaseAddress == hmod)
352 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
353 if (mod->BaseAddress > (void*)hmod) break;
355 return NULL;
359 /**********************************************************************
360 * find_basename_module
362 * Find a module from its base name.
363 * The loader_section must be locked while calling this function
365 static WINE_MODREF *find_basename_module( LPCWSTR name )
367 PLIST_ENTRY mark, entry;
369 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
370 return cached_modref;
372 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
373 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
375 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
376 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
378 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
379 return cached_modref;
382 return NULL;
386 /**********************************************************************
387 * find_fullname_module
389 * Find a module from its full path name.
390 * The loader_section must be locked while calling this function
392 static WINE_MODREF *find_fullname_module( LPCWSTR name )
394 PLIST_ENTRY mark, entry;
396 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
397 return cached_modref;
399 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
400 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
402 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
403 if (!strcmpiW( name, mod->FullDllName.Buffer ))
405 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
406 return cached_modref;
409 return NULL;
413 /*************************************************************************
414 * find_forwarded_export
416 * Find the final function pointer for a forwarded function.
417 * The loader_section must be locked while calling this function.
419 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
421 const IMAGE_EXPORT_DIRECTORY *exports;
422 DWORD exp_size;
423 WINE_MODREF *wm;
424 WCHAR mod_name[32];
425 const char *end = strrchr(forward, '.');
426 FARPROC proc = NULL;
428 if (!end) return NULL;
429 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
430 ascii_to_unicode( mod_name, forward, end - forward );
431 mod_name[end - forward] = 0;
432 if (!strchrW( mod_name, '.' ))
434 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
435 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
438 if (!(wm = find_basename_module( mod_name )))
440 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
441 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
442 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
444 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
446 LdrUnloadDll( wm->ldr.BaseAddress );
447 wm = NULL;
451 if (!wm)
453 ERR( "module not found for forward '%s' used by %s\n",
454 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
455 return NULL;
458 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
459 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
461 const char *name = end + 1;
462 if (*name == '#') /* ordinal */
463 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
464 else
465 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
468 if (!proc)
470 ERR("function not found for forward '%s' used by %s."
471 " If you are using builtin %s, try using the native one instead.\n",
472 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
473 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
475 return proc;
479 /*************************************************************************
480 * find_ordinal_export
482 * Find an exported function by ordinal.
483 * The exports base must have been subtracted from the ordinal already.
484 * The loader_section must be locked while calling this function.
486 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
487 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
489 FARPROC proc;
490 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
492 if (ordinal >= exports->NumberOfFunctions)
494 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
495 return NULL;
497 if (!functions[ordinal]) return NULL;
499 proc = get_rva( module, functions[ordinal] );
501 /* if the address falls into the export dir, it's a forward */
502 if (((const char *)proc >= (const char *)exports) &&
503 ((const char *)proc < (const char *)exports + exp_size))
504 return find_forwarded_export( module, (const char *)proc, load_path );
506 if (TRACE_ON(snoop))
508 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
509 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
511 if (TRACE_ON(relay))
513 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
514 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
516 return proc;
520 /*************************************************************************
521 * find_named_export
523 * Find an exported function by name.
524 * The loader_section must be locked while calling this function.
526 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
527 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
529 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
530 const DWORD *names = get_rva( module, exports->AddressOfNames );
531 int min = 0, max = exports->NumberOfNames - 1;
533 /* first check the hint */
534 if (hint >= 0 && hint <= max)
536 char *ename = get_rva( module, names[hint] );
537 if (!strcmp( ename, name ))
538 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
541 /* then do a binary search */
542 while (min <= max)
544 int res, pos = (min + max) / 2;
545 char *ename = get_rva( module, names[pos] );
546 if (!(res = strcmp( ename, name )))
547 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
548 if (res > 0) max = pos - 1;
549 else min = pos + 1;
551 return NULL;
556 /*************************************************************************
557 * import_dll
559 * Import the dll specified by the given import descriptor.
560 * The loader_section must be locked while calling this function.
562 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
564 NTSTATUS status;
565 WINE_MODREF *wmImp;
566 HMODULE imp_mod;
567 const IMAGE_EXPORT_DIRECTORY *exports;
568 DWORD exp_size;
569 const IMAGE_THUNK_DATA *import_list;
570 IMAGE_THUNK_DATA *thunk_list;
571 WCHAR buffer[32];
572 const char *name = get_rva( module, descr->Name );
573 DWORD len = strlen(name);
574 PVOID protect_base;
575 SIZE_T protect_size = 0;
576 DWORD protect_old;
578 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
579 if (descr->u.OriginalFirstThunk)
580 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
581 else
582 import_list = thunk_list;
584 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
586 if (len * sizeof(WCHAR) < sizeof(buffer))
588 ascii_to_unicode( buffer, name, len );
589 buffer[len] = 0;
590 status = load_dll( load_path, buffer, 0, &wmImp );
592 else /* need to allocate a larger buffer */
594 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
595 if (!ptr) return NULL;
596 ascii_to_unicode( ptr, name, len );
597 ptr[len] = 0;
598 status = load_dll( load_path, ptr, 0, &wmImp );
599 RtlFreeHeap( GetProcessHeap(), 0, ptr );
602 if (status)
604 if (status == STATUS_DLL_NOT_FOUND)
605 ERR("Library %s (which is needed by %s) not found\n",
606 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
607 else
608 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
609 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
610 return NULL;
613 /* unprotect the import address table since it can be located in
614 * readonly section */
615 while (import_list[protect_size].u1.Ordinal) protect_size++;
616 protect_base = thunk_list;
617 protect_size *= sizeof(*thunk_list);
618 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
619 &protect_size, PAGE_READWRITE, &protect_old );
621 imp_mod = wmImp->ldr.BaseAddress;
622 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
624 if (!exports)
626 /* set all imported function to deadbeef */
627 while (import_list->u1.Ordinal)
629 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
631 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
632 WARN("No implementation for %s.%d", name, ordinal );
633 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
635 else
637 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
638 WARN("No implementation for %s.%s", name, pe_name->Name );
639 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
641 WARN(" imported from %s, allocating stub %p\n",
642 debugstr_w(current_modref->ldr.FullDllName.Buffer),
643 (void *)thunk_list->u1.Function );
644 import_list++;
645 thunk_list++;
647 goto done;
650 while (import_list->u1.Ordinal)
652 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
654 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
656 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
657 ordinal - exports->Base, load_path );
658 if (!thunk_list->u1.Function)
660 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
661 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
662 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
663 (void *)thunk_list->u1.Function );
665 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
667 else /* import by name */
669 IMAGE_IMPORT_BY_NAME *pe_name;
670 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
671 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
672 (const char*)pe_name->Name,
673 pe_name->Hint, load_path );
674 if (!thunk_list->u1.Function)
676 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
677 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
678 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
679 (void *)thunk_list->u1.Function );
681 TRACE_(imports)("--- %s %s.%d = %p\n",
682 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
684 import_list++;
685 thunk_list++;
688 done:
689 /* restore old protection of the import address table */
690 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
691 return wmImp;
695 /***********************************************************************
696 * create_module_activation_context
698 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
700 NTSTATUS status;
701 LDR_RESOURCE_INFO info;
702 const IMAGE_RESOURCE_DATA_ENTRY *entry;
704 info.Type = RT_MANIFEST;
705 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
706 info.Language = 0;
707 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
709 ACTCTXW ctx;
710 ctx.cbSize = sizeof(ctx);
711 ctx.lpSource = NULL;
712 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
713 ctx.hModule = module->BaseAddress;
714 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
715 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
717 return status;
721 /*************************************************************************
722 * is_dll_native_subsystem
724 * Check if dll is a proper native driver.
725 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
726 * while being perfectly normal DLLs. This heuristic should catch such breakages.
728 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
730 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
731 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
732 const IMAGE_IMPORT_DESCRIPTOR *imports;
733 DWORD i, size;
734 WCHAR buffer[16];
736 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
737 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
739 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
740 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
742 for (i = 0; imports[i].Name; i++)
744 const char *name = get_rva( module, imports[i].Name );
745 DWORD len = strlen(name);
746 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
747 ascii_to_unicode( buffer, name, len + 1 );
748 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
750 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
751 return FALSE;
755 return TRUE;
758 /*************************************************************************
759 * alloc_tls_slot
761 * Allocate a TLS slot for a newly-loaded module.
762 * The loader_section must be locked while calling this function.
764 static SHORT alloc_tls_slot( LDR_MODULE *mod )
766 const IMAGE_TLS_DIRECTORY *dir;
767 ULONG i, size;
768 void *new_ptr;
769 LIST_ENTRY *entry;
771 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
772 return -1;
774 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
775 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
777 for (i = 0; i < tls_module_count; i++) if (!tls_dirs[i]) break;
779 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
780 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
781 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
783 if (i == tls_module_count)
785 UINT new_count = max( 32, tls_module_count * 2 );
787 if (!tls_dirs)
788 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
789 else
790 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
791 new_count * sizeof(*tls_dirs) );
792 if (!new_ptr) return -1;
794 /* resize the pointer block in all running threads */
795 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
797 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
798 void **old = teb->ThreadLocalStoragePointer;
799 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
801 if (!new) return -1;
802 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
803 teb->ThreadLocalStoragePointer = new;
804 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
805 /* FIXME: can't free old block here, should be freed at thread exit */
808 tls_dirs = new_ptr;
809 tls_module_count = new_count;
812 /* allocate the data block in all running threads */
813 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
815 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
817 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
818 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
819 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
821 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
822 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
824 RtlFreeHeap( GetProcessHeap(), 0,
825 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
828 *(DWORD *)dir->AddressOfIndex = i;
829 tls_dirs[i] = dir;
830 return i;
834 /*************************************************************************
835 * free_tls_slot
837 * Free the module TLS slot on unload.
838 * The loader_section must be locked while calling this function.
840 static void free_tls_slot( LDR_MODULE *mod )
842 ULONG i = (USHORT)mod->TlsIndex;
844 if (mod->TlsIndex == -1) return;
845 assert( i < tls_module_count );
846 tls_dirs[i] = NULL;
850 /****************************************************************
851 * fixup_imports
853 * Fixup all imports of a given module.
854 * The loader_section must be locked while calling this function.
856 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
858 int i, nb_imports;
859 const IMAGE_IMPORT_DESCRIPTOR *imports;
860 WINE_MODREF *prev;
861 DWORD size;
862 NTSTATUS status;
863 ULONG_PTR cookie;
865 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
866 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
868 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
870 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
871 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
872 return STATUS_SUCCESS;
874 nb_imports = 0;
875 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
877 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
879 if (!create_module_activation_context( &wm->ldr ))
880 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
882 /* Allocate module dependency list */
883 wm->nDeps = nb_imports;
884 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
886 /* load the imported modules. They are automatically
887 * added to the modref list of the process.
889 prev = current_modref;
890 current_modref = wm;
891 status = STATUS_SUCCESS;
892 for (i = 0; i < nb_imports; i++)
894 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
895 status = STATUS_DLL_NOT_FOUND;
897 current_modref = prev;
898 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
899 return status;
903 /*************************************************************************
904 * alloc_module
906 * Allocate a WINE_MODREF structure and add it to the process list
907 * The loader_section must be locked while calling this function.
909 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
911 WINE_MODREF *wm;
912 const WCHAR *p;
913 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
914 PLIST_ENTRY entry, mark;
916 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
918 wm->nDeps = 0;
919 wm->deps = NULL;
921 wm->ldr.BaseAddress = hModule;
922 wm->ldr.EntryPoint = NULL;
923 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
924 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
925 wm->ldr.TlsIndex = -1;
926 wm->ldr.LoadCount = 1;
927 wm->ldr.SectionHandle = NULL;
928 wm->ldr.CheckSum = 0;
929 wm->ldr.TimeDateStamp = 0;
930 wm->ldr.ActivationContext = 0;
932 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
933 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
934 else p = wm->ldr.FullDllName.Buffer;
935 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
937 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
939 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
940 if (nt->OptionalHeader.AddressOfEntryPoint)
941 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
944 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
945 &wm->ldr.InLoadOrderModuleList);
947 /* insert module in MemoryList, sorted in increasing base addresses */
948 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
949 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
951 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
952 break;
954 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
955 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
956 wm->ldr.InMemoryOrderModuleList.Flink = entry;
957 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
959 /* wait until init is called for inserting into this list */
960 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
961 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
963 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
965 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
966 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
967 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
969 return wm;
973 /*************************************************************************
974 * alloc_thread_tls
976 * Allocate the per-thread structure for module TLS storage.
978 static NTSTATUS alloc_thread_tls(void)
980 void **pointers;
981 UINT i, size;
983 if (!tls_module_count) return STATUS_SUCCESS;
985 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
986 tls_module_count * sizeof(*pointers) )))
987 return STATUS_NO_MEMORY;
989 for (i = 0; i < tls_module_count; i++)
991 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
993 if (!dir) continue;
994 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
995 if (!size && !dir->SizeOfZeroFill) continue;
997 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
999 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1000 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1001 return STATUS_NO_MEMORY;
1003 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1004 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1006 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1007 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1009 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1010 return STATUS_SUCCESS;
1014 /*************************************************************************
1015 * call_tls_callbacks
1017 static void call_tls_callbacks( HMODULE module, UINT reason )
1019 const IMAGE_TLS_DIRECTORY *dir;
1020 const PIMAGE_TLS_CALLBACK *callback;
1021 ULONG dirsize;
1023 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1024 if (!dir || !dir->AddressOfCallBacks) return;
1026 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1028 if (TRACE_ON(relay))
1029 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1030 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1031 __TRY
1033 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1035 __EXCEPT_ALL
1037 if (TRACE_ON(relay))
1038 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1039 GetCurrentThreadId(), callback, module, reason_names[reason] );
1040 return;
1042 __ENDTRY
1043 if (TRACE_ON(relay))
1044 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1045 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1050 /*************************************************************************
1051 * MODULE_InitDLL
1053 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1055 WCHAR mod_name[32];
1056 NTSTATUS status = STATUS_SUCCESS;
1057 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1058 void *module = wm->ldr.BaseAddress;
1059 BOOL retv = FALSE;
1061 /* Skip calls for modules loaded with special load flags */
1063 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1064 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1065 if (!entry) return STATUS_SUCCESS;
1067 if (TRACE_ON(relay))
1069 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1070 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1071 mod_name[len / sizeof(WCHAR)] = 0;
1072 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1073 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1074 reason_names[reason], lpReserved );
1076 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1077 reason_names[reason], lpReserved );
1079 __TRY
1081 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1082 if (!retv)
1083 status = STATUS_DLL_INIT_FAILED;
1085 __EXCEPT_ALL
1087 if (TRACE_ON(relay))
1088 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1089 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1090 status = GetExceptionCode();
1092 __ENDTRY
1094 /* The state of the module list may have changed due to the call
1095 to the dll. We cannot assume that this module has not been
1096 deleted. */
1097 if (TRACE_ON(relay))
1098 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1099 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1100 reason_names[reason], lpReserved, retv );
1101 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1103 return status;
1107 /*************************************************************************
1108 * process_attach
1110 * Send the process attach notification to all DLLs the given module
1111 * depends on (recursively). This is somewhat complicated due to the fact that
1113 * - we have to respect the module dependencies, i.e. modules implicitly
1114 * referenced by another module have to be initialized before the module
1115 * itself can be initialized
1117 * - the initialization routine of a DLL can itself call LoadLibrary,
1118 * thereby introducing a whole new set of dependencies (even involving
1119 * the 'old' modules) at any time during the whole process
1121 * (Note that this routine can be recursively entered not only directly
1122 * from itself, but also via LoadLibrary from one of the called initialization
1123 * routines.)
1125 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1126 * the process *detach* notifications to be sent in the correct order.
1127 * This must not only take into account module dependencies, but also
1128 * 'hidden' dependencies created by modules calling LoadLibrary in their
1129 * attach notification routine.
1131 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1132 * list after the attach notification has returned. This implies that the
1133 * detach notifications are called in the reverse of the sequence the attach
1134 * notifications *returned*.
1136 * The loader_section must be locked while calling this function.
1138 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1140 NTSTATUS status = STATUS_SUCCESS;
1141 ULONG_PTR cookie;
1142 int i;
1144 if (process_detaching) return status;
1146 /* prevent infinite recursion in case of cyclical dependencies */
1147 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1148 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1149 return status;
1151 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1153 /* Tag current MODREF to prevent recursive loop */
1154 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1155 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1156 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1158 /* Recursively attach all DLLs this one depends on */
1159 for ( i = 0; i < wm->nDeps; i++ )
1161 if (!wm->deps[i]) continue;
1162 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1165 /* Call DLL entry point */
1166 if (status == STATUS_SUCCESS)
1168 WINE_MODREF *prev = current_modref;
1169 current_modref = wm;
1170 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1171 if (status == STATUS_SUCCESS)
1172 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1173 else
1175 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1176 /* point to the name so LdrInitializeThunk can print it */
1177 last_failed_modref = wm;
1178 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1180 current_modref = prev;
1183 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1184 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1185 &wm->ldr.InInitializationOrderModuleList);
1187 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1188 /* Remove recursion flag */
1189 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1191 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1192 return status;
1196 /**********************************************************************
1197 * attach_implicitly_loaded_dlls
1199 * Attach to the (builtin) dlls that have been implicitly loaded because
1200 * of a dependency at the Unix level, but not imported at the Win32 level.
1202 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1204 for (;;)
1206 PLIST_ENTRY mark, entry;
1208 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1209 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1211 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1213 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1214 TRACE( "found implicitly loaded %s, attaching to it\n",
1215 debugstr_w(mod->BaseDllName.Buffer));
1216 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1217 break; /* restart the search from the start */
1219 if (entry == mark) break; /* nothing found */
1224 /*************************************************************************
1225 * process_detach
1227 * Send DLL process detach notifications. See the comment about calling
1228 * sequence at process_attach.
1230 static void process_detach(void)
1232 PLIST_ENTRY mark, entry;
1233 PLDR_MODULE mod;
1235 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1238 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1240 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1241 InInitializationOrderModuleList);
1242 /* Check whether to detach this DLL */
1243 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1244 continue;
1245 if ( mod->LoadCount && !process_detaching )
1246 continue;
1248 /* Call detach notification */
1249 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1250 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1251 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1253 /* Restart at head of WINE_MODREF list, as entries might have
1254 been added and/or removed while performing the call ... */
1255 break;
1257 } while (entry != mark);
1260 /*************************************************************************
1261 * MODULE_DllThreadAttach
1263 * Send DLL thread attach notifications. These are sent in the
1264 * reverse sequence of process detach notification.
1267 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1269 PLIST_ENTRY mark, entry;
1270 PLDR_MODULE mod;
1271 NTSTATUS status;
1273 /* don't do any attach calls if process is exiting */
1274 if (process_detaching) return STATUS_SUCCESS;
1276 RtlEnterCriticalSection( &loader_section );
1278 RtlAcquirePebLock();
1279 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1280 RtlReleasePebLock();
1282 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1284 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1285 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1287 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1288 InInitializationOrderModuleList);
1289 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1290 continue;
1291 if ( mod->Flags & LDR_NO_DLL_CALLS )
1292 continue;
1294 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1295 DLL_THREAD_ATTACH, lpReserved );
1298 done:
1299 RtlLeaveCriticalSection( &loader_section );
1300 return status;
1303 /******************************************************************
1304 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1307 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1309 WINE_MODREF *wm;
1310 NTSTATUS ret = STATUS_SUCCESS;
1312 RtlEnterCriticalSection( &loader_section );
1314 wm = get_modref( hModule );
1315 if (!wm || wm->ldr.TlsIndex != -1)
1316 ret = STATUS_DLL_NOT_FOUND;
1317 else
1318 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1320 RtlLeaveCriticalSection( &loader_section );
1322 return ret;
1325 /******************************************************************
1326 * LdrFindEntryForAddress (NTDLL.@)
1328 * The loader_section must be locked while calling this function
1330 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1332 PLIST_ENTRY mark, entry;
1333 PLDR_MODULE mod;
1335 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1336 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1338 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1339 if (mod->BaseAddress <= addr &&
1340 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1342 *pmod = mod;
1343 return STATUS_SUCCESS;
1345 if (mod->BaseAddress > addr) break;
1347 return STATUS_NO_MORE_ENTRIES;
1350 /******************************************************************
1351 * LdrLockLoaderLock (NTDLL.@)
1353 * Note: some flags are not implemented.
1354 * Flag 0x01 is used to raise exceptions on errors.
1356 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1358 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1360 if (result) *result = 0;
1361 if (magic) *magic = 0;
1362 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1363 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1364 if (!magic) return STATUS_INVALID_PARAMETER_3;
1366 if (flags & 0x2)
1368 if (!RtlTryEnterCriticalSection( &loader_section ))
1370 *result = 2;
1371 return STATUS_SUCCESS;
1373 *result = 1;
1375 else
1377 RtlEnterCriticalSection( &loader_section );
1378 if (result) *result = 1;
1380 *magic = GetCurrentThreadId();
1381 return STATUS_SUCCESS;
1385 /******************************************************************
1386 * LdrUnlockLoaderUnlock (NTDLL.@)
1388 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1390 if (magic)
1392 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1393 RtlLeaveCriticalSection( &loader_section );
1395 return STATUS_SUCCESS;
1399 /******************************************************************
1400 * LdrGetProcedureAddress (NTDLL.@)
1402 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1403 ULONG ord, PVOID *address)
1405 IMAGE_EXPORT_DIRECTORY *exports;
1406 DWORD exp_size;
1407 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1409 RtlEnterCriticalSection( &loader_section );
1411 /* check if the module itself is invalid to return the proper error */
1412 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1413 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1414 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1416 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1417 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1418 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1419 if (proc)
1421 *address = proc;
1422 ret = STATUS_SUCCESS;
1426 RtlLeaveCriticalSection( &loader_section );
1427 return ret;
1431 /***********************************************************************
1432 * is_fake_dll
1434 * Check if a loaded native dll is a Wine fake dll.
1436 static BOOL is_fake_dll( HANDLE handle )
1438 static const char fakedll_signature[] = "Wine placeholder DLL";
1439 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1440 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1441 IO_STATUS_BLOCK io;
1442 LARGE_INTEGER offset;
1444 offset.QuadPart = 0;
1445 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1446 if (io.Information < sizeof(buffer)) return FALSE;
1447 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1448 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1449 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1450 return FALSE;
1454 /***********************************************************************
1455 * get_builtin_fullname
1457 * Build the full pathname for a builtin dll.
1459 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1461 static const WCHAR soW[] = {'.','s','o',0};
1462 WCHAR *p, *fullname;
1463 size_t i, len = strlen(filename);
1465 /* check if path can correspond to the dll we have */
1466 if (path && (p = strrchrW( path, '\\' )))
1468 p++;
1469 for (i = 0; i < len; i++)
1470 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1471 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1473 /* the filename matches, use path as the full path */
1474 len += p - path;
1475 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1477 memcpy( fullname, path, len * sizeof(WCHAR) );
1478 fullname[len] = 0;
1480 return fullname;
1484 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1485 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1487 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1488 p = fullname + system_dir.Length / sizeof(WCHAR);
1489 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1490 ascii_to_unicode( p, filename, len + 1 );
1492 return fullname;
1496 /*************************************************************************
1497 * is_16bit_builtin
1499 static BOOL is_16bit_builtin( HMODULE module )
1501 const IMAGE_EXPORT_DIRECTORY *exports;
1502 DWORD exp_size;
1504 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1505 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1506 return FALSE;
1508 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1512 /***********************************************************************
1513 * load_builtin_callback
1515 * Load a library in memory; callback function for wine_dll_register
1517 static void load_builtin_callback( void *module, const char *filename )
1519 static const WCHAR emptyW[1];
1520 IMAGE_NT_HEADERS *nt;
1521 WINE_MODREF *wm;
1522 WCHAR *fullname;
1523 const WCHAR *load_path;
1525 if (!module)
1527 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1528 return;
1530 if (!(nt = RtlImageNtHeader( module )))
1532 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1533 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1534 return;
1537 virtual_create_builtin_view( module );
1539 /* create the MODREF */
1541 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1543 ERR( "can't load %s\n", filename );
1544 builtin_load_info->status = STATUS_NO_MEMORY;
1545 return;
1548 wm = alloc_module( module, fullname );
1549 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1550 if (!wm)
1552 ERR( "can't load %s\n", filename );
1553 builtin_load_info->status = STATUS_NO_MEMORY;
1554 return;
1556 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1558 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1559 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1560 is_16bit_builtin( module ))
1562 /* fixup imports */
1564 load_path = builtin_load_info->load_path;
1565 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1566 if (!load_path) load_path = emptyW;
1567 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1569 /* the module has only be inserted in the load & memory order lists */
1570 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1571 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1572 /* FIXME: free the modref */
1573 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1574 return;
1578 builtin_load_info->wm = wm;
1579 TRACE( "loaded %s %p %p\n", filename, wm, module );
1581 /* send the DLL load event */
1583 SERVER_START_REQ( load_dll )
1585 req->mapping = 0;
1586 req->base = wine_server_client_ptr( module );
1587 req->size = nt->OptionalHeader.SizeOfImage;
1588 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1589 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1590 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1591 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1592 wine_server_call( req );
1594 SERVER_END_REQ;
1596 /* setup relay debugging entry points */
1597 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1601 /******************************************************************************
1602 * load_native_dll (internal)
1604 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1605 DWORD flags, WINE_MODREF** pwm )
1607 void *module;
1608 HANDLE mapping;
1609 LARGE_INTEGER size;
1610 IMAGE_NT_HEADERS *nt;
1611 SIZE_T len = 0;
1612 WINE_MODREF *wm;
1613 NTSTATUS status;
1615 TRACE("Trying native dll %s\n", debugstr_w(name));
1617 size.QuadPart = 0;
1618 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1619 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1620 if (status != STATUS_SUCCESS) return status;
1622 module = NULL;
1623 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1624 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1625 if (status < 0) goto done;
1627 /* create the MODREF */
1629 if (!(wm = alloc_module( module, name )))
1631 status = STATUS_NO_MEMORY;
1632 goto done;
1635 /* fixup imports */
1637 nt = RtlImageNtHeader( module );
1639 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1640 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1641 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1643 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1645 /* the module has only be inserted in the load & memory order lists */
1646 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1647 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1649 /* FIXME: there are several more dangling references
1650 * left. Including dlls loaded by this dll before the
1651 * failed one. Unrolling is rather difficult with the
1652 * current structure and we can leave them lying
1653 * around with no problems, so we don't care.
1654 * As these might reference our wm, we don't free it.
1656 goto done;
1660 /* send DLL load event */
1662 SERVER_START_REQ( load_dll )
1664 req->mapping = wine_server_obj_handle( mapping );
1665 req->base = wine_server_client_ptr( module );
1666 req->size = nt->OptionalHeader.SizeOfImage;
1667 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1668 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1669 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1670 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1671 wine_server_call( req );
1673 SERVER_END_REQ;
1675 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1677 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1679 wm->ldr.LoadCount = 1;
1680 *pwm = wm;
1681 status = STATUS_SUCCESS;
1682 done:
1683 NtClose( mapping );
1684 return status;
1688 /***********************************************************************
1689 * load_builtin_dll
1691 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1692 DWORD flags, WINE_MODREF** pwm )
1694 char error[256], dllname[MAX_PATH];
1695 const WCHAR *name, *p;
1696 DWORD len, i;
1697 void *handle = NULL;
1698 struct builtin_load_info info, *prev_info;
1700 /* Fix the name in case we have a full path and extension */
1701 name = path;
1702 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1703 if ((p = strrchrW( name, '/' ))) name = p + 1;
1705 /* load_library will modify info.status. Note also that load_library can be
1706 * called several times, if the .so file we're loading has dependencies.
1707 * info.status will gather all the errors we may get while loading all these
1708 * libraries
1710 info.load_path = load_path;
1711 info.filename = NULL;
1712 info.status = STATUS_SUCCESS;
1713 info.wm = NULL;
1715 if (file) /* we have a real file, try to load it */
1717 UNICODE_STRING nt_name;
1718 ANSI_STRING unix_name;
1720 TRACE("Trying built-in %s\n", debugstr_w(path));
1722 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1723 return STATUS_DLL_NOT_FOUND;
1725 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1727 RtlFreeUnicodeString( &nt_name );
1728 return STATUS_DLL_NOT_FOUND;
1730 prev_info = builtin_load_info;
1731 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1732 builtin_load_info = &info;
1733 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1734 builtin_load_info = prev_info;
1735 RtlFreeUnicodeString( &nt_name );
1736 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1737 if (!handle)
1739 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1740 return STATUS_INVALID_IMAGE_FORMAT;
1743 else
1745 int file_exists;
1747 TRACE("Trying built-in %s\n", debugstr_w(name));
1749 /* we don't want to depend on the current codepage here */
1750 len = strlenW( name ) + 1;
1751 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1752 for (i = 0; i < len; i++)
1754 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1755 dllname[i] = (char)name[i];
1756 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1759 prev_info = builtin_load_info;
1760 builtin_load_info = &info;
1761 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1762 builtin_load_info = prev_info;
1763 if (!handle)
1765 if (!file_exists)
1767 /* The file does not exist -> WARN() */
1768 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1769 return STATUS_DLL_NOT_FOUND;
1771 /* ERR() for all other errors (missing functions, ...) */
1772 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1773 return STATUS_PROCEDURE_NOT_FOUND;
1777 if (info.status != STATUS_SUCCESS)
1779 wine_dll_unload( handle );
1780 return info.status;
1783 if (!info.wm)
1785 PLIST_ENTRY mark, entry;
1787 /* The constructor wasn't called, this means the .so is already
1788 * loaded under a different name. Try to find the wm for it. */
1790 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1791 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1793 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1794 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1796 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1797 TRACE( "Found %s at %p for builtin %s\n",
1798 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1799 break;
1802 wine_dll_unload( handle ); /* release the libdl refcount */
1803 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1804 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1806 else
1808 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1809 info.wm->ldr.LoadCount = 1;
1810 info.wm->ldr.SectionHandle = handle;
1813 *pwm = info.wm;
1814 return STATUS_SUCCESS;
1818 /***********************************************************************
1819 * find_actctx_dll
1821 * Find the full path (if any) of the dll from the activation context.
1823 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1825 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1826 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1828 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1829 ACTCTX_SECTION_KEYED_DATA data;
1830 UNICODE_STRING nameW;
1831 NTSTATUS status;
1832 SIZE_T needed, size = 1024;
1833 WCHAR *p;
1835 RtlInitUnicodeString( &nameW, libname );
1836 data.cbSize = sizeof(data);
1837 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1838 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1839 &nameW, &data );
1840 if (status != STATUS_SUCCESS) return status;
1842 for (;;)
1844 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1846 status = STATUS_NO_MEMORY;
1847 goto done;
1849 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1850 AssemblyDetailedInformationInActivationContext,
1851 info, size, &needed );
1852 if (status == STATUS_SUCCESS) break;
1853 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1854 RtlFreeHeap( GetProcessHeap(), 0, info );
1855 size = needed;
1856 /* restart with larger buffer */
1859 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1861 status = STATUS_SXS_KEY_NOT_FOUND;
1862 goto done;
1865 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1867 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1869 p++;
1870 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1872 /* manifest name does not match directory name, so it's not a global
1873 * windows/winsxs manifest; use the manifest directory name instead */
1874 dirlen = p - info->lpAssemblyManifestPath;
1875 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1876 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1878 status = STATUS_NO_MEMORY;
1879 goto done;
1881 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1882 p += dirlen;
1883 strcpyW( p, libname );
1884 goto done;
1888 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1889 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1891 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1893 status = STATUS_NO_MEMORY;
1894 goto done;
1896 strcpyW( p, user_shared_data->NtSystemRoot );
1897 p += strlenW(p);
1898 memcpy( p, winsxsW, sizeof(winsxsW) );
1899 p += sizeof(winsxsW) / sizeof(WCHAR);
1900 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1901 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1902 *p++ = '\\';
1903 strcpyW( p, libname );
1904 done:
1905 RtlFreeHeap( GetProcessHeap(), 0, info );
1906 RtlReleaseActivationContext( data.hActCtx );
1907 return status;
1911 /***********************************************************************
1912 * find_dll_file
1914 * Find the file (or already loaded module) for a given dll name.
1916 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1917 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1919 OBJECT_ATTRIBUTES attr;
1920 IO_STATUS_BLOCK io;
1921 UNICODE_STRING nt_name;
1922 WCHAR *file_part, *ext, *dllname;
1923 ULONG len;
1925 /* first append .dll if needed */
1927 dllname = NULL;
1928 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1930 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1931 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1932 return STATUS_NO_MEMORY;
1933 strcpyW( dllname, libname );
1934 strcatW( dllname, dllW );
1935 libname = dllname;
1938 nt_name.Buffer = NULL;
1940 if (!contains_path( libname ))
1942 NTSTATUS status;
1943 WCHAR *fullname = NULL;
1945 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1947 status = find_actctx_dll( libname, &fullname );
1948 if (status == STATUS_SUCCESS)
1950 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1951 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1952 libname = dllname = fullname;
1954 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1956 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1957 return status;
1961 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1963 /* we need to search for it */
1964 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1965 if (len)
1967 if (len >= *size) goto overflow;
1968 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1970 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1972 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1973 return STATUS_NO_MEMORY;
1975 attr.Length = sizeof(attr);
1976 attr.RootDirectory = 0;
1977 attr.Attributes = OBJ_CASE_INSENSITIVE;
1978 attr.ObjectName = &nt_name;
1979 attr.SecurityDescriptor = NULL;
1980 attr.SecurityQualityOfService = NULL;
1981 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
1982 goto found;
1985 /* not found */
1987 if (!contains_path( libname ))
1989 /* if libname doesn't contain a path at all, we simply return the name as is,
1990 * to be loaded as builtin */
1991 len = strlenW(libname) * sizeof(WCHAR);
1992 if (len >= *size) goto overflow;
1993 strcpyW( filename, libname );
1994 goto found;
1998 /* absolute path name, or relative path name but not found above */
2000 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2002 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2003 return STATUS_NO_MEMORY;
2005 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2006 if (len >= *size) goto overflow;
2007 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2008 if (!(*pwm = find_fullname_module( filename )) && handle)
2010 attr.Length = sizeof(attr);
2011 attr.RootDirectory = 0;
2012 attr.Attributes = OBJ_CASE_INSENSITIVE;
2013 attr.ObjectName = &nt_name;
2014 attr.SecurityDescriptor = NULL;
2015 attr.SecurityQualityOfService = NULL;
2016 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2018 found:
2019 RtlFreeUnicodeString( &nt_name );
2020 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2021 return STATUS_SUCCESS;
2023 overflow:
2024 RtlFreeUnicodeString( &nt_name );
2025 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2026 *size = len + sizeof(WCHAR);
2027 return STATUS_BUFFER_TOO_SMALL;
2031 /***********************************************************************
2032 * load_dll (internal)
2034 * Load a PE style module according to the load order.
2035 * The loader_section must be locked while calling this function.
2037 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2039 enum loadorder loadorder;
2040 WCHAR buffer[32];
2041 WCHAR *filename;
2042 ULONG size;
2043 WINE_MODREF *main_exe;
2044 HANDLE handle = 0;
2045 NTSTATUS nts;
2047 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2049 *pwm = NULL;
2050 filename = buffer;
2051 size = sizeof(buffer);
2052 for (;;)
2054 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2055 if (nts == STATUS_SUCCESS) break;
2056 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2057 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2058 /* grow the buffer and retry */
2059 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2062 if (*pwm) /* found already loaded module */
2064 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2066 TRACE("Found %s for %s at %p, count=%d\n",
2067 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2068 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2069 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2070 return STATUS_SUCCESS;
2073 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2074 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2076 if (handle && is_fake_dll( handle ))
2078 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2079 NtClose( handle );
2080 handle = 0;
2083 switch(loadorder)
2085 case LO_INVALID:
2086 nts = STATUS_NO_MEMORY;
2087 break;
2088 case LO_DISABLED:
2089 nts = STATUS_DLL_NOT_FOUND;
2090 break;
2091 case LO_NATIVE:
2092 case LO_NATIVE_BUILTIN:
2093 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2094 else
2096 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2097 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2098 /* not in PE format, maybe it's a builtin */
2099 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2101 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2102 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2103 break;
2104 case LO_BUILTIN:
2105 case LO_BUILTIN_NATIVE:
2106 case LO_DEFAULT: /* default is builtin,native */
2107 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2108 if (!handle) break; /* nothing else we can try */
2109 /* file is not a builtin library, try without using the specified file */
2110 if (nts != STATUS_SUCCESS)
2111 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2112 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2113 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2115 /* stub-only dll, try native */
2116 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2117 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2118 nts = STATUS_DLL_NOT_FOUND;
2120 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2121 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2122 break;
2125 if (nts == STATUS_SUCCESS)
2127 /* Initialize DLL just loaded */
2128 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2129 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2130 (*pwm)->ldr.BaseAddress);
2131 if (handle) NtClose( handle );
2132 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2133 return nts;
2136 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2137 if (handle) NtClose( handle );
2138 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2139 return nts;
2142 /******************************************************************
2143 * LdrLoadDll (NTDLL.@)
2145 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2146 const UNICODE_STRING *libname, HMODULE* hModule)
2148 WINE_MODREF *wm;
2149 NTSTATUS nts;
2151 RtlEnterCriticalSection( &loader_section );
2153 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2154 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2156 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2158 nts = process_attach( wm, NULL );
2159 if (nts != STATUS_SUCCESS)
2161 LdrUnloadDll(wm->ldr.BaseAddress);
2162 wm = NULL;
2165 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2167 RtlLeaveCriticalSection( &loader_section );
2168 return nts;
2172 /******************************************************************
2173 * LdrGetDllHandle (NTDLL.@)
2175 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2177 NTSTATUS status;
2178 WCHAR buffer[128];
2179 WCHAR *filename;
2180 ULONG size;
2181 WINE_MODREF *wm;
2183 RtlEnterCriticalSection( &loader_section );
2185 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2187 filename = buffer;
2188 size = sizeof(buffer);
2189 for (;;)
2191 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2192 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2193 if (status != STATUS_BUFFER_TOO_SMALL) break;
2194 /* grow the buffer and retry */
2195 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2197 status = STATUS_NO_MEMORY;
2198 break;
2202 if (status == STATUS_SUCCESS)
2204 if (wm) *base = wm->ldr.BaseAddress;
2205 else status = STATUS_DLL_NOT_FOUND;
2208 RtlLeaveCriticalSection( &loader_section );
2209 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2210 return status;
2214 /******************************************************************
2215 * LdrAddRefDll (NTDLL.@)
2217 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2219 NTSTATUS ret = STATUS_SUCCESS;
2220 WINE_MODREF *wm;
2222 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2224 RtlEnterCriticalSection( &loader_section );
2226 if ((wm = get_modref( module )))
2228 if (flags & LDR_ADDREF_DLL_PIN)
2229 wm->ldr.LoadCount = -1;
2230 else
2231 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2232 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2234 else ret = STATUS_INVALID_PARAMETER;
2236 RtlLeaveCriticalSection( &loader_section );
2237 return ret;
2241 /***********************************************************************
2242 * LdrProcessRelocationBlock (NTDLL.@)
2244 * Apply relocations to a given page of a mapped PE image.
2246 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2247 USHORT *relocs, INT_PTR delta )
2249 while (count--)
2251 USHORT offset = *relocs & 0xfff;
2252 int type = *relocs >> 12;
2253 switch(type)
2255 case IMAGE_REL_BASED_ABSOLUTE:
2256 break;
2257 case IMAGE_REL_BASED_HIGH:
2258 *(short *)((char *)page + offset) += HIWORD(delta);
2259 break;
2260 case IMAGE_REL_BASED_LOW:
2261 *(short *)((char *)page + offset) += LOWORD(delta);
2262 break;
2263 case IMAGE_REL_BASED_HIGHLOW:
2264 *(int *)((char *)page + offset) += delta;
2265 break;
2266 #ifdef __x86_64__
2267 case IMAGE_REL_BASED_DIR64:
2268 *(INT_PTR *)((char *)page + offset) += delta;
2269 break;
2270 #elif defined(__arm__)
2271 case IMAGE_REL_BASED_THUMB_MOV32:
2273 DWORD inst = *(INT_PTR *)((char *)page + offset);
2274 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2275 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2276 DWORD hi_delta;
2278 if ((inst & 0x8000fbf0) != 0x0000f240)
2279 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2281 imm16 += LOWORD(delta);
2282 hi_delta = HIWORD(delta) + HIWORD(imm16);
2283 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2284 ((imm16 >> 12) & 0x000f) +
2285 ((imm16 << 20) & 0x70000000) +
2286 ((imm16 << 16) & 0xff0000);
2288 if (hi_delta != 0)
2290 inst = *(INT_PTR *)((char *)page + offset + 4);
2291 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2292 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2294 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2295 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2297 imm16 += hi_delta;
2298 if (imm16 > 0xffff)
2299 ERR("resulting immediate value won't fit: %08x\n", imm16);
2300 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2301 ((imm16 >> 1) & 0x0400) +
2302 ((imm16 >> 12) & 0x000f) +
2303 ((imm16 << 20) & 0x70000000) +
2304 ((imm16 << 16) & 0xff0000);
2307 break;
2308 #endif
2309 default:
2310 FIXME("Unknown/unsupported fixup type %x.\n", type);
2311 return NULL;
2313 relocs++;
2315 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2319 /******************************************************************
2320 * LdrQueryProcessModuleInformation
2323 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2324 ULONG buf_size, ULONG* req_size)
2326 SYSTEM_MODULE* sm = &smi->Modules[0];
2327 ULONG size = sizeof(ULONG);
2328 NTSTATUS nts = STATUS_SUCCESS;
2329 ANSI_STRING str;
2330 char* ptr;
2331 PLIST_ENTRY mark, entry;
2332 PLDR_MODULE mod;
2333 WORD id = 0;
2335 smi->ModulesCount = 0;
2337 RtlEnterCriticalSection( &loader_section );
2338 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2339 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2341 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2342 size += sizeof(*sm);
2343 if (size <= buf_size)
2345 sm->Reserved1 = 0; /* FIXME */
2346 sm->Reserved2 = 0; /* FIXME */
2347 sm->ImageBaseAddress = mod->BaseAddress;
2348 sm->ImageSize = mod->SizeOfImage;
2349 sm->Flags = mod->Flags;
2350 sm->Id = id++;
2351 sm->Rank = 0; /* FIXME */
2352 sm->Unknown = 0; /* FIXME */
2353 str.Length = 0;
2354 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2355 str.Buffer = (char*)sm->Name;
2356 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2357 ptr = strrchr(str.Buffer, '\\');
2358 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2360 smi->ModulesCount++;
2361 sm++;
2363 else nts = STATUS_INFO_LENGTH_MISMATCH;
2365 RtlLeaveCriticalSection( &loader_section );
2367 if (req_size) *req_size = size;
2369 return nts;
2373 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2375 NTSTATUS status;
2376 UNICODE_STRING str;
2377 ULONG size;
2378 WCHAR buffer[64];
2379 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2381 RtlInitUnicodeString( &str, name );
2383 size = sizeof(buffer) - sizeof(WCHAR);
2384 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2385 return status;
2387 if (info->Type != REG_DWORD)
2389 buffer[size / sizeof(WCHAR)] = 0;
2390 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2392 else memcpy( value, info->Data, sizeof(*value) );
2393 return status;
2396 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2397 void *data, ULONG in_size, ULONG *out_size )
2399 NTSTATUS status;
2400 UNICODE_STRING str;
2401 ULONG size;
2402 char *buffer;
2403 KEY_VALUE_PARTIAL_INFORMATION *info;
2404 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2406 RtlInitUnicodeString( &str, name );
2408 size = info_size + in_size;
2409 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2410 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2411 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2412 if (!status || status == STATUS_BUFFER_OVERFLOW)
2414 if (out_size) *out_size = info->DataLength;
2415 if (data && !status) memcpy( data, info->Data, info->DataLength );
2417 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2418 return status;
2422 /******************************************************************
2423 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2425 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2426 void *data, ULONG in_size, ULONG *out_size )
2428 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2429 'S','o','f','t','w','a','r','e','\\',
2430 'M','i','c','r','o','s','o','f','t','\\',
2431 'W','i','n','d','o','w','s',' ','N','T','\\',
2432 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2433 'I','m','a','g','e',' ','F','i','l','e',' ',
2434 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2435 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2436 OBJECT_ATTRIBUTES attr;
2437 UNICODE_STRING name_str;
2438 HANDLE hkey;
2439 NTSTATUS status;
2440 ULONG len;
2441 WCHAR *p;
2443 attr.Length = sizeof(attr);
2444 attr.RootDirectory = 0;
2445 attr.ObjectName = &name_str;
2446 attr.Attributes = OBJ_CASE_INSENSITIVE;
2447 attr.SecurityDescriptor = NULL;
2448 attr.SecurityQualityOfService = NULL;
2450 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2451 else p = key->Buffer;
2452 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2453 name_str.Buffer = path;
2454 name_str.Length = sizeof(optionsW) + len;
2455 name_str.MaximumLength = name_str.Length;
2456 memcpy( path, optionsW, sizeof(optionsW) );
2457 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2458 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2460 if (type == REG_DWORD)
2462 if (out_size) *out_size = sizeof(ULONG);
2463 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2464 else status = STATUS_BUFFER_OVERFLOW;
2466 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2468 NtClose( hkey );
2469 return status;
2473 /******************************************************************
2474 * RtlDllShutdownInProgress (NTDLL.@)
2476 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2478 return process_detaching;
2481 /****************************************************************************
2482 * LdrResolveDelayLoadedAPI (NTDLL.@)
2484 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2485 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2486 IMAGE_THUNK_DATA* addr, ULONG flags )
2488 IMAGE_THUNK_DATA *pIAT, *pINT;
2489 DELAYLOAD_INFO delayinfo;
2490 UNICODE_STRING mod;
2491 const CHAR* name;
2492 HMODULE *phmod;
2493 NTSTATUS nts;
2494 FARPROC fp;
2495 DWORD id;
2497 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2499 phmod = get_rva(base, desc->ModuleHandleRVA);
2500 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2501 pINT = get_rva(base, desc->ImportNameTableRVA);
2502 name = get_rva(base, desc->DllNameRVA);
2503 id = addr - pIAT;
2505 if (!*phmod)
2507 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2509 nts = STATUS_NO_MEMORY;
2510 goto fail;
2512 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2513 RtlFreeUnicodeString(&mod);
2514 if (nts) goto fail;
2517 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2518 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2519 else
2521 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2522 ANSI_STRING fnc;
2524 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2525 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2527 if (!nts)
2529 pIAT[id].u1.Function = (ULONG_PTR)fp;
2530 return fp;
2533 fail:
2534 delayinfo.Size = sizeof(delayinfo);
2535 delayinfo.DelayloadDescriptor = desc;
2536 delayinfo.ThunkAddress = addr;
2537 delayinfo.TargetDllName = name;
2538 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2539 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2540 delayinfo.TargetModuleBase = *phmod;
2541 delayinfo.Unused = NULL;
2542 delayinfo.LastError = nts;
2543 return dllhook(4, &delayinfo);
2546 /******************************************************************
2547 * LdrShutdownProcess (NTDLL.@)
2550 void WINAPI LdrShutdownProcess(void)
2552 TRACE("()\n");
2553 process_detaching = TRUE;
2554 process_detach();
2558 /******************************************************************
2559 * RtlExitUserProcess (NTDLL.@)
2561 void WINAPI RtlExitUserProcess( DWORD status )
2563 RtlEnterCriticalSection( &loader_section );
2564 RtlAcquirePebLock();
2565 NtTerminateProcess( 0, status );
2566 LdrShutdownProcess();
2567 NtTerminateProcess( GetCurrentProcess(), status );
2568 exit( status );
2571 /******************************************************************
2572 * LdrShutdownThread (NTDLL.@)
2575 void WINAPI LdrShutdownThread(void)
2577 PLIST_ENTRY mark, entry;
2578 PLDR_MODULE mod;
2579 UINT i;
2580 void **pointers;
2582 TRACE("()\n");
2584 /* don't do any detach calls if process is exiting */
2585 if (process_detaching) return;
2587 RtlEnterCriticalSection( &loader_section );
2589 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2590 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2592 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2593 InInitializationOrderModuleList);
2594 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2595 continue;
2596 if ( mod->Flags & LDR_NO_DLL_CALLS )
2597 continue;
2599 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2600 DLL_THREAD_DETACH, NULL );
2603 RtlAcquirePebLock();
2604 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2605 RtlReleasePebLock();
2607 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2609 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2610 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2612 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2613 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2614 RtlLeaveCriticalSection( &loader_section );
2618 /***********************************************************************
2619 * free_modref
2622 static void free_modref( WINE_MODREF *wm )
2624 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2625 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2626 if (wm->ldr.InInitializationOrderModuleList.Flink)
2627 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2629 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2630 if (!TRACE_ON(module))
2631 TRACE_(loaddll)("Unloaded module %s : %s\n",
2632 debugstr_w(wm->ldr.FullDllName.Buffer),
2633 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2635 SERVER_START_REQ( unload_dll )
2637 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2638 wine_server_call( req );
2640 SERVER_END_REQ;
2642 free_tls_slot( &wm->ldr );
2643 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2644 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2645 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2646 if (cached_modref == wm) cached_modref = NULL;
2647 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2648 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2649 RtlFreeHeap( GetProcessHeap(), 0, wm );
2652 /***********************************************************************
2653 * MODULE_FlushModrefs
2655 * Remove all unused modrefs and call the internal unloading routines
2656 * for the library type.
2658 * The loader_section must be locked while calling this function.
2660 static void MODULE_FlushModrefs(void)
2662 PLIST_ENTRY mark, entry, prev;
2663 PLDR_MODULE mod;
2664 WINE_MODREF*wm;
2666 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2667 for (entry = mark->Blink; entry != mark; entry = prev)
2669 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2670 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2671 prev = entry->Blink;
2672 if (!mod->LoadCount) free_modref( wm );
2675 /* check load order list too for modules that haven't been initialized yet */
2676 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2677 for (entry = mark->Blink; entry != mark; entry = prev)
2679 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2680 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2681 prev = entry->Blink;
2682 if (!mod->LoadCount) free_modref( wm );
2686 /***********************************************************************
2687 * MODULE_DecRefCount
2689 * The loader_section must be locked while calling this function.
2691 static void MODULE_DecRefCount( WINE_MODREF *wm )
2693 int i;
2695 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2696 return;
2698 if ( wm->ldr.LoadCount <= 0 )
2699 return;
2701 --wm->ldr.LoadCount;
2702 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2704 if ( wm->ldr.LoadCount == 0 )
2706 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2708 for ( i = 0; i < wm->nDeps; i++ )
2709 if ( wm->deps[i] )
2710 MODULE_DecRefCount( wm->deps[i] );
2712 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2716 /******************************************************************
2717 * LdrUnloadDll (NTDLL.@)
2721 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2723 WINE_MODREF *wm;
2724 NTSTATUS retv = STATUS_SUCCESS;
2726 if (process_detaching) return retv;
2728 TRACE("(%p)\n", hModule);
2730 RtlEnterCriticalSection( &loader_section );
2732 free_lib_count++;
2733 if ((wm = get_modref( hModule )) != NULL)
2735 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2737 /* Recursively decrement reference counts */
2738 MODULE_DecRefCount( wm );
2740 /* Call process detach notifications */
2741 if ( free_lib_count <= 1 )
2743 process_detach();
2744 MODULE_FlushModrefs();
2747 TRACE("END\n");
2749 else
2750 retv = STATUS_DLL_NOT_FOUND;
2752 free_lib_count--;
2754 RtlLeaveCriticalSection( &loader_section );
2756 return retv;
2759 /***********************************************************************
2760 * RtlImageNtHeader (NTDLL.@)
2762 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2764 IMAGE_NT_HEADERS *ret;
2766 __TRY
2768 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2770 ret = NULL;
2771 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2773 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2774 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2777 __EXCEPT_PAGE_FAULT
2779 return NULL;
2781 __ENDTRY
2782 return ret;
2786 /***********************************************************************
2787 * attach_process_dlls
2789 * Initial attach to all the dlls loaded by the process.
2791 static NTSTATUS attach_process_dlls( void *wm )
2793 NTSTATUS status;
2795 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2797 RtlEnterCriticalSection( &loader_section );
2798 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2800 if (last_failed_modref)
2801 ERR( "%s failed to initialize, aborting\n",
2802 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2803 return status;
2805 attach_implicitly_loaded_dlls( (LPVOID)1 );
2806 RtlLeaveCriticalSection( &loader_section );
2807 return status;
2811 /***********************************************************************
2812 * load_global_options
2814 static void load_global_options(void)
2816 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2817 'S','y','s','t','e','m','\\',
2818 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2819 'C','o','n','t','r','o','l','\\',
2820 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2821 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2822 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};
2823 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2824 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2825 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};
2826 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};
2828 OBJECT_ATTRIBUTES attr;
2829 UNICODE_STRING name_str;
2830 HANDLE hkey;
2831 ULONG value;
2833 attr.Length = sizeof(attr);
2834 attr.RootDirectory = 0;
2835 attr.ObjectName = &name_str;
2836 attr.Attributes = OBJ_CASE_INSENSITIVE;
2837 attr.SecurityDescriptor = NULL;
2838 attr.SecurityQualityOfService = NULL;
2839 RtlInitUnicodeString( &name_str, sessionW );
2841 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2843 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2845 query_dword_option( hkey, critsectW, &value );
2846 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2848 query_dword_option( hkey, heapresW, &value );
2849 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2851 query_dword_option( hkey, heapcommitW, &value );
2852 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2854 query_dword_option( hkey, decommittotalW, &value );
2855 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2857 query_dword_option( hkey, decommitfreeW, &value );
2858 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2860 NtClose( hkey );
2864 /***********************************************************************
2865 * start_process
2867 static void start_process( void *kernel_start )
2869 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2872 /******************************************************************
2873 * LdrInitializeThunk (NTDLL.@)
2876 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2877 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2879 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2880 NTSTATUS status;
2881 WINE_MODREF *wm;
2882 LPCWSTR load_path;
2883 PEB *peb = NtCurrentTeb()->Peb;
2885 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2887 /* allocate the modref for the main exe (if not already done) */
2888 wm = get_modref( peb->ImageBaseAddress );
2889 assert( wm );
2890 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2892 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2893 exit(1);
2896 peb->LoaderLock = &loader_section;
2897 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2898 if (!peb->ProcessParameters->WindowTitle.Buffer)
2899 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2900 version_init( wm->ldr.FullDllName.Buffer );
2901 virtual_set_large_address_space();
2903 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2904 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2906 /* the main exe needs to be the first in the load order list */
2907 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2908 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2910 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2911 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2913 actctx_init();
2914 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2915 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2916 heap_set_debug_flags( GetProcessHeap() );
2918 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2919 if (status != STATUS_SUCCESS) goto error;
2921 virtual_release_address_space();
2922 virtual_clear_thread_stack();
2923 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2925 error:
2926 ERR( "Main exe initialization for %s failed, status %x\n",
2927 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2928 NtTerminateProcess( GetCurrentProcess(), status );
2932 /***********************************************************************
2933 * RtlImageDirectoryEntryToData (NTDLL.@)
2935 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2937 const IMAGE_NT_HEADERS *nt;
2938 DWORD addr;
2940 if ((ULONG_PTR)module & 1) /* mapped as data file */
2942 module = (HMODULE)((ULONG_PTR)module & ~1);
2943 image = FALSE;
2945 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2946 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2948 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2950 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2951 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2952 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2953 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2955 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2957 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2959 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2960 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2961 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2962 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2964 else return NULL;
2966 /* not mapped as image, need to find the section containing the virtual address */
2967 return RtlImageRvaToVa( nt, module, addr, NULL );
2971 /***********************************************************************
2972 * RtlImageRvaToSection (NTDLL.@)
2974 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2975 HMODULE module, DWORD rva )
2977 int i;
2978 const IMAGE_SECTION_HEADER *sec;
2980 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2981 nt->FileHeader.SizeOfOptionalHeader);
2982 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2984 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2985 return (PIMAGE_SECTION_HEADER)sec;
2987 return NULL;
2991 /***********************************************************************
2992 * RtlImageRvaToVa (NTDLL.@)
2994 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2995 DWORD rva, IMAGE_SECTION_HEADER **section )
2997 IMAGE_SECTION_HEADER *sec;
2999 if (section && *section) /* try this section first */
3001 sec = *section;
3002 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3003 goto found;
3005 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3006 found:
3007 if (section) *section = sec;
3008 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3012 /***********************************************************************
3013 * RtlPcToFileHeader (NTDLL.@)
3015 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3017 LDR_MODULE *module;
3018 PVOID ret = NULL;
3020 RtlEnterCriticalSection( &loader_section );
3021 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3022 RtlLeaveCriticalSection( &loader_section );
3023 *address = ret;
3024 return ret;
3028 /***********************************************************************
3029 * NtLoadDriver (NTDLL.@)
3030 * ZwLoadDriver (NTDLL.@)
3032 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3034 FIXME("(%p), stub!\n",DriverServiceName);
3035 return STATUS_NOT_IMPLEMENTED;
3039 /***********************************************************************
3040 * NtUnloadDriver (NTDLL.@)
3041 * ZwUnloadDriver (NTDLL.@)
3043 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3045 FIXME("(%p), stub!\n",DriverServiceName);
3046 return STATUS_NOT_IMPLEMENTED;
3050 /******************************************************************
3051 * DllMain (NTDLL.@)
3053 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3055 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3056 return TRUE;
3060 /******************************************************************
3061 * __wine_init_windows_dir (NTDLL.@)
3063 * Windows and system dir initialization once kernel32 has been loaded.
3065 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3067 PLIST_ENTRY mark, entry;
3068 LPWSTR buffer, p;
3070 strcpyW( user_shared_data->NtSystemRoot, windir );
3071 DIR_init_windows_dir( windir, sysdir );
3073 /* prepend the system dir to the name of the already created modules */
3074 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3075 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3077 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3079 assert( mod->Flags & LDR_WINE_INTERNAL );
3081 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3082 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3083 if (!buffer) continue;
3084 strcpyW( buffer, system_dir.Buffer );
3085 p = buffer + strlenW( buffer );
3086 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3087 strcpyW( p, mod->FullDllName.Buffer );
3088 RtlInitUnicodeString( &mod->FullDllName, buffer );
3089 RtlInitUnicodeString( &mod->BaseDllName, p );
3094 /***********************************************************************
3095 * __wine_process_init
3097 void __wine_process_init(void)
3099 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3101 WINE_MODREF *wm;
3102 NTSTATUS status;
3103 ANSI_STRING func_name;
3104 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3106 main_exe_file = thread_init();
3108 /* retrieve current umask */
3109 FILE_umask = umask(0777);
3110 umask( FILE_umask );
3112 load_global_options();
3114 /* setup the load callback and create ntdll modref */
3115 wine_dll_set_callback( load_builtin_callback );
3117 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3119 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3120 exit(1);
3122 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3123 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3125 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3126 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3127 0, (void **)&init_func )) != STATUS_SUCCESS)
3129 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3130 exit(1);
3132 init_func();