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/server.h"
44 #include "ntdll_misc.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module
);
48 WINE_DECLARE_DEBUG_CHANNEL(relay
);
49 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
50 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
51 WINE_DECLARE_DEBUG_CHANNEL(imports
);
54 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
56 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
57 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
59 /* we don't want to include winuser.h */
60 #define RT_MANIFEST ((ULONG_PTR)24)
61 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
63 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
64 typedef void (CALLBACK
*LDRENUMPROC
)(LDR_MODULE
*, void *, BOOLEAN
*);
66 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
67 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
68 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
70 static const char * const reason_names
[] =
76 NULL
, NULL
, NULL
, NULL
,
80 static const WCHAR dllW
[] = {'.','d','l','l',0};
82 /* internal representation of 32bit modules. per process. */
83 typedef struct _wine_modref
87 struct _wine_modref
**deps
;
90 /* info about the current builtin dll load */
91 /* used to keep track of things across the register_dll constructor call */
92 struct builtin_load_info
94 const WCHAR
*load_path
;
95 const WCHAR
*filename
;
100 static struct builtin_load_info default_load_info
;
101 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
103 static HANDLE main_exe_file
;
104 static UINT tls_module_count
; /* number of modules with TLS directory */
105 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
106 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
108 static RTL_CRITICAL_SECTION loader_section
;
109 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
111 0, 0, &loader_section
,
112 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
113 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
115 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
117 static WINE_MODREF
*cached_modref
;
118 static WINE_MODREF
*current_modref
;
119 static WINE_MODREF
*last_failed_modref
;
121 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
122 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
123 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
124 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
125 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
126 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
128 /* convert PE image VirtualAddress to Real Address */
129 static inline void *get_rva( HMODULE module
, DWORD va
)
131 return (void *)((char *)module
+ va
);
134 /* check whether the file name contains a path */
135 static inline BOOL
contains_path( LPCWSTR name
)
137 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
140 /* convert from straight ASCII to Unicode without depending on the current codepage */
141 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
143 while (len
--) *dst
++ = (unsigned char)*src
++;
147 /*************************************************************************
148 * call_dll_entry_point
150 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
151 * their entry point, so we need a small asm wrapper. Testing indicates
152 * that only modifying esi leads to a crash, so use this one to backup
153 * ebp while running the dll entry proc.
156 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
157 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
159 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
160 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
162 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
164 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
166 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
168 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
170 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
174 "movl 8(%ebp),%eax\n\t"
177 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
178 "leal -12(%ebp),%esp\n\t"
180 __ASM_CFI(".cfi_same_value %edi\n\t")
182 __ASM_CFI(".cfi_same_value %esi\n\t")
184 __ASM_CFI(".cfi_same_value %ebx\n\t")
186 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
187 __ASM_CFI(".cfi_same_value %ebp\n\t")
190 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
191 UINT reason
, void *reserved
)
193 return proc( module
, reason
, reserved
);
195 #endif /* __i386__ */
198 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
199 /*************************************************************************
202 * Entry point for stub functions.
204 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
206 EXCEPTION_RECORD rec
;
208 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
209 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
210 rec
.ExceptionRecord
= NULL
;
211 rec
.ExceptionAddress
= ret_addr
;
212 rec
.NumberParameters
= 2;
213 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
214 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
215 for (;;) RtlRaiseException( &rec
);
219 #include "pshpack1.h"
223 BYTE pushl1
; /* pushl $name */
225 BYTE pushl2
; /* pushl $dll */
227 BYTE call
; /* call stub_entry_point */
230 #elif defined(__arm__)
233 DWORD ldr_r0
; /* ldr r0, $dll */
234 DWORD ldr_r1
; /* ldr r1, $name */
235 DWORD mov_r2_lr
; /* mov r2, lr */
236 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
241 #elif defined(__aarch64__)
244 DWORD ldr_x0
; /* ldr x0, $dll */
245 DWORD ldr_x1
; /* ldr x1, $name */
246 DWORD mov_x2_lr
; /* mov x2, lr */
247 DWORD ldr_x16
; /* ldr x16, $entry */
248 DWORD br_x16
; /* br x16 */
256 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
258 BYTE movq_rsi
[2]; /* movq $name,%rsi */
260 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
261 BYTE movq_rax
[2]; /* movq $entry, %rax */
263 BYTE jmpq_rax
[2]; /* jmp %rax */
268 /*************************************************************************
271 * Allocate a stub entry point.
273 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
275 #define MAX_SIZE 65536
276 static struct stub
*stubs
;
277 static unsigned int nb_stubs
;
280 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
284 SIZE_T size
= MAX_SIZE
;
285 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
286 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
289 stub
= &stubs
[nb_stubs
++];
291 stub
->pushl1
= 0x68; /* pushl $name */
293 stub
->pushl2
= 0x68; /* pushl $dll */
295 stub
->call
= 0xe8; /* call stub_entry_point */
296 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
297 #elif defined(__arm__)
298 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
299 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
300 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
301 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
304 stub
->entry
= stub_entry_point
;
305 #elif defined(__aarch64__)
306 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
307 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
308 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
309 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
310 stub
->br_x16
= 0xd61f0200; /* br x16 */
313 stub
->entry
= stub_entry_point
;
315 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
316 stub
->movq_rdi
[1] = 0xbf;
318 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
319 stub
->movq_rsi
[1] = 0xbe;
321 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
322 stub
->movq_rsp_rdx
[1] = 0x8b;
323 stub
->movq_rsp_rdx
[2] = 0x14;
324 stub
->movq_rsp_rdx
[3] = 0x24;
325 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
326 stub
->movq_rax
[1] = 0xb8;
327 stub
->entry
= stub_entry_point
;
328 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
329 stub
->jmpq_rax
[1] = 0xe0;
331 return (ULONG_PTR
)stub
;
335 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
336 #endif /* __i386__ */
339 /*************************************************************************
342 * Looks for the referenced HMODULE in the current process
343 * The loader_section must be locked while calling this function.
345 static WINE_MODREF
*get_modref( HMODULE hmod
)
347 PLIST_ENTRY mark
, entry
;
350 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
352 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
353 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
355 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
356 if (mod
->BaseAddress
== hmod
)
357 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
363 /**********************************************************************
364 * find_basename_module
366 * Find a module from its base name.
367 * The loader_section must be locked while calling this function
369 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
371 PLIST_ENTRY mark
, entry
;
373 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
374 return cached_modref
;
376 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
377 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
379 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
380 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
382 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
383 return cached_modref
;
390 /**********************************************************************
391 * find_fullname_module
393 * Find a module from its full path name.
394 * The loader_section must be locked while calling this function
396 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
398 PLIST_ENTRY mark
, entry
;
400 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
401 return cached_modref
;
403 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
404 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
406 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
407 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
409 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
410 return cached_modref
;
417 /*************************************************************************
418 * find_forwarded_export
420 * Find the final function pointer for a forwarded function.
421 * The loader_section must be locked while calling this function.
423 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
425 const IMAGE_EXPORT_DIRECTORY
*exports
;
429 const char *end
= strrchr(forward
, '.');
432 if (!end
) return NULL
;
433 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
434 ascii_to_unicode( mod_name
, forward
, end
- forward
);
435 mod_name
[end
- forward
] = 0;
436 if (!strchrW( mod_name
, '.' ))
438 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
439 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
442 if (!(wm
= find_basename_module( mod_name
)))
444 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
445 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
446 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
448 if (!imports_fixup_done
&& current_modref
)
451 if (current_modref
->nDeps
)
452 deps
= RtlReAllocateHeap( GetProcessHeap(), 0, current_modref
->deps
,
453 (current_modref
->nDeps
+ 1) * sizeof(*deps
) );
455 deps
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps
) );
458 deps
[current_modref
->nDeps
++] = wm
;
459 current_modref
->deps
= deps
;
462 else if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
464 LdrUnloadDll( wm
->ldr
.BaseAddress
);
471 ERR( "module not found for forward '%s' used by %s\n",
472 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
476 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
477 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
479 const char *name
= end
+ 1;
480 if (*name
== '#') /* ordinal */
481 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
483 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
488 ERR("function not found for forward '%s' used by %s."
489 " If you are using builtin %s, try using the native one instead.\n",
490 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
491 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
497 /*************************************************************************
498 * find_ordinal_export
500 * Find an exported function by ordinal.
501 * The exports base must have been subtracted from the ordinal already.
502 * The loader_section must be locked while calling this function.
504 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
505 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
508 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
510 if (ordinal
>= exports
->NumberOfFunctions
)
512 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
515 if (!functions
[ordinal
]) return NULL
;
517 proc
= get_rva( module
, functions
[ordinal
] );
519 /* if the address falls into the export dir, it's a forward */
520 if (((const char *)proc
>= (const char *)exports
) &&
521 ((const char *)proc
< (const char *)exports
+ exp_size
))
522 return find_forwarded_export( module
, (const char *)proc
, load_path
);
526 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
527 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
531 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
532 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
538 /*************************************************************************
541 * Find an exported function by name.
542 * The loader_section must be locked while calling this function.
544 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
545 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
547 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
548 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
549 int min
= 0, max
= exports
->NumberOfNames
- 1;
551 /* first check the hint */
552 if (hint
>= 0 && hint
<= max
)
554 char *ename
= get_rva( module
, names
[hint
] );
555 if (!strcmp( ename
, name
))
556 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
559 /* then do a binary search */
562 int res
, pos
= (min
+ max
) / 2;
563 char *ename
= get_rva( module
, names
[pos
] );
564 if (!(res
= strcmp( ename
, name
)))
565 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
566 if (res
> 0) max
= pos
- 1;
574 /*************************************************************************
577 * Import the dll specified by the given import descriptor.
578 * The loader_section must be locked while calling this function.
580 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
585 const IMAGE_EXPORT_DIRECTORY
*exports
;
587 const IMAGE_THUNK_DATA
*import_list
;
588 IMAGE_THUNK_DATA
*thunk_list
;
590 const char *name
= get_rva( module
, descr
->Name
);
591 DWORD len
= strlen(name
);
593 SIZE_T protect_size
= 0;
596 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
597 if (descr
->u
.OriginalFirstThunk
)
598 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
600 import_list
= thunk_list
;
602 if (!import_list
->u1
.Ordinal
)
604 WARN( "Skipping unused import %s\n", name
);
609 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
611 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
613 ascii_to_unicode( buffer
, name
, len
);
615 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
617 else /* need to allocate a larger buffer */
619 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
620 if (!ptr
) return FALSE
;
621 ascii_to_unicode( ptr
, name
, len
);
623 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
624 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
629 if (status
== STATUS_DLL_NOT_FOUND
)
630 ERR("Library %s (which is needed by %s) not found\n",
631 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
633 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
634 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
638 /* unprotect the import address table since it can be located in
639 * readonly section */
640 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
641 protect_base
= thunk_list
;
642 protect_size
*= sizeof(*thunk_list
);
643 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
644 &protect_size
, PAGE_READWRITE
, &protect_old
);
646 imp_mod
= wmImp
->ldr
.BaseAddress
;
647 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
651 /* set all imported function to deadbeef */
652 while (import_list
->u1
.Ordinal
)
654 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
656 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
657 WARN("No implementation for %s.%d", name
, ordinal
);
658 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
662 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
663 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
664 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
666 WARN(" imported from %s, allocating stub %p\n",
667 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
668 (void *)thunk_list
->u1
.Function
);
675 while (import_list
->u1
.Ordinal
)
677 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
679 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
681 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
682 ordinal
- exports
->Base
, load_path
);
683 if (!thunk_list
->u1
.Function
)
685 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
686 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
687 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
688 (void *)thunk_list
->u1
.Function
);
690 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
692 else /* import by name */
694 IMAGE_IMPORT_BY_NAME
*pe_name
;
695 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
696 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
697 (const char*)pe_name
->Name
,
698 pe_name
->Hint
, load_path
);
699 if (!thunk_list
->u1
.Function
)
701 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
702 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
703 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
704 (void *)thunk_list
->u1
.Function
);
706 TRACE_(imports
)("--- %s %s.%d = %p\n",
707 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
714 /* restore old protection of the import address table */
715 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
721 /***********************************************************************
722 * create_module_activation_context
724 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
727 LDR_RESOURCE_INFO info
;
728 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
730 info
.Type
= RT_MANIFEST
;
731 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
733 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
736 ctx
.cbSize
= sizeof(ctx
);
738 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
739 ctx
.hModule
= module
->BaseAddress
;
740 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
741 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
747 /*************************************************************************
748 * is_dll_native_subsystem
750 * Check if dll is a proper native driver.
751 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
752 * while being perfectly normal DLLs. This heuristic should catch such breakages.
754 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
756 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
757 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
758 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
762 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
763 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
765 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
766 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
768 for (i
= 0; imports
[i
].Name
; i
++)
770 const char *name
= get_rva( module
, imports
[i
].Name
);
771 DWORD len
= strlen(name
);
772 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
773 ascii_to_unicode( buffer
, name
, len
+ 1 );
774 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
776 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
784 /*************************************************************************
787 * Allocate a TLS slot for a newly-loaded module.
788 * The loader_section must be locked while calling this function.
790 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
792 const IMAGE_TLS_DIRECTORY
*dir
;
797 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
800 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
801 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
803 for (i
= 0; i
< tls_module_count
; i
++)
805 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
806 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
810 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
811 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
812 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
814 if (i
== tls_module_count
)
816 UINT new_count
= max( 32, tls_module_count
* 2 );
819 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
821 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
822 new_count
* sizeof(*tls_dirs
) );
823 if (!new_ptr
) return -1;
825 /* resize the pointer block in all running threads */
826 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
828 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
829 void **old
= teb
->ThreadLocalStoragePointer
;
830 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
833 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
834 teb
->ThreadLocalStoragePointer
= new;
835 #if defined(__APPLE__) && defined(__x86_64__)
836 if (teb
->Reserved5
[0])
837 ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
839 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
840 /* FIXME: can't free old block here, should be freed at thread exit */
844 tls_module_count
= new_count
;
847 /* allocate the data block in all running threads */
848 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
850 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
852 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
853 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
854 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
856 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
857 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
859 RtlFreeHeap( GetProcessHeap(), 0,
860 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
863 *(DWORD
*)dir
->AddressOfIndex
= i
;
869 /*************************************************************************
872 * Free the module TLS slot on unload.
873 * The loader_section must be locked while calling this function.
875 static void free_tls_slot( LDR_MODULE
*mod
)
877 ULONG i
= (USHORT
)mod
->TlsIndex
;
879 if (mod
->TlsIndex
== -1) return;
880 assert( i
< tls_module_count
);
881 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
885 /****************************************************************
888 * Fixup all imports of a given module.
889 * The loader_section must be locked while calling this function.
891 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
894 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
895 WINE_MODREF
*prev
, *imp
;
900 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
901 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
903 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
905 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
906 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
907 return STATUS_SUCCESS
;
910 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
912 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
914 if (!create_module_activation_context( &wm
->ldr
))
915 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
917 /* Allocate module dependency list */
918 wm
->nDeps
= nb_imports
;
919 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
921 /* load the imported modules. They are automatically
922 * added to the modref list of the process.
924 prev
= current_modref
;
926 status
= STATUS_SUCCESS
;
927 for (i
= 0; i
< nb_imports
; i
++)
929 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &imp
))
932 status
= STATUS_DLL_NOT_FOUND
;
936 current_modref
= prev
;
937 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
942 /*************************************************************************
945 * Allocate a WINE_MODREF structure and add it to the process list
946 * The loader_section must be locked while calling this function.
948 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
952 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
954 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
959 wm
->ldr
.BaseAddress
= hModule
;
960 wm
->ldr
.EntryPoint
= NULL
;
961 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
962 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
963 wm
->ldr
.TlsIndex
= -1;
964 wm
->ldr
.LoadCount
= 1;
965 wm
->ldr
.SectionHandle
= NULL
;
966 wm
->ldr
.CheckSum
= 0;
967 wm
->ldr
.TimeDateStamp
= 0;
968 wm
->ldr
.ActivationContext
= 0;
970 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
971 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
972 else p
= wm
->ldr
.FullDllName
.Buffer
;
973 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
975 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
977 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
978 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
979 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
980 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
983 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
984 &wm
->ldr
.InLoadOrderModuleList
);
985 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
986 &wm
->ldr
.InMemoryOrderModuleList
);
988 /* wait until init is called for inserting into this list */
989 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
990 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
992 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
994 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
995 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
996 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1002 /*************************************************************************
1005 * Allocate the per-thread structure for module TLS storage.
1007 static NTSTATUS
alloc_thread_tls(void)
1012 if (!tls_module_count
) return STATUS_SUCCESS
;
1014 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1015 tls_module_count
* sizeof(*pointers
) )))
1016 return STATUS_NO_MEMORY
;
1018 for (i
= 0; i
< tls_module_count
; i
++)
1020 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1023 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1024 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1026 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1028 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1029 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1030 return STATUS_NO_MEMORY
;
1032 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1033 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1035 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1036 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1038 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1039 #if defined(__APPLE__) && defined(__x86_64__)
1040 __asm__
volatile (".byte 0x65\n\tmovq %0,%c1"
1042 : "r" (pointers
), "n" (FIELD_OFFSET(TEB
, ThreadLocalStoragePointer
)));
1044 return STATUS_SUCCESS
;
1048 /*************************************************************************
1049 * call_tls_callbacks
1051 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1053 const IMAGE_TLS_DIRECTORY
*dir
;
1054 const PIMAGE_TLS_CALLBACK
*callback
;
1057 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1058 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1060 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1062 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1063 *callback
, module
, reason_names
[reason
] );
1066 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1070 TRACE_(relay
)("\1exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1071 callback
, module
, reason_names
[reason
] );
1075 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1076 *callback
, module
, reason_names
[reason
] );
1081 /*************************************************************************
1084 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1087 NTSTATUS status
= STATUS_SUCCESS
;
1088 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1089 void *module
= wm
->ldr
.BaseAddress
;
1092 /* Skip calls for modules loaded with special load flags */
1094 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1095 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1096 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1098 if (TRACE_ON(relay
))
1100 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1101 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1102 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1103 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1104 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1106 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1107 reason_names
[reason
], lpReserved
);
1111 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1113 status
= STATUS_DLL_INIT_FAILED
;
1117 TRACE_(relay
)("\1exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1118 entry
, module
, reason_names
[reason
], lpReserved
);
1119 status
= GetExceptionCode();
1123 /* The state of the module list may have changed due to the call
1124 to the dll. We cannot assume that this module has not been
1126 if (TRACE_ON(relay
))
1127 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1128 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1130 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1136 /*************************************************************************
1139 * Send the process attach notification to all DLLs the given module
1140 * depends on (recursively). This is somewhat complicated due to the fact that
1142 * - we have to respect the module dependencies, i.e. modules implicitly
1143 * referenced by another module have to be initialized before the module
1144 * itself can be initialized
1146 * - the initialization routine of a DLL can itself call LoadLibrary,
1147 * thereby introducing a whole new set of dependencies (even involving
1148 * the 'old' modules) at any time during the whole process
1150 * (Note that this routine can be recursively entered not only directly
1151 * from itself, but also via LoadLibrary from one of the called initialization
1154 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1155 * the process *detach* notifications to be sent in the correct order.
1156 * This must not only take into account module dependencies, but also
1157 * 'hidden' dependencies created by modules calling LoadLibrary in their
1158 * attach notification routine.
1160 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1161 * list after the attach notification has returned. This implies that the
1162 * detach notifications are called in the reverse of the sequence the attach
1163 * notifications *returned*.
1165 * The loader_section must be locked while calling this function.
1167 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1169 NTSTATUS status
= STATUS_SUCCESS
;
1173 if (process_detaching
) return status
;
1175 /* prevent infinite recursion in case of cyclical dependencies */
1176 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1177 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1180 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1182 /* Tag current MODREF to prevent recursive loop */
1183 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1184 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1185 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1187 /* Recursively attach all DLLs this one depends on */
1188 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1190 if (!wm
->deps
[i
]) continue;
1191 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1194 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1195 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1196 &wm
->ldr
.InInitializationOrderModuleList
);
1198 /* Call DLL entry point */
1199 if (status
== STATUS_SUCCESS
)
1201 WINE_MODREF
*prev
= current_modref
;
1202 current_modref
= wm
;
1203 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1204 if (status
== STATUS_SUCCESS
)
1205 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1208 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1209 /* point to the name so LdrInitializeThunk can print it */
1210 last_failed_modref
= wm
;
1211 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1213 current_modref
= prev
;
1216 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1217 /* Remove recursion flag */
1218 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1220 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1225 /**********************************************************************
1226 * attach_implicitly_loaded_dlls
1228 * Attach to the (builtin) dlls that have been implicitly loaded because
1229 * of a dependency at the Unix level, but not imported at the Win32 level.
1231 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1235 PLIST_ENTRY mark
, entry
;
1237 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1238 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1240 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1242 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1243 TRACE( "found implicitly loaded %s, attaching to it\n",
1244 debugstr_w(mod
->BaseDllName
.Buffer
));
1245 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1246 break; /* restart the search from the start */
1248 if (entry
== mark
) break; /* nothing found */
1253 /*************************************************************************
1256 * Send DLL process detach notifications. See the comment about calling
1257 * sequence at process_attach.
1259 static void process_detach(void)
1261 PLIST_ENTRY mark
, entry
;
1264 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1267 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1269 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1270 InInitializationOrderModuleList
);
1271 /* Check whether to detach this DLL */
1272 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1274 if ( mod
->LoadCount
&& !process_detaching
)
1277 /* Call detach notification */
1278 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1279 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1280 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1282 /* Restart at head of WINE_MODREF list, as entries might have
1283 been added and/or removed while performing the call ... */
1286 } while (entry
!= mark
);
1289 /*************************************************************************
1292 * Send DLL thread attach notifications. These are sent in the
1293 * reverse sequence of process detach notification.
1294 * The loader_section must be locked while calling this function.
1296 static void thread_attach(void)
1298 PLIST_ENTRY mark
, entry
;
1301 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1302 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1304 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1305 InInitializationOrderModuleList
);
1306 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1308 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1311 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1315 /******************************************************************
1316 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1319 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1322 NTSTATUS ret
= STATUS_SUCCESS
;
1324 RtlEnterCriticalSection( &loader_section
);
1326 wm
= get_modref( hModule
);
1327 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1328 ret
= STATUS_DLL_NOT_FOUND
;
1330 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1332 RtlLeaveCriticalSection( &loader_section
);
1337 /******************************************************************
1338 * LdrFindEntryForAddress (NTDLL.@)
1340 * The loader_section must be locked while calling this function
1342 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1344 PLIST_ENTRY mark
, entry
;
1347 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1348 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1350 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1351 if (mod
->BaseAddress
<= addr
&&
1352 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1355 return STATUS_SUCCESS
;
1358 return STATUS_NO_MORE_ENTRIES
;
1361 /******************************************************************
1362 * LdrEnumerateLoadedModules (NTDLL.@)
1364 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1366 LIST_ENTRY
*mark
, *entry
;
1368 BOOLEAN stop
= FALSE
;
1370 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1372 if (unknown
|| !callback
)
1373 return STATUS_INVALID_PARAMETER
;
1375 RtlEnterCriticalSection( &loader_section
);
1377 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1378 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1380 mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1381 callback( mod
, context
, &stop
);
1385 RtlLeaveCriticalSection( &loader_section
);
1386 return STATUS_SUCCESS
;
1389 /******************************************************************
1390 * LdrLockLoaderLock (NTDLL.@)
1392 * Note: some flags are not implemented.
1393 * Flag 0x01 is used to raise exceptions on errors.
1395 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1397 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1399 if (result
) *result
= 0;
1400 if (magic
) *magic
= 0;
1401 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1402 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1403 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1407 if (!RtlTryEnterCriticalSection( &loader_section
))
1410 return STATUS_SUCCESS
;
1416 RtlEnterCriticalSection( &loader_section
);
1417 if (result
) *result
= 1;
1419 *magic
= GetCurrentThreadId();
1420 return STATUS_SUCCESS
;
1424 /******************************************************************
1425 * LdrUnlockLoaderUnlock (NTDLL.@)
1427 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1431 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1432 RtlLeaveCriticalSection( &loader_section
);
1434 return STATUS_SUCCESS
;
1438 /******************************************************************
1439 * LdrGetProcedureAddress (NTDLL.@)
1441 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1442 ULONG ord
, PVOID
*address
)
1444 IMAGE_EXPORT_DIRECTORY
*exports
;
1446 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1448 RtlEnterCriticalSection( &loader_section
);
1450 /* check if the module itself is invalid to return the proper error */
1451 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1452 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1453 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1455 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1456 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1457 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1461 ret
= STATUS_SUCCESS
;
1465 RtlLeaveCriticalSection( &loader_section
);
1470 /***********************************************************************
1473 * Check if a loaded native dll is a Wine fake dll.
1475 static BOOL
is_fake_dll( HANDLE handle
)
1477 static const char fakedll_signature
[] = "Wine placeholder DLL";
1478 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1479 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1481 LARGE_INTEGER offset
;
1483 offset
.QuadPart
= 0;
1484 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1485 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1486 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1487 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1488 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1493 /***********************************************************************
1494 * get_builtin_fullname
1496 * Build the full pathname for a builtin dll.
1498 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1500 static const WCHAR soW
[] = {'.','s','o',0};
1501 WCHAR
*p
, *fullname
;
1502 size_t i
, len
= strlen(filename
);
1504 /* check if path can correspond to the dll we have */
1505 if (path
&& (p
= strrchrW( path
, '\\' )))
1508 for (i
= 0; i
< len
; i
++)
1509 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1510 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1512 /* the filename matches, use path as the full path */
1514 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1516 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1523 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1524 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1526 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1527 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1528 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1529 ascii_to_unicode( p
, filename
, len
+ 1 );
1535 /*************************************************************************
1538 static BOOL
is_16bit_builtin( HMODULE module
)
1540 const IMAGE_EXPORT_DIRECTORY
*exports
;
1543 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1544 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1547 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1551 /***********************************************************************
1552 * load_builtin_callback
1554 * Load a library in memory; callback function for wine_dll_register
1556 static void load_builtin_callback( void *module
, const char *filename
)
1558 static const WCHAR emptyW
[1];
1559 IMAGE_NT_HEADERS
*nt
;
1562 const WCHAR
*load_path
;
1566 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1569 if (!(nt
= RtlImageNtHeader( module
)))
1571 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1572 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1576 virtual_create_builtin_view( module
);
1578 /* create the MODREF */
1580 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1582 ERR( "can't load %s\n", filename
);
1583 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1587 wm
= alloc_module( module
, fullname
);
1588 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1591 ERR( "can't load %s\n", filename
);
1592 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1595 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1597 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1598 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1599 is_16bit_builtin( module
))
1603 load_path
= builtin_load_info
->load_path
;
1604 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1605 if (!load_path
) load_path
= emptyW
;
1606 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1608 /* the module has only be inserted in the load & memory order lists */
1609 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1610 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1611 /* FIXME: free the modref */
1612 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1617 builtin_load_info
->wm
= wm
;
1618 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1620 /* send the DLL load event */
1622 SERVER_START_REQ( load_dll
)
1624 req
->base
= wine_server_client_ptr( module
);
1625 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1626 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1627 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1628 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1629 wine_server_call( req
);
1633 /* setup relay debugging entry points */
1634 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1638 /***********************************************************************
1639 * set_security_cookie
1641 * Create a random security cookie for buffer overflow protection. Make
1642 * sure it does not accidentally match the default cookie value.
1644 static void set_security_cookie( void *module
, SIZE_T len
)
1647 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1651 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1652 if (!loadcfg
) return;
1653 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1654 if (!loadcfg
->SecurityCookie
) return;
1655 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1656 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1658 WARN( "security cookie %p outside of image %p-%p\n",
1659 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1663 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1664 TRACE( "initializing security cookie %p\n", cookie
);
1666 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1669 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1670 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1671 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1672 *cookie
= RtlRandom( &seed
);
1673 #ifdef DEFAULT_SECURITY_COOKIE_64
1674 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1676 *cookie
= RtlRandom( &seed
);
1677 /* fill up, but keep the highest word clear */
1678 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1686 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1688 IMAGE_NT_HEADERS
*nt
;
1690 IMAGE_BASE_RELOCATION
*rel
, *end
;
1691 const IMAGE_DATA_DIRECTORY
*relocs
;
1692 const IMAGE_SECTION_HEADER
*sec
;
1694 ULONG protect_old
[96], i
;
1696 nt
= RtlImageNtHeader( module
);
1697 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1699 assert( module
!= base
);
1701 /* no relocations are performed on non page-aligned binaries */
1702 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1703 return STATUS_SUCCESS
;
1705 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1706 return STATUS_SUCCESS
;
1708 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1710 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1712 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1714 return STATUS_CONFLICTING_ADDRESSES
;
1717 if (!relocs
->Size
) return STATUS_SUCCESS
;
1718 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1720 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1721 return STATUS_INVALID_IMAGE_FORMAT
;
1723 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1724 nt
->FileHeader
.SizeOfOptionalHeader
);
1725 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1727 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1728 SIZE_T size
= sec
[i
].SizeOfRawData
;
1729 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1730 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1733 TRACE( "relocating from %p-%p to %p-%p\n",
1734 base
, base
+ len
, module
, (char *)module
+ len
);
1736 rel
= get_rva( module
, relocs
->VirtualAddress
);
1737 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1738 delta
= (char *)module
- base
;
1740 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1742 if (rel
->VirtualAddress
>= len
)
1744 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1745 return STATUS_ACCESS_VIOLATION
;
1747 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1748 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1749 (USHORT
*)(rel
+ 1), delta
);
1750 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1753 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1755 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1756 SIZE_T size
= sec
[i
].SizeOfRawData
;
1757 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1758 &size
, protect_old
[i
], &protect_old
[i
] );
1761 return STATUS_SUCCESS
;
1765 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
1766 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
1767 static BOOL
is_valid_binary( const pe_image_info_t
*info
)
1770 return info
->machine
== IMAGE_FILE_MACHINE_I386
;
1771 #elif defined(__x86_64__)
1772 return info
->machine
== IMAGE_FILE_MACHINE_AMD64
|| !info
->contains_code
;
1773 #elif defined(__arm__)
1774 return info
->machine
== IMAGE_FILE_MACHINE_ARM
||
1775 info
->machine
== IMAGE_FILE_MACHINE_THUMB
||
1776 info
->machine
== IMAGE_FILE_MACHINE_ARMNT
;
1777 #elif defined(__aarch64__)
1778 return info
->machine
== IMAGE_FILE_MACHINE_ARM64
|| !info
->contains_code
;
1780 return FALSE
; /* no wow64 support on other platforms */
1785 /******************************************************************************
1786 * load_native_dll (internal)
1788 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1789 DWORD flags
, WINE_MODREF
** pwm
)
1794 IMAGE_NT_HEADERS
*nt
;
1798 pe_image_info_t image_info
;
1800 TRACE("Trying native dll %s\n", debugstr_w(name
));
1803 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
1804 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
1805 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1806 if (status
!= STATUS_SUCCESS
) return status
;
1809 status
= virtual_map_section( mapping
, &module
, 0, 0, NULL
, &len
, PAGE_EXECUTE_READ
, &image_info
);
1812 if ((status
== STATUS_SUCCESS
|| status
== STATUS_IMAGE_NOT_AT_BASE
) &&
1813 !is_valid_binary( &image_info
))
1815 NtUnmapViewOfSection( NtCurrentProcess(), module
);
1816 return STATUS_INVALID_IMAGE_FORMAT
;
1819 /* perform base relocation, if necessary */
1821 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1822 status
= perform_relocations( module
, len
);
1824 if (status
!= STATUS_SUCCESS
)
1826 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1830 /* create the MODREF */
1832 if (!(wm
= alloc_module( module
, name
)))
1834 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1835 return STATUS_NO_MEMORY
;
1838 set_security_cookie( module
, len
);
1842 nt
= RtlImageNtHeader( module
);
1844 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1845 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1846 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1848 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1850 /* the module has only be inserted in the load & memory order lists */
1851 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1852 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1854 /* FIXME: there are several more dangling references
1855 * left. Including dlls loaded by this dll before the
1856 * failed one. Unrolling is rather difficult with the
1857 * current structure and we can leave them lying
1858 * around with no problems, so we don't care.
1859 * As these might reference our wm, we don't free it.
1865 /* send DLL load event */
1867 SERVER_START_REQ( load_dll
)
1869 req
->base
= wine_server_client_ptr( module
);
1870 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1871 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1872 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1873 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1874 wine_server_call( req
);
1878 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1880 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1882 wm
->ldr
.LoadCount
= 1;
1884 return STATUS_SUCCESS
;
1888 /***********************************************************************
1891 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1892 DWORD flags
, WINE_MODREF
** pwm
)
1894 char error
[256], dllname
[MAX_PATH
];
1895 const WCHAR
*name
, *p
;
1898 struct builtin_load_info info
, *prev_info
;
1900 /* Fix the name in case we have a full path and extension */
1902 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1903 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1905 /* load_library will modify info.status. Note also that load_library can be
1906 * called several times, if the .so file we're loading has dependencies.
1907 * info.status will gather all the errors we may get while loading all these
1910 info
.load_path
= load_path
;
1911 info
.filename
= NULL
;
1912 info
.status
= STATUS_SUCCESS
;
1915 if (file
) /* we have a real file, try to load it */
1917 UNICODE_STRING nt_name
;
1918 ANSI_STRING unix_name
;
1920 TRACE("Trying built-in %s\n", debugstr_w(path
));
1922 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1923 return STATUS_DLL_NOT_FOUND
;
1925 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1927 RtlFreeUnicodeString( &nt_name
);
1928 return STATUS_DLL_NOT_FOUND
;
1930 prev_info
= builtin_load_info
;
1931 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1932 builtin_load_info
= &info
;
1933 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1934 builtin_load_info
= prev_info
;
1935 RtlFreeUnicodeString( &nt_name
);
1936 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1939 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1940 return STATUS_INVALID_IMAGE_FORMAT
;
1947 TRACE("Trying built-in %s\n", debugstr_w(name
));
1949 /* we don't want to depend on the current codepage here */
1950 len
= strlenW( name
) + 1;
1951 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1952 for (i
= 0; i
< len
; i
++)
1954 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1955 dllname
[i
] = (char)name
[i
];
1956 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1959 prev_info
= builtin_load_info
;
1960 builtin_load_info
= &info
;
1961 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1962 builtin_load_info
= prev_info
;
1967 /* The file does not exist -> WARN() */
1968 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1969 return STATUS_DLL_NOT_FOUND
;
1971 /* ERR() for all other errors (missing functions, ...) */
1972 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1973 return STATUS_PROCEDURE_NOT_FOUND
;
1977 if (info
.status
!= STATUS_SUCCESS
)
1979 wine_dll_unload( handle
);
1985 PLIST_ENTRY mark
, entry
;
1987 /* The constructor wasn't called, this means the .so is already
1988 * loaded under a different name. Try to find the wm for it. */
1990 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1991 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1993 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1994 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1996 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1997 TRACE( "Found %s at %p for builtin %s\n",
1998 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
2002 wine_dll_unload( handle
); /* release the libdl refcount */
2003 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
2004 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
2008 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
2009 info
.wm
->ldr
.LoadCount
= 1;
2010 info
.wm
->ldr
.SectionHandle
= handle
;
2014 return STATUS_SUCCESS
;
2018 /***********************************************************************
2021 * Find the full path (if any) of the dll from the activation context.
2023 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2025 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2026 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2028 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2029 ACTCTX_SECTION_KEYED_DATA data
;
2030 UNICODE_STRING nameW
;
2032 SIZE_T needed
, size
= 1024;
2035 RtlInitUnicodeString( &nameW
, libname
);
2036 data
.cbSize
= sizeof(data
);
2037 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2038 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2040 if (status
!= STATUS_SUCCESS
) return status
;
2044 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2046 status
= STATUS_NO_MEMORY
;
2049 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2050 AssemblyDetailedInformationInActivationContext
,
2051 info
, size
, &needed
);
2052 if (status
== STATUS_SUCCESS
) break;
2053 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2054 RtlFreeHeap( GetProcessHeap(), 0, info
);
2056 /* restart with larger buffer */
2059 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2061 status
= STATUS_SXS_KEY_NOT_FOUND
;
2065 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2067 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2070 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2072 /* manifest name does not match directory name, so it's not a global
2073 * windows/winsxs manifest; use the manifest directory name instead */
2074 dirlen
= p
- info
->lpAssemblyManifestPath
;
2075 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2076 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2078 status
= STATUS_NO_MEMORY
;
2081 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2083 strcpyW( p
, libname
);
2088 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2089 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2091 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2093 status
= STATUS_NO_MEMORY
;
2096 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2098 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2099 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2100 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2101 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2103 strcpyW( p
, libname
);
2105 RtlFreeHeap( GetProcessHeap(), 0, info
);
2106 RtlReleaseActivationContext( data
.hActCtx
);
2111 /***********************************************************************
2114 * Find the file (or already loaded module) for a given dll name.
2116 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2117 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
2119 OBJECT_ATTRIBUTES attr
;
2121 UNICODE_STRING nt_name
;
2122 WCHAR
*file_part
, *ext
, *dllname
;
2125 /* first append .dll if needed */
2128 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2130 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2131 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2132 return STATUS_NO_MEMORY
;
2133 strcpyW( dllname
, libname
);
2134 strcatW( dllname
, dllW
);
2138 nt_name
.Buffer
= NULL
;
2140 if (!contains_path( libname
))
2143 WCHAR
*fullname
= NULL
;
2145 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2147 status
= find_actctx_dll( libname
, &fullname
);
2148 if (status
== STATUS_SUCCESS
)
2150 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2151 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2152 libname
= dllname
= fullname
;
2154 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2156 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2161 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2163 /* we need to search for it */
2164 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2167 if (len
>= *size
) goto overflow
;
2168 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
2170 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2172 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2173 return STATUS_NO_MEMORY
;
2175 attr
.Length
= sizeof(attr
);
2176 attr
.RootDirectory
= 0;
2177 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2178 attr
.ObjectName
= &nt_name
;
2179 attr
.SecurityDescriptor
= NULL
;
2180 attr
.SecurityQualityOfService
= NULL
;
2181 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2187 if (!contains_path( libname
))
2189 /* if libname doesn't contain a path at all, we simply return the name as is,
2190 * to be loaded as builtin */
2191 len
= strlenW(libname
) * sizeof(WCHAR
);
2192 if (len
>= *size
) goto overflow
;
2193 strcpyW( filename
, libname
);
2198 /* absolute path name, or relative path name but not found above */
2200 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2202 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2203 return STATUS_NO_MEMORY
;
2205 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2206 if (len
>= *size
) goto overflow
;
2207 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2208 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
2210 attr
.Length
= sizeof(attr
);
2211 attr
.RootDirectory
= 0;
2212 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2213 attr
.ObjectName
= &nt_name
;
2214 attr
.SecurityDescriptor
= NULL
;
2215 attr
.SecurityQualityOfService
= NULL
;
2216 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2219 RtlFreeUnicodeString( &nt_name
);
2220 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2221 return STATUS_SUCCESS
;
2224 RtlFreeUnicodeString( &nt_name
);
2225 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2226 *size
= len
+ sizeof(WCHAR
);
2227 return STATUS_BUFFER_TOO_SMALL
;
2231 /***********************************************************************
2232 * load_dll (internal)
2234 * Load a PE style module according to the load order.
2235 * The loader_section must be locked while calling this function.
2237 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2239 enum loadorder loadorder
;
2243 WINE_MODREF
*main_exe
;
2247 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2251 size
= sizeof(buffer
);
2254 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2255 if (nts
== STATUS_SUCCESS
) break;
2256 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2257 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2258 /* grow the buffer and retry */
2259 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2262 if (*pwm
) /* found already loaded module */
2264 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2266 TRACE("Found %s for %s at %p, count=%d\n",
2267 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2268 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2269 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2270 return STATUS_SUCCESS
;
2273 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2274 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2276 if (handle
&& is_fake_dll( handle
))
2278 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2286 nts
= STATUS_NO_MEMORY
;
2289 nts
= STATUS_DLL_NOT_FOUND
;
2292 case LO_NATIVE_BUILTIN
:
2293 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2296 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2297 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2298 /* not in PE format, maybe it's a builtin */
2299 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2301 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2302 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2305 case LO_BUILTIN_NATIVE
:
2306 case LO_DEFAULT
: /* default is builtin,native */
2307 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2308 if (!handle
) break; /* nothing else we can try */
2309 /* file is not a builtin library, try without using the specified file */
2310 if (nts
!= STATUS_SUCCESS
)
2311 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2312 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2313 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2315 /* stub-only dll, try native */
2316 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2317 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2318 nts
= STATUS_DLL_NOT_FOUND
;
2320 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2321 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2325 if (nts
== STATUS_SUCCESS
)
2327 /* Initialize DLL just loaded */
2328 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2329 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2330 (*pwm
)->ldr
.BaseAddress
);
2331 if (handle
) NtClose( handle
);
2332 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2336 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2337 if (handle
) NtClose( handle
);
2338 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2342 /******************************************************************
2343 * LdrLoadDll (NTDLL.@)
2345 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2346 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2351 RtlEnterCriticalSection( &loader_section
);
2353 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2354 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2356 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2358 nts
= process_attach( wm
, NULL
);
2359 if (nts
!= STATUS_SUCCESS
)
2361 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2365 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2367 RtlLeaveCriticalSection( &loader_section
);
2372 /******************************************************************
2373 * LdrGetDllHandle (NTDLL.@)
2375 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2383 RtlEnterCriticalSection( &loader_section
);
2385 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2388 size
= sizeof(buffer
);
2391 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2392 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2393 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2394 /* grow the buffer and retry */
2395 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2397 status
= STATUS_NO_MEMORY
;
2402 if (status
== STATUS_SUCCESS
)
2404 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2405 else status
= STATUS_DLL_NOT_FOUND
;
2408 RtlLeaveCriticalSection( &loader_section
);
2409 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2414 /******************************************************************
2415 * LdrAddRefDll (NTDLL.@)
2417 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2419 NTSTATUS ret
= STATUS_SUCCESS
;
2422 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2424 RtlEnterCriticalSection( &loader_section
);
2426 if ((wm
= get_modref( module
)))
2428 if (flags
& LDR_ADDREF_DLL_PIN
)
2429 wm
->ldr
.LoadCount
= -1;
2431 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2432 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2434 else ret
= STATUS_INVALID_PARAMETER
;
2436 RtlLeaveCriticalSection( &loader_section
);
2441 /***********************************************************************
2442 * LdrProcessRelocationBlock (NTDLL.@)
2444 * Apply relocations to a given page of a mapped PE image.
2446 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2447 USHORT
*relocs
, INT_PTR delta
)
2451 USHORT offset
= *relocs
& 0xfff;
2452 int type
= *relocs
>> 12;
2455 case IMAGE_REL_BASED_ABSOLUTE
:
2457 case IMAGE_REL_BASED_HIGH
:
2458 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2460 case IMAGE_REL_BASED_LOW
:
2461 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2463 case IMAGE_REL_BASED_HIGHLOW
:
2464 *(int *)((char *)page
+ offset
) += delta
;
2467 case IMAGE_REL_BASED_DIR64
:
2468 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2470 #elif defined(__arm__)
2471 case IMAGE_REL_BASED_THUMB_MOV32
:
2473 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2474 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2475 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2478 if ((inst
& 0x8000fbf0) != 0x0000f240)
2479 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2481 imm16
+= LOWORD(delta
);
2482 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2483 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2484 ((imm16
>> 12) & 0x000f) +
2485 ((imm16
<< 20) & 0x70000000) +
2486 ((imm16
<< 16) & 0xff0000);
2490 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2491 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2492 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2494 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2495 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2499 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2500 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2501 ((imm16
>> 1) & 0x0400) +
2502 ((imm16
>> 12) & 0x000f) +
2503 ((imm16
<< 20) & 0x70000000) +
2504 ((imm16
<< 16) & 0xff0000);
2510 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2515 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2519 /******************************************************************
2520 * LdrQueryProcessModuleInformation
2523 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2524 ULONG buf_size
, ULONG
* req_size
)
2526 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2527 ULONG size
= sizeof(ULONG
);
2528 NTSTATUS nts
= STATUS_SUCCESS
;
2531 PLIST_ENTRY mark
, entry
;
2535 smi
->ModulesCount
= 0;
2537 RtlEnterCriticalSection( &loader_section
);
2538 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2539 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2541 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2542 size
+= sizeof(*sm
);
2543 if (size
<= buf_size
)
2545 sm
->Reserved1
= 0; /* FIXME */
2546 sm
->Reserved2
= 0; /* FIXME */
2547 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2548 sm
->ImageSize
= mod
->SizeOfImage
;
2549 sm
->Flags
= mod
->Flags
;
2551 sm
->Rank
= 0; /* FIXME */
2552 sm
->Unknown
= 0; /* FIXME */
2554 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2555 str
.Buffer
= (char*)sm
->Name
;
2556 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2557 ptr
= strrchr(str
.Buffer
, '\\');
2558 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2560 smi
->ModulesCount
++;
2563 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2565 RtlLeaveCriticalSection( &loader_section
);
2567 if (req_size
) *req_size
= size
;
2573 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2579 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2581 RtlInitUnicodeString( &str
, name
);
2583 size
= sizeof(buffer
) - sizeof(WCHAR
);
2584 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2587 if (info
->Type
!= REG_DWORD
)
2589 buffer
[size
/ sizeof(WCHAR
)] = 0;
2590 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2592 else memcpy( value
, info
->Data
, sizeof(*value
) );
2596 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2597 void *data
, ULONG in_size
, ULONG
*out_size
)
2603 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2604 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2606 RtlInitUnicodeString( &str
, name
);
2608 size
= info_size
+ in_size
;
2609 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2610 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2611 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2612 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2614 if (out_size
) *out_size
= info
->DataLength
;
2615 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2617 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2622 /******************************************************************
2623 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2625 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2626 void *data
, ULONG in_size
, ULONG
*out_size
)
2628 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2629 'S','o','f','t','w','a','r','e','\\',
2630 'M','i','c','r','o','s','o','f','t','\\',
2631 'W','i','n','d','o','w','s',' ','N','T','\\',
2632 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2633 'I','m','a','g','e',' ','F','i','l','e',' ',
2634 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2635 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2636 OBJECT_ATTRIBUTES attr
;
2637 UNICODE_STRING name_str
;
2643 attr
.Length
= sizeof(attr
);
2644 attr
.RootDirectory
= 0;
2645 attr
.ObjectName
= &name_str
;
2646 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2647 attr
.SecurityDescriptor
= NULL
;
2648 attr
.SecurityQualityOfService
= NULL
;
2650 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2651 else p
= key
->Buffer
;
2652 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2653 name_str
.Buffer
= path
;
2654 name_str
.Length
= sizeof(optionsW
) + len
;
2655 name_str
.MaximumLength
= name_str
.Length
;
2656 memcpy( path
, optionsW
, sizeof(optionsW
) );
2657 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2658 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2660 if (type
== REG_DWORD
)
2662 if (out_size
) *out_size
= sizeof(ULONG
);
2663 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2664 else status
= STATUS_BUFFER_OVERFLOW
;
2666 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2673 /******************************************************************
2674 * RtlDllShutdownInProgress (NTDLL.@)
2676 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2678 return process_detaching
;
2681 /****************************************************************************
2682 * LdrResolveDelayLoadedAPI (NTDLL.@)
2684 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2685 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2686 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2688 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2689 DELAYLOAD_INFO delayinfo
;
2697 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2699 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2700 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2701 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2702 name
= get_rva(base
, desc
->DllNameRVA
);
2707 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2709 nts
= STATUS_NO_MEMORY
;
2712 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2713 RtlFreeUnicodeString(&mod
);
2717 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2718 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2721 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2724 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2725 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2729 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2734 delayinfo
.Size
= sizeof(delayinfo
);
2735 delayinfo
.DelayloadDescriptor
= desc
;
2736 delayinfo
.ThunkAddress
= addr
;
2737 delayinfo
.TargetDllName
= name
;
2738 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2739 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2740 delayinfo
.TargetModuleBase
= *phmod
;
2741 delayinfo
.Unused
= NULL
;
2742 delayinfo
.LastError
= nts
;
2743 return dllhook(4, &delayinfo
);
2746 /******************************************************************
2747 * LdrShutdownProcess (NTDLL.@)
2750 void WINAPI
LdrShutdownProcess(void)
2753 process_detaching
= TRUE
;
2758 /******************************************************************
2759 * RtlExitUserProcess (NTDLL.@)
2761 void WINAPI
RtlExitUserProcess( DWORD status
)
2763 RtlEnterCriticalSection( &loader_section
);
2764 RtlAcquirePebLock();
2765 NtTerminateProcess( 0, status
);
2766 LdrShutdownProcess();
2767 NtTerminateProcess( GetCurrentProcess(), status
);
2771 /******************************************************************
2772 * LdrShutdownThread (NTDLL.@)
2775 void WINAPI
LdrShutdownThread(void)
2777 PLIST_ENTRY mark
, entry
;
2784 /* don't do any detach calls if process is exiting */
2785 if (process_detaching
) return;
2787 RtlEnterCriticalSection( &loader_section
);
2789 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2790 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2792 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2793 InInitializationOrderModuleList
);
2794 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2796 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2799 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2800 DLL_THREAD_DETACH
, NULL
);
2803 RtlAcquirePebLock();
2804 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2805 RtlReleasePebLock();
2807 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2809 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2810 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2812 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2813 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2814 RtlLeaveCriticalSection( &loader_section
);
2818 /***********************************************************************
2822 static void free_modref( WINE_MODREF
*wm
)
2824 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2825 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2826 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2827 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2829 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2830 if (!TRACE_ON(module
))
2831 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2832 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2833 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2835 SERVER_START_REQ( unload_dll
)
2837 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2838 wine_server_call( req
);
2842 free_tls_slot( &wm
->ldr
);
2843 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2844 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2845 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2846 if (cached_modref
== wm
) cached_modref
= NULL
;
2847 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2848 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2849 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2852 /***********************************************************************
2853 * MODULE_FlushModrefs
2855 * Remove all unused modrefs and call the internal unloading routines
2856 * for the library type.
2858 * The loader_section must be locked while calling this function.
2860 static void MODULE_FlushModrefs(void)
2862 PLIST_ENTRY mark
, entry
, prev
;
2866 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2867 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2869 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2870 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2871 prev
= entry
->Blink
;
2872 if (!mod
->LoadCount
) free_modref( wm
);
2875 /* check load order list too for modules that haven't been initialized yet */
2876 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2877 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2879 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2880 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2881 prev
= entry
->Blink
;
2882 if (!mod
->LoadCount
) free_modref( wm
);
2886 /***********************************************************************
2887 * MODULE_DecRefCount
2889 * The loader_section must be locked while calling this function.
2891 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2895 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2898 if ( wm
->ldr
.LoadCount
<= 0 )
2901 --wm
->ldr
.LoadCount
;
2902 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2904 if ( wm
->ldr
.LoadCount
== 0 )
2906 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2908 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2910 MODULE_DecRefCount( wm
->deps
[i
] );
2912 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2916 /******************************************************************
2917 * LdrUnloadDll (NTDLL.@)
2921 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2924 NTSTATUS retv
= STATUS_SUCCESS
;
2926 if (process_detaching
) return retv
;
2928 TRACE("(%p)\n", hModule
);
2930 RtlEnterCriticalSection( &loader_section
);
2933 if ((wm
= get_modref( hModule
)) != NULL
)
2935 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2937 /* Recursively decrement reference counts */
2938 MODULE_DecRefCount( wm
);
2940 /* Call process detach notifications */
2941 if ( free_lib_count
<= 1 )
2944 MODULE_FlushModrefs();
2950 retv
= STATUS_DLL_NOT_FOUND
;
2954 RtlLeaveCriticalSection( &loader_section
);
2959 /***********************************************************************
2960 * RtlImageNtHeader (NTDLL.@)
2962 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2964 IMAGE_NT_HEADERS
*ret
;
2968 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2971 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2973 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2974 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2986 /***********************************************************************
2989 * Attach to all the loaded dlls.
2990 * If this is the first time, perform the full process initialization.
2992 NTSTATUS
attach_dlls( CONTEXT
*context
)
2996 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2998 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
3000 if (process_detaching
) return STATUS_SUCCESS
;
3002 RtlEnterCriticalSection( &loader_section
);
3004 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3007 if (!imports_fixup_done
)
3010 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
3012 ERR( "Importing dlls for %s failed, status %x\n",
3013 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3014 NtTerminateProcess( GetCurrentProcess(), status
);
3016 imports_fixup_done
= TRUE
;
3019 RtlAcquirePebLock();
3020 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
3021 RtlReleasePebLock();
3023 if (!(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
)) /* first time around */
3025 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3027 ERR( "TLS init failed when loading %s, status %x\n",
3028 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3029 NtTerminateProcess( GetCurrentProcess(), status
);
3031 if ((status
= process_attach( wm
, context
)) != STATUS_SUCCESS
)
3033 if (last_failed_modref
)
3034 ERR( "%s failed to initialize, aborting\n",
3035 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3036 ERR( "Initializing dlls for %s failed, status %x\n",
3037 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3038 NtTerminateProcess( GetCurrentProcess(), status
);
3040 attach_implicitly_loaded_dlls( context
);
3041 virtual_release_address_space();
3045 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3046 NtTerminateThread( GetCurrentThread(), status
);
3050 RtlLeaveCriticalSection( &loader_section
);
3051 return STATUS_SUCCESS
;
3055 /***********************************************************************
3056 * load_global_options
3058 static void load_global_options(void)
3060 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
3061 'S','y','s','t','e','m','\\',
3062 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3063 'C','o','n','t','r','o','l','\\',
3064 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3065 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3066 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};
3067 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3068 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3069 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};
3070 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};
3072 OBJECT_ATTRIBUTES attr
;
3073 UNICODE_STRING name_str
;
3077 attr
.Length
= sizeof(attr
);
3078 attr
.RootDirectory
= 0;
3079 attr
.ObjectName
= &name_str
;
3080 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3081 attr
.SecurityDescriptor
= NULL
;
3082 attr
.SecurityQualityOfService
= NULL
;
3083 RtlInitUnicodeString( &name_str
, sessionW
);
3085 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3087 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3089 query_dword_option( hkey
, critsectW
, &value
);
3090 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3092 query_dword_option( hkey
, heapresW
, &value
);
3093 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3095 query_dword_option( hkey
, heapcommitW
, &value
);
3096 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3098 query_dword_option( hkey
, decommittotalW
, &value
);
3099 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3101 query_dword_option( hkey
, decommitfreeW
, &value
);
3102 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3108 /******************************************************************
3109 * LdrInitializeThunk (NTDLL.@)
3112 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3113 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3115 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3118 PEB
*peb
= NtCurrentTeb()->Peb
;
3120 kernel32_start_process
= kernel_start
;
3121 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3123 /* allocate the modref for the main exe (if not already done) */
3124 wm
= get_modref( peb
->ImageBaseAddress
);
3126 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3128 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3132 peb
->LoaderLock
= &loader_section
;
3133 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3134 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3135 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3136 version_init( wm
->ldr
.FullDllName
.Buffer
);
3137 virtual_set_large_address_space();
3139 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3140 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3141 heap_set_debug_flags( GetProcessHeap() );
3143 /* the main exe needs to be the first in the load order list */
3144 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3145 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3146 RemoveEntryList( &wm
->ldr
.InMemoryOrderModuleList
);
3147 InsertHeadList( &peb
->LdrData
->InMemoryOrderModuleList
, &wm
->ldr
.InMemoryOrderModuleList
);
3149 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL
)) != STATUS_SUCCESS
)
3151 ERR( "Main exe initialization for %s failed, status %x\n",
3152 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3153 NtTerminateProcess( GetCurrentProcess(), status
);
3155 server_init_process_done();
3159 /***********************************************************************
3160 * RtlImageDirectoryEntryToData (NTDLL.@)
3162 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3164 const IMAGE_NT_HEADERS
*nt
;
3167 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
3169 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
3172 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3173 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3175 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3177 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3178 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3179 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3180 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3182 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3184 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3186 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3187 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3188 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3189 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3193 /* not mapped as image, need to find the section containing the virtual address */
3194 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3198 /***********************************************************************
3199 * RtlImageRvaToSection (NTDLL.@)
3201 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3202 HMODULE module
, DWORD rva
)
3205 const IMAGE_SECTION_HEADER
*sec
;
3207 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3208 nt
->FileHeader
.SizeOfOptionalHeader
);
3209 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3211 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3212 return (PIMAGE_SECTION_HEADER
)sec
;
3218 /***********************************************************************
3219 * RtlImageRvaToVa (NTDLL.@)
3221 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3222 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3224 IMAGE_SECTION_HEADER
*sec
;
3226 if (section
&& *section
) /* try this section first */
3229 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3232 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3234 if (section
) *section
= sec
;
3235 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3239 /***********************************************************************
3240 * RtlPcToFileHeader (NTDLL.@)
3242 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3247 RtlEnterCriticalSection( &loader_section
);
3248 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3249 RtlLeaveCriticalSection( &loader_section
);
3255 /***********************************************************************
3256 * NtLoadDriver (NTDLL.@)
3257 * ZwLoadDriver (NTDLL.@)
3259 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3261 FIXME("(%p), stub!\n",DriverServiceName
);
3262 return STATUS_NOT_IMPLEMENTED
;
3266 /***********************************************************************
3267 * NtUnloadDriver (NTDLL.@)
3268 * ZwUnloadDriver (NTDLL.@)
3270 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3272 FIXME("(%p), stub!\n",DriverServiceName
);
3273 return STATUS_NOT_IMPLEMENTED
;
3277 /******************************************************************
3280 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3282 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3287 /******************************************************************
3288 * __wine_init_windows_dir (NTDLL.@)
3290 * Windows and system dir initialization once kernel32 has been loaded.
3292 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
3294 PLIST_ENTRY mark
, entry
;
3297 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
3298 DIR_init_windows_dir( windir
, sysdir
);
3300 /* prepend the system dir to the name of the already created modules */
3301 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3302 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3304 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
3306 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
3308 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
3309 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
3310 if (!buffer
) continue;
3311 strcpyW( buffer
, system_dir
.Buffer
);
3312 p
= buffer
+ strlenW( buffer
);
3313 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
3314 strcpyW( p
, mod
->FullDllName
.Buffer
);
3315 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
3316 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
3321 /***********************************************************************
3322 * __wine_process_init
3324 void __wine_process_init(void)
3326 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3330 ANSI_STRING func_name
;
3331 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3333 main_exe_file
= thread_init();
3335 /* retrieve current umask */
3336 FILE_umask
= umask(0777);
3337 umask( FILE_umask
);
3339 load_global_options();
3341 /* setup the load callback and create ntdll modref */
3342 wine_dll_set_callback( load_builtin_callback
);
3344 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3346 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3349 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3350 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3352 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3353 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3354 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3356 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);