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
);
66 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
67 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
69 static const char * const reason_names
[] =
75 NULL
, NULL
, NULL
, NULL
,
79 static const WCHAR dllW
[] = {'.','d','l','l',0};
81 /* internal representation of 32bit modules. per process. */
82 typedef struct _wine_modref
86 struct _wine_modref
**deps
;
89 /* info about the current builtin dll load */
90 /* used to keep track of things across the register_dll constructor call */
91 struct builtin_load_info
93 const WCHAR
*load_path
;
94 const WCHAR
*filename
;
99 static struct builtin_load_info default_load_info
;
100 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
102 static HANDLE main_exe_file
;
103 static UINT tls_module_count
; /* number of modules with TLS directory */
104 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
105 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
107 static RTL_CRITICAL_SECTION loader_section
;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
110 0, 0, &loader_section
,
111 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
112 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
114 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
116 static WINE_MODREF
*cached_modref
;
117 static WINE_MODREF
*current_modref
;
118 static WINE_MODREF
*last_failed_modref
;
120 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
121 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
122 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
123 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
124 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
125 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
127 /* convert PE image VirtualAddress to Real Address */
128 static inline void *get_rva( HMODULE module
, DWORD va
)
130 return (void *)((char *)module
+ va
);
133 /* check whether the file name contains a path */
134 static inline BOOL
contains_path( LPCWSTR name
)
136 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
139 /* convert from straight ASCII to Unicode without depending on the current codepage */
140 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
142 while (len
--) *dst
++ = (unsigned char)*src
++;
146 /*************************************************************************
147 * call_dll_entry_point
149 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
150 * their entry point, so we need a small asm wrapper. Testing indicates
151 * that only modifying esi leads to a crash, so use this one to backup
152 * ebp while running the dll entry proc.
155 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
156 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
158 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
159 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
161 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
163 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
165 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
167 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
169 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
173 "movl 8(%ebp),%eax\n\t"
176 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
177 "leal -12(%ebp),%esp\n\t"
179 __ASM_CFI(".cfi_same_value %edi\n\t")
181 __ASM_CFI(".cfi_same_value %esi\n\t")
183 __ASM_CFI(".cfi_same_value %ebx\n\t")
185 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
186 __ASM_CFI(".cfi_same_value %ebp\n\t")
189 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
190 UINT reason
, void *reserved
)
192 return proc( module
, reason
, reserved
);
194 #endif /* __i386__ */
197 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
198 /*************************************************************************
201 * Entry point for stub functions.
203 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
205 EXCEPTION_RECORD rec
;
207 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
208 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
209 rec
.ExceptionRecord
= NULL
;
210 rec
.ExceptionAddress
= ret_addr
;
211 rec
.NumberParameters
= 2;
212 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
213 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
214 for (;;) RtlRaiseException( &rec
);
218 #include "pshpack1.h"
222 BYTE pushl1
; /* pushl $name */
224 BYTE pushl2
; /* pushl $dll */
226 BYTE call
; /* call stub_entry_point */
229 #elif defined(__arm__)
232 BYTE ldr_r0
[4]; /* ldr r0, $dll */
233 BYTE mov_pc_pc1
[4]; /* mov pc,pc */
235 BYTE ldr_r1
[4]; /* ldr r1, $name */
236 BYTE mov_pc_pc2
[4]; /* mov pc,pc */
238 BYTE mov_r2_lr
[4]; /* mov r2, lr */
239 BYTE ldr_pc_pc
[4]; /* ldr pc, [pc, #-4] */
245 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
247 BYTE movq_rsi
[2]; /* movq $name,%rsi */
249 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
250 BYTE movq_rax
[2]; /* movq $entry, %rax */
252 BYTE jmpq_rax
[2]; /* jmp %rax */
257 /*************************************************************************
260 * Allocate a stub entry point.
262 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
264 #define MAX_SIZE 65536
265 static struct stub
*stubs
;
266 static unsigned int nb_stubs
;
269 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
273 SIZE_T size
= MAX_SIZE
;
274 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
275 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
278 stub
= &stubs
[nb_stubs
++];
280 stub
->pushl1
= 0x68; /* pushl $name */
282 stub
->pushl2
= 0x68; /* pushl $dll */
284 stub
->call
= 0xe8; /* call stub_entry_point */
285 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
286 #elif defined(__arm__)
287 stub
->ldr_r0
[0] = 0x00; /* ldr r0, $dll */
288 stub
->ldr_r0
[1] = 0x00;
289 stub
->ldr_r0
[2] = 0x9f;
290 stub
->ldr_r0
[3] = 0xe5;
291 stub
->mov_pc_pc1
[0] = 0x0f; /* mov pc,pc */
292 stub
->mov_pc_pc1
[1] = 0xf0;
293 stub
->mov_pc_pc1
[2] = 0xa0;
294 stub
->mov_pc_pc1
[3] = 0xe1;
296 stub
->ldr_r1
[0] = 0x00; /* ldr r1, $name */
297 stub
->ldr_r1
[1] = 0x10;
298 stub
->ldr_r1
[2] = 0x9f;
299 stub
->ldr_r1
[3] = 0xe5;
300 stub
->mov_pc_pc2
[0] = 0x0f; /* mov pc,pc */
301 stub
->mov_pc_pc2
[1] = 0xf0;
302 stub
->mov_pc_pc2
[2] = 0xa0;
303 stub
->mov_pc_pc2
[3] = 0xe1;
305 stub
->mov_r2_lr
[0] = 0x0e; /* mov r2, lr */
306 stub
->mov_r2_lr
[1] = 0x20;
307 stub
->mov_r2_lr
[2] = 0xa0;
308 stub
->mov_r2_lr
[3] = 0xe1;
309 stub
->ldr_pc_pc
[0] = 0x04; /* ldr pc, [pc, #-4] */
310 stub
->ldr_pc_pc
[1] = 0xf0;
311 stub
->ldr_pc_pc
[2] = 0x1f;
312 stub
->ldr_pc_pc
[3] = 0xe5;
313 stub
->entry
= stub_entry_point
;
315 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
316 stub
->movq_rdi
[1] = 0xbf;
318 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
319 stub
->movq_rsi
[1] = 0xbe;
321 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
322 stub
->movq_rsp_rdx
[1] = 0x8b;
323 stub
->movq_rsp_rdx
[2] = 0x14;
324 stub
->movq_rsp_rdx
[3] = 0x24;
325 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
326 stub
->movq_rax
[1] = 0xb8;
327 stub
->entry
= stub_entry_point
;
328 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
329 stub
->jmpq_rax
[1] = 0xe0;
331 return (ULONG_PTR
)stub
;
335 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
336 #endif /* __i386__ */
339 /*************************************************************************
342 * Looks for the referenced HMODULE in the current process
343 * The loader_section must be locked while calling this function.
345 static WINE_MODREF
*get_modref( HMODULE hmod
)
347 PLIST_ENTRY mark
, entry
;
350 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
352 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
353 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
355 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
356 if (mod
->BaseAddress
== hmod
)
357 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
363 /**********************************************************************
364 * find_basename_module
366 * Find a module from its base name.
367 * The loader_section must be locked while calling this function
369 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
371 PLIST_ENTRY mark
, entry
;
373 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
374 return cached_modref
;
376 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
377 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
379 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
380 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
382 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
383 return cached_modref
;
390 /**********************************************************************
391 * find_fullname_module
393 * Find a module from its full path name.
394 * The loader_section must be locked while calling this function
396 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
398 PLIST_ENTRY mark
, entry
;
400 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
401 return cached_modref
;
403 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
404 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
406 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
407 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
409 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
410 return cached_modref
;
417 /*************************************************************************
418 * find_forwarded_export
420 * Find the final function pointer for a forwarded function.
421 * The loader_section must be locked while calling this function.
423 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
425 const IMAGE_EXPORT_DIRECTORY
*exports
;
429 const char *end
= strrchr(forward
, '.');
432 if (!end
) return NULL
;
433 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
434 ascii_to_unicode( mod_name
, forward
, end
- forward
);
435 mod_name
[end
- forward
] = 0;
436 if (!strchrW( mod_name
, '.' ))
438 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
439 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
442 if (!(wm
= find_basename_module( mod_name
)))
444 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
445 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
446 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
448 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
450 LdrUnloadDll( wm
->ldr
.BaseAddress
);
457 ERR( "module not found for forward '%s' used by %s\n",
458 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
462 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
463 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
465 const char *name
= end
+ 1;
466 if (*name
== '#') /* ordinal */
467 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
469 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
474 ERR("function not found for forward '%s' used by %s."
475 " If you are using builtin %s, try using the native one instead.\n",
476 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
477 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
483 /*************************************************************************
484 * find_ordinal_export
486 * Find an exported function by ordinal.
487 * The exports base must have been subtracted from the ordinal already.
488 * The loader_section must be locked while calling this function.
490 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
491 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
494 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
496 if (ordinal
>= exports
->NumberOfFunctions
)
498 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
501 if (!functions
[ordinal
]) return NULL
;
503 proc
= get_rva( module
, functions
[ordinal
] );
505 /* if the address falls into the export dir, it's a forward */
506 if (((const char *)proc
>= (const char *)exports
) &&
507 ((const char *)proc
< (const char *)exports
+ exp_size
))
508 return find_forwarded_export( module
, (const char *)proc
, load_path
);
512 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
513 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
517 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
518 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
524 /*************************************************************************
527 * Find an exported function by name.
528 * The loader_section must be locked while calling this function.
530 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
531 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
533 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
534 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
535 int min
= 0, max
= exports
->NumberOfNames
- 1;
537 /* first check the hint */
538 if (hint
>= 0 && hint
<= max
)
540 char *ename
= get_rva( module
, names
[hint
] );
541 if (!strcmp( ename
, name
))
542 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
545 /* then do a binary search */
548 int res
, pos
= (min
+ max
) / 2;
549 char *ename
= get_rva( module
, names
[pos
] );
550 if (!(res
= strcmp( ename
, name
)))
551 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
552 if (res
> 0) max
= pos
- 1;
560 /*************************************************************************
563 * Import the dll specified by the given import descriptor.
564 * The loader_section must be locked while calling this function.
566 static BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
571 const IMAGE_EXPORT_DIRECTORY
*exports
;
573 const IMAGE_THUNK_DATA
*import_list
;
574 IMAGE_THUNK_DATA
*thunk_list
;
576 const char *name
= get_rva( module
, descr
->Name
);
577 DWORD len
= strlen(name
);
579 SIZE_T protect_size
= 0;
582 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
583 if (descr
->u
.OriginalFirstThunk
)
584 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
586 import_list
= thunk_list
;
588 if (!import_list
->u1
.Ordinal
)
590 WARN( "Skipping unused import %s\n", name
);
595 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
597 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
599 ascii_to_unicode( buffer
, name
, len
);
601 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
603 else /* need to allocate a larger buffer */
605 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
606 if (!ptr
) return FALSE
;
607 ascii_to_unicode( ptr
, name
, len
);
609 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
610 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
615 if (status
== STATUS_DLL_NOT_FOUND
)
616 ERR("Library %s (which is needed by %s) not found\n",
617 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
619 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
620 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
624 /* unprotect the import address table since it can be located in
625 * readonly section */
626 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
627 protect_base
= thunk_list
;
628 protect_size
*= sizeof(*thunk_list
);
629 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
630 &protect_size
, PAGE_READWRITE
, &protect_old
);
632 imp_mod
= wmImp
->ldr
.BaseAddress
;
633 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
637 /* set all imported function to deadbeef */
638 while (import_list
->u1
.Ordinal
)
640 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
642 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
643 WARN("No implementation for %s.%d", name
, ordinal
);
644 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
648 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
649 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
650 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
652 WARN(" imported from %s, allocating stub %p\n",
653 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
654 (void *)thunk_list
->u1
.Function
);
661 while (import_list
->u1
.Ordinal
)
663 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
665 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
667 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
668 ordinal
- exports
->Base
, load_path
);
669 if (!thunk_list
->u1
.Function
)
671 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
672 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
673 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
674 (void *)thunk_list
->u1
.Function
);
676 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
678 else /* import by name */
680 IMAGE_IMPORT_BY_NAME
*pe_name
;
681 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
682 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
683 (const char*)pe_name
->Name
,
684 pe_name
->Hint
, load_path
);
685 if (!thunk_list
->u1
.Function
)
687 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
688 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
689 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
690 (void *)thunk_list
->u1
.Function
);
692 TRACE_(imports
)("--- %s %s.%d = %p\n",
693 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
700 /* restore old protection of the import address table */
701 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
707 /***********************************************************************
708 * create_module_activation_context
710 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
713 LDR_RESOURCE_INFO info
;
714 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
716 info
.Type
= RT_MANIFEST
;
717 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
719 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
722 ctx
.cbSize
= sizeof(ctx
);
724 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
725 ctx
.hModule
= module
->BaseAddress
;
726 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
727 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
733 /*************************************************************************
734 * is_dll_native_subsystem
736 * Check if dll is a proper native driver.
737 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
738 * while being perfectly normal DLLs. This heuristic should catch such breakages.
740 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
742 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
743 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
744 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
748 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
749 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
751 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
752 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
754 for (i
= 0; imports
[i
].Name
; i
++)
756 const char *name
= get_rva( module
, imports
[i
].Name
);
757 DWORD len
= strlen(name
);
758 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
759 ascii_to_unicode( buffer
, name
, len
+ 1 );
760 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
762 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
770 /*************************************************************************
773 * Allocate a TLS slot for a newly-loaded module.
774 * The loader_section must be locked while calling this function.
776 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
778 const IMAGE_TLS_DIRECTORY
*dir
;
783 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
786 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
787 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
789 for (i
= 0; i
< tls_module_count
; i
++)
791 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
792 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
796 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
797 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
798 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
800 if (i
== tls_module_count
)
802 UINT new_count
= max( 32, tls_module_count
* 2 );
805 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
807 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
808 new_count
* sizeof(*tls_dirs
) );
809 if (!new_ptr
) return -1;
811 /* resize the pointer block in all running threads */
812 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
814 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
815 void **old
= teb
->ThreadLocalStoragePointer
;
816 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
819 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
820 teb
->ThreadLocalStoragePointer
= new;
821 #if defined(__APPLE__) && defined(__x86_64__)
822 if (teb
->Reserved5
[0])
823 ((TEB
*)teb
->Reserved5
[0])->ThreadLocalStoragePointer
= new;
825 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
826 /* FIXME: can't free old block here, should be freed at thread exit */
830 tls_module_count
= new_count
;
833 /* allocate the data block in all running threads */
834 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
836 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
838 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
839 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
840 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
842 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
843 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
845 RtlFreeHeap( GetProcessHeap(), 0,
846 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
849 *(DWORD
*)dir
->AddressOfIndex
= i
;
855 /*************************************************************************
858 * Free the module TLS slot on unload.
859 * The loader_section must be locked while calling this function.
861 static void free_tls_slot( LDR_MODULE
*mod
)
863 ULONG i
= (USHORT
)mod
->TlsIndex
;
865 if (mod
->TlsIndex
== -1) return;
866 assert( i
< tls_module_count
);
867 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
871 /****************************************************************
874 * Fixup all imports of a given module.
875 * The loader_section must be locked while calling this function.
877 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
880 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
886 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
887 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
889 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
891 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
892 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
893 return STATUS_SUCCESS
;
896 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
898 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
900 if (!create_module_activation_context( &wm
->ldr
))
901 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
903 /* Allocate module dependency list */
904 wm
->nDeps
= nb_imports
;
905 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
907 /* load the imported modules. They are automatically
908 * added to the modref list of the process.
910 prev
= current_modref
;
912 status
= STATUS_SUCCESS
;
913 for (i
= 0; i
< nb_imports
; i
++)
915 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &wm
->deps
[i
] ))
918 status
= STATUS_DLL_NOT_FOUND
;
921 current_modref
= prev
;
922 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
927 /*************************************************************************
930 * Allocate a WINE_MODREF structure and add it to the process list
931 * The loader_section must be locked while calling this function.
933 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
937 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
939 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
944 wm
->ldr
.BaseAddress
= hModule
;
945 wm
->ldr
.EntryPoint
= NULL
;
946 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
947 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
948 wm
->ldr
.TlsIndex
= -1;
949 wm
->ldr
.LoadCount
= 1;
950 wm
->ldr
.SectionHandle
= NULL
;
951 wm
->ldr
.CheckSum
= 0;
952 wm
->ldr
.TimeDateStamp
= 0;
953 wm
->ldr
.ActivationContext
= 0;
955 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
956 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
957 else p
= wm
->ldr
.FullDllName
.Buffer
;
958 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
960 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
962 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
963 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
964 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
965 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
968 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
969 &wm
->ldr
.InLoadOrderModuleList
);
970 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
,
971 &wm
->ldr
.InMemoryOrderModuleList
);
973 /* wait until init is called for inserting into this list */
974 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
975 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
977 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
979 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
980 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
981 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
987 /*************************************************************************
990 * Allocate the per-thread structure for module TLS storage.
992 static NTSTATUS
alloc_thread_tls(void)
997 if (!tls_module_count
) return STATUS_SUCCESS
;
999 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1000 tls_module_count
* sizeof(*pointers
) )))
1001 return STATUS_NO_MEMORY
;
1003 for (i
= 0; i
< tls_module_count
; i
++)
1005 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1008 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1009 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1011 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1013 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1014 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1015 return STATUS_NO_MEMORY
;
1017 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1018 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1020 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1021 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1023 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1024 #if defined(__APPLE__) && defined(__x86_64__)
1025 __asm__
volatile (".byte 0x65\n\tmovq %0,%c1"
1027 : "r" (pointers
), "n" (FIELD_OFFSET(TEB
, ThreadLocalStoragePointer
)));
1029 return STATUS_SUCCESS
;
1033 /*************************************************************************
1034 * call_tls_callbacks
1036 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1038 const IMAGE_TLS_DIRECTORY
*dir
;
1039 const PIMAGE_TLS_CALLBACK
*callback
;
1042 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1043 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1045 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1047 if (TRACE_ON(relay
))
1050 DPRINTF( "%04x:", GetCurrentProcessId() );
1051 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1052 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1056 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1060 if (TRACE_ON(relay
))
1063 DPRINTF( "%04x:", GetCurrentProcessId() );
1064 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1065 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
1070 if (TRACE_ON(relay
))
1073 DPRINTF( "%04x:", GetCurrentProcessId() );
1074 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1075 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1081 /*************************************************************************
1084 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1087 NTSTATUS status
= STATUS_SUCCESS
;
1088 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1089 void *module
= wm
->ldr
.BaseAddress
;
1092 /* Skip calls for modules loaded with special load flags */
1094 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1095 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1096 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1098 if (TRACE_ON(relay
))
1100 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1101 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1102 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1104 DPRINTF( "%04x:", GetCurrentProcessId() );
1105 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1106 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1107 reason_names
[reason
], lpReserved
);
1109 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1110 reason_names
[reason
], lpReserved
);
1114 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1116 status
= STATUS_DLL_INIT_FAILED
;
1120 if (TRACE_ON(relay
))
1123 DPRINTF( "%04x:", GetCurrentProcessId() );
1124 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1125 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
1127 status
= GetExceptionCode();
1131 /* The state of the module list may have changed due to the call
1132 to the dll. We cannot assume that this module has not been
1134 if (TRACE_ON(relay
))
1137 DPRINTF( "%04x:", GetCurrentProcessId() );
1138 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1139 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1140 reason_names
[reason
], lpReserved
, retv
);
1142 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1148 /*************************************************************************
1151 * Send the process attach notification to all DLLs the given module
1152 * depends on (recursively). This is somewhat complicated due to the fact that
1154 * - we have to respect the module dependencies, i.e. modules implicitly
1155 * referenced by another module have to be initialized before the module
1156 * itself can be initialized
1158 * - the initialization routine of a DLL can itself call LoadLibrary,
1159 * thereby introducing a whole new set of dependencies (even involving
1160 * the 'old' modules) at any time during the whole process
1162 * (Note that this routine can be recursively entered not only directly
1163 * from itself, but also via LoadLibrary from one of the called initialization
1166 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1167 * the process *detach* notifications to be sent in the correct order.
1168 * This must not only take into account module dependencies, but also
1169 * 'hidden' dependencies created by modules calling LoadLibrary in their
1170 * attach notification routine.
1172 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1173 * list after the attach notification has returned. This implies that the
1174 * detach notifications are called in the reverse of the sequence the attach
1175 * notifications *returned*.
1177 * The loader_section must be locked while calling this function.
1179 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1181 NTSTATUS status
= STATUS_SUCCESS
;
1185 if (process_detaching
) return status
;
1187 /* prevent infinite recursion in case of cyclical dependencies */
1188 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1189 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1192 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1194 /* Tag current MODREF to prevent recursive loop */
1195 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1196 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1197 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1199 /* Recursively attach all DLLs this one depends on */
1200 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1202 if (!wm
->deps
[i
]) continue;
1203 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1206 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1207 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1208 &wm
->ldr
.InInitializationOrderModuleList
);
1210 /* Call DLL entry point */
1211 if (status
== STATUS_SUCCESS
)
1213 WINE_MODREF
*prev
= current_modref
;
1214 current_modref
= wm
;
1215 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1216 if (status
== STATUS_SUCCESS
)
1217 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1220 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1221 /* point to the name so LdrInitializeThunk can print it */
1222 last_failed_modref
= wm
;
1223 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1225 current_modref
= prev
;
1228 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1229 /* Remove recursion flag */
1230 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1232 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1237 /**********************************************************************
1238 * attach_implicitly_loaded_dlls
1240 * Attach to the (builtin) dlls that have been implicitly loaded because
1241 * of a dependency at the Unix level, but not imported at the Win32 level.
1243 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1247 PLIST_ENTRY mark
, entry
;
1249 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1250 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1252 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1254 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1255 TRACE( "found implicitly loaded %s, attaching to it\n",
1256 debugstr_w(mod
->BaseDllName
.Buffer
));
1257 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1258 break; /* restart the search from the start */
1260 if (entry
== mark
) break; /* nothing found */
1265 /*************************************************************************
1268 * Send DLL process detach notifications. See the comment about calling
1269 * sequence at process_attach.
1271 static void process_detach(void)
1273 PLIST_ENTRY mark
, entry
;
1276 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1279 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1281 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1282 InInitializationOrderModuleList
);
1283 /* Check whether to detach this DLL */
1284 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1286 if ( mod
->LoadCount
&& !process_detaching
)
1289 /* Call detach notification */
1290 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1291 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1292 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1294 /* Restart at head of WINE_MODREF list, as entries might have
1295 been added and/or removed while performing the call ... */
1298 } while (entry
!= mark
);
1301 /*************************************************************************
1302 * MODULE_DllThreadAttach
1304 * Send DLL thread attach notifications. These are sent in the
1305 * reverse sequence of process detach notification.
1308 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1310 PLIST_ENTRY mark
, entry
;
1314 /* don't do any attach calls if process is exiting */
1315 if (process_detaching
) return STATUS_SUCCESS
;
1317 RtlEnterCriticalSection( &loader_section
);
1319 RtlAcquirePebLock();
1320 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
1321 RtlReleasePebLock();
1323 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1325 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1326 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1328 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1329 InInitializationOrderModuleList
);
1330 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1332 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1335 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1336 DLL_THREAD_ATTACH
, lpReserved
);
1340 RtlLeaveCriticalSection( &loader_section
);
1344 /******************************************************************
1345 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1348 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1351 NTSTATUS ret
= STATUS_SUCCESS
;
1353 RtlEnterCriticalSection( &loader_section
);
1355 wm
= get_modref( hModule
);
1356 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1357 ret
= STATUS_DLL_NOT_FOUND
;
1359 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1361 RtlLeaveCriticalSection( &loader_section
);
1366 /******************************************************************
1367 * LdrFindEntryForAddress (NTDLL.@)
1369 * The loader_section must be locked while calling this function
1371 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1373 PLIST_ENTRY mark
, entry
;
1376 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1377 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1379 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1380 if (mod
->BaseAddress
<= addr
&&
1381 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1384 return STATUS_SUCCESS
;
1387 return STATUS_NO_MORE_ENTRIES
;
1390 /******************************************************************
1391 * LdrLockLoaderLock (NTDLL.@)
1393 * Note: some flags are not implemented.
1394 * Flag 0x01 is used to raise exceptions on errors.
1396 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1398 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1400 if (result
) *result
= 0;
1401 if (magic
) *magic
= 0;
1402 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1403 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1404 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1408 if (!RtlTryEnterCriticalSection( &loader_section
))
1411 return STATUS_SUCCESS
;
1417 RtlEnterCriticalSection( &loader_section
);
1418 if (result
) *result
= 1;
1420 *magic
= GetCurrentThreadId();
1421 return STATUS_SUCCESS
;
1425 /******************************************************************
1426 * LdrUnlockLoaderUnlock (NTDLL.@)
1428 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1432 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1433 RtlLeaveCriticalSection( &loader_section
);
1435 return STATUS_SUCCESS
;
1439 /******************************************************************
1440 * LdrGetProcedureAddress (NTDLL.@)
1442 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1443 ULONG ord
, PVOID
*address
)
1445 IMAGE_EXPORT_DIRECTORY
*exports
;
1447 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1449 RtlEnterCriticalSection( &loader_section
);
1451 /* check if the module itself is invalid to return the proper error */
1452 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1453 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1454 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1456 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1457 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1458 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1462 ret
= STATUS_SUCCESS
;
1466 RtlLeaveCriticalSection( &loader_section
);
1471 /***********************************************************************
1474 * Check if a loaded native dll is a Wine fake dll.
1476 static BOOL
is_fake_dll( HANDLE handle
)
1478 static const char fakedll_signature
[] = "Wine placeholder DLL";
1479 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1480 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1482 LARGE_INTEGER offset
;
1484 offset
.QuadPart
= 0;
1485 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1486 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1487 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1488 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1489 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1494 /***********************************************************************
1495 * get_builtin_fullname
1497 * Build the full pathname for a builtin dll.
1499 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1501 static const WCHAR soW
[] = {'.','s','o',0};
1502 WCHAR
*p
, *fullname
;
1503 size_t i
, len
= strlen(filename
);
1505 /* check if path can correspond to the dll we have */
1506 if (path
&& (p
= strrchrW( path
, '\\' )))
1509 for (i
= 0; i
< len
; i
++)
1510 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1511 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1513 /* the filename matches, use path as the full path */
1515 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1517 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1524 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1525 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1527 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1528 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1529 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1530 ascii_to_unicode( p
, filename
, len
+ 1 );
1536 /*************************************************************************
1539 static BOOL
is_16bit_builtin( HMODULE module
)
1541 const IMAGE_EXPORT_DIRECTORY
*exports
;
1544 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1545 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1548 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1552 /***********************************************************************
1553 * load_builtin_callback
1555 * Load a library in memory; callback function for wine_dll_register
1557 static void load_builtin_callback( void *module
, const char *filename
)
1559 static const WCHAR emptyW
[1];
1560 IMAGE_NT_HEADERS
*nt
;
1563 const WCHAR
*load_path
;
1567 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1570 if (!(nt
= RtlImageNtHeader( module
)))
1572 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1573 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1577 virtual_create_builtin_view( module
);
1579 /* create the MODREF */
1581 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1583 ERR( "can't load %s\n", filename
);
1584 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1588 wm
= alloc_module( module
, fullname
);
1589 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1592 ERR( "can't load %s\n", filename
);
1593 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1596 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1598 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1599 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1600 is_16bit_builtin( module
))
1604 load_path
= builtin_load_info
->load_path
;
1605 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1606 if (!load_path
) load_path
= emptyW
;
1607 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1609 /* the module has only be inserted in the load & memory order lists */
1610 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1611 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1612 /* FIXME: free the modref */
1613 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1618 builtin_load_info
->wm
= wm
;
1619 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1621 /* send the DLL load event */
1623 SERVER_START_REQ( load_dll
)
1626 req
->base
= wine_server_client_ptr( module
);
1627 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1628 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1629 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1630 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1631 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1632 wine_server_call( req
);
1636 /* setup relay debugging entry points */
1637 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1641 /***********************************************************************
1642 * set_security_cookie
1644 * Create a random security cookie for buffer overflow protection. Make
1645 * sure it does not accidentally match the default cookie value.
1647 static void set_security_cookie( void *module
, SIZE_T len
)
1650 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1654 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1655 if (!loadcfg
) return;
1656 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1657 if (!loadcfg
->SecurityCookie
) return;
1658 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1659 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1661 WARN( "security cookie %p outside of image %p-%p\n",
1662 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1666 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1667 TRACE( "initializing security cookie %p\n", cookie
);
1669 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1672 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1673 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1674 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1675 *cookie
= RtlRandom( &seed
);
1676 #ifdef DEFAULT_SECURITY_COOKIE_64
1677 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1679 *cookie
= RtlRandom( &seed
);
1680 /* fill up, but keep the highest word clear */
1681 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1689 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1691 IMAGE_NT_HEADERS
*nt
;
1693 IMAGE_BASE_RELOCATION
*rel
, *end
;
1694 const IMAGE_DATA_DIRECTORY
*relocs
;
1695 const IMAGE_SECTION_HEADER
*sec
;
1697 ULONG protect_old
[96], i
;
1699 nt
= RtlImageNtHeader( module
);
1700 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1702 assert( module
!= base
);
1704 /* no relocations are performed on non page-aligned binaries */
1705 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1706 return STATUS_SUCCESS
;
1708 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1709 return STATUS_SUCCESS
;
1711 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1713 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1715 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1717 return STATUS_CONFLICTING_ADDRESSES
;
1720 if (!relocs
->Size
) return STATUS_SUCCESS
;
1721 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1723 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1724 return STATUS_INVALID_IMAGE_FORMAT
;
1726 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1727 nt
->FileHeader
.SizeOfOptionalHeader
);
1728 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1730 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1731 SIZE_T size
= sec
[i
].SizeOfRawData
;
1732 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1733 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1736 TRACE( "relocating from %p-%p to %p-%p\n",
1737 base
, base
+ len
, module
, (char *)module
+ len
);
1739 rel
= get_rva( module
, relocs
->VirtualAddress
);
1740 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1741 delta
= (char *)module
- base
;
1743 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1745 if (rel
->VirtualAddress
>= len
)
1747 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1748 return STATUS_ACCESS_VIOLATION
;
1750 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1751 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1752 (USHORT
*)(rel
+ 1), delta
);
1753 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1756 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1758 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1759 SIZE_T size
= sec
[i
].SizeOfRawData
;
1760 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1761 &size
, protect_old
[i
], &protect_old
[i
] );
1764 return STATUS_SUCCESS
;
1767 /******************************************************************************
1768 * load_native_dll (internal)
1770 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1771 DWORD flags
, WINE_MODREF
** pwm
)
1776 IMAGE_NT_HEADERS
*nt
;
1781 TRACE("Trying native dll %s\n", debugstr_w(name
));
1784 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1785 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1786 if (status
!= STATUS_SUCCESS
) return status
;
1789 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1790 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_EXECUTE_READ
);
1792 /* perform base relocation, if necessary */
1794 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1795 status
= perform_relocations( module
, len
);
1797 if (status
!= STATUS_SUCCESS
)
1799 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1803 /* create the MODREF */
1805 if (!(wm
= alloc_module( module
, name
)))
1807 status
= STATUS_NO_MEMORY
;
1811 set_security_cookie( module
, len
);
1815 nt
= RtlImageNtHeader( module
);
1817 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1818 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1819 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1821 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1823 /* the module has only be inserted in the load & memory order lists */
1824 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1825 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1827 /* FIXME: there are several more dangling references
1828 * left. Including dlls loaded by this dll before the
1829 * failed one. Unrolling is rather difficult with the
1830 * current structure and we can leave them lying
1831 * around with no problems, so we don't care.
1832 * As these might reference our wm, we don't free it.
1838 /* send DLL load event */
1840 SERVER_START_REQ( load_dll
)
1842 req
->mapping
= wine_server_obj_handle( mapping
);
1843 req
->base
= wine_server_client_ptr( module
);
1844 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1845 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1846 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1847 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1848 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1849 wine_server_call( req
);
1853 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1855 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1857 wm
->ldr
.LoadCount
= 1;
1859 status
= STATUS_SUCCESS
;
1866 /***********************************************************************
1869 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1870 DWORD flags
, WINE_MODREF
** pwm
)
1872 char error
[256], dllname
[MAX_PATH
];
1873 const WCHAR
*name
, *p
;
1876 struct builtin_load_info info
, *prev_info
;
1878 /* Fix the name in case we have a full path and extension */
1880 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1881 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1883 /* load_library will modify info.status. Note also that load_library can be
1884 * called several times, if the .so file we're loading has dependencies.
1885 * info.status will gather all the errors we may get while loading all these
1888 info
.load_path
= load_path
;
1889 info
.filename
= NULL
;
1890 info
.status
= STATUS_SUCCESS
;
1893 if (file
) /* we have a real file, try to load it */
1895 UNICODE_STRING nt_name
;
1896 ANSI_STRING unix_name
;
1898 TRACE("Trying built-in %s\n", debugstr_w(path
));
1900 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1901 return STATUS_DLL_NOT_FOUND
;
1903 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1905 RtlFreeUnicodeString( &nt_name
);
1906 return STATUS_DLL_NOT_FOUND
;
1908 prev_info
= builtin_load_info
;
1909 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1910 builtin_load_info
= &info
;
1911 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1912 builtin_load_info
= prev_info
;
1913 RtlFreeUnicodeString( &nt_name
);
1914 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1917 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1918 return STATUS_INVALID_IMAGE_FORMAT
;
1925 TRACE("Trying built-in %s\n", debugstr_w(name
));
1927 /* we don't want to depend on the current codepage here */
1928 len
= strlenW( name
) + 1;
1929 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1930 for (i
= 0; i
< len
; i
++)
1932 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1933 dllname
[i
] = (char)name
[i
];
1934 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1937 prev_info
= builtin_load_info
;
1938 builtin_load_info
= &info
;
1939 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1940 builtin_load_info
= prev_info
;
1945 /* The file does not exist -> WARN() */
1946 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1947 return STATUS_DLL_NOT_FOUND
;
1949 /* ERR() for all other errors (missing functions, ...) */
1950 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1951 return STATUS_PROCEDURE_NOT_FOUND
;
1955 if (info
.status
!= STATUS_SUCCESS
)
1957 wine_dll_unload( handle
);
1963 PLIST_ENTRY mark
, entry
;
1965 /* The constructor wasn't called, this means the .so is already
1966 * loaded under a different name. Try to find the wm for it. */
1968 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1969 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1971 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1972 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1974 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1975 TRACE( "Found %s at %p for builtin %s\n",
1976 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1980 wine_dll_unload( handle
); /* release the libdl refcount */
1981 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1982 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1986 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1987 info
.wm
->ldr
.LoadCount
= 1;
1988 info
.wm
->ldr
.SectionHandle
= handle
;
1992 return STATUS_SUCCESS
;
1996 /***********************************************************************
1999 * Find the full path (if any) of the dll from the activation context.
2001 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2003 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2004 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2006 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2007 ACTCTX_SECTION_KEYED_DATA data
;
2008 UNICODE_STRING nameW
;
2010 SIZE_T needed
, size
= 1024;
2013 RtlInitUnicodeString( &nameW
, libname
);
2014 data
.cbSize
= sizeof(data
);
2015 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2016 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2018 if (status
!= STATUS_SUCCESS
) return status
;
2022 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2024 status
= STATUS_NO_MEMORY
;
2027 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2028 AssemblyDetailedInformationInActivationContext
,
2029 info
, size
, &needed
);
2030 if (status
== STATUS_SUCCESS
) break;
2031 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2032 RtlFreeHeap( GetProcessHeap(), 0, info
);
2034 /* restart with larger buffer */
2037 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2039 status
= STATUS_SXS_KEY_NOT_FOUND
;
2043 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2045 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2048 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2050 /* manifest name does not match directory name, so it's not a global
2051 * windows/winsxs manifest; use the manifest directory name instead */
2052 dirlen
= p
- info
->lpAssemblyManifestPath
;
2053 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2054 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2056 status
= STATUS_NO_MEMORY
;
2059 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2061 strcpyW( p
, libname
);
2066 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2067 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2069 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2071 status
= STATUS_NO_MEMORY
;
2074 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2076 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2077 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2078 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2079 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2081 strcpyW( p
, libname
);
2083 RtlFreeHeap( GetProcessHeap(), 0, info
);
2084 RtlReleaseActivationContext( data
.hActCtx
);
2089 /***********************************************************************
2092 * Find the file (or already loaded module) for a given dll name.
2094 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2095 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
2097 OBJECT_ATTRIBUTES attr
;
2099 UNICODE_STRING nt_name
;
2100 WCHAR
*file_part
, *ext
, *dllname
;
2103 /* first append .dll if needed */
2106 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2108 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2109 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2110 return STATUS_NO_MEMORY
;
2111 strcpyW( dllname
, libname
);
2112 strcatW( dllname
, dllW
);
2116 nt_name
.Buffer
= NULL
;
2118 if (!contains_path( libname
))
2121 WCHAR
*fullname
= NULL
;
2123 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2125 status
= find_actctx_dll( libname
, &fullname
);
2126 if (status
== STATUS_SUCCESS
)
2128 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2129 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2130 libname
= dllname
= fullname
;
2132 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2134 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2139 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2141 /* we need to search for it */
2142 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2145 if (len
>= *size
) goto overflow
;
2146 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
2148 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2150 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2151 return STATUS_NO_MEMORY
;
2153 attr
.Length
= sizeof(attr
);
2154 attr
.RootDirectory
= 0;
2155 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2156 attr
.ObjectName
= &nt_name
;
2157 attr
.SecurityDescriptor
= NULL
;
2158 attr
.SecurityQualityOfService
= NULL
;
2159 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2165 if (!contains_path( libname
))
2167 /* if libname doesn't contain a path at all, we simply return the name as is,
2168 * to be loaded as builtin */
2169 len
= strlenW(libname
) * sizeof(WCHAR
);
2170 if (len
>= *size
) goto overflow
;
2171 strcpyW( filename
, libname
);
2176 /* absolute path name, or relative path name but not found above */
2178 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2180 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2181 return STATUS_NO_MEMORY
;
2183 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2184 if (len
>= *size
) goto overflow
;
2185 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2186 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
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;
2197 RtlFreeUnicodeString( &nt_name
);
2198 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2199 return STATUS_SUCCESS
;
2202 RtlFreeUnicodeString( &nt_name
);
2203 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2204 *size
= len
+ sizeof(WCHAR
);
2205 return STATUS_BUFFER_TOO_SMALL
;
2209 /***********************************************************************
2210 * load_dll (internal)
2212 * Load a PE style module according to the load order.
2213 * The loader_section must be locked while calling this function.
2215 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2217 enum loadorder loadorder
;
2221 WINE_MODREF
*main_exe
;
2225 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2229 size
= sizeof(buffer
);
2232 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2233 if (nts
== STATUS_SUCCESS
) break;
2234 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2235 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2236 /* grow the buffer and retry */
2237 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2240 if (*pwm
) /* found already loaded module */
2242 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2244 TRACE("Found %s for %s at %p, count=%d\n",
2245 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2246 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2247 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2248 return STATUS_SUCCESS
;
2251 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2252 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2254 if (handle
&& is_fake_dll( handle
))
2256 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2264 nts
= STATUS_NO_MEMORY
;
2267 nts
= STATUS_DLL_NOT_FOUND
;
2270 case LO_NATIVE_BUILTIN
:
2271 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2274 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2275 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2276 /* not in PE format, maybe it's a builtin */
2277 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2279 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2280 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2283 case LO_BUILTIN_NATIVE
:
2284 case LO_DEFAULT
: /* default is builtin,native */
2285 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2286 if (!handle
) break; /* nothing else we can try */
2287 /* file is not a builtin library, try without using the specified file */
2288 if (nts
!= STATUS_SUCCESS
)
2289 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2290 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2291 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2293 /* stub-only dll, try native */
2294 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2295 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2296 nts
= STATUS_DLL_NOT_FOUND
;
2298 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2299 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2303 if (nts
== STATUS_SUCCESS
)
2305 /* Initialize DLL just loaded */
2306 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2307 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2308 (*pwm
)->ldr
.BaseAddress
);
2309 if (handle
) NtClose( handle
);
2310 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2314 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2315 if (handle
) NtClose( handle
);
2316 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2320 /******************************************************************
2321 * LdrLoadDll (NTDLL.@)
2323 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2324 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2329 RtlEnterCriticalSection( &loader_section
);
2331 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2332 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2334 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2336 nts
= process_attach( wm
, NULL
);
2337 if (nts
!= STATUS_SUCCESS
)
2339 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2343 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2345 RtlLeaveCriticalSection( &loader_section
);
2350 /******************************************************************
2351 * LdrGetDllHandle (NTDLL.@)
2353 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2361 RtlEnterCriticalSection( &loader_section
);
2363 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2366 size
= sizeof(buffer
);
2369 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2370 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2371 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2372 /* grow the buffer and retry */
2373 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2375 status
= STATUS_NO_MEMORY
;
2380 if (status
== STATUS_SUCCESS
)
2382 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2383 else status
= STATUS_DLL_NOT_FOUND
;
2386 RtlLeaveCriticalSection( &loader_section
);
2387 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2392 /******************************************************************
2393 * LdrAddRefDll (NTDLL.@)
2395 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2397 NTSTATUS ret
= STATUS_SUCCESS
;
2400 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2402 RtlEnterCriticalSection( &loader_section
);
2404 if ((wm
= get_modref( module
)))
2406 if (flags
& LDR_ADDREF_DLL_PIN
)
2407 wm
->ldr
.LoadCount
= -1;
2409 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2410 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2412 else ret
= STATUS_INVALID_PARAMETER
;
2414 RtlLeaveCriticalSection( &loader_section
);
2419 /***********************************************************************
2420 * LdrProcessRelocationBlock (NTDLL.@)
2422 * Apply relocations to a given page of a mapped PE image.
2424 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2425 USHORT
*relocs
, INT_PTR delta
)
2429 USHORT offset
= *relocs
& 0xfff;
2430 int type
= *relocs
>> 12;
2433 case IMAGE_REL_BASED_ABSOLUTE
:
2435 case IMAGE_REL_BASED_HIGH
:
2436 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2438 case IMAGE_REL_BASED_LOW
:
2439 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2441 case IMAGE_REL_BASED_HIGHLOW
:
2442 *(int *)((char *)page
+ offset
) += delta
;
2445 case IMAGE_REL_BASED_DIR64
:
2446 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2448 #elif defined(__arm__)
2449 case IMAGE_REL_BASED_THUMB_MOV32
:
2451 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2452 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2453 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2456 if ((inst
& 0x8000fbf0) != 0x0000f240)
2457 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2459 imm16
+= LOWORD(delta
);
2460 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2461 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2462 ((imm16
>> 12) & 0x000f) +
2463 ((imm16
<< 20) & 0x70000000) +
2464 ((imm16
<< 16) & 0xff0000);
2468 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2469 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2470 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2472 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2473 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2477 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2478 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2479 ((imm16
>> 1) & 0x0400) +
2480 ((imm16
>> 12) & 0x000f) +
2481 ((imm16
<< 20) & 0x70000000) +
2482 ((imm16
<< 16) & 0xff0000);
2488 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2493 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2497 /******************************************************************
2498 * LdrQueryProcessModuleInformation
2501 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2502 ULONG buf_size
, ULONG
* req_size
)
2504 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2505 ULONG size
= sizeof(ULONG
);
2506 NTSTATUS nts
= STATUS_SUCCESS
;
2509 PLIST_ENTRY mark
, entry
;
2513 smi
->ModulesCount
= 0;
2515 RtlEnterCriticalSection( &loader_section
);
2516 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2517 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2519 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2520 size
+= sizeof(*sm
);
2521 if (size
<= buf_size
)
2523 sm
->Reserved1
= 0; /* FIXME */
2524 sm
->Reserved2
= 0; /* FIXME */
2525 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2526 sm
->ImageSize
= mod
->SizeOfImage
;
2527 sm
->Flags
= mod
->Flags
;
2529 sm
->Rank
= 0; /* FIXME */
2530 sm
->Unknown
= 0; /* FIXME */
2532 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2533 str
.Buffer
= (char*)sm
->Name
;
2534 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2535 ptr
= strrchr(str
.Buffer
, '\\');
2536 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2538 smi
->ModulesCount
++;
2541 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2543 RtlLeaveCriticalSection( &loader_section
);
2545 if (req_size
) *req_size
= size
;
2551 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2557 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2559 RtlInitUnicodeString( &str
, name
);
2561 size
= sizeof(buffer
) - sizeof(WCHAR
);
2562 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2565 if (info
->Type
!= REG_DWORD
)
2567 buffer
[size
/ sizeof(WCHAR
)] = 0;
2568 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2570 else memcpy( value
, info
->Data
, sizeof(*value
) );
2574 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2575 void *data
, ULONG in_size
, ULONG
*out_size
)
2581 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2582 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2584 RtlInitUnicodeString( &str
, name
);
2586 size
= info_size
+ in_size
;
2587 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2588 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2589 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2590 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2592 if (out_size
) *out_size
= info
->DataLength
;
2593 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2595 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2600 /******************************************************************
2601 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2603 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2604 void *data
, ULONG in_size
, ULONG
*out_size
)
2606 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2607 'S','o','f','t','w','a','r','e','\\',
2608 'M','i','c','r','o','s','o','f','t','\\',
2609 'W','i','n','d','o','w','s',' ','N','T','\\',
2610 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2611 'I','m','a','g','e',' ','F','i','l','e',' ',
2612 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2613 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2614 OBJECT_ATTRIBUTES attr
;
2615 UNICODE_STRING name_str
;
2621 attr
.Length
= sizeof(attr
);
2622 attr
.RootDirectory
= 0;
2623 attr
.ObjectName
= &name_str
;
2624 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2625 attr
.SecurityDescriptor
= NULL
;
2626 attr
.SecurityQualityOfService
= NULL
;
2628 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2629 else p
= key
->Buffer
;
2630 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2631 name_str
.Buffer
= path
;
2632 name_str
.Length
= sizeof(optionsW
) + len
;
2633 name_str
.MaximumLength
= name_str
.Length
;
2634 memcpy( path
, optionsW
, sizeof(optionsW
) );
2635 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2636 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2638 if (type
== REG_DWORD
)
2640 if (out_size
) *out_size
= sizeof(ULONG
);
2641 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2642 else status
= STATUS_BUFFER_OVERFLOW
;
2644 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2651 /******************************************************************
2652 * RtlDllShutdownInProgress (NTDLL.@)
2654 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2656 return process_detaching
;
2659 /****************************************************************************
2660 * LdrResolveDelayLoadedAPI (NTDLL.@)
2662 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2663 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2664 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2666 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2667 DELAYLOAD_INFO delayinfo
;
2675 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2677 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2678 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2679 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2680 name
= get_rva(base
, desc
->DllNameRVA
);
2685 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2687 nts
= STATUS_NO_MEMORY
;
2690 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2691 RtlFreeUnicodeString(&mod
);
2695 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2696 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2699 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2702 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2703 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2707 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2712 delayinfo
.Size
= sizeof(delayinfo
);
2713 delayinfo
.DelayloadDescriptor
= desc
;
2714 delayinfo
.ThunkAddress
= addr
;
2715 delayinfo
.TargetDllName
= name
;
2716 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2717 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2718 delayinfo
.TargetModuleBase
= *phmod
;
2719 delayinfo
.Unused
= NULL
;
2720 delayinfo
.LastError
= nts
;
2721 return dllhook(4, &delayinfo
);
2724 /******************************************************************
2725 * LdrShutdownProcess (NTDLL.@)
2728 void WINAPI
LdrShutdownProcess(void)
2731 process_detaching
= TRUE
;
2736 /******************************************************************
2737 * RtlExitUserProcess (NTDLL.@)
2739 void WINAPI
RtlExitUserProcess( DWORD status
)
2741 RtlEnterCriticalSection( &loader_section
);
2742 RtlAcquirePebLock();
2743 NtTerminateProcess( 0, status
);
2744 LdrShutdownProcess();
2745 NtTerminateProcess( GetCurrentProcess(), status
);
2749 /******************************************************************
2750 * LdrShutdownThread (NTDLL.@)
2753 void WINAPI
LdrShutdownThread(void)
2755 PLIST_ENTRY mark
, entry
;
2762 /* don't do any detach calls if process is exiting */
2763 if (process_detaching
) return;
2765 RtlEnterCriticalSection( &loader_section
);
2767 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2768 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2770 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2771 InInitializationOrderModuleList
);
2772 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2774 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2777 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2778 DLL_THREAD_DETACH
, NULL
);
2781 RtlAcquirePebLock();
2782 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2783 RtlReleasePebLock();
2785 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2787 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2788 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2790 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2791 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2792 RtlLeaveCriticalSection( &loader_section
);
2796 /***********************************************************************
2800 static void free_modref( WINE_MODREF
*wm
)
2802 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2803 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2804 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2805 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2807 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2808 if (!TRACE_ON(module
))
2809 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2810 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2811 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2813 SERVER_START_REQ( unload_dll
)
2815 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2816 wine_server_call( req
);
2820 free_tls_slot( &wm
->ldr
);
2821 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2822 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2823 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2824 if (cached_modref
== wm
) cached_modref
= NULL
;
2825 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2826 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2827 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2830 /***********************************************************************
2831 * MODULE_FlushModrefs
2833 * Remove all unused modrefs and call the internal unloading routines
2834 * for the library type.
2836 * The loader_section must be locked while calling this function.
2838 static void MODULE_FlushModrefs(void)
2840 PLIST_ENTRY mark
, entry
, prev
;
2844 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2845 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2847 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2848 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2849 prev
= entry
->Blink
;
2850 if (!mod
->LoadCount
) free_modref( wm
);
2853 /* check load order list too for modules that haven't been initialized yet */
2854 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2855 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2857 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2858 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2859 prev
= entry
->Blink
;
2860 if (!mod
->LoadCount
) free_modref( wm
);
2864 /***********************************************************************
2865 * MODULE_DecRefCount
2867 * The loader_section must be locked while calling this function.
2869 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2873 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2876 if ( wm
->ldr
.LoadCount
<= 0 )
2879 --wm
->ldr
.LoadCount
;
2880 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2882 if ( wm
->ldr
.LoadCount
== 0 )
2884 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2886 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2888 MODULE_DecRefCount( wm
->deps
[i
] );
2890 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2894 /******************************************************************
2895 * LdrUnloadDll (NTDLL.@)
2899 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2902 NTSTATUS retv
= STATUS_SUCCESS
;
2904 if (process_detaching
) return retv
;
2906 TRACE("(%p)\n", hModule
);
2908 RtlEnterCriticalSection( &loader_section
);
2911 if ((wm
= get_modref( hModule
)) != NULL
)
2913 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2915 /* Recursively decrement reference counts */
2916 MODULE_DecRefCount( wm
);
2918 /* Call process detach notifications */
2919 if ( free_lib_count
<= 1 )
2922 MODULE_FlushModrefs();
2928 retv
= STATUS_DLL_NOT_FOUND
;
2932 RtlLeaveCriticalSection( &loader_section
);
2937 /***********************************************************************
2938 * RtlImageNtHeader (NTDLL.@)
2940 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2942 IMAGE_NT_HEADERS
*ret
;
2946 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2949 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2951 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2952 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2964 /***********************************************************************
2965 * attach_process_dlls
2967 * Initial attach to all the dlls loaded by the process.
2969 static NTSTATUS
attach_process_dlls( void *wm
)
2973 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2975 RtlEnterCriticalSection( &loader_section
);
2976 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2978 if (last_failed_modref
)
2979 ERR( "%s failed to initialize, aborting\n",
2980 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2983 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2984 RtlLeaveCriticalSection( &loader_section
);
2989 /***********************************************************************
2990 * load_global_options
2992 static void load_global_options(void)
2994 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
2995 'S','y','s','t','e','m','\\',
2996 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2997 'C','o','n','t','r','o','l','\\',
2998 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2999 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3000 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};
3001 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3002 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3003 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};
3004 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};
3006 OBJECT_ATTRIBUTES attr
;
3007 UNICODE_STRING name_str
;
3011 attr
.Length
= sizeof(attr
);
3012 attr
.RootDirectory
= 0;
3013 attr
.ObjectName
= &name_str
;
3014 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3015 attr
.SecurityDescriptor
= NULL
;
3016 attr
.SecurityQualityOfService
= NULL
;
3017 RtlInitUnicodeString( &name_str
, sessionW
);
3019 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3021 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3023 query_dword_option( hkey
, critsectW
, &value
);
3024 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3026 query_dword_option( hkey
, heapresW
, &value
);
3027 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3029 query_dword_option( hkey
, heapcommitW
, &value
);
3030 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3032 query_dword_option( hkey
, decommittotalW
, &value
);
3033 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3035 query_dword_option( hkey
, decommitfreeW
, &value
);
3036 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3042 /***********************************************************************
3045 static void start_process( void *kernel_start
)
3047 call_thread_entry_point( kernel_start
, NtCurrentTeb()->Peb
);
3050 /******************************************************************
3051 * LdrInitializeThunk (NTDLL.@)
3054 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3055 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3057 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3061 PEB
*peb
= NtCurrentTeb()->Peb
;
3063 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3065 /* allocate the modref for the main exe (if not already done) */
3066 wm
= get_modref( peb
->ImageBaseAddress
);
3068 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3070 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3074 peb
->LoaderLock
= &loader_section
;
3075 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3076 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3077 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3078 version_init( wm
->ldr
.FullDllName
.Buffer
);
3079 virtual_set_large_address_space();
3081 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3082 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3084 /* the main exe needs to be the first in the load order list */
3085 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3086 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3087 RemoveEntryList( &wm
->ldr
.InMemoryOrderModuleList
);
3088 InsertHeadList( &peb
->LdrData
->InMemoryOrderModuleList
, &wm
->ldr
.InMemoryOrderModuleList
);
3090 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
3091 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
3094 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3095 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
3096 heap_set_debug_flags( GetProcessHeap() );
3098 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
3099 if (status
!= STATUS_SUCCESS
) goto error
;
3101 virtual_release_address_space();
3102 virtual_clear_thread_stack();
3103 wine_switch_to_stack( start_process
, kernel_start
, NtCurrentTeb()->Tib
.StackBase
);
3106 ERR( "Main exe initialization for %s failed, status %x\n",
3107 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3108 NtTerminateProcess( GetCurrentProcess(), status
);
3112 /***********************************************************************
3113 * RtlImageDirectoryEntryToData (NTDLL.@)
3115 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3117 const IMAGE_NT_HEADERS
*nt
;
3120 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
3122 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
3125 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3126 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3128 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3130 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3131 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3132 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3133 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3135 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3137 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3139 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3140 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3141 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3142 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3146 /* not mapped as image, need to find the section containing the virtual address */
3147 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3151 /***********************************************************************
3152 * RtlImageRvaToSection (NTDLL.@)
3154 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3155 HMODULE module
, DWORD rva
)
3158 const IMAGE_SECTION_HEADER
*sec
;
3160 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3161 nt
->FileHeader
.SizeOfOptionalHeader
);
3162 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3164 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3165 return (PIMAGE_SECTION_HEADER
)sec
;
3171 /***********************************************************************
3172 * RtlImageRvaToVa (NTDLL.@)
3174 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3175 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3177 IMAGE_SECTION_HEADER
*sec
;
3179 if (section
&& *section
) /* try this section first */
3182 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3185 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3187 if (section
) *section
= sec
;
3188 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3192 /***********************************************************************
3193 * RtlPcToFileHeader (NTDLL.@)
3195 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3200 RtlEnterCriticalSection( &loader_section
);
3201 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3202 RtlLeaveCriticalSection( &loader_section
);
3208 /***********************************************************************
3209 * NtLoadDriver (NTDLL.@)
3210 * ZwLoadDriver (NTDLL.@)
3212 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3214 FIXME("(%p), stub!\n",DriverServiceName
);
3215 return STATUS_NOT_IMPLEMENTED
;
3219 /***********************************************************************
3220 * NtUnloadDriver (NTDLL.@)
3221 * ZwUnloadDriver (NTDLL.@)
3223 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3225 FIXME("(%p), stub!\n",DriverServiceName
);
3226 return STATUS_NOT_IMPLEMENTED
;
3230 /******************************************************************
3233 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3235 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3240 /******************************************************************
3241 * __wine_init_windows_dir (NTDLL.@)
3243 * Windows and system dir initialization once kernel32 has been loaded.
3245 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
3247 PLIST_ENTRY mark
, entry
;
3250 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
3251 DIR_init_windows_dir( windir
, sysdir
);
3253 /* prepend the system dir to the name of the already created modules */
3254 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3255 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3257 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
3259 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
3261 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
3262 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
3263 if (!buffer
) continue;
3264 strcpyW( buffer
, system_dir
.Buffer
);
3265 p
= buffer
+ strlenW( buffer
);
3266 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
3267 strcpyW( p
, mod
->FullDllName
.Buffer
);
3268 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
3269 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
3274 /***********************************************************************
3275 * __wine_process_init
3277 void __wine_process_init(void)
3279 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3283 ANSI_STRING func_name
;
3284 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3286 main_exe_file
= thread_init();
3288 /* retrieve current umask */
3289 FILE_umask
= umask(0777);
3290 umask( FILE_umask
);
3292 load_global_options();
3294 /* setup the load callback and create ntdll modref */
3295 wine_dll_set_callback( load_builtin_callback
);
3297 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3299 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3302 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3303 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3305 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3306 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3307 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3309 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);