vbscript: Added support for title and type arguments of MsgBox.
[wine.git] / dlls / ntdll / loader.c
blob79aa3410164945b1894a2cf676f18ccca40d3806
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.
147 #ifdef __i386__
148 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
149 __ASM_GLOBAL_FUNC(call_dll_entry_point,
150 "pushl %ebp\n\t"
151 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
152 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
153 "movl %esp,%ebp\n\t"
154 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
155 "pushl %ebx\n\t"
156 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
157 "subl $8,%esp\n\t"
158 "pushl 20(%ebp)\n\t"
159 "pushl 16(%ebp)\n\t"
160 "pushl 12(%ebp)\n\t"
161 "movl 8(%ebp),%eax\n\t"
162 "call *%eax\n\t"
163 "leal -4(%ebp),%esp\n\t"
164 "popl %ebx\n\t"
165 __ASM_CFI(".cfi_same_value %ebx\n\t")
166 "popl %ebp\n\t"
167 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
168 __ASM_CFI(".cfi_same_value %ebp\n\t")
169 "ret" )
170 #else /* __i386__ */
171 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
172 UINT reason, void *reserved )
174 return proc( module, reason, reserved );
176 #endif /* __i386__ */
179 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
180 /*************************************************************************
181 * stub_entry_point
183 * Entry point for stub functions.
185 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
187 EXCEPTION_RECORD rec;
189 rec.ExceptionCode = EXCEPTION_WINE_STUB;
190 rec.ExceptionFlags = EH_NONCONTINUABLE;
191 rec.ExceptionRecord = NULL;
192 rec.ExceptionAddress = ret_addr;
193 rec.NumberParameters = 2;
194 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
195 rec.ExceptionInformation[1] = (ULONG_PTR)name;
196 for (;;) RtlRaiseException( &rec );
200 #include "pshpack1.h"
201 #ifdef __i386__
202 struct stub
204 BYTE pushl1; /* pushl $name */
205 const char *name;
206 BYTE pushl2; /* pushl $dll */
207 const char *dll;
208 BYTE call; /* call stub_entry_point */
209 DWORD entry;
211 #elif defined(__arm__)
212 struct stub
214 BYTE ldr_r0[4]; /* ldr r0, $dll */
215 BYTE mov_pc_pc1[4]; /* mov pc,pc */
216 const char *dll;
217 BYTE ldr_r1[4]; /* ldr r1, $name */
218 BYTE mov_pc_pc2[4]; /* mov pc,pc */
219 const char *name;
220 BYTE mov_r2_lr[4]; /* mov r2, lr */
221 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #-4] */
222 const void* entry;
224 #else
225 struct stub
227 BYTE movq_rdi[2]; /* movq $dll,%rdi */
228 const char *dll;
229 BYTE movq_rsi[2]; /* movq $name,%rsi */
230 const char *name;
231 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
232 BYTE movq_rax[2]; /* movq $entry, %rax */
233 const void* entry;
234 BYTE jmpq_rax[2]; /* jmp %rax */
236 #endif
237 #include "poppack.h"
239 /*************************************************************************
240 * allocate_stub
242 * Allocate a stub entry point.
244 static ULONG_PTR allocate_stub( const char *dll, const char *name )
246 #define MAX_SIZE 65536
247 static struct stub *stubs;
248 static unsigned int nb_stubs;
249 struct stub *stub;
251 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
253 if (!stubs)
255 SIZE_T size = MAX_SIZE;
256 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
257 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
258 return 0xdeadbeef;
260 stub = &stubs[nb_stubs++];
261 #ifdef __i386__
262 stub->pushl1 = 0x68; /* pushl $name */
263 stub->name = name;
264 stub->pushl2 = 0x68; /* pushl $dll */
265 stub->dll = dll;
266 stub->call = 0xe8; /* call stub_entry_point */
267 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
268 #elif defined(__arm__)
269 stub->ldr_r0[0] = 0x00; /* ldr r0, $dll */
270 stub->ldr_r0[1] = 0x00;
271 stub->ldr_r0[2] = 0x9f;
272 stub->ldr_r0[3] = 0xe5;
273 stub->mov_pc_pc1[0] = 0x0f; /* mov pc,pc */
274 stub->mov_pc_pc1[1] = 0xf0;
275 stub->mov_pc_pc1[2] = 0xa0;
276 stub->mov_pc_pc1[3] = 0xe1;
277 stub->dll = dll;
278 stub->ldr_r1[0] = 0x00; /* ldr r1, $name */
279 stub->ldr_r1[1] = 0x10;
280 stub->ldr_r1[2] = 0x9f;
281 stub->ldr_r1[3] = 0xe5;
282 stub->mov_pc_pc2[0] = 0x0f; /* mov pc,pc */
283 stub->mov_pc_pc2[1] = 0xf0;
284 stub->mov_pc_pc2[2] = 0xa0;
285 stub->mov_pc_pc2[3] = 0xe1;
286 stub->name = name;
287 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
288 stub->mov_r2_lr[1] = 0x20;
289 stub->mov_r2_lr[2] = 0xa0;
290 stub->mov_r2_lr[3] = 0xe1;
291 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #-4] */
292 stub->ldr_pc_pc[1] = 0xf0;
293 stub->ldr_pc_pc[2] = 0x1f;
294 stub->ldr_pc_pc[3] = 0xe5;
295 stub->entry = stub_entry_point;
296 #else
297 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
298 stub->movq_rdi[1] = 0xbf;
299 stub->dll = dll;
300 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
301 stub->movq_rsi[1] = 0xbe;
302 stub->name = name;
303 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
304 stub->movq_rsp_rdx[1] = 0x8b;
305 stub->movq_rsp_rdx[2] = 0x14;
306 stub->movq_rsp_rdx[3] = 0x24;
307 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
308 stub->movq_rax[1] = 0xb8;
309 stub->entry = stub_entry_point;
310 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
311 stub->jmpq_rax[1] = 0xe0;
312 #endif
313 return (ULONG_PTR)stub;
316 #else /* __i386__ */
317 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
318 #endif /* __i386__ */
321 /*************************************************************************
322 * get_modref
324 * Looks for the referenced HMODULE in the current process
325 * The loader_section must be locked while calling this function.
327 static WINE_MODREF *get_modref( HMODULE hmod )
329 PLIST_ENTRY mark, entry;
330 PLDR_MODULE mod;
332 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
334 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
335 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
337 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
338 if (mod->BaseAddress == hmod)
339 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
340 if (mod->BaseAddress > (void*)hmod) break;
342 return NULL;
346 /**********************************************************************
347 * find_basename_module
349 * Find a module from its base name.
350 * The loader_section must be locked while calling this function
352 static WINE_MODREF *find_basename_module( LPCWSTR name )
354 PLIST_ENTRY mark, entry;
356 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
357 return cached_modref;
359 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
360 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
362 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
363 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
365 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
366 return cached_modref;
369 return NULL;
373 /**********************************************************************
374 * find_fullname_module
376 * Find a module from its full path name.
377 * The loader_section must be locked while calling this function
379 static WINE_MODREF *find_fullname_module( LPCWSTR name )
381 PLIST_ENTRY mark, entry;
383 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
384 return cached_modref;
386 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
387 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
389 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
390 if (!strcmpiW( name, mod->FullDllName.Buffer ))
392 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
393 return cached_modref;
396 return NULL;
400 /*************************************************************************
401 * find_forwarded_export
403 * Find the final function pointer for a forwarded function.
404 * The loader_section must be locked while calling this function.
406 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
408 const IMAGE_EXPORT_DIRECTORY *exports;
409 DWORD exp_size;
410 WINE_MODREF *wm;
411 WCHAR mod_name[32];
412 const char *end = strrchr(forward, '.');
413 FARPROC proc = NULL;
415 if (!end) return NULL;
416 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
417 ascii_to_unicode( mod_name, forward, end - forward );
418 mod_name[end - forward] = 0;
419 if (!strchrW( mod_name, '.' ))
421 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
422 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
425 if (!(wm = find_basename_module( mod_name )))
427 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
428 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
429 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
431 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
433 LdrUnloadDll( wm->ldr.BaseAddress );
434 wm = NULL;
438 if (!wm)
440 ERR( "module not found for forward '%s' used by %s\n",
441 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
442 return NULL;
445 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
446 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
448 const char *name = end + 1;
449 if (*name == '#') /* ordinal */
450 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
451 else
452 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
455 if (!proc)
457 ERR("function not found for forward '%s' used by %s."
458 " If you are using builtin %s, try using the native one instead.\n",
459 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
460 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
462 return proc;
466 /*************************************************************************
467 * find_ordinal_export
469 * Find an exported function by ordinal.
470 * The exports base must have been subtracted from the ordinal already.
471 * The loader_section must be locked while calling this function.
473 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
474 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
476 FARPROC proc;
477 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
479 if (ordinal >= exports->NumberOfFunctions)
481 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
482 return NULL;
484 if (!functions[ordinal]) return NULL;
486 proc = get_rva( module, functions[ordinal] );
488 /* if the address falls into the export dir, it's a forward */
489 if (((const char *)proc >= (const char *)exports) &&
490 ((const char *)proc < (const char *)exports + exp_size))
491 return find_forwarded_export( module, (const char *)proc, load_path );
493 if (TRACE_ON(snoop))
495 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
496 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
498 if (TRACE_ON(relay))
500 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
501 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
503 return proc;
507 /*************************************************************************
508 * find_named_export
510 * Find an exported function by name.
511 * The loader_section must be locked while calling this function.
513 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
514 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
516 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
517 const DWORD *names = get_rva( module, exports->AddressOfNames );
518 int min = 0, max = exports->NumberOfNames - 1;
520 /* first check the hint */
521 if (hint >= 0 && hint <= max)
523 char *ename = get_rva( module, names[hint] );
524 if (!strcmp( ename, name ))
525 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
528 /* then do a binary search */
529 while (min <= max)
531 int res, pos = (min + max) / 2;
532 char *ename = get_rva( module, names[pos] );
533 if (!(res = strcmp( ename, name )))
534 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
535 if (res > 0) max = pos - 1;
536 else min = pos + 1;
538 return NULL;
543 /*************************************************************************
544 * import_dll
546 * Import the dll specified by the given import descriptor.
547 * The loader_section must be locked while calling this function.
549 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
551 NTSTATUS status;
552 WINE_MODREF *wmImp;
553 HMODULE imp_mod;
554 const IMAGE_EXPORT_DIRECTORY *exports;
555 DWORD exp_size;
556 const IMAGE_THUNK_DATA *import_list;
557 IMAGE_THUNK_DATA *thunk_list;
558 WCHAR buffer[32];
559 const char *name = get_rva( module, descr->Name );
560 DWORD len = strlen(name);
561 PVOID protect_base;
562 SIZE_T protect_size = 0;
563 DWORD protect_old;
565 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
566 if (descr->u.OriginalFirstThunk)
567 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
568 else
569 import_list = thunk_list;
571 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
573 if (len * sizeof(WCHAR) < sizeof(buffer))
575 ascii_to_unicode( buffer, name, len );
576 buffer[len] = 0;
577 status = load_dll( load_path, buffer, 0, &wmImp );
579 else /* need to allocate a larger buffer */
581 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
582 if (!ptr) return NULL;
583 ascii_to_unicode( ptr, name, len );
584 ptr[len] = 0;
585 status = load_dll( load_path, ptr, 0, &wmImp );
586 RtlFreeHeap( GetProcessHeap(), 0, ptr );
589 if (status)
591 if (status == STATUS_DLL_NOT_FOUND)
592 ERR("Library %s (which is needed by %s) not found\n",
593 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
594 else
595 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
596 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
597 return NULL;
600 /* unprotect the import address table since it can be located in
601 * readonly section */
602 while (import_list[protect_size].u1.Ordinal) protect_size++;
603 protect_base = thunk_list;
604 protect_size *= sizeof(*thunk_list);
605 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
606 &protect_size, PAGE_READWRITE, &protect_old );
608 imp_mod = wmImp->ldr.BaseAddress;
609 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
611 if (!exports)
613 /* set all imported function to deadbeef */
614 while (import_list->u1.Ordinal)
616 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
618 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
619 WARN("No implementation for %s.%d", name, ordinal );
620 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
622 else
624 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
625 WARN("No implementation for %s.%s", name, pe_name->Name );
626 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
628 WARN(" imported from %s, allocating stub %p\n",
629 debugstr_w(current_modref->ldr.FullDllName.Buffer),
630 (void *)thunk_list->u1.Function );
631 import_list++;
632 thunk_list++;
634 goto done;
637 while (import_list->u1.Ordinal)
639 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
641 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
643 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
644 ordinal - exports->Base, load_path );
645 if (!thunk_list->u1.Function)
647 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
648 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
649 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
650 (void *)thunk_list->u1.Function );
652 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
654 else /* import by name */
656 IMAGE_IMPORT_BY_NAME *pe_name;
657 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
658 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
659 (const char*)pe_name->Name,
660 pe_name->Hint, load_path );
661 if (!thunk_list->u1.Function)
663 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
664 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
665 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
666 (void *)thunk_list->u1.Function );
668 TRACE_(imports)("--- %s %s.%d = %p\n",
669 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
671 import_list++;
672 thunk_list++;
675 done:
676 /* restore old protection of the import address table */
677 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
678 return wmImp;
682 /***********************************************************************
683 * create_module_activation_context
685 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
687 NTSTATUS status;
688 LDR_RESOURCE_INFO info;
689 const IMAGE_RESOURCE_DATA_ENTRY *entry;
691 info.Type = RT_MANIFEST;
692 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
693 info.Language = 0;
694 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
696 ACTCTXW ctx;
697 ctx.cbSize = sizeof(ctx);
698 ctx.lpSource = NULL;
699 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
700 ctx.hModule = module->BaseAddress;
701 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
702 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
704 return status;
708 /*************************************************************************
709 * is_dll_native_subsystem
711 * Check if dll is a proper native driver.
712 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
713 * while being perfectly normal DLLs. This heuristic should catch such breakages.
715 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
717 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
718 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
719 const IMAGE_IMPORT_DESCRIPTOR *imports;
720 DWORD i, size;
721 WCHAR buffer[16];
723 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
724 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
726 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
727 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
729 for (i = 0; imports[i].Name; i++)
731 const char *name = get_rva( module, imports[i].Name );
732 DWORD len = strlen(name);
733 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
734 ascii_to_unicode( buffer, name, len + 1 );
735 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
737 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
738 return FALSE;
742 return TRUE;
745 /*************************************************************************
746 * alloc_tls_slot
748 * Allocate a TLS slot for a newly-loaded module.
749 * The loader_section must be locked while calling this function.
751 static SHORT alloc_tls_slot( LDR_MODULE *mod )
753 const IMAGE_TLS_DIRECTORY *dir;
754 ULONG i, size;
755 void *new_ptr;
756 LIST_ENTRY *entry;
758 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
759 return -1;
761 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
762 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
764 for (i = 0; i < tls_module_count; i++) if (!tls_dirs[i]) break;
766 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
767 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
768 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
770 if (i == tls_module_count)
772 UINT new_count = max( 32, tls_module_count * 2 );
774 if (!tls_dirs)
775 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
776 else
777 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
778 new_count * sizeof(*tls_dirs) );
779 if (!new_ptr) return -1;
781 /* resize the pointer block in all running threads */
782 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
784 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
785 void **old = teb->ThreadLocalStoragePointer;
786 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
788 if (!new) return -1;
789 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
790 teb->ThreadLocalStoragePointer = new;
791 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
792 /* FIXME: can't free old block here, should be freed at thread exit */
795 tls_dirs = new_ptr;
796 tls_module_count = new_count;
799 /* allocate the data block in all running threads */
800 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
802 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
804 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
805 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
806 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
808 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
809 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
811 RtlFreeHeap( GetProcessHeap(), 0,
812 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
815 *(DWORD *)dir->AddressOfIndex = i;
816 tls_dirs[i] = dir;
817 return i;
821 /*************************************************************************
822 * free_tls_slot
824 * Free the module TLS slot on unload.
825 * The loader_section must be locked while calling this function.
827 static void free_tls_slot( LDR_MODULE *mod )
829 ULONG i = (USHORT)mod->TlsIndex;
831 if (mod->TlsIndex == -1) return;
832 assert( i < tls_module_count );
833 tls_dirs[i] = NULL;
837 /****************************************************************
838 * fixup_imports
840 * Fixup all imports of a given module.
841 * The loader_section must be locked while calling this function.
843 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
845 int i, nb_imports;
846 const IMAGE_IMPORT_DESCRIPTOR *imports;
847 WINE_MODREF *prev;
848 DWORD size;
849 NTSTATUS status;
850 ULONG_PTR cookie;
852 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
853 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
855 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
857 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
858 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
859 return STATUS_SUCCESS;
861 nb_imports = 0;
862 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
864 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
866 if (!create_module_activation_context( &wm->ldr ))
867 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
869 /* Allocate module dependency list */
870 wm->nDeps = nb_imports;
871 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
873 /* load the imported modules. They are automatically
874 * added to the modref list of the process.
876 prev = current_modref;
877 current_modref = wm;
878 status = STATUS_SUCCESS;
879 for (i = 0; i < nb_imports; i++)
881 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
882 status = STATUS_DLL_NOT_FOUND;
884 current_modref = prev;
885 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
886 return status;
890 /*************************************************************************
891 * alloc_module
893 * Allocate a WINE_MODREF structure and add it to the process list
894 * The loader_section must be locked while calling this function.
896 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
898 WINE_MODREF *wm;
899 const WCHAR *p;
900 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
901 PLIST_ENTRY entry, mark;
903 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
905 wm->nDeps = 0;
906 wm->deps = NULL;
908 wm->ldr.BaseAddress = hModule;
909 wm->ldr.EntryPoint = NULL;
910 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
911 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
912 wm->ldr.TlsIndex = -1;
913 wm->ldr.LoadCount = 1;
914 wm->ldr.SectionHandle = NULL;
915 wm->ldr.CheckSum = 0;
916 wm->ldr.TimeDateStamp = 0;
917 wm->ldr.ActivationContext = 0;
919 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
920 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
921 else p = wm->ldr.FullDllName.Buffer;
922 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
924 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
926 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
927 if (nt->OptionalHeader.AddressOfEntryPoint)
928 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
931 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
932 &wm->ldr.InLoadOrderModuleList);
934 /* insert module in MemoryList, sorted in increasing base addresses */
935 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
936 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
938 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
939 break;
941 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
942 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
943 wm->ldr.InMemoryOrderModuleList.Flink = entry;
944 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
946 /* wait until init is called for inserting into this list */
947 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
948 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
950 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
952 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
953 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
954 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
956 return wm;
960 /*************************************************************************
961 * alloc_thread_tls
963 * Allocate the per-thread structure for module TLS storage.
965 static NTSTATUS alloc_thread_tls(void)
967 void **pointers;
968 UINT i, size;
970 if (!tls_module_count) return STATUS_SUCCESS;
972 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
973 tls_module_count * sizeof(*pointers) )))
974 return STATUS_NO_MEMORY;
976 for (i = 0; i < tls_module_count; i++)
978 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
980 if (!dir) continue;
981 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
982 if (!size && !dir->SizeOfZeroFill) continue;
984 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
986 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
987 RtlFreeHeap( GetProcessHeap(), 0, pointers );
988 return STATUS_NO_MEMORY;
990 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
991 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
993 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
994 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
996 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
997 return STATUS_SUCCESS;
1001 /*************************************************************************
1002 * call_tls_callbacks
1004 static void call_tls_callbacks( HMODULE module, UINT reason )
1006 const IMAGE_TLS_DIRECTORY *dir;
1007 const PIMAGE_TLS_CALLBACK *callback;
1008 ULONG dirsize;
1010 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1011 if (!dir || !dir->AddressOfCallBacks) return;
1013 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1015 if (TRACE_ON(relay))
1016 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1017 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1018 __TRY
1020 (*callback)( module, reason, NULL );
1022 __EXCEPT_ALL
1024 if (TRACE_ON(relay))
1025 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1026 GetCurrentThreadId(), callback, module, reason_names[reason] );
1027 return;
1029 __ENDTRY
1030 if (TRACE_ON(relay))
1031 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1032 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1037 /*************************************************************************
1038 * MODULE_InitDLL
1040 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1042 WCHAR mod_name[32];
1043 NTSTATUS status = STATUS_SUCCESS;
1044 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1045 void *module = wm->ldr.BaseAddress;
1046 BOOL retv = FALSE;
1048 /* Skip calls for modules loaded with special load flags */
1050 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1051 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1052 if (!entry) return STATUS_SUCCESS;
1054 if (TRACE_ON(relay))
1056 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1057 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1058 mod_name[len / sizeof(WCHAR)] = 0;
1059 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1060 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1061 reason_names[reason], lpReserved );
1063 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1064 reason_names[reason], lpReserved );
1066 __TRY
1068 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1069 if (!retv)
1070 status = STATUS_DLL_INIT_FAILED;
1072 __EXCEPT_ALL
1074 if (TRACE_ON(relay))
1075 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1076 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1077 status = GetExceptionCode();
1079 __ENDTRY
1081 /* The state of the module list may have changed due to the call
1082 to the dll. We cannot assume that this module has not been
1083 deleted. */
1084 if (TRACE_ON(relay))
1085 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1086 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1087 reason_names[reason], lpReserved, retv );
1088 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1090 return status;
1094 /*************************************************************************
1095 * process_attach
1097 * Send the process attach notification to all DLLs the given module
1098 * depends on (recursively). This is somewhat complicated due to the fact that
1100 * - we have to respect the module dependencies, i.e. modules implicitly
1101 * referenced by another module have to be initialized before the module
1102 * itself can be initialized
1104 * - the initialization routine of a DLL can itself call LoadLibrary,
1105 * thereby introducing a whole new set of dependencies (even involving
1106 * the 'old' modules) at any time during the whole process
1108 * (Note that this routine can be recursively entered not only directly
1109 * from itself, but also via LoadLibrary from one of the called initialization
1110 * routines.)
1112 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1113 * the process *detach* notifications to be sent in the correct order.
1114 * This must not only take into account module dependencies, but also
1115 * 'hidden' dependencies created by modules calling LoadLibrary in their
1116 * attach notification routine.
1118 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1119 * list after the attach notification has returned. This implies that the
1120 * detach notifications are called in the reverse of the sequence the attach
1121 * notifications *returned*.
1123 * The loader_section must be locked while calling this function.
1125 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1127 NTSTATUS status = STATUS_SUCCESS;
1128 ULONG_PTR cookie;
1129 int i;
1131 if (process_detaching) return status;
1133 /* prevent infinite recursion in case of cyclical dependencies */
1134 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1135 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1136 return status;
1138 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1140 /* Tag current MODREF to prevent recursive loop */
1141 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1142 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1143 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1145 /* Recursively attach all DLLs this one depends on */
1146 for ( i = 0; i < wm->nDeps; i++ )
1148 if (!wm->deps[i]) continue;
1149 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1152 /* Call DLL entry point */
1153 if (status == STATUS_SUCCESS)
1155 WINE_MODREF *prev = current_modref;
1156 current_modref = wm;
1157 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1158 if (status == STATUS_SUCCESS)
1159 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1160 else
1162 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1163 /* point to the name so LdrInitializeThunk can print it */
1164 last_failed_modref = wm;
1165 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1167 current_modref = prev;
1170 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1171 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1172 &wm->ldr.InInitializationOrderModuleList);
1174 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1175 /* Remove recursion flag */
1176 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1178 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1179 return status;
1183 /**********************************************************************
1184 * attach_implicitly_loaded_dlls
1186 * Attach to the (builtin) dlls that have been implicitly loaded because
1187 * of a dependency at the Unix level, but not imported at the Win32 level.
1189 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1191 for (;;)
1193 PLIST_ENTRY mark, entry;
1195 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1196 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1198 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1200 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1201 TRACE( "found implicitly loaded %s, attaching to it\n",
1202 debugstr_w(mod->BaseDllName.Buffer));
1203 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1204 break; /* restart the search from the start */
1206 if (entry == mark) break; /* nothing found */
1211 /*************************************************************************
1212 * process_detach
1214 * Send DLL process detach notifications. See the comment about calling
1215 * sequence at process_attach.
1217 static void process_detach(void)
1219 PLIST_ENTRY mark, entry;
1220 PLDR_MODULE mod;
1222 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1225 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1227 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1228 InInitializationOrderModuleList);
1229 /* Check whether to detach this DLL */
1230 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1231 continue;
1232 if ( mod->LoadCount && !process_detaching )
1233 continue;
1235 /* Call detach notification */
1236 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1237 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1238 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1240 /* Restart at head of WINE_MODREF list, as entries might have
1241 been added and/or removed while performing the call ... */
1242 break;
1244 } while (entry != mark);
1247 /*************************************************************************
1248 * MODULE_DllThreadAttach
1250 * Send DLL thread attach notifications. These are sent in the
1251 * reverse sequence of process detach notification.
1254 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1256 PLIST_ENTRY mark, entry;
1257 PLDR_MODULE mod;
1258 NTSTATUS status;
1260 /* don't do any attach calls if process is exiting */
1261 if (process_detaching) return STATUS_SUCCESS;
1263 RtlEnterCriticalSection( &loader_section );
1265 RtlAcquirePebLock();
1266 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1267 RtlReleasePebLock();
1269 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1271 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1272 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1274 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1275 InInitializationOrderModuleList);
1276 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1277 continue;
1278 if ( mod->Flags & LDR_NO_DLL_CALLS )
1279 continue;
1281 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1282 DLL_THREAD_ATTACH, lpReserved );
1285 done:
1286 RtlLeaveCriticalSection( &loader_section );
1287 return status;
1290 /******************************************************************
1291 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1294 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1296 WINE_MODREF *wm;
1297 NTSTATUS ret = STATUS_SUCCESS;
1299 RtlEnterCriticalSection( &loader_section );
1301 wm = get_modref( hModule );
1302 if (!wm || wm->ldr.TlsIndex != -1)
1303 ret = STATUS_DLL_NOT_FOUND;
1304 else
1305 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1307 RtlLeaveCriticalSection( &loader_section );
1309 return ret;
1312 /******************************************************************
1313 * LdrFindEntryForAddress (NTDLL.@)
1315 * The loader_section must be locked while calling this function
1317 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1319 PLIST_ENTRY mark, entry;
1320 PLDR_MODULE mod;
1322 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1323 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1325 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1326 if (mod->BaseAddress <= addr &&
1327 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1329 *pmod = mod;
1330 return STATUS_SUCCESS;
1332 if (mod->BaseAddress > addr) break;
1334 return STATUS_NO_MORE_ENTRIES;
1337 /******************************************************************
1338 * LdrLockLoaderLock (NTDLL.@)
1340 * Note: some flags are not implemented.
1341 * Flag 0x01 is used to raise exceptions on errors.
1343 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1345 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1347 if (result) *result = 0;
1348 if (magic) *magic = 0;
1349 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1350 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1351 if (!magic) return STATUS_INVALID_PARAMETER_3;
1353 if (flags & 0x2)
1355 if (!RtlTryEnterCriticalSection( &loader_section ))
1357 *result = 2;
1358 return STATUS_SUCCESS;
1360 *result = 1;
1362 else
1364 RtlEnterCriticalSection( &loader_section );
1365 if (result) *result = 1;
1367 *magic = GetCurrentThreadId();
1368 return STATUS_SUCCESS;
1372 /******************************************************************
1373 * LdrUnlockLoaderUnlock (NTDLL.@)
1375 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1377 if (magic)
1379 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1380 RtlLeaveCriticalSection( &loader_section );
1382 return STATUS_SUCCESS;
1386 /******************************************************************
1387 * LdrGetProcedureAddress (NTDLL.@)
1389 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1390 ULONG ord, PVOID *address)
1392 IMAGE_EXPORT_DIRECTORY *exports;
1393 DWORD exp_size;
1394 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1396 RtlEnterCriticalSection( &loader_section );
1398 /* check if the module itself is invalid to return the proper error */
1399 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1400 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1401 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1403 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1404 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1405 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1406 if (proc)
1408 *address = proc;
1409 ret = STATUS_SUCCESS;
1413 RtlLeaveCriticalSection( &loader_section );
1414 return ret;
1418 /***********************************************************************
1419 * is_fake_dll
1421 * Check if a loaded native dll is a Wine fake dll.
1423 static BOOL is_fake_dll( HANDLE handle )
1425 static const char fakedll_signature[] = "Wine placeholder DLL";
1426 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1427 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1428 IO_STATUS_BLOCK io;
1429 LARGE_INTEGER offset;
1431 offset.QuadPart = 0;
1432 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1433 if (io.Information < sizeof(buffer)) return FALSE;
1434 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1435 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1436 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1437 return FALSE;
1441 /***********************************************************************
1442 * get_builtin_fullname
1444 * Build the full pathname for a builtin dll.
1446 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1448 static const WCHAR soW[] = {'.','s','o',0};
1449 WCHAR *p, *fullname;
1450 size_t i, len = strlen(filename);
1452 /* check if path can correspond to the dll we have */
1453 if (path && (p = strrchrW( path, '\\' )))
1455 p++;
1456 for (i = 0; i < len; i++)
1457 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1458 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1460 /* the filename matches, use path as the full path */
1461 len += p - path;
1462 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1464 memcpy( fullname, path, len * sizeof(WCHAR) );
1465 fullname[len] = 0;
1467 return fullname;
1471 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1472 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1474 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1475 p = fullname + system_dir.Length / sizeof(WCHAR);
1476 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1477 ascii_to_unicode( p, filename, len + 1 );
1479 return fullname;
1483 /*************************************************************************
1484 * is_16bit_builtin
1486 static BOOL is_16bit_builtin( HMODULE module )
1488 const IMAGE_EXPORT_DIRECTORY *exports;
1489 DWORD exp_size;
1491 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1492 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1493 return FALSE;
1495 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1499 /***********************************************************************
1500 * load_builtin_callback
1502 * Load a library in memory; callback function for wine_dll_register
1504 static void load_builtin_callback( void *module, const char *filename )
1506 static const WCHAR emptyW[1];
1507 IMAGE_NT_HEADERS *nt;
1508 WINE_MODREF *wm;
1509 WCHAR *fullname;
1510 const WCHAR *load_path;
1512 if (!module)
1514 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1515 return;
1517 if (!(nt = RtlImageNtHeader( module )))
1519 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1520 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1521 return;
1524 virtual_create_builtin_view( module );
1526 /* create the MODREF */
1528 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1530 ERR( "can't load %s\n", filename );
1531 builtin_load_info->status = STATUS_NO_MEMORY;
1532 return;
1535 wm = alloc_module( module, fullname );
1536 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1537 if (!wm)
1539 ERR( "can't load %s\n", filename );
1540 builtin_load_info->status = STATUS_NO_MEMORY;
1541 return;
1543 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1545 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1546 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1547 is_16bit_builtin( module ))
1549 /* fixup imports */
1551 load_path = builtin_load_info->load_path;
1552 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1553 if (!load_path) load_path = emptyW;
1554 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1556 /* the module has only be inserted in the load & memory order lists */
1557 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1558 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1559 /* FIXME: free the modref */
1560 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1561 return;
1565 builtin_load_info->wm = wm;
1566 TRACE( "loaded %s %p %p\n", filename, wm, module );
1568 /* send the DLL load event */
1570 SERVER_START_REQ( load_dll )
1572 req->mapping = 0;
1573 req->base = wine_server_client_ptr( module );
1574 req->size = nt->OptionalHeader.SizeOfImage;
1575 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1576 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1577 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1578 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1579 wine_server_call( req );
1581 SERVER_END_REQ;
1583 /* setup relay debugging entry points */
1584 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1588 /******************************************************************************
1589 * load_native_dll (internal)
1591 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1592 DWORD flags, WINE_MODREF** pwm )
1594 void *module;
1595 HANDLE mapping;
1596 LARGE_INTEGER size;
1597 IMAGE_NT_HEADERS *nt;
1598 SIZE_T len = 0;
1599 WINE_MODREF *wm;
1600 NTSTATUS status;
1602 TRACE("Trying native dll %s\n", debugstr_w(name));
1604 size.QuadPart = 0;
1605 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1606 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1607 if (status != STATUS_SUCCESS) return status;
1609 module = NULL;
1610 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1611 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1612 if (status < 0) goto done;
1614 /* create the MODREF */
1616 if (!(wm = alloc_module( module, name )))
1618 status = STATUS_NO_MEMORY;
1619 goto done;
1622 /* fixup imports */
1624 nt = RtlImageNtHeader( module );
1626 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1627 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1628 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1630 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1632 /* the module has only be inserted in the load & memory order lists */
1633 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1634 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1636 /* FIXME: there are several more dangling references
1637 * left. Including dlls loaded by this dll before the
1638 * failed one. Unrolling is rather difficult with the
1639 * current structure and we can leave them lying
1640 * around with no problems, so we don't care.
1641 * As these might reference our wm, we don't free it.
1643 goto done;
1647 /* send DLL load event */
1649 SERVER_START_REQ( load_dll )
1651 req->mapping = wine_server_obj_handle( mapping );
1652 req->base = wine_server_client_ptr( module );
1653 req->size = nt->OptionalHeader.SizeOfImage;
1654 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1655 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1656 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1657 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1658 wine_server_call( req );
1660 SERVER_END_REQ;
1662 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1664 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1666 wm->ldr.LoadCount = 1;
1667 *pwm = wm;
1668 status = STATUS_SUCCESS;
1669 done:
1670 NtClose( mapping );
1671 return status;
1675 /***********************************************************************
1676 * load_builtin_dll
1678 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1679 DWORD flags, WINE_MODREF** pwm )
1681 char error[256], dllname[MAX_PATH];
1682 const WCHAR *name, *p;
1683 DWORD len, i;
1684 void *handle = NULL;
1685 struct builtin_load_info info, *prev_info;
1687 /* Fix the name in case we have a full path and extension */
1688 name = path;
1689 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1690 if ((p = strrchrW( name, '/' ))) name = p + 1;
1692 /* load_library will modify info.status. Note also that load_library can be
1693 * called several times, if the .so file we're loading has dependencies.
1694 * info.status will gather all the errors we may get while loading all these
1695 * libraries
1697 info.load_path = load_path;
1698 info.filename = NULL;
1699 info.status = STATUS_SUCCESS;
1700 info.wm = NULL;
1702 if (file) /* we have a real file, try to load it */
1704 UNICODE_STRING nt_name;
1705 ANSI_STRING unix_name;
1707 TRACE("Trying built-in %s\n", debugstr_w(path));
1709 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1710 return STATUS_DLL_NOT_FOUND;
1712 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1714 RtlFreeUnicodeString( &nt_name );
1715 return STATUS_DLL_NOT_FOUND;
1717 prev_info = builtin_load_info;
1718 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1719 builtin_load_info = &info;
1720 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1721 builtin_load_info = prev_info;
1722 RtlFreeUnicodeString( &nt_name );
1723 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1724 if (!handle)
1726 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1727 return STATUS_INVALID_IMAGE_FORMAT;
1730 else
1732 int file_exists;
1734 TRACE("Trying built-in %s\n", debugstr_w(name));
1736 /* we don't want to depend on the current codepage here */
1737 len = strlenW( name ) + 1;
1738 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1739 for (i = 0; i < len; i++)
1741 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1742 dllname[i] = (char)name[i];
1743 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1746 prev_info = builtin_load_info;
1747 builtin_load_info = &info;
1748 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1749 builtin_load_info = prev_info;
1750 if (!handle)
1752 if (!file_exists)
1754 /* The file does not exist -> WARN() */
1755 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1756 return STATUS_DLL_NOT_FOUND;
1758 /* ERR() for all other errors (missing functions, ...) */
1759 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1760 return STATUS_PROCEDURE_NOT_FOUND;
1764 if (info.status != STATUS_SUCCESS)
1766 wine_dll_unload( handle );
1767 return info.status;
1770 if (!info.wm)
1772 PLIST_ENTRY mark, entry;
1774 /* The constructor wasn't called, this means the .so is already
1775 * loaded under a different name. Try to find the wm for it. */
1777 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1778 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1780 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1781 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1783 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1784 TRACE( "Found %s at %p for builtin %s\n",
1785 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1786 break;
1789 wine_dll_unload( handle ); /* release the libdl refcount */
1790 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1791 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1793 else
1795 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1796 info.wm->ldr.LoadCount = 1;
1797 info.wm->ldr.SectionHandle = handle;
1800 *pwm = info.wm;
1801 return STATUS_SUCCESS;
1805 /***********************************************************************
1806 * find_actctx_dll
1808 * Find the full path (if any) of the dll from the activation context.
1810 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1812 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1813 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1815 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1816 ACTCTX_SECTION_KEYED_DATA data;
1817 UNICODE_STRING nameW;
1818 NTSTATUS status;
1819 SIZE_T needed, size = 1024;
1820 WCHAR *p;
1822 RtlInitUnicodeString( &nameW, libname );
1823 data.cbSize = sizeof(data);
1824 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1825 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1826 &nameW, &data );
1827 if (status != STATUS_SUCCESS) return status;
1829 for (;;)
1831 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1833 status = STATUS_NO_MEMORY;
1834 goto done;
1836 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1837 AssemblyDetailedInformationInActivationContext,
1838 info, size, &needed );
1839 if (status == STATUS_SUCCESS) break;
1840 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1841 RtlFreeHeap( GetProcessHeap(), 0, info );
1842 size = needed;
1843 /* restart with larger buffer */
1846 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1848 status = STATUS_SXS_KEY_NOT_FOUND;
1849 goto done;
1852 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1854 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1856 p++;
1857 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1859 /* manifest name does not match directory name, so it's not a global
1860 * windows/winsxs manifest; use the manifest directory name instead */
1861 dirlen = p - info->lpAssemblyManifestPath;
1862 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1863 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1865 status = STATUS_NO_MEMORY;
1866 goto done;
1868 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1869 p += dirlen;
1870 strcpyW( p, libname );
1871 goto done;
1875 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1876 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1878 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1880 status = STATUS_NO_MEMORY;
1881 goto done;
1883 strcpyW( p, user_shared_data->NtSystemRoot );
1884 p += strlenW(p);
1885 memcpy( p, winsxsW, sizeof(winsxsW) );
1886 p += sizeof(winsxsW) / sizeof(WCHAR);
1887 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1888 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1889 *p++ = '\\';
1890 strcpyW( p, libname );
1891 done:
1892 RtlFreeHeap( GetProcessHeap(), 0, info );
1893 RtlReleaseActivationContext( data.hActCtx );
1894 return status;
1898 /***********************************************************************
1899 * find_dll_file
1901 * Find the file (or already loaded module) for a given dll name.
1903 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1904 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1906 OBJECT_ATTRIBUTES attr;
1907 IO_STATUS_BLOCK io;
1908 UNICODE_STRING nt_name;
1909 WCHAR *file_part, *ext, *dllname;
1910 ULONG len;
1912 /* first append .dll if needed */
1914 dllname = NULL;
1915 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1917 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1918 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1919 return STATUS_NO_MEMORY;
1920 strcpyW( dllname, libname );
1921 strcatW( dllname, dllW );
1922 libname = dllname;
1925 nt_name.Buffer = NULL;
1927 if (!contains_path( libname ))
1929 NTSTATUS status;
1930 WCHAR *fullname = NULL;
1932 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1934 status = find_actctx_dll( libname, &fullname );
1935 if (status == STATUS_SUCCESS)
1937 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1938 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1939 libname = dllname = fullname;
1941 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1943 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1944 return status;
1948 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1950 /* we need to search for it */
1951 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1952 if (len)
1954 if (len >= *size) goto overflow;
1955 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1957 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1959 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1960 return STATUS_NO_MEMORY;
1962 attr.Length = sizeof(attr);
1963 attr.RootDirectory = 0;
1964 attr.Attributes = OBJ_CASE_INSENSITIVE;
1965 attr.ObjectName = &nt_name;
1966 attr.SecurityDescriptor = NULL;
1967 attr.SecurityQualityOfService = NULL;
1968 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
1969 goto found;
1972 /* not found */
1974 if (!contains_path( libname ))
1976 /* if libname doesn't contain a path at all, we simply return the name as is,
1977 * to be loaded as builtin */
1978 len = strlenW(libname) * sizeof(WCHAR);
1979 if (len >= *size) goto overflow;
1980 strcpyW( filename, libname );
1981 goto found;
1985 /* absolute path name, or relative path name but not found above */
1987 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1989 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1990 return STATUS_NO_MEMORY;
1992 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1993 if (len >= *size) goto overflow;
1994 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1995 if (!(*pwm = find_fullname_module( filename )) && handle)
1997 attr.Length = sizeof(attr);
1998 attr.RootDirectory = 0;
1999 attr.Attributes = OBJ_CASE_INSENSITIVE;
2000 attr.ObjectName = &nt_name;
2001 attr.SecurityDescriptor = NULL;
2002 attr.SecurityQualityOfService = NULL;
2003 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2005 found:
2006 RtlFreeUnicodeString( &nt_name );
2007 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2008 return STATUS_SUCCESS;
2010 overflow:
2011 RtlFreeUnicodeString( &nt_name );
2012 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2013 *size = len + sizeof(WCHAR);
2014 return STATUS_BUFFER_TOO_SMALL;
2018 /***********************************************************************
2019 * load_dll (internal)
2021 * Load a PE style module according to the load order.
2022 * The loader_section must be locked while calling this function.
2024 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2026 enum loadorder loadorder;
2027 WCHAR buffer[32];
2028 WCHAR *filename;
2029 ULONG size;
2030 WINE_MODREF *main_exe;
2031 HANDLE handle = 0;
2032 NTSTATUS nts;
2034 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2036 *pwm = NULL;
2037 filename = buffer;
2038 size = sizeof(buffer);
2039 for (;;)
2041 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2042 if (nts == STATUS_SUCCESS) break;
2043 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2044 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2045 /* grow the buffer and retry */
2046 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2049 if (*pwm) /* found already loaded module */
2051 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2053 TRACE("Found %s for %s at %p, count=%d\n",
2054 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2055 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2056 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2057 return STATUS_SUCCESS;
2060 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2061 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2063 if (handle && is_fake_dll( handle ))
2065 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2066 NtClose( handle );
2067 handle = 0;
2070 switch(loadorder)
2072 case LO_INVALID:
2073 nts = STATUS_NO_MEMORY;
2074 break;
2075 case LO_DISABLED:
2076 nts = STATUS_DLL_NOT_FOUND;
2077 break;
2078 case LO_NATIVE:
2079 case LO_NATIVE_BUILTIN:
2080 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2081 else
2083 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2084 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2085 /* not in PE format, maybe it's a builtin */
2086 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2088 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2089 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2090 break;
2091 case LO_BUILTIN:
2092 case LO_BUILTIN_NATIVE:
2093 case LO_DEFAULT: /* default is builtin,native */
2094 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2095 if (!handle) break; /* nothing else we can try */
2096 /* file is not a builtin library, try without using the specified file */
2097 if (nts != STATUS_SUCCESS)
2098 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2099 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2100 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2102 /* stub-only dll, try native */
2103 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2104 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2105 nts = STATUS_DLL_NOT_FOUND;
2107 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2108 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2109 break;
2112 if (nts == STATUS_SUCCESS)
2114 /* Initialize DLL just loaded */
2115 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2116 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2117 (*pwm)->ldr.BaseAddress);
2118 if (handle) NtClose( handle );
2119 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2120 return nts;
2123 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2124 if (handle) NtClose( handle );
2125 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2126 return nts;
2129 /******************************************************************
2130 * LdrLoadDll (NTDLL.@)
2132 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2133 const UNICODE_STRING *libname, HMODULE* hModule)
2135 WINE_MODREF *wm;
2136 NTSTATUS nts;
2138 RtlEnterCriticalSection( &loader_section );
2140 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2141 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2143 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2145 nts = process_attach( wm, NULL );
2146 if (nts != STATUS_SUCCESS)
2148 LdrUnloadDll(wm->ldr.BaseAddress);
2149 wm = NULL;
2152 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2154 RtlLeaveCriticalSection( &loader_section );
2155 return nts;
2159 /******************************************************************
2160 * LdrGetDllHandle (NTDLL.@)
2162 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2164 NTSTATUS status;
2165 WCHAR buffer[128];
2166 WCHAR *filename;
2167 ULONG size;
2168 WINE_MODREF *wm;
2170 RtlEnterCriticalSection( &loader_section );
2172 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2174 filename = buffer;
2175 size = sizeof(buffer);
2176 for (;;)
2178 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2179 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2180 if (status != STATUS_BUFFER_TOO_SMALL) break;
2181 /* grow the buffer and retry */
2182 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2184 status = STATUS_NO_MEMORY;
2185 break;
2189 if (status == STATUS_SUCCESS)
2191 if (wm) *base = wm->ldr.BaseAddress;
2192 else status = STATUS_DLL_NOT_FOUND;
2195 RtlLeaveCriticalSection( &loader_section );
2196 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2197 return status;
2201 /******************************************************************
2202 * LdrAddRefDll (NTDLL.@)
2204 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2206 NTSTATUS ret = STATUS_SUCCESS;
2207 WINE_MODREF *wm;
2209 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2211 RtlEnterCriticalSection( &loader_section );
2213 if ((wm = get_modref( module )))
2215 if (flags & LDR_ADDREF_DLL_PIN)
2216 wm->ldr.LoadCount = -1;
2217 else
2218 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2219 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2221 else ret = STATUS_INVALID_PARAMETER;
2223 RtlLeaveCriticalSection( &loader_section );
2224 return ret;
2228 /***********************************************************************
2229 * LdrProcessRelocationBlock (NTDLL.@)
2231 * Apply relocations to a given page of a mapped PE image.
2233 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2234 USHORT *relocs, INT_PTR delta )
2236 while (count--)
2238 USHORT offset = *relocs & 0xfff;
2239 int type = *relocs >> 12;
2240 switch(type)
2242 case IMAGE_REL_BASED_ABSOLUTE:
2243 break;
2244 case IMAGE_REL_BASED_HIGH:
2245 *(short *)((char *)page + offset) += HIWORD(delta);
2246 break;
2247 case IMAGE_REL_BASED_LOW:
2248 *(short *)((char *)page + offset) += LOWORD(delta);
2249 break;
2250 case IMAGE_REL_BASED_HIGHLOW:
2251 *(int *)((char *)page + offset) += delta;
2252 break;
2253 #ifdef __x86_64__
2254 case IMAGE_REL_BASED_DIR64:
2255 *(INT_PTR *)((char *)page + offset) += delta;
2256 break;
2257 #elif defined(__arm__)
2258 case IMAGE_REL_BASED_THUMB_MOV32:
2260 DWORD inst = *(INT_PTR *)((char *)page + offset);
2261 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2262 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2263 DWORD hi_delta;
2265 if ((inst & 0x8000fbf0) != 0x0000f240)
2266 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2268 imm16 += LOWORD(delta);
2269 hi_delta = HIWORD(delta) + HIWORD(imm16);
2270 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2271 ((imm16 >> 12) & 0x000f) +
2272 ((imm16 << 20) & 0x70000000) +
2273 ((imm16 << 16) & 0xff0000);
2275 if (hi_delta != 0)
2277 inst = *(INT_PTR *)((char *)page + offset + 4);
2278 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2279 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2281 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2282 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2284 imm16 += hi_delta;
2285 if (imm16 > 0xffff)
2286 ERR("resulting immediate value won't fit: %08x\n", imm16);
2287 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2288 ((imm16 >> 1) & 0x0400) +
2289 ((imm16 >> 12) & 0x000f) +
2290 ((imm16 << 20) & 0x70000000) +
2291 ((imm16 << 16) & 0xff0000);
2294 break;
2295 #endif
2296 default:
2297 FIXME("Unknown/unsupported fixup type %x.\n", type);
2298 return NULL;
2300 relocs++;
2302 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2306 /******************************************************************
2307 * LdrQueryProcessModuleInformation
2310 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2311 ULONG buf_size, ULONG* req_size)
2313 SYSTEM_MODULE* sm = &smi->Modules[0];
2314 ULONG size = sizeof(ULONG);
2315 NTSTATUS nts = STATUS_SUCCESS;
2316 ANSI_STRING str;
2317 char* ptr;
2318 PLIST_ENTRY mark, entry;
2319 PLDR_MODULE mod;
2320 WORD id = 0;
2322 smi->ModulesCount = 0;
2324 RtlEnterCriticalSection( &loader_section );
2325 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2326 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2328 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2329 size += sizeof(*sm);
2330 if (size <= buf_size)
2332 sm->Reserved1 = 0; /* FIXME */
2333 sm->Reserved2 = 0; /* FIXME */
2334 sm->ImageBaseAddress = mod->BaseAddress;
2335 sm->ImageSize = mod->SizeOfImage;
2336 sm->Flags = mod->Flags;
2337 sm->Id = id++;
2338 sm->Rank = 0; /* FIXME */
2339 sm->Unknown = 0; /* FIXME */
2340 str.Length = 0;
2341 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2342 str.Buffer = (char*)sm->Name;
2343 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2344 ptr = strrchr(str.Buffer, '\\');
2345 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2347 smi->ModulesCount++;
2348 sm++;
2350 else nts = STATUS_INFO_LENGTH_MISMATCH;
2352 RtlLeaveCriticalSection( &loader_section );
2354 if (req_size) *req_size = size;
2356 return nts;
2360 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2362 NTSTATUS status;
2363 UNICODE_STRING str;
2364 ULONG size;
2365 WCHAR buffer[64];
2366 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2368 RtlInitUnicodeString( &str, name );
2370 size = sizeof(buffer) - sizeof(WCHAR);
2371 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2372 return status;
2374 if (info->Type != REG_DWORD)
2376 buffer[size / sizeof(WCHAR)] = 0;
2377 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2379 else memcpy( value, info->Data, sizeof(*value) );
2380 return status;
2383 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2384 void *data, ULONG in_size, ULONG *out_size )
2386 NTSTATUS status;
2387 UNICODE_STRING str;
2388 ULONG size;
2389 char *buffer;
2390 KEY_VALUE_PARTIAL_INFORMATION *info;
2391 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2393 RtlInitUnicodeString( &str, name );
2395 size = info_size + in_size;
2396 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2397 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2398 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2399 if (!status || status == STATUS_BUFFER_OVERFLOW)
2401 if (out_size) *out_size = info->DataLength;
2402 if (data && !status) memcpy( data, info->Data, info->DataLength );
2404 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2405 return status;
2409 /******************************************************************
2410 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2412 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2413 void *data, ULONG in_size, ULONG *out_size )
2415 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2416 'S','o','f','t','w','a','r','e','\\',
2417 'M','i','c','r','o','s','o','f','t','\\',
2418 'W','i','n','d','o','w','s',' ','N','T','\\',
2419 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2420 'I','m','a','g','e',' ','F','i','l','e',' ',
2421 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2422 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2423 OBJECT_ATTRIBUTES attr;
2424 UNICODE_STRING name_str;
2425 HANDLE hkey;
2426 NTSTATUS status;
2427 ULONG len;
2428 WCHAR *p;
2430 attr.Length = sizeof(attr);
2431 attr.RootDirectory = 0;
2432 attr.ObjectName = &name_str;
2433 attr.Attributes = OBJ_CASE_INSENSITIVE;
2434 attr.SecurityDescriptor = NULL;
2435 attr.SecurityQualityOfService = NULL;
2437 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2438 else p = key->Buffer;
2439 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2440 name_str.Buffer = path;
2441 name_str.Length = sizeof(optionsW) + len;
2442 name_str.MaximumLength = name_str.Length;
2443 memcpy( path, optionsW, sizeof(optionsW) );
2444 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2445 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2447 if (type == REG_DWORD)
2449 if (out_size) *out_size = sizeof(ULONG);
2450 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2451 else status = STATUS_BUFFER_OVERFLOW;
2453 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2455 NtClose( hkey );
2456 return status;
2460 /******************************************************************
2461 * RtlDllShutdownInProgress (NTDLL.@)
2463 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2465 return process_detaching;
2468 /****************************************************************************
2469 * LdrResolveDelayLoadedAPI (NTDLL.@)
2471 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2472 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2473 IMAGE_THUNK_DATA* addr, ULONG flags )
2475 IMAGE_THUNK_DATA *pIAT, *pINT;
2476 DELAYLOAD_INFO delayinfo;
2477 UNICODE_STRING mod;
2478 const CHAR* name;
2479 HMODULE *phmod;
2480 NTSTATUS nts;
2481 FARPROC fp;
2482 DWORD id;
2484 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2486 phmod = get_rva(base, desc->ModuleHandleRVA);
2487 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2488 pINT = get_rva(base, desc->ImportNameTableRVA);
2489 name = get_rva(base, desc->DllNameRVA);
2490 id = addr - pIAT;
2492 if (!*phmod)
2494 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2496 nts = STATUS_NO_MEMORY;
2497 goto fail;
2499 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2500 RtlFreeUnicodeString(&mod);
2501 if (nts) goto fail;
2504 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2505 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2506 else
2508 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2509 ANSI_STRING fnc;
2511 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2512 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2514 if (!nts)
2516 pIAT[id].u1.Function = (ULONG_PTR)fp;
2517 return fp;
2520 fail:
2521 delayinfo.Size = sizeof(delayinfo);
2522 delayinfo.DelayloadDescriptor = desc;
2523 delayinfo.ThunkAddress = addr;
2524 delayinfo.TargetDllName = name;
2525 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2526 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2527 delayinfo.TargetModuleBase = *phmod;
2528 delayinfo.Unused = NULL;
2529 delayinfo.LastError = nts;
2530 return dllhook(4, &delayinfo);
2533 /******************************************************************
2534 * LdrShutdownProcess (NTDLL.@)
2537 void WINAPI LdrShutdownProcess(void)
2539 TRACE("()\n");
2540 process_detaching = TRUE;
2541 process_detach();
2545 /******************************************************************
2546 * RtlExitUserProcess (NTDLL.@)
2548 void WINAPI RtlExitUserProcess( DWORD status )
2550 RtlEnterCriticalSection( &loader_section );
2551 RtlAcquirePebLock();
2552 NtTerminateProcess( 0, status );
2553 LdrShutdownProcess();
2554 NtTerminateProcess( GetCurrentProcess(), status );
2555 exit( status );
2558 /******************************************************************
2559 * LdrShutdownThread (NTDLL.@)
2562 void WINAPI LdrShutdownThread(void)
2564 PLIST_ENTRY mark, entry;
2565 PLDR_MODULE mod;
2566 UINT i;
2567 void **pointers;
2569 TRACE("()\n");
2571 /* don't do any detach calls if process is exiting */
2572 if (process_detaching) return;
2574 RtlEnterCriticalSection( &loader_section );
2576 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2577 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2579 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2580 InInitializationOrderModuleList);
2581 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2582 continue;
2583 if ( mod->Flags & LDR_NO_DLL_CALLS )
2584 continue;
2586 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2587 DLL_THREAD_DETACH, NULL );
2590 RtlAcquirePebLock();
2591 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2592 RtlReleasePebLock();
2594 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2596 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2597 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2599 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2600 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2601 RtlLeaveCriticalSection( &loader_section );
2605 /***********************************************************************
2606 * free_modref
2609 static void free_modref( WINE_MODREF *wm )
2611 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2612 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2613 if (wm->ldr.InInitializationOrderModuleList.Flink)
2614 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2616 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2617 if (!TRACE_ON(module))
2618 TRACE_(loaddll)("Unloaded module %s : %s\n",
2619 debugstr_w(wm->ldr.FullDllName.Buffer),
2620 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2622 SERVER_START_REQ( unload_dll )
2624 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2625 wine_server_call( req );
2627 SERVER_END_REQ;
2629 free_tls_slot( &wm->ldr );
2630 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2631 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2632 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2633 if (cached_modref == wm) cached_modref = NULL;
2634 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2635 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2636 RtlFreeHeap( GetProcessHeap(), 0, wm );
2639 /***********************************************************************
2640 * MODULE_FlushModrefs
2642 * Remove all unused modrefs and call the internal unloading routines
2643 * for the library type.
2645 * The loader_section must be locked while calling this function.
2647 static void MODULE_FlushModrefs(void)
2649 PLIST_ENTRY mark, entry, prev;
2650 PLDR_MODULE mod;
2651 WINE_MODREF*wm;
2653 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2654 for (entry = mark->Blink; entry != mark; entry = prev)
2656 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2657 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2658 prev = entry->Blink;
2659 if (!mod->LoadCount) free_modref( wm );
2662 /* check load order list too for modules that haven't been initialized yet */
2663 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2664 for (entry = mark->Blink; entry != mark; entry = prev)
2666 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2667 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2668 prev = entry->Blink;
2669 if (!mod->LoadCount) free_modref( wm );
2673 /***********************************************************************
2674 * MODULE_DecRefCount
2676 * The loader_section must be locked while calling this function.
2678 static void MODULE_DecRefCount( WINE_MODREF *wm )
2680 int i;
2682 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2683 return;
2685 if ( wm->ldr.LoadCount <= 0 )
2686 return;
2688 --wm->ldr.LoadCount;
2689 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2691 if ( wm->ldr.LoadCount == 0 )
2693 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2695 for ( i = 0; i < wm->nDeps; i++ )
2696 if ( wm->deps[i] )
2697 MODULE_DecRefCount( wm->deps[i] );
2699 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2703 /******************************************************************
2704 * LdrUnloadDll (NTDLL.@)
2708 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2710 WINE_MODREF *wm;
2711 NTSTATUS retv = STATUS_SUCCESS;
2713 if (process_detaching) return retv;
2715 TRACE("(%p)\n", hModule);
2717 RtlEnterCriticalSection( &loader_section );
2719 free_lib_count++;
2720 if ((wm = get_modref( hModule )) != NULL)
2722 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2724 /* Recursively decrement reference counts */
2725 MODULE_DecRefCount( wm );
2727 /* Call process detach notifications */
2728 if ( free_lib_count <= 1 )
2730 process_detach();
2731 MODULE_FlushModrefs();
2734 TRACE("END\n");
2736 else
2737 retv = STATUS_DLL_NOT_FOUND;
2739 free_lib_count--;
2741 RtlLeaveCriticalSection( &loader_section );
2743 return retv;
2746 /***********************************************************************
2747 * RtlImageNtHeader (NTDLL.@)
2749 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2751 IMAGE_NT_HEADERS *ret;
2753 __TRY
2755 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2757 ret = NULL;
2758 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2760 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2761 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2764 __EXCEPT_PAGE_FAULT
2766 return NULL;
2768 __ENDTRY
2769 return ret;
2773 /***********************************************************************
2774 * attach_process_dlls
2776 * Initial attach to all the dlls loaded by the process.
2778 static NTSTATUS attach_process_dlls( void *wm )
2780 NTSTATUS status;
2782 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2784 RtlEnterCriticalSection( &loader_section );
2785 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2787 if (last_failed_modref)
2788 ERR( "%s failed to initialize, aborting\n",
2789 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2790 return status;
2792 attach_implicitly_loaded_dlls( (LPVOID)1 );
2793 RtlLeaveCriticalSection( &loader_section );
2794 return status;
2798 /***********************************************************************
2799 * load_global_options
2801 static void load_global_options(void)
2803 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2804 'S','y','s','t','e','m','\\',
2805 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2806 'C','o','n','t','r','o','l','\\',
2807 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2808 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2809 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};
2810 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2811 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2812 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};
2813 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};
2815 OBJECT_ATTRIBUTES attr;
2816 UNICODE_STRING name_str;
2817 HANDLE hkey;
2818 ULONG value;
2820 attr.Length = sizeof(attr);
2821 attr.RootDirectory = 0;
2822 attr.ObjectName = &name_str;
2823 attr.Attributes = OBJ_CASE_INSENSITIVE;
2824 attr.SecurityDescriptor = NULL;
2825 attr.SecurityQualityOfService = NULL;
2826 RtlInitUnicodeString( &name_str, sessionW );
2828 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2830 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2832 query_dword_option( hkey, critsectW, &value );
2833 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2835 query_dword_option( hkey, heapresW, &value );
2836 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2838 query_dword_option( hkey, heapcommitW, &value );
2839 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2841 query_dword_option( hkey, decommittotalW, &value );
2842 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2844 query_dword_option( hkey, decommitfreeW, &value );
2845 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2847 NtClose( hkey );
2851 /***********************************************************************
2852 * start_process
2854 static void start_process( void *kernel_start )
2856 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2859 /******************************************************************
2860 * LdrInitializeThunk (NTDLL.@)
2863 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2864 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2866 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2867 NTSTATUS status;
2868 WINE_MODREF *wm;
2869 LPCWSTR load_path;
2870 PEB *peb = NtCurrentTeb()->Peb;
2872 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2874 /* allocate the modref for the main exe (if not already done) */
2875 wm = get_modref( peb->ImageBaseAddress );
2876 assert( wm );
2877 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2879 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2880 exit(1);
2883 peb->LoaderLock = &loader_section;
2884 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2885 if (!peb->ProcessParameters->WindowTitle.Buffer)
2886 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2887 version_init( wm->ldr.FullDllName.Buffer );
2888 virtual_set_large_address_space();
2890 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2891 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2893 /* the main exe needs to be the first in the load order list */
2894 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2895 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2897 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2898 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2900 actctx_init();
2901 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2902 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2903 heap_set_debug_flags( GetProcessHeap() );
2905 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2906 if (status != STATUS_SUCCESS) goto error;
2908 virtual_release_address_space();
2909 virtual_clear_thread_stack();
2910 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2912 error:
2913 ERR( "Main exe initialization for %s failed, status %x\n",
2914 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2915 NtTerminateProcess( GetCurrentProcess(), status );
2919 /***********************************************************************
2920 * RtlImageDirectoryEntryToData (NTDLL.@)
2922 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2924 const IMAGE_NT_HEADERS *nt;
2925 DWORD addr;
2927 if ((ULONG_PTR)module & 1) /* mapped as data file */
2929 module = (HMODULE)((ULONG_PTR)module & ~1);
2930 image = FALSE;
2932 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2933 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2935 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2937 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2938 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2939 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2940 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2942 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2944 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2946 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2947 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2948 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2949 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2951 else return NULL;
2953 /* not mapped as image, need to find the section containing the virtual address */
2954 return RtlImageRvaToVa( nt, module, addr, NULL );
2958 /***********************************************************************
2959 * RtlImageRvaToSection (NTDLL.@)
2961 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2962 HMODULE module, DWORD rva )
2964 int i;
2965 const IMAGE_SECTION_HEADER *sec;
2967 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2968 nt->FileHeader.SizeOfOptionalHeader);
2969 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2971 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2972 return (PIMAGE_SECTION_HEADER)sec;
2974 return NULL;
2978 /***********************************************************************
2979 * RtlImageRvaToVa (NTDLL.@)
2981 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2982 DWORD rva, IMAGE_SECTION_HEADER **section )
2984 IMAGE_SECTION_HEADER *sec;
2986 if (section && *section) /* try this section first */
2988 sec = *section;
2989 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2990 goto found;
2992 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2993 found:
2994 if (section) *section = sec;
2995 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2999 /***********************************************************************
3000 * RtlPcToFileHeader (NTDLL.@)
3002 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3004 LDR_MODULE *module;
3005 PVOID ret = NULL;
3007 RtlEnterCriticalSection( &loader_section );
3008 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3009 RtlLeaveCriticalSection( &loader_section );
3010 *address = ret;
3011 return ret;
3015 /***********************************************************************
3016 * NtLoadDriver (NTDLL.@)
3017 * ZwLoadDriver (NTDLL.@)
3019 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3021 FIXME("(%p), stub!\n",DriverServiceName);
3022 return STATUS_NOT_IMPLEMENTED;
3026 /***********************************************************************
3027 * NtUnloadDriver (NTDLL.@)
3028 * ZwUnloadDriver (NTDLL.@)
3030 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3032 FIXME("(%p), stub!\n",DriverServiceName);
3033 return STATUS_NOT_IMPLEMENTED;
3037 /******************************************************************
3038 * DllMain (NTDLL.@)
3040 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3042 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3043 return TRUE;
3047 /******************************************************************
3048 * __wine_init_windows_dir (NTDLL.@)
3050 * Windows and system dir initialization once kernel32 has been loaded.
3052 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3054 PLIST_ENTRY mark, entry;
3055 LPWSTR buffer, p;
3057 strcpyW( user_shared_data->NtSystemRoot, windir );
3058 DIR_init_windows_dir( windir, sysdir );
3060 /* prepend the system dir to the name of the already created modules */
3061 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3062 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3064 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3066 assert( mod->Flags & LDR_WINE_INTERNAL );
3068 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3069 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3070 if (!buffer) continue;
3071 strcpyW( buffer, system_dir.Buffer );
3072 p = buffer + strlenW( buffer );
3073 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3074 strcpyW( p, mod->FullDllName.Buffer );
3075 RtlInitUnicodeString( &mod->FullDllName, buffer );
3076 RtlInitUnicodeString( &mod->BaseDllName, p );
3081 /***********************************************************************
3082 * __wine_process_init
3084 void __wine_process_init(void)
3086 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3088 WINE_MODREF *wm;
3089 NTSTATUS status;
3090 ANSI_STRING func_name;
3091 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3093 main_exe_file = thread_init();
3095 /* retrieve current umask */
3096 FILE_umask = umask(0777);
3097 umask( FILE_umask );
3099 load_global_options();
3101 /* setup the load callback and create ntdll modref */
3102 wine_dll_set_callback( load_builtin_callback );
3104 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3106 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3107 exit(1);
3109 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3110 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3112 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3113 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3114 0, (void **)&init_func )) != STATUS_SUCCESS)
3116 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3117 exit(1);
3119 init_func();