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 HANDLE main_exe_file
;
121 static UINT tls_module_count
; /* number of modules with TLS directory */
122 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
123 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
125 static RTL_CRITICAL_SECTION loader_section
;
126 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
128 0, 0, &loader_section
,
129 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
130 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
132 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
134 static WINE_MODREF
*cached_modref
;
135 static WINE_MODREF
*current_modref
;
136 static WINE_MODREF
*last_failed_modref
;
138 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
139 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
140 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
141 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
142 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
143 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
145 /* convert PE image VirtualAddress to Real Address */
146 static inline void *get_rva( HMODULE module
, DWORD va
)
148 return (void *)((char *)module
+ va
);
151 /* check whether the file name contains a path */
152 static inline BOOL
contains_path( LPCWSTR name
)
154 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
157 /* convert from straight ASCII to Unicode without depending on the current codepage */
158 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
160 while (len
--) *dst
++ = (unsigned char)*src
++;
164 /*************************************************************************
165 * call_dll_entry_point
167 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
168 * their entry point, so we need a small asm wrapper. Testing indicates
169 * that only modifying esi leads to a crash, so use this one to backup
170 * ebp while running the dll entry proc.
173 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
174 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
176 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
177 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
179 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
181 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
183 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
185 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
187 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
191 "movl 8(%ebp),%eax\n\t"
194 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
195 "leal -12(%ebp),%esp\n\t"
197 __ASM_CFI(".cfi_same_value %edi\n\t")
199 __ASM_CFI(".cfi_same_value %esi\n\t")
201 __ASM_CFI(".cfi_same_value %ebx\n\t")
203 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
204 __ASM_CFI(".cfi_same_value %ebp\n\t")
207 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
208 UINT reason
, void *reserved
)
210 return proc( module
, reason
, reserved
);
212 #endif /* __i386__ */
215 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
216 /*************************************************************************
219 * Entry point for stub functions.
221 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
223 EXCEPTION_RECORD rec
;
225 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
226 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
227 rec
.ExceptionRecord
= NULL
;
228 rec
.ExceptionAddress
= ret_addr
;
229 rec
.NumberParameters
= 2;
230 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
231 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
232 for (;;) RtlRaiseException( &rec
);
236 #include "pshpack1.h"
240 BYTE pushl1
; /* pushl $name */
242 BYTE pushl2
; /* pushl $dll */
244 BYTE call
; /* call stub_entry_point */
247 #elif defined(__arm__)
250 DWORD ldr_r0
; /* ldr r0, $dll */
251 DWORD ldr_r1
; /* ldr r1, $name */
252 DWORD mov_r2_lr
; /* mov r2, lr */
253 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
258 #elif defined(__aarch64__)
261 DWORD ldr_x0
; /* ldr x0, $dll */
262 DWORD ldr_x1
; /* ldr x1, $name */
263 DWORD mov_x2_lr
; /* mov x2, lr */
264 DWORD ldr_x16
; /* ldr x16, $entry */
265 DWORD br_x16
; /* br x16 */
273 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
275 BYTE movq_rsi
[2]; /* movq $name,%rsi */
277 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
278 BYTE movq_rax
[2]; /* movq $entry, %rax */
280 BYTE jmpq_rax
[2]; /* jmp %rax */
285 /*************************************************************************
288 * Allocate a stub entry point.
290 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
292 #define MAX_SIZE 65536
293 static struct stub
*stubs
;
294 static unsigned int nb_stubs
;
297 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
301 SIZE_T size
= MAX_SIZE
;
302 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
303 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
306 stub
= &stubs
[nb_stubs
++];
308 stub
->pushl1
= 0x68; /* pushl $name */
310 stub
->pushl2
= 0x68; /* pushl $dll */
312 stub
->call
= 0xe8; /* call stub_entry_point */
313 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
314 #elif defined(__arm__)
315 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
316 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
317 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
318 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
321 stub
->entry
= stub_entry_point
;
322 #elif defined(__aarch64__)
323 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
324 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
325 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
326 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
327 stub
->br_x16
= 0xd61f0200; /* br x16 */
330 stub
->entry
= stub_entry_point
;
332 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
333 stub
->movq_rdi
[1] = 0xbf;
335 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
336 stub
->movq_rsi
[1] = 0xbe;
338 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
339 stub
->movq_rsp_rdx
[1] = 0x8b;
340 stub
->movq_rsp_rdx
[2] = 0x14;
341 stub
->movq_rsp_rdx
[3] = 0x24;
342 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
343 stub
->movq_rax
[1] = 0xb8;
344 stub
->entry
= stub_entry_point
;
345 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
346 stub
->jmpq_rax
[1] = 0xe0;
348 return (ULONG_PTR
)stub
;
352 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
353 #endif /* __i386__ */
355 /* call ldr notifications */
356 static void call_ldr_notifications( ULONG reason
, LDR_MODULE
*module
)
358 struct ldr_notification
*notify
, *notify_next
;
359 LDR_DLL_NOTIFICATION_DATA data
;
361 data
.Loaded
.Flags
= 0;
362 data
.Loaded
.FullDllName
= &module
->FullDllName
;
363 data
.Loaded
.BaseDllName
= &module
->BaseDllName
;
364 data
.Loaded
.DllBase
= module
->BaseAddress
;
365 data
.Loaded
.SizeOfImage
= module
->SizeOfImage
;
367 LIST_FOR_EACH_ENTRY_SAFE( notify
, notify_next
, &ldr_notifications
, struct ldr_notification
, entry
)
369 TRACE_(relay
)("\1Call LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
370 notify
->callback
, reason
, &data
, notify
->context
);
372 notify
->callback(reason
, &data
, notify
->context
);
374 TRACE_(relay
)("\1Ret LDR notification callback (proc=%p,reason=%u,data=%p,context=%p)\n",
375 notify
->callback
, reason
, &data
, notify
->context
);
379 /*************************************************************************
382 * Looks for the referenced HMODULE in the current process
383 * The loader_section must be locked while calling this function.
385 static WINE_MODREF
*get_modref( HMODULE hmod
)
387 PLIST_ENTRY mark
, entry
;
390 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
392 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
393 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
395 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
396 if (mod
->BaseAddress
== hmod
)
397 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
403 /**********************************************************************
404 * find_basename_module
406 * Find a module from its base name.
407 * The loader_section must be locked while calling this function
409 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
411 PLIST_ENTRY mark
, entry
;
413 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
414 return cached_modref
;
416 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
417 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
419 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
420 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
422 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
423 return cached_modref
;
430 /**********************************************************************
431 * find_fullname_module
433 * Find a module from its full path name.
434 * The loader_section must be locked while calling this function
436 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
438 PLIST_ENTRY mark
, entry
;
440 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
441 return cached_modref
;
443 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
444 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
446 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
447 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
449 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
450 return cached_modref
;
457 /**********************************************************************
460 * Find a module from its file id.
461 * The loader_section must be locked while calling this function
463 static WINE_MODREF
*find_fileid_module( HANDLE handle
, struct stat
*st
)
465 LIST_ENTRY
*mark
, *entry
;
467 if (cached_modref
&& cached_modref
->dev
== st
->st_dev
&& cached_modref
->ino
== st
->st_ino
)
468 return cached_modref
;
470 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
471 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
473 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
474 WINE_MODREF
*wm
= CONTAINING_RECORD( mod
, WINE_MODREF
, ldr
);
476 if (wm
->dev
== st
->st_dev
&& wm
->ino
== st
->st_ino
)
486 /*************************************************************************
487 * find_forwarded_export
489 * Find the final function pointer for a forwarded function.
490 * The loader_section must be locked while calling this function.
492 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
494 const IMAGE_EXPORT_DIRECTORY
*exports
;
498 const char *end
= strrchr(forward
, '.');
501 if (!end
) return NULL
;
502 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
503 ascii_to_unicode( mod_name
, forward
, end
- forward
);
504 mod_name
[end
- forward
] = 0;
505 if (!strchrW( mod_name
, '.' ))
507 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
508 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
511 if (!(wm
= find_basename_module( mod_name
)))
513 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
514 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
515 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
517 if (!imports_fixup_done
&& current_modref
)
520 if (current_modref
->alloc_deps
)
521 deps
= RtlReAllocateHeap( GetProcessHeap(), 0, current_modref
->deps
,
522 (current_modref
->alloc_deps
+ 1) * sizeof(*deps
) );
524 deps
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps
) );
527 deps
[current_modref
->nDeps
++] = wm
;
528 current_modref
->deps
= deps
;
529 current_modref
->alloc_deps
++;
532 else if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
534 LdrUnloadDll( wm
->ldr
.BaseAddress
);
541 ERR( "module not found for forward '%s' used by %s\n",
542 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
546 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
547 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
549 const char *name
= end
+ 1;
550 if (*name
== '#') /* ordinal */
551 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
553 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
558 ERR("function not found for forward '%s' used by %s."
559 " If you are using builtin %s, try using the native one instead.\n",
560 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
561 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
567 /*************************************************************************
568 * find_ordinal_export
570 * Find an exported function by ordinal.
571 * The exports base must have been subtracted from the ordinal already.
572 * The loader_section must be locked while calling this function.
574 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
575 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
578 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
580 if (ordinal
>= exports
->NumberOfFunctions
)
582 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
585 if (!functions
[ordinal
]) return NULL
;
587 proc
= get_rva( module
, functions
[ordinal
] );
589 /* if the address falls into the export dir, it's a forward */
590 if (((const char *)proc
>= (const char *)exports
) &&
591 ((const char *)proc
< (const char *)exports
+ exp_size
))
592 return find_forwarded_export( module
, (const char *)proc
, load_path
);
596 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
597 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
601 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
602 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
608 /*************************************************************************
611 * Find an exported function by name.
612 * The loader_section must be locked while calling this function.
614 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
615 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
617 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
618 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
619 int min
= 0, max
= exports
->NumberOfNames
- 1;
621 /* first check the hint */
622 if (hint
>= 0 && hint
<= max
)
624 char *ename
= get_rva( module
, names
[hint
] );
625 if (!strcmp( ename
, name
))
626 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
629 /* then do a binary search */
632 int res
, pos
= (min
+ max
) / 2;
633 char *ename
= get_rva( module
, names
[pos
] );
634 if (!(res
= strcmp( ename
, name
)))
635 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
636 if (res
> 0) max
= pos
- 1;
644 /*************************************************************************
647 * Import the dll specified by the given import descriptor.
648 * The loader_section must be locked while calling this function.
650 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
655 const IMAGE_EXPORT_DIRECTORY
*exports
;
657 const IMAGE_THUNK_DATA
*import_list
;
658 IMAGE_THUNK_DATA
*thunk_list
;
660 const char *name
= get_rva( module
, descr
->Name
);
661 DWORD len
= strlen(name
);
663 SIZE_T protect_size
= 0;
666 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
667 if (descr
->u
.OriginalFirstThunk
)
668 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
670 import_list
= thunk_list
;
672 if (!import_list
->u1
.Ordinal
)
674 WARN( "Skipping unused import %s\n", name
);
679 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
681 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
683 ascii_to_unicode( buffer
, name
, len
);
685 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
687 else /* need to allocate a larger buffer */
689 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
690 if (!ptr
) return FALSE
;
691 ascii_to_unicode( ptr
, name
, len
);
693 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
694 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
699 if (status
== STATUS_DLL_NOT_FOUND
)
700 ERR("Library %s (which is needed by %s) not found\n",
701 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
703 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
704 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
708 /* unprotect the import address table since it can be located in
709 * readonly section */
710 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
711 protect_base
= thunk_list
;
712 protect_size
*= sizeof(*thunk_list
);
713 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
714 &protect_size
, PAGE_READWRITE
, &protect_old
);
716 imp_mod
= wmImp
->ldr
.BaseAddress
;
717 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
721 /* set all imported function to deadbeef */
722 while (import_list
->u1
.Ordinal
)
724 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
726 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
727 WARN("No implementation for %s.%d", name
, ordinal
);
728 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
732 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
733 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
734 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
736 WARN(" imported from %s, allocating stub %p\n",
737 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
738 (void *)thunk_list
->u1
.Function
);
745 while (import_list
->u1
.Ordinal
)
747 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
749 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
751 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
752 ordinal
- exports
->Base
, load_path
);
753 if (!thunk_list
->u1
.Function
)
755 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
756 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
757 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
758 (void *)thunk_list
->u1
.Function
);
760 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
762 else /* import by name */
764 IMAGE_IMPORT_BY_NAME
*pe_name
;
765 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
766 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
767 (const char*)pe_name
->Name
,
768 pe_name
->Hint
, load_path
);
769 if (!thunk_list
->u1
.Function
)
771 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
772 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
773 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
774 (void *)thunk_list
->u1
.Function
);
776 TRACE_(imports
)("--- %s %s.%d = %p\n",
777 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
784 /* restore old protection of the import address table */
785 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
791 /***********************************************************************
792 * create_module_activation_context
794 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
797 LDR_RESOURCE_INFO info
;
798 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
800 info
.Type
= RT_MANIFEST
;
801 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
803 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
806 ctx
.cbSize
= sizeof(ctx
);
808 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
809 ctx
.hModule
= module
->BaseAddress
;
810 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
811 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
817 /*************************************************************************
818 * is_dll_native_subsystem
820 * Check if dll is a proper native driver.
821 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
822 * while being perfectly normal DLLs. This heuristic should catch such breakages.
824 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
826 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
827 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
828 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
832 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
833 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
835 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
836 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
838 for (i
= 0; imports
[i
].Name
; i
++)
840 const char *name
= get_rva( module
, imports
[i
].Name
);
841 DWORD len
= strlen(name
);
842 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
843 ascii_to_unicode( buffer
, name
, len
+ 1 );
844 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
846 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
854 /*************************************************************************
857 * Allocate a TLS slot for a newly-loaded module.
858 * The loader_section must be locked while calling this function.
860 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
862 const IMAGE_TLS_DIRECTORY
*dir
;
867 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
870 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
871 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
873 for (i
= 0; i
< tls_module_count
; i
++)
875 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
876 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
880 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
881 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
882 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
884 if (i
== tls_module_count
)
886 UINT new_count
= max( 32, tls_module_count
* 2 );
889 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
891 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
892 new_count
* sizeof(*tls_dirs
) );
893 if (!new_ptr
) return -1;
895 /* resize the pointer block in all running threads */
896 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
898 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
899 void **old
= teb
->ThreadLocalStoragePointer
;
900 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
903 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
904 teb
->ThreadLocalStoragePointer
= new;
905 #if defined(__APPLE__) && defined(__x86_64__)
906 if (teb
->Reserved5
[0])
907 ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
909 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
910 /* FIXME: can't free old block here, should be freed at thread exit */
914 tls_module_count
= new_count
;
917 /* allocate the data block in all running threads */
918 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
920 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
922 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
923 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
924 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
926 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
927 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
929 RtlFreeHeap( GetProcessHeap(), 0,
930 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
933 *(DWORD
*)dir
->AddressOfIndex
= i
;
939 /*************************************************************************
942 * Free the module TLS slot on unload.
943 * The loader_section must be locked while calling this function.
945 static void free_tls_slot( LDR_MODULE
*mod
)
947 ULONG i
= (USHORT
)mod
->TlsIndex
;
949 if (mod
->TlsIndex
== -1) return;
950 assert( i
< tls_module_count
);
951 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
955 /****************************************************************
956 * fixup_imports_ilonly
958 * Fixup imports for an IL-only module. All we do is import mscoree.
959 * The loader_section must be locked while calling this function.
961 static NTSTATUS
fixup_imports_ilonly( WINE_MODREF
*wm
, LPCWSTR load_path
, void **entry
)
963 static const WCHAR mscoreeW
[] = {'m','s','c','o','r','e','e','.','d','l','l',0};
964 IMAGE_EXPORT_DIRECTORY
*exports
;
968 WINE_MODREF
*prev
, *imp
;
970 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
971 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
975 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(WINE_MODREF
*) );
977 prev
= current_modref
;
979 if (!(status
= load_dll( load_path
, mscoreeW
, 0, &imp
))) wm
->deps
[0] = imp
;
980 current_modref
= prev
;
983 ERR( "mscoree.dll not found, IL-only binary %s cannot be loaded\n",
984 debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
988 TRACE( "loaded mscoree for %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
990 if ((exports
= RtlImageDirectoryEntryToData( imp
->ldr
.BaseAddress
, TRUE
,
991 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
993 const char *name
= (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) ? "_CorDllMain" : "_CorExeMain";
994 proc
= find_named_export( imp
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
996 if (!proc
) return STATUS_PROCEDURE_NOT_FOUND
;
998 return STATUS_SUCCESS
;
1002 /****************************************************************
1005 * Fixup all imports of a given module.
1006 * The loader_section must be locked while calling this function.
1008 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
1010 int i
, dep
, nb_imports
;
1011 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
1012 WINE_MODREF
*prev
, *imp
;
1017 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
1018 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1020 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
1022 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
1023 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
1024 return STATUS_SUCCESS
;
1027 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
1029 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
1031 if (!create_module_activation_context( &wm
->ldr
))
1032 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1034 /* Allocate module dependency list */
1035 wm
->alloc_deps
= nb_imports
;
1036 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
1038 /* load the imported modules. They are automatically
1039 * added to the modref list of the process.
1041 prev
= current_modref
;
1042 current_modref
= wm
;
1043 status
= STATUS_SUCCESS
;
1044 for (i
= 0; i
< nb_imports
; i
++)
1048 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &imp
))
1051 status
= STATUS_DLL_NOT_FOUND
;
1053 wm
->deps
[dep
] = imp
;
1055 current_modref
= prev
;
1056 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1061 /*************************************************************************
1064 * Allocate a WINE_MODREF structure and add it to the process list
1065 * The loader_section must be locked while calling this function.
1067 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
1071 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
1073 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) ))) return NULL
;
1075 wm
->ldr
.BaseAddress
= hModule
;
1076 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
1077 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
1078 wm
->ldr
.TlsIndex
= -1;
1079 wm
->ldr
.LoadCount
= 1;
1081 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
1082 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
1083 else p
= wm
->ldr
.FullDllName
.Buffer
;
1084 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
1086 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
1088 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
1089 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
1090 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
1091 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1094 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
1095 &wm
->ldr
.InLoadOrderModuleList
);
1096 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
1097 &wm
->ldr
.InMemoryOrderModuleList
);
1098 /* wait until init is called for inserting into InInitializationOrderModuleList */
1100 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
1102 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
1103 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1104 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1110 /*************************************************************************
1113 * Allocate the per-thread structure for module TLS storage.
1115 static NTSTATUS
alloc_thread_tls(void)
1120 if (!tls_module_count
) return STATUS_SUCCESS
;
1122 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1123 tls_module_count
* sizeof(*pointers
) )))
1124 return STATUS_NO_MEMORY
;
1126 for (i
= 0; i
< tls_module_count
; i
++)
1128 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1131 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1132 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1134 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1136 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1137 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1138 return STATUS_NO_MEMORY
;
1140 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1141 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1143 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1144 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1146 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1147 #if defined(__APPLE__) && defined(__x86_64__)
1148 __asm__
volatile (".byte 0x65\n\tmovq %0,%c1"
1150 : "r" (pointers
), "n" (FIELD_OFFSET(TEB
, ThreadLocalStoragePointer
)));
1152 return STATUS_SUCCESS
;
1156 /*************************************************************************
1157 * call_tls_callbacks
1159 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1161 const IMAGE_TLS_DIRECTORY
*dir
;
1162 const PIMAGE_TLS_CALLBACK
*callback
;
1165 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1166 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1168 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1170 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1171 *callback
, module
, reason_names
[reason
] );
1174 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1178 TRACE_(relay
)("\1exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1179 callback
, module
, reason_names
[reason
] );
1183 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1184 *callback
, module
, reason_names
[reason
] );
1189 /*************************************************************************
1192 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1195 NTSTATUS status
= STATUS_SUCCESS
;
1196 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1197 void *module
= wm
->ldr
.BaseAddress
;
1200 /* Skip calls for modules loaded with special load flags */
1202 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1203 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1204 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1206 if (TRACE_ON(relay
))
1208 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1209 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1210 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1211 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1212 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1214 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1215 reason_names
[reason
], lpReserved
);
1219 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1221 status
= STATUS_DLL_INIT_FAILED
;
1225 TRACE_(relay
)("\1exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1226 entry
, module
, reason_names
[reason
], lpReserved
);
1227 status
= GetExceptionCode();
1231 /* The state of the module list may have changed due to the call
1232 to the dll. We cannot assume that this module has not been
1234 if (TRACE_ON(relay
))
1235 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1236 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1238 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1244 /*************************************************************************
1247 * Send the process attach notification to all DLLs the given module
1248 * depends on (recursively). This is somewhat complicated due to the fact that
1250 * - we have to respect the module dependencies, i.e. modules implicitly
1251 * referenced by another module have to be initialized before the module
1252 * itself can be initialized
1254 * - the initialization routine of a DLL can itself call LoadLibrary,
1255 * thereby introducing a whole new set of dependencies (even involving
1256 * the 'old' modules) at any time during the whole process
1258 * (Note that this routine can be recursively entered not only directly
1259 * from itself, but also via LoadLibrary from one of the called initialization
1262 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1263 * the process *detach* notifications to be sent in the correct order.
1264 * This must not only take into account module dependencies, but also
1265 * 'hidden' dependencies created by modules calling LoadLibrary in their
1266 * attach notification routine.
1268 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1269 * list after the attach notification has returned. This implies that the
1270 * detach notifications are called in the reverse of the sequence the attach
1271 * notifications *returned*.
1273 * The loader_section must be locked while calling this function.
1275 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1277 NTSTATUS status
= STATUS_SUCCESS
;
1281 if (process_detaching
) return status
;
1283 /* prevent infinite recursion in case of cyclical dependencies */
1284 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1285 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1288 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1290 /* Tag current MODREF to prevent recursive loop */
1291 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1292 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1293 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1295 /* Recursively attach all DLLs this one depends on */
1296 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1298 if (!wm
->deps
[i
]) continue;
1299 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1302 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1303 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1304 &wm
->ldr
.InInitializationOrderModuleList
);
1306 /* Call DLL entry point */
1307 if (status
== STATUS_SUCCESS
)
1309 WINE_MODREF
*prev
= current_modref
;
1310 current_modref
= wm
;
1312 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_LOADED
, &wm
->ldr
);
1313 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1314 if (status
== STATUS_SUCCESS
)
1316 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1320 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1321 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, &wm
->ldr
);
1323 /* point to the name so LdrInitializeThunk can print it */
1324 last_failed_modref
= wm
;
1325 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1327 current_modref
= prev
;
1330 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1331 /* Remove recursion flag */
1332 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1334 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1339 /**********************************************************************
1340 * attach_implicitly_loaded_dlls
1342 * Attach to the (builtin) dlls that have been implicitly loaded because
1343 * of a dependency at the Unix level, but not imported at the Win32 level.
1345 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1349 PLIST_ENTRY mark
, entry
;
1351 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1352 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1354 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1356 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1357 TRACE( "found implicitly loaded %s, attaching to it\n",
1358 debugstr_w(mod
->BaseDllName
.Buffer
));
1359 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1360 break; /* restart the search from the start */
1362 if (entry
== mark
) break; /* nothing found */
1367 /*************************************************************************
1370 * Send DLL process detach notifications. See the comment about calling
1371 * sequence at process_attach.
1373 static void process_detach(void)
1375 PLIST_ENTRY mark
, entry
;
1378 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1381 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1383 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1384 InInitializationOrderModuleList
);
1385 /* Check whether to detach this DLL */
1386 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1388 if ( mod
->LoadCount
&& !process_detaching
)
1391 /* Call detach notification */
1392 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1393 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1394 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1395 call_ldr_notifications( LDR_DLL_NOTIFICATION_REASON_UNLOADED
, mod
);
1397 /* Restart at head of WINE_MODREF list, as entries might have
1398 been added and/or removed while performing the call ... */
1401 } while (entry
!= mark
);
1404 /*************************************************************************
1407 * Send DLL thread attach notifications. These are sent in the
1408 * reverse sequence of process detach notification.
1409 * The loader_section must be locked while calling this function.
1411 static void thread_attach(void)
1413 PLIST_ENTRY mark
, entry
;
1416 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1417 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1419 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1420 InInitializationOrderModuleList
);
1421 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1423 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1426 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1430 /******************************************************************
1431 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1434 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1437 NTSTATUS ret
= STATUS_SUCCESS
;
1439 RtlEnterCriticalSection( &loader_section
);
1441 wm
= get_modref( hModule
);
1442 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1443 ret
= STATUS_DLL_NOT_FOUND
;
1445 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1447 RtlLeaveCriticalSection( &loader_section
);
1452 /******************************************************************
1453 * LdrFindEntryForAddress (NTDLL.@)
1455 * The loader_section must be locked while calling this function
1457 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1459 PLIST_ENTRY mark
, entry
;
1462 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1463 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1465 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1466 if (mod
->BaseAddress
<= addr
&&
1467 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1470 return STATUS_SUCCESS
;
1473 return STATUS_NO_MORE_ENTRIES
;
1476 /******************************************************************
1477 * LdrEnumerateLoadedModules (NTDLL.@)
1479 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1481 LIST_ENTRY
*mark
, *entry
;
1483 BOOLEAN stop
= FALSE
;
1485 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1487 if (unknown
|| !callback
)
1488 return STATUS_INVALID_PARAMETER
;
1490 RtlEnterCriticalSection( &loader_section
);
1492 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1493 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1495 mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1496 callback( mod
, context
, &stop
);
1500 RtlLeaveCriticalSection( &loader_section
);
1501 return STATUS_SUCCESS
;
1504 /******************************************************************
1505 * LdrRegisterDllNotification (NTDLL.@)
1507 NTSTATUS WINAPI
LdrRegisterDllNotification(ULONG flags
, PLDR_DLL_NOTIFICATION_FUNCTION callback
,
1508 void *context
, void **cookie
)
1510 struct ldr_notification
*notify
;
1512 TRACE( "(%x, %p, %p, %p)\n", flags
, callback
, context
, cookie
);
1514 if (!callback
|| !cookie
)
1515 return STATUS_INVALID_PARAMETER
;
1518 FIXME( "ignoring flags %x\n", flags
);
1520 notify
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*notify
) );
1521 if (!notify
) return STATUS_NO_MEMORY
;
1522 notify
->callback
= callback
;
1523 notify
->context
= context
;
1525 RtlEnterCriticalSection( &loader_section
);
1526 list_add_tail( &ldr_notifications
, ¬ify
->entry
);
1527 RtlLeaveCriticalSection( &loader_section
);
1530 return STATUS_SUCCESS
;
1533 /******************************************************************
1534 * LdrUnregisterDllNotification (NTDLL.@)
1536 NTSTATUS WINAPI
LdrUnregisterDllNotification( void *cookie
)
1538 struct ldr_notification
*notify
= cookie
;
1540 TRACE( "(%p)\n", cookie
);
1542 if (!notify
) return STATUS_INVALID_PARAMETER
;
1544 RtlEnterCriticalSection( &loader_section
);
1545 list_remove( ¬ify
->entry
);
1546 RtlLeaveCriticalSection( &loader_section
);
1548 RtlFreeHeap( GetProcessHeap(), 0, notify
);
1549 return STATUS_SUCCESS
;
1552 /******************************************************************
1553 * LdrLockLoaderLock (NTDLL.@)
1555 * Note: some flags are not implemented.
1556 * Flag 0x01 is used to raise exceptions on errors.
1558 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1560 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1562 if (result
) *result
= 0;
1563 if (magic
) *magic
= 0;
1564 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1565 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1566 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1570 if (!RtlTryEnterCriticalSection( &loader_section
))
1573 return STATUS_SUCCESS
;
1579 RtlEnterCriticalSection( &loader_section
);
1580 if (result
) *result
= 1;
1582 *magic
= GetCurrentThreadId();
1583 return STATUS_SUCCESS
;
1587 /******************************************************************
1588 * LdrUnlockLoaderUnlock (NTDLL.@)
1590 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1594 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1595 RtlLeaveCriticalSection( &loader_section
);
1597 return STATUS_SUCCESS
;
1601 /******************************************************************
1602 * LdrGetProcedureAddress (NTDLL.@)
1604 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1605 ULONG ord
, PVOID
*address
)
1607 IMAGE_EXPORT_DIRECTORY
*exports
;
1609 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1611 RtlEnterCriticalSection( &loader_section
);
1613 /* check if the module itself is invalid to return the proper error */
1614 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1615 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1616 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1618 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1619 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1620 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1624 ret
= STATUS_SUCCESS
;
1628 RtlLeaveCriticalSection( &loader_section
);
1633 /***********************************************************************
1636 * Check if a loaded native dll is a Wine fake dll.
1638 static BOOL
is_fake_dll( HANDLE handle
)
1640 static const char fakedll_signature
[] = "Wine placeholder DLL";
1641 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1642 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1644 LARGE_INTEGER offset
;
1646 offset
.QuadPart
= 0;
1647 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1648 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1649 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1650 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1651 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1656 /***********************************************************************
1657 * get_builtin_fullname
1659 * Build the full pathname for a builtin dll.
1661 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1663 static const WCHAR soW
[] = {'.','s','o',0};
1664 WCHAR
*p
, *fullname
;
1665 size_t i
, len
= strlen(filename
);
1667 /* check if path can correspond to the dll we have */
1668 if (path
&& (p
= strrchrW( path
, '\\' )))
1671 for (i
= 0; i
< len
; i
++)
1672 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1673 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1675 /* the filename matches, use path as the full path */
1677 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1679 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1686 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1687 (strlenW(system_dir
) + len
+ 1) * sizeof(WCHAR
) )))
1689 strcpyW( fullname
, system_dir
);
1690 ascii_to_unicode( fullname
+ strlenW(fullname
), filename
, len
+ 1 );
1696 /*************************************************************************
1699 static BOOL
is_16bit_builtin( HMODULE module
)
1701 const IMAGE_EXPORT_DIRECTORY
*exports
;
1704 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1705 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1708 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1712 /***********************************************************************
1713 * load_builtin_callback
1715 * Load a library in memory; callback function for wine_dll_register
1717 static void load_builtin_callback( void *module
, const char *filename
)
1719 static const WCHAR emptyW
[1];
1720 IMAGE_NT_HEADERS
*nt
;
1723 const WCHAR
*load_path
;
1727 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1730 if (!(nt
= RtlImageNtHeader( module
)))
1732 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1733 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1737 virtual_create_builtin_view( module
);
1739 /* create the MODREF */
1741 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1743 ERR( "can't load %s\n", filename
);
1744 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1748 wm
= alloc_module( module
, fullname
);
1749 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1752 ERR( "can't load %s\n", filename
);
1753 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1756 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1758 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1759 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1760 is_16bit_builtin( module
))
1764 load_path
= builtin_load_info
->load_path
;
1765 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1766 if (!load_path
) load_path
= emptyW
;
1767 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1769 /* the module has only be inserted in the load & memory order lists */
1770 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1771 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1772 /* FIXME: free the modref */
1773 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1778 builtin_load_info
->wm
= wm
;
1779 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1781 /* send the DLL load event */
1783 SERVER_START_REQ( load_dll
)
1785 req
->base
= wine_server_client_ptr( module
);
1786 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1787 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1788 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1789 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1790 wine_server_call( req
);
1794 /* setup relay debugging entry points */
1795 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1799 /***********************************************************************
1800 * set_security_cookie
1802 * Create a random security cookie for buffer overflow protection. Make
1803 * sure it does not accidentally match the default cookie value.
1805 static void set_security_cookie( void *module
, SIZE_T len
)
1808 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1812 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1813 if (!loadcfg
) return;
1814 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1815 if (!loadcfg
->SecurityCookie
) return;
1816 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1817 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1819 WARN( "security cookie %p outside of image %p-%p\n",
1820 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1824 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1825 TRACE( "initializing security cookie %p\n", cookie
);
1827 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1830 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1831 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1832 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1833 *cookie
= RtlRandom( &seed
);
1834 #ifdef DEFAULT_SECURITY_COOKIE_64
1835 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1837 *cookie
= RtlRandom( &seed
);
1838 /* fill up, but keep the highest word clear */
1839 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1847 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1849 IMAGE_NT_HEADERS
*nt
;
1851 IMAGE_BASE_RELOCATION
*rel
, *end
;
1852 const IMAGE_DATA_DIRECTORY
*relocs
;
1853 const IMAGE_SECTION_HEADER
*sec
;
1855 ULONG protect_old
[96], i
;
1857 nt
= RtlImageNtHeader( module
);
1858 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1860 assert( module
!= base
);
1862 /* no relocations are performed on non page-aligned binaries */
1863 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1864 return STATUS_SUCCESS
;
1866 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1867 return STATUS_SUCCESS
;
1869 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1871 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1873 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1875 return STATUS_CONFLICTING_ADDRESSES
;
1878 if (!relocs
->Size
) return STATUS_SUCCESS
;
1879 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1881 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1882 return STATUS_INVALID_IMAGE_FORMAT
;
1884 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1885 nt
->FileHeader
.SizeOfOptionalHeader
);
1886 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1888 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1889 SIZE_T size
= sec
[i
].SizeOfRawData
;
1890 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1891 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1894 TRACE( "relocating from %p-%p to %p-%p\n",
1895 base
, base
+ len
, module
, (char *)module
+ len
);
1897 rel
= get_rva( module
, relocs
->VirtualAddress
);
1898 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1899 delta
= (char *)module
- base
;
1901 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1903 if (rel
->VirtualAddress
>= len
)
1905 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1906 return STATUS_ACCESS_VIOLATION
;
1908 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1909 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1910 (USHORT
*)(rel
+ 1), delta
);
1911 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1914 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1916 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1917 SIZE_T size
= sec
[i
].SizeOfRawData
;
1918 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1919 &size
, protect_old
[i
], &protect_old
[i
] );
1922 return STATUS_SUCCESS
;
1926 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
1927 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
1928 static BOOL
is_valid_binary( HMODULE module
, const pe_image_info_t
*info
)
1931 return info
->machine
== IMAGE_FILE_MACHINE_I386
;
1932 #elif defined(__arm__)
1933 return info
->machine
== IMAGE_FILE_MACHINE_ARM
||
1934 info
->machine
== IMAGE_FILE_MACHINE_THUMB
||
1935 info
->machine
== IMAGE_FILE_MACHINE_ARMNT
;
1936 #elif defined(__x86_64__) || defined(__aarch64__) /* support 32-bit IL-only images on 64-bit */
1937 const IMAGE_COR20_HEADER
*cor_header
;
1941 if (info
->machine
== IMAGE_FILE_MACHINE_AMD64
) return TRUE
;
1943 if (info
->machine
== IMAGE_FILE_MACHINE_ARM64
) return TRUE
;
1945 if (!info
->contains_code
) return TRUE
;
1946 cor_header
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
, &size
);
1947 if (cor_header
&& (cor_header
->Flags
& COMIMAGE_FLAGS_ILONLY
)) return TRUE
;
1950 return FALSE
; /* no wow64 support on other platforms */
1955 /******************************************************************************
1956 * load_native_dll (internal)
1958 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1959 DWORD flags
, WINE_MODREF
** pwm
, struct stat
*st
)
1964 IMAGE_NT_HEADERS
*nt
;
1968 pe_image_info_t image_info
;
1970 TRACE("Trying native dll %s\n", debugstr_w(name
));
1973 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
1974 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
1975 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1976 if (status
!= STATUS_SUCCESS
) return status
;
1979 status
= virtual_map_section( mapping
, &module
, 0, 0, NULL
, &len
, PAGE_EXECUTE_READ
, &image_info
);
1982 if ((status
== STATUS_SUCCESS
|| status
== STATUS_IMAGE_NOT_AT_BASE
) &&
1983 !is_valid_binary( module
, &image_info
))
1985 NtUnmapViewOfSection( NtCurrentProcess(), module
);
1986 return STATUS_INVALID_IMAGE_FORMAT
;
1989 /* perform base relocation, if necessary */
1991 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1992 status
= perform_relocations( module
, len
);
1994 if (status
!= STATUS_SUCCESS
)
1996 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2000 /* create the MODREF */
2002 if (!(wm
= alloc_module( module
, name
)))
2004 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
2005 return STATUS_NO_MEMORY
;
2008 wm
->dev
= st
->st_dev
;
2009 wm
->ino
= st
->st_ino
;
2010 if (image_info
.loader_flags
) wm
->ldr
.Flags
|= LDR_COR_IMAGE
;
2011 if (image_info
.image_flags
& IMAGE_FLAGS_ComPlusILOnly
) wm
->ldr
.Flags
|= LDR_COR_ILONLY
;
2013 set_security_cookie( module
, len
);
2017 nt
= RtlImageNtHeader( module
);
2019 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
2020 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
2021 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
2023 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
2024 status
= fixup_imports_ilonly( wm
, load_path
, &wm
->ldr
.EntryPoint
);
2026 status
= fixup_imports( wm
, load_path
);
2027 if (status
!= STATUS_SUCCESS
)
2029 /* the module has only be inserted in the load & memory order lists */
2030 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2031 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2033 /* FIXME: there are several more dangling references
2034 * left. Including dlls loaded by this dll before the
2035 * failed one. Unrolling is rather difficult with the
2036 * current structure and we can leave them lying
2037 * around with no problems, so we don't care.
2038 * As these might reference our wm, we don't free it.
2044 /* send DLL load event */
2046 SERVER_START_REQ( load_dll
)
2048 req
->base
= wine_server_client_ptr( module
);
2049 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
2050 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
2051 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
2052 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
2053 wine_server_call( req
);
2057 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
2059 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
2061 wm
->ldr
.LoadCount
= 1;
2063 return STATUS_SUCCESS
;
2067 /***********************************************************************
2070 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
2071 DWORD flags
, WINE_MODREF
** pwm
)
2073 char error
[256], dllname
[MAX_PATH
];
2074 const WCHAR
*name
, *p
;
2077 struct builtin_load_info info
, *prev_info
;
2079 /* Fix the name in case we have a full path and extension */
2081 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
2082 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
2084 /* load_library will modify info.status. Note also that load_library can be
2085 * called several times, if the .so file we're loading has dependencies.
2086 * info.status will gather all the errors we may get while loading all these
2089 info
.load_path
= load_path
;
2090 info
.filename
= NULL
;
2091 info
.status
= STATUS_SUCCESS
;
2094 if (file
) /* we have a real file, try to load it */
2096 UNICODE_STRING nt_name
;
2097 ANSI_STRING unix_name
;
2099 TRACE("Trying built-in %s\n", debugstr_w(path
));
2101 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
2102 return STATUS_DLL_NOT_FOUND
;
2104 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
2106 RtlFreeUnicodeString( &nt_name
);
2107 return STATUS_DLL_NOT_FOUND
;
2109 prev_info
= builtin_load_info
;
2110 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
2111 builtin_load_info
= &info
;
2112 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
2113 builtin_load_info
= prev_info
;
2114 RtlFreeUnicodeString( &nt_name
);
2115 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
2118 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
2119 return STATUS_INVALID_IMAGE_FORMAT
;
2126 TRACE("Trying built-in %s\n", debugstr_w(name
));
2128 /* we don't want to depend on the current codepage here */
2129 len
= strlenW( name
) + 1;
2130 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
2131 for (i
= 0; i
< len
; i
++)
2133 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
2134 dllname
[i
] = (char)name
[i
];
2135 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
2138 prev_info
= builtin_load_info
;
2139 builtin_load_info
= &info
;
2140 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
2141 builtin_load_info
= prev_info
;
2146 /* The file does not exist -> WARN() */
2147 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
2148 return STATUS_DLL_NOT_FOUND
;
2150 /* ERR() for all other errors (missing functions, ...) */
2151 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
2152 return STATUS_PROCEDURE_NOT_FOUND
;
2156 if (info
.status
!= STATUS_SUCCESS
)
2158 wine_dll_unload( handle
);
2164 PLIST_ENTRY mark
, entry
;
2166 /* The constructor wasn't called, this means the .so is already
2167 * loaded under a different name. Try to find the wm for it. */
2169 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2170 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2172 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2173 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
2175 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2176 TRACE( "Found %s at %p for builtin %s\n",
2177 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
2181 wine_dll_unload( handle
); /* release the libdl refcount */
2182 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
2183 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
2187 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
2188 info
.wm
->ldr
.LoadCount
= 1;
2189 info
.wm
->ldr
.SectionHandle
= handle
;
2193 return STATUS_SUCCESS
;
2197 /***********************************************************************
2200 * Find the full path (if any) of the dll from the activation context.
2202 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2204 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2205 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2207 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2208 ACTCTX_SECTION_KEYED_DATA data
;
2209 UNICODE_STRING nameW
;
2211 SIZE_T needed
, size
= 1024;
2214 RtlInitUnicodeString( &nameW
, libname
);
2215 data
.cbSize
= sizeof(data
);
2216 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2217 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2219 if (status
!= STATUS_SUCCESS
) return status
;
2223 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2225 status
= STATUS_NO_MEMORY
;
2228 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2229 AssemblyDetailedInformationInActivationContext
,
2230 info
, size
, &needed
);
2231 if (status
== STATUS_SUCCESS
) break;
2232 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2233 RtlFreeHeap( GetProcessHeap(), 0, info
);
2235 /* restart with larger buffer */
2238 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2240 status
= STATUS_SXS_KEY_NOT_FOUND
;
2244 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2246 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2249 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2251 /* manifest name does not match directory name, so it's not a global
2252 * windows/winsxs manifest; use the manifest directory name instead */
2253 dirlen
= p
- info
->lpAssemblyManifestPath
;
2254 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2255 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2257 status
= STATUS_NO_MEMORY
;
2260 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2262 strcpyW( p
, libname
);
2267 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2268 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2270 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2272 status
= STATUS_NO_MEMORY
;
2275 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2277 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2278 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2279 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2280 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2282 strcpyW( p
, libname
);
2284 RtlFreeHeap( GetProcessHeap(), 0, info
);
2285 RtlReleaseActivationContext( data
.hActCtx
);
2290 /***********************************************************************
2293 * Open a file for a new dll. Helper for find_dll_file.
2295 static HANDLE
open_dll_file( UNICODE_STRING
*nt_name
, WINE_MODREF
**pwm
, struct stat
*st
)
2297 OBJECT_ATTRIBUTES attr
;
2300 int fd
, needs_close
;
2302 attr
.Length
= sizeof(attr
);
2303 attr
.RootDirectory
= 0;
2304 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2305 attr
.ObjectName
= nt_name
;
2306 attr
.SecurityDescriptor
= NULL
;
2307 attr
.SecurityQualityOfService
= NULL
;
2308 if (NtOpenFile( &handle
, GENERIC_READ
| SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
| FILE_SHARE_DELETE
,
2309 FILE_SYNCHRONOUS_IO_NONALERT
| FILE_NON_DIRECTORY_FILE
))
2312 if (!server_get_unix_fd( handle
, 0, &fd
, &needs_close
, NULL
, NULL
))
2315 if (needs_close
) close( fd
);
2316 if ((*pwm
= find_fileid_module( handle
, st
)))
2318 TRACE( "%s is the same file as existing module %p %s\n", debugstr_w( nt_name
->Buffer
),
2319 (*pwm
)->ldr
.BaseAddress
, debugstr_w( (*pwm
)->ldr
.FullDllName
.Buffer
));
2328 /***********************************************************************
2331 * Find the file (or already loaded module) for a given dll name.
2333 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2334 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
,
2335 HANDLE
*handle
, struct stat
*st
)
2337 UNICODE_STRING nt_name
;
2338 WCHAR
*file_part
, *ext
, *dllname
;
2341 /* first append .dll if needed */
2345 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2347 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2348 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2349 return STATUS_NO_MEMORY
;
2350 strcpyW( dllname
, libname
);
2351 strcatW( dllname
, dllW
);
2355 nt_name
.Buffer
= NULL
;
2357 if (!contains_path( libname
))
2360 WCHAR
*fullname
= NULL
;
2362 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2364 status
= find_actctx_dll( libname
, &fullname
);
2365 if (status
== STATUS_SUCCESS
)
2367 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2368 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2369 libname
= dllname
= fullname
;
2371 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2373 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2378 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2380 /* we need to search for it */
2381 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2384 if (len
>= *size
) goto overflow
;
2385 if ((*pwm
= find_fullname_module( filename
))) goto found
;
2387 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2389 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2390 return STATUS_NO_MEMORY
;
2392 *handle
= open_dll_file( &nt_name
, pwm
, st
);
2398 if (!contains_path( libname
))
2400 /* if libname doesn't contain a path at all, we simply return the name as is,
2401 * to be loaded as builtin */
2402 len
= strlenW(libname
) * sizeof(WCHAR
);
2403 if (len
>= *size
) goto overflow
;
2404 strcpyW( filename
, libname
);
2409 /* absolute path name, or relative path name but not found above */
2411 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2413 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2414 return STATUS_NO_MEMORY
;
2416 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2417 if (len
>= *size
) goto overflow
;
2418 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2419 if (!(*pwm
= find_fullname_module( filename
)))
2420 *handle
= open_dll_file( &nt_name
, pwm
, st
);
2423 RtlFreeUnicodeString( &nt_name
);
2424 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2425 return STATUS_SUCCESS
;
2428 RtlFreeUnicodeString( &nt_name
);
2429 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2430 *size
= len
+ sizeof(WCHAR
);
2431 return STATUS_BUFFER_TOO_SMALL
;
2435 /***********************************************************************
2436 * load_dll (internal)
2438 * Load a PE style module according to the load order.
2439 * The loader_section must be locked while calling this function.
2441 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2443 enum loadorder loadorder
;
2447 WINE_MODREF
*main_exe
;
2452 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2456 size
= sizeof(buffer
);
2459 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
, &st
);
2460 if (nts
== STATUS_SUCCESS
) break;
2461 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2462 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2463 /* grow the buffer and retry */
2464 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2467 if (*pwm
) /* found already loaded module */
2469 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2471 TRACE("Found %s for %s at %p, count=%d\n",
2472 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2473 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2474 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2475 return STATUS_SUCCESS
;
2478 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2479 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2481 if (handle
&& is_fake_dll( handle
))
2483 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2491 nts
= STATUS_NO_MEMORY
;
2494 nts
= STATUS_DLL_NOT_FOUND
;
2497 case LO_NATIVE_BUILTIN
:
2498 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2501 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
, &st
);
2502 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2503 /* not in PE format, maybe it's a builtin */
2504 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2506 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2507 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2510 case LO_BUILTIN_NATIVE
:
2511 case LO_DEFAULT
: /* default is builtin,native */
2512 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2513 if (!handle
) break; /* nothing else we can try */
2514 /* file is not a builtin library, try without using the specified file */
2515 if (nts
!= STATUS_SUCCESS
)
2516 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2517 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2518 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2520 /* stub-only dll, try native */
2521 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2522 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2523 nts
= STATUS_DLL_NOT_FOUND
;
2525 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2526 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
, &st
);
2530 if (nts
== STATUS_SUCCESS
)
2532 /* Initialize DLL just loaded */
2533 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2534 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2535 (*pwm
)->ldr
.BaseAddress
);
2536 if (handle
) NtClose( handle
);
2537 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2541 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2542 if (handle
) NtClose( handle
);
2543 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2547 /******************************************************************
2548 * LdrLoadDll (NTDLL.@)
2550 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2551 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2556 RtlEnterCriticalSection( &loader_section
);
2558 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2559 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2561 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2563 nts
= process_attach( wm
, NULL
);
2564 if (nts
!= STATUS_SUCCESS
)
2566 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2570 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2572 RtlLeaveCriticalSection( &loader_section
);
2577 /******************************************************************
2578 * LdrGetDllHandle (NTDLL.@)
2580 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2590 RtlEnterCriticalSection( &loader_section
);
2592 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2595 size
= sizeof(buffer
);
2598 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, &handle
, &st
);
2599 if (handle
) NtClose( handle
);
2600 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2601 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2602 /* grow the buffer and retry */
2603 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2605 status
= STATUS_NO_MEMORY
;
2610 if (status
== STATUS_SUCCESS
)
2612 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2613 else status
= STATUS_DLL_NOT_FOUND
;
2616 RtlLeaveCriticalSection( &loader_section
);
2617 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2622 /******************************************************************
2623 * LdrAddRefDll (NTDLL.@)
2625 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2627 NTSTATUS ret
= STATUS_SUCCESS
;
2630 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2632 RtlEnterCriticalSection( &loader_section
);
2634 if ((wm
= get_modref( module
)))
2636 if (flags
& LDR_ADDREF_DLL_PIN
)
2637 wm
->ldr
.LoadCount
= -1;
2639 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2640 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2642 else ret
= STATUS_INVALID_PARAMETER
;
2644 RtlLeaveCriticalSection( &loader_section
);
2649 /***********************************************************************
2650 * LdrProcessRelocationBlock (NTDLL.@)
2652 * Apply relocations to a given page of a mapped PE image.
2654 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2655 USHORT
*relocs
, INT_PTR delta
)
2659 USHORT offset
= *relocs
& 0xfff;
2660 int type
= *relocs
>> 12;
2663 case IMAGE_REL_BASED_ABSOLUTE
:
2665 case IMAGE_REL_BASED_HIGH
:
2666 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2668 case IMAGE_REL_BASED_LOW
:
2669 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2671 case IMAGE_REL_BASED_HIGHLOW
:
2672 *(int *)((char *)page
+ offset
) += delta
;
2675 case IMAGE_REL_BASED_DIR64
:
2676 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2678 #elif defined(__arm__)
2679 case IMAGE_REL_BASED_THUMB_MOV32
:
2681 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2682 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2683 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2686 if ((inst
& 0x8000fbf0) != 0x0000f240)
2687 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2689 imm16
+= LOWORD(delta
);
2690 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2691 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2692 ((imm16
>> 12) & 0x000f) +
2693 ((imm16
<< 20) & 0x70000000) +
2694 ((imm16
<< 16) & 0xff0000);
2698 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2699 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2700 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2702 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2703 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2707 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2708 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2709 ((imm16
>> 1) & 0x0400) +
2710 ((imm16
>> 12) & 0x000f) +
2711 ((imm16
<< 20) & 0x70000000) +
2712 ((imm16
<< 16) & 0xff0000);
2718 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2723 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2727 /******************************************************************
2728 * LdrQueryProcessModuleInformation
2731 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2732 ULONG buf_size
, ULONG
* req_size
)
2734 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2735 ULONG size
= sizeof(ULONG
);
2736 NTSTATUS nts
= STATUS_SUCCESS
;
2739 PLIST_ENTRY mark
, entry
;
2743 smi
->ModulesCount
= 0;
2745 RtlEnterCriticalSection( &loader_section
);
2746 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2747 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2749 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2750 size
+= sizeof(*sm
);
2751 if (size
<= buf_size
)
2753 sm
->Reserved1
= 0; /* FIXME */
2754 sm
->Reserved2
= 0; /* FIXME */
2755 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2756 sm
->ImageSize
= mod
->SizeOfImage
;
2757 sm
->Flags
= mod
->Flags
;
2759 sm
->Rank
= 0; /* FIXME */
2760 sm
->Unknown
= 0; /* FIXME */
2762 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2763 str
.Buffer
= (char*)sm
->Name
;
2764 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2765 ptr
= strrchr(str
.Buffer
, '\\');
2766 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2768 smi
->ModulesCount
++;
2771 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2773 RtlLeaveCriticalSection( &loader_section
);
2775 if (req_size
) *req_size
= size
;
2781 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2787 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2789 RtlInitUnicodeString( &str
, name
);
2791 size
= sizeof(buffer
) - sizeof(WCHAR
);
2792 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2795 if (info
->Type
!= REG_DWORD
)
2797 buffer
[size
/ sizeof(WCHAR
)] = 0;
2798 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2800 else memcpy( value
, info
->Data
, sizeof(*value
) );
2804 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2805 void *data
, ULONG in_size
, ULONG
*out_size
)
2811 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2812 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2814 RtlInitUnicodeString( &str
, name
);
2816 size
= info_size
+ in_size
;
2817 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2818 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2819 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2820 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2822 if (out_size
) *out_size
= info
->DataLength
;
2823 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2825 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2830 /******************************************************************
2831 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2833 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2834 void *data
, ULONG in_size
, ULONG
*out_size
)
2836 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2837 'S','o','f','t','w','a','r','e','\\',
2838 'M','i','c','r','o','s','o','f','t','\\',
2839 'W','i','n','d','o','w','s',' ','N','T','\\',
2840 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2841 'I','m','a','g','e',' ','F','i','l','e',' ',
2842 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2843 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2844 OBJECT_ATTRIBUTES attr
;
2845 UNICODE_STRING name_str
;
2851 attr
.Length
= sizeof(attr
);
2852 attr
.RootDirectory
= 0;
2853 attr
.ObjectName
= &name_str
;
2854 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2855 attr
.SecurityDescriptor
= NULL
;
2856 attr
.SecurityQualityOfService
= NULL
;
2858 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2859 else p
= key
->Buffer
;
2860 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2861 name_str
.Buffer
= path
;
2862 name_str
.Length
= sizeof(optionsW
) + len
;
2863 name_str
.MaximumLength
= name_str
.Length
;
2864 memcpy( path
, optionsW
, sizeof(optionsW
) );
2865 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2866 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2868 if (type
== REG_DWORD
)
2870 if (out_size
) *out_size
= sizeof(ULONG
);
2871 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2872 else status
= STATUS_BUFFER_OVERFLOW
;
2874 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2881 /******************************************************************
2882 * RtlDllShutdownInProgress (NTDLL.@)
2884 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2886 return process_detaching
;
2889 /****************************************************************************
2890 * LdrResolveDelayLoadedAPI (NTDLL.@)
2892 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2893 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2894 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2896 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2897 DELAYLOAD_INFO delayinfo
;
2905 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2907 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2908 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2909 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2910 name
= get_rva(base
, desc
->DllNameRVA
);
2915 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2917 nts
= STATUS_NO_MEMORY
;
2920 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2921 RtlFreeUnicodeString(&mod
);
2925 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2926 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2929 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2932 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2933 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2937 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2942 delayinfo
.Size
= sizeof(delayinfo
);
2943 delayinfo
.DelayloadDescriptor
= desc
;
2944 delayinfo
.ThunkAddress
= addr
;
2945 delayinfo
.TargetDllName
= name
;
2946 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2947 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2948 delayinfo
.TargetModuleBase
= *phmod
;
2949 delayinfo
.Unused
= NULL
;
2950 delayinfo
.LastError
= nts
;
2951 return dllhook(4, &delayinfo
);
2954 /******************************************************************
2955 * LdrShutdownProcess (NTDLL.@)
2958 void WINAPI
LdrShutdownProcess(void)
2961 process_detaching
= TRUE
;
2966 /******************************************************************
2967 * RtlExitUserProcess (NTDLL.@)
2969 void WINAPI
RtlExitUserProcess( DWORD status
)
2971 RtlEnterCriticalSection( &loader_section
);
2972 RtlAcquirePebLock();
2973 NtTerminateProcess( 0, status
);
2974 LdrShutdownProcess();
2975 NtTerminateProcess( GetCurrentProcess(), status
);
2979 /******************************************************************
2980 * LdrShutdownThread (NTDLL.@)
2983 void WINAPI
LdrShutdownThread(void)
2985 PLIST_ENTRY mark
, entry
;
2992 /* don't do any detach calls if process is exiting */
2993 if (process_detaching
) return;
2995 RtlEnterCriticalSection( &loader_section
);
2997 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2998 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
3000 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
3001 InInitializationOrderModuleList
);
3002 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
3004 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
3007 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
3008 DLL_THREAD_DETACH
, NULL
);
3011 RtlAcquirePebLock();
3012 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
3013 RtlReleasePebLock();
3015 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
3017 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
3018 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
3020 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
3021 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
3022 RtlLeaveCriticalSection( &loader_section
);
3026 /***********************************************************************
3030 static void free_modref( WINE_MODREF
*wm
)
3032 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
3033 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
3034 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
3035 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
3037 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
3038 if (!TRACE_ON(module
))
3039 TRACE_(loaddll
)("Unloaded module %s : %s\n",
3040 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
3041 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
3043 SERVER_START_REQ( unload_dll
)
3045 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
3046 wine_server_call( req
);
3050 free_tls_slot( &wm
->ldr
);
3051 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
3052 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
3053 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
3054 if (cached_modref
== wm
) cached_modref
= NULL
;
3055 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
3056 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
3057 RtlFreeHeap( GetProcessHeap(), 0, wm
);
3060 /***********************************************************************
3061 * MODULE_FlushModrefs
3063 * Remove all unused modrefs and call the internal unloading routines
3064 * for the library type.
3066 * The loader_section must be locked while calling this function.
3068 static void MODULE_FlushModrefs(void)
3070 PLIST_ENTRY mark
, entry
, prev
;
3074 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
3075 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3077 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
3078 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3079 prev
= entry
->Blink
;
3080 if (!mod
->LoadCount
) free_modref( wm
);
3083 /* check load order list too for modules that haven't been initialized yet */
3084 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3085 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
3087 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
3088 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
3089 prev
= entry
->Blink
;
3090 if (!mod
->LoadCount
) free_modref( wm
);
3094 /***********************************************************************
3095 * MODULE_DecRefCount
3097 * The loader_section must be locked while calling this function.
3099 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
3103 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
3106 if ( wm
->ldr
.LoadCount
<= 0 )
3109 --wm
->ldr
.LoadCount
;
3110 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
3112 if ( wm
->ldr
.LoadCount
== 0 )
3114 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
3116 for ( i
= 0; i
< wm
->nDeps
; i
++ )
3118 MODULE_DecRefCount( wm
->deps
[i
] );
3120 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
3124 /******************************************************************
3125 * LdrUnloadDll (NTDLL.@)
3129 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
3132 NTSTATUS retv
= STATUS_SUCCESS
;
3134 if (process_detaching
) return retv
;
3136 TRACE("(%p)\n", hModule
);
3138 RtlEnterCriticalSection( &loader_section
);
3141 if ((wm
= get_modref( hModule
)) != NULL
)
3143 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
3145 /* Recursively decrement reference counts */
3146 MODULE_DecRefCount( wm
);
3148 /* Call process detach notifications */
3149 if ( free_lib_count
<= 1 )
3152 MODULE_FlushModrefs();
3158 retv
= STATUS_DLL_NOT_FOUND
;
3162 RtlLeaveCriticalSection( &loader_section
);
3167 /***********************************************************************
3168 * RtlImageNtHeader (NTDLL.@)
3170 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
3172 IMAGE_NT_HEADERS
*ret
;
3176 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
3179 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
3181 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
3182 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
3194 /***********************************************************************
3197 * Attach to all the loaded dlls.
3198 * If this is the first time, perform the full process initialization.
3200 NTSTATUS
attach_dlls( CONTEXT
*context
, void **entry
)
3204 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3206 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
3208 if (process_detaching
) return STATUS_SUCCESS
;
3210 RtlEnterCriticalSection( &loader_section
);
3212 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3215 if (!imports_fixup_done
)
3218 if (wm
->ldr
.Flags
& LDR_COR_ILONLY
)
3219 status
= fixup_imports_ilonly( wm
, load_path
, entry
);
3221 status
= fixup_imports( wm
, load_path
);
3225 ERR( "Importing dlls for %s failed, status %x\n",
3226 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3227 NtTerminateProcess( GetCurrentProcess(), status
);
3229 imports_fixup_done
= TRUE
;
3232 RtlAcquirePebLock();
3233 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
3234 RtlReleasePebLock();
3236 if (!(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
)) /* first time around */
3238 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3240 ERR( "TLS init failed when loading %s, status %x\n",
3241 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3242 NtTerminateProcess( GetCurrentProcess(), status
);
3244 if ((status
= process_attach( wm
, context
)) != STATUS_SUCCESS
)
3246 if (last_failed_modref
)
3247 ERR( "%s failed to initialize, aborting\n",
3248 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3249 ERR( "Initializing dlls for %s failed, status %x\n",
3250 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3251 NtTerminateProcess( GetCurrentProcess(), status
);
3253 attach_implicitly_loaded_dlls( context
);
3254 virtual_release_address_space();
3258 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3259 NtTerminateThread( GetCurrentThread(), status
);
3263 RtlLeaveCriticalSection( &loader_section
);
3264 return STATUS_SUCCESS
;
3268 /***********************************************************************
3269 * load_global_options
3271 static void load_global_options(void)
3273 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
3274 'S','y','s','t','e','m','\\',
3275 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3276 'C','o','n','t','r','o','l','\\',
3277 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3278 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3279 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};
3280 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3281 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3282 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};
3283 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};
3285 OBJECT_ATTRIBUTES attr
;
3286 UNICODE_STRING name_str
;
3290 attr
.Length
= sizeof(attr
);
3291 attr
.RootDirectory
= 0;
3292 attr
.ObjectName
= &name_str
;
3293 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3294 attr
.SecurityDescriptor
= NULL
;
3295 attr
.SecurityQualityOfService
= NULL
;
3296 RtlInitUnicodeString( &name_str
, sessionW
);
3298 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3300 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3302 query_dword_option( hkey
, critsectW
, &value
);
3303 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3305 query_dword_option( hkey
, heapresW
, &value
);
3306 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3308 query_dword_option( hkey
, heapcommitW
, &value
);
3309 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3311 query_dword_option( hkey
, decommittotalW
, &value
);
3312 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3314 query_dword_option( hkey
, decommitfreeW
, &value
);
3315 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3321 /******************************************************************
3322 * LdrInitializeThunk (NTDLL.@)
3325 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3326 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3328 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3331 PEB
*peb
= NtCurrentTeb()->Peb
;
3333 kernel32_start_process
= kernel_start
;
3334 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3336 /* allocate the modref for the main exe (if not already done) */
3337 wm
= get_modref( peb
->ImageBaseAddress
);
3339 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3341 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3345 peb
->LoaderLock
= &loader_section
;
3346 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3347 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3348 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3349 version_init( wm
->ldr
.FullDllName
.Buffer
);
3350 virtual_set_large_address_space();
3352 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3353 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3354 heap_set_debug_flags( GetProcessHeap() );
3356 /* the main exe needs to be the first in the load order list */
3357 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3358 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3359 RemoveEntryList( &wm
->ldr
.InMemoryOrderModuleList
);
3360 InsertHeadList( &peb
->LdrData
->InMemoryOrderModuleList
, &wm
->ldr
.InMemoryOrderModuleList
);
3362 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL
)) != STATUS_SUCCESS
)
3364 ERR( "Main exe initialization for %s failed, status %x\n",
3365 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3366 NtTerminateProcess( GetCurrentProcess(), status
);
3368 server_init_process_done();
3372 /***********************************************************************
3373 * RtlImageDirectoryEntryToData (NTDLL.@)
3375 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3377 const IMAGE_NT_HEADERS
*nt
;
3380 if ((ULONG_PTR
)module
& 1) image
= FALSE
; /* mapped as data file */
3381 module
= (HMODULE
)((ULONG_PTR
)module
& ~3);
3382 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3383 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3385 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3387 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3388 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3389 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3390 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3392 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3394 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3396 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3397 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3398 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3399 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3403 /* not mapped as image, need to find the section containing the virtual address */
3404 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3408 /***********************************************************************
3409 * RtlImageRvaToSection (NTDLL.@)
3411 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3412 HMODULE module
, DWORD rva
)
3415 const IMAGE_SECTION_HEADER
*sec
;
3417 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3418 nt
->FileHeader
.SizeOfOptionalHeader
);
3419 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3421 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3422 return (PIMAGE_SECTION_HEADER
)sec
;
3428 /***********************************************************************
3429 * RtlImageRvaToVa (NTDLL.@)
3431 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3432 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3434 IMAGE_SECTION_HEADER
*sec
;
3436 if (section
&& *section
) /* try this section first */
3439 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3442 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3444 if (section
) *section
= sec
;
3445 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3449 /***********************************************************************
3450 * RtlPcToFileHeader (NTDLL.@)
3452 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3457 RtlEnterCriticalSection( &loader_section
);
3458 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3459 RtlLeaveCriticalSection( &loader_section
);
3465 /***********************************************************************
3466 * NtLoadDriver (NTDLL.@)
3467 * ZwLoadDriver (NTDLL.@)
3469 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3471 FIXME("(%p), stub!\n",DriverServiceName
);
3472 return STATUS_NOT_IMPLEMENTED
;
3476 /***********************************************************************
3477 * NtUnloadDriver (NTDLL.@)
3478 * ZwUnloadDriver (NTDLL.@)
3480 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3482 FIXME("(%p), stub!\n",DriverServiceName
);
3483 return STATUS_NOT_IMPLEMENTED
;
3487 /******************************************************************
3490 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3492 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3497 /***********************************************************************
3498 * __wine_process_init
3500 void __wine_process_init(void)
3502 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3506 ANSI_STRING func_name
;
3507 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3509 main_exe_file
= thread_init();
3511 /* retrieve current umask */
3512 FILE_umask
= umask(0777);
3513 umask( FILE_umask
);
3515 load_global_options();
3517 /* setup the load callback and create ntdll modref */
3518 wine_dll_set_callback( load_builtin_callback
);
3520 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3522 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3525 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3526 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3528 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3529 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3530 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3532 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);