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>
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
35 #define WIN32_NO_STATUS
39 #include "delayloadhandler.h"
41 #include "wine/exception.h"
42 #include "wine/library.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45 #include "wine/server.h"
46 #include "ntdll_misc.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(module
);
50 WINE_DECLARE_DEBUG_CHANNEL(relay
);
51 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
52 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
53 WINE_DECLARE_DEBUG_CHANNEL(imports
);
55 /* we don't want to include winuser.h */
56 #define RT_MANIFEST ((ULONG_PTR)24)
57 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
59 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
61 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
62 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
64 static const char * const reason_names
[] =
70 NULL
, NULL
, NULL
, NULL
,
74 static const WCHAR dllW
[] = {'.','d','l','l',0};
76 /* internal representation of 32bit modules. per process. */
77 typedef struct _wine_modref
81 struct _wine_modref
**deps
;
84 /* info about the current builtin dll load */
85 /* used to keep track of things across the register_dll constructor call */
86 struct builtin_load_info
88 const WCHAR
*load_path
;
89 const WCHAR
*filename
;
94 static struct builtin_load_info default_load_info
;
95 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
97 static HANDLE main_exe_file
;
98 static UINT tls_module_count
; /* number of modules with TLS directory */
99 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
100 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
102 static RTL_CRITICAL_SECTION loader_section
;
103 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
105 0, 0, &loader_section
,
106 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
107 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
109 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
111 static WINE_MODREF
*cached_modref
;
112 static WINE_MODREF
*current_modref
;
113 static WINE_MODREF
*last_failed_modref
;
115 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
116 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
117 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
118 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
119 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
120 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
122 /* convert PE image VirtualAddress to Real Address */
123 static inline void *get_rva( HMODULE module
, DWORD va
)
125 return (void *)((char *)module
+ va
);
128 /* check whether the file name contains a path */
129 static inline BOOL
contains_path( LPCWSTR name
)
131 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
134 /* convert from straight ASCII to Unicode without depending on the current codepage */
135 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
137 while (len
--) *dst
++ = (unsigned char)*src
++;
141 /*************************************************************************
142 * call_dll_entry_point
144 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
145 * their entry point, so we need a small asm wrapper.
148 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
149 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
151 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
152 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
154 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
156 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
161 "movl 8(%ebp),%eax\n\t"
163 "leal -4(%ebp),%esp\n\t"
165 __ASM_CFI(".cfi_same_value %ebx\n\t")
167 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
168 __ASM_CFI(".cfi_same_value %ebp\n\t")
171 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
172 UINT reason
, void *reserved
)
174 return proc( module
, reason
, reserved
);
176 #endif /* __i386__ */
179 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
180 /*************************************************************************
183 * Entry point for stub functions.
185 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
187 EXCEPTION_RECORD rec
;
189 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
190 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
191 rec
.ExceptionRecord
= NULL
;
192 rec
.ExceptionAddress
= ret_addr
;
193 rec
.NumberParameters
= 2;
194 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
195 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
196 for (;;) RtlRaiseException( &rec
);
200 #include "pshpack1.h"
204 BYTE pushl1
; /* pushl $name */
206 BYTE pushl2
; /* pushl $dll */
208 BYTE call
; /* call stub_entry_point */
211 #elif defined(__arm__)
214 BYTE ldr_r0
[4]; /* ldr r0, $dll */
215 BYTE mov_pc_pc1
[4]; /* mov pc,pc */
217 BYTE ldr_r1
[4]; /* ldr r1, $name */
218 BYTE mov_pc_pc2
[4]; /* mov pc,pc */
220 BYTE mov_r2_lr
[4]; /* mov r2, lr */
221 BYTE ldr_pc_pc
[4]; /* ldr pc, [pc, #-4] */
227 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
229 BYTE movq_rsi
[2]; /* movq $name,%rsi */
231 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
232 BYTE movq_rax
[2]; /* movq $entry, %rax */
234 BYTE jmpq_rax
[2]; /* jmp %rax */
239 /*************************************************************************
242 * Allocate a stub entry point.
244 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
246 #define MAX_SIZE 65536
247 static struct stub
*stubs
;
248 static unsigned int nb_stubs
;
251 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
255 SIZE_T size
= MAX_SIZE
;
256 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
257 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
260 stub
= &stubs
[nb_stubs
++];
262 stub
->pushl1
= 0x68; /* pushl $name */
264 stub
->pushl2
= 0x68; /* pushl $dll */
266 stub
->call
= 0xe8; /* call stub_entry_point */
267 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
268 #elif defined(__arm__)
269 stub
->ldr_r0
[0] = 0x00; /* ldr r0, $dll */
270 stub
->ldr_r0
[1] = 0x00;
271 stub
->ldr_r0
[2] = 0x9f;
272 stub
->ldr_r0
[3] = 0xe5;
273 stub
->mov_pc_pc1
[0] = 0x0f; /* mov pc,pc */
274 stub
->mov_pc_pc1
[1] = 0xf0;
275 stub
->mov_pc_pc1
[2] = 0xa0;
276 stub
->mov_pc_pc1
[3] = 0xe1;
278 stub
->ldr_r1
[0] = 0x00; /* ldr r1, $name */
279 stub
->ldr_r1
[1] = 0x10;
280 stub
->ldr_r1
[2] = 0x9f;
281 stub
->ldr_r1
[3] = 0xe5;
282 stub
->mov_pc_pc2
[0] = 0x0f; /* mov pc,pc */
283 stub
->mov_pc_pc2
[1] = 0xf0;
284 stub
->mov_pc_pc2
[2] = 0xa0;
285 stub
->mov_pc_pc2
[3] = 0xe1;
287 stub
->mov_r2_lr
[0] = 0x0e; /* mov r2, lr */
288 stub
->mov_r2_lr
[1] = 0x20;
289 stub
->mov_r2_lr
[2] = 0xa0;
290 stub
->mov_r2_lr
[3] = 0xe1;
291 stub
->ldr_pc_pc
[0] = 0x04; /* ldr pc, [pc, #-4] */
292 stub
->ldr_pc_pc
[1] = 0xf0;
293 stub
->ldr_pc_pc
[2] = 0x1f;
294 stub
->ldr_pc_pc
[3] = 0xe5;
295 stub
->entry
= stub_entry_point
;
297 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
298 stub
->movq_rdi
[1] = 0xbf;
300 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
301 stub
->movq_rsi
[1] = 0xbe;
303 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
304 stub
->movq_rsp_rdx
[1] = 0x8b;
305 stub
->movq_rsp_rdx
[2] = 0x14;
306 stub
->movq_rsp_rdx
[3] = 0x24;
307 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
308 stub
->movq_rax
[1] = 0xb8;
309 stub
->entry
= stub_entry_point
;
310 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
311 stub
->jmpq_rax
[1] = 0xe0;
313 return (ULONG_PTR
)stub
;
317 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
318 #endif /* __i386__ */
321 /*************************************************************************
324 * Looks for the referenced HMODULE in the current process
325 * The loader_section must be locked while calling this function.
327 static WINE_MODREF
*get_modref( HMODULE hmod
)
329 PLIST_ENTRY mark
, entry
;
332 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
334 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
335 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
337 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
338 if (mod
->BaseAddress
== hmod
)
339 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
340 if (mod
->BaseAddress
> (void*)hmod
) break;
346 /**********************************************************************
347 * find_basename_module
349 * Find a module from its base name.
350 * The loader_section must be locked while calling this function
352 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
354 PLIST_ENTRY mark
, entry
;
356 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
357 return cached_modref
;
359 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
360 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
362 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
363 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
365 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
366 return cached_modref
;
373 /**********************************************************************
374 * find_fullname_module
376 * Find a module from its full path name.
377 * The loader_section must be locked while calling this function
379 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
381 PLIST_ENTRY mark
, entry
;
383 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
384 return cached_modref
;
386 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
387 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
389 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
390 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
392 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
393 return cached_modref
;
400 /*************************************************************************
401 * find_forwarded_export
403 * Find the final function pointer for a forwarded function.
404 * The loader_section must be locked while calling this function.
406 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
408 const IMAGE_EXPORT_DIRECTORY
*exports
;
412 const char *end
= strrchr(forward
, '.');
415 if (!end
) return NULL
;
416 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
417 ascii_to_unicode( mod_name
, forward
, end
- forward
);
418 mod_name
[end
- forward
] = 0;
419 if (!strchrW( mod_name
, '.' ))
421 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
422 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
425 if (!(wm
= find_basename_module( mod_name
)))
427 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
428 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
429 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
431 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
433 LdrUnloadDll( wm
->ldr
.BaseAddress
);
440 ERR( "module not found for forward '%s' used by %s\n",
441 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
445 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
446 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
448 const char *name
= end
+ 1;
449 if (*name
== '#') /* ordinal */
450 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
452 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
457 ERR("function not found for forward '%s' used by %s."
458 " If you are using builtin %s, try using the native one instead.\n",
459 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
460 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
466 /*************************************************************************
467 * find_ordinal_export
469 * Find an exported function by ordinal.
470 * The exports base must have been subtracted from the ordinal already.
471 * The loader_section must be locked while calling this function.
473 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
474 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
477 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
479 if (ordinal
>= exports
->NumberOfFunctions
)
481 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
484 if (!functions
[ordinal
]) return NULL
;
486 proc
= get_rva( module
, functions
[ordinal
] );
488 /* if the address falls into the export dir, it's a forward */
489 if (((const char *)proc
>= (const char *)exports
) &&
490 ((const char *)proc
< (const char *)exports
+ exp_size
))
491 return find_forwarded_export( module
, (const char *)proc
, load_path
);
495 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
496 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
500 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
501 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
507 /*************************************************************************
510 * Find an exported function by name.
511 * The loader_section must be locked while calling this function.
513 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
514 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
516 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
517 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
518 int min
= 0, max
= exports
->NumberOfNames
- 1;
520 /* first check the hint */
521 if (hint
>= 0 && hint
<= max
)
523 char *ename
= get_rva( module
, names
[hint
] );
524 if (!strcmp( ename
, name
))
525 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
528 /* then do a binary search */
531 int res
, pos
= (min
+ max
) / 2;
532 char *ename
= get_rva( module
, names
[pos
] );
533 if (!(res
= strcmp( ename
, name
)))
534 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
535 if (res
> 0) max
= pos
- 1;
543 /*************************************************************************
546 * Import the dll specified by the given import descriptor.
547 * The loader_section must be locked while calling this function.
549 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
554 const IMAGE_EXPORT_DIRECTORY
*exports
;
556 const IMAGE_THUNK_DATA
*import_list
;
557 IMAGE_THUNK_DATA
*thunk_list
;
559 const char *name
= get_rva( module
, descr
->Name
);
560 DWORD len
= strlen(name
);
562 SIZE_T protect_size
= 0;
565 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
566 if (descr
->u
.OriginalFirstThunk
)
567 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
569 import_list
= thunk_list
;
571 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
573 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
575 ascii_to_unicode( buffer
, name
, len
);
577 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
579 else /* need to allocate a larger buffer */
581 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
582 if (!ptr
) return NULL
;
583 ascii_to_unicode( ptr
, name
, len
);
585 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
586 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
591 if (status
== STATUS_DLL_NOT_FOUND
)
592 ERR("Library %s (which is needed by %s) not found\n",
593 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
595 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
596 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
600 /* unprotect the import address table since it can be located in
601 * readonly section */
602 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
603 protect_base
= thunk_list
;
604 protect_size
*= sizeof(*thunk_list
);
605 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
606 &protect_size
, PAGE_READWRITE
, &protect_old
);
608 imp_mod
= wmImp
->ldr
.BaseAddress
;
609 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
613 /* set all imported function to deadbeef */
614 while (import_list
->u1
.Ordinal
)
616 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
618 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
619 WARN("No implementation for %s.%d", name
, ordinal
);
620 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
624 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
625 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
626 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
628 WARN(" imported from %s, allocating stub %p\n",
629 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
630 (void *)thunk_list
->u1
.Function
);
637 while (import_list
->u1
.Ordinal
)
639 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
641 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
643 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
644 ordinal
- exports
->Base
, load_path
);
645 if (!thunk_list
->u1
.Function
)
647 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
648 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
649 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
650 (void *)thunk_list
->u1
.Function
);
652 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
654 else /* import by name */
656 IMAGE_IMPORT_BY_NAME
*pe_name
;
657 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
658 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
659 (const char*)pe_name
->Name
,
660 pe_name
->Hint
, load_path
);
661 if (!thunk_list
->u1
.Function
)
663 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
664 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
665 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
666 (void *)thunk_list
->u1
.Function
);
668 TRACE_(imports
)("--- %s %s.%d = %p\n",
669 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
676 /* restore old protection of the import address table */
677 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
682 /***********************************************************************
683 * create_module_activation_context
685 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
688 LDR_RESOURCE_INFO info
;
689 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
691 info
.Type
= RT_MANIFEST
;
692 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
694 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
697 ctx
.cbSize
= sizeof(ctx
);
699 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
700 ctx
.hModule
= module
->BaseAddress
;
701 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
702 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
708 /*************************************************************************
709 * is_dll_native_subsystem
711 * Check if dll is a proper native driver.
712 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
713 * while being perfectly normal DLLs. This heuristic should catch such breakages.
715 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
717 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
718 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
719 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
723 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
724 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
726 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
727 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
729 for (i
= 0; imports
[i
].Name
; i
++)
731 const char *name
= get_rva( module
, imports
[i
].Name
);
732 DWORD len
= strlen(name
);
733 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
734 ascii_to_unicode( buffer
, name
, len
+ 1 );
735 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
737 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
745 /*************************************************************************
748 * Allocate a TLS slot for a newly-loaded module.
749 * The loader_section must be locked while calling this function.
751 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
753 const IMAGE_TLS_DIRECTORY
*dir
;
758 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
761 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
762 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
764 for (i
= 0; i
< tls_module_count
; i
++) if (!tls_dirs
[i
]) break;
766 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
767 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
768 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
770 if (i
== tls_module_count
)
772 UINT new_count
= max( 32, tls_module_count
* 2 );
775 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
777 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
778 new_count
* sizeof(*tls_dirs
) );
779 if (!new_ptr
) return -1;
781 /* resize the pointer block in all running threads */
782 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
784 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
785 void **old
= teb
->ThreadLocalStoragePointer
;
786 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
789 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
790 teb
->ThreadLocalStoragePointer
= new;
791 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
792 /* FIXME: can't free old block here, should be freed at thread exit */
796 tls_module_count
= new_count
;
799 /* allocate the data block in all running threads */
800 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
802 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
804 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
805 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
806 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
808 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
809 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
811 RtlFreeHeap( GetProcessHeap(), 0,
812 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
815 *(DWORD
*)dir
->AddressOfIndex
= i
;
821 /*************************************************************************
824 * Free the module TLS slot on unload.
825 * The loader_section must be locked while calling this function.
827 static void free_tls_slot( LDR_MODULE
*mod
)
829 ULONG i
= (USHORT
)mod
->TlsIndex
;
831 if (mod
->TlsIndex
== -1) return;
832 assert( i
< tls_module_count
);
837 /****************************************************************
840 * Fixup all imports of a given module.
841 * The loader_section must be locked while calling this function.
843 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
846 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
852 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
853 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
855 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
857 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
858 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
859 return STATUS_SUCCESS
;
862 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
864 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
866 if (!create_module_activation_context( &wm
->ldr
))
867 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
869 /* Allocate module dependency list */
870 wm
->nDeps
= nb_imports
;
871 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
873 /* load the imported modules. They are automatically
874 * added to the modref list of the process.
876 prev
= current_modref
;
878 status
= STATUS_SUCCESS
;
879 for (i
= 0; i
< nb_imports
; i
++)
881 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
882 status
= STATUS_DLL_NOT_FOUND
;
884 current_modref
= prev
;
885 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
890 /*************************************************************************
893 * Allocate a WINE_MODREF structure and add it to the process list
894 * The loader_section must be locked while calling this function.
896 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
900 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
901 PLIST_ENTRY entry
, mark
;
903 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
908 wm
->ldr
.BaseAddress
= hModule
;
909 wm
->ldr
.EntryPoint
= NULL
;
910 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
911 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
912 wm
->ldr
.TlsIndex
= -1;
913 wm
->ldr
.LoadCount
= 1;
914 wm
->ldr
.SectionHandle
= NULL
;
915 wm
->ldr
.CheckSum
= 0;
916 wm
->ldr
.TimeDateStamp
= 0;
917 wm
->ldr
.ActivationContext
= 0;
919 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
920 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
921 else p
= wm
->ldr
.FullDllName
.Buffer
;
922 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
924 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && !is_dll_native_subsystem( hModule
, nt
, p
))
926 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
927 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
928 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
931 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
932 &wm
->ldr
.InLoadOrderModuleList
);
934 /* insert module in MemoryList, sorted in increasing base addresses */
935 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
936 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
938 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
941 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
942 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
943 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
944 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
946 /* wait until init is called for inserting into this list */
947 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
948 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
950 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
952 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
953 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
954 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
960 /*************************************************************************
963 * Allocate the per-thread structure for module TLS storage.
965 static NTSTATUS
alloc_thread_tls(void)
970 if (!tls_module_count
) return STATUS_SUCCESS
;
972 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
973 tls_module_count
* sizeof(*pointers
) )))
974 return STATUS_NO_MEMORY
;
976 for (i
= 0; i
< tls_module_count
; i
++)
978 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
981 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
982 if (!size
&& !dir
->SizeOfZeroFill
) continue;
984 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
986 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
987 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
988 return STATUS_NO_MEMORY
;
990 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
991 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
993 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
994 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
996 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
997 return STATUS_SUCCESS
;
1001 /*************************************************************************
1002 * call_tls_callbacks
1004 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1006 const IMAGE_TLS_DIRECTORY
*dir
;
1007 const PIMAGE_TLS_CALLBACK
*callback
;
1010 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1011 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1013 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1015 if (TRACE_ON(relay
))
1016 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1017 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1020 (*callback
)( module
, reason
, NULL
);
1024 if (TRACE_ON(relay
))
1025 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1026 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
1030 if (TRACE_ON(relay
))
1031 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1032 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1037 /*************************************************************************
1040 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1043 NTSTATUS status
= STATUS_SUCCESS
;
1044 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1045 void *module
= wm
->ldr
.BaseAddress
;
1048 /* Skip calls for modules loaded with special load flags */
1050 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1051 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1052 if (!entry
) return STATUS_SUCCESS
;
1054 if (TRACE_ON(relay
))
1056 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1057 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1058 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1059 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1060 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1061 reason_names
[reason
], lpReserved
);
1063 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1064 reason_names
[reason
], lpReserved
);
1068 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1070 status
= STATUS_DLL_INIT_FAILED
;
1074 if (TRACE_ON(relay
))
1075 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1076 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
1077 status
= GetExceptionCode();
1081 /* The state of the module list may have changed due to the call
1082 to the dll. We cannot assume that this module has not been
1084 if (TRACE_ON(relay
))
1085 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1086 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1087 reason_names
[reason
], lpReserved
, retv
);
1088 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1094 /*************************************************************************
1097 * Send the process attach notification to all DLLs the given module
1098 * depends on (recursively). This is somewhat complicated due to the fact that
1100 * - we have to respect the module dependencies, i.e. modules implicitly
1101 * referenced by another module have to be initialized before the module
1102 * itself can be initialized
1104 * - the initialization routine of a DLL can itself call LoadLibrary,
1105 * thereby introducing a whole new set of dependencies (even involving
1106 * the 'old' modules) at any time during the whole process
1108 * (Note that this routine can be recursively entered not only directly
1109 * from itself, but also via LoadLibrary from one of the called initialization
1112 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1113 * the process *detach* notifications to be sent in the correct order.
1114 * This must not only take into account module dependencies, but also
1115 * 'hidden' dependencies created by modules calling LoadLibrary in their
1116 * attach notification routine.
1118 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1119 * list after the attach notification has returned. This implies that the
1120 * detach notifications are called in the reverse of the sequence the attach
1121 * notifications *returned*.
1123 * The loader_section must be locked while calling this function.
1125 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1127 NTSTATUS status
= STATUS_SUCCESS
;
1131 if (process_detaching
) return status
;
1133 /* prevent infinite recursion in case of cyclical dependencies */
1134 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1135 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1138 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1140 /* Tag current MODREF to prevent recursive loop */
1141 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1142 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1143 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1145 /* Recursively attach all DLLs this one depends on */
1146 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1148 if (!wm
->deps
[i
]) continue;
1149 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1152 /* Call DLL entry point */
1153 if (status
== STATUS_SUCCESS
)
1155 WINE_MODREF
*prev
= current_modref
;
1156 current_modref
= wm
;
1157 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1158 if (status
== STATUS_SUCCESS
)
1159 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1162 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1163 /* point to the name so LdrInitializeThunk can print it */
1164 last_failed_modref
= wm
;
1165 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1167 current_modref
= prev
;
1170 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1171 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1172 &wm
->ldr
.InInitializationOrderModuleList
);
1174 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1175 /* Remove recursion flag */
1176 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1178 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1183 /**********************************************************************
1184 * attach_implicitly_loaded_dlls
1186 * Attach to the (builtin) dlls that have been implicitly loaded because
1187 * of a dependency at the Unix level, but not imported at the Win32 level.
1189 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1193 PLIST_ENTRY mark
, entry
;
1195 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1196 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1198 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1200 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1201 TRACE( "found implicitly loaded %s, attaching to it\n",
1202 debugstr_w(mod
->BaseDllName
.Buffer
));
1203 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1204 break; /* restart the search from the start */
1206 if (entry
== mark
) break; /* nothing found */
1211 /*************************************************************************
1214 * Send DLL process detach notifications. See the comment about calling
1215 * sequence at process_attach.
1217 static void process_detach(void)
1219 PLIST_ENTRY mark
, entry
;
1222 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1225 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1227 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1228 InInitializationOrderModuleList
);
1229 /* Check whether to detach this DLL */
1230 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1232 if ( mod
->LoadCount
&& !process_detaching
)
1235 /* Call detach notification */
1236 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1237 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1238 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1240 /* Restart at head of WINE_MODREF list, as entries might have
1241 been added and/or removed while performing the call ... */
1244 } while (entry
!= mark
);
1247 /*************************************************************************
1248 * MODULE_DllThreadAttach
1250 * Send DLL thread attach notifications. These are sent in the
1251 * reverse sequence of process detach notification.
1254 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1256 PLIST_ENTRY mark
, entry
;
1260 /* don't do any attach calls if process is exiting */
1261 if (process_detaching
) return STATUS_SUCCESS
;
1263 RtlEnterCriticalSection( &loader_section
);
1265 RtlAcquirePebLock();
1266 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
1267 RtlReleasePebLock();
1269 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1271 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1272 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1274 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1275 InInitializationOrderModuleList
);
1276 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1278 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1281 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1282 DLL_THREAD_ATTACH
, lpReserved
);
1286 RtlLeaveCriticalSection( &loader_section
);
1290 /******************************************************************
1291 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1294 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1297 NTSTATUS ret
= STATUS_SUCCESS
;
1299 RtlEnterCriticalSection( &loader_section
);
1301 wm
= get_modref( hModule
);
1302 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1303 ret
= STATUS_DLL_NOT_FOUND
;
1305 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1307 RtlLeaveCriticalSection( &loader_section
);
1312 /******************************************************************
1313 * LdrFindEntryForAddress (NTDLL.@)
1315 * The loader_section must be locked while calling this function
1317 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1319 PLIST_ENTRY mark
, entry
;
1322 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1323 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1325 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1326 if (mod
->BaseAddress
<= addr
&&
1327 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1330 return STATUS_SUCCESS
;
1332 if (mod
->BaseAddress
> addr
) break;
1334 return STATUS_NO_MORE_ENTRIES
;
1337 /******************************************************************
1338 * LdrLockLoaderLock (NTDLL.@)
1340 * Note: flags are not implemented.
1341 * Flag 0x01 is used to raise exceptions on errors.
1342 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1344 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1346 if (flags
) FIXME( "flags %x not supported\n", flags
);
1348 if (result
) *result
= 1;
1349 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1350 RtlEnterCriticalSection( &loader_section
);
1351 *magic
= GetCurrentThreadId();
1352 return STATUS_SUCCESS
;
1356 /******************************************************************
1357 * LdrUnlockLoaderUnlock (NTDLL.@)
1359 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1363 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1364 RtlLeaveCriticalSection( &loader_section
);
1366 return STATUS_SUCCESS
;
1370 /******************************************************************
1371 * LdrGetProcedureAddress (NTDLL.@)
1373 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1374 ULONG ord
, PVOID
*address
)
1376 IMAGE_EXPORT_DIRECTORY
*exports
;
1378 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1380 RtlEnterCriticalSection( &loader_section
);
1382 /* check if the module itself is invalid to return the proper error */
1383 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1384 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1385 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1387 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1388 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1389 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1393 ret
= STATUS_SUCCESS
;
1397 RtlLeaveCriticalSection( &loader_section
);
1402 /***********************************************************************
1405 * Check if a loaded native dll is a Wine fake dll.
1407 static BOOL
is_fake_dll( HANDLE handle
)
1409 static const char fakedll_signature
[] = "Wine placeholder DLL";
1410 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1411 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1413 LARGE_INTEGER offset
;
1415 offset
.QuadPart
= 0;
1416 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1417 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1418 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1419 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1420 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1425 /***********************************************************************
1426 * get_builtin_fullname
1428 * Build the full pathname for a builtin dll.
1430 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1432 static const WCHAR soW
[] = {'.','s','o',0};
1433 WCHAR
*p
, *fullname
;
1434 size_t i
, len
= strlen(filename
);
1436 /* check if path can correspond to the dll we have */
1437 if (path
&& (p
= strrchrW( path
, '\\' )))
1440 for (i
= 0; i
< len
; i
++)
1441 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1442 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1444 /* the filename matches, use path as the full path */
1446 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1448 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1455 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1456 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1458 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1459 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1460 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1461 ascii_to_unicode( p
, filename
, len
+ 1 );
1467 /*************************************************************************
1470 static BOOL
is_16bit_builtin( HMODULE module
)
1472 const IMAGE_EXPORT_DIRECTORY
*exports
;
1475 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1476 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1479 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1483 /***********************************************************************
1484 * load_builtin_callback
1486 * Load a library in memory; callback function for wine_dll_register
1488 static void load_builtin_callback( void *module
, const char *filename
)
1490 static const WCHAR emptyW
[1];
1491 IMAGE_NT_HEADERS
*nt
;
1494 const WCHAR
*load_path
;
1498 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1501 if (!(nt
= RtlImageNtHeader( module
)))
1503 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1504 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1508 virtual_create_builtin_view( module
);
1510 /* create the MODREF */
1512 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1514 ERR( "can't load %s\n", filename
);
1515 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1519 wm
= alloc_module( module
, fullname
);
1520 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1523 ERR( "can't load %s\n", filename
);
1524 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1527 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1529 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1530 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1531 is_16bit_builtin( module
))
1535 load_path
= builtin_load_info
->load_path
;
1536 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1537 if (!load_path
) load_path
= emptyW
;
1538 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1540 /* the module has only be inserted in the load & memory order lists */
1541 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1542 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1543 /* FIXME: free the modref */
1544 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1549 builtin_load_info
->wm
= wm
;
1550 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1552 /* send the DLL load event */
1554 SERVER_START_REQ( load_dll
)
1557 req
->base
= wine_server_client_ptr( module
);
1558 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1559 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1560 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1561 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1562 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1563 wine_server_call( req
);
1567 /* setup relay debugging entry points */
1568 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1572 /******************************************************************************
1573 * load_native_dll (internal)
1575 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1576 DWORD flags
, WINE_MODREF
** pwm
)
1581 IMAGE_NT_HEADERS
*nt
;
1586 TRACE("Trying native dll %s\n", debugstr_w(name
));
1589 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1590 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1591 if (status
!= STATUS_SUCCESS
) return status
;
1594 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1595 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_EXECUTE_READ
);
1596 if (status
< 0) goto done
;
1598 /* create the MODREF */
1600 if (!(wm
= alloc_module( module
, name
)))
1602 status
= STATUS_NO_MEMORY
;
1608 nt
= RtlImageNtHeader( module
);
1610 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1611 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1612 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1614 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1616 /* the module has only be inserted in the load & memory order lists */
1617 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1618 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1620 /* FIXME: there are several more dangling references
1621 * left. Including dlls loaded by this dll before the
1622 * failed one. Unrolling is rather difficult with the
1623 * current structure and we can leave them lying
1624 * around with no problems, so we don't care.
1625 * As these might reference our wm, we don't free it.
1631 /* send DLL load event */
1633 SERVER_START_REQ( load_dll
)
1635 req
->mapping
= wine_server_obj_handle( mapping
);
1636 req
->base
= wine_server_client_ptr( module
);
1637 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1638 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1639 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1640 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1641 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1642 wine_server_call( req
);
1646 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1648 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1650 wm
->ldr
.LoadCount
= 1;
1652 status
= STATUS_SUCCESS
;
1659 /***********************************************************************
1662 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1663 DWORD flags
, WINE_MODREF
** pwm
)
1665 char error
[256], dllname
[MAX_PATH
];
1666 const WCHAR
*name
, *p
;
1668 void *handle
= NULL
;
1669 struct builtin_load_info info
, *prev_info
;
1671 /* Fix the name in case we have a full path and extension */
1673 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1674 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1676 /* load_library will modify info.status. Note also that load_library can be
1677 * called several times, if the .so file we're loading has dependencies.
1678 * info.status will gather all the errors we may get while loading all these
1681 info
.load_path
= load_path
;
1682 info
.filename
= NULL
;
1683 info
.status
= STATUS_SUCCESS
;
1686 if (file
) /* we have a real file, try to load it */
1688 UNICODE_STRING nt_name
;
1689 ANSI_STRING unix_name
;
1691 TRACE("Trying built-in %s\n", debugstr_w(path
));
1693 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1694 return STATUS_DLL_NOT_FOUND
;
1696 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1698 RtlFreeUnicodeString( &nt_name
);
1699 return STATUS_DLL_NOT_FOUND
;
1701 prev_info
= builtin_load_info
;
1702 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1703 builtin_load_info
= &info
;
1704 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1705 builtin_load_info
= prev_info
;
1706 RtlFreeUnicodeString( &nt_name
);
1707 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1710 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1711 return STATUS_INVALID_IMAGE_FORMAT
;
1718 TRACE("Trying built-in %s\n", debugstr_w(name
));
1720 /* we don't want to depend on the current codepage here */
1721 len
= strlenW( name
) + 1;
1722 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1723 for (i
= 0; i
< len
; i
++)
1725 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1726 dllname
[i
] = (char)name
[i
];
1727 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1730 prev_info
= builtin_load_info
;
1731 builtin_load_info
= &info
;
1732 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1733 builtin_load_info
= prev_info
;
1738 /* The file does not exist -> WARN() */
1739 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1740 return STATUS_DLL_NOT_FOUND
;
1742 /* ERR() for all other errors (missing functions, ...) */
1743 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1744 return STATUS_PROCEDURE_NOT_FOUND
;
1748 if (info
.status
!= STATUS_SUCCESS
)
1750 wine_dll_unload( handle
);
1756 PLIST_ENTRY mark
, entry
;
1758 /* The constructor wasn't called, this means the .so is already
1759 * loaded under a different name. Try to find the wm for it. */
1761 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1762 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1764 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1765 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1767 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1768 TRACE( "Found %s at %p for builtin %s\n",
1769 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1773 wine_dll_unload( handle
); /* release the libdl refcount */
1774 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1775 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1779 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1780 info
.wm
->ldr
.LoadCount
= 1;
1781 info
.wm
->ldr
.SectionHandle
= handle
;
1785 return STATUS_SUCCESS
;
1789 /***********************************************************************
1792 * Find the full path (if any) of the dll from the activation context.
1794 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
1796 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
1797 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
1799 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
1800 ACTCTX_SECTION_KEYED_DATA data
;
1801 UNICODE_STRING nameW
;
1803 SIZE_T needed
, size
= 1024;
1806 RtlInitUnicodeString( &nameW
, libname
);
1807 data
.cbSize
= sizeof(data
);
1808 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
1809 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
1811 if (status
!= STATUS_SUCCESS
) return status
;
1815 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1817 status
= STATUS_NO_MEMORY
;
1820 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
1821 AssemblyDetailedInformationInActivationContext
,
1822 info
, size
, &needed
);
1823 if (status
== STATUS_SUCCESS
) break;
1824 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
1825 RtlFreeHeap( GetProcessHeap(), 0, info
);
1827 /* restart with larger buffer */
1830 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
1832 status
= STATUS_SXS_KEY_NOT_FOUND
;
1836 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
1838 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1841 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
1843 /* manifest name does not match directory name, so it's not a global
1844 * windows/winsxs manifest; use the manifest directory name instead */
1845 dirlen
= p
- info
->lpAssemblyManifestPath
;
1846 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
1847 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1849 status
= STATUS_NO_MEMORY
;
1852 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
1854 strcpyW( p
, libname
);
1859 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
1860 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
1862 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1864 status
= STATUS_NO_MEMORY
;
1867 strcpyW( p
, user_shared_data
->NtSystemRoot
);
1869 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
1870 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
1871 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
1872 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1874 strcpyW( p
, libname
);
1876 RtlFreeHeap( GetProcessHeap(), 0, info
);
1877 RtlReleaseActivationContext( data
.hActCtx
);
1882 /***********************************************************************
1885 * Find the file (or already loaded module) for a given dll name.
1887 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1888 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1890 OBJECT_ATTRIBUTES attr
;
1892 UNICODE_STRING nt_name
;
1893 WCHAR
*file_part
, *ext
, *dllname
;
1896 /* first append .dll if needed */
1899 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1901 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1902 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1903 return STATUS_NO_MEMORY
;
1904 strcpyW( dllname
, libname
);
1905 strcatW( dllname
, dllW
);
1909 nt_name
.Buffer
= NULL
;
1911 if (!contains_path( libname
))
1914 WCHAR
*fullname
= NULL
;
1916 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1918 status
= find_actctx_dll( libname
, &fullname
);
1919 if (status
== STATUS_SUCCESS
)
1921 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
1922 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1923 libname
= dllname
= fullname
;
1925 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
1927 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1932 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1934 /* we need to search for it */
1935 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1938 if (len
>= *size
) goto overflow
;
1939 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
1941 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1943 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1944 return STATUS_NO_MEMORY
;
1946 attr
.Length
= sizeof(attr
);
1947 attr
.RootDirectory
= 0;
1948 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1949 attr
.ObjectName
= &nt_name
;
1950 attr
.SecurityDescriptor
= NULL
;
1951 attr
.SecurityQualityOfService
= NULL
;
1952 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
1958 if (!contains_path( libname
))
1960 /* if libname doesn't contain a path at all, we simply return the name as is,
1961 * to be loaded as builtin */
1962 len
= strlenW(libname
) * sizeof(WCHAR
);
1963 if (len
>= *size
) goto overflow
;
1964 strcpyW( filename
, libname
);
1969 /* absolute path name, or relative path name but not found above */
1971 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1973 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1974 return STATUS_NO_MEMORY
;
1976 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1977 if (len
>= *size
) goto overflow
;
1978 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1979 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
1981 attr
.Length
= sizeof(attr
);
1982 attr
.RootDirectory
= 0;
1983 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1984 attr
.ObjectName
= &nt_name
;
1985 attr
.SecurityDescriptor
= NULL
;
1986 attr
.SecurityQualityOfService
= NULL
;
1987 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
1990 RtlFreeUnicodeString( &nt_name
);
1991 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1992 return STATUS_SUCCESS
;
1995 RtlFreeUnicodeString( &nt_name
);
1996 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1997 *size
= len
+ sizeof(WCHAR
);
1998 return STATUS_BUFFER_TOO_SMALL
;
2002 /***********************************************************************
2003 * load_dll (internal)
2005 * Load a PE style module according to the load order.
2006 * The loader_section must be locked while calling this function.
2008 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2010 enum loadorder loadorder
;
2014 WINE_MODREF
*main_exe
;
2018 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2022 size
= sizeof(buffer
);
2025 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2026 if (nts
== STATUS_SUCCESS
) break;
2027 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2028 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2029 /* grow the buffer and retry */
2030 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2033 if (*pwm
) /* found already loaded module */
2035 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2037 TRACE("Found %s for %s at %p, count=%d\n",
2038 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2039 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2040 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2041 return STATUS_SUCCESS
;
2044 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2045 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2047 if (handle
&& is_fake_dll( handle
))
2049 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2057 nts
= STATUS_NO_MEMORY
;
2060 nts
= STATUS_DLL_NOT_FOUND
;
2063 case LO_NATIVE_BUILTIN
:
2064 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2067 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2068 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2069 /* not in PE format, maybe it's a builtin */
2070 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2072 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2073 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2076 case LO_BUILTIN_NATIVE
:
2077 case LO_DEFAULT
: /* default is builtin,native */
2078 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2079 if (!handle
) break; /* nothing else we can try */
2080 /* file is not a builtin library, try without using the specified file */
2081 if (nts
!= STATUS_SUCCESS
)
2082 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2083 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2084 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2086 /* stub-only dll, try native */
2087 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2088 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2089 nts
= STATUS_DLL_NOT_FOUND
;
2091 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2092 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2096 if (nts
== STATUS_SUCCESS
)
2098 /* Initialize DLL just loaded */
2099 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2100 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2101 (*pwm
)->ldr
.BaseAddress
);
2102 if (handle
) NtClose( handle
);
2103 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2107 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2108 if (handle
) NtClose( handle
);
2109 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2113 /******************************************************************
2114 * LdrLoadDll (NTDLL.@)
2116 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2117 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2122 RtlEnterCriticalSection( &loader_section
);
2124 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2125 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2127 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2129 nts
= process_attach( wm
, NULL
);
2130 if (nts
!= STATUS_SUCCESS
)
2132 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2136 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2138 RtlLeaveCriticalSection( &loader_section
);
2143 /******************************************************************
2144 * LdrGetDllHandle (NTDLL.@)
2146 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2154 RtlEnterCriticalSection( &loader_section
);
2156 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2159 size
= sizeof(buffer
);
2162 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2163 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2164 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2165 /* grow the buffer and retry */
2166 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2168 status
= STATUS_NO_MEMORY
;
2173 if (status
== STATUS_SUCCESS
)
2175 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2176 else status
= STATUS_DLL_NOT_FOUND
;
2179 RtlLeaveCriticalSection( &loader_section
);
2180 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2185 /******************************************************************
2186 * LdrAddRefDll (NTDLL.@)
2188 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2190 NTSTATUS ret
= STATUS_SUCCESS
;
2193 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2195 RtlEnterCriticalSection( &loader_section
);
2197 if ((wm
= get_modref( module
)))
2199 if (flags
& LDR_ADDREF_DLL_PIN
)
2200 wm
->ldr
.LoadCount
= -1;
2202 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2203 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2205 else ret
= STATUS_INVALID_PARAMETER
;
2207 RtlLeaveCriticalSection( &loader_section
);
2212 /***********************************************************************
2213 * LdrProcessRelocationBlock (NTDLL.@)
2215 * Apply relocations to a given page of a mapped PE image.
2217 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2218 USHORT
*relocs
, INT_PTR delta
)
2222 USHORT offset
= *relocs
& 0xfff;
2223 int type
= *relocs
>> 12;
2226 case IMAGE_REL_BASED_ABSOLUTE
:
2228 case IMAGE_REL_BASED_HIGH
:
2229 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2231 case IMAGE_REL_BASED_LOW
:
2232 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2234 case IMAGE_REL_BASED_HIGHLOW
:
2235 *(int *)((char *)page
+ offset
) += delta
;
2238 case IMAGE_REL_BASED_DIR64
:
2239 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2241 #elif defined(__arm__)
2242 case IMAGE_REL_BASED_THUMB_MOV32
:
2244 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2245 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2246 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2249 if ((inst
& 0x8000fbf0) != 0x0000f240)
2250 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2252 imm16
+= LOWORD(delta
);
2253 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2254 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2255 ((imm16
>> 12) & 0x000f) +
2256 ((imm16
<< 20) & 0x70000000) +
2257 ((imm16
<< 16) & 0xff0000);
2261 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2262 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2263 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2265 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2266 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2270 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2271 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2272 ((imm16
>> 1) & 0x0400) +
2273 ((imm16
>> 12) & 0x000f) +
2274 ((imm16
<< 20) & 0x70000000) +
2275 ((imm16
<< 16) & 0xff0000);
2281 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2286 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2290 /******************************************************************
2291 * LdrQueryProcessModuleInformation
2294 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2295 ULONG buf_size
, ULONG
* req_size
)
2297 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2298 ULONG size
= sizeof(ULONG
);
2299 NTSTATUS nts
= STATUS_SUCCESS
;
2302 PLIST_ENTRY mark
, entry
;
2306 smi
->ModulesCount
= 0;
2308 RtlEnterCriticalSection( &loader_section
);
2309 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2310 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2312 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2313 size
+= sizeof(*sm
);
2314 if (size
<= buf_size
)
2316 sm
->Reserved1
= 0; /* FIXME */
2317 sm
->Reserved2
= 0; /* FIXME */
2318 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2319 sm
->ImageSize
= mod
->SizeOfImage
;
2320 sm
->Flags
= mod
->Flags
;
2322 sm
->Rank
= 0; /* FIXME */
2323 sm
->Unknown
= 0; /* FIXME */
2325 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2326 str
.Buffer
= (char*)sm
->Name
;
2327 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2328 ptr
= strrchr(str
.Buffer
, '\\');
2329 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2331 smi
->ModulesCount
++;
2334 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2336 RtlLeaveCriticalSection( &loader_section
);
2338 if (req_size
) *req_size
= size
;
2344 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2350 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2352 RtlInitUnicodeString( &str
, name
);
2354 size
= sizeof(buffer
) - sizeof(WCHAR
);
2355 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2358 if (info
->Type
!= REG_DWORD
)
2360 buffer
[size
/ sizeof(WCHAR
)] = 0;
2361 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2363 else memcpy( value
, info
->Data
, sizeof(*value
) );
2367 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2368 void *data
, ULONG in_size
, ULONG
*out_size
)
2374 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2375 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2377 RtlInitUnicodeString( &str
, name
);
2379 size
= info_size
+ in_size
;
2380 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2381 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2382 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2383 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2385 if (out_size
) *out_size
= info
->DataLength
;
2386 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2388 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2393 /******************************************************************
2394 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2396 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2397 void *data
, ULONG in_size
, ULONG
*out_size
)
2399 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2400 'S','o','f','t','w','a','r','e','\\',
2401 'M','i','c','r','o','s','o','f','t','\\',
2402 'W','i','n','d','o','w','s',' ','N','T','\\',
2403 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2404 'I','m','a','g','e',' ','F','i','l','e',' ',
2405 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2406 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2407 OBJECT_ATTRIBUTES attr
;
2408 UNICODE_STRING name_str
;
2414 attr
.Length
= sizeof(attr
);
2415 attr
.RootDirectory
= 0;
2416 attr
.ObjectName
= &name_str
;
2417 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2418 attr
.SecurityDescriptor
= NULL
;
2419 attr
.SecurityQualityOfService
= NULL
;
2421 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2422 else p
= key
->Buffer
;
2423 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2424 name_str
.Buffer
= path
;
2425 name_str
.Length
= sizeof(optionsW
) + len
;
2426 name_str
.MaximumLength
= name_str
.Length
;
2427 memcpy( path
, optionsW
, sizeof(optionsW
) );
2428 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2429 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2431 if (type
== REG_DWORD
)
2433 if (out_size
) *out_size
= sizeof(ULONG
);
2434 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2435 else status
= STATUS_BUFFER_OVERFLOW
;
2437 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2444 /******************************************************************
2445 * RtlDllShutdownInProgress (NTDLL.@)
2447 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2449 return process_detaching
;
2452 /****************************************************************************
2453 * LdrResolveDelayLoadedAPI (NTDLL.@)
2455 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2456 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2457 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2459 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2460 DELAYLOAD_INFO delayinfo
;
2468 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2470 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2471 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2472 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2473 name
= get_rva(base
, desc
->DllNameRVA
);
2478 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2480 nts
= STATUS_NO_MEMORY
;
2483 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2484 RtlFreeUnicodeString(&mod
);
2488 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2489 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2492 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2495 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2496 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2500 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2505 delayinfo
.Size
= sizeof(delayinfo
);
2506 delayinfo
.DelayloadDescriptor
= desc
;
2507 delayinfo
.ThunkAddress
= addr
;
2508 delayinfo
.TargetDllName
= name
;
2509 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2510 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2511 delayinfo
.TargetModuleBase
= *phmod
;
2512 delayinfo
.Unused
= NULL
;
2513 delayinfo
.LastError
= nts
;
2514 return dllhook(4, &delayinfo
);
2517 /******************************************************************
2518 * LdrShutdownProcess (NTDLL.@)
2521 void WINAPI
LdrShutdownProcess(void)
2524 process_detaching
= TRUE
;
2529 /******************************************************************
2530 * RtlExitUserProcess (NTDLL.@)
2532 void WINAPI
RtlExitUserProcess( DWORD status
)
2534 RtlEnterCriticalSection( &loader_section
);
2535 RtlAcquirePebLock();
2536 NtTerminateProcess( 0, status
);
2537 LdrShutdownProcess();
2538 NtTerminateProcess( GetCurrentProcess(), status
);
2542 /******************************************************************
2543 * LdrShutdownThread (NTDLL.@)
2546 void WINAPI
LdrShutdownThread(void)
2548 PLIST_ENTRY mark
, entry
;
2555 /* don't do any detach calls if process is exiting */
2556 if (process_detaching
) return;
2558 RtlEnterCriticalSection( &loader_section
);
2560 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2561 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2563 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2564 InInitializationOrderModuleList
);
2565 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2567 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2570 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2571 DLL_THREAD_DETACH
, NULL
);
2574 RtlAcquirePebLock();
2575 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2576 RtlReleasePebLock();
2578 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2580 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2581 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2583 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2584 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2585 RtlLeaveCriticalSection( &loader_section
);
2589 /***********************************************************************
2593 static void free_modref( WINE_MODREF
*wm
)
2595 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2596 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2597 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2598 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2600 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2601 if (!TRACE_ON(module
))
2602 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2603 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2604 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2606 SERVER_START_REQ( unload_dll
)
2608 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2609 wine_server_call( req
);
2613 free_tls_slot( &wm
->ldr
);
2614 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2615 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2616 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2617 if (cached_modref
== wm
) cached_modref
= NULL
;
2618 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2619 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2620 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2623 /***********************************************************************
2624 * MODULE_FlushModrefs
2626 * Remove all unused modrefs and call the internal unloading routines
2627 * for the library type.
2629 * The loader_section must be locked while calling this function.
2631 static void MODULE_FlushModrefs(void)
2633 PLIST_ENTRY mark
, entry
, prev
;
2637 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2638 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2640 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2641 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2642 prev
= entry
->Blink
;
2643 if (!mod
->LoadCount
) free_modref( wm
);
2646 /* check load order list too for modules that haven't been initialized yet */
2647 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2648 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2650 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2651 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2652 prev
= entry
->Blink
;
2653 if (!mod
->LoadCount
) free_modref( wm
);
2657 /***********************************************************************
2658 * MODULE_DecRefCount
2660 * The loader_section must be locked while calling this function.
2662 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2666 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2669 if ( wm
->ldr
.LoadCount
<= 0 )
2672 --wm
->ldr
.LoadCount
;
2673 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2675 if ( wm
->ldr
.LoadCount
== 0 )
2677 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2679 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2681 MODULE_DecRefCount( wm
->deps
[i
] );
2683 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2687 /******************************************************************
2688 * LdrUnloadDll (NTDLL.@)
2692 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2695 NTSTATUS retv
= STATUS_SUCCESS
;
2697 if (process_detaching
) return retv
;
2699 TRACE("(%p)\n", hModule
);
2701 RtlEnterCriticalSection( &loader_section
);
2704 if ((wm
= get_modref( hModule
)) != NULL
)
2706 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2708 /* Recursively decrement reference counts */
2709 MODULE_DecRefCount( wm
);
2711 /* Call process detach notifications */
2712 if ( free_lib_count
<= 1 )
2715 MODULE_FlushModrefs();
2721 retv
= STATUS_DLL_NOT_FOUND
;
2725 RtlLeaveCriticalSection( &loader_section
);
2730 /***********************************************************************
2731 * RtlImageNtHeader (NTDLL.@)
2733 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2735 IMAGE_NT_HEADERS
*ret
;
2739 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2742 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2744 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2745 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2757 /***********************************************************************
2758 * attach_process_dlls
2760 * Initial attach to all the dlls loaded by the process.
2762 static NTSTATUS
attach_process_dlls( void *wm
)
2766 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2768 RtlEnterCriticalSection( &loader_section
);
2769 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2771 if (last_failed_modref
)
2772 ERR( "%s failed to initialize, aborting\n",
2773 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2776 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2777 RtlLeaveCriticalSection( &loader_section
);
2782 /***********************************************************************
2783 * load_global_options
2785 static void load_global_options(void)
2787 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
2788 'S','y','s','t','e','m','\\',
2789 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2790 'C','o','n','t','r','o','l','\\',
2791 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2792 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2793 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};
2794 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2795 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2796 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};
2797 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};
2799 OBJECT_ATTRIBUTES attr
;
2800 UNICODE_STRING name_str
;
2804 attr
.Length
= sizeof(attr
);
2805 attr
.RootDirectory
= 0;
2806 attr
.ObjectName
= &name_str
;
2807 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2808 attr
.SecurityDescriptor
= NULL
;
2809 attr
.SecurityQualityOfService
= NULL
;
2810 RtlInitUnicodeString( &name_str
, sessionW
);
2812 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
2814 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
2816 query_dword_option( hkey
, critsectW
, &value
);
2817 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
2819 query_dword_option( hkey
, heapresW
, &value
);
2820 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
2822 query_dword_option( hkey
, heapcommitW
, &value
);
2823 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
2825 query_dword_option( hkey
, decommittotalW
, &value
);
2826 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
2828 query_dword_option( hkey
, decommitfreeW
, &value
);
2829 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
2835 /***********************************************************************
2838 static void start_process( void *kernel_start
)
2840 call_thread_entry_point( kernel_start
, NtCurrentTeb()->Peb
);
2843 /******************************************************************
2844 * LdrInitializeThunk (NTDLL.@)
2847 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
2848 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
2850 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2854 PEB
*peb
= NtCurrentTeb()->Peb
;
2856 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
2858 /* allocate the modref for the main exe (if not already done) */
2859 wm
= get_modref( peb
->ImageBaseAddress
);
2861 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
2863 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
2867 peb
->LoaderLock
= &loader_section
;
2868 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2869 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
2870 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
2871 version_init( wm
->ldr
.FullDllName
.Buffer
);
2872 virtual_set_large_address_space();
2874 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
2875 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
2877 /* the main exe needs to be the first in the load order list */
2878 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2879 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2881 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
2882 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
2885 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2886 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2887 heap_set_debug_flags( GetProcessHeap() );
2889 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
2890 if (status
!= STATUS_SUCCESS
) goto error
;
2892 virtual_release_address_space();
2893 virtual_clear_thread_stack();
2894 wine_switch_to_stack( start_process
, kernel_start
, NtCurrentTeb()->Tib
.StackBase
);
2897 ERR( "Main exe initialization for %s failed, status %x\n",
2898 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2899 NtTerminateProcess( GetCurrentProcess(), status
);
2903 /***********************************************************************
2904 * RtlImageDirectoryEntryToData (NTDLL.@)
2906 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2908 const IMAGE_NT_HEADERS
*nt
;
2911 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2913 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2916 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2917 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
2919 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
2921 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2922 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2923 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
2924 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2926 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
2928 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
2930 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2931 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2932 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
2933 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2937 /* not mapped as image, need to find the section containing the virtual address */
2938 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2942 /***********************************************************************
2943 * RtlImageRvaToSection (NTDLL.@)
2945 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2946 HMODULE module
, DWORD rva
)
2949 const IMAGE_SECTION_HEADER
*sec
;
2951 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2952 nt
->FileHeader
.SizeOfOptionalHeader
);
2953 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2955 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2956 return (PIMAGE_SECTION_HEADER
)sec
;
2962 /***********************************************************************
2963 * RtlImageRvaToVa (NTDLL.@)
2965 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2966 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2968 IMAGE_SECTION_HEADER
*sec
;
2970 if (section
&& *section
) /* try this section first */
2973 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2976 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2978 if (section
) *section
= sec
;
2979 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2983 /***********************************************************************
2984 * RtlPcToFileHeader (NTDLL.@)
2986 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
2991 RtlEnterCriticalSection( &loader_section
);
2992 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
2993 RtlLeaveCriticalSection( &loader_section
);
2999 /***********************************************************************
3000 * NtLoadDriver (NTDLL.@)
3001 * ZwLoadDriver (NTDLL.@)
3003 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3005 FIXME("(%p), stub!\n",DriverServiceName
);
3006 return STATUS_NOT_IMPLEMENTED
;
3010 /***********************************************************************
3011 * NtUnloadDriver (NTDLL.@)
3012 * ZwUnloadDriver (NTDLL.@)
3014 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3016 FIXME("(%p), stub!\n",DriverServiceName
);
3017 return STATUS_NOT_IMPLEMENTED
;
3021 /******************************************************************
3024 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3026 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3031 /******************************************************************
3032 * __wine_init_windows_dir (NTDLL.@)
3034 * Windows and system dir initialization once kernel32 has been loaded.
3036 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
3038 PLIST_ENTRY mark
, entry
;
3041 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
3042 DIR_init_windows_dir( windir
, sysdir
);
3044 /* prepend the system dir to the name of the already created modules */
3045 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3046 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3048 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
3050 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
3052 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
3053 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
3054 if (!buffer
) continue;
3055 strcpyW( buffer
, system_dir
.Buffer
);
3056 p
= buffer
+ strlenW( buffer
);
3057 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
3058 strcpyW( p
, mod
->FullDllName
.Buffer
);
3059 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
3060 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
3065 /***********************************************************************
3066 * __wine_process_init
3068 void __wine_process_init(void)
3070 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3074 ANSI_STRING func_name
;
3075 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3077 main_exe_file
= thread_init();
3079 /* retrieve current umask */
3080 FILE_umask
= umask(0777);
3081 umask( FILE_umask
);
3083 load_global_options();
3085 /* setup the load callback and create ntdll modref */
3086 wine_dll_set_callback( load_builtin_callback
);
3088 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3090 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3093 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3094 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3096 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3097 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3098 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3100 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);