4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "wine/port.h"
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
32 #define WIN32_NO_STATUS
33 #define NONAMELESSUNION
37 #include "delayloadhandler.h"
39 #include "wine/exception.h"
40 #include "wine/library.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
44 #include "ntdll_misc.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(module
);
48 WINE_DECLARE_DEBUG_CHANNEL(relay
);
49 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
50 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
51 WINE_DECLARE_DEBUG_CHANNEL(imports
);
52 WINE_DECLARE_DEBUG_CHANNEL(pid
);
55 #define DEFAULT_SECURITY_COOKIE_64 (((ULONGLONG)0x00002b99 << 32) | 0x2ddfa232)
57 #define DEFAULT_SECURITY_COOKIE_32 0xbb40e64e
58 #define DEFAULT_SECURITY_COOKIE_16 (DEFAULT_SECURITY_COOKIE_32 >> 16)
60 /* we don't want to include winuser.h */
61 #define RT_MANIFEST ((ULONG_PTR)24)
62 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
64 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
66 static BOOL process_detaching
= FALSE
; /* set on process detach to avoid deadlocks with thread detach */
67 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
69 static const char * const reason_names
[] =
75 NULL
, NULL
, NULL
, NULL
,
79 static const WCHAR dllW
[] = {'.','d','l','l',0};
81 /* internal representation of 32bit modules. per process. */
82 typedef struct _wine_modref
86 struct _wine_modref
**deps
;
89 /* info about the current builtin dll load */
90 /* used to keep track of things across the register_dll constructor call */
91 struct builtin_load_info
93 const WCHAR
*load_path
;
94 const WCHAR
*filename
;
99 static struct builtin_load_info default_load_info
;
100 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
102 static HANDLE main_exe_file
;
103 static UINT tls_module_count
; /* number of modules with TLS directory */
104 static IMAGE_TLS_DIRECTORY
*tls_dirs
; /* array of TLS directories */
105 LIST_ENTRY tls_links
= { &tls_links
, &tls_links
};
107 static RTL_CRITICAL_SECTION loader_section
;
108 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
110 0, 0, &loader_section
,
111 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
112 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
114 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
116 static WINE_MODREF
*cached_modref
;
117 static WINE_MODREF
*current_modref
;
118 static WINE_MODREF
*last_failed_modref
;
120 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
121 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
122 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
123 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
124 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
125 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
127 /* convert PE image VirtualAddress to Real Address */
128 static inline void *get_rva( HMODULE module
, DWORD va
)
130 return (void *)((char *)module
+ va
);
133 /* check whether the file name contains a path */
134 static inline BOOL
contains_path( LPCWSTR name
)
136 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
139 /* convert from straight ASCII to Unicode without depending on the current codepage */
140 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
142 while (len
--) *dst
++ = (unsigned char)*src
++;
146 /*************************************************************************
147 * call_dll_entry_point
149 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
150 * their entry point, so we need a small asm wrapper. Testing indicates
151 * that only modifying esi leads to a crash, so use this one to backup
152 * ebp while running the dll entry proc.
155 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
156 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
158 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
159 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
161 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
163 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
165 __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
167 __ASM_CFI(".cfi_rel_offset %edi,-12\n\t")
169 __ASM_CFI(".cfi_def_cfa_register %esi\n\t")
173 "movl 8(%ebp),%eax\n\t"
176 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
177 "leal -12(%ebp),%esp\n\t"
179 __ASM_CFI(".cfi_same_value %edi\n\t")
181 __ASM_CFI(".cfi_same_value %esi\n\t")
183 __ASM_CFI(".cfi_same_value %ebx\n\t")
185 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
186 __ASM_CFI(".cfi_same_value %ebp\n\t")
189 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
190 UINT reason
, void *reserved
)
192 return proc( module
, reason
, reserved
);
194 #endif /* __i386__ */
197 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
198 /*************************************************************************
201 * Entry point for stub functions.
203 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
205 EXCEPTION_RECORD rec
;
207 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
208 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
209 rec
.ExceptionRecord
= NULL
;
210 rec
.ExceptionAddress
= ret_addr
;
211 rec
.NumberParameters
= 2;
212 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
213 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
214 for (;;) RtlRaiseException( &rec
);
218 #include "pshpack1.h"
222 BYTE pushl1
; /* pushl $name */
224 BYTE pushl2
; /* pushl $dll */
226 BYTE call
; /* call stub_entry_point */
229 #elif defined(__arm__)
232 BYTE ldr_r0
[4]; /* ldr r0, $dll */
233 BYTE mov_pc_pc1
[4]; /* mov pc,pc */
235 BYTE ldr_r1
[4]; /* ldr r1, $name */
236 BYTE mov_pc_pc2
[4]; /* mov pc,pc */
238 BYTE mov_r2_lr
[4]; /* mov r2, lr */
239 BYTE ldr_pc_pc
[4]; /* ldr pc, [pc, #-4] */
245 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
247 BYTE movq_rsi
[2]; /* movq $name,%rsi */
249 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
250 BYTE movq_rax
[2]; /* movq $entry, %rax */
252 BYTE jmpq_rax
[2]; /* jmp %rax */
257 /*************************************************************************
260 * Allocate a stub entry point.
262 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
264 #define MAX_SIZE 65536
265 static struct stub
*stubs
;
266 static unsigned int nb_stubs
;
269 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
273 SIZE_T size
= MAX_SIZE
;
274 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
275 MEM_COMMIT
, PAGE_EXECUTE_READWRITE
) != STATUS_SUCCESS
)
278 stub
= &stubs
[nb_stubs
++];
280 stub
->pushl1
= 0x68; /* pushl $name */
282 stub
->pushl2
= 0x68; /* pushl $dll */
284 stub
->call
= 0xe8; /* call stub_entry_point */
285 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
286 #elif defined(__arm__)
287 stub
->ldr_r0
[0] = 0x00; /* ldr r0, $dll */
288 stub
->ldr_r0
[1] = 0x00;
289 stub
->ldr_r0
[2] = 0x9f;
290 stub
->ldr_r0
[3] = 0xe5;
291 stub
->mov_pc_pc1
[0] = 0x0f; /* mov pc,pc */
292 stub
->mov_pc_pc1
[1] = 0xf0;
293 stub
->mov_pc_pc1
[2] = 0xa0;
294 stub
->mov_pc_pc1
[3] = 0xe1;
296 stub
->ldr_r1
[0] = 0x00; /* ldr r1, $name */
297 stub
->ldr_r1
[1] = 0x10;
298 stub
->ldr_r1
[2] = 0x9f;
299 stub
->ldr_r1
[3] = 0xe5;
300 stub
->mov_pc_pc2
[0] = 0x0f; /* mov pc,pc */
301 stub
->mov_pc_pc2
[1] = 0xf0;
302 stub
->mov_pc_pc2
[2] = 0xa0;
303 stub
->mov_pc_pc2
[3] = 0xe1;
305 stub
->mov_r2_lr
[0] = 0x0e; /* mov r2, lr */
306 stub
->mov_r2_lr
[1] = 0x20;
307 stub
->mov_r2_lr
[2] = 0xa0;
308 stub
->mov_r2_lr
[3] = 0xe1;
309 stub
->ldr_pc_pc
[0] = 0x04; /* ldr pc, [pc, #-4] */
310 stub
->ldr_pc_pc
[1] = 0xf0;
311 stub
->ldr_pc_pc
[2] = 0x1f;
312 stub
->ldr_pc_pc
[3] = 0xe5;
313 stub
->entry
= stub_entry_point
;
315 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
316 stub
->movq_rdi
[1] = 0xbf;
318 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
319 stub
->movq_rsi
[1] = 0xbe;
321 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
322 stub
->movq_rsp_rdx
[1] = 0x8b;
323 stub
->movq_rsp_rdx
[2] = 0x14;
324 stub
->movq_rsp_rdx
[3] = 0x24;
325 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
326 stub
->movq_rax
[1] = 0xb8;
327 stub
->entry
= stub_entry_point
;
328 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
329 stub
->jmpq_rax
[1] = 0xe0;
331 return (ULONG_PTR
)stub
;
335 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
336 #endif /* __i386__ */
339 /*************************************************************************
342 * Looks for the referenced HMODULE in the current process
343 * The loader_section must be locked while calling this function.
345 static WINE_MODREF
*get_modref( HMODULE hmod
)
347 PLIST_ENTRY mark
, entry
;
350 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
352 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
353 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
355 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
356 if (mod
->BaseAddress
== hmod
)
357 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
358 if (mod
->BaseAddress
> (void*)hmod
) break;
364 /**********************************************************************
365 * find_basename_module
367 * Find a module from its base name.
368 * The loader_section must be locked while calling this function
370 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
372 PLIST_ENTRY mark
, entry
;
374 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
375 return cached_modref
;
377 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
378 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
380 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
381 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
383 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
384 return cached_modref
;
391 /**********************************************************************
392 * find_fullname_module
394 * Find a module from its full path name.
395 * The loader_section must be locked while calling this function
397 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
399 PLIST_ENTRY mark
, entry
;
401 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
402 return cached_modref
;
404 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
405 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
407 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
408 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
410 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
411 return cached_modref
;
418 /*************************************************************************
419 * find_forwarded_export
421 * Find the final function pointer for a forwarded function.
422 * The loader_section must be locked while calling this function.
424 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
426 const IMAGE_EXPORT_DIRECTORY
*exports
;
430 const char *end
= strrchr(forward
, '.');
433 if (!end
) return NULL
;
434 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
435 ascii_to_unicode( mod_name
, forward
, end
- forward
);
436 mod_name
[end
- forward
] = 0;
437 if (!strchrW( mod_name
, '.' ))
439 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
440 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
443 if (!(wm
= find_basename_module( mod_name
)))
445 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
446 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
447 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
449 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
451 LdrUnloadDll( wm
->ldr
.BaseAddress
);
458 ERR( "module not found for forward '%s' used by %s\n",
459 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
463 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
464 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
466 const char *name
= end
+ 1;
467 if (*name
== '#') /* ordinal */
468 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
470 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
475 ERR("function not found for forward '%s' used by %s."
476 " If you are using builtin %s, try using the native one instead.\n",
477 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
478 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
484 /*************************************************************************
485 * find_ordinal_export
487 * Find an exported function by ordinal.
488 * The exports base must have been subtracted from the ordinal already.
489 * The loader_section must be locked while calling this function.
491 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
492 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
495 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
497 if (ordinal
>= exports
->NumberOfFunctions
)
499 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
502 if (!functions
[ordinal
]) return NULL
;
504 proc
= get_rva( module
, functions
[ordinal
] );
506 /* if the address falls into the export dir, it's a forward */
507 if (((const char *)proc
>= (const char *)exports
) &&
508 ((const char *)proc
< (const char *)exports
+ exp_size
))
509 return find_forwarded_export( module
, (const char *)proc
, load_path
);
513 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
514 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
518 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
519 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
525 /*************************************************************************
528 * Find an exported function by name.
529 * The loader_section must be locked while calling this function.
531 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
532 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
534 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
535 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
536 int min
= 0, max
= exports
->NumberOfNames
- 1;
538 /* first check the hint */
539 if (hint
>= 0 && hint
<= max
)
541 char *ename
= get_rva( module
, names
[hint
] );
542 if (!strcmp( ename
, name
))
543 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
546 /* then do a binary search */
549 int res
, pos
= (min
+ max
) / 2;
550 char *ename
= get_rva( module
, names
[pos
] );
551 if (!(res
= strcmp( ename
, name
)))
552 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
553 if (res
> 0) max
= pos
- 1;
561 /*************************************************************************
564 * Import the dll specified by the given import descriptor.
565 * The loader_section must be locked while calling this function.
567 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
572 const IMAGE_EXPORT_DIRECTORY
*exports
;
574 const IMAGE_THUNK_DATA
*import_list
;
575 IMAGE_THUNK_DATA
*thunk_list
;
577 const char *name
= get_rva( module
, descr
->Name
);
578 DWORD len
= strlen(name
);
580 SIZE_T protect_size
= 0;
583 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
584 if (descr
->u
.OriginalFirstThunk
)
585 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
587 import_list
= thunk_list
;
589 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
591 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
593 ascii_to_unicode( buffer
, name
, len
);
595 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
597 else /* need to allocate a larger buffer */
599 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
600 if (!ptr
) return NULL
;
601 ascii_to_unicode( ptr
, name
, len
);
603 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
604 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
609 if (status
== STATUS_DLL_NOT_FOUND
)
610 ERR("Library %s (which is needed by %s) not found\n",
611 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
613 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
614 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
618 /* unprotect the import address table since it can be located in
619 * readonly section */
620 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
621 protect_base
= thunk_list
;
622 protect_size
*= sizeof(*thunk_list
);
623 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
624 &protect_size
, PAGE_READWRITE
, &protect_old
);
626 imp_mod
= wmImp
->ldr
.BaseAddress
;
627 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
631 /* set all imported function to deadbeef */
632 while (import_list
->u1
.Ordinal
)
634 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
636 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
637 WARN("No implementation for %s.%d", name
, ordinal
);
638 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
642 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
643 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
644 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
646 WARN(" imported from %s, allocating stub %p\n",
647 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
648 (void *)thunk_list
->u1
.Function
);
655 while (import_list
->u1
.Ordinal
)
657 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
659 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
661 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
662 ordinal
- exports
->Base
, load_path
);
663 if (!thunk_list
->u1
.Function
)
665 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
666 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
667 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
668 (void *)thunk_list
->u1
.Function
);
670 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
672 else /* import by name */
674 IMAGE_IMPORT_BY_NAME
*pe_name
;
675 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
676 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
677 (const char*)pe_name
->Name
,
678 pe_name
->Hint
, load_path
);
679 if (!thunk_list
->u1
.Function
)
681 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
682 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
683 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
684 (void *)thunk_list
->u1
.Function
);
686 TRACE_(imports
)("--- %s %s.%d = %p\n",
687 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
694 /* restore old protection of the import address table */
695 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
700 /***********************************************************************
701 * create_module_activation_context
703 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
706 LDR_RESOURCE_INFO info
;
707 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
709 info
.Type
= RT_MANIFEST
;
710 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
712 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
715 ctx
.cbSize
= sizeof(ctx
);
717 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
718 ctx
.hModule
= module
->BaseAddress
;
719 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
720 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
726 /*************************************************************************
727 * is_dll_native_subsystem
729 * Check if dll is a proper native driver.
730 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
731 * while being perfectly normal DLLs. This heuristic should catch such breakages.
733 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
735 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
736 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
737 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
741 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
742 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
744 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
745 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
747 for (i
= 0; imports
[i
].Name
; i
++)
749 const char *name
= get_rva( module
, imports
[i
].Name
);
750 DWORD len
= strlen(name
);
751 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
752 ascii_to_unicode( buffer
, name
, len
+ 1 );
753 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
755 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
763 /*************************************************************************
766 * Allocate a TLS slot for a newly-loaded module.
767 * The loader_section must be locked while calling this function.
769 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
771 const IMAGE_TLS_DIRECTORY
*dir
;
776 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
779 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
780 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
782 for (i
= 0; i
< tls_module_count
; i
++)
784 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
785 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
789 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
790 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
791 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
793 if (i
== tls_module_count
)
795 UINT new_count
= max( 32, tls_module_count
* 2 );
798 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
800 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
801 new_count
* sizeof(*tls_dirs
) );
802 if (!new_ptr
) return -1;
804 /* resize the pointer block in all running threads */
805 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
807 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
808 void **old
= teb
->ThreadLocalStoragePointer
;
809 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
812 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
813 teb
->ThreadLocalStoragePointer
= new;
814 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
815 /* FIXME: can't free old block here, should be freed at thread exit */
819 tls_module_count
= new_count
;
822 /* allocate the data block in all running threads */
823 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
825 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
827 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
828 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
829 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
831 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
832 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
834 RtlFreeHeap( GetProcessHeap(), 0,
835 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
838 *(DWORD
*)dir
->AddressOfIndex
= i
;
844 /*************************************************************************
847 * Free the module TLS slot on unload.
848 * The loader_section must be locked while calling this function.
850 static void free_tls_slot( LDR_MODULE
*mod
)
852 ULONG i
= (USHORT
)mod
->TlsIndex
;
854 if (mod
->TlsIndex
== -1) return;
855 assert( i
< tls_module_count
);
856 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
860 /****************************************************************
863 * Fixup all imports of a given module.
864 * The loader_section must be locked while calling this function.
866 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
869 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
875 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
876 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
878 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
880 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
881 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
882 return STATUS_SUCCESS
;
885 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
887 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
889 if (!create_module_activation_context( &wm
->ldr
))
890 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
892 /* Allocate module dependency list */
893 wm
->nDeps
= nb_imports
;
894 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
896 /* load the imported modules. They are automatically
897 * added to the modref list of the process.
899 prev
= current_modref
;
901 status
= STATUS_SUCCESS
;
902 for (i
= 0; i
< nb_imports
; i
++)
904 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
905 status
= STATUS_DLL_NOT_FOUND
;
907 current_modref
= prev
;
908 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
913 /*************************************************************************
916 * Allocate a WINE_MODREF structure and add it to the process list
917 * The loader_section must be locked while calling this function.
919 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
923 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
924 PLIST_ENTRY entry
, mark
;
926 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
931 wm
->ldr
.BaseAddress
= hModule
;
932 wm
->ldr
.EntryPoint
= NULL
;
933 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
934 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
935 wm
->ldr
.TlsIndex
= -1;
936 wm
->ldr
.LoadCount
= 1;
937 wm
->ldr
.SectionHandle
= NULL
;
938 wm
->ldr
.CheckSum
= 0;
939 wm
->ldr
.TimeDateStamp
= 0;
940 wm
->ldr
.ActivationContext
= 0;
942 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
943 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
944 else p
= wm
->ldr
.FullDllName
.Buffer
;
945 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
947 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
949 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
950 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
951 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
952 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
955 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
956 &wm
->ldr
.InLoadOrderModuleList
);
958 /* insert module in MemoryList, sorted in increasing base addresses */
959 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
960 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
962 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
965 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
966 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
967 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
968 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
970 /* wait until init is called for inserting into this list */
971 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
972 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
974 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
976 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
977 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
978 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
984 /*************************************************************************
987 * Allocate the per-thread structure for module TLS storage.
989 static NTSTATUS
alloc_thread_tls(void)
994 if (!tls_module_count
) return STATUS_SUCCESS
;
996 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
997 tls_module_count
* sizeof(*pointers
) )))
998 return STATUS_NO_MEMORY
;
1000 for (i
= 0; i
< tls_module_count
; i
++)
1002 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1005 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1006 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1008 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1010 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1011 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1012 return STATUS_NO_MEMORY
;
1014 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1015 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1017 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1018 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1020 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1021 return STATUS_SUCCESS
;
1025 /*************************************************************************
1026 * call_tls_callbacks
1028 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1030 const IMAGE_TLS_DIRECTORY
*dir
;
1031 const PIMAGE_TLS_CALLBACK
*callback
;
1034 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1035 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1037 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1039 if (TRACE_ON(relay
))
1042 DPRINTF( "%04x:", GetCurrentProcessId() );
1043 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1044 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1048 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1052 if (TRACE_ON(relay
))
1055 DPRINTF( "%04x:", GetCurrentProcessId() );
1056 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1057 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
1062 if (TRACE_ON(relay
))
1065 DPRINTF( "%04x:", GetCurrentProcessId() );
1066 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1067 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1073 /*************************************************************************
1076 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1079 NTSTATUS status
= STATUS_SUCCESS
;
1080 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1081 void *module
= wm
->ldr
.BaseAddress
;
1084 /* Skip calls for modules loaded with special load flags */
1086 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1087 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1088 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1090 if (TRACE_ON(relay
))
1092 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1093 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1094 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1096 DPRINTF( "%04x:", GetCurrentProcessId() );
1097 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1098 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1099 reason_names
[reason
], lpReserved
);
1101 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1102 reason_names
[reason
], lpReserved
);
1106 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1108 status
= STATUS_DLL_INIT_FAILED
;
1112 if (TRACE_ON(relay
))
1115 DPRINTF( "%04x:", GetCurrentProcessId() );
1116 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1117 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
1119 status
= GetExceptionCode();
1123 /* The state of the module list may have changed due to the call
1124 to the dll. We cannot assume that this module has not been
1126 if (TRACE_ON(relay
))
1129 DPRINTF( "%04x:", GetCurrentProcessId() );
1130 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1131 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1132 reason_names
[reason
], lpReserved
, retv
);
1134 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1140 /*************************************************************************
1143 * Send the process attach notification to all DLLs the given module
1144 * depends on (recursively). This is somewhat complicated due to the fact that
1146 * - we have to respect the module dependencies, i.e. modules implicitly
1147 * referenced by another module have to be initialized before the module
1148 * itself can be initialized
1150 * - the initialization routine of a DLL can itself call LoadLibrary,
1151 * thereby introducing a whole new set of dependencies (even involving
1152 * the 'old' modules) at any time during the whole process
1154 * (Note that this routine can be recursively entered not only directly
1155 * from itself, but also via LoadLibrary from one of the called initialization
1158 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1159 * the process *detach* notifications to be sent in the correct order.
1160 * This must not only take into account module dependencies, but also
1161 * 'hidden' dependencies created by modules calling LoadLibrary in their
1162 * attach notification routine.
1164 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1165 * list after the attach notification has returned. This implies that the
1166 * detach notifications are called in the reverse of the sequence the attach
1167 * notifications *returned*.
1169 * The loader_section must be locked while calling this function.
1171 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1173 NTSTATUS status
= STATUS_SUCCESS
;
1177 if (process_detaching
) return status
;
1179 /* prevent infinite recursion in case of cyclical dependencies */
1180 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1181 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1184 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1186 /* Tag current MODREF to prevent recursive loop */
1187 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1188 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1189 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1191 /* Recursively attach all DLLs this one depends on */
1192 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1194 if (!wm
->deps
[i
]) continue;
1195 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1198 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1199 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1200 &wm
->ldr
.InInitializationOrderModuleList
);
1202 /* Call DLL entry point */
1203 if (status
== STATUS_SUCCESS
)
1205 WINE_MODREF
*prev
= current_modref
;
1206 current_modref
= wm
;
1207 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1208 if (status
== STATUS_SUCCESS
)
1209 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1212 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1213 /* point to the name so LdrInitializeThunk can print it */
1214 last_failed_modref
= wm
;
1215 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1217 current_modref
= prev
;
1220 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1221 /* Remove recursion flag */
1222 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1224 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1229 /**********************************************************************
1230 * attach_implicitly_loaded_dlls
1232 * Attach to the (builtin) dlls that have been implicitly loaded because
1233 * of a dependency at the Unix level, but not imported at the Win32 level.
1235 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1239 PLIST_ENTRY mark
, entry
;
1241 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1242 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1244 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1246 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1247 TRACE( "found implicitly loaded %s, attaching to it\n",
1248 debugstr_w(mod
->BaseDllName
.Buffer
));
1249 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1250 break; /* restart the search from the start */
1252 if (entry
== mark
) break; /* nothing found */
1257 /*************************************************************************
1260 * Send DLL process detach notifications. See the comment about calling
1261 * sequence at process_attach.
1263 static void process_detach(void)
1265 PLIST_ENTRY mark
, entry
;
1268 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1271 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1273 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1274 InInitializationOrderModuleList
);
1275 /* Check whether to detach this DLL */
1276 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1278 if ( mod
->LoadCount
&& !process_detaching
)
1281 /* Call detach notification */
1282 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1283 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1284 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1286 /* Restart at head of WINE_MODREF list, as entries might have
1287 been added and/or removed while performing the call ... */
1290 } while (entry
!= mark
);
1293 /*************************************************************************
1294 * MODULE_DllThreadAttach
1296 * Send DLL thread attach notifications. These are sent in the
1297 * reverse sequence of process detach notification.
1300 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1302 PLIST_ENTRY mark
, entry
;
1306 /* don't do any attach calls if process is exiting */
1307 if (process_detaching
) return STATUS_SUCCESS
;
1309 RtlEnterCriticalSection( &loader_section
);
1311 RtlAcquirePebLock();
1312 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
1313 RtlReleasePebLock();
1315 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1317 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1318 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1320 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1321 InInitializationOrderModuleList
);
1322 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1324 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1327 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1328 DLL_THREAD_ATTACH
, lpReserved
);
1332 RtlLeaveCriticalSection( &loader_section
);
1336 /******************************************************************
1337 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1340 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1343 NTSTATUS ret
= STATUS_SUCCESS
;
1345 RtlEnterCriticalSection( &loader_section
);
1347 wm
= get_modref( hModule
);
1348 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1349 ret
= STATUS_DLL_NOT_FOUND
;
1351 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1353 RtlLeaveCriticalSection( &loader_section
);
1358 /******************************************************************
1359 * LdrFindEntryForAddress (NTDLL.@)
1361 * The loader_section must be locked while calling this function
1363 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1365 PLIST_ENTRY mark
, entry
;
1368 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1369 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1371 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1372 if (mod
->BaseAddress
<= addr
&&
1373 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1376 return STATUS_SUCCESS
;
1378 if (mod
->BaseAddress
> addr
) break;
1380 return STATUS_NO_MORE_ENTRIES
;
1383 /******************************************************************
1384 * LdrLockLoaderLock (NTDLL.@)
1386 * Note: some flags are not implemented.
1387 * Flag 0x01 is used to raise exceptions on errors.
1389 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1391 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1393 if (result
) *result
= 0;
1394 if (magic
) *magic
= 0;
1395 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1396 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1397 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1401 if (!RtlTryEnterCriticalSection( &loader_section
))
1404 return STATUS_SUCCESS
;
1410 RtlEnterCriticalSection( &loader_section
);
1411 if (result
) *result
= 1;
1413 *magic
= GetCurrentThreadId();
1414 return STATUS_SUCCESS
;
1418 /******************************************************************
1419 * LdrUnlockLoaderUnlock (NTDLL.@)
1421 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1425 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1426 RtlLeaveCriticalSection( &loader_section
);
1428 return STATUS_SUCCESS
;
1432 /******************************************************************
1433 * LdrGetProcedureAddress (NTDLL.@)
1435 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1436 ULONG ord
, PVOID
*address
)
1438 IMAGE_EXPORT_DIRECTORY
*exports
;
1440 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1442 RtlEnterCriticalSection( &loader_section
);
1444 /* check if the module itself is invalid to return the proper error */
1445 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1446 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1447 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1449 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1450 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1451 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1455 ret
= STATUS_SUCCESS
;
1459 RtlLeaveCriticalSection( &loader_section
);
1464 /***********************************************************************
1467 * Check if a loaded native dll is a Wine fake dll.
1469 static BOOL
is_fake_dll( HANDLE handle
)
1471 static const char fakedll_signature
[] = "Wine placeholder DLL";
1472 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1473 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1475 LARGE_INTEGER offset
;
1477 offset
.QuadPart
= 0;
1478 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1479 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1480 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1481 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1482 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1487 /***********************************************************************
1488 * get_builtin_fullname
1490 * Build the full pathname for a builtin dll.
1492 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1494 static const WCHAR soW
[] = {'.','s','o',0};
1495 WCHAR
*p
, *fullname
;
1496 size_t i
, len
= strlen(filename
);
1498 /* check if path can correspond to the dll we have */
1499 if (path
&& (p
= strrchrW( path
, '\\' )))
1502 for (i
= 0; i
< len
; i
++)
1503 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1504 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1506 /* the filename matches, use path as the full path */
1508 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1510 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1517 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1518 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1520 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1521 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1522 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1523 ascii_to_unicode( p
, filename
, len
+ 1 );
1529 /*************************************************************************
1532 static BOOL
is_16bit_builtin( HMODULE module
)
1534 const IMAGE_EXPORT_DIRECTORY
*exports
;
1537 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1538 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1541 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1545 /***********************************************************************
1546 * load_builtin_callback
1548 * Load a library in memory; callback function for wine_dll_register
1550 static void load_builtin_callback( void *module
, const char *filename
)
1552 static const WCHAR emptyW
[1];
1553 IMAGE_NT_HEADERS
*nt
;
1556 const WCHAR
*load_path
;
1560 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1563 if (!(nt
= RtlImageNtHeader( module
)))
1565 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1566 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1570 virtual_create_builtin_view( module
);
1572 /* create the MODREF */
1574 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1576 ERR( "can't load %s\n", filename
);
1577 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1581 wm
= alloc_module( module
, fullname
);
1582 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1585 ERR( "can't load %s\n", filename
);
1586 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1589 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1591 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1592 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1593 is_16bit_builtin( module
))
1597 load_path
= builtin_load_info
->load_path
;
1598 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1599 if (!load_path
) load_path
= emptyW
;
1600 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1602 /* the module has only be inserted in the load & memory order lists */
1603 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1604 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1605 /* FIXME: free the modref */
1606 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1611 builtin_load_info
->wm
= wm
;
1612 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1614 /* send the DLL load event */
1616 SERVER_START_REQ( load_dll
)
1619 req
->base
= wine_server_client_ptr( module
);
1620 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1621 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1622 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1623 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1624 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1625 wine_server_call( req
);
1629 /* setup relay debugging entry points */
1630 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1634 /***********************************************************************
1635 * set_security_cookie
1637 * Create a random security cookie for buffer overflow protection. Make
1638 * sure it does not accidentally match the default cookie value.
1640 static void set_security_cookie( void *module
, SIZE_T len
)
1643 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1647 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1648 if (!loadcfg
) return;
1649 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1650 if (!loadcfg
->SecurityCookie
) return;
1651 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1652 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1654 WARN( "security cookie %p outside of image %p-%p\n",
1655 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1659 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1660 TRACE( "initializing security cookie %p\n", cookie
);
1662 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1665 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1666 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1667 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1668 *cookie
= RtlRandom( &seed
);
1669 #ifdef DEFAULT_SECURITY_COOKIE_64
1670 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1672 *cookie
= RtlRandom( &seed
);
1673 /* fill up, but keep the highest word clear */
1674 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1682 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1684 IMAGE_NT_HEADERS
*nt
;
1686 IMAGE_BASE_RELOCATION
*rel
, *end
;
1687 const IMAGE_DATA_DIRECTORY
*relocs
;
1688 const IMAGE_SECTION_HEADER
*sec
;
1690 ULONG protect_old
[96], i
;
1692 nt
= RtlImageNtHeader( module
);
1693 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1695 assert( module
!= base
);
1697 /* no relocations are performed on non page-aligned binaries */
1698 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1699 return STATUS_SUCCESS
;
1701 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1702 return STATUS_SUCCESS
;
1704 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1706 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1708 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1710 return STATUS_CONFLICTING_ADDRESSES
;
1713 if (!relocs
->Size
) return STATUS_SUCCESS
;
1714 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1716 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1717 return STATUS_INVALID_IMAGE_FORMAT
;
1719 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1720 nt
->FileHeader
.SizeOfOptionalHeader
);
1721 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1723 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1724 SIZE_T size
= sec
[i
].SizeOfRawData
;
1725 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1726 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1729 TRACE( "relocating from %p-%p to %p-%p\n",
1730 base
, base
+ len
, module
, (char *)module
+ len
);
1732 rel
= get_rva( module
, relocs
->VirtualAddress
);
1733 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1734 delta
= (char *)module
- base
;
1736 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1738 if (rel
->VirtualAddress
>= len
)
1740 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1741 return STATUS_ACCESS_VIOLATION
;
1743 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1744 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1745 (USHORT
*)(rel
+ 1), delta
);
1746 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1749 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1751 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1752 SIZE_T size
= sec
[i
].SizeOfRawData
;
1753 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1754 &size
, protect_old
[i
], &protect_old
[i
] );
1757 return STATUS_SUCCESS
;
1760 /******************************************************************************
1761 * load_native_dll (internal)
1763 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1764 DWORD flags
, WINE_MODREF
** pwm
)
1769 IMAGE_NT_HEADERS
*nt
;
1774 TRACE("Trying native dll %s\n", debugstr_w(name
));
1777 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1778 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1779 if (status
!= STATUS_SUCCESS
) return status
;
1782 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1783 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_EXECUTE_READ
);
1785 /* perform base relocation, if necessary */
1787 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1788 status
= perform_relocations( module
, len
);
1790 if (status
!= STATUS_SUCCESS
)
1792 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1796 /* create the MODREF */
1798 if (!(wm
= alloc_module( module
, name
)))
1800 status
= STATUS_NO_MEMORY
;
1804 set_security_cookie( module
, len
);
1808 nt
= RtlImageNtHeader( module
);
1810 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1811 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1812 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1814 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1816 /* the module has only be inserted in the load & memory order lists */
1817 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1818 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1820 /* FIXME: there are several more dangling references
1821 * left. Including dlls loaded by this dll before the
1822 * failed one. Unrolling is rather difficult with the
1823 * current structure and we can leave them lying
1824 * around with no problems, so we don't care.
1825 * As these might reference our wm, we don't free it.
1831 /* send DLL load event */
1833 SERVER_START_REQ( load_dll
)
1835 req
->mapping
= wine_server_obj_handle( mapping
);
1836 req
->base
= wine_server_client_ptr( module
);
1837 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1838 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1839 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1840 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1841 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1842 wine_server_call( req
);
1846 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1848 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1850 wm
->ldr
.LoadCount
= 1;
1852 status
= STATUS_SUCCESS
;
1859 /***********************************************************************
1862 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1863 DWORD flags
, WINE_MODREF
** pwm
)
1865 char error
[256], dllname
[MAX_PATH
];
1866 const WCHAR
*name
, *p
;
1868 void *handle
= NULL
;
1869 struct builtin_load_info info
, *prev_info
;
1871 /* Fix the name in case we have a full path and extension */
1873 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1874 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1876 /* load_library will modify info.status. Note also that load_library can be
1877 * called several times, if the .so file we're loading has dependencies.
1878 * info.status will gather all the errors we may get while loading all these
1881 info
.load_path
= load_path
;
1882 info
.filename
= NULL
;
1883 info
.status
= STATUS_SUCCESS
;
1886 if (file
) /* we have a real file, try to load it */
1888 UNICODE_STRING nt_name
;
1889 ANSI_STRING unix_name
;
1891 TRACE("Trying built-in %s\n", debugstr_w(path
));
1893 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1894 return STATUS_DLL_NOT_FOUND
;
1896 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1898 RtlFreeUnicodeString( &nt_name
);
1899 return STATUS_DLL_NOT_FOUND
;
1901 prev_info
= builtin_load_info
;
1902 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1903 builtin_load_info
= &info
;
1904 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1905 builtin_load_info
= prev_info
;
1906 RtlFreeUnicodeString( &nt_name
);
1907 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1910 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1911 return STATUS_INVALID_IMAGE_FORMAT
;
1918 TRACE("Trying built-in %s\n", debugstr_w(name
));
1920 /* we don't want to depend on the current codepage here */
1921 len
= strlenW( name
) + 1;
1922 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1923 for (i
= 0; i
< len
; i
++)
1925 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1926 dllname
[i
] = (char)name
[i
];
1927 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1930 prev_info
= builtin_load_info
;
1931 builtin_load_info
= &info
;
1932 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1933 builtin_load_info
= prev_info
;
1938 /* The file does not exist -> WARN() */
1939 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1940 return STATUS_DLL_NOT_FOUND
;
1942 /* ERR() for all other errors (missing functions, ...) */
1943 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1944 return STATUS_PROCEDURE_NOT_FOUND
;
1948 if (info
.status
!= STATUS_SUCCESS
)
1950 wine_dll_unload( handle
);
1956 PLIST_ENTRY mark
, entry
;
1958 /* The constructor wasn't called, this means the .so is already
1959 * loaded under a different name. Try to find the wm for it. */
1961 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1962 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1964 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1965 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1967 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1968 TRACE( "Found %s at %p for builtin %s\n",
1969 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1973 wine_dll_unload( handle
); /* release the libdl refcount */
1974 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1975 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1979 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1980 info
.wm
->ldr
.LoadCount
= 1;
1981 info
.wm
->ldr
.SectionHandle
= handle
;
1985 return STATUS_SUCCESS
;
1989 /***********************************************************************
1992 * Find the full path (if any) of the dll from the activation context.
1994 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
1996 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
1997 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
1999 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2000 ACTCTX_SECTION_KEYED_DATA data
;
2001 UNICODE_STRING nameW
;
2003 SIZE_T needed
, size
= 1024;
2006 RtlInitUnicodeString( &nameW
, libname
);
2007 data
.cbSize
= sizeof(data
);
2008 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2009 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2011 if (status
!= STATUS_SUCCESS
) return status
;
2015 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2017 status
= STATUS_NO_MEMORY
;
2020 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2021 AssemblyDetailedInformationInActivationContext
,
2022 info
, size
, &needed
);
2023 if (status
== STATUS_SUCCESS
) break;
2024 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2025 RtlFreeHeap( GetProcessHeap(), 0, info
);
2027 /* restart with larger buffer */
2030 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2032 status
= STATUS_SXS_KEY_NOT_FOUND
;
2036 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2038 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2041 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2043 /* manifest name does not match directory name, so it's not a global
2044 * windows/winsxs manifest; use the manifest directory name instead */
2045 dirlen
= p
- info
->lpAssemblyManifestPath
;
2046 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2047 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2049 status
= STATUS_NO_MEMORY
;
2052 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2054 strcpyW( p
, libname
);
2059 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2060 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2062 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2064 status
= STATUS_NO_MEMORY
;
2067 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2069 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2070 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2071 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2072 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2074 strcpyW( p
, libname
);
2076 RtlFreeHeap( GetProcessHeap(), 0, info
);
2077 RtlReleaseActivationContext( data
.hActCtx
);
2082 /***********************************************************************
2085 * Find the file (or already loaded module) for a given dll name.
2087 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2088 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
2090 OBJECT_ATTRIBUTES attr
;
2092 UNICODE_STRING nt_name
;
2093 WCHAR
*file_part
, *ext
, *dllname
;
2096 /* first append .dll if needed */
2099 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2101 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2102 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2103 return STATUS_NO_MEMORY
;
2104 strcpyW( dllname
, libname
);
2105 strcatW( dllname
, dllW
);
2109 nt_name
.Buffer
= NULL
;
2111 if (!contains_path( libname
))
2114 WCHAR
*fullname
= NULL
;
2116 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2118 status
= find_actctx_dll( libname
, &fullname
);
2119 if (status
== STATUS_SUCCESS
)
2121 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2122 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2123 libname
= dllname
= fullname
;
2125 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2127 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2132 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2134 /* we need to search for it */
2135 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2138 if (len
>= *size
) goto overflow
;
2139 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
2141 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2143 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2144 return STATUS_NO_MEMORY
;
2146 attr
.Length
= sizeof(attr
);
2147 attr
.RootDirectory
= 0;
2148 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2149 attr
.ObjectName
= &nt_name
;
2150 attr
.SecurityDescriptor
= NULL
;
2151 attr
.SecurityQualityOfService
= NULL
;
2152 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2158 if (!contains_path( libname
))
2160 /* if libname doesn't contain a path at all, we simply return the name as is,
2161 * to be loaded as builtin */
2162 len
= strlenW(libname
) * sizeof(WCHAR
);
2163 if (len
>= *size
) goto overflow
;
2164 strcpyW( filename
, libname
);
2169 /* absolute path name, or relative path name but not found above */
2171 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2173 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2174 return STATUS_NO_MEMORY
;
2176 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2177 if (len
>= *size
) goto overflow
;
2178 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2179 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
2181 attr
.Length
= sizeof(attr
);
2182 attr
.RootDirectory
= 0;
2183 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2184 attr
.ObjectName
= &nt_name
;
2185 attr
.SecurityDescriptor
= NULL
;
2186 attr
.SecurityQualityOfService
= NULL
;
2187 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2190 RtlFreeUnicodeString( &nt_name
);
2191 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2192 return STATUS_SUCCESS
;
2195 RtlFreeUnicodeString( &nt_name
);
2196 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2197 *size
= len
+ sizeof(WCHAR
);
2198 return STATUS_BUFFER_TOO_SMALL
;
2202 /***********************************************************************
2203 * load_dll (internal)
2205 * Load a PE style module according to the load order.
2206 * The loader_section must be locked while calling this function.
2208 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2210 enum loadorder loadorder
;
2214 WINE_MODREF
*main_exe
;
2218 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2222 size
= sizeof(buffer
);
2225 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2226 if (nts
== STATUS_SUCCESS
) break;
2227 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2228 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2229 /* grow the buffer and retry */
2230 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2233 if (*pwm
) /* found already loaded module */
2235 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2237 TRACE("Found %s for %s at %p, count=%d\n",
2238 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2239 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2240 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2241 return STATUS_SUCCESS
;
2244 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2245 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2247 if (handle
&& is_fake_dll( handle
))
2249 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2257 nts
= STATUS_NO_MEMORY
;
2260 nts
= STATUS_DLL_NOT_FOUND
;
2263 case LO_NATIVE_BUILTIN
:
2264 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2267 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2268 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2269 /* not in PE format, maybe it's a builtin */
2270 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2272 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2273 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2276 case LO_BUILTIN_NATIVE
:
2277 case LO_DEFAULT
: /* default is builtin,native */
2278 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2279 if (!handle
) break; /* nothing else we can try */
2280 /* file is not a builtin library, try without using the specified file */
2281 if (nts
!= STATUS_SUCCESS
)
2282 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2283 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2284 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2286 /* stub-only dll, try native */
2287 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2288 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2289 nts
= STATUS_DLL_NOT_FOUND
;
2291 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2292 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2296 if (nts
== STATUS_SUCCESS
)
2298 /* Initialize DLL just loaded */
2299 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2300 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2301 (*pwm
)->ldr
.BaseAddress
);
2302 if (handle
) NtClose( handle
);
2303 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2307 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2308 if (handle
) NtClose( handle
);
2309 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2313 /******************************************************************
2314 * LdrLoadDll (NTDLL.@)
2316 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2317 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2322 RtlEnterCriticalSection( &loader_section
);
2324 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2325 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2327 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2329 nts
= process_attach( wm
, NULL
);
2330 if (nts
!= STATUS_SUCCESS
)
2332 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2336 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2338 RtlLeaveCriticalSection( &loader_section
);
2343 /******************************************************************
2344 * LdrGetDllHandle (NTDLL.@)
2346 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2354 RtlEnterCriticalSection( &loader_section
);
2356 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2359 size
= sizeof(buffer
);
2362 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2363 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2364 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2365 /* grow the buffer and retry */
2366 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2368 status
= STATUS_NO_MEMORY
;
2373 if (status
== STATUS_SUCCESS
)
2375 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2376 else status
= STATUS_DLL_NOT_FOUND
;
2379 RtlLeaveCriticalSection( &loader_section
);
2380 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2385 /******************************************************************
2386 * LdrAddRefDll (NTDLL.@)
2388 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2390 NTSTATUS ret
= STATUS_SUCCESS
;
2393 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2395 RtlEnterCriticalSection( &loader_section
);
2397 if ((wm
= get_modref( module
)))
2399 if (flags
& LDR_ADDREF_DLL_PIN
)
2400 wm
->ldr
.LoadCount
= -1;
2402 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2403 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2405 else ret
= STATUS_INVALID_PARAMETER
;
2407 RtlLeaveCriticalSection( &loader_section
);
2412 /***********************************************************************
2413 * LdrProcessRelocationBlock (NTDLL.@)
2415 * Apply relocations to a given page of a mapped PE image.
2417 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2418 USHORT
*relocs
, INT_PTR delta
)
2422 USHORT offset
= *relocs
& 0xfff;
2423 int type
= *relocs
>> 12;
2426 case IMAGE_REL_BASED_ABSOLUTE
:
2428 case IMAGE_REL_BASED_HIGH
:
2429 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2431 case IMAGE_REL_BASED_LOW
:
2432 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2434 case IMAGE_REL_BASED_HIGHLOW
:
2435 *(int *)((char *)page
+ offset
) += delta
;
2438 case IMAGE_REL_BASED_DIR64
:
2439 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2441 #elif defined(__arm__)
2442 case IMAGE_REL_BASED_THUMB_MOV32
:
2444 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2445 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2446 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2449 if ((inst
& 0x8000fbf0) != 0x0000f240)
2450 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2452 imm16
+= LOWORD(delta
);
2453 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2454 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2455 ((imm16
>> 12) & 0x000f) +
2456 ((imm16
<< 20) & 0x70000000) +
2457 ((imm16
<< 16) & 0xff0000);
2461 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2462 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2463 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2465 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2466 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2470 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2471 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2472 ((imm16
>> 1) & 0x0400) +
2473 ((imm16
>> 12) & 0x000f) +
2474 ((imm16
<< 20) & 0x70000000) +
2475 ((imm16
<< 16) & 0xff0000);
2481 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2486 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2490 /******************************************************************
2491 * LdrQueryProcessModuleInformation
2494 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2495 ULONG buf_size
, ULONG
* req_size
)
2497 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2498 ULONG size
= sizeof(ULONG
);
2499 NTSTATUS nts
= STATUS_SUCCESS
;
2502 PLIST_ENTRY mark
, entry
;
2506 smi
->ModulesCount
= 0;
2508 RtlEnterCriticalSection( &loader_section
);
2509 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2510 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2512 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2513 size
+= sizeof(*sm
);
2514 if (size
<= buf_size
)
2516 sm
->Reserved1
= 0; /* FIXME */
2517 sm
->Reserved2
= 0; /* FIXME */
2518 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2519 sm
->ImageSize
= mod
->SizeOfImage
;
2520 sm
->Flags
= mod
->Flags
;
2522 sm
->Rank
= 0; /* FIXME */
2523 sm
->Unknown
= 0; /* FIXME */
2525 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2526 str
.Buffer
= (char*)sm
->Name
;
2527 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2528 ptr
= strrchr(str
.Buffer
, '\\');
2529 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2531 smi
->ModulesCount
++;
2534 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2536 RtlLeaveCriticalSection( &loader_section
);
2538 if (req_size
) *req_size
= size
;
2544 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2550 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2552 RtlInitUnicodeString( &str
, name
);
2554 size
= sizeof(buffer
) - sizeof(WCHAR
);
2555 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2558 if (info
->Type
!= REG_DWORD
)
2560 buffer
[size
/ sizeof(WCHAR
)] = 0;
2561 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2563 else memcpy( value
, info
->Data
, sizeof(*value
) );
2567 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2568 void *data
, ULONG in_size
, ULONG
*out_size
)
2574 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2575 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2577 RtlInitUnicodeString( &str
, name
);
2579 size
= info_size
+ in_size
;
2580 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2581 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2582 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2583 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2585 if (out_size
) *out_size
= info
->DataLength
;
2586 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2588 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2593 /******************************************************************
2594 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2596 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2597 void *data
, ULONG in_size
, ULONG
*out_size
)
2599 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2600 'S','o','f','t','w','a','r','e','\\',
2601 'M','i','c','r','o','s','o','f','t','\\',
2602 'W','i','n','d','o','w','s',' ','N','T','\\',
2603 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2604 'I','m','a','g','e',' ','F','i','l','e',' ',
2605 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2606 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2607 OBJECT_ATTRIBUTES attr
;
2608 UNICODE_STRING name_str
;
2614 attr
.Length
= sizeof(attr
);
2615 attr
.RootDirectory
= 0;
2616 attr
.ObjectName
= &name_str
;
2617 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2618 attr
.SecurityDescriptor
= NULL
;
2619 attr
.SecurityQualityOfService
= NULL
;
2621 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2622 else p
= key
->Buffer
;
2623 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2624 name_str
.Buffer
= path
;
2625 name_str
.Length
= sizeof(optionsW
) + len
;
2626 name_str
.MaximumLength
= name_str
.Length
;
2627 memcpy( path
, optionsW
, sizeof(optionsW
) );
2628 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2629 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2631 if (type
== REG_DWORD
)
2633 if (out_size
) *out_size
= sizeof(ULONG
);
2634 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2635 else status
= STATUS_BUFFER_OVERFLOW
;
2637 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2644 /******************************************************************
2645 * RtlDllShutdownInProgress (NTDLL.@)
2647 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2649 return process_detaching
;
2652 /****************************************************************************
2653 * LdrResolveDelayLoadedAPI (NTDLL.@)
2655 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2656 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2657 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2659 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2660 DELAYLOAD_INFO delayinfo
;
2668 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2670 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2671 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2672 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2673 name
= get_rva(base
, desc
->DllNameRVA
);
2678 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2680 nts
= STATUS_NO_MEMORY
;
2683 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2684 RtlFreeUnicodeString(&mod
);
2688 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2689 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2692 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2695 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2696 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2700 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2705 delayinfo
.Size
= sizeof(delayinfo
);
2706 delayinfo
.DelayloadDescriptor
= desc
;
2707 delayinfo
.ThunkAddress
= addr
;
2708 delayinfo
.TargetDllName
= name
;
2709 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2710 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2711 delayinfo
.TargetModuleBase
= *phmod
;
2712 delayinfo
.Unused
= NULL
;
2713 delayinfo
.LastError
= nts
;
2714 return dllhook(4, &delayinfo
);
2717 /******************************************************************
2718 * LdrShutdownProcess (NTDLL.@)
2721 void WINAPI
LdrShutdownProcess(void)
2724 process_detaching
= TRUE
;
2729 /******************************************************************
2730 * RtlExitUserProcess (NTDLL.@)
2732 void WINAPI
RtlExitUserProcess( DWORD status
)
2734 RtlEnterCriticalSection( &loader_section
);
2735 RtlAcquirePebLock();
2736 NtTerminateProcess( 0, status
);
2737 LdrShutdownProcess();
2738 NtTerminateProcess( GetCurrentProcess(), status
);
2742 /******************************************************************
2743 * LdrShutdownThread (NTDLL.@)
2746 void WINAPI
LdrShutdownThread(void)
2748 PLIST_ENTRY mark
, entry
;
2755 /* don't do any detach calls if process is exiting */
2756 if (process_detaching
) return;
2758 RtlEnterCriticalSection( &loader_section
);
2760 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2761 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2763 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2764 InInitializationOrderModuleList
);
2765 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2767 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2770 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2771 DLL_THREAD_DETACH
, NULL
);
2774 RtlAcquirePebLock();
2775 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2776 RtlReleasePebLock();
2778 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2780 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2781 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2783 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2784 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2785 RtlLeaveCriticalSection( &loader_section
);
2789 /***********************************************************************
2793 static void free_modref( WINE_MODREF
*wm
)
2795 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2796 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2797 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2798 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2800 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2801 if (!TRACE_ON(module
))
2802 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2803 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2804 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2806 SERVER_START_REQ( unload_dll
)
2808 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2809 wine_server_call( req
);
2813 free_tls_slot( &wm
->ldr
);
2814 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2815 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2816 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2817 if (cached_modref
== wm
) cached_modref
= NULL
;
2818 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2819 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2820 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2823 /***********************************************************************
2824 * MODULE_FlushModrefs
2826 * Remove all unused modrefs and call the internal unloading routines
2827 * for the library type.
2829 * The loader_section must be locked while calling this function.
2831 static void MODULE_FlushModrefs(void)
2833 PLIST_ENTRY mark
, entry
, prev
;
2837 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2838 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2840 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2841 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2842 prev
= entry
->Blink
;
2843 if (!mod
->LoadCount
) free_modref( wm
);
2846 /* check load order list too for modules that haven't been initialized yet */
2847 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2848 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2850 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2851 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2852 prev
= entry
->Blink
;
2853 if (!mod
->LoadCount
) free_modref( wm
);
2857 /***********************************************************************
2858 * MODULE_DecRefCount
2860 * The loader_section must be locked while calling this function.
2862 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2866 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2869 if ( wm
->ldr
.LoadCount
<= 0 )
2872 --wm
->ldr
.LoadCount
;
2873 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2875 if ( wm
->ldr
.LoadCount
== 0 )
2877 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2879 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2881 MODULE_DecRefCount( wm
->deps
[i
] );
2883 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2887 /******************************************************************
2888 * LdrUnloadDll (NTDLL.@)
2892 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2895 NTSTATUS retv
= STATUS_SUCCESS
;
2897 if (process_detaching
) return retv
;
2899 TRACE("(%p)\n", hModule
);
2901 RtlEnterCriticalSection( &loader_section
);
2904 if ((wm
= get_modref( hModule
)) != NULL
)
2906 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2908 /* Recursively decrement reference counts */
2909 MODULE_DecRefCount( wm
);
2911 /* Call process detach notifications */
2912 if ( free_lib_count
<= 1 )
2915 MODULE_FlushModrefs();
2921 retv
= STATUS_DLL_NOT_FOUND
;
2925 RtlLeaveCriticalSection( &loader_section
);
2930 /***********************************************************************
2931 * RtlImageNtHeader (NTDLL.@)
2933 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2935 IMAGE_NT_HEADERS
*ret
;
2939 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2942 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2944 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2945 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2957 /***********************************************************************
2958 * attach_process_dlls
2960 * Initial attach to all the dlls loaded by the process.
2962 static NTSTATUS
attach_process_dlls( void *wm
)
2966 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2968 RtlEnterCriticalSection( &loader_section
);
2969 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2971 if (last_failed_modref
)
2972 ERR( "%s failed to initialize, aborting\n",
2973 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2976 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2977 RtlLeaveCriticalSection( &loader_section
);
2982 /***********************************************************************
2983 * load_global_options
2985 static void load_global_options(void)
2987 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
2988 'S','y','s','t','e','m','\\',
2989 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2990 'C','o','n','t','r','o','l','\\',
2991 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2992 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2993 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};
2994 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2995 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2996 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};
2997 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};
2999 OBJECT_ATTRIBUTES attr
;
3000 UNICODE_STRING name_str
;
3004 attr
.Length
= sizeof(attr
);
3005 attr
.RootDirectory
= 0;
3006 attr
.ObjectName
= &name_str
;
3007 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3008 attr
.SecurityDescriptor
= NULL
;
3009 attr
.SecurityQualityOfService
= NULL
;
3010 RtlInitUnicodeString( &name_str
, sessionW
);
3012 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3014 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3016 query_dword_option( hkey
, critsectW
, &value
);
3017 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3019 query_dword_option( hkey
, heapresW
, &value
);
3020 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3022 query_dword_option( hkey
, heapcommitW
, &value
);
3023 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3025 query_dword_option( hkey
, decommittotalW
, &value
);
3026 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3028 query_dword_option( hkey
, decommitfreeW
, &value
);
3029 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3035 /***********************************************************************
3038 static void start_process( void *kernel_start
)
3040 call_thread_entry_point( kernel_start
, NtCurrentTeb()->Peb
);
3043 /******************************************************************
3044 * LdrInitializeThunk (NTDLL.@)
3047 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3048 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3050 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3054 PEB
*peb
= NtCurrentTeb()->Peb
;
3056 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3058 /* allocate the modref for the main exe (if not already done) */
3059 wm
= get_modref( peb
->ImageBaseAddress
);
3061 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3063 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3067 peb
->LoaderLock
= &loader_section
;
3068 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3069 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3070 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3071 version_init( wm
->ldr
.FullDllName
.Buffer
);
3072 virtual_set_large_address_space();
3074 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3075 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3077 /* the main exe needs to be the first in the load order list */
3078 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3079 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3081 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
3082 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
3085 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3086 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
3087 heap_set_debug_flags( GetProcessHeap() );
3089 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
3090 if (status
!= STATUS_SUCCESS
) goto error
;
3092 virtual_release_address_space();
3093 virtual_clear_thread_stack();
3094 wine_switch_to_stack( start_process
, kernel_start
, NtCurrentTeb()->Tib
.StackBase
);
3097 ERR( "Main exe initialization for %s failed, status %x\n",
3098 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3099 NtTerminateProcess( GetCurrentProcess(), status
);
3103 /***********************************************************************
3104 * RtlImageDirectoryEntryToData (NTDLL.@)
3106 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3108 const IMAGE_NT_HEADERS
*nt
;
3111 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
3113 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
3116 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3117 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3119 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3121 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3122 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3123 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3124 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3126 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3128 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3130 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3131 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3132 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3133 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3137 /* not mapped as image, need to find the section containing the virtual address */
3138 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3142 /***********************************************************************
3143 * RtlImageRvaToSection (NTDLL.@)
3145 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3146 HMODULE module
, DWORD rva
)
3149 const IMAGE_SECTION_HEADER
*sec
;
3151 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3152 nt
->FileHeader
.SizeOfOptionalHeader
);
3153 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3155 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3156 return (PIMAGE_SECTION_HEADER
)sec
;
3162 /***********************************************************************
3163 * RtlImageRvaToVa (NTDLL.@)
3165 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3166 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3168 IMAGE_SECTION_HEADER
*sec
;
3170 if (section
&& *section
) /* try this section first */
3173 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3176 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3178 if (section
) *section
= sec
;
3179 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3183 /***********************************************************************
3184 * RtlPcToFileHeader (NTDLL.@)
3186 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3191 RtlEnterCriticalSection( &loader_section
);
3192 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3193 RtlLeaveCriticalSection( &loader_section
);
3199 /***********************************************************************
3200 * NtLoadDriver (NTDLL.@)
3201 * ZwLoadDriver (NTDLL.@)
3203 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3205 FIXME("(%p), stub!\n",DriverServiceName
);
3206 return STATUS_NOT_IMPLEMENTED
;
3210 /***********************************************************************
3211 * NtUnloadDriver (NTDLL.@)
3212 * ZwUnloadDriver (NTDLL.@)
3214 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3216 FIXME("(%p), stub!\n",DriverServiceName
);
3217 return STATUS_NOT_IMPLEMENTED
;
3221 /******************************************************************
3224 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3226 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3231 /******************************************************************
3232 * __wine_init_windows_dir (NTDLL.@)
3234 * Windows and system dir initialization once kernel32 has been loaded.
3236 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
3238 PLIST_ENTRY mark
, entry
;
3241 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
3242 DIR_init_windows_dir( windir
, sysdir
);
3244 /* prepend the system dir to the name of the already created modules */
3245 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3246 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3248 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
3250 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
3252 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
3253 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
3254 if (!buffer
) continue;
3255 strcpyW( buffer
, system_dir
.Buffer
);
3256 p
= buffer
+ strlenW( buffer
);
3257 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
3258 strcpyW( p
, mod
->FullDllName
.Buffer
);
3259 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
3260 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
3265 /***********************************************************************
3266 * __wine_process_init
3268 void __wine_process_init(void)
3270 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3274 ANSI_STRING func_name
;
3275 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3277 main_exe_file
= thread_init();
3279 /* retrieve current umask */
3280 FILE_umask
= umask(0777);
3281 umask( FILE_umask
);
3283 load_global_options();
3285 /* setup the load callback and create ntdll modref */
3286 wine_dll_set_callback( load_builtin_callback
);
3288 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3290 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3293 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3294 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3296 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3297 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3298 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3300 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);