msvfw32: Simplify error handling in ICSeqCompressFrameStart.
[wine/multimedia.git] / dlls / ntdll / loader.c
blob831f04980ee0b8766a842739878c75d4cdedca0f
1 /*
2 * Loader functions
4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdarg.h>
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
29 #endif
31 #include "ntstatus.h"
32 #define WIN32_NO_STATUS
33 #define NONAMELESSUNION
34 #include "windef.h"
35 #include "winnt.h"
36 #include "winternl.h"
37 #include "delayloadhandler.h"
39 #include "wine/exception.h"
40 #include "wine/library.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
44 #include "ntdll_misc.h"
45 #include "ddk/wdm.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module);
48 WINE_DECLARE_DEBUG_CHANNEL(relay);
49 WINE_DECLARE_DEBUG_CHANNEL(snoop);
50 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
51 WINE_DECLARE_DEBUG_CHANNEL(imports);
52 WINE_DECLARE_DEBUG_CHANNEL(pid);
54 #ifdef _WIN64
55 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
56 #endif
57 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
58 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
60 /* we don't want to include winuser.h */
61 #define RT_MANIFEST ((ULONG_PTR)24)
62 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
64 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
66 static BOOL process_detaching = FALSE; /* set on process detach to avoid deadlocks with thread detach */
67 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
69 static const char * const reason_names[] =
71 "PROCESS_DETACH",
72 "PROCESS_ATTACH",
73 "THREAD_ATTACH",
74 "THREAD_DETACH",
75 NULL, NULL, NULL, NULL,
76 "WINE_PREATTACH"
79 static const WCHAR dllW[] = {'.','d','l','l',0};
81 /* internal representation of 32bit modules. per process. */
82 typedef struct _wine_modref
84 LDR_MODULE ldr;
85 int nDeps;
86 struct _wine_modref **deps;
87 } WINE_MODREF;
89 /* info about the current builtin dll load */
90 /* used to keep track of things across the register_dll constructor call */
91 struct builtin_load_info
93 const WCHAR *load_path;
94 const WCHAR *filename;
95 NTSTATUS status;
96 WINE_MODREF *wm;
99 static struct builtin_load_info default_load_info;
100 static struct builtin_load_info *builtin_load_info = &default_load_info;
102 static HANDLE main_exe_file;
103 static UINT tls_module_count; /* number of modules with TLS directory */
104 static IMAGE_TLS_DIRECTORY *tls_dirs; /* array of TLS directories */
105 LIST_ENTRY tls_links = { &tls_links, &tls_links };
107 static RTL_CRITICAL_SECTION loader_section;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
110 0, 0, &loader_section,
111 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
112 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
114 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
116 static WINE_MODREF *cached_modref;
117 static WINE_MODREF *current_modref;
118 static WINE_MODREF *last_failed_modref;
120 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
121 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
122 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
123 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
124 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
125 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
127 /* convert PE image VirtualAddress to Real Address */
128 static inline void *get_rva( HMODULE module, DWORD va )
130 return (void *)((char *)module + va);
133 /* check whether the file name contains a path */
134 static inline BOOL contains_path( LPCWSTR name )
136 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
139 /* convert from straight ASCII to Unicode without depending on the current codepage */
140 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
142 while (len--) *dst++ = (unsigned char)*src++;
146 /*************************************************************************
147 * call_dll_entry_point
149 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
150 * their entry point, so we need a small asm wrapper. Testing indicates
151 * that only modifying esi leads to a crash, so use this one to backup
152 * ebp while running the dll entry proc.
154 #ifdef __i386__
155 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
156 __ASM_GLOBAL_FUNC(call_dll_entry_point,
157 "pushl %ebp\n\t"
158 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
159 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
160 "movl %esp,%ebp\n\t"
161 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
162 "pushl %ebx\n\t"
163 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
164 "pushl %esi\n\t"
165 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
166 "pushl %edi\n\t"
167 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
168 "movl %ebp,%esi\n\t"
169 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
170 "pushl 20(%ebp)\n\t"
171 "pushl 16(%ebp)\n\t"
172 "pushl 12(%ebp)\n\t"
173 "movl 8(%ebp),%eax\n\t"
174 "call *%eax\n\t"
175 "movl %esi,%ebp\n\t"
176 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
177 "leal -12(%ebp),%esp\n\t"
178 "popl %edi\n\t"
179 __ASM_CFI(".cfi_same_value %edi\n\t")
180 "popl %esi\n\t"
181 __ASM_CFI(".cfi_same_value %esi\n\t")
182 "popl %ebx\n\t"
183 __ASM_CFI(".cfi_same_value %ebx\n\t")
184 "popl %ebp\n\t"
185 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
186 __ASM_CFI(".cfi_same_value %ebp\n\t")
187 "ret" )
188 #else /* __i386__ */
189 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
190 UINT reason, void *reserved )
192 return proc( module, reason, reserved );
194 #endif /* __i386__ */
197 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
198 /*************************************************************************
199 * stub_entry_point
201 * Entry point for stub functions.
203 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
205 EXCEPTION_RECORD rec;
207 rec.ExceptionCode = EXCEPTION_WINE_STUB;
208 rec.ExceptionFlags = EH_NONCONTINUABLE;
209 rec.ExceptionRecord = NULL;
210 rec.ExceptionAddress = ret_addr;
211 rec.NumberParameters = 2;
212 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
213 rec.ExceptionInformation[1] = (ULONG_PTR)name;
214 for (;;) RtlRaiseException( &rec );
218 #include "pshpack1.h"
219 #ifdef __i386__
220 struct stub
222 BYTE pushl1; /* pushl $name */
223 const char *name;
224 BYTE pushl2; /* pushl $dll */
225 const char *dll;
226 BYTE call; /* call stub_entry_point */
227 DWORD entry;
229 #elif defined(__arm__)
230 struct stub
232 BYTE ldr_r0[4]; /* ldr r0, $dll */
233 BYTE mov_pc_pc1[4]; /* mov pc,pc */
234 const char *dll;
235 BYTE ldr_r1[4]; /* ldr r1, $name */
236 BYTE mov_pc_pc2[4]; /* mov pc,pc */
237 const char *name;
238 BYTE mov_r2_lr[4]; /* mov r2, lr */
239 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #-4] */
240 const void* entry;
242 #else
243 struct stub
245 BYTE movq_rdi[2]; /* movq $dll,%rdi */
246 const char *dll;
247 BYTE movq_rsi[2]; /* movq $name,%rsi */
248 const char *name;
249 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
250 BYTE movq_rax[2]; /* movq $entry, %rax */
251 const void* entry;
252 BYTE jmpq_rax[2]; /* jmp %rax */
254 #endif
255 #include "poppack.h"
257 /*************************************************************************
258 * allocate_stub
260 * Allocate a stub entry point.
262 static ULONG_PTR allocate_stub( const char *dll, const char *name )
264 #define MAX_SIZE 65536
265 static struct stub *stubs;
266 static unsigned int nb_stubs;
267 struct stub *stub;
269 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
271 if (!stubs)
273 SIZE_T size = MAX_SIZE;
274 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
275 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
276 return 0xdeadbeef;
278 stub = &stubs[nb_stubs++];
279 #ifdef __i386__
280 stub->pushl1 = 0x68; /* pushl $name */
281 stub->name = name;
282 stub->pushl2 = 0x68; /* pushl $dll */
283 stub->dll = dll;
284 stub->call = 0xe8; /* call stub_entry_point */
285 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
286 #elif defined(__arm__)
287 stub->ldr_r0[0] = 0x00; /* ldr r0, $dll */
288 stub->ldr_r0[1] = 0x00;
289 stub->ldr_r0[2] = 0x9f;
290 stub->ldr_r0[3] = 0xe5;
291 stub->mov_pc_pc1[0] = 0x0f; /* mov pc,pc */
292 stub->mov_pc_pc1[1] = 0xf0;
293 stub->mov_pc_pc1[2] = 0xa0;
294 stub->mov_pc_pc1[3] = 0xe1;
295 stub->dll = dll;
296 stub->ldr_r1[0] = 0x00; /* ldr r1, $name */
297 stub->ldr_r1[1] = 0x10;
298 stub->ldr_r1[2] = 0x9f;
299 stub->ldr_r1[3] = 0xe5;
300 stub->mov_pc_pc2[0] = 0x0f; /* mov pc,pc */
301 stub->mov_pc_pc2[1] = 0xf0;
302 stub->mov_pc_pc2[2] = 0xa0;
303 stub->mov_pc_pc2[3] = 0xe1;
304 stub->name = name;
305 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
306 stub->mov_r2_lr[1] = 0x20;
307 stub->mov_r2_lr[2] = 0xa0;
308 stub->mov_r2_lr[3] = 0xe1;
309 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #-4] */
310 stub->ldr_pc_pc[1] = 0xf0;
311 stub->ldr_pc_pc[2] = 0x1f;
312 stub->ldr_pc_pc[3] = 0xe5;
313 stub->entry = stub_entry_point;
314 #else
315 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
316 stub->movq_rdi[1] = 0xbf;
317 stub->dll = dll;
318 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
319 stub->movq_rsi[1] = 0xbe;
320 stub->name = name;
321 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
322 stub->movq_rsp_rdx[1] = 0x8b;
323 stub->movq_rsp_rdx[2] = 0x14;
324 stub->movq_rsp_rdx[3] = 0x24;
325 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
326 stub->movq_rax[1] = 0xb8;
327 stub->entry = stub_entry_point;
328 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
329 stub->jmpq_rax[1] = 0xe0;
330 #endif
331 return (ULONG_PTR)stub;
334 #else /* __i386__ */
335 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
336 #endif /* __i386__ */
339 /*************************************************************************
340 * get_modref
342 * Looks for the referenced HMODULE in the current process
343 * The loader_section must be locked while calling this function.
345 static WINE_MODREF *get_modref( HMODULE hmod )
347 PLIST_ENTRY mark, entry;
348 PLDR_MODULE mod;
350 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
352 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
353 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
355 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
356 if (mod->BaseAddress == hmod)
357 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
358 if (mod->BaseAddress > (void*)hmod) break;
360 return NULL;
364 /**********************************************************************
365 * find_basename_module
367 * Find a module from its base name.
368 * The loader_section must be locked while calling this function
370 static WINE_MODREF *find_basename_module( LPCWSTR name )
372 PLIST_ENTRY mark, entry;
374 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
375 return cached_modref;
377 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
378 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
380 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
381 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
383 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
384 return cached_modref;
387 return NULL;
391 /**********************************************************************
392 * find_fullname_module
394 * Find a module from its full path name.
395 * The loader_section must be locked while calling this function
397 static WINE_MODREF *find_fullname_module( LPCWSTR name )
399 PLIST_ENTRY mark, entry;
401 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
402 return cached_modref;
404 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
405 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
407 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
408 if (!strcmpiW( name, mod->FullDllName.Buffer ))
410 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
411 return cached_modref;
414 return NULL;
418 /*************************************************************************
419 * find_forwarded_export
421 * Find the final function pointer for a forwarded function.
422 * The loader_section must be locked while calling this function.
424 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
426 const IMAGE_EXPORT_DIRECTORY *exports;
427 DWORD exp_size;
428 WINE_MODREF *wm;
429 WCHAR mod_name[32];
430 const char *end = strrchr(forward, '.');
431 FARPROC proc = NULL;
433 if (!end) return NULL;
434 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
435 ascii_to_unicode( mod_name, forward, end - forward );
436 mod_name[end - forward] = 0;
437 if (!strchrW( mod_name, '.' ))
439 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
440 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
443 if (!(wm = find_basename_module( mod_name )))
445 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
446 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
447 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
449 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
451 LdrUnloadDll( wm->ldr.BaseAddress );
452 wm = NULL;
456 if (!wm)
458 ERR( "module not found for forward '%s' used by %s\n",
459 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
460 return NULL;
463 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
464 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
466 const char *name = end + 1;
467 if (*name == '#') /* ordinal */
468 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
469 else
470 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
473 if (!proc)
475 ERR("function not found for forward '%s' used by %s."
476 " If you are using builtin %s, try using the native one instead.\n",
477 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
478 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
480 return proc;
484 /*************************************************************************
485 * find_ordinal_export
487 * Find an exported function by ordinal.
488 * The exports base must have been subtracted from the ordinal already.
489 * The loader_section must be locked while calling this function.
491 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
492 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
494 FARPROC proc;
495 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
497 if (ordinal >= exports->NumberOfFunctions)
499 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
500 return NULL;
502 if (!functions[ordinal]) return NULL;
504 proc = get_rva( module, functions[ordinal] );
506 /* if the address falls into the export dir, it's a forward */
507 if (((const char *)proc >= (const char *)exports) &&
508 ((const char *)proc < (const char *)exports + exp_size))
509 return find_forwarded_export( module, (const char *)proc, load_path );
511 if (TRACE_ON(snoop))
513 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
514 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
516 if (TRACE_ON(relay))
518 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
519 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
521 return proc;
525 /*************************************************************************
526 * find_named_export
528 * Find an exported function by name.
529 * The loader_section must be locked while calling this function.
531 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
532 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
534 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
535 const DWORD *names = get_rva( module, exports->AddressOfNames );
536 int min = 0, max = exports->NumberOfNames - 1;
538 /* first check the hint */
539 if (hint >= 0 && hint <= max)
541 char *ename = get_rva( module, names[hint] );
542 if (!strcmp( ename, name ))
543 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
546 /* then do a binary search */
547 while (min <= max)
549 int res, pos = (min + max) / 2;
550 char *ename = get_rva( module, names[pos] );
551 if (!(res = strcmp( ename, name )))
552 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
553 if (res > 0) max = pos - 1;
554 else min = pos + 1;
556 return NULL;
561 /*************************************************************************
562 * import_dll
564 * Import the dll specified by the given import descriptor.
565 * The loader_section must be locked while calling this function.
567 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
569 NTSTATUS status;
570 WINE_MODREF *wmImp;
571 HMODULE imp_mod;
572 const IMAGE_EXPORT_DIRECTORY *exports;
573 DWORD exp_size;
574 const IMAGE_THUNK_DATA *import_list;
575 IMAGE_THUNK_DATA *thunk_list;
576 WCHAR buffer[32];
577 const char *name = get_rva( module, descr->Name );
578 DWORD len = strlen(name);
579 PVOID protect_base;
580 SIZE_T protect_size = 0;
581 DWORD protect_old;
583 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
584 if (descr->u.OriginalFirstThunk)
585 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
586 else
587 import_list = thunk_list;
589 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
591 if (len * sizeof(WCHAR) < sizeof(buffer))
593 ascii_to_unicode( buffer, name, len );
594 buffer[len] = 0;
595 status = load_dll( load_path, buffer, 0, &wmImp );
597 else /* need to allocate a larger buffer */
599 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
600 if (!ptr) return NULL;
601 ascii_to_unicode( ptr, name, len );
602 ptr[len] = 0;
603 status = load_dll( load_path, ptr, 0, &wmImp );
604 RtlFreeHeap( GetProcessHeap(), 0, ptr );
607 if (status)
609 if (status == STATUS_DLL_NOT_FOUND)
610 ERR("Library %s (which is needed by %s) not found\n",
611 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
612 else
613 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
614 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
615 return NULL;
618 /* unprotect the import address table since it can be located in
619 * readonly section */
620 while (import_list[protect_size].u1.Ordinal) protect_size++;
621 protect_base = thunk_list;
622 protect_size *= sizeof(*thunk_list);
623 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
624 &protect_size, PAGE_READWRITE, &protect_old );
626 imp_mod = wmImp->ldr.BaseAddress;
627 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
629 if (!exports)
631 /* set all imported function to deadbeef */
632 while (import_list->u1.Ordinal)
634 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
636 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
637 WARN("No implementation for %s.%d", name, ordinal );
638 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
640 else
642 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
643 WARN("No implementation for %s.%s", name, pe_name->Name );
644 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
646 WARN(" imported from %s, allocating stub %p\n",
647 debugstr_w(current_modref->ldr.FullDllName.Buffer),
648 (void *)thunk_list->u1.Function );
649 import_list++;
650 thunk_list++;
652 goto done;
655 while (import_list->u1.Ordinal)
657 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
659 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
661 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
662 ordinal - exports->Base, load_path );
663 if (!thunk_list->u1.Function)
665 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
666 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
667 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
668 (void *)thunk_list->u1.Function );
670 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
672 else /* import by name */
674 IMAGE_IMPORT_BY_NAME *pe_name;
675 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
676 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
677 (const char*)pe_name->Name,
678 pe_name->Hint, load_path );
679 if (!thunk_list->u1.Function)
681 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
682 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
683 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
684 (void *)thunk_list->u1.Function );
686 TRACE_(imports)("--- %s %s.%d = %p\n",
687 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
689 import_list++;
690 thunk_list++;
693 done:
694 /* restore old protection of the import address table */
695 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, &protect_old );
696 return wmImp;
700 /***********************************************************************
701 * create_module_activation_context
703 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
705 NTSTATUS status;
706 LDR_RESOURCE_INFO info;
707 const IMAGE_RESOURCE_DATA_ENTRY *entry;
709 info.Type = RT_MANIFEST;
710 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
711 info.Language = 0;
712 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
714 ACTCTXW ctx;
715 ctx.cbSize = sizeof(ctx);
716 ctx.lpSource = NULL;
717 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
718 ctx.hModule = module->BaseAddress;
719 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
720 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
722 return status;
726 /*************************************************************************
727 * is_dll_native_subsystem
729 * Check if dll is a proper native driver.
730 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
731 * while being perfectly normal DLLs. This heuristic should catch such breakages.
733 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
735 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
736 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
737 const IMAGE_IMPORT_DESCRIPTOR *imports;
738 DWORD i, size;
739 WCHAR buffer[16];
741 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
742 if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
744 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
745 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
747 for (i = 0; imports[i].Name; i++)
749 const char *name = get_rva( module, imports[i].Name );
750 DWORD len = strlen(name);
751 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
752 ascii_to_unicode( buffer, name, len + 1 );
753 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
755 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
756 return FALSE;
760 return TRUE;
763 /*************************************************************************
764 * alloc_tls_slot
766 * Allocate a TLS slot for a newly-loaded module.
767 * The loader_section must be locked while calling this function.
769 static SHORT alloc_tls_slot( LDR_MODULE *mod )
771 const IMAGE_TLS_DIRECTORY *dir;
772 ULONG i, size;
773 void *new_ptr;
774 LIST_ENTRY *entry;
776 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &size )))
777 return -1;
779 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
780 if (!size && !dir->SizeOfZeroFill && !dir->AddressOfCallBacks) return -1;
782 for (i = 0; i < tls_module_count; i++)
784 if (!tls_dirs[i].StartAddressOfRawData && !tls_dirs[i].EndAddressOfRawData &&
785 !tls_dirs[i].SizeOfZeroFill && !tls_dirs[i].AddressOfCallBacks)
786 break;
789 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod->BaseAddress,
790 (void *)dir->StartAddressOfRawData, (void *)dir->EndAddressOfRawData, dir->SizeOfZeroFill,
791 (void *)dir->AddressOfIndex, (void *)dir->AddressOfCallBacks, dir->Characteristics, i );
793 if (i == tls_module_count)
795 UINT new_count = max( 32, tls_module_count * 2 );
797 if (!tls_dirs)
798 new_ptr = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*tls_dirs) );
799 else
800 new_ptr = RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, tls_dirs,
801 new_count * sizeof(*tls_dirs) );
802 if (!new_ptr) return -1;
804 /* resize the pointer block in all running threads */
805 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
807 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
808 void **old = teb->ThreadLocalStoragePointer;
809 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, new_count * sizeof(*new));
811 if (!new) return -1;
812 if (old) memcpy( new, old, tls_module_count * sizeof(*new) );
813 teb->ThreadLocalStoragePointer = new;
814 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR)teb->ClientId.UniqueThread, old, new );
815 /* FIXME: can't free old block here, should be freed at thread exit */
818 tls_dirs = new_ptr;
819 tls_module_count = new_count;
822 /* allocate the data block in all running threads */
823 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
825 TEB *teb = CONTAINING_RECORD( entry, TEB, TlsLinks );
827 if (!(new_ptr = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill ))) return -1;
828 memcpy( new_ptr, (void *)dir->StartAddressOfRawData, size );
829 memset( (char *)new_ptr + size, 0, dir->SizeOfZeroFill );
831 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
832 (ULONG_PTR)teb->ClientId.UniqueThread, i, size, dir->SizeOfZeroFill, new_ptr );
834 RtlFreeHeap( GetProcessHeap(), 0,
835 interlocked_xchg_ptr( (void **)teb->ThreadLocalStoragePointer + i, new_ptr ));
838 *(DWORD *)dir->AddressOfIndex = i;
839 tls_dirs[i] = *dir;
840 return i;
844 /*************************************************************************
845 * free_tls_slot
847 * Free the module TLS slot on unload.
848 * The loader_section must be locked while calling this function.
850 static void free_tls_slot( LDR_MODULE *mod )
852 ULONG i = (USHORT)mod->TlsIndex;
854 if (mod->TlsIndex == -1) return;
855 assert( i < tls_module_count );
856 memset( &tls_dirs[i], 0, sizeof(tls_dirs[i]) );
860 /****************************************************************
861 * fixup_imports
863 * Fixup all imports of a given module.
864 * The loader_section must be locked while calling this function.
866 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
868 int i, nb_imports;
869 const IMAGE_IMPORT_DESCRIPTOR *imports;
870 WINE_MODREF *prev;
871 DWORD size;
872 NTSTATUS status;
873 ULONG_PTR cookie;
875 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
876 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
878 wm->ldr.TlsIndex = alloc_tls_slot( &wm->ldr );
880 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
881 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
882 return STATUS_SUCCESS;
884 nb_imports = 0;
885 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
887 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
889 if (!create_module_activation_context( &wm->ldr ))
890 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
892 /* Allocate module dependency list */
893 wm->nDeps = nb_imports;
894 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
896 /* load the imported modules. They are automatically
897 * added to the modref list of the process.
899 prev = current_modref;
900 current_modref = wm;
901 status = STATUS_SUCCESS;
902 for (i = 0; i < nb_imports; i++)
904 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
905 status = STATUS_DLL_NOT_FOUND;
907 current_modref = prev;
908 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
909 return status;
913 /*************************************************************************
914 * alloc_module
916 * Allocate a WINE_MODREF structure and add it to the process list
917 * The loader_section must be locked while calling this function.
919 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
921 WINE_MODREF *wm;
922 const WCHAR *p;
923 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
924 PLIST_ENTRY entry, mark;
926 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
928 wm->nDeps = 0;
929 wm->deps = NULL;
931 wm->ldr.BaseAddress = hModule;
932 wm->ldr.EntryPoint = NULL;
933 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
934 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
935 wm->ldr.TlsIndex = -1;
936 wm->ldr.LoadCount = 1;
937 wm->ldr.SectionHandle = NULL;
938 wm->ldr.CheckSum = 0;
939 wm->ldr.TimeDateStamp = 0;
940 wm->ldr.ActivationContext = 0;
942 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
943 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
944 else p = wm->ldr.FullDllName.Buffer;
945 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
947 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) || !is_dll_native_subsystem( hModule, nt, p ))
949 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
950 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
951 if (nt->OptionalHeader.AddressOfEntryPoint)
952 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
955 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
956 &wm->ldr.InLoadOrderModuleList);
958 /* insert module in MemoryList, sorted in increasing base addresses */
959 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
960 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
962 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
963 break;
965 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
966 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
967 wm->ldr.InMemoryOrderModuleList.Flink = entry;
968 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
970 /* wait until init is called for inserting into this list */
971 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
972 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
974 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
976 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
977 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
978 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
980 return wm;
984 /*************************************************************************
985 * alloc_thread_tls
987 * Allocate the per-thread structure for module TLS storage.
989 static NTSTATUS alloc_thread_tls(void)
991 void **pointers;
992 UINT i, size;
994 if (!tls_module_count) return STATUS_SUCCESS;
996 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY,
997 tls_module_count * sizeof(*pointers) )))
998 return STATUS_NO_MEMORY;
1000 for (i = 0; i < tls_module_count; i++)
1002 const IMAGE_TLS_DIRECTORY *dir = &tls_dirs[i];
1004 if (!dir) continue;
1005 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
1006 if (!size && !dir->SizeOfZeroFill) continue;
1008 if (!(pointers[i] = RtlAllocateHeap( GetProcessHeap(), 0, size + dir->SizeOfZeroFill )))
1010 while (i) RtlFreeHeap( GetProcessHeap(), 0, pointers[--i] );
1011 RtlFreeHeap( GetProcessHeap(), 0, pointers );
1012 return STATUS_NO_MEMORY;
1014 memcpy( pointers[i], (void *)dir->StartAddressOfRawData, size );
1015 memset( (char *)pointers[i] + size, 0, dir->SizeOfZeroFill );
1017 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1018 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill, pointers[i] );
1020 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
1021 return STATUS_SUCCESS;
1025 /*************************************************************************
1026 * call_tls_callbacks
1028 static void call_tls_callbacks( HMODULE module, UINT reason )
1030 const IMAGE_TLS_DIRECTORY *dir;
1031 const PIMAGE_TLS_CALLBACK *callback;
1032 ULONG dirsize;
1034 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
1035 if (!dir || !dir->AddressOfCallBacks) return;
1037 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
1039 if (TRACE_ON(relay))
1041 if (TRACE_ON(pid))
1042 DPRINTF( "%04x:", GetCurrentProcessId() );
1043 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1044 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1046 __TRY
1048 call_dll_entry_point( (DLLENTRYPROC)*callback, module, reason, NULL );
1050 __EXCEPT_ALL
1052 if (TRACE_ON(relay))
1054 if (TRACE_ON(pid))
1055 DPRINTF( "%04x:", GetCurrentProcessId() );
1056 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1057 GetCurrentThreadId(), callback, module, reason_names[reason] );
1059 return;
1061 __ENDTRY
1062 if (TRACE_ON(relay))
1064 if (TRACE_ON(pid))
1065 DPRINTF( "%04x:", GetCurrentProcessId() );
1066 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1067 GetCurrentThreadId(), *callback, module, reason_names[reason] );
1073 /*************************************************************************
1074 * MODULE_InitDLL
1076 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
1078 WCHAR mod_name[32];
1079 NTSTATUS status = STATUS_SUCCESS;
1080 DLLENTRYPROC entry = wm->ldr.EntryPoint;
1081 void *module = wm->ldr.BaseAddress;
1082 BOOL retv = FALSE;
1084 /* Skip calls for modules loaded with special load flags */
1086 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1087 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1088 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return STATUS_SUCCESS;
1090 if (TRACE_ON(relay))
1092 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1093 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1094 mod_name[len / sizeof(WCHAR)] = 0;
1095 if (TRACE_ON(pid))
1096 DPRINTF( "%04x:", GetCurrentProcessId() );
1097 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1098 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1099 reason_names[reason], lpReserved );
1101 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1102 reason_names[reason], lpReserved );
1104 __TRY
1106 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1107 if (!retv)
1108 status = STATUS_DLL_INIT_FAILED;
1110 __EXCEPT_ALL
1112 if (TRACE_ON(relay))
1114 if (TRACE_ON(pid))
1115 DPRINTF( "%04x:", GetCurrentProcessId() );
1116 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1117 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1119 status = GetExceptionCode();
1121 __ENDTRY
1123 /* The state of the module list may have changed due to the call
1124 to the dll. We cannot assume that this module has not been
1125 deleted. */
1126 if (TRACE_ON(relay))
1128 if (TRACE_ON(pid))
1129 DPRINTF( "%04x:", GetCurrentProcessId() );
1130 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1131 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1132 reason_names[reason], lpReserved, retv );
1134 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1136 return status;
1140 /*************************************************************************
1141 * process_attach
1143 * Send the process attach notification to all DLLs the given module
1144 * depends on (recursively). This is somewhat complicated due to the fact that
1146 * - we have to respect the module dependencies, i.e. modules implicitly
1147 * referenced by another module have to be initialized before the module
1148 * itself can be initialized
1150 * - the initialization routine of a DLL can itself call LoadLibrary,
1151 * thereby introducing a whole new set of dependencies (even involving
1152 * the 'old' modules) at any time during the whole process
1154 * (Note that this routine can be recursively entered not only directly
1155 * from itself, but also via LoadLibrary from one of the called initialization
1156 * routines.)
1158 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1159 * the process *detach* notifications to be sent in the correct order.
1160 * This must not only take into account module dependencies, but also
1161 * 'hidden' dependencies created by modules calling LoadLibrary in their
1162 * attach notification routine.
1164 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1165 * list after the attach notification has returned. This implies that the
1166 * detach notifications are called in the reverse of the sequence the attach
1167 * notifications *returned*.
1169 * The loader_section must be locked while calling this function.
1171 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1173 NTSTATUS status = STATUS_SUCCESS;
1174 ULONG_PTR cookie;
1175 int i;
1177 if (process_detaching) return status;
1179 /* prevent infinite recursion in case of cyclical dependencies */
1180 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1181 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1182 return status;
1184 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1186 /* Tag current MODREF to prevent recursive loop */
1187 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1188 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1189 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1191 /* Recursively attach all DLLs this one depends on */
1192 for ( i = 0; i < wm->nDeps; i++ )
1194 if (!wm->deps[i]) continue;
1195 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1198 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1199 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1200 &wm->ldr.InInitializationOrderModuleList);
1202 /* Call DLL entry point */
1203 if (status == STATUS_SUCCESS)
1205 WINE_MODREF *prev = current_modref;
1206 current_modref = wm;
1207 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1208 if (status == STATUS_SUCCESS)
1209 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1210 else
1212 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1213 /* point to the name so LdrInitializeThunk can print it */
1214 last_failed_modref = wm;
1215 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1217 current_modref = prev;
1220 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1221 /* Remove recursion flag */
1222 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1224 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1225 return status;
1229 /**********************************************************************
1230 * attach_implicitly_loaded_dlls
1232 * Attach to the (builtin) dlls that have been implicitly loaded because
1233 * of a dependency at the Unix level, but not imported at the Win32 level.
1235 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1237 for (;;)
1239 PLIST_ENTRY mark, entry;
1241 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1242 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1244 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1246 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1247 TRACE( "found implicitly loaded %s, attaching to it\n",
1248 debugstr_w(mod->BaseDllName.Buffer));
1249 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1250 break; /* restart the search from the start */
1252 if (entry == mark) break; /* nothing found */
1257 /*************************************************************************
1258 * process_detach
1260 * Send DLL process detach notifications. See the comment about calling
1261 * sequence at process_attach.
1263 static void process_detach(void)
1265 PLIST_ENTRY mark, entry;
1266 PLDR_MODULE mod;
1268 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1271 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1273 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1274 InInitializationOrderModuleList);
1275 /* Check whether to detach this DLL */
1276 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1277 continue;
1278 if ( mod->LoadCount && !process_detaching )
1279 continue;
1281 /* Call detach notification */
1282 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1283 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1284 DLL_PROCESS_DETACH, ULongToPtr(process_detaching) );
1286 /* Restart at head of WINE_MODREF list, as entries might have
1287 been added and/or removed while performing the call ... */
1288 break;
1290 } while (entry != mark);
1293 /*************************************************************************
1294 * MODULE_DllThreadAttach
1296 * Send DLL thread attach notifications. These are sent in the
1297 * reverse sequence of process detach notification.
1300 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1302 PLIST_ENTRY mark, entry;
1303 PLDR_MODULE mod;
1304 NTSTATUS status;
1306 /* don't do any attach calls if process is exiting */
1307 if (process_detaching) return STATUS_SUCCESS;
1309 RtlEnterCriticalSection( &loader_section );
1311 RtlAcquirePebLock();
1312 InsertHeadList( &tls_links, &NtCurrentTeb()->TlsLinks );
1313 RtlReleasePebLock();
1315 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1317 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1318 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1320 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1321 InInitializationOrderModuleList);
1322 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1323 continue;
1324 if ( mod->Flags & LDR_NO_DLL_CALLS )
1325 continue;
1327 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1328 DLL_THREAD_ATTACH, lpReserved );
1331 done:
1332 RtlLeaveCriticalSection( &loader_section );
1333 return status;
1336 /******************************************************************
1337 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1340 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1342 WINE_MODREF *wm;
1343 NTSTATUS ret = STATUS_SUCCESS;
1345 RtlEnterCriticalSection( &loader_section );
1347 wm = get_modref( hModule );
1348 if (!wm || wm->ldr.TlsIndex != -1)
1349 ret = STATUS_DLL_NOT_FOUND;
1350 else
1351 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1353 RtlLeaveCriticalSection( &loader_section );
1355 return ret;
1358 /******************************************************************
1359 * LdrFindEntryForAddress (NTDLL.@)
1361 * The loader_section must be locked while calling this function
1363 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1365 PLIST_ENTRY mark, entry;
1366 PLDR_MODULE mod;
1368 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1369 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1371 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1372 if (mod->BaseAddress <= addr &&
1373 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1375 *pmod = mod;
1376 return STATUS_SUCCESS;
1378 if (mod->BaseAddress > addr) break;
1380 return STATUS_NO_MORE_ENTRIES;
1383 /******************************************************************
1384 * LdrLockLoaderLock (NTDLL.@)
1386 * Note: some flags are not implemented.
1387 * Flag 0x01 is used to raise exceptions on errors.
1389 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG_PTR *magic )
1391 if (flags & ~0x2) FIXME( "flags %x not supported\n", flags );
1393 if (result) *result = 0;
1394 if (magic) *magic = 0;
1395 if (flags & ~0x3) return STATUS_INVALID_PARAMETER_1;
1396 if (!result && (flags & 0x2)) return STATUS_INVALID_PARAMETER_2;
1397 if (!magic) return STATUS_INVALID_PARAMETER_3;
1399 if (flags & 0x2)
1401 if (!RtlTryEnterCriticalSection( &loader_section ))
1403 *result = 2;
1404 return STATUS_SUCCESS;
1406 *result = 1;
1408 else
1410 RtlEnterCriticalSection( &loader_section );
1411 if (result) *result = 1;
1413 *magic = GetCurrentThreadId();
1414 return STATUS_SUCCESS;
1418 /******************************************************************
1419 * LdrUnlockLoaderUnlock (NTDLL.@)
1421 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG_PTR magic )
1423 if (magic)
1425 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1426 RtlLeaveCriticalSection( &loader_section );
1428 return STATUS_SUCCESS;
1432 /******************************************************************
1433 * LdrGetProcedureAddress (NTDLL.@)
1435 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1436 ULONG ord, PVOID *address)
1438 IMAGE_EXPORT_DIRECTORY *exports;
1439 DWORD exp_size;
1440 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1442 RtlEnterCriticalSection( &loader_section );
1444 /* check if the module itself is invalid to return the proper error */
1445 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1446 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1447 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1449 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1450 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1451 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1452 if (proc)
1454 *address = proc;
1455 ret = STATUS_SUCCESS;
1459 RtlLeaveCriticalSection( &loader_section );
1460 return ret;
1464 /***********************************************************************
1465 * is_fake_dll
1467 * Check if a loaded native dll is a Wine fake dll.
1469 static BOOL is_fake_dll( HANDLE handle )
1471 static const char fakedll_signature[] = "Wine placeholder DLL";
1472 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1473 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1474 IO_STATUS_BLOCK io;
1475 LARGE_INTEGER offset;
1477 offset.QuadPart = 0;
1478 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1479 if (io.Information < sizeof(buffer)) return FALSE;
1480 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1481 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1482 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1483 return FALSE;
1487 /***********************************************************************
1488 * get_builtin_fullname
1490 * Build the full pathname for a builtin dll.
1492 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1494 static const WCHAR soW[] = {'.','s','o',0};
1495 WCHAR *p, *fullname;
1496 size_t i, len = strlen(filename);
1498 /* check if path can correspond to the dll we have */
1499 if (path && (p = strrchrW( path, '\\' )))
1501 p++;
1502 for (i = 0; i < len; i++)
1503 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1504 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1506 /* the filename matches, use path as the full path */
1507 len += p - path;
1508 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1510 memcpy( fullname, path, len * sizeof(WCHAR) );
1511 fullname[len] = 0;
1513 return fullname;
1517 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1518 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1520 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1521 p = fullname + system_dir.Length / sizeof(WCHAR);
1522 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1523 ascii_to_unicode( p, filename, len + 1 );
1525 return fullname;
1529 /*************************************************************************
1530 * is_16bit_builtin
1532 static BOOL is_16bit_builtin( HMODULE module )
1534 const IMAGE_EXPORT_DIRECTORY *exports;
1535 DWORD exp_size;
1537 if (!(exports = RtlImageDirectoryEntryToData( module, TRUE,
1538 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1539 return FALSE;
1541 return find_named_export( module, exports, exp_size, "__wine_spec_dos_header", -1, NULL ) != NULL;
1545 /***********************************************************************
1546 * load_builtin_callback
1548 * Load a library in memory; callback function for wine_dll_register
1550 static void load_builtin_callback( void *module, const char *filename )
1552 static const WCHAR emptyW[1];
1553 IMAGE_NT_HEADERS *nt;
1554 WINE_MODREF *wm;
1555 WCHAR *fullname;
1556 const WCHAR *load_path;
1558 if (!module)
1560 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1561 return;
1563 if (!(nt = RtlImageNtHeader( module )))
1565 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1566 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1567 return;
1570 virtual_create_builtin_view( module );
1572 /* create the MODREF */
1574 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1576 ERR( "can't load %s\n", filename );
1577 builtin_load_info->status = STATUS_NO_MEMORY;
1578 return;
1581 wm = alloc_module( module, fullname );
1582 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1583 if (!wm)
1585 ERR( "can't load %s\n", filename );
1586 builtin_load_info->status = STATUS_NO_MEMORY;
1587 return;
1589 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1591 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1592 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE ||
1593 is_16bit_builtin( module ))
1595 /* fixup imports */
1597 load_path = builtin_load_info->load_path;
1598 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1599 if (!load_path) load_path = emptyW;
1600 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1602 /* the module has only be inserted in the load & memory order lists */
1603 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1604 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1605 /* FIXME: free the modref */
1606 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1607 return;
1611 builtin_load_info->wm = wm;
1612 TRACE( "loaded %s %p %p\n", filename, wm, module );
1614 /* send the DLL load event */
1616 SERVER_START_REQ( load_dll )
1618 req->mapping = 0;
1619 req->base = wine_server_client_ptr( module );
1620 req->size = nt->OptionalHeader.SizeOfImage;
1621 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1622 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1623 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1624 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1625 wine_server_call( req );
1627 SERVER_END_REQ;
1629 /* setup relay debugging entry points */
1630 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1634 /***********************************************************************
1635 * set_security_cookie
1637 * Create a random security cookie for buffer overflow protection. Make
1638 * sure it does not accidentally match the default cookie value.
1640 static void set_security_cookie( void *module, SIZE_T len )
1642 static ULONG seed;
1643 IMAGE_LOAD_CONFIG_DIRECTORY *loadcfg;
1644 ULONG loadcfg_size;
1645 ULONG_PTR *cookie;
1647 loadcfg = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &loadcfg_size );
1648 if (!loadcfg) return;
1649 if (loadcfg_size < offsetof(IMAGE_LOAD_CONFIG_DIRECTORY, SecurityCookie) + sizeof(loadcfg->SecurityCookie)) return;
1650 if (!loadcfg->SecurityCookie) return;
1651 if (loadcfg->SecurityCookie < (ULONG_PTR)module ||
1652 loadcfg->SecurityCookie > (ULONG_PTR)module + len - sizeof(ULONG_PTR))
1654 WARN( "security cookie %p outside of image %p-%p\n",
1655 (void *)loadcfg->SecurityCookie, module, (char *)module + len );
1656 return;
1659 cookie = (ULONG_PTR *)loadcfg->SecurityCookie;
1660 TRACE( "initializing security cookie %p\n", cookie );
1662 if (!seed) seed = NtGetTickCount() ^ GetCurrentProcessId();
1663 for (;;)
1665 if (*cookie == DEFAULT_SECURITY_COOKIE_16)
1666 *cookie = RtlRandom( &seed ) >> 16; /* leave the high word clear */
1667 else if (*cookie == DEFAULT_SECURITY_COOKIE_32)
1668 *cookie = RtlRandom( &seed );
1669 #ifdef DEFAULT_SECURITY_COOKIE_64
1670 else if (*cookie == DEFAULT_SECURITY_COOKIE_64)
1672 *cookie = RtlRandom( &seed );
1673 /* fill up, but keep the highest word clear */
1674 *cookie ^= (ULONG_PTR)RtlRandom( &seed ) << 16;
1676 #endif
1677 else
1678 break;
1682 static NTSTATUS perform_relocations( void *module, SIZE_T len )
1684 IMAGE_NT_HEADERS *nt;
1685 char *base;
1686 IMAGE_BASE_RELOCATION *rel, *end;
1687 const IMAGE_DATA_DIRECTORY *relocs;
1688 const IMAGE_SECTION_HEADER *sec;
1689 INT_PTR delta;
1690 ULONG protect_old[96], i;
1692 nt = RtlImageNtHeader( module );
1693 base = (char *)nt->OptionalHeader.ImageBase;
1695 assert( module != base );
1697 /* no relocations are performed on non page-aligned binaries */
1698 if (nt->OptionalHeader.SectionAlignment < page_size)
1699 return STATUS_SUCCESS;
1701 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && NtCurrentTeb()->Peb->ImageBaseAddress)
1702 return STATUS_SUCCESS;
1704 relocs = &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
1706 if (nt->FileHeader.Characteristics & IMAGE_FILE_RELOCS_STRIPPED)
1708 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1709 base, module );
1710 return STATUS_CONFLICTING_ADDRESSES;
1713 if (!relocs->Size) return STATUS_SUCCESS;
1714 if (!relocs->VirtualAddress) return STATUS_CONFLICTING_ADDRESSES;
1716 if (nt->FileHeader.NumberOfSections > sizeof(protect_old)/sizeof(protect_old[0]))
1717 return STATUS_INVALID_IMAGE_FORMAT;
1719 sec = (const IMAGE_SECTION_HEADER *)((const char *)&nt->OptionalHeader +
1720 nt->FileHeader.SizeOfOptionalHeader);
1721 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1723 void *addr = get_rva( module, sec[i].VirtualAddress );
1724 SIZE_T size = sec[i].SizeOfRawData;
1725 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1726 &size, PAGE_READWRITE, &protect_old[i] );
1729 TRACE( "relocating from %p-%p to %p-%p\n",
1730 base, base + len, module, (char *)module + len );
1732 rel = get_rva( module, relocs->VirtualAddress );
1733 end = get_rva( module, relocs->VirtualAddress + relocs->Size );
1734 delta = (char *)module - base;
1736 while (rel < end - 1 && rel->SizeOfBlock)
1738 if (rel->VirtualAddress >= len)
1740 WARN( "invalid address %p in relocation %p\n", get_rva( module, rel->VirtualAddress ), rel );
1741 return STATUS_ACCESS_VIOLATION;
1743 rel = LdrProcessRelocationBlock( get_rva( module, rel->VirtualAddress ),
1744 (rel->SizeOfBlock - sizeof(*rel)) / sizeof(USHORT),
1745 (USHORT *)(rel + 1), delta );
1746 if (!rel) return STATUS_INVALID_IMAGE_FORMAT;
1749 for (i = 0; i < nt->FileHeader.NumberOfSections; i++)
1751 void *addr = get_rva( module, sec[i].VirtualAddress );
1752 SIZE_T size = sec[i].SizeOfRawData;
1753 NtProtectVirtualMemory( NtCurrentProcess(), &addr,
1754 &size, protect_old[i], &protect_old[i] );
1757 return STATUS_SUCCESS;
1760 /******************************************************************************
1761 * load_native_dll (internal)
1763 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1764 DWORD flags, WINE_MODREF** pwm )
1766 void *module;
1767 HANDLE mapping;
1768 LARGE_INTEGER size;
1769 IMAGE_NT_HEADERS *nt;
1770 SIZE_T len = 0;
1771 WINE_MODREF *wm;
1772 NTSTATUS status;
1774 TRACE("Trying native dll %s\n", debugstr_w(name));
1776 size.QuadPart = 0;
1777 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1778 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1779 if (status != STATUS_SUCCESS) return status;
1781 module = NULL;
1782 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1783 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1785 /* perform base relocation, if necessary */
1787 if (status == STATUS_IMAGE_NOT_AT_BASE)
1788 status = perform_relocations( module, len );
1790 if (status != STATUS_SUCCESS)
1792 if (module) NtUnmapViewOfSection( NtCurrentProcess(), module );
1793 goto done;
1796 /* create the MODREF */
1798 if (!(wm = alloc_module( module, name )))
1800 status = STATUS_NO_MEMORY;
1801 goto done;
1804 set_security_cookie( module, len );
1806 /* fixup imports */
1808 nt = RtlImageNtHeader( module );
1810 if (!(flags & DONT_RESOLVE_DLL_REFERENCES) &&
1811 ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) ||
1812 nt->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_NATIVE))
1814 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1816 /* the module has only be inserted in the load & memory order lists */
1817 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1818 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1820 /* FIXME: there are several more dangling references
1821 * left. Including dlls loaded by this dll before the
1822 * failed one. Unrolling is rather difficult with the
1823 * current structure and we can leave them lying
1824 * around with no problems, so we don't care.
1825 * As these might reference our wm, we don't free it.
1827 goto done;
1831 /* send DLL load event */
1833 SERVER_START_REQ( load_dll )
1835 req->mapping = wine_server_obj_handle( mapping );
1836 req->base = wine_server_client_ptr( module );
1837 req->size = nt->OptionalHeader.SizeOfImage;
1838 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1839 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1840 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1841 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1842 wine_server_call( req );
1844 SERVER_END_REQ;
1846 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1848 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1850 wm->ldr.LoadCount = 1;
1851 *pwm = wm;
1852 status = STATUS_SUCCESS;
1853 done:
1854 NtClose( mapping );
1855 return status;
1859 /***********************************************************************
1860 * load_builtin_dll
1862 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1863 DWORD flags, WINE_MODREF** pwm )
1865 char error[256], dllname[MAX_PATH];
1866 const WCHAR *name, *p;
1867 DWORD len, i;
1868 void *handle = NULL;
1869 struct builtin_load_info info, *prev_info;
1871 /* Fix the name in case we have a full path and extension */
1872 name = path;
1873 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1874 if ((p = strrchrW( name, '/' ))) name = p + 1;
1876 /* load_library will modify info.status. Note also that load_library can be
1877 * called several times, if the .so file we're loading has dependencies.
1878 * info.status will gather all the errors we may get while loading all these
1879 * libraries
1881 info.load_path = load_path;
1882 info.filename = NULL;
1883 info.status = STATUS_SUCCESS;
1884 info.wm = NULL;
1886 if (file) /* we have a real file, try to load it */
1888 UNICODE_STRING nt_name;
1889 ANSI_STRING unix_name;
1891 TRACE("Trying built-in %s\n", debugstr_w(path));
1893 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1894 return STATUS_DLL_NOT_FOUND;
1896 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1898 RtlFreeUnicodeString( &nt_name );
1899 return STATUS_DLL_NOT_FOUND;
1901 prev_info = builtin_load_info;
1902 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1903 builtin_load_info = &info;
1904 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1905 builtin_load_info = prev_info;
1906 RtlFreeUnicodeString( &nt_name );
1907 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1908 if (!handle)
1910 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1911 return STATUS_INVALID_IMAGE_FORMAT;
1914 else
1916 int file_exists;
1918 TRACE("Trying built-in %s\n", debugstr_w(name));
1920 /* we don't want to depend on the current codepage here */
1921 len = strlenW( name ) + 1;
1922 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1923 for (i = 0; i < len; i++)
1925 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1926 dllname[i] = (char)name[i];
1927 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1930 prev_info = builtin_load_info;
1931 builtin_load_info = &info;
1932 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1933 builtin_load_info = prev_info;
1934 if (!handle)
1936 if (!file_exists)
1938 /* The file does not exist -> WARN() */
1939 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1940 return STATUS_DLL_NOT_FOUND;
1942 /* ERR() for all other errors (missing functions, ...) */
1943 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1944 return STATUS_PROCEDURE_NOT_FOUND;
1948 if (info.status != STATUS_SUCCESS)
1950 wine_dll_unload( handle );
1951 return info.status;
1954 if (!info.wm)
1956 PLIST_ENTRY mark, entry;
1958 /* The constructor wasn't called, this means the .so is already
1959 * loaded under a different name. Try to find the wm for it. */
1961 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1962 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1964 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1965 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1967 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1968 TRACE( "Found %s at %p for builtin %s\n",
1969 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1970 break;
1973 wine_dll_unload( handle ); /* release the libdl refcount */
1974 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1975 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1977 else
1979 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1980 info.wm->ldr.LoadCount = 1;
1981 info.wm->ldr.SectionHandle = handle;
1984 *pwm = info.wm;
1985 return STATUS_SUCCESS;
1989 /***********************************************************************
1990 * find_actctx_dll
1992 * Find the full path (if any) of the dll from the activation context.
1994 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1996 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1997 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1999 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
2000 ACTCTX_SECTION_KEYED_DATA data;
2001 UNICODE_STRING nameW;
2002 NTSTATUS status;
2003 SIZE_T needed, size = 1024;
2004 WCHAR *p;
2006 RtlInitUnicodeString( &nameW, libname );
2007 data.cbSize = sizeof(data);
2008 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
2009 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
2010 &nameW, &data );
2011 if (status != STATUS_SUCCESS) return status;
2013 for (;;)
2015 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2017 status = STATUS_NO_MEMORY;
2018 goto done;
2020 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
2021 AssemblyDetailedInformationInActivationContext,
2022 info, size, &needed );
2023 if (status == STATUS_SUCCESS) break;
2024 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
2025 RtlFreeHeap( GetProcessHeap(), 0, info );
2026 size = needed;
2027 /* restart with larger buffer */
2030 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
2032 status = STATUS_SXS_KEY_NOT_FOUND;
2033 goto done;
2036 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
2038 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2040 p++;
2041 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
2043 /* manifest name does not match directory name, so it's not a global
2044 * windows/winsxs manifest; use the manifest directory name instead */
2045 dirlen = p - info->lpAssemblyManifestPath;
2046 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
2047 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2049 status = STATUS_NO_MEMORY;
2050 goto done;
2052 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
2053 p += dirlen;
2054 strcpyW( p, libname );
2055 goto done;
2059 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
2060 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
2062 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
2064 status = STATUS_NO_MEMORY;
2065 goto done;
2067 strcpyW( p, user_shared_data->NtSystemRoot );
2068 p += strlenW(p);
2069 memcpy( p, winsxsW, sizeof(winsxsW) );
2070 p += sizeof(winsxsW) / sizeof(WCHAR);
2071 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
2072 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
2073 *p++ = '\\';
2074 strcpyW( p, libname );
2075 done:
2076 RtlFreeHeap( GetProcessHeap(), 0, info );
2077 RtlReleaseActivationContext( data.hActCtx );
2078 return status;
2082 /***********************************************************************
2083 * find_dll_file
2085 * Find the file (or already loaded module) for a given dll name.
2087 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
2088 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
2090 OBJECT_ATTRIBUTES attr;
2091 IO_STATUS_BLOCK io;
2092 UNICODE_STRING nt_name;
2093 WCHAR *file_part, *ext, *dllname;
2094 ULONG len;
2096 /* first append .dll if needed */
2098 dllname = NULL;
2099 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
2101 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
2102 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
2103 return STATUS_NO_MEMORY;
2104 strcpyW( dllname, libname );
2105 strcatW( dllname, dllW );
2106 libname = dllname;
2109 nt_name.Buffer = NULL;
2111 if (!contains_path( libname ))
2113 NTSTATUS status;
2114 WCHAR *fullname = NULL;
2116 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
2118 status = find_actctx_dll( libname, &fullname );
2119 if (status == STATUS_SUCCESS)
2121 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
2122 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2123 libname = dllname = fullname;
2125 else if (status != STATUS_SXS_KEY_NOT_FOUND)
2127 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2128 return status;
2132 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
2134 /* we need to search for it */
2135 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
2136 if (len)
2138 if (len >= *size) goto overflow;
2139 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
2141 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
2143 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2144 return STATUS_NO_MEMORY;
2146 attr.Length = sizeof(attr);
2147 attr.RootDirectory = 0;
2148 attr.Attributes = OBJ_CASE_INSENSITIVE;
2149 attr.ObjectName = &nt_name;
2150 attr.SecurityDescriptor = NULL;
2151 attr.SecurityQualityOfService = NULL;
2152 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2153 goto found;
2156 /* not found */
2158 if (!contains_path( libname ))
2160 /* if libname doesn't contain a path at all, we simply return the name as is,
2161 * to be loaded as builtin */
2162 len = strlenW(libname) * sizeof(WCHAR);
2163 if (len >= *size) goto overflow;
2164 strcpyW( filename, libname );
2165 goto found;
2169 /* absolute path name, or relative path name but not found above */
2171 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
2173 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2174 return STATUS_NO_MEMORY;
2176 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
2177 if (len >= *size) goto overflow;
2178 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
2179 if (!(*pwm = find_fullname_module( filename )) && handle)
2181 attr.Length = sizeof(attr);
2182 attr.RootDirectory = 0;
2183 attr.Attributes = OBJ_CASE_INSENSITIVE;
2184 attr.ObjectName = &nt_name;
2185 attr.SecurityDescriptor = NULL;
2186 attr.SecurityQualityOfService = NULL;
2187 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE )) *handle = 0;
2189 found:
2190 RtlFreeUnicodeString( &nt_name );
2191 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2192 return STATUS_SUCCESS;
2194 overflow:
2195 RtlFreeUnicodeString( &nt_name );
2196 RtlFreeHeap( GetProcessHeap(), 0, dllname );
2197 *size = len + sizeof(WCHAR);
2198 return STATUS_BUFFER_TOO_SMALL;
2202 /***********************************************************************
2203 * load_dll (internal)
2205 * Load a PE style module according to the load order.
2206 * The loader_section must be locked while calling this function.
2208 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
2210 enum loadorder loadorder;
2211 WCHAR buffer[32];
2212 WCHAR *filename;
2213 ULONG size;
2214 WINE_MODREF *main_exe;
2215 HANDLE handle = 0;
2216 NTSTATUS nts;
2218 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
2220 *pwm = NULL;
2221 filename = buffer;
2222 size = sizeof(buffer);
2223 for (;;)
2225 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
2226 if (nts == STATUS_SUCCESS) break;
2227 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2228 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
2229 /* grow the buffer and retry */
2230 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2233 if (*pwm) /* found already loaded module */
2235 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
2237 TRACE("Found %s for %s at %p, count=%d\n",
2238 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
2239 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
2240 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2241 return STATUS_SUCCESS;
2244 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
2245 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
2247 if (handle && is_fake_dll( handle ))
2249 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
2250 NtClose( handle );
2251 handle = 0;
2254 switch(loadorder)
2256 case LO_INVALID:
2257 nts = STATUS_NO_MEMORY;
2258 break;
2259 case LO_DISABLED:
2260 nts = STATUS_DLL_NOT_FOUND;
2261 break;
2262 case LO_NATIVE:
2263 case LO_NATIVE_BUILTIN:
2264 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2265 else
2267 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2268 if (nts == STATUS_INVALID_IMAGE_NOT_MZ)
2269 /* not in PE format, maybe it's a builtin */
2270 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2272 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2273 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2274 break;
2275 case LO_BUILTIN:
2276 case LO_BUILTIN_NATIVE:
2277 case LO_DEFAULT: /* default is builtin,native */
2278 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2279 if (!handle) break; /* nothing else we can try */
2280 /* file is not a builtin library, try without using the specified file */
2281 if (nts != STATUS_SUCCESS)
2282 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2283 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2284 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2286 /* stub-only dll, try native */
2287 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2288 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2289 nts = STATUS_DLL_NOT_FOUND;
2291 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2292 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2293 break;
2296 if (nts == STATUS_SUCCESS)
2298 /* Initialize DLL just loaded */
2299 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2300 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2301 (*pwm)->ldr.BaseAddress);
2302 if (handle) NtClose( handle );
2303 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2304 return nts;
2307 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2308 if (handle) NtClose( handle );
2309 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2310 return nts;
2313 /******************************************************************
2314 * LdrLoadDll (NTDLL.@)
2316 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2317 const UNICODE_STRING *libname, HMODULE* hModule)
2319 WINE_MODREF *wm;
2320 NTSTATUS nts;
2322 RtlEnterCriticalSection( &loader_section );
2324 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2325 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2327 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2329 nts = process_attach( wm, NULL );
2330 if (nts != STATUS_SUCCESS)
2332 LdrUnloadDll(wm->ldr.BaseAddress);
2333 wm = NULL;
2336 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2338 RtlLeaveCriticalSection( &loader_section );
2339 return nts;
2343 /******************************************************************
2344 * LdrGetDllHandle (NTDLL.@)
2346 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2348 NTSTATUS status;
2349 WCHAR buffer[128];
2350 WCHAR *filename;
2351 ULONG size;
2352 WINE_MODREF *wm;
2354 RtlEnterCriticalSection( &loader_section );
2356 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2358 filename = buffer;
2359 size = sizeof(buffer);
2360 for (;;)
2362 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2363 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2364 if (status != STATUS_BUFFER_TOO_SMALL) break;
2365 /* grow the buffer and retry */
2366 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2368 status = STATUS_NO_MEMORY;
2369 break;
2373 if (status == STATUS_SUCCESS)
2375 if (wm) *base = wm->ldr.BaseAddress;
2376 else status = STATUS_DLL_NOT_FOUND;
2379 RtlLeaveCriticalSection( &loader_section );
2380 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2381 return status;
2385 /******************************************************************
2386 * LdrAddRefDll (NTDLL.@)
2388 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2390 NTSTATUS ret = STATUS_SUCCESS;
2391 WINE_MODREF *wm;
2393 if (flags & ~LDR_ADDREF_DLL_PIN) FIXME( "%p flags %x not implemented\n", module, flags );
2395 RtlEnterCriticalSection( &loader_section );
2397 if ((wm = get_modref( module )))
2399 if (flags & LDR_ADDREF_DLL_PIN)
2400 wm->ldr.LoadCount = -1;
2401 else
2402 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2403 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2405 else ret = STATUS_INVALID_PARAMETER;
2407 RtlLeaveCriticalSection( &loader_section );
2408 return ret;
2412 /***********************************************************************
2413 * LdrProcessRelocationBlock (NTDLL.@)
2415 * Apply relocations to a given page of a mapped PE image.
2417 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2418 USHORT *relocs, INT_PTR delta )
2420 while (count--)
2422 USHORT offset = *relocs & 0xfff;
2423 int type = *relocs >> 12;
2424 switch(type)
2426 case IMAGE_REL_BASED_ABSOLUTE:
2427 break;
2428 case IMAGE_REL_BASED_HIGH:
2429 *(short *)((char *)page + offset) += HIWORD(delta);
2430 break;
2431 case IMAGE_REL_BASED_LOW:
2432 *(short *)((char *)page + offset) += LOWORD(delta);
2433 break;
2434 case IMAGE_REL_BASED_HIGHLOW:
2435 *(int *)((char *)page + offset) += delta;
2436 break;
2437 #ifdef __x86_64__
2438 case IMAGE_REL_BASED_DIR64:
2439 *(INT_PTR *)((char *)page + offset) += delta;
2440 break;
2441 #elif defined(__arm__)
2442 case IMAGE_REL_BASED_THUMB_MOV32:
2444 DWORD inst = *(INT_PTR *)((char *)page + offset);
2445 DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2446 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2447 DWORD hi_delta;
2449 if ((inst & 0x8000fbf0) != 0x0000f240)
2450 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2452 imm16 += LOWORD(delta);
2453 hi_delta = HIWORD(delta) + HIWORD(imm16);
2454 *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2455 ((imm16 >> 12) & 0x000f) +
2456 ((imm16 << 20) & 0x70000000) +
2457 ((imm16 << 16) & 0xff0000);
2459 if (hi_delta != 0)
2461 inst = *(INT_PTR *)((char *)page + offset + 4);
2462 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2463 ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2465 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2466 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2468 imm16 += hi_delta;
2469 if (imm16 > 0xffff)
2470 ERR("resulting immediate value won't fit: %08x\n", imm16);
2471 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2472 ((imm16 >> 1) & 0x0400) +
2473 ((imm16 >> 12) & 0x000f) +
2474 ((imm16 << 20) & 0x70000000) +
2475 ((imm16 << 16) & 0xff0000);
2478 break;
2479 #endif
2480 default:
2481 FIXME("Unknown/unsupported fixup type %x.\n", type);
2482 return NULL;
2484 relocs++;
2486 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2490 /******************************************************************
2491 * LdrQueryProcessModuleInformation
2494 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2495 ULONG buf_size, ULONG* req_size)
2497 SYSTEM_MODULE* sm = &smi->Modules[0];
2498 ULONG size = sizeof(ULONG);
2499 NTSTATUS nts = STATUS_SUCCESS;
2500 ANSI_STRING str;
2501 char* ptr;
2502 PLIST_ENTRY mark, entry;
2503 PLDR_MODULE mod;
2504 WORD id = 0;
2506 smi->ModulesCount = 0;
2508 RtlEnterCriticalSection( &loader_section );
2509 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2510 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2512 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2513 size += sizeof(*sm);
2514 if (size <= buf_size)
2516 sm->Reserved1 = 0; /* FIXME */
2517 sm->Reserved2 = 0; /* FIXME */
2518 sm->ImageBaseAddress = mod->BaseAddress;
2519 sm->ImageSize = mod->SizeOfImage;
2520 sm->Flags = mod->Flags;
2521 sm->Id = id++;
2522 sm->Rank = 0; /* FIXME */
2523 sm->Unknown = 0; /* FIXME */
2524 str.Length = 0;
2525 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2526 str.Buffer = (char*)sm->Name;
2527 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2528 ptr = strrchr(str.Buffer, '\\');
2529 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2531 smi->ModulesCount++;
2532 sm++;
2534 else nts = STATUS_INFO_LENGTH_MISMATCH;
2536 RtlLeaveCriticalSection( &loader_section );
2538 if (req_size) *req_size = size;
2540 return nts;
2544 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2546 NTSTATUS status;
2547 UNICODE_STRING str;
2548 ULONG size;
2549 WCHAR buffer[64];
2550 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2552 RtlInitUnicodeString( &str, name );
2554 size = sizeof(buffer) - sizeof(WCHAR);
2555 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2556 return status;
2558 if (info->Type != REG_DWORD)
2560 buffer[size / sizeof(WCHAR)] = 0;
2561 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2563 else memcpy( value, info->Data, sizeof(*value) );
2564 return status;
2567 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2568 void *data, ULONG in_size, ULONG *out_size )
2570 NTSTATUS status;
2571 UNICODE_STRING str;
2572 ULONG size;
2573 char *buffer;
2574 KEY_VALUE_PARTIAL_INFORMATION *info;
2575 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2577 RtlInitUnicodeString( &str, name );
2579 size = info_size + in_size;
2580 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2581 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2582 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2583 if (!status || status == STATUS_BUFFER_OVERFLOW)
2585 if (out_size) *out_size = info->DataLength;
2586 if (data && !status) memcpy( data, info->Data, info->DataLength );
2588 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2589 return status;
2593 /******************************************************************
2594 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2596 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2597 void *data, ULONG in_size, ULONG *out_size )
2599 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2600 'S','o','f','t','w','a','r','e','\\',
2601 'M','i','c','r','o','s','o','f','t','\\',
2602 'W','i','n','d','o','w','s',' ','N','T','\\',
2603 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2604 'I','m','a','g','e',' ','F','i','l','e',' ',
2605 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2606 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2607 OBJECT_ATTRIBUTES attr;
2608 UNICODE_STRING name_str;
2609 HANDLE hkey;
2610 NTSTATUS status;
2611 ULONG len;
2612 WCHAR *p;
2614 attr.Length = sizeof(attr);
2615 attr.RootDirectory = 0;
2616 attr.ObjectName = &name_str;
2617 attr.Attributes = OBJ_CASE_INSENSITIVE;
2618 attr.SecurityDescriptor = NULL;
2619 attr.SecurityQualityOfService = NULL;
2621 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2622 else p = key->Buffer;
2623 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2624 name_str.Buffer = path;
2625 name_str.Length = sizeof(optionsW) + len;
2626 name_str.MaximumLength = name_str.Length;
2627 memcpy( path, optionsW, sizeof(optionsW) );
2628 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2629 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2631 if (type == REG_DWORD)
2633 if (out_size) *out_size = sizeof(ULONG);
2634 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2635 else status = STATUS_BUFFER_OVERFLOW;
2637 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2639 NtClose( hkey );
2640 return status;
2644 /******************************************************************
2645 * RtlDllShutdownInProgress (NTDLL.@)
2647 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2649 return process_detaching;
2652 /****************************************************************************
2653 * LdrResolveDelayLoadedAPI (NTDLL.@)
2655 void* WINAPI LdrResolveDelayLoadedAPI( void* base, const IMAGE_DELAYLOAD_DESCRIPTOR* desc,
2656 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook, void* syshook,
2657 IMAGE_THUNK_DATA* addr, ULONG flags )
2659 IMAGE_THUNK_DATA *pIAT, *pINT;
2660 DELAYLOAD_INFO delayinfo;
2661 UNICODE_STRING mod;
2662 const CHAR* name;
2663 HMODULE *phmod;
2664 NTSTATUS nts;
2665 FARPROC fp;
2666 DWORD id;
2668 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base, desc, dllhook, syshook, addr, flags);
2670 phmod = get_rva(base, desc->ModuleHandleRVA);
2671 pIAT = get_rva(base, desc->ImportAddressTableRVA);
2672 pINT = get_rva(base, desc->ImportNameTableRVA);
2673 name = get_rva(base, desc->DllNameRVA);
2674 id = addr - pIAT;
2676 if (!*phmod)
2678 if (!RtlCreateUnicodeStringFromAsciiz(&mod, name))
2680 nts = STATUS_NO_MEMORY;
2681 goto fail;
2683 nts = LdrLoadDll(NULL, 0, &mod, phmod);
2684 RtlFreeUnicodeString(&mod);
2685 if (nts) goto fail;
2688 if (IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal))
2689 nts = LdrGetProcedureAddress(*phmod, NULL, LOWORD(pINT[id].u1.Ordinal), (void**)&fp);
2690 else
2692 const IMAGE_IMPORT_BY_NAME* iibn = get_rva(base, pINT[id].u1.AddressOfData);
2693 ANSI_STRING fnc;
2695 RtlInitAnsiString(&fnc, (char*)iibn->Name);
2696 nts = LdrGetProcedureAddress(*phmod, &fnc, 0, (void**)&fp);
2698 if (!nts)
2700 pIAT[id].u1.Function = (ULONG_PTR)fp;
2701 return fp;
2704 fail:
2705 delayinfo.Size = sizeof(delayinfo);
2706 delayinfo.DelayloadDescriptor = desc;
2707 delayinfo.ThunkAddress = addr;
2708 delayinfo.TargetDllName = name;
2709 delayinfo.TargetApiDescriptor.ImportDescribedByName = !IMAGE_SNAP_BY_ORDINAL(pINT[id].u1.Ordinal);
2710 delayinfo.TargetApiDescriptor.Description.Ordinal = LOWORD(pINT[id].u1.Ordinal);
2711 delayinfo.TargetModuleBase = *phmod;
2712 delayinfo.Unused = NULL;
2713 delayinfo.LastError = nts;
2714 return dllhook(4, &delayinfo);
2717 /******************************************************************
2718 * LdrShutdownProcess (NTDLL.@)
2721 void WINAPI LdrShutdownProcess(void)
2723 TRACE("()\n");
2724 process_detaching = TRUE;
2725 process_detach();
2729 /******************************************************************
2730 * RtlExitUserProcess (NTDLL.@)
2732 void WINAPI RtlExitUserProcess( DWORD status )
2734 RtlEnterCriticalSection( &loader_section );
2735 RtlAcquirePebLock();
2736 NtTerminateProcess( 0, status );
2737 LdrShutdownProcess();
2738 NtTerminateProcess( GetCurrentProcess(), status );
2739 exit( status );
2742 /******************************************************************
2743 * LdrShutdownThread (NTDLL.@)
2746 void WINAPI LdrShutdownThread(void)
2748 PLIST_ENTRY mark, entry;
2749 PLDR_MODULE mod;
2750 UINT i;
2751 void **pointers;
2753 TRACE("()\n");
2755 /* don't do any detach calls if process is exiting */
2756 if (process_detaching) return;
2758 RtlEnterCriticalSection( &loader_section );
2760 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2761 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2763 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2764 InInitializationOrderModuleList);
2765 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2766 continue;
2767 if ( mod->Flags & LDR_NO_DLL_CALLS )
2768 continue;
2770 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2771 DLL_THREAD_DETACH, NULL );
2774 RtlAcquirePebLock();
2775 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
2776 RtlReleasePebLock();
2778 if ((pointers = NtCurrentTeb()->ThreadLocalStoragePointer))
2780 for (i = 0; i < tls_module_count; i++) RtlFreeHeap( GetProcessHeap(), 0, pointers[i] );
2781 RtlFreeHeap( GetProcessHeap(), 0, pointers );
2783 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
2784 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
2785 RtlLeaveCriticalSection( &loader_section );
2789 /***********************************************************************
2790 * free_modref
2793 static void free_modref( WINE_MODREF *wm )
2795 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2796 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2797 if (wm->ldr.InInitializationOrderModuleList.Flink)
2798 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2800 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2801 if (!TRACE_ON(module))
2802 TRACE_(loaddll)("Unloaded module %s : %s\n",
2803 debugstr_w(wm->ldr.FullDllName.Buffer),
2804 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2806 SERVER_START_REQ( unload_dll )
2808 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2809 wine_server_call( req );
2811 SERVER_END_REQ;
2813 free_tls_slot( &wm->ldr );
2814 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2815 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2816 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2817 if (cached_modref == wm) cached_modref = NULL;
2818 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2819 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2820 RtlFreeHeap( GetProcessHeap(), 0, wm );
2823 /***********************************************************************
2824 * MODULE_FlushModrefs
2826 * Remove all unused modrefs and call the internal unloading routines
2827 * for the library type.
2829 * The loader_section must be locked while calling this function.
2831 static void MODULE_FlushModrefs(void)
2833 PLIST_ENTRY mark, entry, prev;
2834 PLDR_MODULE mod;
2835 WINE_MODREF*wm;
2837 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2838 for (entry = mark->Blink; entry != mark; entry = prev)
2840 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2841 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2842 prev = entry->Blink;
2843 if (!mod->LoadCount) free_modref( wm );
2846 /* check load order list too for modules that haven't been initialized yet */
2847 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2848 for (entry = mark->Blink; entry != mark; entry = prev)
2850 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2851 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2852 prev = entry->Blink;
2853 if (!mod->LoadCount) free_modref( wm );
2857 /***********************************************************************
2858 * MODULE_DecRefCount
2860 * The loader_section must be locked while calling this function.
2862 static void MODULE_DecRefCount( WINE_MODREF *wm )
2864 int i;
2866 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2867 return;
2869 if ( wm->ldr.LoadCount <= 0 )
2870 return;
2872 --wm->ldr.LoadCount;
2873 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2875 if ( wm->ldr.LoadCount == 0 )
2877 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2879 for ( i = 0; i < wm->nDeps; i++ )
2880 if ( wm->deps[i] )
2881 MODULE_DecRefCount( wm->deps[i] );
2883 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2887 /******************************************************************
2888 * LdrUnloadDll (NTDLL.@)
2892 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2894 WINE_MODREF *wm;
2895 NTSTATUS retv = STATUS_SUCCESS;
2897 if (process_detaching) return retv;
2899 TRACE("(%p)\n", hModule);
2901 RtlEnterCriticalSection( &loader_section );
2903 free_lib_count++;
2904 if ((wm = get_modref( hModule )) != NULL)
2906 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2908 /* Recursively decrement reference counts */
2909 MODULE_DecRefCount( wm );
2911 /* Call process detach notifications */
2912 if ( free_lib_count <= 1 )
2914 process_detach();
2915 MODULE_FlushModrefs();
2918 TRACE("END\n");
2920 else
2921 retv = STATUS_DLL_NOT_FOUND;
2923 free_lib_count--;
2925 RtlLeaveCriticalSection( &loader_section );
2927 return retv;
2930 /***********************************************************************
2931 * RtlImageNtHeader (NTDLL.@)
2933 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2935 IMAGE_NT_HEADERS *ret;
2937 __TRY
2939 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2941 ret = NULL;
2942 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2944 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2945 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2948 __EXCEPT_PAGE_FAULT
2950 return NULL;
2952 __ENDTRY
2953 return ret;
2957 /***********************************************************************
2958 * attach_process_dlls
2960 * Initial attach to all the dlls loaded by the process.
2962 static NTSTATUS attach_process_dlls( void *wm )
2964 NTSTATUS status;
2966 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2968 RtlEnterCriticalSection( &loader_section );
2969 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2971 if (last_failed_modref)
2972 ERR( "%s failed to initialize, aborting\n",
2973 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2974 return status;
2976 attach_implicitly_loaded_dlls( (LPVOID)1 );
2977 RtlLeaveCriticalSection( &loader_section );
2978 return status;
2982 /***********************************************************************
2983 * load_global_options
2985 static void load_global_options(void)
2987 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2988 'S','y','s','t','e','m','\\',
2989 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2990 'C','o','n','t','r','o','l','\\',
2991 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2992 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2993 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};
2994 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2995 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2996 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};
2997 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};
2999 OBJECT_ATTRIBUTES attr;
3000 UNICODE_STRING name_str;
3001 HANDLE hkey;
3002 ULONG value;
3004 attr.Length = sizeof(attr);
3005 attr.RootDirectory = 0;
3006 attr.ObjectName = &name_str;
3007 attr.Attributes = OBJ_CASE_INSENSITIVE;
3008 attr.SecurityDescriptor = NULL;
3009 attr.SecurityQualityOfService = NULL;
3010 RtlInitUnicodeString( &name_str, sessionW );
3012 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
3014 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
3016 query_dword_option( hkey, critsectW, &value );
3017 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
3019 query_dword_option( hkey, heapresW, &value );
3020 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
3022 query_dword_option( hkey, heapcommitW, &value );
3023 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
3025 query_dword_option( hkey, decommittotalW, &value );
3026 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
3028 query_dword_option( hkey, decommitfreeW, &value );
3029 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
3031 NtClose( hkey );
3035 /***********************************************************************
3036 * start_process
3038 static void start_process( void *kernel_start )
3040 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
3043 /******************************************************************
3044 * LdrInitializeThunk (NTDLL.@)
3047 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
3048 ULONG_PTR unknown3, ULONG_PTR unknown4 )
3050 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
3051 NTSTATUS status;
3052 WINE_MODREF *wm;
3053 LPCWSTR load_path;
3054 PEB *peb = NtCurrentTeb()->Peb;
3056 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
3058 /* allocate the modref for the main exe (if not already done) */
3059 wm = get_modref( peb->ImageBaseAddress );
3060 assert( wm );
3061 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
3063 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
3064 exit(1);
3067 peb->LoaderLock = &loader_section;
3068 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
3069 if (!peb->ProcessParameters->WindowTitle.Buffer)
3070 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
3071 version_init( wm->ldr.FullDllName.Buffer );
3072 virtual_set_large_address_space();
3074 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
3075 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
3077 /* the main exe needs to be the first in the load order list */
3078 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
3079 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
3081 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
3082 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
3084 actctx_init();
3085 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
3086 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
3087 heap_set_debug_flags( GetProcessHeap() );
3089 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
3090 if (status != STATUS_SUCCESS) goto error;
3092 virtual_release_address_space();
3093 virtual_clear_thread_stack();
3094 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
3096 error:
3097 ERR( "Main exe initialization for %s failed, status %x\n",
3098 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
3099 NtTerminateProcess( GetCurrentProcess(), status );
3103 /***********************************************************************
3104 * RtlImageDirectoryEntryToData (NTDLL.@)
3106 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
3108 const IMAGE_NT_HEADERS *nt;
3109 DWORD addr;
3111 if ((ULONG_PTR)module & 1) /* mapped as data file */
3113 module = (HMODULE)((ULONG_PTR)module & ~1);
3114 image = FALSE;
3116 if (!(nt = RtlImageNtHeader( module ))) return NULL;
3117 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
3119 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
3121 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3122 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3123 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
3124 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3126 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
3128 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
3130 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
3131 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
3132 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
3133 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
3135 else return NULL;
3137 /* not mapped as image, need to find the section containing the virtual address */
3138 return RtlImageRvaToVa( nt, module, addr, NULL );
3142 /***********************************************************************
3143 * RtlImageRvaToSection (NTDLL.@)
3145 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
3146 HMODULE module, DWORD rva )
3148 int i;
3149 const IMAGE_SECTION_HEADER *sec;
3151 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
3152 nt->FileHeader.SizeOfOptionalHeader);
3153 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
3155 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3156 return (PIMAGE_SECTION_HEADER)sec;
3158 return NULL;
3162 /***********************************************************************
3163 * RtlImageRvaToVa (NTDLL.@)
3165 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
3166 DWORD rva, IMAGE_SECTION_HEADER **section )
3168 IMAGE_SECTION_HEADER *sec;
3170 if (section && *section) /* try this section first */
3172 sec = *section;
3173 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
3174 goto found;
3176 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
3177 found:
3178 if (section) *section = sec;
3179 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
3183 /***********************************************************************
3184 * RtlPcToFileHeader (NTDLL.@)
3186 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
3188 LDR_MODULE *module;
3189 PVOID ret = NULL;
3191 RtlEnterCriticalSection( &loader_section );
3192 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
3193 RtlLeaveCriticalSection( &loader_section );
3194 *address = ret;
3195 return ret;
3199 /***********************************************************************
3200 * NtLoadDriver (NTDLL.@)
3201 * ZwLoadDriver (NTDLL.@)
3203 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
3205 FIXME("(%p), stub!\n",DriverServiceName);
3206 return STATUS_NOT_IMPLEMENTED;
3210 /***********************************************************************
3211 * NtUnloadDriver (NTDLL.@)
3212 * ZwUnloadDriver (NTDLL.@)
3214 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
3216 FIXME("(%p), stub!\n",DriverServiceName);
3217 return STATUS_NOT_IMPLEMENTED;
3221 /******************************************************************
3222 * DllMain (NTDLL.@)
3224 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
3226 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
3227 return TRUE;
3231 /******************************************************************
3232 * __wine_init_windows_dir (NTDLL.@)
3234 * Windows and system dir initialization once kernel32 has been loaded.
3236 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
3238 PLIST_ENTRY mark, entry;
3239 LPWSTR buffer, p;
3241 strcpyW( user_shared_data->NtSystemRoot, windir );
3242 DIR_init_windows_dir( windir, sysdir );
3244 /* prepend the system dir to the name of the already created modules */
3245 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
3246 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
3248 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
3250 assert( mod->Flags & LDR_WINE_INTERNAL );
3252 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
3253 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
3254 if (!buffer) continue;
3255 strcpyW( buffer, system_dir.Buffer );
3256 p = buffer + strlenW( buffer );
3257 if (p > buffer && p[-1] != '\\') *p++ = '\\';
3258 strcpyW( p, mod->FullDllName.Buffer );
3259 RtlInitUnicodeString( &mod->FullDllName, buffer );
3260 RtlInitUnicodeString( &mod->BaseDllName, p );
3265 /***********************************************************************
3266 * __wine_process_init
3268 void __wine_process_init(void)
3270 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3272 WINE_MODREF *wm;
3273 NTSTATUS status;
3274 ANSI_STRING func_name;
3275 void (* DECLSPEC_NORETURN CDECL init_func)(void);
3277 main_exe_file = thread_init();
3279 /* retrieve current umask */
3280 FILE_umask = umask(0777);
3281 umask( FILE_umask );
3283 load_global_options();
3285 /* setup the load callback and create ntdll modref */
3286 wine_dll_set_callback( load_builtin_callback );
3288 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
3290 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
3291 exit(1);
3293 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
3294 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
3296 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
3297 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
3298 0, (void **)&init_func )) != STATUS_SUCCESS)
3300 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
3301 exit(1);
3303 init_func();