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
40 #include "wine/exception.h"
41 #include "wine/library.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module
);
49 WINE_DECLARE_DEBUG_CHANNEL(relay
);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
52 WINE_DECLARE_DEBUG_CHANNEL(imports
);
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
60 static int process_detaching
= 0; /* set on process detach to avoid deadlocks with thread detach */
61 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
63 static const char * const reason_names
[] =
69 NULL
, NULL
, NULL
, NULL
,
73 static const WCHAR dllW
[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
80 struct _wine_modref
**deps
;
83 /* info about the current builtin dll load */
84 /* used to keep track of things across the register_dll constructor call */
85 struct builtin_load_info
87 const WCHAR
*load_path
;
88 const WCHAR
*filename
;
93 static struct builtin_load_info default_load_info
;
94 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
96 static HANDLE main_exe_file
;
97 static UINT tls_module_count
; /* number of modules with TLS directory */
98 static UINT tls_total_size
; /* total size of TLS storage */
99 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
100 #define TLS_ALIGNMENT (2 * sizeof(void *))
101 #define TLS_ALIGN(size) (((size) + TLS_ALIGNMENT - 1) & ~(TLS_ALIGNMENT - 1))
103 static RTL_CRITICAL_SECTION loader_section
;
104 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
106 0, 0, &loader_section
,
107 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
108 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
110 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
112 static WINE_MODREF
*cached_modref
;
113 static WINE_MODREF
*current_modref
;
114 static WINE_MODREF
*last_failed_modref
;
116 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
117 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
118 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
119 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
120 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
121 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
123 /* convert PE image VirtualAddress to Real Address */
124 static inline void *get_rva( HMODULE module
, DWORD va
)
126 return (void *)((char *)module
+ va
);
129 /* check whether the file name contains a path */
130 static inline int contains_path( LPCWSTR name
)
132 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
135 /* convert from straight ASCII to Unicode without depending on the current codepage */
136 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
138 while (len
--) *dst
++ = (unsigned char)*src
++;
142 /*************************************************************************
143 * call_dll_entry_point
145 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
146 * their entry point, so we need a small asm wrapper.
149 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
150 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
152 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
153 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
155 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
157 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
162 "movl 8(%ebp),%eax\n\t"
164 "leal -4(%ebp),%esp\n\t"
166 __ASM_CFI(".cfi_same_value %ebx\n\t")
168 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
169 __ASM_CFI(".cfi_same_value %ebp\n\t")
172 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
173 UINT reason
, void *reserved
)
175 return proc( module
, reason
, reserved
);
177 #endif /* __i386__ */
180 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
181 /*************************************************************************
184 * Entry point for stub functions.
186 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
188 EXCEPTION_RECORD rec
;
190 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
191 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
192 rec
.ExceptionRecord
= NULL
;
193 rec
.ExceptionAddress
= ret_addr
;
194 rec
.NumberParameters
= 2;
195 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
196 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
197 for (;;) RtlRaiseException( &rec
);
201 #include "pshpack1.h"
205 BYTE pushl1
; /* pushl $name */
207 BYTE pushl2
; /* pushl $dll */
209 BYTE call
; /* call stub_entry_point */
212 #elif defined(__arm__)
215 BYTE ldr_r0
[4]; /* ldr r0, $dll */
216 BYTE mov_pc_pc1
[4]; /* mov pc,pc */
218 BYTE ldr_r1
[4]; /* ldr r1, $name */
219 BYTE mov_pc_pc2
[4]; /* mov pc,pc */
221 BYTE mov_r2_lr
[4]; /* mov r2, lr */
222 BYTE ldr_pc_pc
[4]; /* ldr pc, [pc, #-4] */
228 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
230 BYTE movq_rsi
[2]; /* movq $name,%rsi */
232 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
233 BYTE movq_rax
[2]; /* movq $entry, %rax */
235 BYTE jmpq_rax
[2]; /* jmp %rax */
240 /*************************************************************************
243 * Allocate a stub entry point.
245 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
247 #define MAX_SIZE 65536
248 static struct stub
*stubs
;
249 static unsigned int nb_stubs
;
252 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
256 SIZE_T size
= MAX_SIZE
;
257 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
258 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
261 stub
= &stubs
[nb_stubs
++];
263 stub
->pushl1
= 0x68; /* pushl $name */
265 stub
->pushl2
= 0x68; /* pushl $dll */
267 stub
->call
= 0xe8; /* call stub_entry_point */
268 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
269 #elif defined(__arm__)
270 stub
->ldr_r0
[0] = 0x00; /* ldr r0, $dll */
271 stub
->ldr_r0
[1] = 0x00;
272 stub
->ldr_r0
[2] = 0x9f;
273 stub
->ldr_r0
[3] = 0xe5;
274 stub
->mov_pc_pc1
[0] = 0x0f; /* mov pc,pc */
275 stub
->mov_pc_pc1
[1] = 0xf0;
276 stub
->mov_pc_pc1
[2] = 0xa0;
277 stub
->mov_pc_pc1
[3] = 0xe1;
279 stub
->ldr_r1
[0] = 0x00; /* ldr r1, $name */
280 stub
->ldr_r1
[1] = 0x10;
281 stub
->ldr_r1
[2] = 0x9f;
282 stub
->ldr_r1
[3] = 0xe5;
283 stub
->mov_pc_pc2
[0] = 0x0f; /* mov pc,pc */
284 stub
->mov_pc_pc2
[1] = 0xf0;
285 stub
->mov_pc_pc2
[2] = 0xa0;
286 stub
->mov_pc_pc2
[3] = 0xe1;
288 stub
->mov_r2_lr
[0] = 0x0e; /* mov r2, lr */
289 stub
->mov_r2_lr
[1] = 0x20;
290 stub
->mov_r2_lr
[2] = 0xa0;
291 stub
->mov_r2_lr
[3] = 0xe1;
292 stub
->ldr_pc_pc
[0] = 0x04; /* ldr pc, [pc, #-4] */
293 stub
->ldr_pc_pc
[1] = 0xf0;
294 stub
->ldr_pc_pc
[2] = 0x1f;
295 stub
->ldr_pc_pc
[3] = 0xe5;
296 stub
->entry
= stub_entry_point
;
298 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
299 stub
->movq_rdi
[1] = 0xbf;
301 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
302 stub
->movq_rsi
[1] = 0xbe;
304 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
305 stub
->movq_rsp_rdx
[1] = 0x8b;
306 stub
->movq_rsp_rdx
[2] = 0x14;
307 stub
->movq_rsp_rdx
[3] = 0x24;
308 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
309 stub
->movq_rax
[1] = 0xb8;
310 stub
->entry
= stub_entry_point
;
311 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
312 stub
->jmpq_rax
[1] = 0xe0;
314 return (ULONG_PTR
)stub
;
318 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
319 #endif /* __i386__ */
322 /*************************************************************************
325 * Looks for the referenced HMODULE in the current process
326 * The loader_section must be locked while calling this function.
328 static WINE_MODREF
*get_modref( HMODULE hmod
)
330 PLIST_ENTRY mark
, entry
;
333 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
335 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
336 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
338 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
339 if (mod
->BaseAddress
== hmod
)
340 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
341 if (mod
->BaseAddress
> (void*)hmod
) break;
347 /**********************************************************************
348 * find_basename_module
350 * Find a module from its base name.
351 * The loader_section must be locked while calling this function
353 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
355 PLIST_ENTRY mark
, entry
;
357 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
358 return cached_modref
;
360 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
361 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
363 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
364 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
366 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
367 return cached_modref
;
374 /**********************************************************************
375 * find_fullname_module
377 * Find a module from its full path name.
378 * The loader_section must be locked while calling this function
380 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
382 PLIST_ENTRY mark
, entry
;
384 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
385 return cached_modref
;
387 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
388 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
390 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
391 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
393 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
394 return cached_modref
;
401 /*************************************************************************
402 * find_forwarded_export
404 * Find the final function pointer for a forwarded function.
405 * The loader_section must be locked while calling this function.
407 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
409 const IMAGE_EXPORT_DIRECTORY
*exports
;
413 const char *end
= strrchr(forward
, '.');
416 if (!end
) return NULL
;
417 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
418 ascii_to_unicode( mod_name
, forward
, end
- forward
);
419 mod_name
[end
- forward
] = 0;
420 if (!strchrW( mod_name
, '.' ))
422 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
423 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
426 if (!(wm
= find_basename_module( mod_name
)))
428 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
429 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
430 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
432 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
434 LdrUnloadDll( wm
->ldr
.BaseAddress
);
441 ERR( "module not found for forward '%s' used by %s\n",
442 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
446 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
447 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
449 const char *name
= end
+ 1;
450 if (*name
== '#') /* ordinal */
451 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
453 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
458 ERR("function not found for forward '%s' used by %s."
459 " If you are using builtin %s, try using the native one instead.\n",
460 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
461 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
467 /*************************************************************************
468 * find_ordinal_export
470 * Find an exported function by ordinal.
471 * The exports base must have been subtracted from the ordinal already.
472 * The loader_section must be locked while calling this function.
474 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
475 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
478 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
480 if (ordinal
>= exports
->NumberOfFunctions
)
482 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
485 if (!functions
[ordinal
]) return NULL
;
487 proc
= get_rva( module
, functions
[ordinal
] );
489 /* if the address falls into the export dir, it's a forward */
490 if (((const char *)proc
>= (const char *)exports
) &&
491 ((const char *)proc
< (const char *)exports
+ exp_size
))
492 return find_forwarded_export( module
, (const char *)proc
, load_path
);
496 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
497 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
501 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
502 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
508 /*************************************************************************
511 * Find an exported function by name.
512 * The loader_section must be locked while calling this function.
514 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
515 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
517 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
518 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
519 int min
= 0, max
= exports
->NumberOfNames
- 1;
521 /* first check the hint */
522 if (hint
>= 0 && hint
<= max
)
524 char *ename
= get_rva( module
, names
[hint
] );
525 if (!strcmp( ename
, name
))
526 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
529 /* then do a binary search */
532 int res
, pos
= (min
+ max
) / 2;
533 char *ename
= get_rva( module
, names
[pos
] );
534 if (!(res
= strcmp( ename
, name
)))
535 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
536 if (res
> 0) max
= pos
- 1;
544 /*************************************************************************
547 * Import the dll specified by the given import descriptor.
548 * The loader_section must be locked while calling this function.
550 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
555 const IMAGE_EXPORT_DIRECTORY
*exports
;
557 const IMAGE_THUNK_DATA
*import_list
;
558 IMAGE_THUNK_DATA
*thunk_list
;
560 const char *name
= get_rva( module
, descr
->Name
);
561 DWORD len
= strlen(name
);
563 SIZE_T protect_size
= 0;
566 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
567 if (descr
->u
.OriginalFirstThunk
)
568 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
570 import_list
= thunk_list
;
572 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
574 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
576 ascii_to_unicode( buffer
, name
, len
);
578 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
580 else /* need to allocate a larger buffer */
582 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
583 if (!ptr
) return NULL
;
584 ascii_to_unicode( ptr
, name
, len
);
586 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
587 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
592 if (status
== STATUS_DLL_NOT_FOUND
)
593 ERR("Library %s (which is needed by %s) not found\n",
594 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
596 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
597 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
601 /* unprotect the import address table since it can be located in
602 * readonly section */
603 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
604 protect_base
= thunk_list
;
605 protect_size
*= sizeof(*thunk_list
);
606 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
607 &protect_size
, PAGE_READWRITE
, &protect_old
);
609 imp_mod
= wmImp
->ldr
.BaseAddress
;
610 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
614 /* set all imported function to deadbeef */
615 while (import_list
->u1
.Ordinal
)
617 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
619 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
620 WARN("No implementation for %s.%d", name
, ordinal
);
621 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
625 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
626 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
627 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
629 WARN(" imported from %s, allocating stub %p\n",
630 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
631 (void *)thunk_list
->u1
.Function
);
638 while (import_list
->u1
.Ordinal
)
640 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
642 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
644 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
645 ordinal
- exports
->Base
, load_path
);
646 if (!thunk_list
->u1
.Function
)
648 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
649 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
650 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
651 (void *)thunk_list
->u1
.Function
);
653 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
655 else /* import by name */
657 IMAGE_IMPORT_BY_NAME
*pe_name
;
658 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
659 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
660 (const char*)pe_name
->Name
,
661 pe_name
->Hint
, load_path
);
662 if (!thunk_list
->u1
.Function
)
664 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
665 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
666 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
667 (void *)thunk_list
->u1
.Function
);
669 TRACE_(imports
)("--- %s %s.%d = %p\n",
670 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
677 /* restore old protection of the import address table */
678 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
683 /***********************************************************************
684 * create_module_activation_context
686 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
689 LDR_RESOURCE_INFO info
;
690 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
692 info
.Type
= RT_MANIFEST
;
693 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
695 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
698 ctx
.cbSize
= sizeof(ctx
);
700 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
701 ctx
.hModule
= module
->BaseAddress
;
702 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
703 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
709 /****************************************************************
712 * Fixup all imports of a given module.
713 * The loader_section must be locked while calling this function.
715 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
718 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
724 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
725 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
727 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
728 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
729 return STATUS_SUCCESS
;
732 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
734 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
736 if (!create_module_activation_context( &wm
->ldr
))
737 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
739 /* Allocate module dependency list */
740 wm
->nDeps
= nb_imports
;
741 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
743 /* load the imported modules. They are automatically
744 * added to the modref list of the process.
746 prev
= current_modref
;
748 status
= STATUS_SUCCESS
;
749 for (i
= 0; i
< nb_imports
; i
++)
751 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
752 status
= STATUS_DLL_NOT_FOUND
;
754 current_modref
= prev
;
755 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
760 /*************************************************************************
761 * is_dll_native_subsystem
763 * Check if dll is a proper native driver.
764 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
765 * while being perfectly normal DLLs. This heuristic should catch such breakages.
767 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
769 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
770 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
771 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
775 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
776 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
778 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
779 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
781 for (i
= 0; imports
[i
].Name
; i
++)
783 const char *name
= get_rva( module
, imports
[i
].Name
);
784 DWORD len
= strlen(name
);
785 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
786 ascii_to_unicode( buffer
, name
, len
+ 1 );
787 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
789 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
798 /*************************************************************************
801 * Allocate a WINE_MODREF structure and add it to the process list
802 * The loader_section must be locked while calling this function.
804 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
808 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
809 PLIST_ENTRY entry
, mark
;
811 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
816 wm
->ldr
.BaseAddress
= hModule
;
817 wm
->ldr
.EntryPoint
= NULL
;
818 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
819 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
820 wm
->ldr
.LoadCount
= 1;
821 wm
->ldr
.TlsIndex
= -1;
822 wm
->ldr
.SectionHandle
= NULL
;
823 wm
->ldr
.CheckSum
= 0;
824 wm
->ldr
.TimeDateStamp
= 0;
825 wm
->ldr
.ActivationContext
= 0;
827 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
828 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
829 else p
= wm
->ldr
.FullDllName
.Buffer
;
830 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
832 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && !is_dll_native_subsystem( hModule
, nt
, p
))
834 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
835 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
836 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
839 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
840 &wm
->ldr
.InLoadOrderModuleList
);
842 /* insert module in MemoryList, sorted in increasing base addresses */
843 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
844 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
846 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
849 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
850 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
851 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
852 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
854 /* wait until init is called for inserting into this list */
855 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
856 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
858 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
860 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
861 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
862 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
868 /*************************************************************************
871 * Allocate the process-wide structure for module TLS storage.
873 static NTSTATUS
alloc_process_tls(void)
875 PLIST_ENTRY mark
, entry
;
877 const IMAGE_TLS_DIRECTORY
*dir
;
880 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
881 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
883 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
884 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
885 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
887 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
888 if (!size
&& !dir
->AddressOfCallBacks
) continue;
889 tls_total_size
+= TLS_ALIGN(size
);
892 if (!tls_module_count
) return STATUS_SUCCESS
;
894 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
896 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
897 if (!tls_dirs
) return STATUS_NO_MEMORY
;
899 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
901 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
902 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
903 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
906 *(DWORD
*)dir
->AddressOfIndex
= i
;
908 mod
->LoadCount
= -1; /* can't unload it */
911 return STATUS_SUCCESS
;
915 /*************************************************************************
918 * Allocate the per-thread structure for module TLS storage.
920 static NTSTATUS
alloc_thread_tls(void)
926 if (!tls_module_count
) return STATUS_SUCCESS
;
928 size
= TLS_ALIGN( tls_module_count
* sizeof(*pointers
) );
929 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ tls_total_size
)))
930 return STATUS_NO_MEMORY
;
931 data
= (char *)pointers
+ size
;
933 for (i
= 0; i
< tls_module_count
; i
++)
935 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
936 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
938 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
939 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
940 (void *)dir
->StartAddressOfRawData
, data
);
943 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
944 memset( data
+ size
, 0, dir
->SizeOfZeroFill
);
945 data
+= TLS_ALIGN( size
+ dir
->SizeOfZeroFill
);
947 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
948 return STATUS_SUCCESS
;
952 /*************************************************************************
955 static void call_tls_callbacks( HMODULE module
, UINT reason
)
957 const IMAGE_TLS_DIRECTORY
*dir
;
958 const PIMAGE_TLS_CALLBACK
*callback
;
961 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
962 if (!dir
|| !dir
->AddressOfCallBacks
) return;
964 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
967 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
968 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
971 (*callback
)( module
, reason
, NULL
);
976 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
977 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
982 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
983 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
988 /*************************************************************************
991 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
994 NTSTATUS status
= STATUS_SUCCESS
;
995 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
996 void *module
= wm
->ldr
.BaseAddress
;
999 /* Skip calls for modules loaded with special load flags */
1001 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1002 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1003 if (!entry
) return STATUS_SUCCESS
;
1005 if (TRACE_ON(relay
))
1007 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1008 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1009 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1010 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1011 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1012 reason_names
[reason
], lpReserved
);
1014 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1015 reason_names
[reason
], lpReserved
);
1019 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1021 status
= STATUS_DLL_INIT_FAILED
;
1025 if (TRACE_ON(relay
))
1026 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1027 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
1028 status
= GetExceptionCode();
1032 /* The state of the module list may have changed due to the call
1033 to the dll. We cannot assume that this module has not been
1035 if (TRACE_ON(relay
))
1036 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1037 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1038 reason_names
[reason
], lpReserved
, retv
);
1039 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1045 /*************************************************************************
1048 * Send the process attach notification to all DLLs the given module
1049 * depends on (recursively). This is somewhat complicated due to the fact that
1051 * - we have to respect the module dependencies, i.e. modules implicitly
1052 * referenced by another module have to be initialized before the module
1053 * itself can be initialized
1055 * - the initialization routine of a DLL can itself call LoadLibrary,
1056 * thereby introducing a whole new set of dependencies (even involving
1057 * the 'old' modules) at any time during the whole process
1059 * (Note that this routine can be recursively entered not only directly
1060 * from itself, but also via LoadLibrary from one of the called initialization
1063 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1064 * the process *detach* notifications to be sent in the correct order.
1065 * This must not only take into account module dependencies, but also
1066 * 'hidden' dependencies created by modules calling LoadLibrary in their
1067 * attach notification routine.
1069 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1070 * list after the attach notification has returned. This implies that the
1071 * detach notifications are called in the reverse of the sequence the attach
1072 * notifications *returned*.
1074 * The loader_section must be locked while calling this function.
1076 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1078 NTSTATUS status
= STATUS_SUCCESS
;
1082 if (process_detaching
) return status
;
1084 /* prevent infinite recursion in case of cyclical dependencies */
1085 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1086 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1089 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1091 /* Tag current MODREF to prevent recursive loop */
1092 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1093 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1094 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1096 /* Recursively attach all DLLs this one depends on */
1097 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1099 if (!wm
->deps
[i
]) continue;
1100 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1103 /* Call DLL entry point */
1104 if (status
== STATUS_SUCCESS
)
1106 WINE_MODREF
*prev
= current_modref
;
1107 current_modref
= wm
;
1108 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1109 if (status
== STATUS_SUCCESS
)
1110 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1113 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1114 /* point to the name so LdrInitializeThunk can print it */
1115 last_failed_modref
= wm
;
1116 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1118 current_modref
= prev
;
1121 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1122 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1123 &wm
->ldr
.InInitializationOrderModuleList
);
1125 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1126 /* Remove recursion flag */
1127 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1129 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1134 /**********************************************************************
1135 * attach_implicitly_loaded_dlls
1137 * Attach to the (builtin) dlls that have been implicitly loaded because
1138 * of a dependency at the Unix level, but not imported at the Win32 level.
1140 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1144 PLIST_ENTRY mark
, entry
;
1146 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1147 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1149 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1151 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1152 TRACE( "found implicitly loaded %s, attaching to it\n",
1153 debugstr_w(mod
->BaseDllName
.Buffer
));
1154 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1155 break; /* restart the search from the start */
1157 if (entry
== mark
) break; /* nothing found */
1162 /*************************************************************************
1165 * Send DLL process detach notifications. See the comment about calling
1166 * sequence at process_attach. Unless the bForceDetach flag
1167 * is set, only DLLs with zero refcount are notified.
1169 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
1171 PLIST_ENTRY mark
, entry
;
1174 RtlEnterCriticalSection( &loader_section
);
1175 if (bForceDetach
) process_detaching
= 1;
1176 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1179 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1181 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1182 InInitializationOrderModuleList
);
1183 /* Check whether to detach this DLL */
1184 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1186 if ( mod
->LoadCount
&& !bForceDetach
)
1189 /* Call detach notification */
1190 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1191 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1192 DLL_PROCESS_DETACH
, lpReserved
);
1194 /* Restart at head of WINE_MODREF list, as entries might have
1195 been added and/or removed while performing the call ... */
1198 } while (entry
!= mark
);
1200 RtlLeaveCriticalSection( &loader_section
);
1203 /*************************************************************************
1204 * MODULE_DllThreadAttach
1206 * Send DLL thread attach notifications. These are sent in the
1207 * reverse sequence of process detach notification.
1210 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1212 PLIST_ENTRY mark
, entry
;
1216 /* don't do any attach calls if process is exiting */
1217 if (process_detaching
) return STATUS_SUCCESS
;
1218 /* FIXME: there is still a race here */
1220 RtlEnterCriticalSection( &loader_section
);
1222 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1224 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1225 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1227 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1228 InInitializationOrderModuleList
);
1229 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1231 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1234 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1235 DLL_THREAD_ATTACH
, lpReserved
);
1239 RtlLeaveCriticalSection( &loader_section
);
1243 /******************************************************************
1244 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1247 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1250 NTSTATUS ret
= STATUS_SUCCESS
;
1252 RtlEnterCriticalSection( &loader_section
);
1254 wm
= get_modref( hModule
);
1255 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1256 ret
= STATUS_DLL_NOT_FOUND
;
1258 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1260 RtlLeaveCriticalSection( &loader_section
);
1265 /******************************************************************
1266 * LdrFindEntryForAddress (NTDLL.@)
1268 * The loader_section must be locked while calling this function
1270 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1272 PLIST_ENTRY mark
, entry
;
1275 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1276 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1278 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1279 if (mod
->BaseAddress
<= addr
&&
1280 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1283 return STATUS_SUCCESS
;
1285 if (mod
->BaseAddress
> addr
) break;
1287 return STATUS_NO_MORE_ENTRIES
;
1290 /******************************************************************
1291 * LdrLockLoaderLock (NTDLL.@)
1293 * Note: flags are not implemented.
1294 * Flag 0x01 is used to raise exceptions on errors.
1295 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1297 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1299 if (flags
) FIXME( "flags %x not supported\n", flags
);
1301 if (result
) *result
= 1;
1302 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1303 RtlEnterCriticalSection( &loader_section
);
1304 *magic
= GetCurrentThreadId();
1305 return STATUS_SUCCESS
;
1309 /******************************************************************
1310 * LdrUnlockLoaderUnlock (NTDLL.@)
1312 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1316 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1317 RtlLeaveCriticalSection( &loader_section
);
1319 return STATUS_SUCCESS
;
1323 /******************************************************************
1324 * LdrGetProcedureAddress (NTDLL.@)
1326 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1327 ULONG ord
, PVOID
*address
)
1329 IMAGE_EXPORT_DIRECTORY
*exports
;
1331 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1333 RtlEnterCriticalSection( &loader_section
);
1335 /* check if the module itself is invalid to return the proper error */
1336 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1337 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1338 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1340 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1341 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1342 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1346 ret
= STATUS_SUCCESS
;
1350 RtlLeaveCriticalSection( &loader_section
);
1355 /***********************************************************************
1358 * Check if a loaded native dll is a Wine fake dll.
1360 static BOOL
is_fake_dll( HANDLE handle
)
1362 static const char fakedll_signature
[] = "Wine placeholder DLL";
1363 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1364 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1366 LARGE_INTEGER offset
;
1368 offset
.QuadPart
= 0;
1369 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1370 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1371 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1372 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1373 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1378 /***********************************************************************
1379 * get_builtin_fullname
1381 * Build the full pathname for a builtin dll.
1383 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1385 static const WCHAR soW
[] = {'.','s','o',0};
1386 WCHAR
*p
, *fullname
;
1387 size_t i
, len
= strlen(filename
);
1389 /* check if path can correspond to the dll we have */
1390 if (path
&& (p
= strrchrW( path
, '\\' )))
1393 for (i
= 0; i
< len
; i
++)
1394 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1395 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1397 /* the filename matches, use path as the full path */
1399 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1401 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1408 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1409 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1411 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1412 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1413 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1414 ascii_to_unicode( p
, filename
, len
+ 1 );
1420 /***********************************************************************
1421 * load_builtin_callback
1423 * Load a library in memory; callback function for wine_dll_register
1425 static void load_builtin_callback( void *module
, const char *filename
)
1427 static const WCHAR emptyW
[1];
1428 IMAGE_NT_HEADERS
*nt
;
1431 const WCHAR
*load_path
;
1435 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1438 if (!(nt
= RtlImageNtHeader( module
)))
1440 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1441 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1445 virtual_create_builtin_view( module
);
1447 /* create the MODREF */
1449 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1451 ERR( "can't load %s\n", filename
);
1452 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1456 wm
= alloc_module( module
, fullname
);
1457 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1460 ERR( "can't load %s\n", filename
);
1461 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1464 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1466 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1467 !NtCurrentTeb()->Peb
->ImageBaseAddress
) /* if we already have an executable, ignore this one */
1469 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1475 load_path
= builtin_load_info
->load_path
;
1476 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1477 if (!load_path
) load_path
= emptyW
;
1478 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1480 /* the module has only be inserted in the load & memory order lists */
1481 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1482 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1483 /* FIXME: free the modref */
1484 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1489 builtin_load_info
->wm
= wm
;
1490 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1492 /* send the DLL load event */
1494 SERVER_START_REQ( load_dll
)
1497 req
->base
= wine_server_client_ptr( module
);
1498 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1499 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1500 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1501 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1502 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1503 wine_server_call( req
);
1507 /* setup relay debugging entry points */
1508 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1512 /******************************************************************************
1513 * load_native_dll (internal)
1515 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1516 DWORD flags
, WINE_MODREF
** pwm
)
1521 IMAGE_NT_HEADERS
*nt
;
1526 TRACE("Trying native dll %s\n", debugstr_w(name
));
1529 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1530 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1531 if (status
!= STATUS_SUCCESS
) return status
;
1534 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1535 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_EXECUTE_READ
);
1536 if (status
< 0) goto done
;
1538 /* create the MODREF */
1540 if (!(wm
= alloc_module( module
, name
)))
1542 status
= STATUS_NO_MEMORY
;
1548 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1550 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1552 /* the module has only be inserted in the load & memory order lists */
1553 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1554 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1556 /* FIXME: there are several more dangling references
1557 * left. Including dlls loaded by this dll before the
1558 * failed one. Unrolling is rather difficult with the
1559 * current structure and we can leave them lying
1560 * around with no problems, so we don't care.
1561 * As these might reference our wm, we don't free it.
1567 /* send DLL load event */
1569 nt
= RtlImageNtHeader( module
);
1571 SERVER_START_REQ( load_dll
)
1573 req
->mapping
= wine_server_obj_handle( mapping
);
1574 req
->base
= wine_server_client_ptr( module
);
1575 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1576 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1577 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1578 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1579 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1580 wine_server_call( req
);
1584 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1586 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1588 wm
->ldr
.LoadCount
= 1;
1590 status
= STATUS_SUCCESS
;
1597 /***********************************************************************
1600 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1601 DWORD flags
, WINE_MODREF
** pwm
)
1603 char error
[256], dllname
[MAX_PATH
];
1604 const WCHAR
*name
, *p
;
1606 void *handle
= NULL
;
1607 struct builtin_load_info info
, *prev_info
;
1609 /* Fix the name in case we have a full path and extension */
1611 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1612 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1614 /* load_library will modify info.status. Note also that load_library can be
1615 * called several times, if the .so file we're loading has dependencies.
1616 * info.status will gather all the errors we may get while loading all these
1619 info
.load_path
= load_path
;
1620 info
.filename
= NULL
;
1621 info
.status
= STATUS_SUCCESS
;
1624 if (file
) /* we have a real file, try to load it */
1626 UNICODE_STRING nt_name
;
1627 ANSI_STRING unix_name
;
1629 TRACE("Trying built-in %s\n", debugstr_w(path
));
1631 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1632 return STATUS_DLL_NOT_FOUND
;
1634 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1636 RtlFreeUnicodeString( &nt_name
);
1637 return STATUS_DLL_NOT_FOUND
;
1639 prev_info
= builtin_load_info
;
1640 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1641 builtin_load_info
= &info
;
1642 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1643 builtin_load_info
= prev_info
;
1644 RtlFreeUnicodeString( &nt_name
);
1645 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1648 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1649 return STATUS_INVALID_IMAGE_FORMAT
;
1656 TRACE("Trying built-in %s\n", debugstr_w(name
));
1658 /* we don't want to depend on the current codepage here */
1659 len
= strlenW( name
) + 1;
1660 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1661 for (i
= 0; i
< len
; i
++)
1663 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1664 dllname
[i
] = (char)name
[i
];
1665 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1668 prev_info
= builtin_load_info
;
1669 builtin_load_info
= &info
;
1670 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1671 builtin_load_info
= prev_info
;
1676 /* The file does not exist -> WARN() */
1677 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1678 return STATUS_DLL_NOT_FOUND
;
1680 /* ERR() for all other errors (missing functions, ...) */
1681 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1682 return STATUS_PROCEDURE_NOT_FOUND
;
1686 if (info
.status
!= STATUS_SUCCESS
)
1688 wine_dll_unload( handle
);
1694 PLIST_ENTRY mark
, entry
;
1696 /* The constructor wasn't called, this means the .so is already
1697 * loaded under a different name. Try to find the wm for it. */
1699 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1700 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1702 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1703 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1705 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1706 TRACE( "Found %s at %p for builtin %s\n",
1707 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1711 wine_dll_unload( handle
); /* release the libdl refcount */
1712 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1713 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1717 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1718 info
.wm
->ldr
.LoadCount
= 1;
1719 info
.wm
->ldr
.SectionHandle
= handle
;
1723 return STATUS_SUCCESS
;
1727 /***********************************************************************
1730 * Find the full path (if any) of the dll from the activation context.
1732 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
1734 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
1735 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
1737 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
1738 ACTCTX_SECTION_KEYED_DATA data
;
1739 UNICODE_STRING nameW
;
1741 SIZE_T needed
, size
= 1024;
1744 RtlInitUnicodeString( &nameW
, libname
);
1745 data
.cbSize
= sizeof(data
);
1746 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
1747 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
1749 if (status
!= STATUS_SUCCESS
) return status
;
1753 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1755 status
= STATUS_NO_MEMORY
;
1758 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
1759 AssemblyDetailedInformationInActivationContext
,
1760 info
, size
, &needed
);
1761 if (status
== STATUS_SUCCESS
) break;
1762 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
1763 RtlFreeHeap( GetProcessHeap(), 0, info
);
1765 /* restart with larger buffer */
1768 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
1770 status
= STATUS_SXS_KEY_NOT_FOUND
;
1774 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
1776 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1779 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
1781 /* manifest name does not match directory name, so it's not a global
1782 * windows/winsxs manifest; use the manifest directory name instead */
1783 dirlen
= p
- info
->lpAssemblyManifestPath
;
1784 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
1785 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1787 status
= STATUS_NO_MEMORY
;
1790 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
1792 strcpyW( p
, libname
);
1797 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
1798 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
1800 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1802 status
= STATUS_NO_MEMORY
;
1805 strcpyW( p
, user_shared_data
->NtSystemRoot
);
1807 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
1808 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
1809 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
1810 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1812 strcpyW( p
, libname
);
1814 RtlFreeHeap( GetProcessHeap(), 0, info
);
1815 RtlReleaseActivationContext( data
.hActCtx
);
1820 /***********************************************************************
1823 * Find the file (or already loaded module) for a given dll name.
1825 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1826 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1828 OBJECT_ATTRIBUTES attr
;
1830 UNICODE_STRING nt_name
;
1831 WCHAR
*file_part
, *ext
, *dllname
;
1834 /* first append .dll if needed */
1837 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1839 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1840 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1841 return STATUS_NO_MEMORY
;
1842 strcpyW( dllname
, libname
);
1843 strcatW( dllname
, dllW
);
1847 nt_name
.Buffer
= NULL
;
1849 if (!contains_path( libname
))
1852 WCHAR
*fullname
= NULL
;
1854 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1856 status
= find_actctx_dll( libname
, &fullname
);
1857 if (status
== STATUS_SUCCESS
)
1859 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
1860 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1861 libname
= dllname
= fullname
;
1863 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
1865 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1870 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1872 /* we need to search for it */
1873 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1876 if (len
>= *size
) goto overflow
;
1877 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
1879 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1881 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1882 return STATUS_NO_MEMORY
;
1884 attr
.Length
= sizeof(attr
);
1885 attr
.RootDirectory
= 0;
1886 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1887 attr
.ObjectName
= &nt_name
;
1888 attr
.SecurityDescriptor
= NULL
;
1889 attr
.SecurityQualityOfService
= NULL
;
1890 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1896 if (!contains_path( libname
))
1898 /* if libname doesn't contain a path at all, we simply return the name as is,
1899 * to be loaded as builtin */
1900 len
= strlenW(libname
) * sizeof(WCHAR
);
1901 if (len
>= *size
) goto overflow
;
1902 strcpyW( filename
, libname
);
1907 /* absolute path name, or relative path name but not found above */
1909 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1911 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1912 return STATUS_NO_MEMORY
;
1914 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1915 if (len
>= *size
) goto overflow
;
1916 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1917 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
1919 attr
.Length
= sizeof(attr
);
1920 attr
.RootDirectory
= 0;
1921 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1922 attr
.ObjectName
= &nt_name
;
1923 attr
.SecurityDescriptor
= NULL
;
1924 attr
.SecurityQualityOfService
= NULL
;
1925 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1928 RtlFreeUnicodeString( &nt_name
);
1929 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1930 return STATUS_SUCCESS
;
1933 RtlFreeUnicodeString( &nt_name
);
1934 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1935 *size
= len
+ sizeof(WCHAR
);
1936 return STATUS_BUFFER_TOO_SMALL
;
1940 /***********************************************************************
1941 * load_dll (internal)
1943 * Load a PE style module according to the load order.
1944 * The loader_section must be locked while calling this function.
1946 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1948 enum loadorder loadorder
;
1952 WINE_MODREF
*main_exe
;
1956 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1960 size
= sizeof(buffer
);
1963 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1964 if (nts
== STATUS_SUCCESS
) break;
1965 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1966 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1967 /* grow the buffer and retry */
1968 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1971 if (*pwm
) /* found already loaded module */
1973 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1975 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
)) fixup_imports( *pwm
, load_path
);
1977 TRACE("Found %s for %s at %p, count=%d\n",
1978 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1979 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1980 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1981 return STATUS_SUCCESS
;
1984 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1985 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1987 if (handle
&& is_fake_dll( handle
))
1989 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
1997 nts
= STATUS_NO_MEMORY
;
2000 nts
= STATUS_DLL_NOT_FOUND
;
2003 case LO_NATIVE_BUILTIN
:
2004 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2007 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2008 if (nts
== STATUS_INVALID_FILE_FOR_SECTION
)
2009 /* not in PE format, maybe it's a builtin */
2010 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2012 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2013 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2016 case LO_BUILTIN_NATIVE
:
2017 case LO_DEFAULT
: /* default is builtin,native */
2018 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2019 if (!handle
) break; /* nothing else we can try */
2020 /* file is not a builtin library, try without using the specified file */
2021 if (nts
!= STATUS_SUCCESS
)
2022 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2023 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2024 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2026 /* stub-only dll, try native */
2027 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2028 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2029 nts
= STATUS_DLL_NOT_FOUND
;
2031 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2032 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2036 if (nts
== STATUS_SUCCESS
)
2038 /* Initialize DLL just loaded */
2039 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2040 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2041 (*pwm
)->ldr
.BaseAddress
);
2042 if (handle
) NtClose( handle
);
2043 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2047 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2048 if (handle
) NtClose( handle
);
2049 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2053 /******************************************************************
2054 * LdrLoadDll (NTDLL.@)
2056 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2057 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2062 RtlEnterCriticalSection( &loader_section
);
2064 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2065 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2067 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2069 nts
= process_attach( wm
, NULL
);
2070 if (nts
!= STATUS_SUCCESS
)
2072 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2076 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2078 RtlLeaveCriticalSection( &loader_section
);
2083 /******************************************************************
2084 * LdrGetDllHandle (NTDLL.@)
2086 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2094 RtlEnterCriticalSection( &loader_section
);
2096 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2099 size
= sizeof(buffer
);
2102 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2103 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2104 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2105 /* grow the buffer and retry */
2106 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2108 status
= STATUS_NO_MEMORY
;
2113 if (status
== STATUS_SUCCESS
)
2115 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2116 else status
= STATUS_DLL_NOT_FOUND
;
2119 RtlLeaveCriticalSection( &loader_section
);
2120 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2125 /******************************************************************
2126 * LdrAddRefDll (NTDLL.@)
2128 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2130 NTSTATUS ret
= STATUS_SUCCESS
;
2133 if (flags
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2135 RtlEnterCriticalSection( &loader_section
);
2137 if ((wm
= get_modref( module
)))
2139 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2140 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2142 else ret
= STATUS_INVALID_PARAMETER
;
2144 RtlLeaveCriticalSection( &loader_section
);
2149 /***********************************************************************
2150 * LdrProcessRelocationBlock (NTDLL.@)
2152 * Apply relocations to a given page of a mapped PE image.
2154 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2155 USHORT
*relocs
, INT_PTR delta
)
2159 USHORT offset
= *relocs
& 0xfff;
2160 int type
= *relocs
>> 12;
2163 case IMAGE_REL_BASED_ABSOLUTE
:
2165 case IMAGE_REL_BASED_HIGH
:
2166 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2168 case IMAGE_REL_BASED_LOW
:
2169 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2171 case IMAGE_REL_BASED_HIGHLOW
:
2172 *(int *)((char *)page
+ offset
) += delta
;
2175 case IMAGE_REL_BASED_DIR64
:
2176 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2178 #elif defined(__arm__)
2179 case IMAGE_REL_BASED_THUMB_MOV32
:
2181 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2182 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2183 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x000f);
2185 if ((inst
& 0x8000fbf0) != 0x0000f240)
2186 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2188 imm16
+= LOWORD(delta
);
2190 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2191 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2192 ((imm16
>> 12) & 0x000f) +
2193 ((imm16
<< 20) & 0x70000000) +
2194 ((imm16
<< 16) & 0x0f0000);
2198 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2199 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2200 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x000f);
2202 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2203 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2205 imm16
+= HIWORD(delta
);
2207 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2208 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2209 ((imm16
>> 1) & 0x0400) +
2210 ((imm16
>> 12) & 0x000f) +
2211 ((imm16
<< 20) & 0x70000000) +
2212 ((imm16
<< 16) & 0x0f0000);
2218 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2223 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2227 /******************************************************************
2228 * LdrQueryProcessModuleInformation
2231 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2232 ULONG buf_size
, ULONG
* req_size
)
2234 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2235 ULONG size
= sizeof(ULONG
);
2236 NTSTATUS nts
= STATUS_SUCCESS
;
2239 PLIST_ENTRY mark
, entry
;
2243 smi
->ModulesCount
= 0;
2245 RtlEnterCriticalSection( &loader_section
);
2246 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2247 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2249 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2250 size
+= sizeof(*sm
);
2251 if (size
<= buf_size
)
2253 sm
->Reserved1
= 0; /* FIXME */
2254 sm
->Reserved2
= 0; /* FIXME */
2255 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2256 sm
->ImageSize
= mod
->SizeOfImage
;
2257 sm
->Flags
= mod
->Flags
;
2259 sm
->Rank
= 0; /* FIXME */
2260 sm
->Unknown
= 0; /* FIXME */
2262 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2263 str
.Buffer
= (char*)sm
->Name
;
2264 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2265 ptr
= strrchr(str
.Buffer
, '\\');
2266 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2268 smi
->ModulesCount
++;
2271 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2273 RtlLeaveCriticalSection( &loader_section
);
2275 if (req_size
) *req_size
= size
;
2281 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2287 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2289 RtlInitUnicodeString( &str
, name
);
2291 size
= sizeof(buffer
) - sizeof(WCHAR
);
2292 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2295 if (info
->Type
!= REG_DWORD
)
2297 buffer
[size
/ sizeof(WCHAR
)] = 0;
2298 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2300 else memcpy( value
, info
->Data
, sizeof(*value
) );
2304 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2305 void *data
, ULONG in_size
, ULONG
*out_size
)
2311 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2312 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2314 RtlInitUnicodeString( &str
, name
);
2316 size
= info_size
+ in_size
;
2317 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2318 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2319 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2320 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2322 if (out_size
) *out_size
= info
->DataLength
;
2323 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2325 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2330 /******************************************************************
2331 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2333 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2334 void *data
, ULONG in_size
, ULONG
*out_size
)
2336 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2337 'S','o','f','t','w','a','r','e','\\',
2338 'M','i','c','r','o','s','o','f','t','\\',
2339 'W','i','n','d','o','w','s',' ','N','T','\\',
2340 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2341 'I','m','a','g','e',' ','F','i','l','e',' ',
2342 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2343 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2344 OBJECT_ATTRIBUTES attr
;
2345 UNICODE_STRING name_str
;
2351 attr
.Length
= sizeof(attr
);
2352 attr
.RootDirectory
= 0;
2353 attr
.ObjectName
= &name_str
;
2354 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2355 attr
.SecurityDescriptor
= NULL
;
2356 attr
.SecurityQualityOfService
= NULL
;
2358 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2359 else p
= key
->Buffer
;
2360 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2361 name_str
.Buffer
= path
;
2362 name_str
.Length
= sizeof(optionsW
) + len
;
2363 name_str
.MaximumLength
= name_str
.Length
;
2364 memcpy( path
, optionsW
, sizeof(optionsW
) );
2365 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2366 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2368 if (type
== REG_DWORD
)
2370 if (out_size
) *out_size
= sizeof(ULONG
);
2371 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2372 else status
= STATUS_BUFFER_OVERFLOW
;
2374 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2381 /******************************************************************
2382 * RtlDllShutdownInProgress (NTDLL.@)
2384 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2386 return process_detaching
;
2390 /******************************************************************
2391 * LdrShutdownProcess (NTDLL.@)
2394 void WINAPI
LdrShutdownProcess(void)
2397 process_detach( TRUE
, (LPVOID
)1 );
2400 /******************************************************************
2401 * LdrShutdownThread (NTDLL.@)
2404 void WINAPI
LdrShutdownThread(void)
2406 PLIST_ENTRY mark
, entry
;
2411 /* don't do any detach calls if process is exiting */
2412 if (process_detaching
) return;
2413 /* FIXME: there is still a race here */
2415 RtlEnterCriticalSection( &loader_section
);
2417 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2418 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2420 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2421 InInitializationOrderModuleList
);
2422 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2424 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2427 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2428 DLL_THREAD_DETACH
, NULL
);
2431 RtlLeaveCriticalSection( &loader_section
);
2432 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2436 /***********************************************************************
2440 static void free_modref( WINE_MODREF
*wm
)
2442 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2443 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2444 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2445 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2447 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2448 if (!TRACE_ON(module
))
2449 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2450 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2451 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2453 SERVER_START_REQ( unload_dll
)
2455 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2456 wine_server_call( req
);
2460 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2461 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2462 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2463 if (cached_modref
== wm
) cached_modref
= NULL
;
2464 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2465 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2466 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2469 /***********************************************************************
2470 * MODULE_FlushModrefs
2472 * Remove all unused modrefs and call the internal unloading routines
2473 * for the library type.
2475 * The loader_section must be locked while calling this function.
2477 static void MODULE_FlushModrefs(void)
2479 PLIST_ENTRY mark
, entry
, prev
;
2483 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2484 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2486 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2487 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2488 prev
= entry
->Blink
;
2489 if (!mod
->LoadCount
) free_modref( wm
);
2492 /* check load order list too for modules that haven't been initialized yet */
2493 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2494 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2496 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2497 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2498 prev
= entry
->Blink
;
2499 if (!mod
->LoadCount
) free_modref( wm
);
2503 /***********************************************************************
2504 * MODULE_DecRefCount
2506 * The loader_section must be locked while calling this function.
2508 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2512 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2515 if ( wm
->ldr
.LoadCount
<= 0 )
2518 --wm
->ldr
.LoadCount
;
2519 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2521 if ( wm
->ldr
.LoadCount
== 0 )
2523 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2525 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2527 MODULE_DecRefCount( wm
->deps
[i
] );
2529 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2533 /******************************************************************
2534 * LdrUnloadDll (NTDLL.@)
2538 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2540 NTSTATUS retv
= STATUS_SUCCESS
;
2542 TRACE("(%p)\n", hModule
);
2544 RtlEnterCriticalSection( &loader_section
);
2546 /* if we're stopping the whole process (and forcing the removal of all
2547 * DLLs) the library will be freed anyway
2549 if (!process_detaching
)
2554 if ((wm
= get_modref( hModule
)) != NULL
)
2556 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2558 /* Recursively decrement reference counts */
2559 MODULE_DecRefCount( wm
);
2561 /* Call process detach notifications */
2562 if ( free_lib_count
<= 1 )
2564 process_detach( FALSE
, NULL
);
2565 MODULE_FlushModrefs();
2571 retv
= STATUS_DLL_NOT_FOUND
;
2576 RtlLeaveCriticalSection( &loader_section
);
2581 /***********************************************************************
2582 * RtlImageNtHeader (NTDLL.@)
2584 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2586 IMAGE_NT_HEADERS
*ret
;
2590 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2593 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2595 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2596 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2608 /***********************************************************************
2609 * attach_process_dlls
2611 * Initial attach to all the dlls loaded by the process.
2613 static NTSTATUS
attach_process_dlls( void *wm
)
2617 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2619 RtlEnterCriticalSection( &loader_section
);
2620 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2622 if (last_failed_modref
)
2623 ERR( "%s failed to initialize, aborting\n",
2624 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2627 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2628 RtlLeaveCriticalSection( &loader_section
);
2633 /***********************************************************************
2634 * load_global_options
2636 static void load_global_options(void)
2638 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
2639 'S','y','s','t','e','m','\\',
2640 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2641 'C','o','n','t','r','o','l','\\',
2642 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2643 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2644 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};
2645 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2646 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2647 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};
2648 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};
2650 OBJECT_ATTRIBUTES attr
;
2651 UNICODE_STRING name_str
;
2655 attr
.Length
= sizeof(attr
);
2656 attr
.RootDirectory
= 0;
2657 attr
.ObjectName
= &name_str
;
2658 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2659 attr
.SecurityDescriptor
= NULL
;
2660 attr
.SecurityQualityOfService
= NULL
;
2661 RtlInitUnicodeString( &name_str
, sessionW
);
2663 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
2665 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
2667 query_dword_option( hkey
, critsectW
, &value
);
2668 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
2670 query_dword_option( hkey
, heapresW
, &value
);
2671 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
2673 query_dword_option( hkey
, heapcommitW
, &value
);
2674 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
2676 query_dword_option( hkey
, decommittotalW
, &value
);
2677 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
2679 query_dword_option( hkey
, decommitfreeW
, &value
);
2680 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
2686 /***********************************************************************
2689 static void start_process( void *kernel_start
)
2691 call_thread_entry_point( kernel_start
, NtCurrentTeb()->Peb
);
2694 /******************************************************************
2695 * LdrInitializeThunk (NTDLL.@)
2698 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
2699 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
2701 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2705 PEB
*peb
= NtCurrentTeb()->Peb
;
2706 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
2708 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
2710 /* allocate the modref for the main exe (if not already done) */
2711 wm
= get_modref( peb
->ImageBaseAddress
);
2713 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
2715 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
2719 peb
->LoaderLock
= &loader_section
;
2720 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2721 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
2722 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
2723 version_init( wm
->ldr
.FullDllName
.Buffer
);
2725 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
2726 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
2728 /* the main exe needs to be the first in the load order list */
2729 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2730 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2732 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
2733 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
2736 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2737 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2738 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2739 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2740 heap_set_debug_flags( GetProcessHeap() );
2742 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
2743 if (status
!= STATUS_SUCCESS
) goto error
;
2745 virtual_release_address_space( nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
);
2746 virtual_clear_thread_stack();
2747 wine_switch_to_stack( start_process
, kernel_start
, NtCurrentTeb()->Tib
.StackBase
);
2750 ERR( "Main exe initialization for %s failed, status %x\n",
2751 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2752 NtTerminateProcess( GetCurrentProcess(), status
);
2756 /***********************************************************************
2757 * RtlImageDirectoryEntryToData (NTDLL.@)
2759 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2761 const IMAGE_NT_HEADERS
*nt
;
2764 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2766 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2769 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2770 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
2772 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
2774 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2775 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2776 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
2777 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2779 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
2781 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
2783 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2784 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2785 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
2786 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2790 /* not mapped as image, need to find the section containing the virtual address */
2791 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2795 /***********************************************************************
2796 * RtlImageRvaToSection (NTDLL.@)
2798 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2799 HMODULE module
, DWORD rva
)
2802 const IMAGE_SECTION_HEADER
*sec
;
2804 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2805 nt
->FileHeader
.SizeOfOptionalHeader
);
2806 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2808 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2809 return (PIMAGE_SECTION_HEADER
)sec
;
2815 /***********************************************************************
2816 * RtlImageRvaToVa (NTDLL.@)
2818 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2819 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2821 IMAGE_SECTION_HEADER
*sec
;
2823 if (section
&& *section
) /* try this section first */
2826 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2829 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2831 if (section
) *section
= sec
;
2832 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2836 /***********************************************************************
2837 * RtlPcToFileHeader (NTDLL.@)
2839 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
2844 RtlEnterCriticalSection( &loader_section
);
2845 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
2846 RtlLeaveCriticalSection( &loader_section
);
2852 /***********************************************************************
2853 * NtLoadDriver (NTDLL.@)
2854 * ZwLoadDriver (NTDLL.@)
2856 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2858 FIXME("(%p), stub!\n",DriverServiceName
);
2859 return STATUS_NOT_IMPLEMENTED
;
2863 /***********************************************************************
2864 * NtUnloadDriver (NTDLL.@)
2865 * ZwUnloadDriver (NTDLL.@)
2867 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2869 FIXME("(%p), stub!\n",DriverServiceName
);
2870 return STATUS_NOT_IMPLEMENTED
;
2874 /******************************************************************
2877 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2879 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2884 /******************************************************************
2885 * __wine_init_windows_dir (NTDLL.@)
2887 * Windows and system dir initialization once kernel32 has been loaded.
2889 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2891 PLIST_ENTRY mark
, entry
;
2894 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
2895 DIR_init_windows_dir( windir
, sysdir
);
2897 /* prepend the system dir to the name of the already created modules */
2898 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2899 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2901 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2903 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2905 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2906 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2907 if (!buffer
) continue;
2908 strcpyW( buffer
, system_dir
.Buffer
);
2909 p
= buffer
+ strlenW( buffer
);
2910 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2911 strcpyW( p
, mod
->FullDllName
.Buffer
);
2912 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2913 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2918 /***********************************************************************
2919 * __wine_process_init
2921 void __wine_process_init(void)
2923 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2927 ANSI_STRING func_name
;
2928 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
2930 main_exe_file
= thread_init();
2932 /* retrieve current umask */
2933 FILE_umask
= umask(0777);
2934 umask( FILE_umask
);
2936 load_global_options();
2938 /* setup the load callback and create ntdll modref */
2939 wine_dll_set_callback( load_builtin_callback
);
2941 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
2943 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
2946 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
2947 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
2949 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2950 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2951 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2953 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);