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 BOOL
import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
, WINE_MODREF
**pwm
)
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 if (!import_list
->u1
.Ordinal
)
591 WARN( "Skipping unused import %s\n", name
);
596 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
598 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
600 ascii_to_unicode( buffer
, name
, len
);
602 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
604 else /* need to allocate a larger buffer */
606 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
607 if (!ptr
) return FALSE
;
608 ascii_to_unicode( ptr
, name
, len
);
610 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
611 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
616 if (status
== STATUS_DLL_NOT_FOUND
)
617 ERR("Library %s (which is needed by %s) not found\n",
618 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
620 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
621 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
625 /* unprotect the import address table since it can be located in
626 * readonly section */
627 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
628 protect_base
= thunk_list
;
629 protect_size
*= sizeof(*thunk_list
);
630 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
631 &protect_size
, PAGE_READWRITE
, &protect_old
);
633 imp_mod
= wmImp
->ldr
.BaseAddress
;
634 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
638 /* set all imported function to deadbeef */
639 while (import_list
->u1
.Ordinal
)
641 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
643 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
644 WARN("No implementation for %s.%d", name
, ordinal
);
645 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
649 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
650 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
651 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
653 WARN(" imported from %s, allocating stub %p\n",
654 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
655 (void *)thunk_list
->u1
.Function
);
662 while (import_list
->u1
.Ordinal
)
664 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
666 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
668 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
669 ordinal
- exports
->Base
, load_path
);
670 if (!thunk_list
->u1
.Function
)
672 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
673 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
674 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
675 (void *)thunk_list
->u1
.Function
);
677 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
679 else /* import by name */
681 IMAGE_IMPORT_BY_NAME
*pe_name
;
682 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
683 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
684 (const char*)pe_name
->Name
,
685 pe_name
->Hint
, load_path
);
686 if (!thunk_list
->u1
.Function
)
688 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
689 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
690 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
691 (void *)thunk_list
->u1
.Function
);
693 TRACE_(imports
)("--- %s %s.%d = %p\n",
694 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
701 /* restore old protection of the import address table */
702 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, &protect_old
);
708 /***********************************************************************
709 * create_module_activation_context
711 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
714 LDR_RESOURCE_INFO info
;
715 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
717 info
.Type
= RT_MANIFEST
;
718 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
720 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
723 ctx
.cbSize
= sizeof(ctx
);
725 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
726 ctx
.hModule
= module
->BaseAddress
;
727 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
728 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
734 /*************************************************************************
735 * is_dll_native_subsystem
737 * Check if dll is a proper native driver.
738 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
739 * while being perfectly normal DLLs. This heuristic should catch such breakages.
741 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
743 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
744 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
745 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
749 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
750 if (nt
->OptionalHeader
.SectionAlignment
< page_size
) return TRUE
;
752 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
753 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
755 for (i
= 0; imports
[i
].Name
; i
++)
757 const char *name
= get_rva( module
, imports
[i
].Name
);
758 DWORD len
= strlen(name
);
759 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
760 ascii_to_unicode( buffer
, name
, len
+ 1 );
761 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
763 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
771 /*************************************************************************
774 * Allocate a TLS slot for a newly-loaded module.
775 * The loader_section must be locked while calling this function.
777 static SHORT
alloc_tls_slot( LDR_MODULE
*mod
)
779 const IMAGE_TLS_DIRECTORY
*dir
;
784 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
787 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
788 if (!size
&& !dir
->SizeOfZeroFill
&& !dir
->AddressOfCallBacks
) return -1;
790 for (i
= 0; i
< tls_module_count
; i
++)
792 if (!tls_dirs
[i
].StartAddressOfRawData
&& !tls_dirs
[i
].EndAddressOfRawData
&&
793 !tls_dirs
[i
].SizeOfZeroFill
&& !tls_dirs
[i
].AddressOfCallBacks
)
797 TRACE( "module %p data %p-%p zerofill %u index %p callback %p flags %x -> slot %u\n", mod
->BaseAddress
,
798 (void *)dir
->StartAddressOfRawData
, (void *)dir
->EndAddressOfRawData
, dir
->SizeOfZeroFill
,
799 (void *)dir
->AddressOfIndex
, (void *)dir
->AddressOfCallBacks
, dir
->Characteristics
, i
);
801 if (i
== tls_module_count
)
803 UINT new_count
= max( 32, tls_module_count
* 2 );
806 new_ptr
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*tls_dirs
) );
808 new_ptr
= RtlReAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, tls_dirs
,
809 new_count
* sizeof(*tls_dirs
) );
810 if (!new_ptr
) return -1;
812 /* resize the pointer block in all running threads */
813 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
815 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
816 void **old
= teb
->ThreadLocalStoragePointer
;
817 void **new = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
, new_count
* sizeof(*new));
820 if (old
) memcpy( new, old
, tls_module_count
* sizeof(*new) );
821 teb
->ThreadLocalStoragePointer
= new;
822 TRACE( "thread %04lx tls block %p -> %p\n", (ULONG_PTR
)teb
->ClientId
.UniqueThread
, old
, new );
823 /* FIXME: can't free old block here, should be freed at thread exit */
827 tls_module_count
= new_count
;
830 /* allocate the data block in all running threads */
831 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
833 TEB
*teb
= CONTAINING_RECORD( entry
, TEB
, TlsLinks
);
835 if (!(new_ptr
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
))) return -1;
836 memcpy( new_ptr
, (void *)dir
->StartAddressOfRawData
, size
);
837 memset( (char *)new_ptr
+ size
, 0, dir
->SizeOfZeroFill
);
839 TRACE( "thread %04lx slot %u: %u/%u bytes at %p\n",
840 (ULONG_PTR
)teb
->ClientId
.UniqueThread
, i
, size
, dir
->SizeOfZeroFill
, new_ptr
);
842 RtlFreeHeap( GetProcessHeap(), 0,
843 interlocked_xchg_ptr( (void **)teb
->ThreadLocalStoragePointer
+ i
, new_ptr
));
846 *(DWORD
*)dir
->AddressOfIndex
= i
;
852 /*************************************************************************
855 * Free the module TLS slot on unload.
856 * The loader_section must be locked while calling this function.
858 static void free_tls_slot( LDR_MODULE
*mod
)
860 ULONG i
= (USHORT
)mod
->TlsIndex
;
862 if (mod
->TlsIndex
== -1) return;
863 assert( i
< tls_module_count
);
864 memset( &tls_dirs
[i
], 0, sizeof(tls_dirs
[i
]) );
868 /****************************************************************
871 * Fixup all imports of a given module.
872 * The loader_section must be locked while calling this function.
874 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
877 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
883 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
884 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
886 wm
->ldr
.TlsIndex
= alloc_tls_slot( &wm
->ldr
);
888 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
889 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
890 return STATUS_SUCCESS
;
893 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
895 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
897 if (!create_module_activation_context( &wm
->ldr
))
898 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
900 /* Allocate module dependency list */
901 wm
->nDeps
= nb_imports
;
902 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
904 /* load the imported modules. They are automatically
905 * added to the modref list of the process.
907 prev
= current_modref
;
909 status
= STATUS_SUCCESS
;
910 for (i
= 0; i
< nb_imports
; i
++)
912 if (!import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
, &wm
->deps
[i
] ))
915 status
= STATUS_DLL_NOT_FOUND
;
918 current_modref
= prev
;
919 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
924 /*************************************************************************
927 * Allocate a WINE_MODREF structure and add it to the process list
928 * The loader_section must be locked while calling this function.
930 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
934 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
935 PLIST_ENTRY entry
, mark
;
937 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
942 wm
->ldr
.BaseAddress
= hModule
;
943 wm
->ldr
.EntryPoint
= NULL
;
944 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
945 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
946 wm
->ldr
.TlsIndex
= -1;
947 wm
->ldr
.LoadCount
= 1;
948 wm
->ldr
.SectionHandle
= NULL
;
949 wm
->ldr
.CheckSum
= 0;
950 wm
->ldr
.TimeDateStamp
= 0;
951 wm
->ldr
.ActivationContext
= 0;
953 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
954 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
955 else p
= wm
->ldr
.FullDllName
.Buffer
;
956 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
958 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) || !is_dll_native_subsystem( hModule
, nt
, p
))
960 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
961 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
962 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
963 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
966 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
967 &wm
->ldr
.InLoadOrderModuleList
);
969 /* insert module in MemoryList, sorted in increasing base addresses */
970 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
971 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
973 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
976 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
977 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
978 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
979 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
981 /* wait until init is called for inserting into this list */
982 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
983 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
985 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
987 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
988 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
989 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
995 /*************************************************************************
998 * Allocate the per-thread structure for module TLS storage.
1000 static NTSTATUS
alloc_thread_tls(void)
1005 if (!tls_module_count
) return STATUS_SUCCESS
;
1007 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY
,
1008 tls_module_count
* sizeof(*pointers
) )))
1009 return STATUS_NO_MEMORY
;
1011 for (i
= 0; i
< tls_module_count
; i
++)
1013 const IMAGE_TLS_DIRECTORY
*dir
= &tls_dirs
[i
];
1016 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
1017 if (!size
&& !dir
->SizeOfZeroFill
) continue;
1019 if (!(pointers
[i
] = RtlAllocateHeap( GetProcessHeap(), 0, size
+ dir
->SizeOfZeroFill
)))
1021 while (i
) RtlFreeHeap( GetProcessHeap(), 0, pointers
[--i
] );
1022 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
1023 return STATUS_NO_MEMORY
;
1025 memcpy( pointers
[i
], (void *)dir
->StartAddressOfRawData
, size
);
1026 memset( (char *)pointers
[i
] + size
, 0, dir
->SizeOfZeroFill
);
1028 TRACE( "thread %04x slot %u: %u/%u bytes at %p\n",
1029 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
, pointers
[i
] );
1031 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
1032 return STATUS_SUCCESS
;
1036 /*************************************************************************
1037 * call_tls_callbacks
1039 static void call_tls_callbacks( HMODULE module
, UINT reason
)
1041 const IMAGE_TLS_DIRECTORY
*dir
;
1042 const PIMAGE_TLS_CALLBACK
*callback
;
1045 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
1046 if (!dir
|| !dir
->AddressOfCallBacks
) return;
1048 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
1050 if (TRACE_ON(relay
))
1053 DPRINTF( "%04x:", GetCurrentProcessId() );
1054 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1055 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1059 call_dll_entry_point( (DLLENTRYPROC
)*callback
, module
, reason
, NULL
);
1063 if (TRACE_ON(relay
))
1066 DPRINTF( "%04x:", GetCurrentProcessId() );
1067 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1068 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
1073 if (TRACE_ON(relay
))
1076 DPRINTF( "%04x:", GetCurrentProcessId() );
1077 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
1078 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
1084 /*************************************************************************
1087 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
1090 NTSTATUS status
= STATUS_SUCCESS
;
1091 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
1092 void *module
= wm
->ldr
.BaseAddress
;
1095 /* Skip calls for modules loaded with special load flags */
1097 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
1098 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
1099 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return STATUS_SUCCESS
;
1101 if (TRACE_ON(relay
))
1103 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
1104 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
1105 mod_name
[len
/ sizeof(WCHAR
)] = 0;
1107 DPRINTF( "%04x:", GetCurrentProcessId() );
1108 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1109 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1110 reason_names
[reason
], lpReserved
);
1112 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
1113 reason_names
[reason
], lpReserved
);
1117 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
1119 status
= STATUS_DLL_INIT_FAILED
;
1123 if (TRACE_ON(relay
))
1126 DPRINTF( "%04x:", GetCurrentProcessId() );
1127 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1128 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
1130 status
= GetExceptionCode();
1134 /* The state of the module list may have changed due to the call
1135 to the dll. We cannot assume that this module has not been
1137 if (TRACE_ON(relay
))
1140 DPRINTF( "%04x:", GetCurrentProcessId() );
1141 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1142 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
1143 reason_names
[reason
], lpReserved
, retv
);
1145 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1151 /*************************************************************************
1154 * Send the process attach notification to all DLLs the given module
1155 * depends on (recursively). This is somewhat complicated due to the fact that
1157 * - we have to respect the module dependencies, i.e. modules implicitly
1158 * referenced by another module have to be initialized before the module
1159 * itself can be initialized
1161 * - the initialization routine of a DLL can itself call LoadLibrary,
1162 * thereby introducing a whole new set of dependencies (even involving
1163 * the 'old' modules) at any time during the whole process
1165 * (Note that this routine can be recursively entered not only directly
1166 * from itself, but also via LoadLibrary from one of the called initialization
1169 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1170 * the process *detach* notifications to be sent in the correct order.
1171 * This must not only take into account module dependencies, but also
1172 * 'hidden' dependencies created by modules calling LoadLibrary in their
1173 * attach notification routine.
1175 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1176 * list after the attach notification has returned. This implies that the
1177 * detach notifications are called in the reverse of the sequence the attach
1178 * notifications *returned*.
1180 * The loader_section must be locked while calling this function.
1182 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1184 NTSTATUS status
= STATUS_SUCCESS
;
1188 if (process_detaching
) return status
;
1190 /* prevent infinite recursion in case of cyclical dependencies */
1191 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1192 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1195 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1197 /* Tag current MODREF to prevent recursive loop */
1198 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1199 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1200 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1202 /* Recursively attach all DLLs this one depends on */
1203 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1205 if (!wm
->deps
[i
]) continue;
1206 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1209 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1210 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1211 &wm
->ldr
.InInitializationOrderModuleList
);
1213 /* Call DLL entry point */
1214 if (status
== STATUS_SUCCESS
)
1216 WINE_MODREF
*prev
= current_modref
;
1217 current_modref
= wm
;
1218 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1219 if (status
== STATUS_SUCCESS
)
1220 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1223 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1224 /* point to the name so LdrInitializeThunk can print it */
1225 last_failed_modref
= wm
;
1226 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1228 current_modref
= prev
;
1231 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1232 /* Remove recursion flag */
1233 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1235 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1240 /**********************************************************************
1241 * attach_implicitly_loaded_dlls
1243 * Attach to the (builtin) dlls that have been implicitly loaded because
1244 * of a dependency at the Unix level, but not imported at the Win32 level.
1246 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1250 PLIST_ENTRY mark
, entry
;
1252 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1253 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1255 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1257 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1258 TRACE( "found implicitly loaded %s, attaching to it\n",
1259 debugstr_w(mod
->BaseDllName
.Buffer
));
1260 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1261 break; /* restart the search from the start */
1263 if (entry
== mark
) break; /* nothing found */
1268 /*************************************************************************
1271 * Send DLL process detach notifications. See the comment about calling
1272 * sequence at process_attach.
1274 static void process_detach(void)
1276 PLIST_ENTRY mark
, entry
;
1279 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1282 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1284 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1285 InInitializationOrderModuleList
);
1286 /* Check whether to detach this DLL */
1287 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1289 if ( mod
->LoadCount
&& !process_detaching
)
1292 /* Call detach notification */
1293 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1294 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1295 DLL_PROCESS_DETACH
, ULongToPtr(process_detaching
) );
1297 /* Restart at head of WINE_MODREF list, as entries might have
1298 been added and/or removed while performing the call ... */
1301 } while (entry
!= mark
);
1304 /*************************************************************************
1305 * MODULE_DllThreadAttach
1307 * Send DLL thread attach notifications. These are sent in the
1308 * reverse sequence of process detach notification.
1311 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1313 PLIST_ENTRY mark
, entry
;
1317 /* don't do any attach calls if process is exiting */
1318 if (process_detaching
) return STATUS_SUCCESS
;
1320 RtlEnterCriticalSection( &loader_section
);
1322 RtlAcquirePebLock();
1323 InsertHeadList( &tls_links
, &NtCurrentTeb()->TlsLinks
);
1324 RtlReleasePebLock();
1326 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1328 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1329 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1331 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1332 InInitializationOrderModuleList
);
1333 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1335 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1338 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1339 DLL_THREAD_ATTACH
, lpReserved
);
1343 RtlLeaveCriticalSection( &loader_section
);
1347 /******************************************************************
1348 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1351 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1354 NTSTATUS ret
= STATUS_SUCCESS
;
1356 RtlEnterCriticalSection( &loader_section
);
1358 wm
= get_modref( hModule
);
1359 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1360 ret
= STATUS_DLL_NOT_FOUND
;
1362 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1364 RtlLeaveCriticalSection( &loader_section
);
1369 /******************************************************************
1370 * LdrFindEntryForAddress (NTDLL.@)
1372 * The loader_section must be locked while calling this function
1374 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1376 PLIST_ENTRY mark
, entry
;
1379 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1380 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1382 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1383 if (mod
->BaseAddress
<= addr
&&
1384 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1387 return STATUS_SUCCESS
;
1389 if (mod
->BaseAddress
> addr
) break;
1391 return STATUS_NO_MORE_ENTRIES
;
1394 /******************************************************************
1395 * LdrLockLoaderLock (NTDLL.@)
1397 * Note: some flags are not implemented.
1398 * Flag 0x01 is used to raise exceptions on errors.
1400 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG_PTR
*magic
)
1402 if (flags
& ~0x2) FIXME( "flags %x not supported\n", flags
);
1404 if (result
) *result
= 0;
1405 if (magic
) *magic
= 0;
1406 if (flags
& ~0x3) return STATUS_INVALID_PARAMETER_1
;
1407 if (!result
&& (flags
& 0x2)) return STATUS_INVALID_PARAMETER_2
;
1408 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1412 if (!RtlTryEnterCriticalSection( &loader_section
))
1415 return STATUS_SUCCESS
;
1421 RtlEnterCriticalSection( &loader_section
);
1422 if (result
) *result
= 1;
1424 *magic
= GetCurrentThreadId();
1425 return STATUS_SUCCESS
;
1429 /******************************************************************
1430 * LdrUnlockLoaderUnlock (NTDLL.@)
1432 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG_PTR magic
)
1436 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1437 RtlLeaveCriticalSection( &loader_section
);
1439 return STATUS_SUCCESS
;
1443 /******************************************************************
1444 * LdrGetProcedureAddress (NTDLL.@)
1446 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1447 ULONG ord
, PVOID
*address
)
1449 IMAGE_EXPORT_DIRECTORY
*exports
;
1451 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1453 RtlEnterCriticalSection( &loader_section
);
1455 /* check if the module itself is invalid to return the proper error */
1456 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1457 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1458 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1460 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1461 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1462 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1466 ret
= STATUS_SUCCESS
;
1470 RtlLeaveCriticalSection( &loader_section
);
1475 /***********************************************************************
1478 * Check if a loaded native dll is a Wine fake dll.
1480 static BOOL
is_fake_dll( HANDLE handle
)
1482 static const char fakedll_signature
[] = "Wine placeholder DLL";
1483 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1484 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1486 LARGE_INTEGER offset
;
1488 offset
.QuadPart
= 0;
1489 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1490 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1491 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1492 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1493 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1498 /***********************************************************************
1499 * get_builtin_fullname
1501 * Build the full pathname for a builtin dll.
1503 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1505 static const WCHAR soW
[] = {'.','s','o',0};
1506 WCHAR
*p
, *fullname
;
1507 size_t i
, len
= strlen(filename
);
1509 /* check if path can correspond to the dll we have */
1510 if (path
&& (p
= strrchrW( path
, '\\' )))
1513 for (i
= 0; i
< len
; i
++)
1514 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1515 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1517 /* the filename matches, use path as the full path */
1519 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1521 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1528 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1529 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1531 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1532 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1533 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1534 ascii_to_unicode( p
, filename
, len
+ 1 );
1540 /*************************************************************************
1543 static BOOL
is_16bit_builtin( HMODULE module
)
1545 const IMAGE_EXPORT_DIRECTORY
*exports
;
1548 if (!(exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1549 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1552 return find_named_export( module
, exports
, exp_size
, "__wine_spec_dos_header", -1, NULL
) != NULL
;
1556 /***********************************************************************
1557 * load_builtin_callback
1559 * Load a library in memory; callback function for wine_dll_register
1561 static void load_builtin_callback( void *module
, const char *filename
)
1563 static const WCHAR emptyW
[1];
1564 IMAGE_NT_HEADERS
*nt
;
1567 const WCHAR
*load_path
;
1571 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1574 if (!(nt
= RtlImageNtHeader( module
)))
1576 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1577 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1581 virtual_create_builtin_view( module
);
1583 /* create the MODREF */
1585 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1587 ERR( "can't load %s\n", filename
);
1588 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1592 wm
= alloc_module( module
, fullname
);
1593 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1596 ERR( "can't load %s\n", filename
);
1597 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1600 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1602 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1603 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
||
1604 is_16bit_builtin( module
))
1608 load_path
= builtin_load_info
->load_path
;
1609 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1610 if (!load_path
) load_path
= emptyW
;
1611 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1613 /* the module has only be inserted in the load & memory order lists */
1614 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1615 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1616 /* FIXME: free the modref */
1617 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1622 builtin_load_info
->wm
= wm
;
1623 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1625 /* send the DLL load event */
1627 SERVER_START_REQ( load_dll
)
1630 req
->base
= wine_server_client_ptr( module
);
1631 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1632 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1633 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1634 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1635 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1636 wine_server_call( req
);
1640 /* setup relay debugging entry points */
1641 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1645 /***********************************************************************
1646 * set_security_cookie
1648 * Create a random security cookie for buffer overflow protection. Make
1649 * sure it does not accidentally match the default cookie value.
1651 static void set_security_cookie( void *module
, SIZE_T len
)
1654 IMAGE_LOAD_CONFIG_DIRECTORY
*loadcfg
;
1658 loadcfg
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
, &loadcfg_size
);
1659 if (!loadcfg
) return;
1660 if (loadcfg_size
< offsetof(IMAGE_LOAD_CONFIG_DIRECTORY
, SecurityCookie
) + sizeof(loadcfg
->SecurityCookie
)) return;
1661 if (!loadcfg
->SecurityCookie
) return;
1662 if (loadcfg
->SecurityCookie
< (ULONG_PTR
)module
||
1663 loadcfg
->SecurityCookie
> (ULONG_PTR
)module
+ len
- sizeof(ULONG_PTR
))
1665 WARN( "security cookie %p outside of image %p-%p\n",
1666 (void *)loadcfg
->SecurityCookie
, module
, (char *)module
+ len
);
1670 cookie
= (ULONG_PTR
*)loadcfg
->SecurityCookie
;
1671 TRACE( "initializing security cookie %p\n", cookie
);
1673 if (!seed
) seed
= NtGetTickCount() ^ GetCurrentProcessId();
1676 if (*cookie
== DEFAULT_SECURITY_COOKIE_16
)
1677 *cookie
= RtlRandom( &seed
) >> 16; /* leave the high word clear */
1678 else if (*cookie
== DEFAULT_SECURITY_COOKIE_32
)
1679 *cookie
= RtlRandom( &seed
);
1680 #ifdef DEFAULT_SECURITY_COOKIE_64
1681 else if (*cookie
== DEFAULT_SECURITY_COOKIE_64
)
1683 *cookie
= RtlRandom( &seed
);
1684 /* fill up, but keep the highest word clear */
1685 *cookie
^= (ULONG_PTR
)RtlRandom( &seed
) << 16;
1693 static NTSTATUS
perform_relocations( void *module
, SIZE_T len
)
1695 IMAGE_NT_HEADERS
*nt
;
1697 IMAGE_BASE_RELOCATION
*rel
, *end
;
1698 const IMAGE_DATA_DIRECTORY
*relocs
;
1699 const IMAGE_SECTION_HEADER
*sec
;
1701 ULONG protect_old
[96], i
;
1703 nt
= RtlImageNtHeader( module
);
1704 base
= (char *)nt
->OptionalHeader
.ImageBase
;
1706 assert( module
!= base
);
1708 /* no relocations are performed on non page-aligned binaries */
1709 if (nt
->OptionalHeader
.SectionAlignment
< page_size
)
1710 return STATUS_SUCCESS
;
1712 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && NtCurrentTeb()->Peb
->ImageBaseAddress
)
1713 return STATUS_SUCCESS
;
1715 relocs
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_DIRECTORY_ENTRY_BASERELOC
];
1717 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_RELOCS_STRIPPED
)
1719 WARN( "Need to relocate module from %p to %p, but there are no relocation records\n",
1721 return STATUS_CONFLICTING_ADDRESSES
;
1724 if (!relocs
->Size
) return STATUS_SUCCESS
;
1725 if (!relocs
->VirtualAddress
) return STATUS_CONFLICTING_ADDRESSES
;
1727 if (nt
->FileHeader
.NumberOfSections
> sizeof(protect_old
)/sizeof(protect_old
[0]))
1728 return STATUS_INVALID_IMAGE_FORMAT
;
1730 sec
= (const IMAGE_SECTION_HEADER
*)((const char *)&nt
->OptionalHeader
+
1731 nt
->FileHeader
.SizeOfOptionalHeader
);
1732 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1734 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1735 SIZE_T size
= sec
[i
].SizeOfRawData
;
1736 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1737 &size
, PAGE_READWRITE
, &protect_old
[i
] );
1740 TRACE( "relocating from %p-%p to %p-%p\n",
1741 base
, base
+ len
, module
, (char *)module
+ len
);
1743 rel
= get_rva( module
, relocs
->VirtualAddress
);
1744 end
= get_rva( module
, relocs
->VirtualAddress
+ relocs
->Size
);
1745 delta
= (char *)module
- base
;
1747 while (rel
< end
- 1 && rel
->SizeOfBlock
)
1749 if (rel
->VirtualAddress
>= len
)
1751 WARN( "invalid address %p in relocation %p\n", get_rva( module
, rel
->VirtualAddress
), rel
);
1752 return STATUS_ACCESS_VIOLATION
;
1754 rel
= LdrProcessRelocationBlock( get_rva( module
, rel
->VirtualAddress
),
1755 (rel
->SizeOfBlock
- sizeof(*rel
)) / sizeof(USHORT
),
1756 (USHORT
*)(rel
+ 1), delta
);
1757 if (!rel
) return STATUS_INVALID_IMAGE_FORMAT
;
1760 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++)
1762 void *addr
= get_rva( module
, sec
[i
].VirtualAddress
);
1763 SIZE_T size
= sec
[i
].SizeOfRawData
;
1764 NtProtectVirtualMemory( NtCurrentProcess(), &addr
,
1765 &size
, protect_old
[i
], &protect_old
[i
] );
1768 return STATUS_SUCCESS
;
1771 /******************************************************************************
1772 * load_native_dll (internal)
1774 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1775 DWORD flags
, WINE_MODREF
** pwm
)
1780 IMAGE_NT_HEADERS
*nt
;
1785 TRACE("Trying native dll %s\n", debugstr_w(name
));
1788 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1789 NULL
, &size
, PAGE_EXECUTE_READ
, SEC_IMAGE
, file
);
1790 if (status
!= STATUS_SUCCESS
) return status
;
1793 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1794 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_EXECUTE_READ
);
1796 /* perform base relocation, if necessary */
1798 if (status
== STATUS_IMAGE_NOT_AT_BASE
)
1799 status
= perform_relocations( module
, len
);
1801 if (status
!= STATUS_SUCCESS
)
1803 if (module
) NtUnmapViewOfSection( NtCurrentProcess(), module
);
1807 /* create the MODREF */
1809 if (!(wm
= alloc_module( module
, name
)))
1811 status
= STATUS_NO_MEMORY
;
1815 set_security_cookie( module
, len
);
1819 nt
= RtlImageNtHeader( module
);
1821 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
) &&
1822 ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) ||
1823 nt
->OptionalHeader
.Subsystem
== IMAGE_SUBSYSTEM_NATIVE
))
1825 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1827 /* the module has only be inserted in the load & memory order lists */
1828 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1829 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1831 /* FIXME: there are several more dangling references
1832 * left. Including dlls loaded by this dll before the
1833 * failed one. Unrolling is rather difficult with the
1834 * current structure and we can leave them lying
1835 * around with no problems, so we don't care.
1836 * As these might reference our wm, we don't free it.
1842 /* send DLL load event */
1844 SERVER_START_REQ( load_dll
)
1846 req
->mapping
= wine_server_obj_handle( mapping
);
1847 req
->base
= wine_server_client_ptr( module
);
1848 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1849 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1850 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1851 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1852 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1853 wine_server_call( req
);
1857 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1859 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1861 wm
->ldr
.LoadCount
= 1;
1863 status
= STATUS_SUCCESS
;
1870 /***********************************************************************
1873 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1874 DWORD flags
, WINE_MODREF
** pwm
)
1876 char error
[256], dllname
[MAX_PATH
];
1877 const WCHAR
*name
, *p
;
1880 struct builtin_load_info info
, *prev_info
;
1882 /* Fix the name in case we have a full path and extension */
1884 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1885 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1887 /* load_library will modify info.status. Note also that load_library can be
1888 * called several times, if the .so file we're loading has dependencies.
1889 * info.status will gather all the errors we may get while loading all these
1892 info
.load_path
= load_path
;
1893 info
.filename
= NULL
;
1894 info
.status
= STATUS_SUCCESS
;
1897 if (file
) /* we have a real file, try to load it */
1899 UNICODE_STRING nt_name
;
1900 ANSI_STRING unix_name
;
1902 TRACE("Trying built-in %s\n", debugstr_w(path
));
1904 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1905 return STATUS_DLL_NOT_FOUND
;
1907 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1909 RtlFreeUnicodeString( &nt_name
);
1910 return STATUS_DLL_NOT_FOUND
;
1912 prev_info
= builtin_load_info
;
1913 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1914 builtin_load_info
= &info
;
1915 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1916 builtin_load_info
= prev_info
;
1917 RtlFreeUnicodeString( &nt_name
);
1918 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1921 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1922 return STATUS_INVALID_IMAGE_FORMAT
;
1929 TRACE("Trying built-in %s\n", debugstr_w(name
));
1931 /* we don't want to depend on the current codepage here */
1932 len
= strlenW( name
) + 1;
1933 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1934 for (i
= 0; i
< len
; i
++)
1936 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1937 dllname
[i
] = (char)name
[i
];
1938 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1941 prev_info
= builtin_load_info
;
1942 builtin_load_info
= &info
;
1943 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1944 builtin_load_info
= prev_info
;
1949 /* The file does not exist -> WARN() */
1950 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1951 return STATUS_DLL_NOT_FOUND
;
1953 /* ERR() for all other errors (missing functions, ...) */
1954 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1955 return STATUS_PROCEDURE_NOT_FOUND
;
1959 if (info
.status
!= STATUS_SUCCESS
)
1961 wine_dll_unload( handle
);
1967 PLIST_ENTRY mark
, entry
;
1969 /* The constructor wasn't called, this means the .so is already
1970 * loaded under a different name. Try to find the wm for it. */
1972 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1973 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1975 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1976 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1978 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1979 TRACE( "Found %s at %p for builtin %s\n",
1980 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1984 wine_dll_unload( handle
); /* release the libdl refcount */
1985 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1986 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1990 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1991 info
.wm
->ldr
.LoadCount
= 1;
1992 info
.wm
->ldr
.SectionHandle
= handle
;
1996 return STATUS_SUCCESS
;
2000 /***********************************************************************
2003 * Find the full path (if any) of the dll from the activation context.
2005 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
2007 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
2008 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
2010 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
2011 ACTCTX_SECTION_KEYED_DATA data
;
2012 UNICODE_STRING nameW
;
2014 SIZE_T needed
, size
= 1024;
2017 RtlInitUnicodeString( &nameW
, libname
);
2018 data
.cbSize
= sizeof(data
);
2019 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
2020 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
2022 if (status
!= STATUS_SUCCESS
) return status
;
2026 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2028 status
= STATUS_NO_MEMORY
;
2031 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
2032 AssemblyDetailedInformationInActivationContext
,
2033 info
, size
, &needed
);
2034 if (status
== STATUS_SUCCESS
) break;
2035 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
2036 RtlFreeHeap( GetProcessHeap(), 0, info
);
2038 /* restart with larger buffer */
2041 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
2043 status
= STATUS_SXS_KEY_NOT_FOUND
;
2047 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
2049 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2052 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
2054 /* manifest name does not match directory name, so it's not a global
2055 * windows/winsxs manifest; use the manifest directory name instead */
2056 dirlen
= p
- info
->lpAssemblyManifestPath
;
2057 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
2058 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2060 status
= STATUS_NO_MEMORY
;
2063 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
2065 strcpyW( p
, libname
);
2070 needed
= (strlenW(user_shared_data
->NtSystemRoot
) * sizeof(WCHAR
) +
2071 sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+ nameW
.Length
+ 2*sizeof(WCHAR
));
2073 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
2075 status
= STATUS_NO_MEMORY
;
2078 strcpyW( p
, user_shared_data
->NtSystemRoot
);
2080 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
2081 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
2082 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
2083 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
2085 strcpyW( p
, libname
);
2087 RtlFreeHeap( GetProcessHeap(), 0, info
);
2088 RtlReleaseActivationContext( data
.hActCtx
);
2093 /***********************************************************************
2096 * Find the file (or already loaded module) for a given dll name.
2098 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
2099 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
2101 OBJECT_ATTRIBUTES attr
;
2103 UNICODE_STRING nt_name
;
2104 WCHAR
*file_part
, *ext
, *dllname
;
2107 /* first append .dll if needed */
2110 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
2112 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
2113 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
2114 return STATUS_NO_MEMORY
;
2115 strcpyW( dllname
, libname
);
2116 strcatW( dllname
, dllW
);
2120 nt_name
.Buffer
= NULL
;
2122 if (!contains_path( libname
))
2125 WCHAR
*fullname
= NULL
;
2127 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
2129 status
= find_actctx_dll( libname
, &fullname
);
2130 if (status
== STATUS_SUCCESS
)
2132 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
2133 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2134 libname
= dllname
= fullname
;
2136 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
2138 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2143 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
2145 /* we need to search for it */
2146 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
2149 if (len
>= *size
) goto overflow
;
2150 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
2152 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
2154 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2155 return STATUS_NO_MEMORY
;
2157 attr
.Length
= sizeof(attr
);
2158 attr
.RootDirectory
= 0;
2159 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2160 attr
.ObjectName
= &nt_name
;
2161 attr
.SecurityDescriptor
= NULL
;
2162 attr
.SecurityQualityOfService
= NULL
;
2163 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2169 if (!contains_path( libname
))
2171 /* if libname doesn't contain a path at all, we simply return the name as is,
2172 * to be loaded as builtin */
2173 len
= strlenW(libname
) * sizeof(WCHAR
);
2174 if (len
>= *size
) goto overflow
;
2175 strcpyW( filename
, libname
);
2180 /* absolute path name, or relative path name but not found above */
2182 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
2184 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2185 return STATUS_NO_MEMORY
;
2187 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
2188 if (len
>= *size
) goto overflow
;
2189 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
2190 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
2192 attr
.Length
= sizeof(attr
);
2193 attr
.RootDirectory
= 0;
2194 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2195 attr
.ObjectName
= &nt_name
;
2196 attr
.SecurityDescriptor
= NULL
;
2197 attr
.SecurityQualityOfService
= NULL
;
2198 if (NtOpenFile( handle
, GENERIC_READ
|SYNCHRONIZE
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, FILE_SYNCHRONOUS_IO_NONALERT
|FILE_NON_DIRECTORY_FILE
)) *handle
= 0;
2201 RtlFreeUnicodeString( &nt_name
);
2202 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2203 return STATUS_SUCCESS
;
2206 RtlFreeUnicodeString( &nt_name
);
2207 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
2208 *size
= len
+ sizeof(WCHAR
);
2209 return STATUS_BUFFER_TOO_SMALL
;
2213 /***********************************************************************
2214 * load_dll (internal)
2216 * Load a PE style module according to the load order.
2217 * The loader_section must be locked while calling this function.
2219 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
2221 enum loadorder loadorder
;
2225 WINE_MODREF
*main_exe
;
2229 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
2233 size
= sizeof(buffer
);
2236 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
2237 if (nts
== STATUS_SUCCESS
) break;
2238 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2239 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
2240 /* grow the buffer and retry */
2241 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2244 if (*pwm
) /* found already loaded module */
2246 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
2248 TRACE("Found %s for %s at %p, count=%d\n",
2249 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
2250 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
2251 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2252 return STATUS_SUCCESS
;
2255 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
2256 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
2258 if (handle
&& is_fake_dll( handle
))
2260 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
2268 nts
= STATUS_NO_MEMORY
;
2271 nts
= STATUS_DLL_NOT_FOUND
;
2274 case LO_NATIVE_BUILTIN
:
2275 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
2278 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2279 if (nts
== STATUS_INVALID_IMAGE_NOT_MZ
)
2280 /* not in PE format, maybe it's a builtin */
2281 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2283 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
2284 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2287 case LO_BUILTIN_NATIVE
:
2288 case LO_DEFAULT
: /* default is builtin,native */
2289 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
2290 if (!handle
) break; /* nothing else we can try */
2291 /* file is not a builtin library, try without using the specified file */
2292 if (nts
!= STATUS_SUCCESS
)
2293 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
2294 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
2295 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
2297 /* stub-only dll, try native */
2298 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
2299 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
2300 nts
= STATUS_DLL_NOT_FOUND
;
2302 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
2303 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
2307 if (nts
== STATUS_SUCCESS
)
2309 /* Initialize DLL just loaded */
2310 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
2311 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
2312 (*pwm
)->ldr
.BaseAddress
);
2313 if (handle
) NtClose( handle
);
2314 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2318 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2319 if (handle
) NtClose( handle
);
2320 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2324 /******************************************************************
2325 * LdrLoadDll (NTDLL.@)
2327 NTSTATUS WINAPI DECLSPEC_HOTPATCH
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2328 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2333 RtlEnterCriticalSection( &loader_section
);
2335 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2336 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2338 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2340 nts
= process_attach( wm
, NULL
);
2341 if (nts
!= STATUS_SUCCESS
)
2343 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2347 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2349 RtlLeaveCriticalSection( &loader_section
);
2354 /******************************************************************
2355 * LdrGetDllHandle (NTDLL.@)
2357 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2365 RtlEnterCriticalSection( &loader_section
);
2367 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2370 size
= sizeof(buffer
);
2373 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2374 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2375 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2376 /* grow the buffer and retry */
2377 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2379 status
= STATUS_NO_MEMORY
;
2384 if (status
== STATUS_SUCCESS
)
2386 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2387 else status
= STATUS_DLL_NOT_FOUND
;
2390 RtlLeaveCriticalSection( &loader_section
);
2391 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2396 /******************************************************************
2397 * LdrAddRefDll (NTDLL.@)
2399 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2401 NTSTATUS ret
= STATUS_SUCCESS
;
2404 if (flags
& ~LDR_ADDREF_DLL_PIN
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2406 RtlEnterCriticalSection( &loader_section
);
2408 if ((wm
= get_modref( module
)))
2410 if (flags
& LDR_ADDREF_DLL_PIN
)
2411 wm
->ldr
.LoadCount
= -1;
2413 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2414 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2416 else ret
= STATUS_INVALID_PARAMETER
;
2418 RtlLeaveCriticalSection( &loader_section
);
2423 /***********************************************************************
2424 * LdrProcessRelocationBlock (NTDLL.@)
2426 * Apply relocations to a given page of a mapped PE image.
2428 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2429 USHORT
*relocs
, INT_PTR delta
)
2433 USHORT offset
= *relocs
& 0xfff;
2434 int type
= *relocs
>> 12;
2437 case IMAGE_REL_BASED_ABSOLUTE
:
2439 case IMAGE_REL_BASED_HIGH
:
2440 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2442 case IMAGE_REL_BASED_LOW
:
2443 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2445 case IMAGE_REL_BASED_HIGHLOW
:
2446 *(int *)((char *)page
+ offset
) += delta
;
2449 case IMAGE_REL_BASED_DIR64
:
2450 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2452 #elif defined(__arm__)
2453 case IMAGE_REL_BASED_THUMB_MOV32
:
2455 DWORD inst
= *(INT_PTR
*)((char *)page
+ offset
);
2456 DWORD imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2457 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2460 if ((inst
& 0x8000fbf0) != 0x0000f240)
2461 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst
);
2463 imm16
+= LOWORD(delta
);
2464 hi_delta
= HIWORD(delta
) + HIWORD(imm16
);
2465 *(INT_PTR
*)((char *)page
+ offset
) = (inst
& 0x8f00fbf0) + ((imm16
>> 1) & 0x0400) +
2466 ((imm16
>> 12) & 0x000f) +
2467 ((imm16
<< 20) & 0x70000000) +
2468 ((imm16
<< 16) & 0xff0000);
2472 inst
= *(INT_PTR
*)((char *)page
+ offset
+ 4);
2473 imm16
= ((inst
<< 1) & 0x0800) + ((inst
<< 12) & 0xf000) +
2474 ((inst
>> 20) & 0x0700) + ((inst
>> 16) & 0x00ff);
2476 if ((inst
& 0x8000fbf0) != 0x0000f2c0)
2477 ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst
);
2481 ERR("resulting immediate value won't fit: %08x\n", imm16
);
2482 *(INT_PTR
*)((char *)page
+ offset
+ 4) = (inst
& 0x8f00fbf0) +
2483 ((imm16
>> 1) & 0x0400) +
2484 ((imm16
>> 12) & 0x000f) +
2485 ((imm16
<< 20) & 0x70000000) +
2486 ((imm16
<< 16) & 0xff0000);
2492 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2497 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2501 /******************************************************************
2502 * LdrQueryProcessModuleInformation
2505 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2506 ULONG buf_size
, ULONG
* req_size
)
2508 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2509 ULONG size
= sizeof(ULONG
);
2510 NTSTATUS nts
= STATUS_SUCCESS
;
2513 PLIST_ENTRY mark
, entry
;
2517 smi
->ModulesCount
= 0;
2519 RtlEnterCriticalSection( &loader_section
);
2520 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2521 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2523 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2524 size
+= sizeof(*sm
);
2525 if (size
<= buf_size
)
2527 sm
->Reserved1
= 0; /* FIXME */
2528 sm
->Reserved2
= 0; /* FIXME */
2529 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2530 sm
->ImageSize
= mod
->SizeOfImage
;
2531 sm
->Flags
= mod
->Flags
;
2533 sm
->Rank
= 0; /* FIXME */
2534 sm
->Unknown
= 0; /* FIXME */
2536 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2537 str
.Buffer
= (char*)sm
->Name
;
2538 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2539 ptr
= strrchr(str
.Buffer
, '\\');
2540 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2542 smi
->ModulesCount
++;
2545 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2547 RtlLeaveCriticalSection( &loader_section
);
2549 if (req_size
) *req_size
= size
;
2555 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2561 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2563 RtlInitUnicodeString( &str
, name
);
2565 size
= sizeof(buffer
) - sizeof(WCHAR
);
2566 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2569 if (info
->Type
!= REG_DWORD
)
2571 buffer
[size
/ sizeof(WCHAR
)] = 0;
2572 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2574 else memcpy( value
, info
->Data
, sizeof(*value
) );
2578 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2579 void *data
, ULONG in_size
, ULONG
*out_size
)
2585 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2586 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2588 RtlInitUnicodeString( &str
, name
);
2590 size
= info_size
+ in_size
;
2591 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2592 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2593 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2594 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2596 if (out_size
) *out_size
= info
->DataLength
;
2597 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2599 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2604 /******************************************************************
2605 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2607 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2608 void *data
, ULONG in_size
, ULONG
*out_size
)
2610 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2611 'S','o','f','t','w','a','r','e','\\',
2612 'M','i','c','r','o','s','o','f','t','\\',
2613 'W','i','n','d','o','w','s',' ','N','T','\\',
2614 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2615 'I','m','a','g','e',' ','F','i','l','e',' ',
2616 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2617 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2618 OBJECT_ATTRIBUTES attr
;
2619 UNICODE_STRING name_str
;
2625 attr
.Length
= sizeof(attr
);
2626 attr
.RootDirectory
= 0;
2627 attr
.ObjectName
= &name_str
;
2628 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2629 attr
.SecurityDescriptor
= NULL
;
2630 attr
.SecurityQualityOfService
= NULL
;
2632 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2633 else p
= key
->Buffer
;
2634 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2635 name_str
.Buffer
= path
;
2636 name_str
.Length
= sizeof(optionsW
) + len
;
2637 name_str
.MaximumLength
= name_str
.Length
;
2638 memcpy( path
, optionsW
, sizeof(optionsW
) );
2639 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2640 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2642 if (type
== REG_DWORD
)
2644 if (out_size
) *out_size
= sizeof(ULONG
);
2645 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2646 else status
= STATUS_BUFFER_OVERFLOW
;
2648 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2655 /******************************************************************
2656 * RtlDllShutdownInProgress (NTDLL.@)
2658 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2660 return process_detaching
;
2663 /****************************************************************************
2664 * LdrResolveDelayLoadedAPI (NTDLL.@)
2666 void* WINAPI
LdrResolveDelayLoadedAPI( void* base
, const IMAGE_DELAYLOAD_DESCRIPTOR
* desc
,
2667 PDELAYLOAD_FAILURE_DLL_CALLBACK dllhook
, void* syshook
,
2668 IMAGE_THUNK_DATA
* addr
, ULONG flags
)
2670 IMAGE_THUNK_DATA
*pIAT
, *pINT
;
2671 DELAYLOAD_INFO delayinfo
;
2679 FIXME("(%p, %p, %p, %p, %p, 0x%08x), partial stub\n", base
, desc
, dllhook
, syshook
, addr
, flags
);
2681 phmod
= get_rva(base
, desc
->ModuleHandleRVA
);
2682 pIAT
= get_rva(base
, desc
->ImportAddressTableRVA
);
2683 pINT
= get_rva(base
, desc
->ImportNameTableRVA
);
2684 name
= get_rva(base
, desc
->DllNameRVA
);
2689 if (!RtlCreateUnicodeStringFromAsciiz(&mod
, name
))
2691 nts
= STATUS_NO_MEMORY
;
2694 nts
= LdrLoadDll(NULL
, 0, &mod
, phmod
);
2695 RtlFreeUnicodeString(&mod
);
2699 if (IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
))
2700 nts
= LdrGetProcedureAddress(*phmod
, NULL
, LOWORD(pINT
[id
].u1
.Ordinal
), (void**)&fp
);
2703 const IMAGE_IMPORT_BY_NAME
* iibn
= get_rva(base
, pINT
[id
].u1
.AddressOfData
);
2706 RtlInitAnsiString(&fnc
, (char*)iibn
->Name
);
2707 nts
= LdrGetProcedureAddress(*phmod
, &fnc
, 0, (void**)&fp
);
2711 pIAT
[id
].u1
.Function
= (ULONG_PTR
)fp
;
2716 delayinfo
.Size
= sizeof(delayinfo
);
2717 delayinfo
.DelayloadDescriptor
= desc
;
2718 delayinfo
.ThunkAddress
= addr
;
2719 delayinfo
.TargetDllName
= name
;
2720 delayinfo
.TargetApiDescriptor
.ImportDescribedByName
= !IMAGE_SNAP_BY_ORDINAL(pINT
[id
].u1
.Ordinal
);
2721 delayinfo
.TargetApiDescriptor
.Description
.Ordinal
= LOWORD(pINT
[id
].u1
.Ordinal
);
2722 delayinfo
.TargetModuleBase
= *phmod
;
2723 delayinfo
.Unused
= NULL
;
2724 delayinfo
.LastError
= nts
;
2725 return dllhook(4, &delayinfo
);
2728 /******************************************************************
2729 * LdrShutdownProcess (NTDLL.@)
2732 void WINAPI
LdrShutdownProcess(void)
2735 process_detaching
= TRUE
;
2740 /******************************************************************
2741 * RtlExitUserProcess (NTDLL.@)
2743 void WINAPI
RtlExitUserProcess( DWORD status
)
2745 RtlEnterCriticalSection( &loader_section
);
2746 RtlAcquirePebLock();
2747 NtTerminateProcess( 0, status
);
2748 LdrShutdownProcess();
2749 NtTerminateProcess( GetCurrentProcess(), status
);
2753 /******************************************************************
2754 * LdrShutdownThread (NTDLL.@)
2757 void WINAPI
LdrShutdownThread(void)
2759 PLIST_ENTRY mark
, entry
;
2766 /* don't do any detach calls if process is exiting */
2767 if (process_detaching
) return;
2769 RtlEnterCriticalSection( &loader_section
);
2771 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2772 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2774 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2775 InInitializationOrderModuleList
);
2776 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2778 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2781 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2782 DLL_THREAD_DETACH
, NULL
);
2785 RtlAcquirePebLock();
2786 RemoveEntryList( &NtCurrentTeb()->TlsLinks
);
2787 RtlReleasePebLock();
2789 if ((pointers
= NtCurrentTeb()->ThreadLocalStoragePointer
))
2791 for (i
= 0; i
< tls_module_count
; i
++) RtlFreeHeap( GetProcessHeap(), 0, pointers
[i
] );
2792 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
2794 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots
);
2795 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots
);
2796 RtlLeaveCriticalSection( &loader_section
);
2800 /***********************************************************************
2804 static void free_modref( WINE_MODREF
*wm
)
2806 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2807 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2808 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2809 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2811 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2812 if (!TRACE_ON(module
))
2813 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2814 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2815 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2817 SERVER_START_REQ( unload_dll
)
2819 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2820 wine_server_call( req
);
2824 free_tls_slot( &wm
->ldr
);
2825 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2826 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2827 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2828 if (cached_modref
== wm
) cached_modref
= NULL
;
2829 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2830 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2831 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2834 /***********************************************************************
2835 * MODULE_FlushModrefs
2837 * Remove all unused modrefs and call the internal unloading routines
2838 * for the library type.
2840 * The loader_section must be locked while calling this function.
2842 static void MODULE_FlushModrefs(void)
2844 PLIST_ENTRY mark
, entry
, prev
;
2848 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2849 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2851 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2852 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2853 prev
= entry
->Blink
;
2854 if (!mod
->LoadCount
) free_modref( wm
);
2857 /* check load order list too for modules that haven't been initialized yet */
2858 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2859 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2861 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2862 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2863 prev
= entry
->Blink
;
2864 if (!mod
->LoadCount
) free_modref( wm
);
2868 /***********************************************************************
2869 * MODULE_DecRefCount
2871 * The loader_section must be locked while calling this function.
2873 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2877 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2880 if ( wm
->ldr
.LoadCount
<= 0 )
2883 --wm
->ldr
.LoadCount
;
2884 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2886 if ( wm
->ldr
.LoadCount
== 0 )
2888 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2890 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2892 MODULE_DecRefCount( wm
->deps
[i
] );
2894 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2898 /******************************************************************
2899 * LdrUnloadDll (NTDLL.@)
2903 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2906 NTSTATUS retv
= STATUS_SUCCESS
;
2908 if (process_detaching
) return retv
;
2910 TRACE("(%p)\n", hModule
);
2912 RtlEnterCriticalSection( &loader_section
);
2915 if ((wm
= get_modref( hModule
)) != NULL
)
2917 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2919 /* Recursively decrement reference counts */
2920 MODULE_DecRefCount( wm
);
2922 /* Call process detach notifications */
2923 if ( free_lib_count
<= 1 )
2926 MODULE_FlushModrefs();
2932 retv
= STATUS_DLL_NOT_FOUND
;
2936 RtlLeaveCriticalSection( &loader_section
);
2941 /***********************************************************************
2942 * RtlImageNtHeader (NTDLL.@)
2944 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2946 IMAGE_NT_HEADERS
*ret
;
2950 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2953 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2955 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2956 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2968 /***********************************************************************
2969 * attach_process_dlls
2971 * Initial attach to all the dlls loaded by the process.
2973 static NTSTATUS
attach_process_dlls( void *wm
)
2977 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2979 RtlEnterCriticalSection( &loader_section
);
2980 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2982 if (last_failed_modref
)
2983 ERR( "%s failed to initialize, aborting\n",
2984 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2987 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2988 RtlLeaveCriticalSection( &loader_section
);
2993 /***********************************************************************
2994 * load_global_options
2996 static void load_global_options(void)
2998 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
2999 'S','y','s','t','e','m','\\',
3000 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
3001 'C','o','n','t','r','o','l','\\',
3002 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
3003 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3004 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};
3005 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
3006 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
3007 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};
3008 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};
3010 OBJECT_ATTRIBUTES attr
;
3011 UNICODE_STRING name_str
;
3015 attr
.Length
= sizeof(attr
);
3016 attr
.RootDirectory
= 0;
3017 attr
.ObjectName
= &name_str
;
3018 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
3019 attr
.SecurityDescriptor
= NULL
;
3020 attr
.SecurityQualityOfService
= NULL
;
3021 RtlInitUnicodeString( &name_str
, sessionW
);
3023 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
3025 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
3027 query_dword_option( hkey
, critsectW
, &value
);
3028 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
3030 query_dword_option( hkey
, heapresW
, &value
);
3031 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
3033 query_dword_option( hkey
, heapcommitW
, &value
);
3034 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
3036 query_dword_option( hkey
, decommittotalW
, &value
);
3037 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
3039 query_dword_option( hkey
, decommitfreeW
, &value
);
3040 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
3046 /***********************************************************************
3049 static void start_process( void *kernel_start
)
3051 call_thread_entry_point( kernel_start
, NtCurrentTeb()->Peb
);
3054 /******************************************************************
3055 * LdrInitializeThunk (NTDLL.@)
3058 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
3059 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
3061 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
3065 PEB
*peb
= NtCurrentTeb()->Peb
;
3067 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
3069 /* allocate the modref for the main exe (if not already done) */
3070 wm
= get_modref( peb
->ImageBaseAddress
);
3072 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
3074 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
3078 peb
->LoaderLock
= &loader_section
;
3079 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
3080 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
3081 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
3082 version_init( wm
->ldr
.FullDllName
.Buffer
);
3083 virtual_set_large_address_space();
3085 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
3086 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
3088 /* the main exe needs to be the first in the load order list */
3089 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
3090 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
3092 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
3093 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
3096 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
3097 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
3098 heap_set_debug_flags( GetProcessHeap() );
3100 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
3101 if (status
!= STATUS_SUCCESS
) goto error
;
3103 virtual_release_address_space();
3104 virtual_clear_thread_stack();
3105 wine_switch_to_stack( start_process
, kernel_start
, NtCurrentTeb()->Tib
.StackBase
);
3108 ERR( "Main exe initialization for %s failed, status %x\n",
3109 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
3110 NtTerminateProcess( GetCurrentProcess(), status
);
3114 /***********************************************************************
3115 * RtlImageDirectoryEntryToData (NTDLL.@)
3117 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
3119 const IMAGE_NT_HEADERS
*nt
;
3122 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
3124 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
3127 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
3128 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
3130 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
3132 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3133 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3134 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
3135 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3137 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
3139 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
3141 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
3142 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
3143 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
3144 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
3148 /* not mapped as image, need to find the section containing the virtual address */
3149 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
3153 /***********************************************************************
3154 * RtlImageRvaToSection (NTDLL.@)
3156 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
3157 HMODULE module
, DWORD rva
)
3160 const IMAGE_SECTION_HEADER
*sec
;
3162 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
3163 nt
->FileHeader
.SizeOfOptionalHeader
);
3164 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
3166 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3167 return (PIMAGE_SECTION_HEADER
)sec
;
3173 /***********************************************************************
3174 * RtlImageRvaToVa (NTDLL.@)
3176 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
3177 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
3179 IMAGE_SECTION_HEADER
*sec
;
3181 if (section
&& *section
) /* try this section first */
3184 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
3187 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
3189 if (section
) *section
= sec
;
3190 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
3194 /***********************************************************************
3195 * RtlPcToFileHeader (NTDLL.@)
3197 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
3202 RtlEnterCriticalSection( &loader_section
);
3203 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
3204 RtlLeaveCriticalSection( &loader_section
);
3210 /***********************************************************************
3211 * NtLoadDriver (NTDLL.@)
3212 * ZwLoadDriver (NTDLL.@)
3214 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
3216 FIXME("(%p), stub!\n",DriverServiceName
);
3217 return STATUS_NOT_IMPLEMENTED
;
3221 /***********************************************************************
3222 * NtUnloadDriver (NTDLL.@)
3223 * ZwUnloadDriver (NTDLL.@)
3225 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
3227 FIXME("(%p), stub!\n",DriverServiceName
);
3228 return STATUS_NOT_IMPLEMENTED
;
3232 /******************************************************************
3235 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
3237 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
3242 /******************************************************************
3243 * __wine_init_windows_dir (NTDLL.@)
3245 * Windows and system dir initialization once kernel32 has been loaded.
3247 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
3249 PLIST_ENTRY mark
, entry
;
3252 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
3253 DIR_init_windows_dir( windir
, sysdir
);
3255 /* prepend the system dir to the name of the already created modules */
3256 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
3257 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
3259 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
3261 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
3263 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
3264 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
3265 if (!buffer
) continue;
3266 strcpyW( buffer
, system_dir
.Buffer
);
3267 p
= buffer
+ strlenW( buffer
);
3268 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
3269 strcpyW( p
, mod
->FullDllName
.Buffer
);
3270 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
3271 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
3276 /***********************************************************************
3277 * __wine_process_init
3279 void __wine_process_init(void)
3281 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
3285 ANSI_STRING func_name
;
3286 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
3288 main_exe_file
= thread_init();
3290 /* retrieve current umask */
3291 FILE_umask
= umask(0777);
3292 umask( FILE_umask
);
3294 load_global_options();
3296 /* setup the load callback and create ntdll modref */
3297 wine_dll_set_callback( load_builtin_callback
);
3299 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
3301 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
3304 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
3305 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
3307 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
3308 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
3309 0, (void **)&init_func
)) != STATUS_SUCCESS
)
3311 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);