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
);
52 WINE_DECLARE_DEBUG_CHANNEL(pid
);
55 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
57 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
58 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
60 /* we don't want to include winuser.h */
61 #define RT_MANIFEST ((ULONG_PTR)24)
62 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
64 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
65 typedef void (CALLBACK
*LDRENUMPROC
)(LDR_MODULE
*, void *, BOOLEAN
*);
67 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
68 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
70 static const char * const reason_names
[] =
76 NULL
, NULL
, NULL
, NULL
,
80 static const WCHAR dllW
[] = {'.','d','l','l',0};
82 /* internal representation of 32bit modules. per process. */
83 typedef struct _wine_modref
87 struct _wine_modref
**deps
;
90 /* info about the current builtin dll load */
91 /* used to keep track of things across the register_dll constructor call */
92 struct builtin_load_info
94 const WCHAR
*load_path
;
95 const WCHAR
*filename
;
100 static struct builtin_load_info default_load_info
;
101 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
106 LPTHREAD_START_ROUTINE entry
;
109 static HANDLE main_exe_file
;
110 static UINT tls_module_count
; /* number of modules with TLS directory */
111 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
112 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
114 static RTL_CRITICAL_SECTION loader_section
;
115 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
117 0, 0, &loader_section
,
118 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
119 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
121 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
123 static WINE_MODREF
*cached_modref
;
124 static WINE_MODREF
*current_modref
;
125 static WINE_MODREF
*last_failed_modref
;
127 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
128 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
129 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
130 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
131 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
132 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
134 /* convert PE image VirtualAddress to Real Address */
135 static inline void *get_rva( HMODULE module
, DWORD va
)
137 return (void *)((char *)module
+ va
);
140 /* check whether the file name contains a path */
141 static inline BOOL
contains_path( LPCWSTR name
)
143 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
146 /* convert from straight ASCII to Unicode without depending on the current codepage */
147 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
149 while (len
--) *dst
++ = (unsigned char)*src
++;
153 /*************************************************************************
154 * call_dll_entry_point
156 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
157 * their entry point, so we need a small asm wrapper. Testing indicates
158 * that only modifying esi leads to a crash, so use this one to backup
159 * ebp while running the dll entry proc.
162 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
163 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
165 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
166 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
168 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
170 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
172 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
174 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
176 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
180 "movl 8(%ebp),%eax\n\t"
183 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
184 "leal -12(%ebp),%esp\n\t"
186 __ASM_CFI(".cfi_same_value %edi\n\t")
188 __ASM_CFI(".cfi_same_value %esi\n\t")
190 __ASM_CFI(".cfi_same_value %ebx\n\t")
192 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
193 __ASM_CFI(".cfi_same_value %ebp\n\t")
196 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
197 UINT reason
, void *reserved
)
199 return proc( module
, reason
, reserved
);
201 #endif /* __i386__ */
204 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
205 /*************************************************************************
208 * Entry point for stub functions.
210 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
212 EXCEPTION_RECORD rec
;
214 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
215 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
216 rec
.ExceptionRecord
= NULL
;
217 rec
.ExceptionAddress
= ret_addr
;
218 rec
.NumberParameters
= 2;
219 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
220 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
221 for (;;) RtlRaiseException( &rec
);
225 #include "pshpack1.h"
229 BYTE pushl1
; /* pushl $name */
231 BYTE pushl2
; /* pushl $dll */
233 BYTE call
; /* call stub_entry_point */
236 #elif defined(__arm__)
239 BYTE ldr_r0
[4]; /* ldr r0, $dll */
240 BYTE mov_pc_pc1
[4]; /* mov pc,pc */
242 BYTE ldr_r1
[4]; /* ldr r1, $name */
243 BYTE mov_pc_pc2
[4]; /* mov pc,pc */
245 BYTE mov_r2_lr
[4]; /* mov r2, lr */
246 BYTE ldr_pc_pc
[4]; /* ldr pc, [pc, #-4] */
252 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
254 BYTE movq_rsi
[2]; /* movq $name,%rsi */
256 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
257 BYTE movq_rax
[2]; /* movq $entry, %rax */
259 BYTE jmpq_rax
[2]; /* jmp %rax */
264 /*************************************************************************
267 * Allocate a stub entry point.
269 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
271 #define MAX_SIZE 65536
272 static struct stub
*stubs
;
273 static unsigned int nb_stubs
;
276 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
280 SIZE_T size
= MAX_SIZE
;
281 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
282 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
285 stub
= &stubs
[nb_stubs
++];
287 stub
->pushl1
= 0x68; /* pushl $name */
289 stub
->pushl2
= 0x68; /* pushl $dll */
291 stub
->call
= 0xe8; /* call stub_entry_point */
292 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
293 #elif defined(__arm__)
294 stub
->ldr_r0
[0] = 0x00; /* ldr r0, $dll */
295 stub
->ldr_r0
[1] = 0x00;
296 stub
->ldr_r0
[2] = 0x9f;
297 stub
->ldr_r0
[3] = 0xe5;
298 stub
->mov_pc_pc1
[0] = 0x0f; /* mov pc,pc */
299 stub
->mov_pc_pc1
[1] = 0xf0;
300 stub
->mov_pc_pc1
[2] = 0xa0;
301 stub
->mov_pc_pc1
[3] = 0xe1;
303 stub
->ldr_r1
[0] = 0x00; /* ldr r1, $name */
304 stub
->ldr_r1
[1] = 0x10;
305 stub
->ldr_r1
[2] = 0x9f;
306 stub
->ldr_r1
[3] = 0xe5;
307 stub
->mov_pc_pc2
[0] = 0x0f; /* mov pc,pc */
308 stub
->mov_pc_pc2
[1] = 0xf0;
309 stub
->mov_pc_pc2
[2] = 0xa0;
310 stub
->mov_pc_pc2
[3] = 0xe1;
312 stub
->mov_r2_lr
[0] = 0x0e; /* mov r2, lr */
313 stub
->mov_r2_lr
[1] = 0x20;
314 stub
->mov_r2_lr
[2] = 0xa0;
315 stub
->mov_r2_lr
[3] = 0xe1;
316 stub
->ldr_pc_pc
[0] = 0x04; /* ldr pc, [pc, #-4] */
317 stub
->ldr_pc_pc
[1] = 0xf0;
318 stub
->ldr_pc_pc
[2] = 0x1f;
319 stub
->ldr_pc_pc
[3] = 0xe5;
320 stub
->entry
= stub_entry_point
;
322 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
323 stub
->movq_rdi
[1] = 0xbf;
325 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
326 stub
->movq_rsi
[1] = 0xbe;
328 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
329 stub
->movq_rsp_rdx
[1] = 0x8b;
330 stub
->movq_rsp_rdx
[2] = 0x14;
331 stub
->movq_rsp_rdx
[3] = 0x24;
332 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
333 stub
->movq_rax
[1] = 0xb8;
334 stub
->entry
= stub_entry_point
;
335 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
336 stub
->jmpq_rax
[1] = 0xe0;
338 return (ULONG_PTR
)stub
;
342 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
343 #endif /* __i386__ */
346 /*************************************************************************
349 * Looks for the referenced HMODULE in the current process
350 * The loader_section must be locked while calling this function.
352 static WINE_MODREF
*get_modref( HMODULE hmod
)
354 PLIST_ENTRY mark
, entry
;
357 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
359 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
360 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
362 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
363 if (mod
->BaseAddress
== hmod
)
364 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
370 /**********************************************************************
371 * find_basename_module
373 * Find a module from its base name.
374 * The loader_section must be locked while calling this function
376 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
378 PLIST_ENTRY mark
, entry
;
380 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
381 return cached_modref
;
383 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
384 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
386 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
387 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
389 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
390 return cached_modref
;
397 /**********************************************************************
398 * find_fullname_module
400 * Find a module from its full path name.
401 * The loader_section must be locked while calling this function
403 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
405 PLIST_ENTRY mark
, entry
;
407 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
408 return cached_modref
;
410 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
411 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
413 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
414 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
416 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
417 return cached_modref
;
424 /*************************************************************************
425 * find_forwarded_export
427 * Find the final function pointer for a forwarded function.
428 * The loader_section must be locked while calling this function.
430 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
432 const IMAGE_EXPORT_DIRECTORY
*exports
;
436 const char *end
= strrchr(forward
, '.');
439 if (!end
) return NULL
;
440 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
441 ascii_to_unicode( mod_name
, forward
, end
- forward
);
442 mod_name
[end
- forward
] = 0;
443 if (!strchrW( mod_name
, '.' ))
445 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
446 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
449 if (!(wm
= find_basename_module( mod_name
)))
451 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
452 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
453 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
455 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
457 LdrUnloadDll( wm
->ldr
.BaseAddress
);
464 ERR( "module not found for forward '%s' used by %s\n",
465 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
469 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
470 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
472 const char *name
= end
+ 1;
473 if (*name
== '#') /* ordinal */
474 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
476 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
481 ERR("function not found for forward '%s' used by %s."
482 " If you are using builtin %s, try using the native one instead.\n",
483 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
484 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
490 /*************************************************************************
491 * find_ordinal_export
493 * Find an exported function by ordinal.
494 * The exports base must have been subtracted from the ordinal already.
495 * The loader_section must be locked while calling this function.
497 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
498 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
501 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
503 if (ordinal
>= exports
->NumberOfFunctions
)
505 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
508 if (!functions
[ordinal
]) return NULL
;
510 proc
= get_rva( module
, functions
[ordinal
] );
512 /* if the address falls into the export dir, it's a forward */
513 if (((const char *)proc
>= (const char *)exports
) &&
514 ((const char *)proc
< (const char *)exports
+ exp_size
))
515 return find_forwarded_export( module
, (const char *)proc
, load_path
);
519 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
520 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
524 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
525 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
531 /*************************************************************************
534 * Find an exported function by name.
535 * The loader_section must be locked while calling this function.
537 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
538 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
540 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
541 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
542 int min
= 0, max
= exports
->NumberOfNames
- 1;
544 /* first check the hint */
545 if (hint
>= 0 && hint
<= max
)
547 char *ename
= get_rva( module
, names
[hint
] );
548 if (!strcmp( ename
, name
))
549 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
552 /* then do a binary search */
555 int res
, pos
= (min
+ max
) / 2;
556 char *ename
= get_rva( module
, names
[pos
] );
557 if (!(res
= strcmp( ename
, name
)))
558 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
559 if (res
> 0) max
= pos
- 1;
567 /*************************************************************************
570 * Import the dll specified by the given import descriptor.
571 * The loader_section must be locked while calling this function.
573 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
578 const IMAGE_EXPORT_DIRECTORY
*exports
;
580 const IMAGE_THUNK_DATA
*import_list
;
581 IMAGE_THUNK_DATA
*thunk_list
;
583 const char *name
= get_rva( module
, descr
->Name
);
584 DWORD len
= strlen(name
);
586 SIZE_T protect_size
= 0;
589 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
590 if (descr
->u
.OriginalFirstThunk
)
591 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
593 import_list
= thunk_list
;
595 if (!import_list
->u1
.Ordinal
)
597 WARN( "Skipping unused import %s\n", name
);
602 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
604 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
606 ascii_to_unicode( buffer
, name
, len
);
608 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
610 else /* need to allocate a larger buffer */
612 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
613 if (!ptr
) return FALSE
;
614 ascii_to_unicode( ptr
, name
, len
);
616 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
617 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
622 if (status
== STATUS_DLL_NOT_FOUND
)
623 ERR("Library %s (which is needed by %s) not found\n",
624 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
626 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
627 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
631 /* unprotect the import address table since it can be located in
632 * readonly section */
633 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
634 protect_base
= thunk_list
;
635 protect_size
*= sizeof(*thunk_list
);
636 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
637 &protect_size
, PAGE_READWRITE
, &protect_old
);
639 imp_mod
= wmImp
->ldr
.BaseAddress
;
640 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
644 /* set all imported function to deadbeef */
645 while (import_list
->u1
.Ordinal
)
647 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
649 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
650 WARN("No implementation for %s.%d", name
, ordinal
);
651 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
655 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
656 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
657 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
659 WARN(" imported from %s, allocating stub %p\n",
660 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
661 (void *)thunk_list
->u1
.Function
);
668 while (import_list
->u1
.Ordinal
)
670 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
672 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
674 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
675 ordinal
- exports
->Base
, load_path
);
676 if (!thunk_list
->u1
.Function
)
678 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
679 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
680 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
681 (void *)thunk_list
->u1
.Function
);
683 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
685 else /* import by name */
687 IMAGE_IMPORT_BY_NAME
*pe_name
;
688 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
689 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
690 (const char*)pe_name
->Name
,
691 pe_name
->Hint
, load_path
);
692 if (!thunk_list
->u1
.Function
)
694 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
695 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
696 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
697 (void *)thunk_list
->u1
.Function
);
699 TRACE_(imports
)("--- %s %s.%d = %p\n",
700 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
707 /* restore old protection of the import address table */
708 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
714 /***********************************************************************
715 * create_module_activation_context
717 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
720 LDR_RESOURCE_INFO info
;
721 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
723 info
.Type
= RT_MANIFEST
;
724 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
726 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
729 ctx
.cbSize
= sizeof(ctx
);
731 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
732 ctx
.hModule
= module
->BaseAddress
;
733 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
734 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
740 /*************************************************************************
741 * is_dll_native_subsystem
743 * Check if dll is a proper native driver.
744 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
745 * while being perfectly normal DLLs. This heuristic should catch such breakages.
747 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
749 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
750 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
751 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
755 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
756 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
758 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
759 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
761 for (i
= 0; imports
[i
].Name
; i
++)
763 const char *name
= get_rva( module
, imports
[i
].Name
);
764 DWORD len
= strlen(name
);
765 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
766 ascii_to_unicode( buffer
, name
, len
+ 1 );
767 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
769 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
777 /*************************************************************************
780 * Allocate a TLS slot for a newly-loaded module.
781 * The loader_section must be locked while calling this function.
783 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
785 const IMAGE_TLS_DIRECTORY
*dir
;
790 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
793 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
794 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
796 for (i
= 0; i
< tls_module_count
; i
++)
798 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
799 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
803 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
804 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
805 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
807 if (i
== tls_module_count
)
809 UINT new_count
= max( 32, tls_module_count
* 2 );
812 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
814 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
815 new_count
* sizeof(*tls_dirs
) );
816 if (!new_ptr
) return -1;
818 /* resize the pointer block in all running threads */
819 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
821 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
822 void **old
= teb
->ThreadLocalStoragePointer
;
823 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
826 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
827 teb
->ThreadLocalStoragePointer
= new;
828 #if defined(__APPLE__) && defined(__x86_64__)
829 if (teb
->Reserved5
[0])
830 ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
832 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
833 /* FIXME: can't free old block here, should be freed at thread exit */
837 tls_module_count
= new_count
;
840 /* allocate the data block in all running threads */
841 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
843 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
845 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
846 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
847 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
849 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
850 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
852 RtlFreeHeap( GetProcessHeap(), 0,
853 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
856 *(DWORD
*)dir
->AddressOfIndex
= i
;
862 /*************************************************************************
865 * Free the module TLS slot on unload.
866 * The loader_section must be locked while calling this function.
868 static void free_tls_slot( LDR_MODULE
*mod
)
870 ULONG i
= (USHORT
)mod
->TlsIndex
;
872 if (mod
->TlsIndex
== -1) return;
873 assert( i
< tls_module_count
);
874 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
878 /****************************************************************
881 * Fixup all imports of a given module.
882 * The loader_section must be locked while calling this function.
884 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
887 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
893 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
894 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
896 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
898 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
899 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
900 return STATUS_SUCCESS
;
903 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
905 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
907 if (!create_module_activation_context( &wm
->ldr
))
908 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
910 /* Allocate module dependency list */
911 wm
->nDeps
= nb_imports
;
912 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
914 /* load the imported modules. They are automatically
915 * added to the modref list of the process.
917 prev
= current_modref
;
919 status
= STATUS_SUCCESS
;
920 for (i
= 0; i
< nb_imports
; i
++)
922 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &wm
->deps
[i
] ))
925 status
= STATUS_DLL_NOT_FOUND
;
928 current_modref
= prev
;
929 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
934 /*************************************************************************
937 * Allocate a WINE_MODREF structure and add it to the process list
938 * The loader_section must be locked while calling this function.
940 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
944 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
946 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
951 wm
->ldr
.BaseAddress
= hModule
;
952 wm
->ldr
.EntryPoint
= NULL
;
953 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
954 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
955 wm
->ldr
.TlsIndex
= -1;
956 wm
->ldr
.LoadCount
= 1;
957 wm
->ldr
.SectionHandle
= NULL
;
958 wm
->ldr
.CheckSum
= 0;
959 wm
->ldr
.TimeDateStamp
= 0;
960 wm
->ldr
.ActivationContext
= 0;
962 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
963 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
964 else p
= wm
->ldr
.FullDllName
.Buffer
;
965 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
967 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
969 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
970 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
971 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
972 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
975 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
976 &wm
->ldr
.InLoadOrderModuleList
);
977 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
978 &wm
->ldr
.InMemoryOrderModuleList
);
980 /* wait until init is called for inserting into this list */
981 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
982 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
984 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
986 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
987 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
988 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
994 /*************************************************************************
997 * Allocate the per-thread structure for module TLS storage.
999 static NTSTATUS
alloc_thread_tls(void)
1004 if (!tls_module_count
) return STATUS_SUCCESS
;
1006 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1007 tls_module_count
* sizeof(*pointers
) )))
1008 return STATUS_NO_MEMORY
;
1010 for (i
= 0; i
< tls_module_count
; i
++)
1012 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1015 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1016 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1018 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1020 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1021 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1022 return STATUS_NO_MEMORY
;
1024 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1025 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1027 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1028 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1030 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1031 #if defined(__APPLE__) && defined(__x86_64__)
1032 __asm__
volatile (".byte 0x65\n\tmovq %0,%c1"
1034 : "r" (pointers
), "n" (FIELD_OFFSET(TEB
, ThreadLocalStoragePointer
)));
1036 return STATUS_SUCCESS
;
1040 /*************************************************************************
1041 * call_tls_callbacks
1043 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1045 const IMAGE_TLS_DIRECTORY
*dir
;
1046 const PIMAGE_TLS_CALLBACK
*callback
;
1049 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1050 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1052 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1054 if (TRACE_ON(relay
))
1057 DPRINTF( "%04x:", GetCurrentProcessId() );
1058 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1059 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1063 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1067 if (TRACE_ON(relay
))
1070 DPRINTF( "%04x:", GetCurrentProcessId() );
1071 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1072 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
1077 if (TRACE_ON(relay
))
1080 DPRINTF( "%04x:", GetCurrentProcessId() );
1081 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1082 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1088 /*************************************************************************
1091 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1094 NTSTATUS status
= STATUS_SUCCESS
;
1095 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1096 void *module
= wm
->ldr
.BaseAddress
;
1099 /* Skip calls for modules loaded with special load flags */
1101 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1102 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1103 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1105 if (TRACE_ON(relay
))
1107 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1108 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1109 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1111 DPRINTF( "%04x:", GetCurrentProcessId() );
1112 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1113 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1114 reason_names
[reason
], lpReserved
);
1116 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1117 reason_names
[reason
], lpReserved
);
1121 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1123 status
= STATUS_DLL_INIT_FAILED
;
1127 if (TRACE_ON(relay
))
1130 DPRINTF( "%04x:", GetCurrentProcessId() );
1131 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1132 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
1134 status
= GetExceptionCode();
1138 /* The state of the module list may have changed due to the call
1139 to the dll. We cannot assume that this module has not been
1141 if (TRACE_ON(relay
))
1144 DPRINTF( "%04x:", GetCurrentProcessId() );
1145 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1146 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1147 reason_names
[reason
], lpReserved
, retv
);
1149 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1155 /*************************************************************************
1158 * Send the process attach notification to all DLLs the given module
1159 * depends on (recursively). This is somewhat complicated due to the fact that
1161 * - we have to respect the module dependencies, i.e. modules implicitly
1162 * referenced by another module have to be initialized before the module
1163 * itself can be initialized
1165 * - the initialization routine of a DLL can itself call LoadLibrary,
1166 * thereby introducing a whole new set of dependencies (even involving
1167 * the 'old' modules) at any time during the whole process
1169 * (Note that this routine can be recursively entered not only directly
1170 * from itself, but also via LoadLibrary from one of the called initialization
1173 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1174 * the process *detach* notifications to be sent in the correct order.
1175 * This must not only take into account module dependencies, but also
1176 * 'hidden' dependencies created by modules calling LoadLibrary in their
1177 * attach notification routine.
1179 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1180 * list after the attach notification has returned. This implies that the
1181 * detach notifications are called in the reverse of the sequence the attach
1182 * notifications *returned*.
1184 * The loader_section must be locked while calling this function.
1186 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1188 NTSTATUS status
= STATUS_SUCCESS
;
1192 if (process_detaching
) return status
;
1194 /* prevent infinite recursion in case of cyclical dependencies */
1195 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1196 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1199 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1201 /* Tag current MODREF to prevent recursive loop */
1202 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1203 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1204 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1206 /* Recursively attach all DLLs this one depends on */
1207 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1209 if (!wm
->deps
[i
]) continue;
1210 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1213 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1214 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1215 &wm
->ldr
.InInitializationOrderModuleList
);
1217 /* Call DLL entry point */
1218 if (status
== STATUS_SUCCESS
)
1220 WINE_MODREF
*prev
= current_modref
;
1221 current_modref
= wm
;
1222 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1223 if (status
== STATUS_SUCCESS
)
1224 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1227 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1228 /* point to the name so LdrInitializeThunk can print it */
1229 last_failed_modref
= wm
;
1230 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1232 current_modref
= prev
;
1235 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1236 /* Remove recursion flag */
1237 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1239 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1244 /**********************************************************************
1245 * attach_implicitly_loaded_dlls
1247 * Attach to the (builtin) dlls that have been implicitly loaded because
1248 * of a dependency at the Unix level, but not imported at the Win32 level.
1250 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1254 PLIST_ENTRY mark
, entry
;
1256 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1257 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1259 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1261 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1262 TRACE( "found implicitly loaded %s, attaching to it\n",
1263 debugstr_w(mod
->BaseDllName
.Buffer
));
1264 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1265 break; /* restart the search from the start */
1267 if (entry
== mark
) break; /* nothing found */
1272 /*************************************************************************
1275 * Send DLL process detach notifications. See the comment about calling
1276 * sequence at process_attach.
1278 static void process_detach(void)
1280 PLIST_ENTRY mark
, entry
;
1283 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1286 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1288 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1289 InInitializationOrderModuleList
);
1290 /* Check whether to detach this DLL */
1291 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1293 if ( mod
->LoadCount
&& !process_detaching
)
1296 /* Call detach notification */
1297 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1298 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1299 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1301 /* Restart at head of WINE_MODREF list, as entries might have
1302 been added and/or removed while performing the call ... */
1305 } while (entry
!= mark
);
1308 /*************************************************************************
1309 * MODULE_DllThreadAttach
1311 * Send DLL thread attach notifications. These are sent in the
1312 * reverse sequence of process detach notification.
1315 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1317 PLIST_ENTRY mark
, entry
;
1321 /* don't do any attach calls if process is exiting */
1322 if (process_detaching
) return STATUS_SUCCESS
;
1324 RtlEnterCriticalSection( &loader_section
);
1326 RtlAcquirePebLock();
1327 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
1328 RtlReleasePebLock();
1330 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1332 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1333 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1335 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1336 InInitializationOrderModuleList
);
1337 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1339 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1342 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1343 DLL_THREAD_ATTACH
, lpReserved
);
1347 RtlLeaveCriticalSection( &loader_section
);
1351 /******************************************************************
1352 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1355 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1358 NTSTATUS ret
= STATUS_SUCCESS
;
1360 RtlEnterCriticalSection( &loader_section
);
1362 wm
= get_modref( hModule
);
1363 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1364 ret
= STATUS_DLL_NOT_FOUND
;
1366 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1368 RtlLeaveCriticalSection( &loader_section
);
1373 /******************************************************************
1374 * LdrFindEntryForAddress (NTDLL.@)
1376 * The loader_section must be locked while calling this function
1378 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1380 PLIST_ENTRY mark
, entry
;
1383 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1384 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1386 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1387 if (mod
->BaseAddress
<= addr
&&
1388 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1391 return STATUS_SUCCESS
;
1394 return STATUS_NO_MORE_ENTRIES
;
1397 /******************************************************************
1398 * LdrEnumerateLoadedModules (NTDLL.@)
1400 NTSTATUS WINAPI
LdrEnumerateLoadedModules( void *unknown
, LDRENUMPROC callback
, void *context
)
1402 LIST_ENTRY
*mark
, *entry
;
1404 BOOLEAN stop
= FALSE
;
1406 TRACE( "(%p, %p, %p)\n", unknown
, callback
, context
);
1408 if (unknown
|| !callback
)
1409 return STATUS_INVALID_PARAMETER
;
1411 RtlEnterCriticalSection( &loader_section
);
1413 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1414 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1416 mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1417 callback( mod
, context
, &stop
);
1421 RtlLeaveCriticalSection( &loader_section
);
1422 return STATUS_SUCCESS
;
1425 /******************************************************************
1426 * LdrLockLoaderLock (NTDLL.@)
1428 * Note: some flags are not implemented.
1429 * Flag 0x01 is used to raise exceptions on errors.
1431 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1433 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1435 if (result
) *result
= 0;
1436 if (magic
) *magic
= 0;
1437 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1438 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1439 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1443 if (!RtlTryEnterCriticalSection( &loader_section
))
1446 return STATUS_SUCCESS
;
1452 RtlEnterCriticalSection( &loader_section
);
1453 if (result
) *result
= 1;
1455 *magic
= GetCurrentThreadId();
1456 return STATUS_SUCCESS
;
1460 /******************************************************************
1461 * LdrUnlockLoaderUnlock (NTDLL.@)
1463 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1467 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1468 RtlLeaveCriticalSection( &loader_section
);
1470 return STATUS_SUCCESS
;
1474 /******************************************************************
1475 * LdrGetProcedureAddress (NTDLL.@)
1477 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1478 ULONG ord
, PVOID
*address
)
1480 IMAGE_EXPORT_DIRECTORY
*exports
;
1482 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1484 RtlEnterCriticalSection( &loader_section
);
1486 /* check if the module itself is invalid to return the proper error */
1487 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1488 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1489 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1491 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1492 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1493 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1497 ret
= STATUS_SUCCESS
;
1501 RtlLeaveCriticalSection( &loader_section
);
1506 /***********************************************************************
1509 * Check if a loaded native dll is a Wine fake dll.
1511 static BOOL
is_fake_dll( HANDLE handle
)
1513 static const char fakedll_signature
[] = "Wine placeholder DLL";
1514 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1515 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1517 LARGE_INTEGER offset
;
1519 offset
.QuadPart
= 0;
1520 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1521 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1522 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1523 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1524 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1529 /***********************************************************************
1530 * get_builtin_fullname
1532 * Build the full pathname for a builtin dll.
1534 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1536 static const WCHAR soW
[] = {'.','s','o',0};
1537 WCHAR
*p
, *fullname
;
1538 size_t i
, len
= strlen(filename
);
1540 /* check if path can correspond to the dll we have */
1541 if (path
&& (p
= strrchrW( path
, '\\' )))
1544 for (i
= 0; i
< len
; i
++)
1545 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1546 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1548 /* the filename matches, use path as the full path */
1550 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1552 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1559 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1560 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1562 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1563 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1564 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1565 ascii_to_unicode( p
, filename
, len
+ 1 );
1571 /*************************************************************************
1574 static BOOL
is_16bit_builtin( HMODULE module
)
1576 const IMAGE_EXPORT_DIRECTORY
*exports
;
1579 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1580 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1583 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1587 /***********************************************************************
1588 * load_builtin_callback
1590 * Load a library in memory; callback function for wine_dll_register
1592 static void load_builtin_callback( void *module
, const char *filename
)
1594 static const WCHAR emptyW
[1];
1595 IMAGE_NT_HEADERS
*nt
;
1598 const WCHAR
*load_path
;
1602 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1605 if (!(nt
= RtlImageNtHeader( module
)))
1607 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1608 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1612 virtual_create_builtin_view( module
);
1614 /* create the MODREF */
1616 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1618 ERR( "can't load %s\n", filename
);
1619 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1623 wm
= alloc_module( module
, fullname
);
1624 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1627 ERR( "can't load %s\n", filename
);
1628 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1631 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1633 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1634 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1635 is_16bit_builtin( module
))
1639 load_path
= builtin_load_info
->load_path
;
1640 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1641 if (!load_path
) load_path
= emptyW
;
1642 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1644 /* the module has only be inserted in the load & memory order lists */
1645 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1646 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1647 /* FIXME: free the modref */
1648 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1653 builtin_load_info
->wm
= wm
;
1654 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1656 /* send the DLL load event */
1658 SERVER_START_REQ( load_dll
)
1661 req
->base
= wine_server_client_ptr( module
);
1662 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1663 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1664 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1665 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1666 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1667 wine_server_call( req
);
1671 /* setup relay debugging entry points */
1672 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1676 /***********************************************************************
1677 * set_security_cookie
1679 * Create a random security cookie for buffer overflow protection. Make
1680 * sure it does not accidentally match the default cookie value.
1682 static void set_security_cookie( void *module
, SIZE_T len
)
1685 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1689 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1690 if (!loadcfg
) return;
1691 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1692 if (!loadcfg
->SecurityCookie
) return;
1693 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1694 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1696 WARN( "security cookie %p outside of image %p-%p\n",
1697 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1701 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1702 TRACE( "initializing security cookie %p\n", cookie
);
1704 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1707 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1708 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1709 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1710 *cookie
= RtlRandom( &seed
);
1711 #ifdef DEFAULT_SECURITY_COOKIE_64
1712 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1714 *cookie
= RtlRandom( &seed
);
1715 /* fill up, but keep the highest word clear */
1716 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1724 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1726 IMAGE_NT_HEADERS
*nt
;
1728 IMAGE_BASE_RELOCATION
*rel
, *end
;
1729 const IMAGE_DATA_DIRECTORY
*relocs
;
1730 const IMAGE_SECTION_HEADER
*sec
;
1732 ULONG protect_old
[96], i
;
1734 nt
= RtlImageNtHeader( module
);
1735 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1737 assert( module
!= base
);
1739 /* no relocations are performed on non page-aligned binaries */
1740 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1741 return STATUS_SUCCESS
;
1743 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1744 return STATUS_SUCCESS
;
1746 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1748 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1750 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1752 return STATUS_CONFLICTING_ADDRESSES
;
1755 if (!relocs
->Size
) return STATUS_SUCCESS
;
1756 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1758 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1759 return STATUS_INVALID_IMAGE_FORMAT
;
1761 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1762 nt
->FileHeader
.SizeOfOptionalHeader
);
1763 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1765 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1766 SIZE_T size
= sec
[i
].SizeOfRawData
;
1767 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1768 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1771 TRACE( "relocating from %p-%p to %p-%p\n",
1772 base
, base
+ len
, module
, (char *)module
+ len
);
1774 rel
= get_rva( module
, relocs
->VirtualAddress
);
1775 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1776 delta
= (char *)module
- base
;
1778 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1780 if (rel
->VirtualAddress
>= len
)
1782 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1783 return STATUS_ACCESS_VIOLATION
;
1785 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1786 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1787 (USHORT
*)(rel
+ 1), delta
);
1788 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1791 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1793 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1794 SIZE_T size
= sec
[i
].SizeOfRawData
;
1795 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1796 &size
, protect_old
[i
], &protect_old
[i
] );
1799 return STATUS_SUCCESS
;
1802 /******************************************************************************
1803 * load_native_dll (internal)
1805 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1806 DWORD flags
, WINE_MODREF
** pwm
)
1811 IMAGE_NT_HEADERS
*nt
;
1816 TRACE("Trying native dll %s\n", debugstr_w(name
));
1819 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1820 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1821 if (status
!= STATUS_SUCCESS
) return status
;
1824 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1825 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_EXECUTE_READ
);
1827 /* perform base relocation, if necessary */
1829 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1830 status
= perform_relocations( module
, len
);
1832 if (status
!= STATUS_SUCCESS
)
1834 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1838 /* create the MODREF */
1840 if (!(wm
= alloc_module( module
, name
)))
1842 status
= STATUS_NO_MEMORY
;
1846 set_security_cookie( module
, len
);
1850 nt
= RtlImageNtHeader( module
);
1852 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1853 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1854 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1856 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1858 /* the module has only be inserted in the load & memory order lists */
1859 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1860 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1862 /* FIXME: there are several more dangling references
1863 * left. Including dlls loaded by this dll before the
1864 * failed one. Unrolling is rather difficult with the
1865 * current structure and we can leave them lying
1866 * around with no problems, so we don't care.
1867 * As these might reference our wm, we don't free it.
1873 /* send DLL load event */
1875 SERVER_START_REQ( load_dll
)
1877 req
->mapping
= wine_server_obj_handle( mapping
);
1878 req
->base
= wine_server_client_ptr( module
);
1879 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1880 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1881 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1882 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1883 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1884 wine_server_call( req
);
1888 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1890 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1892 wm
->ldr
.LoadCount
= 1;
1894 status
= STATUS_SUCCESS
;
1901 /***********************************************************************
1904 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1905 DWORD flags
, WINE_MODREF
** pwm
)
1907 char error
[256], dllname
[MAX_PATH
];
1908 const WCHAR
*name
, *p
;
1911 struct builtin_load_info info
, *prev_info
;
1913 /* Fix the name in case we have a full path and extension */
1915 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1916 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1918 /* load_library will modify info.status. Note also that load_library can be
1919 * called several times, if the .so file we're loading has dependencies.
1920 * info.status will gather all the errors we may get while loading all these
1923 info
.load_path
= load_path
;
1924 info
.filename
= NULL
;
1925 info
.status
= STATUS_SUCCESS
;
1928 if (file
) /* we have a real file, try to load it */
1930 UNICODE_STRING nt_name
;
1931 ANSI_STRING unix_name
;
1933 TRACE("Trying built-in %s\n", debugstr_w(path
));
1935 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1936 return STATUS_DLL_NOT_FOUND
;
1938 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1940 RtlFreeUnicodeString( &nt_name
);
1941 return STATUS_DLL_NOT_FOUND
;
1943 prev_info
= builtin_load_info
;
1944 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1945 builtin_load_info
= &info
;
1946 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1947 builtin_load_info
= prev_info
;
1948 RtlFreeUnicodeString( &nt_name
);
1949 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1952 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1953 return STATUS_INVALID_IMAGE_FORMAT
;
1960 TRACE("Trying built-in %s\n", debugstr_w(name
));
1962 /* we don't want to depend on the current codepage here */
1963 len
= strlenW( name
) + 1;
1964 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1965 for (i
= 0; i
< len
; i
++)
1967 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1968 dllname
[i
] = (char)name
[i
];
1969 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1972 prev_info
= builtin_load_info
;
1973 builtin_load_info
= &info
;
1974 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1975 builtin_load_info
= prev_info
;
1980 /* The file does not exist -> WARN() */
1981 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1982 return STATUS_DLL_NOT_FOUND
;
1984 /* ERR() for all other errors (missing functions, ...) */
1985 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1986 return STATUS_PROCEDURE_NOT_FOUND
;
1990 if (info
.status
!= STATUS_SUCCESS
)
1992 wine_dll_unload( handle
);
1998 PLIST_ENTRY mark
, entry
;
2000 /* The constructor wasn't called, this means the .so is already
2001 * loaded under a different name. Try to find the wm for it. */
2003 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2004 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2006 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2007 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
2009 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2010 TRACE( "Found %s at %p for builtin %s\n",
2011 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
2015 wine_dll_unload( handle
); /* release the libdl refcount */
2016 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
2017 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
2021 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
2022 info
.wm
->ldr
.LoadCount
= 1;
2023 info
.wm
->ldr
.SectionHandle
= handle
;
2027 return STATUS_SUCCESS
;
2031 /***********************************************************************
2034 * Find the full path (if any) of the dll from the activation context.
2036 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2038 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2039 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2041 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2042 ACTCTX_SECTION_KEYED_DATA data
;
2043 UNICODE_STRING nameW
;
2045 SIZE_T needed
, size
= 1024;
2048 RtlInitUnicodeString( &nameW
, libname
);
2049 data
.cbSize
= sizeof(data
);
2050 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2051 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2053 if (status
!= STATUS_SUCCESS
) return status
;
2057 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2059 status
= STATUS_NO_MEMORY
;
2062 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2063 AssemblyDetailedInformationInActivationContext
,
2064 info
, size
, &needed
);
2065 if (status
== STATUS_SUCCESS
) break;
2066 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2067 RtlFreeHeap( GetProcessHeap(), 0, info
);
2069 /* restart with larger buffer */
2072 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2074 status
= STATUS_SXS_KEY_NOT_FOUND
;
2078 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2080 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2083 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2085 /* manifest name does not match directory name, so it's not a global
2086 * windows/winsxs manifest; use the manifest directory name instead */
2087 dirlen
= p
- info
->lpAssemblyManifestPath
;
2088 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2089 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2091 status
= STATUS_NO_MEMORY
;
2094 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2096 strcpyW( p
, libname
);
2101 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2102 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2104 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2106 status
= STATUS_NO_MEMORY
;
2109 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2111 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2112 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2113 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2114 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2116 strcpyW( p
, libname
);
2118 RtlFreeHeap( GetProcessHeap(), 0, info
);
2119 RtlReleaseActivationContext( data
.hActCtx
);
2124 /***********************************************************************
2127 * Find the file (or already loaded module) for a given dll name.
2129 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2130 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
2132 OBJECT_ATTRIBUTES attr
;
2134 UNICODE_STRING nt_name
;
2135 WCHAR
*file_part
, *ext
, *dllname
;
2138 /* first append .dll if needed */
2141 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2143 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2144 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2145 return STATUS_NO_MEMORY
;
2146 strcpyW( dllname
, libname
);
2147 strcatW( dllname
, dllW
);
2151 nt_name
.Buffer
= NULL
;
2153 if (!contains_path( libname
))
2156 WCHAR
*fullname
= NULL
;
2158 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2160 status
= find_actctx_dll( libname
, &fullname
);
2161 if (status
== STATUS_SUCCESS
)
2163 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2164 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2165 libname
= dllname
= fullname
;
2167 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2169 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2174 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2176 /* we need to search for it */
2177 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2180 if (len
>= *size
) goto overflow
;
2181 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
2183 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2185 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2186 return STATUS_NO_MEMORY
;
2188 attr
.Length
= sizeof(attr
);
2189 attr
.RootDirectory
= 0;
2190 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2191 attr
.ObjectName
= &nt_name
;
2192 attr
.SecurityDescriptor
= NULL
;
2193 attr
.SecurityQualityOfService
= NULL
;
2194 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2200 if (!contains_path( libname
))
2202 /* if libname doesn't contain a path at all, we simply return the name as is,
2203 * to be loaded as builtin */
2204 len
= strlenW(libname
) * sizeof(WCHAR
);
2205 if (len
>= *size
) goto overflow
;
2206 strcpyW( filename
, libname
);
2211 /* absolute path name, or relative path name but not found above */
2213 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2215 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2216 return STATUS_NO_MEMORY
;
2218 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2219 if (len
>= *size
) goto overflow
;
2220 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2221 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
2223 attr
.Length
= sizeof(attr
);
2224 attr
.RootDirectory
= 0;
2225 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2226 attr
.ObjectName
= &nt_name
;
2227 attr
.SecurityDescriptor
= NULL
;
2228 attr
.SecurityQualityOfService
= NULL
;
2229 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2232 RtlFreeUnicodeString( &nt_name
);
2233 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2234 return STATUS_SUCCESS
;
2237 RtlFreeUnicodeString( &nt_name
);
2238 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2239 *size
= len
+ sizeof(WCHAR
);
2240 return STATUS_BUFFER_TOO_SMALL
;
2244 /***********************************************************************
2245 * load_dll (internal)
2247 * Load a PE style module according to the load order.
2248 * The loader_section must be locked while calling this function.
2250 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2252 enum loadorder loadorder
;
2256 WINE_MODREF
*main_exe
;
2260 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2264 size
= sizeof(buffer
);
2267 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2268 if (nts
== STATUS_SUCCESS
) break;
2269 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2270 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2271 /* grow the buffer and retry */
2272 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2275 if (*pwm
) /* found already loaded module */
2277 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2279 TRACE("Found %s for %s at %p, count=%d\n",
2280 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2281 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2282 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2283 return STATUS_SUCCESS
;
2286 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2287 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2289 if (handle
&& is_fake_dll( handle
))
2291 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2299 nts
= STATUS_NO_MEMORY
;
2302 nts
= STATUS_DLL_NOT_FOUND
;
2305 case LO_NATIVE_BUILTIN
:
2306 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2309 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2310 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2311 /* not in PE format, maybe it's a builtin */
2312 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2314 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2315 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2318 case LO_BUILTIN_NATIVE
:
2319 case LO_DEFAULT
: /* default is builtin,native */
2320 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2321 if (!handle
) break; /* nothing else we can try */
2322 /* file is not a builtin library, try without using the specified file */
2323 if (nts
!= STATUS_SUCCESS
)
2324 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2325 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2326 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2328 /* stub-only dll, try native */
2329 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2330 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2331 nts
= STATUS_DLL_NOT_FOUND
;
2333 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2334 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2338 if (nts
== STATUS_SUCCESS
)
2340 /* Initialize DLL just loaded */
2341 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2342 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2343 (*pwm
)->ldr
.BaseAddress
);
2344 if (handle
) NtClose( handle
);
2345 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2349 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2350 if (handle
) NtClose( handle
);
2351 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2355 /******************************************************************
2356 * LdrLoadDll (NTDLL.@)
2358 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2359 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2364 RtlEnterCriticalSection( &loader_section
);
2366 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2367 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2369 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2371 nts
= process_attach( wm
, NULL
);
2372 if (nts
!= STATUS_SUCCESS
)
2374 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2378 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2380 RtlLeaveCriticalSection( &loader_section
);
2385 /******************************************************************
2386 * LdrGetDllHandle (NTDLL.@)
2388 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2396 RtlEnterCriticalSection( &loader_section
);
2398 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2401 size
= sizeof(buffer
);
2404 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2405 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2406 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2407 /* grow the buffer and retry */
2408 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2410 status
= STATUS_NO_MEMORY
;
2415 if (status
== STATUS_SUCCESS
)
2417 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2418 else status
= STATUS_DLL_NOT_FOUND
;
2421 RtlLeaveCriticalSection( &loader_section
);
2422 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2427 /******************************************************************
2428 * LdrAddRefDll (NTDLL.@)
2430 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2432 NTSTATUS ret
= STATUS_SUCCESS
;
2435 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2437 RtlEnterCriticalSection( &loader_section
);
2439 if ((wm
= get_modref( module
)))
2441 if (flags
& LDR_ADDREF_DLL_PIN
)
2442 wm
->ldr
.LoadCount
= -1;
2444 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2445 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2447 else ret
= STATUS_INVALID_PARAMETER
;
2449 RtlLeaveCriticalSection( &loader_section
);
2454 /***********************************************************************
2455 * LdrProcessRelocationBlock (NTDLL.@)
2457 * Apply relocations to a given page of a mapped PE image.
2459 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2460 USHORT
*relocs
, INT_PTR delta
)
2464 USHORT offset
= *relocs
& 0xfff;
2465 int type
= *relocs
>> 12;
2468 case IMAGE_REL_BASED_ABSOLUTE
:
2470 case IMAGE_REL_BASED_HIGH
:
2471 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2473 case IMAGE_REL_BASED_LOW
:
2474 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2476 case IMAGE_REL_BASED_HIGHLOW
:
2477 *(int *)((char *)page
+ offset
) += delta
;
2480 case IMAGE_REL_BASED_DIR64
:
2481 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2483 #elif defined(__arm__)
2484 case IMAGE_REL_BASED_THUMB_MOV32
:
2486 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2487 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2488 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2491 if ((inst
& 0x8000fbf0) != 0x0000f240)
2492 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2494 imm16
+= LOWORD(delta
);
2495 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2496 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2497 ((imm16
>> 12) & 0x000f) +
2498 ((imm16
<< 20) & 0x70000000) +
2499 ((imm16
<< 16) & 0xff0000);
2503 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2504 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2505 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2507 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2508 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2512 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2513 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2514 ((imm16
>> 1) & 0x0400) +
2515 ((imm16
>> 12) & 0x000f) +
2516 ((imm16
<< 20) & 0x70000000) +
2517 ((imm16
<< 16) & 0xff0000);
2523 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2528 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2532 /******************************************************************
2533 * LdrQueryProcessModuleInformation
2536 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2537 ULONG buf_size
, ULONG
* req_size
)
2539 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2540 ULONG size
= sizeof(ULONG
);
2541 NTSTATUS nts
= STATUS_SUCCESS
;
2544 PLIST_ENTRY mark
, entry
;
2548 smi
->ModulesCount
= 0;
2550 RtlEnterCriticalSection( &loader_section
);
2551 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2552 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2554 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2555 size
+= sizeof(*sm
);
2556 if (size
<= buf_size
)
2558 sm
->Reserved1
= 0; /* FIXME */
2559 sm
->Reserved2
= 0; /* FIXME */
2560 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2561 sm
->ImageSize
= mod
->SizeOfImage
;
2562 sm
->Flags
= mod
->Flags
;
2564 sm
->Rank
= 0; /* FIXME */
2565 sm
->Unknown
= 0; /* FIXME */
2567 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2568 str
.Buffer
= (char*)sm
->Name
;
2569 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2570 ptr
= strrchr(str
.Buffer
, '\\');
2571 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2573 smi
->ModulesCount
++;
2576 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2578 RtlLeaveCriticalSection( &loader_section
);
2580 if (req_size
) *req_size
= size
;
2586 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2592 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2594 RtlInitUnicodeString( &str
, name
);
2596 size
= sizeof(buffer
) - sizeof(WCHAR
);
2597 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2600 if (info
->Type
!= REG_DWORD
)
2602 buffer
[size
/ sizeof(WCHAR
)] = 0;
2603 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2605 else memcpy( value
, info
->Data
, sizeof(*value
) );
2609 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2610 void *data
, ULONG in_size
, ULONG
*out_size
)
2616 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2617 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2619 RtlInitUnicodeString( &str
, name
);
2621 size
= info_size
+ in_size
;
2622 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2623 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2624 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2625 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2627 if (out_size
) *out_size
= info
->DataLength
;
2628 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2630 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2635 /******************************************************************
2636 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2638 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2639 void *data
, ULONG in_size
, ULONG
*out_size
)
2641 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2642 'S','o','f','t','w','a','r','e','\\',
2643 'M','i','c','r','o','s','o','f','t','\\',
2644 'W','i','n','d','o','w','s',' ','N','T','\\',
2645 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2646 'I','m','a','g','e',' ','F','i','l','e',' ',
2647 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2648 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2649 OBJECT_ATTRIBUTES attr
;
2650 UNICODE_STRING name_str
;
2656 attr
.Length
= sizeof(attr
);
2657 attr
.RootDirectory
= 0;
2658 attr
.ObjectName
= &name_str
;
2659 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2660 attr
.SecurityDescriptor
= NULL
;
2661 attr
.SecurityQualityOfService
= NULL
;
2663 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2664 else p
= key
->Buffer
;
2665 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2666 name_str
.Buffer
= path
;
2667 name_str
.Length
= sizeof(optionsW
) + len
;
2668 name_str
.MaximumLength
= name_str
.Length
;
2669 memcpy( path
, optionsW
, sizeof(optionsW
) );
2670 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2671 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2673 if (type
== REG_DWORD
)
2675 if (out_size
) *out_size
= sizeof(ULONG
);
2676 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2677 else status
= STATUS_BUFFER_OVERFLOW
;
2679 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2686 /******************************************************************
2687 * RtlDllShutdownInProgress (NTDLL.@)
2689 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2691 return process_detaching
;
2694 /****************************************************************************
2695 * LdrResolveDelayLoadedAPI (NTDLL.@)
2697 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2698 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2699 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2701 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2702 DELAYLOAD_INFO delayinfo
;
2710 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2712 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2713 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2714 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2715 name
= get_rva(base
, desc
->DllNameRVA
);
2720 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2722 nts
= STATUS_NO_MEMORY
;
2725 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2726 RtlFreeUnicodeString(&mod
);
2730 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2731 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2734 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2737 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2738 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2742 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2747 delayinfo
.Size
= sizeof(delayinfo
);
2748 delayinfo
.DelayloadDescriptor
= desc
;
2749 delayinfo
.ThunkAddress
= addr
;
2750 delayinfo
.TargetDllName
= name
;
2751 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2752 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2753 delayinfo
.TargetModuleBase
= *phmod
;
2754 delayinfo
.Unused
= NULL
;
2755 delayinfo
.LastError
= nts
;
2756 return dllhook(4, &delayinfo
);
2759 /******************************************************************
2760 * LdrShutdownProcess (NTDLL.@)
2763 void WINAPI
LdrShutdownProcess(void)
2766 process_detaching
= TRUE
;
2771 /******************************************************************
2772 * RtlExitUserProcess (NTDLL.@)
2774 void WINAPI
RtlExitUserProcess( DWORD status
)
2776 RtlEnterCriticalSection( &loader_section
);
2777 RtlAcquirePebLock();
2778 NtTerminateProcess( 0, status
);
2779 LdrShutdownProcess();
2780 NtTerminateProcess( GetCurrentProcess(), status
);
2784 /******************************************************************
2785 * LdrShutdownThread (NTDLL.@)
2788 void WINAPI
LdrShutdownThread(void)
2790 PLIST_ENTRY mark
, entry
;
2797 /* don't do any detach calls if process is exiting */
2798 if (process_detaching
) return;
2800 RtlEnterCriticalSection( &loader_section
);
2802 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2803 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2805 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2806 InInitializationOrderModuleList
);
2807 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2809 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2812 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2813 DLL_THREAD_DETACH
, NULL
);
2816 RtlAcquirePebLock();
2817 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2818 RtlReleasePebLock();
2820 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2822 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2823 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2825 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2826 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2827 RtlLeaveCriticalSection( &loader_section
);
2831 /***********************************************************************
2835 static void free_modref( WINE_MODREF
*wm
)
2837 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2838 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2839 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2840 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2842 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2843 if (!TRACE_ON(module
))
2844 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2845 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2846 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2848 SERVER_START_REQ( unload_dll
)
2850 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2851 wine_server_call( req
);
2855 free_tls_slot( &wm
->ldr
);
2856 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2857 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2858 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2859 if (cached_modref
== wm
) cached_modref
= NULL
;
2860 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2861 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2862 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2865 /***********************************************************************
2866 * MODULE_FlushModrefs
2868 * Remove all unused modrefs and call the internal unloading routines
2869 * for the library type.
2871 * The loader_section must be locked while calling this function.
2873 static void MODULE_FlushModrefs(void)
2875 PLIST_ENTRY mark
, entry
, prev
;
2879 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2880 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2882 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2883 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2884 prev
= entry
->Blink
;
2885 if (!mod
->LoadCount
) free_modref( wm
);
2888 /* check load order list too for modules that haven't been initialized yet */
2889 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2890 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2892 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2893 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2894 prev
= entry
->Blink
;
2895 if (!mod
->LoadCount
) free_modref( wm
);
2899 /***********************************************************************
2900 * MODULE_DecRefCount
2902 * The loader_section must be locked while calling this function.
2904 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2908 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2911 if ( wm
->ldr
.LoadCount
<= 0 )
2914 --wm
->ldr
.LoadCount
;
2915 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2917 if ( wm
->ldr
.LoadCount
== 0 )
2919 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2921 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2923 MODULE_DecRefCount( wm
->deps
[i
] );
2925 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2929 /******************************************************************
2930 * LdrUnloadDll (NTDLL.@)
2934 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2937 NTSTATUS retv
= STATUS_SUCCESS
;
2939 if (process_detaching
) return retv
;
2941 TRACE("(%p)\n", hModule
);
2943 RtlEnterCriticalSection( &loader_section
);
2946 if ((wm
= get_modref( hModule
)) != NULL
)
2948 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2950 /* Recursively decrement reference counts */
2951 MODULE_DecRefCount( wm
);
2953 /* Call process detach notifications */
2954 if ( free_lib_count
<= 1 )
2957 MODULE_FlushModrefs();
2963 retv
= STATUS_DLL_NOT_FOUND
;
2967 RtlLeaveCriticalSection( &loader_section
);
2972 /***********************************************************************
2973 * RtlImageNtHeader (NTDLL.@)
2975 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2977 IMAGE_NT_HEADERS
*ret
;
2981 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2984 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2986 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2987 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2999 /***********************************************************************
3000 * attach_process_dlls
3002 * Initial attach to all the dlls loaded by the process.
3004 static NTSTATUS
attach_process_dlls( void *wm
)
3008 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
3010 RtlEnterCriticalSection( &loader_section
);
3011 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
3013 if (last_failed_modref
)
3014 ERR( "%s failed to initialize, aborting\n",
3015 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
3018 attach_implicitly_loaded_dlls( (LPVOID
)1 );
3019 RtlLeaveCriticalSection( &loader_section
);
3024 /***********************************************************************
3025 * load_global_options
3027 static void load_global_options(void)
3029 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
3030 'S','y','s','t','e','m','\\',
3031 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3032 'C','o','n','t','r','o','l','\\',
3033 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3034 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3035 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};
3036 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3037 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3038 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};
3039 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};
3041 OBJECT_ATTRIBUTES attr
;
3042 UNICODE_STRING name_str
;
3046 attr
.Length
= sizeof(attr
);
3047 attr
.RootDirectory
= 0;
3048 attr
.ObjectName
= &name_str
;
3049 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3050 attr
.SecurityDescriptor
= NULL
;
3051 attr
.SecurityQualityOfService
= NULL
;
3052 RtlInitUnicodeString( &name_str
, sessionW
);
3054 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3056 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3058 query_dword_option( hkey
, critsectW
, &value
);
3059 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3061 query_dword_option( hkey
, heapresW
, &value
);
3062 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3064 query_dword_option( hkey
, heapcommitW
, &value
);
3065 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3067 query_dword_option( hkey
, decommittotalW
, &value
);
3068 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3070 query_dword_option( hkey
, decommitfreeW
, &value
);
3071 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3077 /***********************************************************************
3080 static void start_process( void *arg
)
3082 struct start_params
*start_params
= (struct start_params
*)arg
;
3083 call_thread_entry_point( start_params
->kernel_start
, start_params
->entry
);
3086 /******************************************************************
3087 * LdrInitializeThunk (NTDLL.@)
3090 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3091 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3093 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3097 PEB
*peb
= NtCurrentTeb()->Peb
;
3098 struct start_params start_params
;
3100 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3102 /* allocate the modref for the main exe (if not already done) */
3103 wm
= get_modref( peb
->ImageBaseAddress
);
3105 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3107 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3111 peb
->LoaderLock
= &loader_section
;
3112 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3113 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3114 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3115 version_init( wm
->ldr
.FullDllName
.Buffer
);
3116 virtual_set_large_address_space();
3118 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3119 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3121 /* the main exe needs to be the first in the load order list */
3122 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3123 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3124 RemoveEntryList( &wm
->ldr
.InMemoryOrderModuleList
);
3125 InsertHeadList( &peb
->LdrData
->InMemoryOrderModuleList
, &wm
->ldr
.InMemoryOrderModuleList
);
3127 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
3128 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
3131 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3132 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
3133 heap_set_debug_flags( GetProcessHeap() );
3135 /* Store original entrypoint (in case it gets corrupted) */
3136 start_params
.kernel_start
= kernel_start
;
3137 start_params
.entry
= wm
->ldr
.EntryPoint
;
3139 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
3140 if (status
!= STATUS_SUCCESS
) goto error
;
3142 virtual_release_address_space();
3143 virtual_clear_thread_stack();
3144 wine_switch_to_stack( start_process
, &start_params
, NtCurrentTeb()->Tib
.StackBase
);
3147 ERR( "Main exe initialization for %s failed, status %x\n",
3148 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3149 NtTerminateProcess( GetCurrentProcess(), status
);
3153 /***********************************************************************
3154 * RtlImageDirectoryEntryToData (NTDLL.@)
3156 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3158 const IMAGE_NT_HEADERS
*nt
;
3161 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
3163 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
3166 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3167 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3169 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3171 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3172 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3173 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3174 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3176 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3178 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3180 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3181 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3182 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3183 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3187 /* not mapped as image, need to find the section containing the virtual address */
3188 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3192 /***********************************************************************
3193 * RtlImageRvaToSection (NTDLL.@)
3195 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3196 HMODULE module
, DWORD rva
)
3199 const IMAGE_SECTION_HEADER
*sec
;
3201 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3202 nt
->FileHeader
.SizeOfOptionalHeader
);
3203 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3205 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3206 return (PIMAGE_SECTION_HEADER
)sec
;
3212 /***********************************************************************
3213 * RtlImageRvaToVa (NTDLL.@)
3215 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3216 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3218 IMAGE_SECTION_HEADER
*sec
;
3220 if (section
&& *section
) /* try this section first */
3223 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3226 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3228 if (section
) *section
= sec
;
3229 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3233 /***********************************************************************
3234 * RtlPcToFileHeader (NTDLL.@)
3236 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3241 RtlEnterCriticalSection( &loader_section
);
3242 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3243 RtlLeaveCriticalSection( &loader_section
);
3249 /***********************************************************************
3250 * NtLoadDriver (NTDLL.@)
3251 * ZwLoadDriver (NTDLL.@)
3253 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3255 FIXME("(%p), stub!\n",DriverServiceName
);
3256 return STATUS_NOT_IMPLEMENTED
;
3260 /***********************************************************************
3261 * NtUnloadDriver (NTDLL.@)
3262 * ZwUnloadDriver (NTDLL.@)
3264 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3266 FIXME("(%p), stub!\n",DriverServiceName
);
3267 return STATUS_NOT_IMPLEMENTED
;
3271 /******************************************************************
3274 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3276 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3281 /******************************************************************
3282 * __wine_init_windows_dir (NTDLL.@)
3284 * Windows and system dir initialization once kernel32 has been loaded.
3286 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
3288 PLIST_ENTRY mark
, entry
;
3291 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
3292 DIR_init_windows_dir( windir
, sysdir
);
3294 /* prepend the system dir to the name of the already created modules */
3295 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3296 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3298 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
3300 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
3302 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
3303 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
3304 if (!buffer
) continue;
3305 strcpyW( buffer
, system_dir
.Buffer
);
3306 p
= buffer
+ strlenW( buffer
);
3307 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
3308 strcpyW( p
, mod
->FullDllName
.Buffer
);
3309 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
3310 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
3315 /***********************************************************************
3316 * __wine_process_init
3318 void __wine_process_init(void)
3320 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3324 ANSI_STRING func_name
;
3325 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3327 main_exe_file
= thread_init();
3329 /* retrieve current umask */
3330 FILE_umask
= umask(0777);
3331 umask( FILE_umask
);
3333 load_global_options();
3335 /* setup the load callback and create ntdll modref */
3336 wine_dll_set_callback( load_builtin_callback
);
3338 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3340 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3343 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3344 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3346 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3347 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3348 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3350 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);