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
23 #include "wine/port.h"
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
32 #define WIN32_NO_STATUS
33 #define NONAMELESSUNION
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/list.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module
);
49 WINE_DECLARE_DEBUG_CHANNEL(relay
);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
52 WINE_DECLARE_DEBUG_CHANNEL(imports
);
55 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
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
);
65 typedef void (CALLBACK
*LDRENUMPROC
)(LDR_MODULE
*, void *, BOOLEAN
*);
67 /* system directory with trailing backslash */
68 const WCHAR system_dir
[] = {'C',':','\\','w','i','n','d','o','w','s','\\',
69 's','y','s','t','e','m','3','2','\\',0};
71 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
72 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
73 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
75 struct ldr_notification
78 PLDR_DLL_NOTIFICATION_FUNCTION callback
;
82 static struct list ldr_notifications
= LIST_INIT( ldr_notifications
);
84 static const char * const reason_names
[] =
90 NULL
, NULL
, NULL
, NULL
,
94 static const WCHAR dllW
[] = {'.','d','l','l',0};
96 /* internal representation of 32bit modules. per process. */
97 typedef struct _wine_modref
104 struct _wine_modref
**deps
;
107 /* info about the current builtin dll load */
108 /* used to keep track of things across the register_dll constructor call */
109 struct builtin_load_info
111 const WCHAR
*load_path
;
112 const WCHAR
*filename
;
117 static struct builtin_load_info default_load_info
;
118 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
120 static UINT tls_module_count
; /* number of modules with TLS directory */
121 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
122 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
124 static RTL_CRITICAL_SECTION loader_section
;
125 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
127 0, 0, &loader_section
,
128 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
129 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
131 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
133 static WINE_MODREF
*cached_modref
;
134 static WINE_MODREF
*current_modref
;
135 static WINE_MODREF
*last_failed_modref
;
137 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
138 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
139 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
140 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
141 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
142 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
144 /* convert PE image VirtualAddress to Real Address */
145 static inline void *get_rva( HMODULE module
, DWORD va
)
147 return (void *)((char *)module
+ va
);
150 /* check whether the file name contains a path */
151 static inline BOOL
contains_path( LPCWSTR name
)
153 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
156 /* convert from straight ASCII to Unicode without depending on the current codepage */
157 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
159 while (len
--) *dst
++ = (unsigned char)*src
++;
163 /*************************************************************************
164 * call_dll_entry_point
166 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
167 * their entry point, so we need a small asm wrapper. Testing indicates
168 * that only modifying esi leads to a crash, so use this one to backup
169 * ebp while running the dll entry proc.
172 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
173 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
175 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
176 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
178 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
180 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
182 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
184 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
186 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
190 "movl 8(%ebp),%eax\n\t"
193 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
194 "leal -12(%ebp),%esp\n\t"
196 __ASM_CFI(".cfi_same_value %edi\n\t")
198 __ASM_CFI(".cfi_same_value %esi\n\t")
200 __ASM_CFI(".cfi_same_value %ebx\n\t")
202 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
203 __ASM_CFI(".cfi_same_value %ebp\n\t")
206 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
207 UINT reason
, void *reserved
)
209 return proc( module
, reason
, reserved
);
211 #endif /* __i386__ */
214 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
215 /*************************************************************************
218 * Entry point for stub functions.
220 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
222 EXCEPTION_RECORD rec
;
224 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
225 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
226 rec
.ExceptionRecord
= NULL
;
227 rec
.ExceptionAddress
= ret_addr
;
228 rec
.NumberParameters
= 2;
229 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
230 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
231 for (;;) RtlRaiseException( &rec
);
235 #include "pshpack1.h"
239 BYTE pushl1
; /* pushl $name */
241 BYTE pushl2
; /* pushl $dll */
243 BYTE call
; /* call stub_entry_point */
246 #elif defined(__arm__)
249 DWORD ldr_r0
; /* ldr r0, $dll */
250 DWORD ldr_r1
; /* ldr r1, $name */
251 DWORD mov_r2_lr
; /* mov r2, lr */
252 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
257 #elif defined(__aarch64__)
260 DWORD ldr_x0
; /* ldr x0, $dll */
261 DWORD ldr_x1
; /* ldr x1, $name */
262 DWORD mov_x2_lr
; /* mov x2, lr */
263 DWORD ldr_x16
; /* ldr x16, $entry */
264 DWORD br_x16
; /* br x16 */
272 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
274 BYTE movq_rsi
[2]; /* movq $name,%rsi */
276 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
277 BYTE movq_rax
[2]; /* movq $entry, %rax */
279 BYTE jmpq_rax
[2]; /* jmp %rax */
284 /*************************************************************************
287 * Allocate a stub entry point.
289 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
291 #define MAX_SIZE 65536
292 static struct stub
*stubs
;
293 static unsigned int nb_stubs
;
296 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
300 SIZE_T size
= MAX_SIZE
;
301 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
302 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
305 stub
= &stubs
[nb_stubs
++];
307 stub
->pushl1
= 0x68; /* pushl $name */
309 stub
->pushl2
= 0x68; /* pushl $dll */
311 stub
->call
= 0xe8; /* call stub_entry_point */
312 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
313 #elif defined(__arm__)
314 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
315 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
316 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
317 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
320 stub
->entry
= stub_entry_point
;
321 #elif defined(__aarch64__)
322 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
323 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
324 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
325 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
326 stub
->br_x16
= 0xd61f0200; /* br x16 */
329 stub
->entry
= stub_entry_point
;
331 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
332 stub
->movq_rdi
[1] = 0xbf;
334 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
335 stub
->movq_rsi
[1] = 0xbe;
337 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
338 stub
->movq_rsp_rdx
[1] = 0x8b;
339 stub
->movq_rsp_rdx
[2] = 0x14;
340 stub
->movq_rsp_rdx
[3] = 0x24;
341 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
342 stub
->movq_rax
[1] = 0xb8;
343 stub
->entry
= stub_entry_point
;
344 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
345 stub
->jmpq_rax
[1] = 0xe0;
347 return (ULONG_PTR
)stub
;
351 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
352 #endif /* __i386__ */
354 /* call ldr notifications */
355 static void call_ldr_notifications( ULONG reason
, LDR_MODULE
*module
)
357 struct ldr_notification
*notify
, *notify_next
;
358 LDR_DLL_NOTIFICATION_DATA data
;
360 data
.Loaded
.Flags
= 0;
361 data
.Loaded
.FullDllName
= &module
->FullDllName
;
362 data
.Loaded
.BaseDllName
= &module
->BaseDllName
;
363 data
.Loaded
.DllBase
= module
->BaseAddress
;
364 data
.Loaded
.SizeOfImage
= module
->SizeOfImage
;
366 LIST_FOR_EACH_ENTRY_SAFE( notify
, notify_next
, &ldr_notifications
, struct ldr_notification
, entry
)
368 TRACE_(relay
)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
369 notify
->callback
, reason
, &data
, notify
->context
);
371 notify
->callback(reason
, &data
, notify
->context
);
373 TRACE_(relay
)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
374 notify
->callback
, reason
, &data
, notify
->context
);
378 /*************************************************************************
381 * Looks for the referenced HMODULE in the current process
382 * The loader_section must be locked while calling this function.
384 static WINE_MODREF
*get_modref( HMODULE hmod
)
386 PLIST_ENTRY mark
, entry
;
389 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
391 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
392 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
394 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
395 if (mod
->BaseAddress
== hmod
)
396 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
402 /**********************************************************************
403 * find_basename_module
405 * Find a module from its base name.
406 * The loader_section must be locked while calling this function
408 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
410 PLIST_ENTRY mark
, entry
;
412 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
413 return cached_modref
;
415 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
416 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
418 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
419 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
421 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
422 return cached_modref
;
429 /**********************************************************************
430 * find_fullname_module
432 * Find a module from its full path name.
433 * The loader_section must be locked while calling this function
435 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
437 PLIST_ENTRY mark
, entry
;
439 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
440 return cached_modref
;
442 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
443 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
445 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
446 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
448 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
449 return cached_modref
;
456 /**********************************************************************
459 * Find a module from its file id.
460 * The loader_section must be locked while calling this function
462 static WINE_MODREF
*find_fileid_module( HANDLE handle
, struct stat
*st
)
464 LIST_ENTRY
*mark
, *entry
;
466 if (cached_modref
&& cached_modref
->dev
== st
->st_dev
&& cached_modref
->ino
== st
->st_ino
)
467 return cached_modref
;
469 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
470 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
472 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
473 WINE_MODREF
*wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
475 if (wm
->dev
== st
->st_dev
&& wm
->ino
== st
->st_ino
)
485 /*************************************************************************
486 * find_forwarded_export
488 * Find the final function pointer for a forwarded function.
489 * The loader_section must be locked while calling this function.
491 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
493 const IMAGE_EXPORT_DIRECTORY
*exports
;
497 const char *end
= strrchr(forward
, '.');
500 if (!end
) return NULL
;
501 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
502 ascii_to_unicode( mod_name
, forward
, end
- forward
);
503 mod_name
[end
- forward
] = 0;
504 if (!strchrW( mod_name
, '.' ))
506 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
507 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
510 if (!(wm
= find_basename_module( mod_name
)))
512 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
513 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
514 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
516 if (!imports_fixup_done
&& current_modref
)
519 if (current_modref
->alloc_deps
)
520 deps
= RtlReAllocateHeap( GetProcessHeap(), 0, current_modref
->deps
,
521 (current_modref
->alloc_deps
+ 1) * sizeof(*deps
) );
523 deps
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps
) );
526 deps
[current_modref
->nDeps
++] = wm
;
527 current_modref
->deps
= deps
;
528 current_modref
->alloc_deps
++;
531 else if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
533 LdrUnloadDll( wm
->ldr
.BaseAddress
);
540 ERR( "module not found for forward '%s' used by %s\n",
541 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
545 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
546 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
548 const char *name
= end
+ 1;
549 if (*name
== '#') /* ordinal */
550 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
552 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
557 ERR("function not found for forward '%s' used by %s."
558 " If you are using builtin %s, try using the native one instead.\n",
559 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
560 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
566 /*************************************************************************
567 * find_ordinal_export
569 * Find an exported function by ordinal.
570 * The exports base must have been subtracted from the ordinal already.
571 * The loader_section must be locked while calling this function.
573 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
574 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
577 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
579 if (ordinal
>= exports
->NumberOfFunctions
)
581 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
584 if (!functions
[ordinal
]) return NULL
;
586 proc
= get_rva( module
, functions
[ordinal
] );
588 /* if the address falls into the export dir, it's a forward */
589 if (((const char *)proc
>= (const char *)exports
) &&
590 ((const char *)proc
< (const char *)exports
+ exp_size
))
591 return find_forwarded_export( module
, (const char *)proc
, load_path
);
595 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
596 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
600 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
601 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
607 /*************************************************************************
610 * Find an exported function by name.
611 * The loader_section must be locked while calling this function.
613 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
614 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
616 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
617 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
618 int min
= 0, max
= exports
->NumberOfNames
- 1;
620 /* first check the hint */
621 if (hint
>= 0 && hint
<= max
)
623 char *ename
= get_rva( module
, names
[hint
] );
624 if (!strcmp( ename
, name
))
625 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
628 /* then do a binary search */
631 int res
, pos
= (min
+ max
) / 2;
632 char *ename
= get_rva( module
, names
[pos
] );
633 if (!(res
= strcmp( ename
, name
)))
634 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
635 if (res
> 0) max
= pos
- 1;
643 /*************************************************************************
646 * Import the dll specified by the given import descriptor.
647 * The loader_section must be locked while calling this function.
649 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
654 const IMAGE_EXPORT_DIRECTORY
*exports
;
656 const IMAGE_THUNK_DATA
*import_list
;
657 IMAGE_THUNK_DATA
*thunk_list
;
659 const char *name
= get_rva( module
, descr
->Name
);
660 DWORD len
= strlen(name
);
662 SIZE_T protect_size
= 0;
665 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
666 if (descr
->u
.OriginalFirstThunk
)
667 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
669 import_list
= thunk_list
;
671 if (!import_list
->u1
.Ordinal
)
673 WARN( "Skipping unused import %s\n", name
);
678 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
680 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
682 ascii_to_unicode( buffer
, name
, len
);
684 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
686 else /* need to allocate a larger buffer */
688 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
689 if (!ptr
) return FALSE
;
690 ascii_to_unicode( ptr
, name
, len
);
692 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
693 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
698 if (status
== STATUS_DLL_NOT_FOUND
)
699 ERR("Library %s (which is needed by %s) not found\n",
700 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
702 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
703 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
707 /* unprotect the import address table since it can be located in
708 * readonly section */
709 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
710 protect_base
= thunk_list
;
711 protect_size
*= sizeof(*thunk_list
);
712 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
713 &protect_size
, PAGE_READWRITE
, &protect_old
);
715 imp_mod
= wmImp
->ldr
.BaseAddress
;
716 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
720 /* set all imported function to deadbeef */
721 while (import_list
->u1
.Ordinal
)
723 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
725 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
726 WARN("No implementation for %s.%d", name
, ordinal
);
727 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
731 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
732 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
733 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
735 WARN(" imported from %s, allocating stub %p\n",
736 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
737 (void *)thunk_list
->u1
.Function
);
744 while (import_list
->u1
.Ordinal
)
746 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
748 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
750 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
751 ordinal
- exports
->Base
, load_path
);
752 if (!thunk_list
->u1
.Function
)
754 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
755 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
756 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
757 (void *)thunk_list
->u1
.Function
);
759 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
761 else /* import by name */
763 IMAGE_IMPORT_BY_NAME
*pe_name
;
764 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
765 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
766 (const char*)pe_name
->Name
,
767 pe_name
->Hint
, load_path
);
768 if (!thunk_list
->u1
.Function
)
770 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
771 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
772 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
773 (void *)thunk_list
->u1
.Function
);
775 TRACE_(imports
)("--- %s %s.%d = %p\n",
776 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
783 /* restore old protection of the import address table */
784 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
790 /***********************************************************************
791 * create_module_activation_context
793 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
796 LDR_RESOURCE_INFO info
;
797 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
799 info
.Type
= RT_MANIFEST
;
800 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
802 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
805 ctx
.cbSize
= sizeof(ctx
);
807 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
808 ctx
.hModule
= module
->BaseAddress
;
809 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
810 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
816 /*************************************************************************
817 * is_dll_native_subsystem
819 * Check if dll is a proper native driver.
820 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
821 * while being perfectly normal DLLs. This heuristic should catch such breakages.
823 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
825 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
826 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
827 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
831 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
832 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
834 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
835 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
837 for (i
= 0; imports
[i
].Name
; i
++)
839 const char *name
= get_rva( module
, imports
[i
].Name
);
840 DWORD len
= strlen(name
);
841 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
842 ascii_to_unicode( buffer
, name
, len
+ 1 );
843 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
845 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
853 /*************************************************************************
856 * Allocate a TLS slot for a newly-loaded module.
857 * The loader_section must be locked while calling this function.
859 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
861 const IMAGE_TLS_DIRECTORY
*dir
;
866 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
869 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
870 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
872 for (i
= 0; i
< tls_module_count
; i
++)
874 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
875 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
879 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
880 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
881 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
883 if (i
== tls_module_count
)
885 UINT new_count
= max( 32, tls_module_count
* 2 );
888 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
890 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
891 new_count
* sizeof(*tls_dirs
) );
892 if (!new_ptr
) return -1;
894 /* resize the pointer block in all running threads */
895 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
897 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
898 void **old
= teb
->ThreadLocalStoragePointer
;
899 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
902 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
903 teb
->ThreadLocalStoragePointer
= new;
904 #if defined(__APPLE__) && defined(__x86_64__)
905 if (teb
->Reserved5
[0])
906 ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
908 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
909 /* FIXME: can't free old block here, should be freed at thread exit */
913 tls_module_count
= new_count
;
916 /* allocate the data block in all running threads */
917 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
919 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
921 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
922 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
923 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
925 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
926 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
928 RtlFreeHeap( GetProcessHeap(), 0,
929 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
932 *(DWORD
*)dir
->AddressOfIndex
= i
;
938 /*************************************************************************
941 * Free the module TLS slot on unload.
942 * The loader_section must be locked while calling this function.
944 static void free_tls_slot( LDR_MODULE
*mod
)
946 ULONG i
= (USHORT
)mod
->TlsIndex
;
948 if (mod
->TlsIndex
== -1) return;
949 assert( i
< tls_module_count
);
950 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
954 /****************************************************************
955 * fixup_imports_ilonly
957 * Fixup imports for an IL-only module. All we do is import mscoree.
958 * The loader_section must be locked while calling this function.
960 static NTSTATUS
fixup_imports_ilonly( WINE_MODREF
*wm
, LPCWSTR load_path
, void **entry
)
962 static const WCHAR mscoreeW
[] = {'m','s','c','o','r','e','e','.','d','l','l',0};
963 IMAGE_EXPORT_DIRECTORY
*exports
;
967 WINE_MODREF
*prev
, *imp
;
969 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
970 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
974 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(WINE_MODREF
*) );
976 prev
= current_modref
;
978 if (!(status
= load_dll( load_path
, mscoreeW
, 0, &imp
))) wm
->deps
[0] = imp
;
979 current_modref
= prev
;
982 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
983 debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
987 TRACE( "loaded mscoree for %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
989 if ((exports
= RtlImageDirectoryEntryToData( imp
->ldr
.BaseAddress
, TRUE
,
990 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
992 const char *name
= (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) ? "_CorDllMain" : "_CorExeMain";
993 proc
= find_named_export( imp
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
995 if (!proc
) return STATUS_PROCEDURE_NOT_FOUND
;
997 return STATUS_SUCCESS
;
1001 /****************************************************************
1004 * Fixup all imports of a given module.
1005 * The loader_section must be locked while calling this function.
1007 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
1009 int i
, dep
, nb_imports
;
1010 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1011 WINE_MODREF
*prev
, *imp
;
1016 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1017 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1019 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
1021 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
1022 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1023 return STATUS_SUCCESS
;
1026 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
1028 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
1030 if (!create_module_activation_context( &wm
->ldr
))
1031 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1033 /* Allocate module dependency list */
1034 wm
->alloc_deps
= nb_imports
;
1035 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
1037 /* load the imported modules. They are automatically
1038 * added to the modref list of the process.
1040 prev
= current_modref
;
1041 current_modref
= wm
;
1042 status
= STATUS_SUCCESS
;
1043 for (i
= 0; i
< nb_imports
; i
++)
1047 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &imp
))
1050 status
= STATUS_DLL_NOT_FOUND
;
1052 wm
->deps
[dep
] = imp
;
1054 current_modref
= prev
;
1055 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1060 /*************************************************************************
1063 * Allocate a WINE_MODREF structure and add it to the process list
1064 * The loader_section must be locked while calling this function.
1066 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
1070 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
1072 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) ))) return NULL
;
1074 wm
->ldr
.BaseAddress
= hModule
;
1075 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
1076 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
1077 wm
->ldr
.TlsIndex
= -1;
1078 wm
->ldr
.LoadCount
= 1;
1080 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
1081 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
1082 else p
= wm
->ldr
.FullDllName
.Buffer
;
1083 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
1085 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
1087 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
1088 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
1089 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
1090 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1093 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
1094 &wm
->ldr
.InLoadOrderModuleList
);
1095 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
1096 &wm
->ldr
.InMemoryOrderModuleList
);
1097 /* wait until init is called for inserting into InInitializationOrderModuleList */
1099 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
1101 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
1102 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1103 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1109 /*************************************************************************
1112 * Allocate the per-thread structure for module TLS storage.
1114 static NTSTATUS
alloc_thread_tls(void)
1119 if (!tls_module_count
) return STATUS_SUCCESS
;
1121 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1122 tls_module_count
* sizeof(*pointers
) )))
1123 return STATUS_NO_MEMORY
;
1125 for (i
= 0; i
< tls_module_count
; i
++)
1127 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1130 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1131 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1133 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1135 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1136 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1137 return STATUS_NO_MEMORY
;
1139 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1140 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1142 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1143 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1145 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1146 #if defined(__APPLE__) && defined(__x86_64__)
1147 __asm__
volatile (".byte 0x65\n\tmovq %0,%c1"
1149 : "r" (pointers
), "n" (FIELD_OFFSET(TEB
, ThreadLocalStoragePointer
)));
1151 return STATUS_SUCCESS
;
1155 /*************************************************************************
1156 * call_tls_callbacks
1158 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1160 const IMAGE_TLS_DIRECTORY
*dir
;
1161 const PIMAGE_TLS_CALLBACK
*callback
;
1164 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1165 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1167 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1169 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1170 *callback
, module
, reason_names
[reason
] );
1173 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1177 TRACE_(relay
)("\1exception %08x in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1178 GetExceptionCode(), callback
, module
, reason_names
[reason
] );
1182 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1183 *callback
, module
, reason_names
[reason
] );
1188 /*************************************************************************
1191 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1194 NTSTATUS status
= STATUS_SUCCESS
;
1195 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1196 void *module
= wm
->ldr
.BaseAddress
;
1199 /* Skip calls for modules loaded with special load flags */
1201 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1202 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1203 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1205 if (TRACE_ON(relay
))
1207 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1208 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1209 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1210 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1211 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1213 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1214 reason_names
[reason
], lpReserved
);
1218 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1220 status
= STATUS_DLL_INIT_FAILED
;
1224 status
= GetExceptionCode();
1225 TRACE_(relay
)("\1exception %08x in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1226 status
, entry
, module
, reason_names
[reason
], lpReserved
);
1230 /* The state of the module list may have changed due to the call
1231 to the dll. We cannot assume that this module has not been
1233 if (TRACE_ON(relay
))
1234 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1235 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1237 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1243 /*************************************************************************
1246 * Send the process attach notification to all DLLs the given module
1247 * depends on (recursively). This is somewhat complicated due to the fact that
1249 * - we have to respect the module dependencies, i.e. modules implicitly
1250 * referenced by another module have to be initialized before the module
1251 * itself can be initialized
1253 * - the initialization routine of a DLL can itself call LoadLibrary,
1254 * thereby introducing a whole new set of dependencies (even involving
1255 * the 'old' modules) at any time during the whole process
1257 * (Note that this routine can be recursively entered not only directly
1258 * from itself, but also via LoadLibrary from one of the called initialization
1261 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1262 * the process *detach* notifications to be sent in the correct order.
1263 * This must not only take into account module dependencies, but also
1264 * 'hidden' dependencies created by modules calling LoadLibrary in their
1265 * attach notification routine.
1267 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1268 * list after the attach notification has returned. This implies that the
1269 * detach notifications are called in the reverse of the sequence the attach
1270 * notifications *returned*.
1272 * The loader_section must be locked while calling this function.
1274 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1276 NTSTATUS status
= STATUS_SUCCESS
;
1280 if (process_detaching
) return status
;
1282 /* prevent infinite recursion in case of cyclical dependencies */
1283 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1284 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1287 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1289 /* Tag current MODREF to prevent recursive loop */
1290 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1291 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1292 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1294 /* Recursively attach all DLLs this one depends on */
1295 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1297 if (!wm
->deps
[i
]) continue;
1298 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1301 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1302 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1303 &wm
->ldr
.InInitializationOrderModuleList
);
1305 /* Call DLL entry point */
1306 if (status
== STATUS_SUCCESS
)
1308 WINE_MODREF
*prev
= current_modref
;
1309 current_modref
= wm
;
1311 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED
, &wm
->ldr
);
1312 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1313 if (status
== STATUS_SUCCESS
)
1315 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1319 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1320 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, &wm
->ldr
);
1322 /* point to the name so LdrInitializeThunk can print it */
1323 last_failed_modref
= wm
;
1324 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1326 current_modref
= prev
;
1329 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1330 /* Remove recursion flag */
1331 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1333 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1338 /**********************************************************************
1339 * attach_implicitly_loaded_dlls
1341 * Attach to the (builtin) dlls that have been implicitly loaded because
1342 * of a dependency at the Unix level, but not imported at the Win32 level.
1344 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1348 PLIST_ENTRY mark
, entry
;
1350 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1351 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1353 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1355 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1356 TRACE( "found implicitly loaded %s, attaching to it\n",
1357 debugstr_w(mod
->BaseDllName
.Buffer
));
1358 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1359 break; /* restart the search from the start */
1361 if (entry
== mark
) break; /* nothing found */
1366 /*************************************************************************
1369 * Send DLL process detach notifications. See the comment about calling
1370 * sequence at process_attach.
1372 static void process_detach(void)
1374 PLIST_ENTRY mark
, entry
;
1377 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1380 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1382 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1383 InInitializationOrderModuleList
);
1384 /* Check whether to detach this DLL */
1385 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1387 if ( mod
->LoadCount
&& !process_detaching
)
1390 /* Call detach notification */
1391 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1392 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1393 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1394 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, mod
);
1396 /* Restart at head of WINE_MODREF list, as entries might have
1397 been added and/or removed while performing the call ... */
1400 } while (entry
!= mark
);
1403 /*************************************************************************
1406 * Send DLL thread attach notifications. These are sent in the
1407 * reverse sequence of process detach notification.
1408 * The loader_section must be locked while calling this function.
1410 static void thread_attach(void)
1412 PLIST_ENTRY mark
, entry
;
1415 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1416 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1418 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1419 InInitializationOrderModuleList
);
1420 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1422 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1425 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1429 /******************************************************************
1430 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1433 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1436 NTSTATUS ret
= STATUS_SUCCESS
;
1438 RtlEnterCriticalSection( &loader_section
);
1440 wm
= get_modref( hModule
);
1441 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1442 ret
= STATUS_DLL_NOT_FOUND
;
1444 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1446 RtlLeaveCriticalSection( &loader_section
);
1451 /******************************************************************
1452 * LdrFindEntryForAddress (NTDLL.@)
1454 * The loader_section must be locked while calling this function
1456 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1458 PLIST_ENTRY mark
, entry
;
1461 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1462 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1464 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1465 if (mod
->BaseAddress
<= addr
&&
1466 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1469 return STATUS_SUCCESS
;
1472 return STATUS_NO_MORE_ENTRIES
;
1475 /******************************************************************
1476 * LdrEnumerateLoadedModules (NTDLL.@)
1478 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1480 LIST_ENTRY
*mark
, *entry
;
1482 BOOLEAN stop
= FALSE
;
1484 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1486 if (unknown
|| !callback
)
1487 return STATUS_INVALID_PARAMETER
;
1489 RtlEnterCriticalSection( &loader_section
);
1491 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1492 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1494 mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1495 callback( mod
, context
, &stop
);
1499 RtlLeaveCriticalSection( &loader_section
);
1500 return STATUS_SUCCESS
;
1503 /******************************************************************
1504 * LdrRegisterDllNotification (NTDLL.@)
1506 NTSTATUS WINAPI
LdrRegisterDllNotification(ULONG flags
, PLDR_DLL_NOTIFICATION_FUNCTION callback
,
1507 void *context
, void **cookie
)
1509 struct ldr_notification
*notify
;
1511 TRACE( "(%x, %p, %p, %p)\n", flags
, callback
, context
, cookie
);
1513 if (!callback
|| !cookie
)
1514 return STATUS_INVALID_PARAMETER
;
1517 FIXME( "ignoring flags %x\n", flags
);
1519 notify
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify
) );
1520 if (!notify
) return STATUS_NO_MEMORY
;
1521 notify
->callback
= callback
;
1522 notify
->context
= context
;
1524 RtlEnterCriticalSection( &loader_section
);
1525 list_add_tail( &ldr_notifications
, ¬ify
->entry
);
1526 RtlLeaveCriticalSection( &loader_section
);
1529 return STATUS_SUCCESS
;
1532 /******************************************************************
1533 * LdrUnregisterDllNotification (NTDLL.@)
1535 NTSTATUS WINAPI
LdrUnregisterDllNotification( void *cookie
)
1537 struct ldr_notification
*notify
= cookie
;
1539 TRACE( "(%p)\n", cookie
);
1541 if (!notify
) return STATUS_INVALID_PARAMETER
;
1543 RtlEnterCriticalSection( &loader_section
);
1544 list_remove( ¬ify
->entry
);
1545 RtlLeaveCriticalSection( &loader_section
);
1547 RtlFreeHeap( GetProcessHeap(), 0, notify
);
1548 return STATUS_SUCCESS
;
1551 /******************************************************************
1552 * LdrLockLoaderLock (NTDLL.@)
1554 * Note: some flags are not implemented.
1555 * Flag 0x01 is used to raise exceptions on errors.
1557 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1559 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1561 if (result
) *result
= 0;
1562 if (magic
) *magic
= 0;
1563 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1564 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1565 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1569 if (!RtlTryEnterCriticalSection( &loader_section
))
1572 return STATUS_SUCCESS
;
1578 RtlEnterCriticalSection( &loader_section
);
1579 if (result
) *result
= 1;
1581 *magic
= GetCurrentThreadId();
1582 return STATUS_SUCCESS
;
1586 /******************************************************************
1587 * LdrUnlockLoaderUnlock (NTDLL.@)
1589 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1593 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1594 RtlLeaveCriticalSection( &loader_section
);
1596 return STATUS_SUCCESS
;
1600 /******************************************************************
1601 * LdrGetProcedureAddress (NTDLL.@)
1603 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1604 ULONG ord
, PVOID
*address
)
1606 IMAGE_EXPORT_DIRECTORY
*exports
;
1608 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1610 RtlEnterCriticalSection( &loader_section
);
1612 /* check if the module itself is invalid to return the proper error */
1613 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1614 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1615 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1617 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1618 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1619 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1623 ret
= STATUS_SUCCESS
;
1627 RtlLeaveCriticalSection( &loader_section
);
1632 /***********************************************************************
1635 * Check if a loaded native dll is a Wine fake dll.
1637 static BOOL
is_fake_dll( HANDLE handle
)
1639 static const char fakedll_signature
[] = "Wine placeholder DLL";
1640 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1641 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1643 LARGE_INTEGER offset
;
1645 offset
.QuadPart
= 0;
1646 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1647 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1648 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1649 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1650 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1655 /***********************************************************************
1656 * get_builtin_fullname
1658 * Build the full pathname for a builtin dll.
1660 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1662 static const WCHAR soW
[] = {'.','s','o',0};
1663 WCHAR
*p
, *fullname
;
1664 size_t i
, len
= strlen(filename
);
1666 /* check if path can correspond to the dll we have */
1667 if (path
&& (p
= strrchrW( path
, '\\' )))
1670 for (i
= 0; i
< len
; i
++)
1671 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1672 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1674 /* the filename matches, use path as the full path */
1676 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1678 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1685 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1686 (strlenW(system_dir
) + len
+ 1) * sizeof(WCHAR
) )))
1688 strcpyW( fullname
, system_dir
);
1689 ascii_to_unicode( fullname
+ strlenW(fullname
), filename
, len
+ 1 );
1695 /*************************************************************************
1698 static BOOL
is_16bit_builtin( HMODULE module
)
1700 const IMAGE_EXPORT_DIRECTORY
*exports
;
1703 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1704 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1707 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1711 /***********************************************************************
1712 * load_builtin_callback
1714 * Load a library in memory; callback function for wine_dll_register
1716 static void load_builtin_callback( void *module
, const char *filename
)
1718 static const WCHAR emptyW
[1];
1719 IMAGE_NT_HEADERS
*nt
;
1722 const WCHAR
*load_path
;
1726 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1729 if (!(nt
= RtlImageNtHeader( module
)))
1731 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1732 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1736 virtual_create_builtin_view( module
);
1738 /* create the MODREF */
1740 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1742 ERR( "can't load %s\n", filename
);
1743 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1747 wm
= alloc_module( module
, fullname
);
1748 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1751 ERR( "can't load %s\n", filename
);
1752 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1755 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1757 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1758 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1759 is_16bit_builtin( module
))
1763 load_path
= builtin_load_info
->load_path
;
1764 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1765 if (!load_path
) load_path
= emptyW
;
1766 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1768 /* the module has only be inserted in the load & memory order lists */
1769 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1770 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1771 /* FIXME: free the modref */
1772 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1777 builtin_load_info
->wm
= wm
;
1778 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1780 /* send the DLL load event */
1782 SERVER_START_REQ( load_dll
)
1784 req
->base
= wine_server_client_ptr( module
);
1785 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1786 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1787 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1788 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1789 wine_server_call( req
);
1793 /* setup relay debugging entry points */
1794 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1798 /***********************************************************************
1799 * set_security_cookie
1801 * Create a random security cookie for buffer overflow protection. Make
1802 * sure it does not accidentally match the default cookie value.
1804 static void set_security_cookie( void *module
, SIZE_T len
)
1807 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1811 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1812 if (!loadcfg
) return;
1813 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1814 if (!loadcfg
->SecurityCookie
) return;
1815 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1816 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1818 WARN( "security cookie %p outside of image %p-%p\n",
1819 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1823 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1824 TRACE( "initializing security cookie %p\n", cookie
);
1826 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1829 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1830 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1831 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1832 *cookie
= RtlRandom( &seed
);
1833 #ifdef DEFAULT_SECURITY_COOKIE_64
1834 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1836 *cookie
= RtlRandom( &seed
);
1837 /* fill up, but keep the highest word clear */
1838 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1846 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1848 IMAGE_NT_HEADERS
*nt
;
1850 IMAGE_BASE_RELOCATION
*rel
, *end
;
1851 const IMAGE_DATA_DIRECTORY
*relocs
;
1852 const IMAGE_SECTION_HEADER
*sec
;
1854 ULONG protect_old
[96], i
;
1856 nt
= RtlImageNtHeader( module
);
1857 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1859 assert( module
!= base
);
1861 /* no relocations are performed on non page-aligned binaries */
1862 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1863 return STATUS_SUCCESS
;
1865 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1866 return STATUS_SUCCESS
;
1868 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1870 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1872 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1874 return STATUS_CONFLICTING_ADDRESSES
;
1877 if (!relocs
->Size
) return STATUS_SUCCESS
;
1878 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1880 if (nt
->FileHeader
.NumberOfSections
> ARRAY_SIZE( protect_old
))
1881 return STATUS_INVALID_IMAGE_FORMAT
;
1883 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1884 nt
->FileHeader
.SizeOfOptionalHeader
);
1885 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1887 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1888 SIZE_T size
= sec
[i
].SizeOfRawData
;
1889 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1890 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1893 TRACE( "relocating from %p-%p to %p-%p\n",
1894 base
, base
+ len
, module
, (char *)module
+ len
);
1896 rel
= get_rva( module
, relocs
->VirtualAddress
);
1897 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1898 delta
= (char *)module
- base
;
1900 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1902 if (rel
->VirtualAddress
>= len
)
1904 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1905 return STATUS_ACCESS_VIOLATION
;
1907 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1908 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1909 (USHORT
*)(rel
+ 1), delta
);
1910 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1913 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1915 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1916 SIZE_T size
= sec
[i
].SizeOfRawData
;
1917 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1918 &size
, protect_old
[i
], &protect_old
[i
] );
1921 return STATUS_SUCCESS
;
1925 /* convert PE header to 64-bit when loading a 32-bit IL-only module into a 64-bit process */
1926 static BOOL
convert_to_pe64( HMODULE module
, const pe_image_info_t
*info
)
1928 static const ULONG copy_dirs
[] = { IMAGE_DIRECTORY_ENTRY_RESOURCE
,
1929 IMAGE_DIRECTORY_ENTRY_SECURITY
,
1930 IMAGE_DIRECTORY_ENTRY_BASERELOC
,
1931 IMAGE_DIRECTORY_ENTRY_DEBUG
,
1932 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
};
1933 IMAGE_OPTIONAL_HEADER32 hdr32
= { IMAGE_NT_OPTIONAL_HDR32_MAGIC
};
1934 IMAGE_OPTIONAL_HEADER64 hdr64
= { IMAGE_NT_OPTIONAL_HDR64_MAGIC
};
1935 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( module
);
1936 SIZE_T hdr_size
= min( sizeof(hdr32
), nt
->FileHeader
.SizeOfOptionalHeader
);
1937 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char *)&nt
->OptionalHeader
+ hdr_size
);
1938 SIZE_T size
= (char *)(nt
+ 1) + nt
->FileHeader
.NumberOfSections
* sizeof(*sec
) - (char *)module
;
1939 void *addr
= module
;
1942 TRACE( "%p\n", module
);
1944 if (size
> info
->header_size
) return FALSE
;
1945 if (NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, PAGE_READWRITE
, &old_prot
))
1948 memcpy( &hdr32
, &nt
->OptionalHeader
, hdr_size
);
1949 memcpy( &hdr64
, &hdr32
, offsetof( IMAGE_OPTIONAL_HEADER64
, SizeOfStackReserve
));
1950 hdr64
.Magic
= IMAGE_NT_OPTIONAL_HDR64_MAGIC
;
1951 hdr64
.AddressOfEntryPoint
= 0;
1952 hdr64
.ImageBase
= hdr32
.ImageBase
;
1953 hdr64
.SizeOfStackReserve
= hdr32
.SizeOfStackReserve
;
1954 hdr64
.SizeOfStackCommit
= hdr32
.SizeOfStackCommit
;
1955 hdr64
.SizeOfHeapReserve
= hdr32
.SizeOfHeapReserve
;
1956 hdr64
.SizeOfHeapCommit
= hdr32
.SizeOfHeapCommit
;
1957 hdr64
.LoaderFlags
= hdr32
.LoaderFlags
;
1958 hdr64
.NumberOfRvaAndSizes
= hdr32
.NumberOfRvaAndSizes
;
1959 for (i
= 0; i
< ARRAY_SIZE( copy_dirs
); i
++)
1960 hdr64
.DataDirectory
[copy_dirs
[i
]] = hdr32
.DataDirectory
[copy_dirs
[i
]];
1962 memmove( nt
+ 1, sec
, nt
->FileHeader
.NumberOfSections
* sizeof(*sec
) );
1963 nt
->FileHeader
.SizeOfOptionalHeader
= sizeof(hdr64
);
1964 nt
->OptionalHeader
= hdr64
;
1965 NtProtectVirtualMemory( NtCurrentProcess(), &addr
, &size
, old_prot
, &old_prot
);
1970 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
1971 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
1972 static BOOL
is_valid_binary( HMODULE module
, const pe_image_info_t
*info
)
1975 return info
->machine
== IMAGE_FILE_MACHINE_I386
;
1976 #elif defined(__arm__)
1977 return info
->machine
== IMAGE_FILE_MACHINE_ARM
||
1978 info
->machine
== IMAGE_FILE_MACHINE_THUMB
||
1979 info
->machine
== IMAGE_FILE_MACHINE_ARMNT
;
1980 #elif defined(_WIN64) /* support 32-bit IL-only images on 64-bit */
1982 if (info
->machine
== IMAGE_FILE_MACHINE_AMD64
) return TRUE
;
1984 if (info
->machine
== IMAGE_FILE_MACHINE_ARM64
) return TRUE
;
1986 if (!info
->contains_code
) return TRUE
;
1987 if (info
->image_flags
& IMAGE_FLAGS_ComPlusNativeReady
)
1989 if (!convert_to_pe64( module
, info
)) return FALSE
;
1991 if (info
->image_flags
& IMAGE_FLAGS_ComPlusILOnly
) return TRUE
;
1994 return FALSE
; /* no wow64 support on other platforms */
1999 /******************************************************************************
2000 * load_native_dll (internal)
2002 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
2003 DWORD flags
, WINE_MODREF
** pwm
, struct stat
*st
)
2008 IMAGE_NT_HEADERS
*nt
;
2012 pe_image_info_t image_info
;
2014 TRACE("Trying native dll %s\n", debugstr_w(name
));
2017 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
2018 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
2019 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
2020 if (status
!= STATUS_SUCCESS
) return status
;
2023 status
= virtual_map_section( mapping
, &module
, 0, 0, NULL
, &len
, PAGE_EXECUTE_READ
, &image_info
);
2026 if ((status
== STATUS_SUCCESS
|| status
== STATUS_IMAGE_NOT_AT_BASE
) &&
2027 !is_valid_binary( module
, &image_info
))
2029 NtUnmapViewOfSection( NtCurrentProcess(), module
);
2030 return STATUS_INVALID_IMAGE_FORMAT
;
2033 /* perform base relocation, if necessary */
2035 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
2036 status
= perform_relocations( module
, len
);
2038 if (status
!= STATUS_SUCCESS
)
2040 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2044 /* create the MODREF */
2046 if (!(wm
= alloc_module( module
, name
)))
2048 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2049 return STATUS_NO_MEMORY
;
2052 wm
->dev
= st
->st_dev
;
2053 wm
->ino
= st
->st_ino
;
2054 if (image_info
.loader_flags
) wm
->ldr
.Flags
|= LDR_COR_IMAGE
;
2055 if (image_info
.image_flags
& IMAGE_FLAGS_ComPlusILOnly
) wm
->ldr
.Flags
|= LDR_COR_ILONLY
;
2057 set_security_cookie( module
, len
);
2061 nt
= RtlImageNtHeader( module
);
2063 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
2064 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
2065 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
2067 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
2068 status
= fixup_imports_ilonly( wm
, load_path
, &wm
->ldr
.EntryPoint
);
2070 status
= fixup_imports( wm
, load_path
);
2071 if (status
!= STATUS_SUCCESS
)
2073 /* the module has only be inserted in the load & memory order lists */
2074 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2075 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2077 /* FIXME: there are several more dangling references
2078 * left. Including dlls loaded by this dll before the
2079 * failed one. Unrolling is rather difficult with the
2080 * current structure and we can leave them lying
2081 * around with no problems, so we don't care.
2082 * As these might reference our wm, we don't free it.
2088 /* send DLL load event */
2090 SERVER_START_REQ( load_dll
)
2092 req
->base
= wine_server_client_ptr( module
);
2093 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
2094 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
2095 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
2096 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
2097 wine_server_call( req
);
2101 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
2103 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
2105 wm
->ldr
.LoadCount
= 1;
2107 return STATUS_SUCCESS
;
2111 /***********************************************************************
2114 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
2115 DWORD flags
, WINE_MODREF
** pwm
)
2117 char error
[256], dllname
[MAX_PATH
];
2118 const WCHAR
*name
, *p
;
2121 struct builtin_load_info info
, *prev_info
;
2123 /* Fix the name in case we have a full path and extension */
2125 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
2126 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
2128 /* load_library will modify info.status. Note also that load_library can be
2129 * called several times, if the .so file we're loading has dependencies.
2130 * info.status will gather all the errors we may get while loading all these
2133 info
.load_path
= load_path
;
2134 info
.filename
= NULL
;
2135 info
.status
= STATUS_SUCCESS
;
2138 if (file
) /* we have a real file, try to load it */
2140 UNICODE_STRING nt_name
;
2141 ANSI_STRING unix_name
;
2143 TRACE("Trying built-in %s\n", debugstr_w(path
));
2145 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
2146 return STATUS_DLL_NOT_FOUND
;
2148 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
2150 RtlFreeUnicodeString( &nt_name
);
2151 return STATUS_DLL_NOT_FOUND
;
2153 prev_info
= builtin_load_info
;
2154 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
2155 builtin_load_info
= &info
;
2156 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
2157 builtin_load_info
= prev_info
;
2158 RtlFreeUnicodeString( &nt_name
);
2159 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
2162 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
2163 return STATUS_INVALID_IMAGE_FORMAT
;
2170 TRACE("Trying built-in %s\n", debugstr_w(name
));
2172 /* we don't want to depend on the current codepage here */
2173 len
= strlenW( name
) + 1;
2174 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
2175 for (i
= 0; i
< len
; i
++)
2177 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
2178 dllname
[i
] = (char)name
[i
];
2179 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
2182 prev_info
= builtin_load_info
;
2183 builtin_load_info
= &info
;
2184 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
2185 builtin_load_info
= prev_info
;
2190 /* The file does not exist -> WARN() */
2191 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
2192 return STATUS_DLL_NOT_FOUND
;
2194 /* ERR() for all other errors (missing functions, ...) */
2195 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
2196 return STATUS_PROCEDURE_NOT_FOUND
;
2200 if (info
.status
!= STATUS_SUCCESS
)
2202 wine_dll_unload( handle
);
2208 PLIST_ENTRY mark
, entry
;
2210 /* The constructor wasn't called, this means the .so is already
2211 * loaded under a different name. Try to find the wm for it. */
2213 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2214 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2216 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2217 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
2219 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2220 TRACE( "Found %s at %p for builtin %s\n",
2221 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
2225 wine_dll_unload( handle
); /* release the libdl refcount */
2226 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
2227 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
2231 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
2232 info
.wm
->ldr
.LoadCount
= 1;
2233 info
.wm
->ldr
.SectionHandle
= handle
;
2237 return STATUS_SUCCESS
;
2241 /***********************************************************************
2244 * Find the full path (if any) of the dll from the activation context.
2246 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2248 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2249 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2251 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2252 ACTCTX_SECTION_KEYED_DATA data
;
2253 UNICODE_STRING nameW
;
2255 SIZE_T needed
, size
= 1024;
2258 RtlInitUnicodeString( &nameW
, libname
);
2259 data
.cbSize
= sizeof(data
);
2260 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2261 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2263 if (status
!= STATUS_SUCCESS
) return status
;
2267 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2269 status
= STATUS_NO_MEMORY
;
2272 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2273 AssemblyDetailedInformationInActivationContext
,
2274 info
, size
, &needed
);
2275 if (status
== STATUS_SUCCESS
) break;
2276 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2277 RtlFreeHeap( GetProcessHeap(), 0, info
);
2279 /* restart with larger buffer */
2282 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2284 status
= STATUS_SXS_KEY_NOT_FOUND
;
2288 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2290 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2293 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2295 /* manifest name does not match directory name, so it's not a global
2296 * windows/winsxs manifest; use the manifest directory name instead */
2297 dirlen
= p
- info
->lpAssemblyManifestPath
;
2298 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2299 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2301 status
= STATUS_NO_MEMORY
;
2304 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2306 strcpyW( p
, libname
);
2311 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2312 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2314 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2316 status
= STATUS_NO_MEMORY
;
2319 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2321 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2322 p
+= ARRAY_SIZE( winsxsW
);
2323 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2324 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2326 strcpyW( p
, libname
);
2328 RtlFreeHeap( GetProcessHeap(), 0, info
);
2329 RtlReleaseActivationContext( data
.hActCtx
);
2334 /***********************************************************************
2337 * Open a file for a new dll. Helper for find_dll_file.
2339 static HANDLE
open_dll_file( UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, struct stat
*st
)
2341 OBJECT_ATTRIBUTES attr
;
2344 int fd
, needs_close
;
2346 attr
.Length
= sizeof(attr
);
2347 attr
.RootDirectory
= 0;
2348 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2349 attr
.ObjectName
= nt_name
;
2350 attr
.SecurityDescriptor
= NULL
;
2351 attr
.SecurityQualityOfService
= NULL
;
2352 if (NtOpenFile( &handle
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2353 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
))
2356 if (!server_get_unix_fd( handle
, 0, &fd
, &needs_close
, NULL
, NULL
))
2359 if (needs_close
) close( fd
);
2360 if ((*pwm
= find_fileid_module( handle
, st
)))
2362 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name
->Buffer
),
2363 (*pwm
)->ldr
.BaseAddress
, debugstr_w( (*pwm
)->ldr
.FullDllName
.Buffer
));
2372 /***********************************************************************
2375 * Find the file (or already loaded module) for a given dll name.
2377 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2378 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
,
2379 HANDLE
*handle
, struct stat
*st
)
2381 UNICODE_STRING nt_name
;
2382 WCHAR
*file_part
, *ext
, *dllname
;
2385 /* first append .dll if needed */
2389 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2391 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2392 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2393 return STATUS_NO_MEMORY
;
2394 strcpyW( dllname
, libname
);
2395 strcatW( dllname
, dllW
);
2399 nt_name
.Buffer
= NULL
;
2401 if (!contains_path( libname
))
2404 WCHAR
*fullname
= NULL
;
2406 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2408 status
= find_actctx_dll( libname
, &fullname
);
2409 if (status
== STATUS_SUCCESS
)
2411 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2412 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2413 libname
= dllname
= fullname
;
2415 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2417 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2422 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2424 /* we need to search for it */
2425 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2428 if (len
>= *size
) goto overflow
;
2429 if ((*pwm
= find_fullname_module( filename
))) goto found
;
2431 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2433 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2434 return STATUS_NO_MEMORY
;
2436 *handle
= open_dll_file( &nt_name
, pwm
, st
);
2442 if (!contains_path( libname
))
2444 /* if libname doesn't contain a path at all, we simply return the name as is,
2445 * to be loaded as builtin */
2446 len
= strlenW(libname
) * sizeof(WCHAR
);
2447 if (len
>= *size
) goto overflow
;
2448 strcpyW( filename
, libname
);
2453 /* absolute path name, or relative path name but not found above */
2455 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2457 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2458 return STATUS_NO_MEMORY
;
2460 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2461 if (len
>= *size
) goto overflow
;
2462 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2463 if (!(*pwm
= find_fullname_module( filename
)))
2464 *handle
= open_dll_file( &nt_name
, pwm
, st
);
2467 RtlFreeUnicodeString( &nt_name
);
2468 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2469 return STATUS_SUCCESS
;
2472 RtlFreeUnicodeString( &nt_name
);
2473 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2474 *size
= len
+ sizeof(WCHAR
);
2475 return STATUS_BUFFER_TOO_SMALL
;
2479 /***********************************************************************
2480 * load_dll (internal)
2482 * Load a PE style module according to the load order.
2483 * The loader_section must be locked while calling this function.
2485 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2487 enum loadorder loadorder
;
2491 WINE_MODREF
*main_exe
;
2496 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2500 size
= sizeof(buffer
);
2503 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
, &st
);
2504 if (nts
== STATUS_SUCCESS
) break;
2505 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2506 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2507 /* grow the buffer and retry */
2508 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2511 if (*pwm
) /* found already loaded module */
2513 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2515 TRACE("Found %s for %s at %p, count=%d\n",
2516 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2517 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2518 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2519 return STATUS_SUCCESS
;
2522 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2523 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2525 if (handle
&& is_fake_dll( handle
))
2527 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2535 nts
= STATUS_NO_MEMORY
;
2538 nts
= STATUS_DLL_NOT_FOUND
;
2541 case LO_NATIVE_BUILTIN
:
2542 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2545 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
, &st
);
2546 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2547 /* not in PE format, maybe it's a builtin */
2548 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2550 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2551 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2554 case LO_BUILTIN_NATIVE
:
2555 case LO_DEFAULT
: /* default is builtin,native */
2556 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2557 if (!handle
) break; /* nothing else we can try */
2558 /* file is not a builtin library, try without using the specified file */
2559 if (nts
!= STATUS_SUCCESS
)
2560 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2561 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2562 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2564 /* stub-only dll, try native */
2565 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2566 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2567 nts
= STATUS_DLL_NOT_FOUND
;
2569 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2570 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
, &st
);
2574 if (nts
== STATUS_SUCCESS
)
2576 /* Initialize DLL just loaded */
2577 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2578 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2579 (*pwm
)->ldr
.BaseAddress
);
2580 if (handle
) NtClose( handle
);
2581 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2585 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2586 if (handle
) NtClose( handle
);
2587 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2591 /******************************************************************
2592 * LdrLoadDll (NTDLL.@)
2594 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2595 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2600 RtlEnterCriticalSection( &loader_section
);
2602 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2603 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2605 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2607 nts
= process_attach( wm
, NULL
);
2608 if (nts
!= STATUS_SUCCESS
)
2610 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2614 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2616 RtlLeaveCriticalSection( &loader_section
);
2621 /******************************************************************
2622 * LdrGetDllHandle (NTDLL.@)
2624 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2634 RtlEnterCriticalSection( &loader_section
);
2636 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2639 size
= sizeof(buffer
);
2642 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, &handle
, &st
);
2643 if (handle
) NtClose( handle
);
2644 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2645 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2646 /* grow the buffer and retry */
2647 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2649 status
= STATUS_NO_MEMORY
;
2654 if (status
== STATUS_SUCCESS
)
2656 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2657 else status
= STATUS_DLL_NOT_FOUND
;
2660 RtlLeaveCriticalSection( &loader_section
);
2661 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2666 /******************************************************************
2667 * LdrAddRefDll (NTDLL.@)
2669 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2671 NTSTATUS ret
= STATUS_SUCCESS
;
2674 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2676 RtlEnterCriticalSection( &loader_section
);
2678 if ((wm
= get_modref( module
)))
2680 if (flags
& LDR_ADDREF_DLL_PIN
)
2681 wm
->ldr
.LoadCount
= -1;
2683 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2684 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2686 else ret
= STATUS_INVALID_PARAMETER
;
2688 RtlLeaveCriticalSection( &loader_section
);
2693 /***********************************************************************
2694 * LdrProcessRelocationBlock (NTDLL.@)
2696 * Apply relocations to a given page of a mapped PE image.
2698 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2699 USHORT
*relocs
, INT_PTR delta
)
2703 USHORT offset
= *relocs
& 0xfff;
2704 int type
= *relocs
>> 12;
2707 case IMAGE_REL_BASED_ABSOLUTE
:
2709 case IMAGE_REL_BASED_HIGH
:
2710 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2712 case IMAGE_REL_BASED_LOW
:
2713 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2715 case IMAGE_REL_BASED_HIGHLOW
:
2716 *(int *)((char *)page
+ offset
) += delta
;
2719 case IMAGE_REL_BASED_DIR64
:
2720 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2722 #elif defined(__arm__)
2723 case IMAGE_REL_BASED_THUMB_MOV32
:
2725 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2726 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2727 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2730 if ((inst
& 0x8000fbf0) != 0x0000f240)
2731 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2733 imm16
+= LOWORD(delta
);
2734 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2735 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2736 ((imm16
>> 12) & 0x000f) +
2737 ((imm16
<< 20) & 0x70000000) +
2738 ((imm16
<< 16) & 0xff0000);
2742 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2743 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2744 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2746 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2747 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2751 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2752 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2753 ((imm16
>> 1) & 0x0400) +
2754 ((imm16
>> 12) & 0x000f) +
2755 ((imm16
<< 20) & 0x70000000) +
2756 ((imm16
<< 16) & 0xff0000);
2762 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2767 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2771 /******************************************************************
2772 * LdrQueryProcessModuleInformation
2775 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2776 ULONG buf_size
, ULONG
* req_size
)
2778 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2779 ULONG size
= sizeof(ULONG
);
2780 NTSTATUS nts
= STATUS_SUCCESS
;
2783 PLIST_ENTRY mark
, entry
;
2787 smi
->ModulesCount
= 0;
2789 RtlEnterCriticalSection( &loader_section
);
2790 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2791 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2793 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2794 size
+= sizeof(*sm
);
2795 if (size
<= buf_size
)
2797 sm
->Reserved1
= 0; /* FIXME */
2798 sm
->Reserved2
= 0; /* FIXME */
2799 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2800 sm
->ImageSize
= mod
->SizeOfImage
;
2801 sm
->Flags
= mod
->Flags
;
2803 sm
->Rank
= 0; /* FIXME */
2804 sm
->Unknown
= 0; /* FIXME */
2806 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2807 str
.Buffer
= (char*)sm
->Name
;
2808 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2809 ptr
= strrchr(str
.Buffer
, '\\');
2810 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2812 smi
->ModulesCount
++;
2815 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2817 RtlLeaveCriticalSection( &loader_section
);
2819 if (req_size
) *req_size
= size
;
2825 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2831 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2833 RtlInitUnicodeString( &str
, name
);
2835 size
= sizeof(buffer
) - sizeof(WCHAR
);
2836 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2839 if (info
->Type
!= REG_DWORD
)
2841 buffer
[size
/ sizeof(WCHAR
)] = 0;
2842 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2844 else memcpy( value
, info
->Data
, sizeof(*value
) );
2848 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2849 void *data
, ULONG in_size
, ULONG
*out_size
)
2855 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2856 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2858 RtlInitUnicodeString( &str
, name
);
2860 size
= info_size
+ in_size
;
2861 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2862 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2863 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2864 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2866 if (out_size
) *out_size
= info
->DataLength
;
2867 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2869 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2874 /******************************************************************
2875 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2877 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2878 void *data
, ULONG in_size
, ULONG
*out_size
)
2880 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2881 'S','o','f','t','w','a','r','e','\\',
2882 'M','i','c','r','o','s','o','f','t','\\',
2883 'W','i','n','d','o','w','s',' ','N','T','\\',
2884 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2885 'I','m','a','g','e',' ','F','i','l','e',' ',
2886 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2887 WCHAR path
[MAX_PATH
+ ARRAY_SIZE( optionsW
)];
2888 OBJECT_ATTRIBUTES attr
;
2889 UNICODE_STRING name_str
;
2895 attr
.Length
= sizeof(attr
);
2896 attr
.RootDirectory
= 0;
2897 attr
.ObjectName
= &name_str
;
2898 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2899 attr
.SecurityDescriptor
= NULL
;
2900 attr
.SecurityQualityOfService
= NULL
;
2902 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2903 else p
= key
->Buffer
;
2904 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2905 name_str
.Buffer
= path
;
2906 name_str
.Length
= sizeof(optionsW
) + len
;
2907 name_str
.MaximumLength
= name_str
.Length
;
2908 memcpy( path
, optionsW
, sizeof(optionsW
) );
2909 memcpy( path
+ ARRAY_SIZE( optionsW
), p
, len
);
2910 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2912 if (type
== REG_DWORD
)
2914 if (out_size
) *out_size
= sizeof(ULONG
);
2915 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2916 else status
= STATUS_BUFFER_OVERFLOW
;
2918 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2925 /******************************************************************
2926 * RtlDllShutdownInProgress (NTDLL.@)
2928 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2930 return process_detaching
;
2933 /****************************************************************************
2934 * LdrResolveDelayLoadedAPI (NTDLL.@)
2936 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2937 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2938 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2940 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2941 DELAYLOAD_INFO delayinfo
;
2949 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2951 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2952 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2953 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2954 name
= get_rva(base
, desc
->DllNameRVA
);
2959 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2961 nts
= STATUS_NO_MEMORY
;
2964 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2965 RtlFreeUnicodeString(&mod
);
2969 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2970 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2973 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2976 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2977 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2981 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2986 delayinfo
.Size
= sizeof(delayinfo
);
2987 delayinfo
.DelayloadDescriptor
= desc
;
2988 delayinfo
.ThunkAddress
= addr
;
2989 delayinfo
.TargetDllName
= name
;
2990 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2991 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2992 delayinfo
.TargetModuleBase
= *phmod
;
2993 delayinfo
.Unused
= NULL
;
2994 delayinfo
.LastError
= nts
;
2995 return dllhook(4, &delayinfo
);
2998 /******************************************************************
2999 * LdrShutdownProcess (NTDLL.@)
3002 void WINAPI
LdrShutdownProcess(void)
3005 process_detaching
= TRUE
;
3010 /******************************************************************
3011 * RtlExitUserProcess (NTDLL.@)
3013 void WINAPI
RtlExitUserProcess( DWORD status
)
3015 RtlEnterCriticalSection( &loader_section
);
3016 RtlAcquirePebLock();
3017 NtTerminateProcess( 0, status
);
3018 LdrShutdownProcess();
3019 NtTerminateProcess( GetCurrentProcess(), status
);
3023 /******************************************************************
3024 * LdrShutdownThread (NTDLL.@)
3027 void WINAPI
LdrShutdownThread(void)
3029 PLIST_ENTRY mark
, entry
;
3036 /* don't do any detach calls if process is exiting */
3037 if (process_detaching
) return;
3039 RtlEnterCriticalSection( &loader_section
);
3041 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3042 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
3044 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
3045 InInitializationOrderModuleList
);
3046 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
3048 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
3051 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
3052 DLL_THREAD_DETACH
, NULL
);
3055 RtlAcquirePebLock();
3056 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
3057 RtlReleasePebLock();
3059 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
3061 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
3062 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
3064 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
3065 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
3066 RtlLeaveCriticalSection( &loader_section
);
3070 /***********************************************************************
3074 static void free_modref( WINE_MODREF
*wm
)
3076 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
3077 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
3078 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
3079 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
3081 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
3082 if (!TRACE_ON(module
))
3083 TRACE_(loaddll
)("Unloaded module %s : %s\n",
3084 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
3085 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
3087 SERVER_START_REQ( unload_dll
)
3089 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
3090 wine_server_call( req
);
3094 free_tls_slot( &wm
->ldr
);
3095 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
3096 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
3097 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
3098 if (cached_modref
== wm
) cached_modref
= NULL
;
3099 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
3100 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
3101 RtlFreeHeap( GetProcessHeap(), 0, wm
);
3104 /***********************************************************************
3105 * MODULE_FlushModrefs
3107 * Remove all unused modrefs and call the internal unloading routines
3108 * for the library type.
3110 * The loader_section must be locked while calling this function.
3112 static void MODULE_FlushModrefs(void)
3114 PLIST_ENTRY mark
, entry
, prev
;
3118 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3119 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3121 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
3122 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3123 prev
= entry
->Blink
;
3124 if (!mod
->LoadCount
) free_modref( wm
);
3127 /* check load order list too for modules that haven't been initialized yet */
3128 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3129 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3131 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
3132 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3133 prev
= entry
->Blink
;
3134 if (!mod
->LoadCount
) free_modref( wm
);
3138 /***********************************************************************
3139 * MODULE_DecRefCount
3141 * The loader_section must be locked while calling this function.
3143 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
3147 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
3150 if ( wm
->ldr
.LoadCount
<= 0 )
3153 --wm
->ldr
.LoadCount
;
3154 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3156 if ( wm
->ldr
.LoadCount
== 0 )
3158 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
3160 for ( i
= 0; i
< wm
->nDeps
; i
++ )
3162 MODULE_DecRefCount( wm
->deps
[i
] );
3164 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
3168 /******************************************************************
3169 * LdrUnloadDll (NTDLL.@)
3173 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
3176 NTSTATUS retv
= STATUS_SUCCESS
;
3178 if (process_detaching
) return retv
;
3180 TRACE("(%p)\n", hModule
);
3182 RtlEnterCriticalSection( &loader_section
);
3185 if ((wm
= get_modref( hModule
)) != NULL
)
3187 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
3189 /* Recursively decrement reference counts */
3190 MODULE_DecRefCount( wm
);
3192 /* Call process detach notifications */
3193 if ( free_lib_count
<= 1 )
3196 MODULE_FlushModrefs();
3202 retv
= STATUS_DLL_NOT_FOUND
;
3206 RtlLeaveCriticalSection( &loader_section
);
3211 /***********************************************************************
3212 * RtlImageNtHeader (NTDLL.@)
3214 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
3216 IMAGE_NT_HEADERS
*ret
;
3220 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
3223 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
3225 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
3226 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
3238 /***********************************************************************
3241 * Attach to all the loaded dlls.
3242 * If this is the first time, perform the full process initialization.
3244 NTSTATUS
attach_dlls( CONTEXT
*context
, void **entry
)
3248 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3250 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
3252 if (process_detaching
) return STATUS_SUCCESS
;
3254 RtlEnterCriticalSection( &loader_section
);
3256 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3259 if (!imports_fixup_done
)
3262 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
3263 status
= fixup_imports_ilonly( wm
, load_path
, entry
);
3265 status
= fixup_imports( wm
, load_path
);
3269 ERR( "Importing dlls for %s failed, status %x\n",
3270 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3271 NtTerminateProcess( GetCurrentProcess(), status
);
3273 imports_fixup_done
= TRUE
;
3276 RtlAcquirePebLock();
3277 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
3278 RtlReleasePebLock();
3280 if (!(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
)) /* first time around */
3282 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3284 ERR( "TLS init failed when loading %s, status %x\n",
3285 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3286 NtTerminateProcess( GetCurrentProcess(), status
);
3288 if ((status
= process_attach( wm
, context
)) != STATUS_SUCCESS
)
3290 if (last_failed_modref
)
3291 ERR( "%s failed to initialize, aborting\n",
3292 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3293 ERR( "Initializing dlls for %s failed, status %x\n",
3294 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3295 NtTerminateProcess( GetCurrentProcess(), status
);
3297 attach_implicitly_loaded_dlls( context
);
3298 virtual_release_address_space();
3302 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3303 NtTerminateThread( GetCurrentThread(), status
);
3307 RtlLeaveCriticalSection( &loader_section
);
3308 return STATUS_SUCCESS
;
3312 /***********************************************************************
3313 * load_global_options
3315 static void load_global_options(void)
3317 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
3318 'S','y','s','t','e','m','\\',
3319 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3320 'C','o','n','t','r','o','l','\\',
3321 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3322 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3323 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};
3324 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3325 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3326 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};
3327 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};
3329 OBJECT_ATTRIBUTES attr
;
3330 UNICODE_STRING name_str
;
3334 attr
.Length
= sizeof(attr
);
3335 attr
.RootDirectory
= 0;
3336 attr
.ObjectName
= &name_str
;
3337 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3338 attr
.SecurityDescriptor
= NULL
;
3339 attr
.SecurityQualityOfService
= NULL
;
3340 RtlInitUnicodeString( &name_str
, sessionW
);
3342 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3344 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3346 query_dword_option( hkey
, critsectW
, &value
);
3347 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3349 query_dword_option( hkey
, heapresW
, &value
);
3350 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3352 query_dword_option( hkey
, heapcommitW
, &value
);
3353 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3355 query_dword_option( hkey
, decommittotalW
, &value
);
3356 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3358 query_dword_option( hkey
, decommitfreeW
, &value
);
3359 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3365 /******************************************************************
3366 * LdrInitializeThunk (NTDLL.@)
3369 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3370 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3372 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3375 PEB
*peb
= NtCurrentTeb()->Peb
;
3377 kernel32_start_process
= kernel_start
;
3379 /* allocate the modref for the main exe (if not already done) */
3380 wm
= get_modref( peb
->ImageBaseAddress
);
3382 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3384 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3388 peb
->LoaderLock
= &loader_section
;
3389 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3390 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3391 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3392 version_init( wm
->ldr
.FullDllName
.Buffer
);
3393 virtual_set_large_address_space();
3395 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3396 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3397 heap_set_debug_flags( GetProcessHeap() );
3399 /* the main exe needs to be the first in the load order list */
3400 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3401 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3402 RemoveEntryList( &wm
->ldr
.InMemoryOrderModuleList
);
3403 InsertHeadList( &peb
->LdrData
->InMemoryOrderModuleList
, &wm
->ldr
.InMemoryOrderModuleList
);
3405 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL
)) != STATUS_SUCCESS
)
3407 ERR( "Main exe initialization for %s failed, status %x\n",
3408 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3409 NtTerminateProcess( GetCurrentProcess(), status
);
3411 server_init_process_done();
3415 /***********************************************************************
3416 * RtlImageDirectoryEntryToData (NTDLL.@)
3418 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3420 const IMAGE_NT_HEADERS
*nt
;
3423 if ((ULONG_PTR
)module
& 1) image
= FALSE
; /* mapped as data file */
3424 module
= (HMODULE
)((ULONG_PTR
)module
& ~3);
3425 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3426 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3428 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3430 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3431 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3432 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3433 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3435 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3437 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3439 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3440 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3441 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3442 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3446 /* not mapped as image, need to find the section containing the virtual address */
3447 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3451 /***********************************************************************
3452 * RtlImageRvaToSection (NTDLL.@)
3454 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3455 HMODULE module
, DWORD rva
)
3458 const IMAGE_SECTION_HEADER
*sec
;
3460 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3461 nt
->FileHeader
.SizeOfOptionalHeader
);
3462 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3464 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3465 return (PIMAGE_SECTION_HEADER
)sec
;
3471 /***********************************************************************
3472 * RtlImageRvaToVa (NTDLL.@)
3474 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3475 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3477 IMAGE_SECTION_HEADER
*sec
;
3479 if (section
&& *section
) /* try this section first */
3482 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3485 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3487 if (section
) *section
= sec
;
3488 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3492 /***********************************************************************
3493 * RtlPcToFileHeader (NTDLL.@)
3495 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3500 RtlEnterCriticalSection( &loader_section
);
3501 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3502 RtlLeaveCriticalSection( &loader_section
);
3508 /***********************************************************************
3509 * NtLoadDriver (NTDLL.@)
3510 * ZwLoadDriver (NTDLL.@)
3512 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3514 FIXME("(%p), stub!\n",DriverServiceName
);
3515 return STATUS_NOT_IMPLEMENTED
;
3519 /***********************************************************************
3520 * NtUnloadDriver (NTDLL.@)
3521 * ZwUnloadDriver (NTDLL.@)
3523 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3525 FIXME("(%p), stub!\n",DriverServiceName
);
3526 return STATUS_NOT_IMPLEMENTED
;
3530 /******************************************************************
3533 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3535 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3540 /***********************************************************************
3541 * __wine_process_init
3543 void __wine_process_init(void)
3545 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3549 ANSI_STRING func_name
;
3550 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3554 /* retrieve current umask */
3555 FILE_umask
= umask(0777);
3556 umask( FILE_umask
);
3558 load_global_options();
3560 /* setup the load callback and create ntdll modref */
3561 wine_dll_set_callback( load_builtin_callback
);
3563 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3565 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3568 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3569 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3570 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3572 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);