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 /* system directory with trailing backslash */
67 const WCHAR system_dir
[] = {'C',':','\\','w','i','n','d','o','w','s','\\',
68 's','y','s','t','e','m','3','2','\\',0};
70 static BOOL imports_fixup_done
= FALSE
; /* set once the imports have been fixed up, before attaching them */
71 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
72 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
74 static const char * const reason_names
[] =
80 NULL
, NULL
, NULL
, NULL
,
84 static const WCHAR dllW
[] = {'.','d','l','l',0};
86 /* internal representation of 32bit modules. per process. */
87 typedef struct _wine_modref
91 struct _wine_modref
**deps
;
94 /* info about the current builtin dll load */
95 /* used to keep track of things across the register_dll constructor call */
96 struct builtin_load_info
98 const WCHAR
*load_path
;
99 const WCHAR
*filename
;
104 static struct builtin_load_info default_load_info
;
105 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
107 static HANDLE main_exe_file
;
108 static UINT tls_module_count
; /* number of modules with TLS directory */
109 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
110 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
112 static RTL_CRITICAL_SECTION loader_section
;
113 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
115 0, 0, &loader_section
,
116 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
117 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
119 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
121 static WINE_MODREF
*cached_modref
;
122 static WINE_MODREF
*current_modref
;
123 static WINE_MODREF
*last_failed_modref
;
125 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
126 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
127 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
128 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
129 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
130 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
132 /* convert PE image VirtualAddress to Real Address */
133 static inline void *get_rva( HMODULE module
, DWORD va
)
135 return (void *)((char *)module
+ va
);
138 /* check whether the file name contains a path */
139 static inline BOOL
contains_path( LPCWSTR name
)
141 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
144 /* convert from straight ASCII to Unicode without depending on the current codepage */
145 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
147 while (len
--) *dst
++ = (unsigned char)*src
++;
151 /*************************************************************************
152 * call_dll_entry_point
154 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
155 * their entry point, so we need a small asm wrapper. Testing indicates
156 * that only modifying esi leads to a crash, so use this one to backup
157 * ebp while running the dll entry proc.
160 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
161 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
163 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
164 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
166 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
168 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
170 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
172 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
174 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
178 "movl 8(%ebp),%eax\n\t"
181 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
182 "leal -12(%ebp),%esp\n\t"
184 __ASM_CFI(".cfi_same_value %edi\n\t")
186 __ASM_CFI(".cfi_same_value %esi\n\t")
188 __ASM_CFI(".cfi_same_value %ebx\n\t")
190 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
191 __ASM_CFI(".cfi_same_value %ebp\n\t")
194 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
195 UINT reason
, void *reserved
)
197 return proc( module
, reason
, reserved
);
199 #endif /* __i386__ */
202 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
203 /*************************************************************************
206 * Entry point for stub functions.
208 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
210 EXCEPTION_RECORD rec
;
212 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
213 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
214 rec
.ExceptionRecord
= NULL
;
215 rec
.ExceptionAddress
= ret_addr
;
216 rec
.NumberParameters
= 2;
217 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
218 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
219 for (;;) RtlRaiseException( &rec
);
223 #include "pshpack1.h"
227 BYTE pushl1
; /* pushl $name */
229 BYTE pushl2
; /* pushl $dll */
231 BYTE call
; /* call stub_entry_point */
234 #elif defined(__arm__)
237 DWORD ldr_r0
; /* ldr r0, $dll */
238 DWORD ldr_r1
; /* ldr r1, $name */
239 DWORD mov_r2_lr
; /* mov r2, lr */
240 DWORD ldr_pc_pc
; /* ldr pc, [pc, #4] */
245 #elif defined(__aarch64__)
248 DWORD ldr_x0
; /* ldr x0, $dll */
249 DWORD ldr_x1
; /* ldr x1, $name */
250 DWORD mov_x2_lr
; /* mov x2, lr */
251 DWORD ldr_x16
; /* ldr x16, $entry */
252 DWORD br_x16
; /* br x16 */
260 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
262 BYTE movq_rsi
[2]; /* movq $name,%rsi */
264 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
265 BYTE movq_rax
[2]; /* movq $entry, %rax */
267 BYTE jmpq_rax
[2]; /* jmp %rax */
272 /*************************************************************************
275 * Allocate a stub entry point.
277 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
279 #define MAX_SIZE 65536
280 static struct stub
*stubs
;
281 static unsigned int nb_stubs
;
284 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
288 SIZE_T size
= MAX_SIZE
;
289 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
290 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
293 stub
= &stubs
[nb_stubs
++];
295 stub
->pushl1
= 0x68; /* pushl $name */
297 stub
->pushl2
= 0x68; /* pushl $dll */
299 stub
->call
= 0xe8; /* call stub_entry_point */
300 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
301 #elif defined(__arm__)
302 stub
->ldr_r0
= 0xe59f0008; /* ldr r0, [pc, #8] ($dll) */
303 stub
->ldr_r1
= 0xe59f1008; /* ldr r1, [pc, #8] ($name) */
304 stub
->mov_r2_lr
= 0xe1a0200e; /* mov r2, lr */
305 stub
->ldr_pc_pc
= 0xe59ff004; /* ldr pc, [pc, #4] */
308 stub
->entry
= stub_entry_point
;
309 #elif defined(__aarch64__)
310 stub
->ldr_x0
= 0x580000a0; /* ldr x0, #20 ($dll) */
311 stub
->ldr_x1
= 0x580000c1; /* ldr x1, #24 ($name) */
312 stub
->mov_x2_lr
= 0xaa1e03e2; /* mov x2, lr */
313 stub
->ldr_x16
= 0x580000d0; /* ldr x16, #24 ($entry) */
314 stub
->br_x16
= 0xd61f0200; /* br x16 */
317 stub
->entry
= stub_entry_point
;
319 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
320 stub
->movq_rdi
[1] = 0xbf;
322 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
323 stub
->movq_rsi
[1] = 0xbe;
325 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
326 stub
->movq_rsp_rdx
[1] = 0x8b;
327 stub
->movq_rsp_rdx
[2] = 0x14;
328 stub
->movq_rsp_rdx
[3] = 0x24;
329 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
330 stub
->movq_rax
[1] = 0xb8;
331 stub
->entry
= stub_entry_point
;
332 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
333 stub
->jmpq_rax
[1] = 0xe0;
335 return (ULONG_PTR
)stub
;
339 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
340 #endif /* __i386__ */
343 /*************************************************************************
346 * Looks for the referenced HMODULE in the current process
347 * The loader_section must be locked while calling this function.
349 static WINE_MODREF
*get_modref( HMODULE hmod
)
351 PLIST_ENTRY mark
, entry
;
354 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
356 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
357 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
359 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
360 if (mod
->BaseAddress
== hmod
)
361 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
367 /**********************************************************************
368 * find_basename_module
370 * Find a module from its base name.
371 * The loader_section must be locked while calling this function
373 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
375 PLIST_ENTRY mark
, entry
;
377 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
378 return cached_modref
;
380 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
381 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
383 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
384 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
386 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
387 return cached_modref
;
394 /**********************************************************************
395 * find_fullname_module
397 * Find a module from its full path name.
398 * The loader_section must be locked while calling this function
400 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
402 PLIST_ENTRY mark
, entry
;
404 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
405 return cached_modref
;
407 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
408 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
410 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
411 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
413 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
414 return cached_modref
;
421 /*************************************************************************
422 * find_forwarded_export
424 * Find the final function pointer for a forwarded function.
425 * The loader_section must be locked while calling this function.
427 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
429 const IMAGE_EXPORT_DIRECTORY
*exports
;
433 const char *end
= strrchr(forward
, '.');
436 if (!end
) return NULL
;
437 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
438 ascii_to_unicode( mod_name
, forward
, end
- forward
);
439 mod_name
[end
- forward
] = 0;
440 if (!strchrW( mod_name
, '.' ))
442 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
443 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
446 if (!(wm
= find_basename_module( mod_name
)))
448 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
449 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
450 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
452 if (!imports_fixup_done
&& current_modref
)
455 if (current_modref
->nDeps
)
456 deps
= RtlReAllocateHeap( GetProcessHeap(), 0, current_modref
->deps
,
457 (current_modref
->nDeps
+ 1) * sizeof(*deps
) );
459 deps
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*deps
) );
462 deps
[current_modref
->nDeps
++] = wm
;
463 current_modref
->deps
= deps
;
466 else if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
468 LdrUnloadDll( wm
->ldr
.BaseAddress
);
475 ERR( "module not found for forward '%s' used by %s\n",
476 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
480 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
481 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
483 const char *name
= end
+ 1;
484 if (*name
== '#') /* ordinal */
485 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
487 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
492 ERR("function not found for forward '%s' used by %s."
493 " If you are using builtin %s, try using the native one instead.\n",
494 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
495 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
501 /*************************************************************************
502 * find_ordinal_export
504 * Find an exported function by ordinal.
505 * The exports base must have been subtracted from the ordinal already.
506 * The loader_section must be locked while calling this function.
508 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
509 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
512 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
514 if (ordinal
>= exports
->NumberOfFunctions
)
516 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
519 if (!functions
[ordinal
]) return NULL
;
521 proc
= get_rva( module
, functions
[ordinal
] );
523 /* if the address falls into the export dir, it's a forward */
524 if (((const char *)proc
>= (const char *)exports
) &&
525 ((const char *)proc
< (const char *)exports
+ exp_size
))
526 return find_forwarded_export( module
, (const char *)proc
, load_path
);
530 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
531 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
535 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
536 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
542 /*************************************************************************
545 * Find an exported function by name.
546 * The loader_section must be locked while calling this function.
548 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
549 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
551 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
552 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
553 int min
= 0, max
= exports
->NumberOfNames
- 1;
555 /* first check the hint */
556 if (hint
>= 0 && hint
<= max
)
558 char *ename
= get_rva( module
, names
[hint
] );
559 if (!strcmp( ename
, name
))
560 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
563 /* then do a binary search */
566 int res
, pos
= (min
+ max
) / 2;
567 char *ename
= get_rva( module
, names
[pos
] );
568 if (!(res
= strcmp( ename
, name
)))
569 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
570 if (res
> 0) max
= pos
- 1;
578 /*************************************************************************
581 * Import the dll specified by the given import descriptor.
582 * The loader_section must be locked while calling this function.
584 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
589 const IMAGE_EXPORT_DIRECTORY
*exports
;
591 const IMAGE_THUNK_DATA
*import_list
;
592 IMAGE_THUNK_DATA
*thunk_list
;
594 const char *name
= get_rva( module
, descr
->Name
);
595 DWORD len
= strlen(name
);
597 SIZE_T protect_size
= 0;
600 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
601 if (descr
->u
.OriginalFirstThunk
)
602 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
604 import_list
= thunk_list
;
606 if (!import_list
->u1
.Ordinal
)
608 WARN( "Skipping unused import %s\n", name
);
613 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
615 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
617 ascii_to_unicode( buffer
, name
, len
);
619 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
621 else /* need to allocate a larger buffer */
623 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
624 if (!ptr
) return FALSE
;
625 ascii_to_unicode( ptr
, name
, len
);
627 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
628 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
633 if (status
== STATUS_DLL_NOT_FOUND
)
634 ERR("Library %s (which is needed by %s) not found\n",
635 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
637 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
638 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
642 /* unprotect the import address table since it can be located in
643 * readonly section */
644 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
645 protect_base
= thunk_list
;
646 protect_size
*= sizeof(*thunk_list
);
647 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
648 &protect_size
, PAGE_READWRITE
, &protect_old
);
650 imp_mod
= wmImp
->ldr
.BaseAddress
;
651 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
655 /* set all imported function to deadbeef */
656 while (import_list
->u1
.Ordinal
)
658 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
660 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
661 WARN("No implementation for %s.%d", name
, ordinal
);
662 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
666 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
667 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
668 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
670 WARN(" imported from %s, allocating stub %p\n",
671 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
672 (void *)thunk_list
->u1
.Function
);
679 while (import_list
->u1
.Ordinal
)
681 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
683 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
685 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
686 ordinal
- exports
->Base
, load_path
);
687 if (!thunk_list
->u1
.Function
)
689 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
690 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
691 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
692 (void *)thunk_list
->u1
.Function
);
694 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
696 else /* import by name */
698 IMAGE_IMPORT_BY_NAME
*pe_name
;
699 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
700 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
701 (const char*)pe_name
->Name
,
702 pe_name
->Hint
, load_path
);
703 if (!thunk_list
->u1
.Function
)
705 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
706 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
707 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
708 (void *)thunk_list
->u1
.Function
);
710 TRACE_(imports
)("--- %s %s.%d = %p\n",
711 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
718 /* restore old protection of the import address table */
719 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
725 /***********************************************************************
726 * create_module_activation_context
728 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
731 LDR_RESOURCE_INFO info
;
732 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
734 info
.Type
= RT_MANIFEST
;
735 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
737 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
740 ctx
.cbSize
= sizeof(ctx
);
742 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
743 ctx
.hModule
= module
->BaseAddress
;
744 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
745 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
751 /*************************************************************************
752 * is_dll_native_subsystem
754 * Check if dll is a proper native driver.
755 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
756 * while being perfectly normal DLLs. This heuristic should catch such breakages.
758 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
760 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
761 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
762 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
766 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
767 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
769 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
770 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
772 for (i
= 0; imports
[i
].Name
; i
++)
774 const char *name
= get_rva( module
, imports
[i
].Name
);
775 DWORD len
= strlen(name
);
776 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
777 ascii_to_unicode( buffer
, name
, len
+ 1 );
778 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
780 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
788 /*************************************************************************
791 * Allocate a TLS slot for a newly-loaded module.
792 * The loader_section must be locked while calling this function.
794 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
796 const IMAGE_TLS_DIRECTORY
*dir
;
801 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
804 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
805 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
807 for (i
= 0; i
< tls_module_count
; i
++)
809 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
810 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
814 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
815 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
816 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
818 if (i
== tls_module_count
)
820 UINT new_count
= max( 32, tls_module_count
* 2 );
823 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
825 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
826 new_count
* sizeof(*tls_dirs
) );
827 if (!new_ptr
) return -1;
829 /* resize the pointer block in all running threads */
830 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
832 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
833 void **old
= teb
->ThreadLocalStoragePointer
;
834 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
837 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
838 teb
->ThreadLocalStoragePointer
= new;
839 #if defined(__APPLE__) && defined(__x86_64__)
840 if (teb
->Reserved5
[0])
841 ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
843 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
844 /* FIXME: can't free old block here, should be freed at thread exit */
848 tls_module_count
= new_count
;
851 /* allocate the data block in all running threads */
852 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
854 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
856 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
857 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
858 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
860 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
861 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
863 RtlFreeHeap( GetProcessHeap(), 0,
864 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
867 *(DWORD
*)dir
->AddressOfIndex
= i
;
873 /*************************************************************************
876 * Free the module TLS slot on unload.
877 * The loader_section must be locked while calling this function.
879 static void free_tls_slot( LDR_MODULE
*mod
)
881 ULONG i
= (USHORT
)mod
->TlsIndex
;
883 if (mod
->TlsIndex
== -1) return;
884 assert( i
< tls_module_count
);
885 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
889 /****************************************************************
892 * Fixup all imports of a given module.
893 * The loader_section must be locked while calling this function.
895 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
898 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
899 WINE_MODREF
*prev
, *imp
;
904 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
905 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
907 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
909 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
910 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
911 return STATUS_SUCCESS
;
914 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
916 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
918 if (!create_module_activation_context( &wm
->ldr
))
919 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
921 /* Allocate module dependency list */
922 wm
->nDeps
= nb_imports
;
923 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
925 /* load the imported modules. They are automatically
926 * added to the modref list of the process.
928 prev
= current_modref
;
930 status
= STATUS_SUCCESS
;
931 for (i
= 0; i
< nb_imports
; i
++)
933 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &imp
))
936 status
= STATUS_DLL_NOT_FOUND
;
940 current_modref
= prev
;
941 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
946 /*************************************************************************
949 * Allocate a WINE_MODREF structure and add it to the process list
950 * The loader_section must be locked while calling this function.
952 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
956 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
958 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
963 wm
->ldr
.BaseAddress
= hModule
;
964 wm
->ldr
.EntryPoint
= NULL
;
965 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
966 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
967 wm
->ldr
.TlsIndex
= -1;
968 wm
->ldr
.LoadCount
= 1;
969 wm
->ldr
.SectionHandle
= NULL
;
970 wm
->ldr
.CheckSum
= 0;
971 wm
->ldr
.TimeDateStamp
= 0;
972 wm
->ldr
.ActivationContext
= 0;
974 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
975 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
976 else p
= wm
->ldr
.FullDllName
.Buffer
;
977 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
979 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
981 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
982 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
983 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
984 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
987 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
988 &wm
->ldr
.InLoadOrderModuleList
);
989 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
990 &wm
->ldr
.InMemoryOrderModuleList
);
992 /* wait until init is called for inserting into this list */
993 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
994 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
996 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
998 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
999 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
1000 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
1006 /*************************************************************************
1009 * Allocate the per-thread structure for module TLS storage.
1011 static NTSTATUS
alloc_thread_tls(void)
1016 if (!tls_module_count
) return STATUS_SUCCESS
;
1018 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1019 tls_module_count
* sizeof(*pointers
) )))
1020 return STATUS_NO_MEMORY
;
1022 for (i
= 0; i
< tls_module_count
; i
++)
1024 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1027 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1028 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1030 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1032 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1033 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1034 return STATUS_NO_MEMORY
;
1036 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1037 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1039 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1040 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1042 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1043 #if defined(__APPLE__) && defined(__x86_64__)
1044 __asm__
volatile (".byte 0x65\n\tmovq %0,%c1"
1046 : "r" (pointers
), "n" (FIELD_OFFSET(TEB
, ThreadLocalStoragePointer
)));
1048 return STATUS_SUCCESS
;
1052 /*************************************************************************
1053 * call_tls_callbacks
1055 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1057 const IMAGE_TLS_DIRECTORY
*dir
;
1058 const PIMAGE_TLS_CALLBACK
*callback
;
1061 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1062 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1064 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1066 TRACE_(relay
)("\1Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1067 *callback
, module
, reason_names
[reason
] );
1070 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1074 TRACE_(relay
)("\1exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1075 callback
, module
, reason_names
[reason
] );
1079 TRACE_(relay
)("\1Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1080 *callback
, module
, reason_names
[reason
] );
1085 /*************************************************************************
1088 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1091 NTSTATUS status
= STATUS_SUCCESS
;
1092 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1093 void *module
= wm
->ldr
.BaseAddress
;
1096 /* Skip calls for modules loaded with special load flags */
1098 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1099 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1100 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1102 if (TRACE_ON(relay
))
1104 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1105 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1106 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1107 TRACE_(relay
)("\1Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1108 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
);
1110 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1111 reason_names
[reason
], lpReserved
);
1115 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1117 status
= STATUS_DLL_INIT_FAILED
;
1121 TRACE_(relay
)("\1exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1122 entry
, module
, reason_names
[reason
], lpReserved
);
1123 status
= GetExceptionCode();
1127 /* The state of the module list may have changed due to the call
1128 to the dll. We cannot assume that this module has not been
1130 if (TRACE_ON(relay
))
1131 TRACE_(relay
)("\1Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1132 entry
, module
, debugstr_w(mod_name
), reason_names
[reason
], lpReserved
, retv
);
1134 TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1140 /*************************************************************************
1143 * Send the process attach notification to all DLLs the given module
1144 * depends on (recursively). This is somewhat complicated due to the fact that
1146 * - we have to respect the module dependencies, i.e. modules implicitly
1147 * referenced by another module have to be initialized before the module
1148 * itself can be initialized
1150 * - the initialization routine of a DLL can itself call LoadLibrary,
1151 * thereby introducing a whole new set of dependencies (even involving
1152 * the 'old' modules) at any time during the whole process
1154 * (Note that this routine can be recursively entered not only directly
1155 * from itself, but also via LoadLibrary from one of the called initialization
1158 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1159 * the process *detach* notifications to be sent in the correct order.
1160 * This must not only take into account module dependencies, but also
1161 * 'hidden' dependencies created by modules calling LoadLibrary in their
1162 * attach notification routine.
1164 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1165 * list after the attach notification has returned. This implies that the
1166 * detach notifications are called in the reverse of the sequence the attach
1167 * notifications *returned*.
1169 * The loader_section must be locked while calling this function.
1171 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1173 NTSTATUS status
= STATUS_SUCCESS
;
1177 if (process_detaching
) return status
;
1179 /* prevent infinite recursion in case of cyclical dependencies */
1180 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1181 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1184 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1186 /* Tag current MODREF to prevent recursive loop */
1187 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1188 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1189 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1191 /* Recursively attach all DLLs this one depends on */
1192 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1194 if (!wm
->deps
[i
]) continue;
1195 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1198 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1199 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1200 &wm
->ldr
.InInitializationOrderModuleList
);
1202 /* Call DLL entry point */
1203 if (status
== STATUS_SUCCESS
)
1205 WINE_MODREF
*prev
= current_modref
;
1206 current_modref
= wm
;
1207 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1208 if (status
== STATUS_SUCCESS
)
1209 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1212 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1213 /* point to the name so LdrInitializeThunk can print it */
1214 last_failed_modref
= wm
;
1215 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1217 current_modref
= prev
;
1220 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1221 /* Remove recursion flag */
1222 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1224 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1229 /**********************************************************************
1230 * attach_implicitly_loaded_dlls
1232 * Attach to the (builtin) dlls that have been implicitly loaded because
1233 * of a dependency at the Unix level, but not imported at the Win32 level.
1235 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1239 PLIST_ENTRY mark
, entry
;
1241 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1242 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1244 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1246 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1247 TRACE( "found implicitly loaded %s, attaching to it\n",
1248 debugstr_w(mod
->BaseDllName
.Buffer
));
1249 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1250 break; /* restart the search from the start */
1252 if (entry
== mark
) break; /* nothing found */
1257 /*************************************************************************
1260 * Send DLL process detach notifications. See the comment about calling
1261 * sequence at process_attach.
1263 static void process_detach(void)
1265 PLIST_ENTRY mark
, entry
;
1268 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1271 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1273 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1274 InInitializationOrderModuleList
);
1275 /* Check whether to detach this DLL */
1276 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1278 if ( mod
->LoadCount
&& !process_detaching
)
1281 /* Call detach notification */
1282 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1283 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1284 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1286 /* Restart at head of WINE_MODREF list, as entries might have
1287 been added and/or removed while performing the call ... */
1290 } while (entry
!= mark
);
1293 /*************************************************************************
1296 * Send DLL thread attach notifications. These are sent in the
1297 * reverse sequence of process detach notification.
1298 * The loader_section must be locked while calling this function.
1300 static void thread_attach(void)
1302 PLIST_ENTRY mark
, entry
;
1305 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1306 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1308 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1309 InInitializationOrderModuleList
);
1310 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1312 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1315 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), DLL_THREAD_ATTACH
, NULL
);
1319 /******************************************************************
1320 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1323 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1326 NTSTATUS ret
= STATUS_SUCCESS
;
1328 RtlEnterCriticalSection( &loader_section
);
1330 wm
= get_modref( hModule
);
1331 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1332 ret
= STATUS_DLL_NOT_FOUND
;
1334 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1336 RtlLeaveCriticalSection( &loader_section
);
1341 /******************************************************************
1342 * LdrFindEntryForAddress (NTDLL.@)
1344 * The loader_section must be locked while calling this function
1346 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1348 PLIST_ENTRY mark
, entry
;
1351 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1352 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1354 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1355 if (mod
->BaseAddress
<= addr
&&
1356 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1359 return STATUS_SUCCESS
;
1362 return STATUS_NO_MORE_ENTRIES
;
1365 /******************************************************************
1366 * LdrEnumerateLoadedModules (NTDLL.@)
1368 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1370 LIST_ENTRY
*mark
, *entry
;
1372 BOOLEAN stop
= FALSE
;
1374 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1376 if (unknown
|| !callback
)
1377 return STATUS_INVALID_PARAMETER
;
1379 RtlEnterCriticalSection( &loader_section
);
1381 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1382 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1384 mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1385 callback( mod
, context
, &stop
);
1389 RtlLeaveCriticalSection( &loader_section
);
1390 return STATUS_SUCCESS
;
1393 /******************************************************************
1394 * LdrLockLoaderLock (NTDLL.@)
1396 * Note: some flags are not implemented.
1397 * Flag 0x01 is used to raise exceptions on errors.
1399 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1401 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1403 if (result
) *result
= 0;
1404 if (magic
) *magic
= 0;
1405 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1406 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1407 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1411 if (!RtlTryEnterCriticalSection( &loader_section
))
1414 return STATUS_SUCCESS
;
1420 RtlEnterCriticalSection( &loader_section
);
1421 if (result
) *result
= 1;
1423 *magic
= GetCurrentThreadId();
1424 return STATUS_SUCCESS
;
1428 /******************************************************************
1429 * LdrUnlockLoaderUnlock (NTDLL.@)
1431 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1435 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1436 RtlLeaveCriticalSection( &loader_section
);
1438 return STATUS_SUCCESS
;
1442 /******************************************************************
1443 * LdrGetProcedureAddress (NTDLL.@)
1445 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1446 ULONG ord
, PVOID
*address
)
1448 IMAGE_EXPORT_DIRECTORY
*exports
;
1450 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1452 RtlEnterCriticalSection( &loader_section
);
1454 /* check if the module itself is invalid to return the proper error */
1455 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1456 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1457 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1459 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1460 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1461 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1465 ret
= STATUS_SUCCESS
;
1469 RtlLeaveCriticalSection( &loader_section
);
1474 /***********************************************************************
1477 * Check if a loaded native dll is a Wine fake dll.
1479 static BOOL
is_fake_dll( HANDLE handle
)
1481 static const char fakedll_signature
[] = "Wine placeholder DLL";
1482 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1483 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1485 LARGE_INTEGER offset
;
1487 offset
.QuadPart
= 0;
1488 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1489 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1490 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1491 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1492 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1497 /***********************************************************************
1498 * get_builtin_fullname
1500 * Build the full pathname for a builtin dll.
1502 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1504 static const WCHAR soW
[] = {'.','s','o',0};
1505 WCHAR
*p
, *fullname
;
1506 size_t i
, len
= strlen(filename
);
1508 /* check if path can correspond to the dll we have */
1509 if (path
&& (p
= strrchrW( path
, '\\' )))
1512 for (i
= 0; i
< len
; i
++)
1513 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1514 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1516 /* the filename matches, use path as the full path */
1518 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1520 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1527 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1528 (strlenW(system_dir
) + len
+ 1) * sizeof(WCHAR
) )))
1530 strcpyW( fullname
, system_dir
);
1531 ascii_to_unicode( fullname
+ strlenW(fullname
), filename
, len
+ 1 );
1537 /*************************************************************************
1540 static BOOL
is_16bit_builtin( HMODULE module
)
1542 const IMAGE_EXPORT_DIRECTORY
*exports
;
1545 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1546 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1549 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1553 /***********************************************************************
1554 * load_builtin_callback
1556 * Load a library in memory; callback function for wine_dll_register
1558 static void load_builtin_callback( void *module
, const char *filename
)
1560 static const WCHAR emptyW
[1];
1561 IMAGE_NT_HEADERS
*nt
;
1564 const WCHAR
*load_path
;
1568 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1571 if (!(nt
= RtlImageNtHeader( module
)))
1573 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1574 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1578 virtual_create_builtin_view( module
);
1580 /* create the MODREF */
1582 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1584 ERR( "can't load %s\n", filename
);
1585 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1589 wm
= alloc_module( module
, fullname
);
1590 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1593 ERR( "can't load %s\n", filename
);
1594 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1597 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1599 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1600 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1601 is_16bit_builtin( module
))
1605 load_path
= builtin_load_info
->load_path
;
1606 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1607 if (!load_path
) load_path
= emptyW
;
1608 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1610 /* the module has only be inserted in the load & memory order lists */
1611 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1612 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1613 /* FIXME: free the modref */
1614 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1619 builtin_load_info
->wm
= wm
;
1620 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1622 /* send the DLL load event */
1624 SERVER_START_REQ( load_dll
)
1626 req
->base
= wine_server_client_ptr( module
);
1627 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1628 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1629 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1630 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1631 wine_server_call( req
);
1635 /* setup relay debugging entry points */
1636 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1640 /***********************************************************************
1641 * set_security_cookie
1643 * Create a random security cookie for buffer overflow protection. Make
1644 * sure it does not accidentally match the default cookie value.
1646 static void set_security_cookie( void *module
, SIZE_T len
)
1649 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1653 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1654 if (!loadcfg
) return;
1655 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1656 if (!loadcfg
->SecurityCookie
) return;
1657 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1658 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1660 WARN( "security cookie %p outside of image %p-%p\n",
1661 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1665 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1666 TRACE( "initializing security cookie %p\n", cookie
);
1668 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1671 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1672 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1673 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1674 *cookie
= RtlRandom( &seed
);
1675 #ifdef DEFAULT_SECURITY_COOKIE_64
1676 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1678 *cookie
= RtlRandom( &seed
);
1679 /* fill up, but keep the highest word clear */
1680 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1688 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1690 IMAGE_NT_HEADERS
*nt
;
1692 IMAGE_BASE_RELOCATION
*rel
, *end
;
1693 const IMAGE_DATA_DIRECTORY
*relocs
;
1694 const IMAGE_SECTION_HEADER
*sec
;
1696 ULONG protect_old
[96], i
;
1698 nt
= RtlImageNtHeader( module
);
1699 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1701 assert( module
!= base
);
1703 /* no relocations are performed on non page-aligned binaries */
1704 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1705 return STATUS_SUCCESS
;
1707 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1708 return STATUS_SUCCESS
;
1710 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1712 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1714 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1716 return STATUS_CONFLICTING_ADDRESSES
;
1719 if (!relocs
->Size
) return STATUS_SUCCESS
;
1720 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1722 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1723 return STATUS_INVALID_IMAGE_FORMAT
;
1725 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1726 nt
->FileHeader
.SizeOfOptionalHeader
);
1727 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1729 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1730 SIZE_T size
= sec
[i
].SizeOfRawData
;
1731 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1732 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1735 TRACE( "relocating from %p-%p to %p-%p\n",
1736 base
, base
+ len
, module
, (char *)module
+ len
);
1738 rel
= get_rva( module
, relocs
->VirtualAddress
);
1739 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1740 delta
= (char *)module
- base
;
1742 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1744 if (rel
->VirtualAddress
>= len
)
1746 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1747 return STATUS_ACCESS_VIOLATION
;
1749 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1750 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1751 (USHORT
*)(rel
+ 1), delta
);
1752 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1755 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1757 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1758 SIZE_T size
= sec
[i
].SizeOfRawData
;
1759 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1760 &size
, protect_old
[i
], &protect_old
[i
] );
1763 return STATUS_SUCCESS
;
1767 /* On WoW64 setups, an image mapping can also be created for the other 32/64 CPU */
1768 /* but it cannot necessarily be loaded as a dll, so we need some additional checks */
1769 static BOOL
is_valid_binary( const pe_image_info_t
*info
)
1772 return info
->machine
== IMAGE_FILE_MACHINE_I386
;
1773 #elif defined(__x86_64__)
1774 return info
->machine
== IMAGE_FILE_MACHINE_AMD64
|| !info
->contains_code
;
1775 #elif defined(__arm__)
1776 return info
->machine
== IMAGE_FILE_MACHINE_ARM
||
1777 info
->machine
== IMAGE_FILE_MACHINE_THUMB
||
1778 info
->machine
== IMAGE_FILE_MACHINE_ARMNT
;
1779 #elif defined(__aarch64__)
1780 return info
->machine
== IMAGE_FILE_MACHINE_ARM64
|| !info
->contains_code
;
1782 return FALSE
; /* no wow64 support on other platforms */
1787 /******************************************************************************
1788 * load_native_dll (internal)
1790 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1791 DWORD flags
, WINE_MODREF
** pwm
)
1796 IMAGE_NT_HEADERS
*nt
;
1800 pe_image_info_t image_info
;
1802 TRACE("Trying native dll %s\n", debugstr_w(name
));
1805 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
|
1806 SECTION_MAP_READ
| SECTION_MAP_EXECUTE
,
1807 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1808 if (status
!= STATUS_SUCCESS
) return status
;
1811 status
= virtual_map_section( mapping
, &module
, 0, 0, NULL
, &len
, PAGE_EXECUTE_READ
, &image_info
);
1814 if ((status
== STATUS_SUCCESS
|| status
== STATUS_IMAGE_NOT_AT_BASE
) &&
1815 !is_valid_binary( &image_info
))
1817 NtUnmapViewOfSection( NtCurrentProcess(), module
);
1818 return STATUS_INVALID_IMAGE_FORMAT
;
1821 /* perform base relocation, if necessary */
1823 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1824 status
= perform_relocations( module
, len
);
1826 if (status
!= STATUS_SUCCESS
)
1828 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1832 /* create the MODREF */
1834 if (!(wm
= alloc_module( module
, name
)))
1836 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1837 return STATUS_NO_MEMORY
;
1840 set_security_cookie( module
, len
);
1844 nt
= RtlImageNtHeader( module
);
1846 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1847 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1848 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1850 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1852 /* the module has only be inserted in the load & memory order lists */
1853 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1854 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1856 /* FIXME: there are several more dangling references
1857 * left. Including dlls loaded by this dll before the
1858 * failed one. Unrolling is rather difficult with the
1859 * current structure and we can leave them lying
1860 * around with no problems, so we don't care.
1861 * As these might reference our wm, we don't free it.
1867 /* send DLL load event */
1869 SERVER_START_REQ( load_dll
)
1871 req
->base
= wine_server_client_ptr( module
);
1872 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1873 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1874 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1875 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1876 wine_server_call( req
);
1880 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1882 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1884 wm
->ldr
.LoadCount
= 1;
1886 return STATUS_SUCCESS
;
1890 /***********************************************************************
1893 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1894 DWORD flags
, WINE_MODREF
** pwm
)
1896 char error
[256], dllname
[MAX_PATH
];
1897 const WCHAR
*name
, *p
;
1900 struct builtin_load_info info
, *prev_info
;
1902 /* Fix the name in case we have a full path and extension */
1904 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1905 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1907 /* load_library will modify info.status. Note also that load_library can be
1908 * called several times, if the .so file we're loading has dependencies.
1909 * info.status will gather all the errors we may get while loading all these
1912 info
.load_path
= load_path
;
1913 info
.filename
= NULL
;
1914 info
.status
= STATUS_SUCCESS
;
1917 if (file
) /* we have a real file, try to load it */
1919 UNICODE_STRING nt_name
;
1920 ANSI_STRING unix_name
;
1922 TRACE("Trying built-in %s\n", debugstr_w(path
));
1924 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1925 return STATUS_DLL_NOT_FOUND
;
1927 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1929 RtlFreeUnicodeString( &nt_name
);
1930 return STATUS_DLL_NOT_FOUND
;
1932 prev_info
= builtin_load_info
;
1933 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1934 builtin_load_info
= &info
;
1935 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1936 builtin_load_info
= prev_info
;
1937 RtlFreeUnicodeString( &nt_name
);
1938 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1941 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1942 return STATUS_INVALID_IMAGE_FORMAT
;
1949 TRACE("Trying built-in %s\n", debugstr_w(name
));
1951 /* we don't want to depend on the current codepage here */
1952 len
= strlenW( name
) + 1;
1953 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1954 for (i
= 0; i
< len
; i
++)
1956 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1957 dllname
[i
] = (char)name
[i
];
1958 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1961 prev_info
= builtin_load_info
;
1962 builtin_load_info
= &info
;
1963 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1964 builtin_load_info
= prev_info
;
1969 /* The file does not exist -> WARN() */
1970 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1971 return STATUS_DLL_NOT_FOUND
;
1973 /* ERR() for all other errors (missing functions, ...) */
1974 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1975 return STATUS_PROCEDURE_NOT_FOUND
;
1979 if (info
.status
!= STATUS_SUCCESS
)
1981 wine_dll_unload( handle
);
1987 PLIST_ENTRY mark
, entry
;
1989 /* The constructor wasn't called, this means the .so is already
1990 * loaded under a different name. Try to find the wm for it. */
1992 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1993 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1995 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1996 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1998 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1999 TRACE( "Found %s at %p for builtin %s\n",
2000 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
2004 wine_dll_unload( handle
); /* release the libdl refcount */
2005 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
2006 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
2010 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
2011 info
.wm
->ldr
.LoadCount
= 1;
2012 info
.wm
->ldr
.SectionHandle
= handle
;
2016 return STATUS_SUCCESS
;
2020 /***********************************************************************
2023 * Find the full path (if any) of the dll from the activation context.
2025 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2027 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2028 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2030 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2031 ACTCTX_SECTION_KEYED_DATA data
;
2032 UNICODE_STRING nameW
;
2034 SIZE_T needed
, size
= 1024;
2037 RtlInitUnicodeString( &nameW
, libname
);
2038 data
.cbSize
= sizeof(data
);
2039 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2040 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2042 if (status
!= STATUS_SUCCESS
) return status
;
2046 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2048 status
= STATUS_NO_MEMORY
;
2051 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2052 AssemblyDetailedInformationInActivationContext
,
2053 info
, size
, &needed
);
2054 if (status
== STATUS_SUCCESS
) break;
2055 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2056 RtlFreeHeap( GetProcessHeap(), 0, info
);
2058 /* restart with larger buffer */
2061 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2063 status
= STATUS_SXS_KEY_NOT_FOUND
;
2067 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2069 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2072 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2074 /* manifest name does not match directory name, so it's not a global
2075 * windows/winsxs manifest; use the manifest directory name instead */
2076 dirlen
= p
- info
->lpAssemblyManifestPath
;
2077 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2078 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2080 status
= STATUS_NO_MEMORY
;
2083 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2085 strcpyW( p
, libname
);
2090 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2091 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2093 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2095 status
= STATUS_NO_MEMORY
;
2098 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2100 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2101 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2102 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2103 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2105 strcpyW( p
, libname
);
2107 RtlFreeHeap( GetProcessHeap(), 0, info
);
2108 RtlReleaseActivationContext( data
.hActCtx
);
2113 /***********************************************************************
2116 * Find the file (or already loaded module) for a given dll name.
2118 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2119 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
2121 OBJECT_ATTRIBUTES attr
;
2123 UNICODE_STRING nt_name
;
2124 WCHAR
*file_part
, *ext
, *dllname
;
2127 /* first append .dll if needed */
2130 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2132 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2133 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2134 return STATUS_NO_MEMORY
;
2135 strcpyW( dllname
, libname
);
2136 strcatW( dllname
, dllW
);
2140 nt_name
.Buffer
= NULL
;
2142 if (!contains_path( libname
))
2145 WCHAR
*fullname
= NULL
;
2147 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2149 status
= find_actctx_dll( libname
, &fullname
);
2150 if (status
== STATUS_SUCCESS
)
2152 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2153 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2154 libname
= dllname
= fullname
;
2156 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2158 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2163 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2165 /* we need to search for it */
2166 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2169 if (len
>= *size
) goto overflow
;
2170 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
2172 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2174 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2175 return STATUS_NO_MEMORY
;
2177 attr
.Length
= sizeof(attr
);
2178 attr
.RootDirectory
= 0;
2179 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2180 attr
.ObjectName
= &nt_name
;
2181 attr
.SecurityDescriptor
= NULL
;
2182 attr
.SecurityQualityOfService
= NULL
;
2183 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2189 if (!contains_path( libname
))
2191 /* if libname doesn't contain a path at all, we simply return the name as is,
2192 * to be loaded as builtin */
2193 len
= strlenW(libname
) * sizeof(WCHAR
);
2194 if (len
>= *size
) goto overflow
;
2195 strcpyW( filename
, libname
);
2200 /* absolute path name, or relative path name but not found above */
2202 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2204 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2205 return STATUS_NO_MEMORY
;
2207 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2208 if (len
>= *size
) goto overflow
;
2209 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2210 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
2212 attr
.Length
= sizeof(attr
);
2213 attr
.RootDirectory
= 0;
2214 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2215 attr
.ObjectName
= &nt_name
;
2216 attr
.SecurityDescriptor
= NULL
;
2217 attr
.SecurityQualityOfService
= NULL
;
2218 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2221 RtlFreeUnicodeString( &nt_name
);
2222 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2223 return STATUS_SUCCESS
;
2226 RtlFreeUnicodeString( &nt_name
);
2227 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2228 *size
= len
+ sizeof(WCHAR
);
2229 return STATUS_BUFFER_TOO_SMALL
;
2233 /***********************************************************************
2234 * load_dll (internal)
2236 * Load a PE style module according to the load order.
2237 * The loader_section must be locked while calling this function.
2239 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2241 enum loadorder loadorder
;
2245 WINE_MODREF
*main_exe
;
2249 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2253 size
= sizeof(buffer
);
2256 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2257 if (nts
== STATUS_SUCCESS
) break;
2258 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2259 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2260 /* grow the buffer and retry */
2261 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2264 if (*pwm
) /* found already loaded module */
2266 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2268 TRACE("Found %s for %s at %p, count=%d\n",
2269 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2270 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2271 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2272 return STATUS_SUCCESS
;
2275 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2276 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2278 if (handle
&& is_fake_dll( handle
))
2280 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2288 nts
= STATUS_NO_MEMORY
;
2291 nts
= STATUS_DLL_NOT_FOUND
;
2294 case LO_NATIVE_BUILTIN
:
2295 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2298 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2299 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2300 /* not in PE format, maybe it's a builtin */
2301 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2303 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2304 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2307 case LO_BUILTIN_NATIVE
:
2308 case LO_DEFAULT
: /* default is builtin,native */
2309 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2310 if (!handle
) break; /* nothing else we can try */
2311 /* file is not a builtin library, try without using the specified file */
2312 if (nts
!= STATUS_SUCCESS
)
2313 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2314 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2315 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2317 /* stub-only dll, try native */
2318 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2319 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2320 nts
= STATUS_DLL_NOT_FOUND
;
2322 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2323 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2327 if (nts
== STATUS_SUCCESS
)
2329 /* Initialize DLL just loaded */
2330 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2331 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2332 (*pwm
)->ldr
.BaseAddress
);
2333 if (handle
) NtClose( handle
);
2334 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2338 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2339 if (handle
) NtClose( handle
);
2340 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2344 /******************************************************************
2345 * LdrLoadDll (NTDLL.@)
2347 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2348 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2353 RtlEnterCriticalSection( &loader_section
);
2355 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2356 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2358 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2360 nts
= process_attach( wm
, NULL
);
2361 if (nts
!= STATUS_SUCCESS
)
2363 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2367 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2369 RtlLeaveCriticalSection( &loader_section
);
2374 /******************************************************************
2375 * LdrGetDllHandle (NTDLL.@)
2377 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2385 RtlEnterCriticalSection( &loader_section
);
2387 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2390 size
= sizeof(buffer
);
2393 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2394 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2395 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2396 /* grow the buffer and retry */
2397 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2399 status
= STATUS_NO_MEMORY
;
2404 if (status
== STATUS_SUCCESS
)
2406 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2407 else status
= STATUS_DLL_NOT_FOUND
;
2410 RtlLeaveCriticalSection( &loader_section
);
2411 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2416 /******************************************************************
2417 * LdrAddRefDll (NTDLL.@)
2419 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2421 NTSTATUS ret
= STATUS_SUCCESS
;
2424 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2426 RtlEnterCriticalSection( &loader_section
);
2428 if ((wm
= get_modref( module
)))
2430 if (flags
& LDR_ADDREF_DLL_PIN
)
2431 wm
->ldr
.LoadCount
= -1;
2433 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2434 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2436 else ret
= STATUS_INVALID_PARAMETER
;
2438 RtlLeaveCriticalSection( &loader_section
);
2443 /***********************************************************************
2444 * LdrProcessRelocationBlock (NTDLL.@)
2446 * Apply relocations to a given page of a mapped PE image.
2448 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2449 USHORT
*relocs
, INT_PTR delta
)
2453 USHORT offset
= *relocs
& 0xfff;
2454 int type
= *relocs
>> 12;
2457 case IMAGE_REL_BASED_ABSOLUTE
:
2459 case IMAGE_REL_BASED_HIGH
:
2460 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2462 case IMAGE_REL_BASED_LOW
:
2463 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2465 case IMAGE_REL_BASED_HIGHLOW
:
2466 *(int *)((char *)page
+ offset
) += delta
;
2469 case IMAGE_REL_BASED_DIR64
:
2470 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2472 #elif defined(__arm__)
2473 case IMAGE_REL_BASED_THUMB_MOV32
:
2475 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2476 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2477 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2480 if ((inst
& 0x8000fbf0) != 0x0000f240)
2481 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2483 imm16
+= LOWORD(delta
);
2484 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2485 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2486 ((imm16
>> 12) & 0x000f) +
2487 ((imm16
<< 20) & 0x70000000) +
2488 ((imm16
<< 16) & 0xff0000);
2492 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2493 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2494 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2496 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2497 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2501 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2502 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2503 ((imm16
>> 1) & 0x0400) +
2504 ((imm16
>> 12) & 0x000f) +
2505 ((imm16
<< 20) & 0x70000000) +
2506 ((imm16
<< 16) & 0xff0000);
2512 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2517 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2521 /******************************************************************
2522 * LdrQueryProcessModuleInformation
2525 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2526 ULONG buf_size
, ULONG
* req_size
)
2528 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2529 ULONG size
= sizeof(ULONG
);
2530 NTSTATUS nts
= STATUS_SUCCESS
;
2533 PLIST_ENTRY mark
, entry
;
2537 smi
->ModulesCount
= 0;
2539 RtlEnterCriticalSection( &loader_section
);
2540 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2541 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2543 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2544 size
+= sizeof(*sm
);
2545 if (size
<= buf_size
)
2547 sm
->Reserved1
= 0; /* FIXME */
2548 sm
->Reserved2
= 0; /* FIXME */
2549 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2550 sm
->ImageSize
= mod
->SizeOfImage
;
2551 sm
->Flags
= mod
->Flags
;
2553 sm
->Rank
= 0; /* FIXME */
2554 sm
->Unknown
= 0; /* FIXME */
2556 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2557 str
.Buffer
= (char*)sm
->Name
;
2558 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2559 ptr
= strrchr(str
.Buffer
, '\\');
2560 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2562 smi
->ModulesCount
++;
2565 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2567 RtlLeaveCriticalSection( &loader_section
);
2569 if (req_size
) *req_size
= size
;
2575 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2581 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2583 RtlInitUnicodeString( &str
, name
);
2585 size
= sizeof(buffer
) - sizeof(WCHAR
);
2586 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2589 if (info
->Type
!= REG_DWORD
)
2591 buffer
[size
/ sizeof(WCHAR
)] = 0;
2592 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2594 else memcpy( value
, info
->Data
, sizeof(*value
) );
2598 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2599 void *data
, ULONG in_size
, ULONG
*out_size
)
2605 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2606 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2608 RtlInitUnicodeString( &str
, name
);
2610 size
= info_size
+ in_size
;
2611 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2612 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2613 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2614 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2616 if (out_size
) *out_size
= info
->DataLength
;
2617 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2619 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2624 /******************************************************************
2625 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2627 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2628 void *data
, ULONG in_size
, ULONG
*out_size
)
2630 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2631 'S','o','f','t','w','a','r','e','\\',
2632 'M','i','c','r','o','s','o','f','t','\\',
2633 'W','i','n','d','o','w','s',' ','N','T','\\',
2634 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2635 'I','m','a','g','e',' ','F','i','l','e',' ',
2636 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2637 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2638 OBJECT_ATTRIBUTES attr
;
2639 UNICODE_STRING name_str
;
2645 attr
.Length
= sizeof(attr
);
2646 attr
.RootDirectory
= 0;
2647 attr
.ObjectName
= &name_str
;
2648 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2649 attr
.SecurityDescriptor
= NULL
;
2650 attr
.SecurityQualityOfService
= NULL
;
2652 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2653 else p
= key
->Buffer
;
2654 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2655 name_str
.Buffer
= path
;
2656 name_str
.Length
= sizeof(optionsW
) + len
;
2657 name_str
.MaximumLength
= name_str
.Length
;
2658 memcpy( path
, optionsW
, sizeof(optionsW
) );
2659 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2660 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2662 if (type
== REG_DWORD
)
2664 if (out_size
) *out_size
= sizeof(ULONG
);
2665 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2666 else status
= STATUS_BUFFER_OVERFLOW
;
2668 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2675 /******************************************************************
2676 * RtlDllShutdownInProgress (NTDLL.@)
2678 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2680 return process_detaching
;
2683 /****************************************************************************
2684 * LdrResolveDelayLoadedAPI (NTDLL.@)
2686 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2687 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2688 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2690 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2691 DELAYLOAD_INFO delayinfo
;
2699 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2701 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2702 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2703 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2704 name
= get_rva(base
, desc
->DllNameRVA
);
2709 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2711 nts
= STATUS_NO_MEMORY
;
2714 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2715 RtlFreeUnicodeString(&mod
);
2719 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2720 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2723 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2726 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2727 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2731 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2736 delayinfo
.Size
= sizeof(delayinfo
);
2737 delayinfo
.DelayloadDescriptor
= desc
;
2738 delayinfo
.ThunkAddress
= addr
;
2739 delayinfo
.TargetDllName
= name
;
2740 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2741 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2742 delayinfo
.TargetModuleBase
= *phmod
;
2743 delayinfo
.Unused
= NULL
;
2744 delayinfo
.LastError
= nts
;
2745 return dllhook(4, &delayinfo
);
2748 /******************************************************************
2749 * LdrShutdownProcess (NTDLL.@)
2752 void WINAPI
LdrShutdownProcess(void)
2755 process_detaching
= TRUE
;
2760 /******************************************************************
2761 * RtlExitUserProcess (NTDLL.@)
2763 void WINAPI
RtlExitUserProcess( DWORD status
)
2765 RtlEnterCriticalSection( &loader_section
);
2766 RtlAcquirePebLock();
2767 NtTerminateProcess( 0, status
);
2768 LdrShutdownProcess();
2769 NtTerminateProcess( GetCurrentProcess(), status
);
2773 /******************************************************************
2774 * LdrShutdownThread (NTDLL.@)
2777 void WINAPI
LdrShutdownThread(void)
2779 PLIST_ENTRY mark
, entry
;
2786 /* don't do any detach calls if process is exiting */
2787 if (process_detaching
) return;
2789 RtlEnterCriticalSection( &loader_section
);
2791 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2792 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2794 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2795 InInitializationOrderModuleList
);
2796 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2798 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2801 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2802 DLL_THREAD_DETACH
, NULL
);
2805 RtlAcquirePebLock();
2806 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2807 RtlReleasePebLock();
2809 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2811 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2812 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2814 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2815 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2816 RtlLeaveCriticalSection( &loader_section
);
2820 /***********************************************************************
2824 static void free_modref( WINE_MODREF
*wm
)
2826 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2827 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2828 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2829 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2831 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2832 if (!TRACE_ON(module
))
2833 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2834 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2835 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2837 SERVER_START_REQ( unload_dll
)
2839 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2840 wine_server_call( req
);
2844 free_tls_slot( &wm
->ldr
);
2845 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2846 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2847 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2848 if (cached_modref
== wm
) cached_modref
= NULL
;
2849 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2850 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2851 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2854 /***********************************************************************
2855 * MODULE_FlushModrefs
2857 * Remove all unused modrefs and call the internal unloading routines
2858 * for the library type.
2860 * The loader_section must be locked while calling this function.
2862 static void MODULE_FlushModrefs(void)
2864 PLIST_ENTRY mark
, entry
, prev
;
2868 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2869 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2871 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2872 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2873 prev
= entry
->Blink
;
2874 if (!mod
->LoadCount
) free_modref( wm
);
2877 /* check load order list too for modules that haven't been initialized yet */
2878 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2879 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2881 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2882 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2883 prev
= entry
->Blink
;
2884 if (!mod
->LoadCount
) free_modref( wm
);
2888 /***********************************************************************
2889 * MODULE_DecRefCount
2891 * The loader_section must be locked while calling this function.
2893 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2897 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2900 if ( wm
->ldr
.LoadCount
<= 0 )
2903 --wm
->ldr
.LoadCount
;
2904 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2906 if ( wm
->ldr
.LoadCount
== 0 )
2908 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2910 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2912 MODULE_DecRefCount( wm
->deps
[i
] );
2914 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2918 /******************************************************************
2919 * LdrUnloadDll (NTDLL.@)
2923 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2926 NTSTATUS retv
= STATUS_SUCCESS
;
2928 if (process_detaching
) return retv
;
2930 TRACE("(%p)\n", hModule
);
2932 RtlEnterCriticalSection( &loader_section
);
2935 if ((wm
= get_modref( hModule
)) != NULL
)
2937 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2939 /* Recursively decrement reference counts */
2940 MODULE_DecRefCount( wm
);
2942 /* Call process detach notifications */
2943 if ( free_lib_count
<= 1 )
2946 MODULE_FlushModrefs();
2952 retv
= STATUS_DLL_NOT_FOUND
;
2956 RtlLeaveCriticalSection( &loader_section
);
2961 /***********************************************************************
2962 * RtlImageNtHeader (NTDLL.@)
2964 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2966 IMAGE_NT_HEADERS
*ret
;
2970 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2973 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2975 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2976 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2988 /***********************************************************************
2991 * Attach to all the loaded dlls.
2992 * If this is the first time, perform the full process initialization.
2994 NTSTATUS
attach_dlls( CONTEXT
*context
)
2998 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3000 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
3002 if (process_detaching
) return STATUS_SUCCESS
;
3004 RtlEnterCriticalSection( &loader_section
);
3006 wm
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
3009 if (!imports_fixup_done
)
3012 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
3014 ERR( "Importing dlls for %s failed, status %x\n",
3015 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3016 NtTerminateProcess( GetCurrentProcess(), status
);
3018 imports_fixup_done
= TRUE
;
3021 RtlAcquirePebLock();
3022 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
3023 RtlReleasePebLock();
3025 if (!(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
)) /* first time around */
3027 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3029 ERR( "TLS init failed when loading %s, status %x\n",
3030 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3031 NtTerminateProcess( GetCurrentProcess(), status
);
3033 if ((status
= process_attach( wm
, context
)) != STATUS_SUCCESS
)
3035 if (last_failed_modref
)
3036 ERR( "%s failed to initialize, aborting\n",
3037 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3038 ERR( "Initializing dlls for %s failed, status %x\n",
3039 debugstr_w(NtCurrentTeb()->Peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3040 NtTerminateProcess( GetCurrentProcess(), status
);
3042 attach_implicitly_loaded_dlls( context
);
3043 virtual_release_address_space();
3047 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
)
3048 NtTerminateThread( GetCurrentThread(), status
);
3052 RtlLeaveCriticalSection( &loader_section
);
3053 return STATUS_SUCCESS
;
3057 /***********************************************************************
3058 * load_global_options
3060 static void load_global_options(void)
3062 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
3063 'S','y','s','t','e','m','\\',
3064 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3065 'C','o','n','t','r','o','l','\\',
3066 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3067 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3068 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};
3069 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3070 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3071 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};
3072 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};
3074 OBJECT_ATTRIBUTES attr
;
3075 UNICODE_STRING name_str
;
3079 attr
.Length
= sizeof(attr
);
3080 attr
.RootDirectory
= 0;
3081 attr
.ObjectName
= &name_str
;
3082 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3083 attr
.SecurityDescriptor
= NULL
;
3084 attr
.SecurityQualityOfService
= NULL
;
3085 RtlInitUnicodeString( &name_str
, sessionW
);
3087 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3089 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3091 query_dword_option( hkey
, critsectW
, &value
);
3092 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3094 query_dword_option( hkey
, heapresW
, &value
);
3095 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3097 query_dword_option( hkey
, heapcommitW
, &value
);
3098 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3100 query_dword_option( hkey
, decommittotalW
, &value
);
3101 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3103 query_dword_option( hkey
, decommitfreeW
, &value
);
3104 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3110 /******************************************************************
3111 * LdrInitializeThunk (NTDLL.@)
3114 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3115 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3117 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3120 PEB
*peb
= NtCurrentTeb()->Peb
;
3122 kernel32_start_process
= kernel_start
;
3123 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3125 /* allocate the modref for the main exe (if not already done) */
3126 wm
= get_modref( peb
->ImageBaseAddress
);
3128 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3130 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3134 peb
->LoaderLock
= &loader_section
;
3135 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3136 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3137 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3138 version_init( wm
->ldr
.FullDllName
.Buffer
);
3139 virtual_set_large_address_space();
3141 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3142 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3143 heap_set_debug_flags( GetProcessHeap() );
3145 /* the main exe needs to be the first in the load order list */
3146 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3147 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3148 RemoveEntryList( &wm
->ldr
.InMemoryOrderModuleList
);
3149 InsertHeadList( &peb
->LdrData
->InMemoryOrderModuleList
, &wm
->ldr
.InMemoryOrderModuleList
);
3151 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0, NULL
)) != STATUS_SUCCESS
)
3153 ERR( "Main exe initialization for %s failed, status %x\n",
3154 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3155 NtTerminateProcess( GetCurrentProcess(), status
);
3157 server_init_process_done();
3161 /***********************************************************************
3162 * RtlImageDirectoryEntryToData (NTDLL.@)
3164 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3166 const IMAGE_NT_HEADERS
*nt
;
3169 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
3171 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
3174 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3175 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3177 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3179 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3180 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3181 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3182 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3184 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3186 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3188 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3189 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3190 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3191 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3195 /* not mapped as image, need to find the section containing the virtual address */
3196 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3200 /***********************************************************************
3201 * RtlImageRvaToSection (NTDLL.@)
3203 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3204 HMODULE module
, DWORD rva
)
3207 const IMAGE_SECTION_HEADER
*sec
;
3209 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3210 nt
->FileHeader
.SizeOfOptionalHeader
);
3211 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3213 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3214 return (PIMAGE_SECTION_HEADER
)sec
;
3220 /***********************************************************************
3221 * RtlImageRvaToVa (NTDLL.@)
3223 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3224 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3226 IMAGE_SECTION_HEADER
*sec
;
3228 if (section
&& *section
) /* try this section first */
3231 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3234 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3236 if (section
) *section
= sec
;
3237 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3241 /***********************************************************************
3242 * RtlPcToFileHeader (NTDLL.@)
3244 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3249 RtlEnterCriticalSection( &loader_section
);
3250 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3251 RtlLeaveCriticalSection( &loader_section
);
3257 /***********************************************************************
3258 * NtLoadDriver (NTDLL.@)
3259 * ZwLoadDriver (NTDLL.@)
3261 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3263 FIXME("(%p), stub!\n",DriverServiceName
);
3264 return STATUS_NOT_IMPLEMENTED
;
3268 /***********************************************************************
3269 * NtUnloadDriver (NTDLL.@)
3270 * ZwUnloadDriver (NTDLL.@)
3272 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3274 FIXME("(%p), stub!\n",DriverServiceName
);
3275 return STATUS_NOT_IMPLEMENTED
;
3279 /******************************************************************
3282 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3284 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3289 /***********************************************************************
3290 * __wine_process_init
3292 void __wine_process_init(void)
3294 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3298 ANSI_STRING func_name
;
3299 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3301 main_exe_file
= thread_init();
3303 /* retrieve current umask */
3304 FILE_umask
= umask(0777);
3305 umask( FILE_umask
);
3307 load_global_options();
3309 /* setup the load callback and create ntdll modref */
3310 wine_dll_set_callback( load_builtin_callback
);
3312 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3314 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3317 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3318 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3320 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3321 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3322 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3324 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);