include: Fix off-by-one error in EmfPlusRecordType enumeration.
[wine/multimedia.git] / dlls / ntdll / loader.c
blobe25ba1f537b9a844007b0a340fe0613f1162f1a6
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 * fixup_imports
711 * Fixup all imports of a given module.
712 * The loader_section must be locked while calling this function.
714 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
716 int i, nb_imports;
717 const IMAGE_IMPORT_DESCRIPTOR *imports;
718 WINE_MODREF *prev;
719 DWORD size;
720 NTSTATUS status;
721 ULONG_PTR cookie;
723 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
724 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
726 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
727 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
728 return STATUS_SUCCESS;
730 nb_imports = 0;
731 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
733 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
735 if (!create_module_activation_context( &wm->ldr ))
736 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
738 /* Allocate module dependency list */
739 wm->nDeps = nb_imports;
740 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
742 /* load the imported modules. They are automatically
743 * added to the modref list of the process.
745 prev = current_modref;
746 current_modref = wm;
747 status = STATUS_SUCCESS;
748 for (i = 0; i < nb_imports; i++)
750 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
751 status = STATUS_DLL_NOT_FOUND;
753 current_modref = prev;
754 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
755 return status;
759 /*************************************************************************
760 * is_dll_native_subsystem
762 * Check if dll is a proper native driver.
763 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
764 * while being perfectly normal DLLs. This heuristic should catch such breakages.
766 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
768 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
769 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
770 const IMAGE_IMPORT_DESCRIPTOR *imports;
771 DWORD i, size;
772 WCHAR buffer[16];
774 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
775 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
777 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
778 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
780 for (i = 0; imports[i].Name; i++)
782 const char *name = get_rva( module, imports[i].Name );
783 DWORD len = strlen(name);
784 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
785 ascii_to_unicode( buffer, name, len + 1 );
786 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
788 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
789 return FALSE;
793 return TRUE;
796 /*************************************************************************
797 * alloc_tls_slot
799 * Allocate a TLS slot for a newly-loaded module.
800 * The loader_section must be locked while calling this function.
802 static SHORT alloc_tls_slot( LDR_MODULE *mod )
804 const IMAGE_TLS_DIRECTORY *dir;
805 ULONG i, size;
806 void *new_ptr;
807 LIST_ENTRY *entry;
809 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
810 return -1;
812 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
813 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
815 for (i = 0; i < tls_module_count; i++) if (!tls_dirs[i]) break;
817 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
818 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
819 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
821 if (i == tls_module_count)
823 UINT new_count = max( 32, tls_module_count * 2 );
825 if (!tls_dirs)
826 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
827 else
828 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
829 new_count * sizeof(*tls_dirs) );
830 if (!new_ptr) return -1;
832 /* resize the pointer block in all running threads */
833 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
835 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
836 void **old = teb->ThreadLocalStoragePointer;
837 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
839 if (!new) return -1;
840 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
841 teb->ThreadLocalStoragePointer = new;
842 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
843 /* FIXME: can't free old block here, should be freed at thread exit */
846 tls_dirs = new_ptr;
847 tls_module_count = new_count;
850 /* allocate the data block in all running threads */
851 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
853 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
855 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
856 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
857 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
859 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
860 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
862 RtlFreeHeap( GetProcessHeap(), 0,
863 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
866 *(DWORD *)dir->AddressOfIndex = i;
867 tls_dirs[i] = dir;
868 return i;
872 /*************************************************************************
873 * free_tls_slot
875 * Free the module TLS slot on unload.
876 * The loader_section must be locked while calling this function.
878 static void free_tls_slot( LDR_MODULE *mod )
880 ULONG i = (USHORT)mod->TlsIndex;
882 if (mod->TlsIndex == -1) return;
883 assert( i < tls_module_count );
884 tls_dirs[i] = NULL;
888 /*************************************************************************
889 * alloc_module
891 * Allocate a WINE_MODREF structure and add it to the process list
892 * The loader_section must be locked while calling this function.
894 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
896 WINE_MODREF *wm;
897 const WCHAR *p;
898 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
899 PLIST_ENTRY entry, mark;
901 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
903 wm->nDeps = 0;
904 wm->deps = NULL;
906 wm->ldr.BaseAddress = hModule;
907 wm->ldr.EntryPoint = NULL;
908 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
909 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
910 wm->ldr.LoadCount = 1;
911 wm->ldr.SectionHandle = NULL;
912 wm->ldr.CheckSum = 0;
913 wm->ldr.TimeDateStamp = 0;
914 wm->ldr.ActivationContext = 0;
916 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
917 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
918 else p = wm->ldr.FullDllName.Buffer;
919 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
921 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
923 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
924 if (nt->OptionalHeader.AddressOfEntryPoint)
925 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
928 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
929 &wm->ldr.InLoadOrderModuleList);
931 /* insert module in MemoryList, sorted in increasing base addresses */
932 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
933 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
935 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
936 break;
938 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
939 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
940 wm->ldr.InMemoryOrderModuleList.Flink = entry;
941 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
943 /* wait until init is called for inserting into this list */
944 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
945 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
947 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
949 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
951 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
952 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
953 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
955 return wm;
959 /*************************************************************************
960 * alloc_thread_tls
962 * Allocate the per-thread structure for module TLS storage.
964 static NTSTATUS alloc_thread_tls(void)
966 void **pointers;
967 UINT i, size;
969 if (!tls_module_count) return STATUS_SUCCESS;
971 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
972 tls_module_count * sizeof(*pointers) )))
973 return STATUS_NO_MEMORY;
975 for (i = 0; i < tls_module_count; i++)
977 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
979 if (!dir) continue;
980 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
981 if (!size && !dir->SizeOfZeroFill) continue;
983 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
985 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
986 RtlFreeHeap( GetProcessHeap(), 0, pointers );
987 return STATUS_NO_MEMORY;
989 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
990 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
992 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
993 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
995 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
996 return STATUS_SUCCESS;
1000 /*************************************************************************
1001 * call_tls_callbacks
1003 static void call_tls_callbacks( HMODULE module, UINT reason )
1005 const IMAGE_TLS_DIRECTORY *dir;
1006 const PIMAGE_TLS_CALLBACK *callback;
1007 ULONG dirsize;
1009 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1010 if (!dir || !dir->AddressOfCallBacks) return;
1012 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1014 if (TRACE_ON(relay))
1015 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1016 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1017 __TRY
1019 (*callback)( module, reason, NULL );
1021 __EXCEPT_ALL
1023 if (TRACE_ON(relay))
1024 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1025 GetCurrentThreadId(), callback, module, reason_names[reason] );
1026 return;
1028 __ENDTRY
1029 if (TRACE_ON(relay))
1030 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1031 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1036 /*************************************************************************
1037 * MODULE_InitDLL
1039 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1041 WCHAR mod_name[32];
1042 NTSTATUS status = STATUS_SUCCESS;
1043 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1044 void *module = wm->ldr.BaseAddress;
1045 BOOL retv = FALSE;
1047 /* Skip calls for modules loaded with special load flags */
1049 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1050 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1051 if (!entry) return STATUS_SUCCESS;
1053 if (TRACE_ON(relay))
1055 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1056 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1057 mod_name[len / sizeof(WCHAR)] = 0;
1058 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1059 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1060 reason_names[reason], lpReserved );
1062 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1063 reason_names[reason], lpReserved );
1065 __TRY
1067 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1068 if (!retv)
1069 status = STATUS_DLL_INIT_FAILED;
1071 __EXCEPT_ALL
1073 if (TRACE_ON(relay))
1074 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1075 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1076 status = GetExceptionCode();
1078 __ENDTRY
1080 /* The state of the module list may have changed due to the call
1081 to the dll. We cannot assume that this module has not been
1082 deleted. */
1083 if (TRACE_ON(relay))
1084 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1085 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1086 reason_names[reason], lpReserved, retv );
1087 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1089 return status;
1093 /*************************************************************************
1094 * process_attach
1096 * Send the process attach notification to all DLLs the given module
1097 * depends on (recursively). This is somewhat complicated due to the fact that
1099 * - we have to respect the module dependencies, i.e. modules implicitly
1100 * referenced by another module have to be initialized before the module
1101 * itself can be initialized
1103 * - the initialization routine of a DLL can itself call LoadLibrary,
1104 * thereby introducing a whole new set of dependencies (even involving
1105 * the 'old' modules) at any time during the whole process
1107 * (Note that this routine can be recursively entered not only directly
1108 * from itself, but also via LoadLibrary from one of the called initialization
1109 * routines.)
1111 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1112 * the process *detach* notifications to be sent in the correct order.
1113 * This must not only take into account module dependencies, but also
1114 * 'hidden' dependencies created by modules calling LoadLibrary in their
1115 * attach notification routine.
1117 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1118 * list after the attach notification has returned. This implies that the
1119 * detach notifications are called in the reverse of the sequence the attach
1120 * notifications *returned*.
1122 * The loader_section must be locked while calling this function.
1124 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1126 NTSTATUS status = STATUS_SUCCESS;
1127 ULONG_PTR cookie;
1128 int i;
1130 if (process_detaching) return status;
1132 /* prevent infinite recursion in case of cyclical dependencies */
1133 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1134 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1135 return status;
1137 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1139 /* Tag current MODREF to prevent recursive loop */
1140 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1141 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1142 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1144 /* Recursively attach all DLLs this one depends on */
1145 for ( i = 0; i < wm->nDeps; i++ )
1147 if (!wm->deps[i]) continue;
1148 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1151 /* Call DLL entry point */
1152 if (status == STATUS_SUCCESS)
1154 WINE_MODREF *prev = current_modref;
1155 current_modref = wm;
1156 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1157 if (status == STATUS_SUCCESS)
1158 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1159 else
1161 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1162 /* point to the name so LdrInitializeThunk can print it */
1163 last_failed_modref = wm;
1164 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1166 current_modref = prev;
1169 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1170 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1171 &wm->ldr.InInitializationOrderModuleList);
1173 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1174 /* Remove recursion flag */
1175 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1177 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1178 return status;
1182 /**********************************************************************
1183 * attach_implicitly_loaded_dlls
1185 * Attach to the (builtin) dlls that have been implicitly loaded because
1186 * of a dependency at the Unix level, but not imported at the Win32 level.
1188 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1190 for (;;)
1192 PLIST_ENTRY mark, entry;
1194 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1195 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1197 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1199 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1200 TRACE( "found implicitly loaded %s, attaching to it\n",
1201 debugstr_w(mod->BaseDllName.Buffer));
1202 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1203 break; /* restart the search from the start */
1205 if (entry == mark) break; /* nothing found */
1210 /*************************************************************************
1211 * process_detach
1213 * Send DLL process detach notifications. See the comment about calling
1214 * sequence at process_attach.
1216 static void process_detach(void)
1218 PLIST_ENTRY mark, entry;
1219 PLDR_MODULE mod;
1221 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1224 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1226 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1227 InInitializationOrderModuleList);
1228 /* Check whether to detach this DLL */
1229 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1230 continue;
1231 if ( mod->LoadCount && !process_detaching )
1232 continue;
1234 /* Call detach notification */
1235 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1236 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1237 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1239 /* Restart at head of WINE_MODREF list, as entries might have
1240 been added and/or removed while performing the call ... */
1241 break;
1243 } while (entry != mark);
1246 /*************************************************************************
1247 * MODULE_DllThreadAttach
1249 * Send DLL thread attach notifications. These are sent in the
1250 * reverse sequence of process detach notification.
1253 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1255 PLIST_ENTRY mark, entry;
1256 PLDR_MODULE mod;
1257 NTSTATUS status;
1259 /* don't do any attach calls if process is exiting */
1260 if (process_detaching) return STATUS_SUCCESS;
1262 RtlEnterCriticalSection( &loader_section );
1264 RtlAcquirePebLock();
1265 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1266 RtlReleasePebLock();
1268 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1270 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1271 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1273 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1274 InInitializationOrderModuleList);
1275 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1276 continue;
1277 if ( mod->Flags & LDR_NO_DLL_CALLS )
1278 continue;
1280 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1281 DLL_THREAD_ATTACH, lpReserved );
1284 done:
1285 RtlLeaveCriticalSection( &loader_section );
1286 return status;
1289 /******************************************************************
1290 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1293 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1295 WINE_MODREF *wm;
1296 NTSTATUS ret = STATUS_SUCCESS;
1298 RtlEnterCriticalSection( &loader_section );
1300 wm = get_modref( hModule );
1301 if (!wm || wm->ldr.TlsIndex != -1)
1302 ret = STATUS_DLL_NOT_FOUND;
1303 else
1304 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1306 RtlLeaveCriticalSection( &loader_section );
1308 return ret;
1311 /******************************************************************
1312 * LdrFindEntryForAddress (NTDLL.@)
1314 * The loader_section must be locked while calling this function
1316 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1318 PLIST_ENTRY mark, entry;
1319 PLDR_MODULE mod;
1321 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1322 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1324 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1325 if (mod->BaseAddress <= addr &&
1326 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1328 *pmod = mod;
1329 return STATUS_SUCCESS;
1331 if (mod->BaseAddress > addr) break;
1333 return STATUS_NO_MORE_ENTRIES;
1336 /******************************************************************
1337 * LdrLockLoaderLock (NTDLL.@)
1339 * Note: flags are not implemented.
1340 * Flag 0x01 is used to raise exceptions on errors.
1341 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1343 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1345 if (flags) FIXME( "flags %x not supported\n", flags );
1347 if (result) *result = 1;
1348 if (!magic) return STATUS_INVALID_PARAMETER_3;
1349 RtlEnterCriticalSection( &loader_section );
1350 *magic = GetCurrentThreadId();
1351 return STATUS_SUCCESS;
1355 /******************************************************************
1356 * LdrUnlockLoaderUnlock (NTDLL.@)
1358 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1360 if (magic)
1362 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1363 RtlLeaveCriticalSection( &loader_section );
1365 return STATUS_SUCCESS;
1369 /******************************************************************
1370 * LdrGetProcedureAddress (NTDLL.@)
1372 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1373 ULONG ord, PVOID *address)
1375 IMAGE_EXPORT_DIRECTORY *exports;
1376 DWORD exp_size;
1377 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1379 RtlEnterCriticalSection( &loader_section );
1381 /* check if the module itself is invalid to return the proper error */
1382 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1383 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1384 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1386 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1387 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1388 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1389 if (proc)
1391 *address = proc;
1392 ret = STATUS_SUCCESS;
1396 RtlLeaveCriticalSection( &loader_section );
1397 return ret;
1401 /***********************************************************************
1402 * is_fake_dll
1404 * Check if a loaded native dll is a Wine fake dll.
1406 static BOOL is_fake_dll( HANDLE handle )
1408 static const char fakedll_signature[] = "Wine placeholder DLL";
1409 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1410 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1411 IO_STATUS_BLOCK io;
1412 LARGE_INTEGER offset;
1414 offset.QuadPart = 0;
1415 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1416 if (io.Information < sizeof(buffer)) return FALSE;
1417 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1418 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1419 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1420 return FALSE;
1424 /***********************************************************************
1425 * get_builtin_fullname
1427 * Build the full pathname for a builtin dll.
1429 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1431 static const WCHAR soW[] = {'.','s','o',0};
1432 WCHAR *p, *fullname;
1433 size_t i, len = strlen(filename);
1435 /* check if path can correspond to the dll we have */
1436 if (path && (p = strrchrW( path, '\\' )))
1438 p++;
1439 for (i = 0; i < len; i++)
1440 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1441 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1443 /* the filename matches, use path as the full path */
1444 len += p - path;
1445 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1447 memcpy( fullname, path, len * sizeof(WCHAR) );
1448 fullname[len] = 0;
1450 return fullname;
1454 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1455 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1457 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1458 p = fullname + system_dir.Length / sizeof(WCHAR);
1459 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1460 ascii_to_unicode( p, filename, len + 1 );
1462 return fullname;
1466 /***********************************************************************
1467 * load_builtin_callback
1469 * Load a library in memory; callback function for wine_dll_register
1471 static void load_builtin_callback( void *module, const char *filename )
1473 static const WCHAR emptyW[1];
1474 IMAGE_NT_HEADERS *nt;
1475 WINE_MODREF *wm;
1476 WCHAR *fullname;
1477 const WCHAR *load_path;
1479 if (!module)
1481 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1482 return;
1484 if (!(nt = RtlImageNtHeader( module )))
1486 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1487 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1488 return;
1491 virtual_create_builtin_view( module );
1493 /* create the MODREF */
1495 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1497 ERR( "can't load %s\n", filename );
1498 builtin_load_info->status = STATUS_NO_MEMORY;
1499 return;
1502 wm = alloc_module( module, fullname );
1503 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1504 if (!wm)
1506 ERR( "can't load %s\n", filename );
1507 builtin_load_info->status = STATUS_NO_MEMORY;
1508 return;
1510 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1512 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1513 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1515 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1517 else
1519 /* fixup imports */
1521 load_path = builtin_load_info->load_path;
1522 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1523 if (!load_path) load_path = emptyW;
1524 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1526 /* the module has only be inserted in the load & memory order lists */
1527 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1528 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1529 /* FIXME: free the modref */
1530 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1531 return;
1535 builtin_load_info->wm = wm;
1536 TRACE( "loaded %s %p %p\n", filename, wm, module );
1538 /* send the DLL load event */
1540 SERVER_START_REQ( load_dll )
1542 req->mapping = 0;
1543 req->base = wine_server_client_ptr( module );
1544 req->size = nt->OptionalHeader.SizeOfImage;
1545 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1546 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1547 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1548 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1549 wine_server_call( req );
1551 SERVER_END_REQ;
1553 /* setup relay debugging entry points */
1554 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1558 /******************************************************************************
1559 * load_native_dll (internal)
1561 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1562 DWORD flags, WINE_MODREF** pwm )
1564 void *module;
1565 HANDLE mapping;
1566 LARGE_INTEGER size;
1567 IMAGE_NT_HEADERS *nt;
1568 SIZE_T len = 0;
1569 WINE_MODREF *wm;
1570 NTSTATUS status;
1572 TRACE("Trying native dll %s\n", debugstr_w(name));
1574 size.QuadPart = 0;
1575 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1576 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1577 if (status != STATUS_SUCCESS) return status;
1579 module = NULL;
1580 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1581 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1582 if (status < 0) goto done;
1584 /* create the MODREF */
1586 if (!(wm = alloc_module( module, name )))
1588 status = STATUS_NO_MEMORY;
1589 goto done;
1592 /* fixup imports */
1594 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1596 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1598 /* the module has only be inserted in the load & memory order lists */
1599 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1600 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1602 /* FIXME: there are several more dangling references
1603 * left. Including dlls loaded by this dll before the
1604 * failed one. Unrolling is rather difficult with the
1605 * current structure and we can leave them lying
1606 * around with no problems, so we don't care.
1607 * As these might reference our wm, we don't free it.
1609 goto done;
1613 /* send DLL load event */
1615 nt = RtlImageNtHeader( module );
1617 SERVER_START_REQ( load_dll )
1619 req->mapping = wine_server_obj_handle( mapping );
1620 req->base = wine_server_client_ptr( module );
1621 req->size = nt->OptionalHeader.SizeOfImage;
1622 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1623 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1624 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1625 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1626 wine_server_call( req );
1628 SERVER_END_REQ;
1630 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1632 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1634 wm->ldr.LoadCount = 1;
1635 *pwm = wm;
1636 status = STATUS_SUCCESS;
1637 done:
1638 NtClose( mapping );
1639 return status;
1643 /***********************************************************************
1644 * load_builtin_dll
1646 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1647 DWORD flags, WINE_MODREF** pwm )
1649 char error[256], dllname[MAX_PATH];
1650 const WCHAR *name, *p;
1651 DWORD len, i;
1652 void *handle = NULL;
1653 struct builtin_load_info info, *prev_info;
1655 /* Fix the name in case we have a full path and extension */
1656 name = path;
1657 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1658 if ((p = strrchrW( name, '/' ))) name = p + 1;
1660 /* load_library will modify info.status. Note also that load_library can be
1661 * called several times, if the .so file we're loading has dependencies.
1662 * info.status will gather all the errors we may get while loading all these
1663 * libraries
1665 info.load_path = load_path;
1666 info.filename = NULL;
1667 info.status = STATUS_SUCCESS;
1668 info.wm = NULL;
1670 if (file) /* we have a real file, try to load it */
1672 UNICODE_STRING nt_name;
1673 ANSI_STRING unix_name;
1675 TRACE("Trying built-in %s\n", debugstr_w(path));
1677 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1678 return STATUS_DLL_NOT_FOUND;
1680 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1682 RtlFreeUnicodeString( &nt_name );
1683 return STATUS_DLL_NOT_FOUND;
1685 prev_info = builtin_load_info;
1686 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1687 builtin_load_info = &info;
1688 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1689 builtin_load_info = prev_info;
1690 RtlFreeUnicodeString( &nt_name );
1691 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1692 if (!handle)
1694 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1695 return STATUS_INVALID_IMAGE_FORMAT;
1698 else
1700 int file_exists;
1702 TRACE("Trying built-in %s\n", debugstr_w(name));
1704 /* we don't want to depend on the current codepage here */
1705 len = strlenW( name ) + 1;
1706 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1707 for (i = 0; i < len; i++)
1709 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1710 dllname[i] = (char)name[i];
1711 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1714 prev_info = builtin_load_info;
1715 builtin_load_info = &info;
1716 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1717 builtin_load_info = prev_info;
1718 if (!handle)
1720 if (!file_exists)
1722 /* The file does not exist -> WARN() */
1723 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1724 return STATUS_DLL_NOT_FOUND;
1726 /* ERR() for all other errors (missing functions, ...) */
1727 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1728 return STATUS_PROCEDURE_NOT_FOUND;
1732 if (info.status != STATUS_SUCCESS)
1734 wine_dll_unload( handle );
1735 return info.status;
1738 if (!info.wm)
1740 PLIST_ENTRY mark, entry;
1742 /* The constructor wasn't called, this means the .so is already
1743 * loaded under a different name. Try to find the wm for it. */
1745 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1746 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1748 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1749 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1751 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1752 TRACE( "Found %s at %p for builtin %s\n",
1753 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1754 break;
1757 wine_dll_unload( handle ); /* release the libdl refcount */
1758 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1759 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1761 else
1763 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1764 info.wm->ldr.LoadCount = 1;
1765 info.wm->ldr.SectionHandle = handle;
1768 *pwm = info.wm;
1769 return STATUS_SUCCESS;
1773 /***********************************************************************
1774 * find_actctx_dll
1776 * Find the full path (if any) of the dll from the activation context.
1778 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1780 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1781 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1783 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1784 ACTCTX_SECTION_KEYED_DATA data;
1785 UNICODE_STRING nameW;
1786 NTSTATUS status;
1787 SIZE_T needed, size = 1024;
1788 WCHAR *p;
1790 RtlInitUnicodeString( &nameW, libname );
1791 data.cbSize = sizeof(data);
1792 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1793 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1794 &nameW, &data );
1795 if (status != STATUS_SUCCESS) return status;
1797 for (;;)
1799 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1801 status = STATUS_NO_MEMORY;
1802 goto done;
1804 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1805 AssemblyDetailedInformationInActivationContext,
1806 info, size, &needed );
1807 if (status == STATUS_SUCCESS) break;
1808 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1809 RtlFreeHeap( GetProcessHeap(), 0, info );
1810 size = needed;
1811 /* restart with larger buffer */
1814 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1816 status = STATUS_SXS_KEY_NOT_FOUND;
1817 goto done;
1820 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1822 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1824 p++;
1825 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1827 /* manifest name does not match directory name, so it's not a global
1828 * windows/winsxs manifest; use the manifest directory name instead */
1829 dirlen = p - info->lpAssemblyManifestPath;
1830 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1831 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1833 status = STATUS_NO_MEMORY;
1834 goto done;
1836 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1837 p += dirlen;
1838 strcpyW( p, libname );
1839 goto done;
1843 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1844 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1846 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1848 status = STATUS_NO_MEMORY;
1849 goto done;
1851 strcpyW( p, user_shared_data->NtSystemRoot );
1852 p += strlenW(p);
1853 memcpy( p, winsxsW, sizeof(winsxsW) );
1854 p += sizeof(winsxsW) / sizeof(WCHAR);
1855 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1856 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1857 *p++ = '\\';
1858 strcpyW( p, libname );
1859 done:
1860 RtlFreeHeap( GetProcessHeap(), 0, info );
1861 RtlReleaseActivationContext( data.hActCtx );
1862 return status;
1866 /***********************************************************************
1867 * find_dll_file
1869 * Find the file (or already loaded module) for a given dll name.
1871 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1872 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1874 OBJECT_ATTRIBUTES attr;
1875 IO_STATUS_BLOCK io;
1876 UNICODE_STRING nt_name;
1877 WCHAR *file_part, *ext, *dllname;
1878 ULONG len;
1880 /* first append .dll if needed */
1882 dllname = NULL;
1883 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1885 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1886 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1887 return STATUS_NO_MEMORY;
1888 strcpyW( dllname, libname );
1889 strcatW( dllname, dllW );
1890 libname = dllname;
1893 nt_name.Buffer = NULL;
1895 if (!contains_path( libname ))
1897 NTSTATUS status;
1898 WCHAR *fullname = NULL;
1900 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1902 status = find_actctx_dll( libname, &fullname );
1903 if (status == STATUS_SUCCESS)
1905 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1906 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1907 libname = dllname = fullname;
1909 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1911 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1912 return status;
1916 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1918 /* we need to search for it */
1919 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1920 if (len)
1922 if (len >= *size) goto overflow;
1923 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1925 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1927 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1928 return STATUS_NO_MEMORY;
1930 attr.Length = sizeof(attr);
1931 attr.RootDirectory = 0;
1932 attr.Attributes = OBJ_CASE_INSENSITIVE;
1933 attr.ObjectName = &nt_name;
1934 attr.SecurityDescriptor = NULL;
1935 attr.SecurityQualityOfService = NULL;
1936 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
1937 goto found;
1940 /* not found */
1942 if (!contains_path( libname ))
1944 /* if libname doesn't contain a path at all, we simply return the name as is,
1945 * to be loaded as builtin */
1946 len = strlenW(libname) * sizeof(WCHAR);
1947 if (len >= *size) goto overflow;
1948 strcpyW( filename, libname );
1949 goto found;
1953 /* absolute path name, or relative path name but not found above */
1955 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1957 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1958 return STATUS_NO_MEMORY;
1960 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1961 if (len >= *size) goto overflow;
1962 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1963 if (!(*pwm = find_fullname_module( filename )) && handle)
1965 attr.Length = sizeof(attr);
1966 attr.RootDirectory = 0;
1967 attr.Attributes = OBJ_CASE_INSENSITIVE;
1968 attr.ObjectName = &nt_name;
1969 attr.SecurityDescriptor = NULL;
1970 attr.SecurityQualityOfService = NULL;
1971 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
1973 found:
1974 RtlFreeUnicodeString( &nt_name );
1975 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1976 return STATUS_SUCCESS;
1978 overflow:
1979 RtlFreeUnicodeString( &nt_name );
1980 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1981 *size = len + sizeof(WCHAR);
1982 return STATUS_BUFFER_TOO_SMALL;
1986 /***********************************************************************
1987 * load_dll (internal)
1989 * Load a PE style module according to the load order.
1990 * The loader_section must be locked while calling this function.
1992 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1994 enum loadorder loadorder;
1995 WCHAR buffer[32];
1996 WCHAR *filename;
1997 ULONG size;
1998 WINE_MODREF *main_exe;
1999 HANDLE handle = 0;
2000 NTSTATUS nts;
2002 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2004 *pwm = NULL;
2005 filename = buffer;
2006 size = sizeof(buffer);
2007 for (;;)
2009 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2010 if (nts == STATUS_SUCCESS) break;
2011 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2012 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2013 /* grow the buffer and retry */
2014 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2017 if (*pwm) /* found already loaded module */
2019 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2021 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
2023 TRACE("Found %s for %s at %p, count=%d\n",
2024 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2025 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2026 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2027 return STATUS_SUCCESS;
2030 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2031 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2033 if (handle && is_fake_dll( handle ))
2035 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2036 NtClose( handle );
2037 handle = 0;
2040 switch(loadorder)
2042 case LO_INVALID:
2043 nts = STATUS_NO_MEMORY;
2044 break;
2045 case LO_DISABLED:
2046 nts = STATUS_DLL_NOT_FOUND;
2047 break;
2048 case LO_NATIVE:
2049 case LO_NATIVE_BUILTIN:
2050 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2051 else
2053 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2054 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2055 /* not in PE format, maybe it's a builtin */
2056 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2058 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2059 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2060 break;
2061 case LO_BUILTIN:
2062 case LO_BUILTIN_NATIVE:
2063 case LO_DEFAULT: /* default is builtin,native */
2064 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2065 if (!handle) break; /* nothing else we can try */
2066 /* file is not a builtin library, try without using the specified file */
2067 if (nts != STATUS_SUCCESS)
2068 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2069 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2070 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2072 /* stub-only dll, try native */
2073 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2074 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2075 nts = STATUS_DLL_NOT_FOUND;
2077 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2078 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2079 break;
2082 if (nts == STATUS_SUCCESS)
2084 /* Initialize DLL just loaded */
2085 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2086 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2087 (*pwm)->ldr.BaseAddress);
2088 if (handle) NtClose( handle );
2089 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2090 return nts;
2093 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2094 if (handle) NtClose( handle );
2095 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2096 return nts;
2099 /******************************************************************
2100 * LdrLoadDll (NTDLL.@)
2102 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2103 const UNICODE_STRING *libname, HMODULE* hModule)
2105 WINE_MODREF *wm;
2106 NTSTATUS nts;
2108 RtlEnterCriticalSection( &loader_section );
2110 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2111 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2113 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2115 nts = process_attach( wm, NULL );
2116 if (nts != STATUS_SUCCESS)
2118 LdrUnloadDll(wm->ldr.BaseAddress);
2119 wm = NULL;
2122 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2124 RtlLeaveCriticalSection( &loader_section );
2125 return nts;
2129 /******************************************************************
2130 * LdrGetDllHandle (NTDLL.@)
2132 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2134 NTSTATUS status;
2135 WCHAR buffer[128];
2136 WCHAR *filename;
2137 ULONG size;
2138 WINE_MODREF *wm;
2140 RtlEnterCriticalSection( &loader_section );
2142 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2144 filename = buffer;
2145 size = sizeof(buffer);
2146 for (;;)
2148 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2149 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2150 if (status != STATUS_BUFFER_TOO_SMALL) break;
2151 /* grow the buffer and retry */
2152 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2154 status = STATUS_NO_MEMORY;
2155 break;
2159 if (status == STATUS_SUCCESS)
2161 if (wm) *base = wm->ldr.BaseAddress;
2162 else status = STATUS_DLL_NOT_FOUND;
2165 RtlLeaveCriticalSection( &loader_section );
2166 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2167 return status;
2171 /******************************************************************
2172 * LdrAddRefDll (NTDLL.@)
2174 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2176 NTSTATUS ret = STATUS_SUCCESS;
2177 WINE_MODREF *wm;
2179 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2181 RtlEnterCriticalSection( &loader_section );
2183 if ((wm = get_modref( module )))
2185 if (flags & LDR_ADDREF_DLL_PIN)
2186 wm->ldr.LoadCount = -1;
2187 else
2188 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2189 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2191 else ret = STATUS_INVALID_PARAMETER;
2193 RtlLeaveCriticalSection( &loader_section );
2194 return ret;
2198 /***********************************************************************
2199 * LdrProcessRelocationBlock (NTDLL.@)
2201 * Apply relocations to a given page of a mapped PE image.
2203 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2204 USHORT *relocs, INT_PTR delta )
2206 while (count--)
2208 USHORT offset = *relocs & 0xfff;
2209 int type = *relocs >> 12;
2210 switch(type)
2212 case IMAGE_REL_BASED_ABSOLUTE:
2213 break;
2214 case IMAGE_REL_BASED_HIGH:
2215 *(short *)((char *)page + offset) += HIWORD(delta);
2216 break;
2217 case IMAGE_REL_BASED_LOW:
2218 *(short *)((char *)page + offset) += LOWORD(delta);
2219 break;
2220 case IMAGE_REL_BASED_HIGHLOW:
2221 *(int *)((char *)page + offset) += delta;
2222 break;
2223 #ifdef __x86_64__
2224 case IMAGE_REL_BASED_DIR64:
2225 *(INT_PTR *)((char *)page + offset) += delta;
2226 break;
2227 #elif defined(__arm__)
2228 case IMAGE_REL_BASED_THUMB_MOV32:
2230 DWORD inst = *(INT_PTR *)((char *)page + offset);
2231 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2232 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2233 DWORD hi_delta;
2235 if ((inst & 0x8000fbf0) != 0x0000f240)
2236 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2238 imm16 += LOWORD(delta);
2239 hi_delta = HIWORD(delta) + HIWORD(imm16);
2240 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2241 ((imm16 >> 12) & 0x000f) +
2242 ((imm16 << 20) & 0x70000000) +
2243 ((imm16 << 16) & 0xff0000);
2245 if (hi_delta != 0)
2247 inst = *(INT_PTR *)((char *)page + offset + 4);
2248 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2249 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2251 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2252 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2254 imm16 += hi_delta;
2255 if (imm16 > 0xffff)
2256 ERR("resulting immediate value won't fit: %08x\n", imm16);
2257 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2258 ((imm16 >> 1) & 0x0400) +
2259 ((imm16 >> 12) & 0x000f) +
2260 ((imm16 << 20) & 0x70000000) +
2261 ((imm16 << 16) & 0xff0000);
2264 break;
2265 #endif
2266 default:
2267 FIXME("Unknown/unsupported fixup type %x.\n", type);
2268 return NULL;
2270 relocs++;
2272 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2276 /******************************************************************
2277 * LdrQueryProcessModuleInformation
2280 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2281 ULONG buf_size, ULONG* req_size)
2283 SYSTEM_MODULE* sm = &smi->Modules[0];
2284 ULONG size = sizeof(ULONG);
2285 NTSTATUS nts = STATUS_SUCCESS;
2286 ANSI_STRING str;
2287 char* ptr;
2288 PLIST_ENTRY mark, entry;
2289 PLDR_MODULE mod;
2290 WORD id = 0;
2292 smi->ModulesCount = 0;
2294 RtlEnterCriticalSection( &loader_section );
2295 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2296 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2298 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2299 size += sizeof(*sm);
2300 if (size <= buf_size)
2302 sm->Reserved1 = 0; /* FIXME */
2303 sm->Reserved2 = 0; /* FIXME */
2304 sm->ImageBaseAddress = mod->BaseAddress;
2305 sm->ImageSize = mod->SizeOfImage;
2306 sm->Flags = mod->Flags;
2307 sm->Id = id++;
2308 sm->Rank = 0; /* FIXME */
2309 sm->Unknown = 0; /* FIXME */
2310 str.Length = 0;
2311 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2312 str.Buffer = (char*)sm->Name;
2313 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2314 ptr = strrchr(str.Buffer, '\\');
2315 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2317 smi->ModulesCount++;
2318 sm++;
2320 else nts = STATUS_INFO_LENGTH_MISMATCH;
2322 RtlLeaveCriticalSection( &loader_section );
2324 if (req_size) *req_size = size;
2326 return nts;
2330 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2332 NTSTATUS status;
2333 UNICODE_STRING str;
2334 ULONG size;
2335 WCHAR buffer[64];
2336 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2338 RtlInitUnicodeString( &str, name );
2340 size = sizeof(buffer) - sizeof(WCHAR);
2341 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2342 return status;
2344 if (info->Type != REG_DWORD)
2346 buffer[size / sizeof(WCHAR)] = 0;
2347 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2349 else memcpy( value, info->Data, sizeof(*value) );
2350 return status;
2353 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2354 void *data, ULONG in_size, ULONG *out_size )
2356 NTSTATUS status;
2357 UNICODE_STRING str;
2358 ULONG size;
2359 char *buffer;
2360 KEY_VALUE_PARTIAL_INFORMATION *info;
2361 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2363 RtlInitUnicodeString( &str, name );
2365 size = info_size + in_size;
2366 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2367 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2368 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2369 if (!status || status == STATUS_BUFFER_OVERFLOW)
2371 if (out_size) *out_size = info->DataLength;
2372 if (data && !status) memcpy( data, info->Data, info->DataLength );
2374 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2375 return status;
2379 /******************************************************************
2380 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2382 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2383 void *data, ULONG in_size, ULONG *out_size )
2385 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2386 'S','o','f','t','w','a','r','e','\\',
2387 'M','i','c','r','o','s','o','f','t','\\',
2388 'W','i','n','d','o','w','s',' ','N','T','\\',
2389 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2390 'I','m','a','g','e',' ','F','i','l','e',' ',
2391 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2392 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2393 OBJECT_ATTRIBUTES attr;
2394 UNICODE_STRING name_str;
2395 HANDLE hkey;
2396 NTSTATUS status;
2397 ULONG len;
2398 WCHAR *p;
2400 attr.Length = sizeof(attr);
2401 attr.RootDirectory = 0;
2402 attr.ObjectName = &name_str;
2403 attr.Attributes = OBJ_CASE_INSENSITIVE;
2404 attr.SecurityDescriptor = NULL;
2405 attr.SecurityQualityOfService = NULL;
2407 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2408 else p = key->Buffer;
2409 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2410 name_str.Buffer = path;
2411 name_str.Length = sizeof(optionsW) + len;
2412 name_str.MaximumLength = name_str.Length;
2413 memcpy( path, optionsW, sizeof(optionsW) );
2414 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2415 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2417 if (type == REG_DWORD)
2419 if (out_size) *out_size = sizeof(ULONG);
2420 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2421 else status = STATUS_BUFFER_OVERFLOW;
2423 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2425 NtClose( hkey );
2426 return status;
2430 /******************************************************************
2431 * RtlDllShutdownInProgress (NTDLL.@)
2433 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2435 return process_detaching;
2438 /****************************************************************************
2439 * LdrResolveDelayLoadedAPI (NTDLL.@)
2441 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2442 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2443 IMAGE_THUNK_DATA* addr, ULONG flags )
2445 IMAGE_THUNK_DATA *pIAT, *pINT;
2446 DELAYLOAD_INFO delayinfo;
2447 UNICODE_STRING mod;
2448 const CHAR* name;
2449 HMODULE *phmod;
2450 NTSTATUS nts;
2451 FARPROC fp;
2452 DWORD id;
2454 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2456 phmod = get_rva(base, desc->ModuleHandleRVA);
2457 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2458 pINT = get_rva(base, desc->ImportNameTableRVA);
2459 name = get_rva(base, desc->DllNameRVA);
2460 id = addr - pIAT;
2462 if (!*phmod)
2464 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2466 nts = STATUS_NO_MEMORY;
2467 goto fail;
2469 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2470 RtlFreeUnicodeString(&mod);
2471 if (nts) goto fail;
2474 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2475 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2476 else
2478 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2479 ANSI_STRING fnc;
2481 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2482 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2484 if (!nts)
2486 pIAT[id].u1.Function = (ULONG_PTR)fp;
2487 return fp;
2490 fail:
2491 delayinfo.Size = sizeof(delayinfo);
2492 delayinfo.DelayloadDescriptor = desc;
2493 delayinfo.ThunkAddress = addr;
2494 delayinfo.TargetDllName = name;
2495 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2496 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2497 delayinfo.TargetModuleBase = *phmod;
2498 delayinfo.Unused = NULL;
2499 delayinfo.LastError = nts;
2500 return dllhook(4, &delayinfo);
2503 /******************************************************************
2504 * LdrShutdownProcess (NTDLL.@)
2507 void WINAPI LdrShutdownProcess(void)
2509 TRACE("()\n");
2510 process_detaching = TRUE;
2511 process_detach();
2515 /******************************************************************
2516 * RtlExitUserProcess (NTDLL.@)
2518 void WINAPI RtlExitUserProcess( DWORD status )
2520 RtlEnterCriticalSection( &loader_section );
2521 RtlAcquirePebLock();
2522 NtTerminateProcess( 0, status );
2523 LdrShutdownProcess();
2524 NtTerminateProcess( GetCurrentProcess(), status );
2525 exit( status );
2528 /******************************************************************
2529 * LdrShutdownThread (NTDLL.@)
2532 void WINAPI LdrShutdownThread(void)
2534 PLIST_ENTRY mark, entry;
2535 PLDR_MODULE mod;
2536 UINT i;
2537 void **pointers;
2539 TRACE("()\n");
2541 /* don't do any detach calls if process is exiting */
2542 if (process_detaching) return;
2544 RtlEnterCriticalSection( &loader_section );
2546 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2547 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2549 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2550 InInitializationOrderModuleList);
2551 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2552 continue;
2553 if ( mod->Flags & LDR_NO_DLL_CALLS )
2554 continue;
2556 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2557 DLL_THREAD_DETACH, NULL );
2560 RtlAcquirePebLock();
2561 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2562 RtlReleasePebLock();
2564 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2566 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2567 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2569 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2570 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2571 RtlLeaveCriticalSection( &loader_section );
2575 /***********************************************************************
2576 * free_modref
2579 static void free_modref( WINE_MODREF *wm )
2581 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2582 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2583 if (wm->ldr.InInitializationOrderModuleList.Flink)
2584 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2586 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2587 if (!TRACE_ON(module))
2588 TRACE_(loaddll)("Unloaded module %s : %s\n",
2589 debugstr_w(wm->ldr.FullDllName.Buffer),
2590 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2592 SERVER_START_REQ( unload_dll )
2594 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2595 wine_server_call( req );
2597 SERVER_END_REQ;
2599 free_tls_slot( &wm->ldr );
2600 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2601 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2602 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2603 if (cached_modref == wm) cached_modref = NULL;
2604 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2605 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2606 RtlFreeHeap( GetProcessHeap(), 0, wm );
2609 /***********************************************************************
2610 * MODULE_FlushModrefs
2612 * Remove all unused modrefs and call the internal unloading routines
2613 * for the library type.
2615 * The loader_section must be locked while calling this function.
2617 static void MODULE_FlushModrefs(void)
2619 PLIST_ENTRY mark, entry, prev;
2620 PLDR_MODULE mod;
2621 WINE_MODREF*wm;
2623 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2624 for (entry = mark->Blink; entry != mark; entry = prev)
2626 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2627 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2628 prev = entry->Blink;
2629 if (!mod->LoadCount) free_modref( wm );
2632 /* check load order list too for modules that haven't been initialized yet */
2633 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2634 for (entry = mark->Blink; entry != mark; entry = prev)
2636 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2637 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2638 prev = entry->Blink;
2639 if (!mod->LoadCount) free_modref( wm );
2643 /***********************************************************************
2644 * MODULE_DecRefCount
2646 * The loader_section must be locked while calling this function.
2648 static void MODULE_DecRefCount( WINE_MODREF *wm )
2650 int i;
2652 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2653 return;
2655 if ( wm->ldr.LoadCount <= 0 )
2656 return;
2658 --wm->ldr.LoadCount;
2659 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2661 if ( wm->ldr.LoadCount == 0 )
2663 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2665 for ( i = 0; i < wm->nDeps; i++ )
2666 if ( wm->deps[i] )
2667 MODULE_DecRefCount( wm->deps[i] );
2669 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2673 /******************************************************************
2674 * LdrUnloadDll (NTDLL.@)
2678 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2680 WINE_MODREF *wm;
2681 NTSTATUS retv = STATUS_SUCCESS;
2683 if (process_detaching) return retv;
2685 TRACE("(%p)\n", hModule);
2687 RtlEnterCriticalSection( &loader_section );
2689 free_lib_count++;
2690 if ((wm = get_modref( hModule )) != NULL)
2692 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2694 /* Recursively decrement reference counts */
2695 MODULE_DecRefCount( wm );
2697 /* Call process detach notifications */
2698 if ( free_lib_count <= 1 )
2700 process_detach();
2701 MODULE_FlushModrefs();
2704 TRACE("END\n");
2706 else
2707 retv = STATUS_DLL_NOT_FOUND;
2709 free_lib_count--;
2711 RtlLeaveCriticalSection( &loader_section );
2713 return retv;
2716 /***********************************************************************
2717 * RtlImageNtHeader (NTDLL.@)
2719 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2721 IMAGE_NT_HEADERS *ret;
2723 __TRY
2725 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2727 ret = NULL;
2728 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2730 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2731 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2734 __EXCEPT_PAGE_FAULT
2736 return NULL;
2738 __ENDTRY
2739 return ret;
2743 /***********************************************************************
2744 * attach_process_dlls
2746 * Initial attach to all the dlls loaded by the process.
2748 static NTSTATUS attach_process_dlls( void *wm )
2750 NTSTATUS status;
2752 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2754 RtlEnterCriticalSection( &loader_section );
2755 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2757 if (last_failed_modref)
2758 ERR( "%s failed to initialize, aborting\n",
2759 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2760 return status;
2762 attach_implicitly_loaded_dlls( (LPVOID)1 );
2763 RtlLeaveCriticalSection( &loader_section );
2764 return status;
2768 /***********************************************************************
2769 * load_global_options
2771 static void load_global_options(void)
2773 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2774 'S','y','s','t','e','m','\\',
2775 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2776 'C','o','n','t','r','o','l','\\',
2777 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2778 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2779 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};
2780 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2781 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2782 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};
2783 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};
2785 OBJECT_ATTRIBUTES attr;
2786 UNICODE_STRING name_str;
2787 HANDLE hkey;
2788 ULONG value;
2790 attr.Length = sizeof(attr);
2791 attr.RootDirectory = 0;
2792 attr.ObjectName = &name_str;
2793 attr.Attributes = OBJ_CASE_INSENSITIVE;
2794 attr.SecurityDescriptor = NULL;
2795 attr.SecurityQualityOfService = NULL;
2796 RtlInitUnicodeString( &name_str, sessionW );
2798 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2800 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2802 query_dword_option( hkey, critsectW, &value );
2803 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2805 query_dword_option( hkey, heapresW, &value );
2806 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2808 query_dword_option( hkey, heapcommitW, &value );
2809 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2811 query_dword_option( hkey, decommittotalW, &value );
2812 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2814 query_dword_option( hkey, decommitfreeW, &value );
2815 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2817 NtClose( hkey );
2821 /***********************************************************************
2822 * start_process
2824 static void start_process( void *kernel_start )
2826 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2829 /******************************************************************
2830 * LdrInitializeThunk (NTDLL.@)
2833 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2834 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2836 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2837 NTSTATUS status;
2838 WINE_MODREF *wm;
2839 LPCWSTR load_path;
2840 PEB *peb = NtCurrentTeb()->Peb;
2842 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2844 /* allocate the modref for the main exe (if not already done) */
2845 wm = get_modref( peb->ImageBaseAddress );
2846 assert( wm );
2847 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2849 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2850 exit(1);
2853 peb->LoaderLock = &loader_section;
2854 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2855 if (!peb->ProcessParameters->WindowTitle.Buffer)
2856 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2857 version_init( wm->ldr.FullDllName.Buffer );
2858 virtual_set_large_address_space();
2860 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2861 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2863 /* the main exe needs to be the first in the load order list */
2864 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2865 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2867 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2868 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2870 actctx_init();
2871 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2872 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2873 heap_set_debug_flags( GetProcessHeap() );
2875 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2876 if (status != STATUS_SUCCESS) goto error;
2878 virtual_release_address_space();
2879 virtual_clear_thread_stack();
2880 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2882 error:
2883 ERR( "Main exe initialization for %s failed, status %x\n",
2884 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2885 NtTerminateProcess( GetCurrentProcess(), status );
2889 /***********************************************************************
2890 * RtlImageDirectoryEntryToData (NTDLL.@)
2892 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2894 const IMAGE_NT_HEADERS *nt;
2895 DWORD addr;
2897 if ((ULONG_PTR)module & 1) /* mapped as data file */
2899 module = (HMODULE)((ULONG_PTR)module & ~1);
2900 image = FALSE;
2902 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2903 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2905 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2907 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2908 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2909 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2910 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2912 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2914 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2916 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2917 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2918 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2919 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2921 else return NULL;
2923 /* not mapped as image, need to find the section containing the virtual address */
2924 return RtlImageRvaToVa( nt, module, addr, NULL );
2928 /***********************************************************************
2929 * RtlImageRvaToSection (NTDLL.@)
2931 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2932 HMODULE module, DWORD rva )
2934 int i;
2935 const IMAGE_SECTION_HEADER *sec;
2937 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2938 nt->FileHeader.SizeOfOptionalHeader);
2939 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2941 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2942 return (PIMAGE_SECTION_HEADER)sec;
2944 return NULL;
2948 /***********************************************************************
2949 * RtlImageRvaToVa (NTDLL.@)
2951 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2952 DWORD rva, IMAGE_SECTION_HEADER **section )
2954 IMAGE_SECTION_HEADER *sec;
2956 if (section && *section) /* try this section first */
2958 sec = *section;
2959 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2960 goto found;
2962 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2963 found:
2964 if (section) *section = sec;
2965 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2969 /***********************************************************************
2970 * RtlPcToFileHeader (NTDLL.@)
2972 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2974 LDR_MODULE *module;
2975 PVOID ret = NULL;
2977 RtlEnterCriticalSection( &loader_section );
2978 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2979 RtlLeaveCriticalSection( &loader_section );
2980 *address = ret;
2981 return ret;
2985 /***********************************************************************
2986 * NtLoadDriver (NTDLL.@)
2987 * ZwLoadDriver (NTDLL.@)
2989 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2991 FIXME("(%p), stub!\n",DriverServiceName);
2992 return STATUS_NOT_IMPLEMENTED;
2996 /***********************************************************************
2997 * NtUnloadDriver (NTDLL.@)
2998 * ZwUnloadDriver (NTDLL.@)
3000 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3002 FIXME("(%p), stub!\n",DriverServiceName);
3003 return STATUS_NOT_IMPLEMENTED;
3007 /******************************************************************
3008 * DllMain (NTDLL.@)
3010 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3012 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3013 return TRUE;
3017 /******************************************************************
3018 * __wine_init_windows_dir (NTDLL.@)
3020 * Windows and system dir initialization once kernel32 has been loaded.
3022 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3024 PLIST_ENTRY mark, entry;
3025 LPWSTR buffer, p;
3027 strcpyW( user_shared_data->NtSystemRoot, windir );
3028 DIR_init_windows_dir( windir, sysdir );
3030 /* prepend the system dir to the name of the already created modules */
3031 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3032 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3034 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3036 assert( mod->Flags & LDR_WINE_INTERNAL );
3038 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3039 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3040 if (!buffer) continue;
3041 strcpyW( buffer, system_dir.Buffer );
3042 p = buffer + strlenW( buffer );
3043 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3044 strcpyW( p, mod->FullDllName.Buffer );
3045 RtlInitUnicodeString( &mod->FullDllName, buffer );
3046 RtlInitUnicodeString( &mod->BaseDllName, p );
3051 /***********************************************************************
3052 * __wine_process_init
3054 void __wine_process_init(void)
3056 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3058 WINE_MODREF *wm;
3059 NTSTATUS status;
3060 ANSI_STRING func_name;
3061 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3063 main_exe_file = thread_init();
3065 /* retrieve current umask */
3066 FILE_umask = umask(0777);
3067 umask( FILE_umask );
3069 load_global_options();
3071 /* setup the load callback and create ntdll modref */
3072 wine_dll_set_callback( load_builtin_callback );
3074 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3076 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3077 exit(1);
3079 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3080 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3082 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3083 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3084 0, (void **)&init_func )) != STATUS_SUCCESS)
3086 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3087 exit(1);
3089 init_func();