4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "wine/port.h"
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
35 #define WIN32_NO_STATUS
40 #include "wine/exception.h"
41 #include "wine/library.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module
);
49 WINE_DECLARE_DEBUG_CHANNEL(relay
);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
52 WINE_DECLARE_DEBUG_CHANNEL(imports
);
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
60 static int process_detaching
= 0; /* set on process detach to avoid deadlocks with thread detach */
61 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
63 static const char * const reason_names
[] =
69 NULL
, NULL
, NULL
, NULL
,
73 static const WCHAR dllW
[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
80 struct _wine_modref
**deps
;
83 /* info about the current builtin dll load */
84 /* used to keep track of things across the register_dll constructor call */
85 struct builtin_load_info
87 const WCHAR
*load_path
;
88 const WCHAR
*filename
;
93 static struct builtin_load_info default_load_info
;
94 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
96 static HANDLE main_exe_file
;
97 static UINT tls_module_count
; /* number of modules with TLS directory */
98 static UINT tls_total_size
; /* total size of TLS storage */
99 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
100 #define TLS_ALIGNMENT (2 * sizeof(void *))
101 #define TLS_ALIGN(size) (((size) + TLS_ALIGNMENT - 1) & ~(TLS_ALIGNMENT - 1))
103 static RTL_CRITICAL_SECTION loader_section
;
104 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
106 0, 0, &loader_section
,
107 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
108 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
110 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
112 static WINE_MODREF
*cached_modref
;
113 static WINE_MODREF
*current_modref
;
114 static WINE_MODREF
*last_failed_modref
;
116 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
117 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
118 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
119 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
);
120 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
121 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
123 /* convert PE image VirtualAddress to Real Address */
124 static inline void *get_rva( HMODULE module
, DWORD va
)
126 return (void *)((char *)module
+ va
);
129 /* check whether the file name contains a path */
130 static inline int contains_path( LPCWSTR name
)
132 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
135 /* convert from straight ASCII to Unicode without depending on the current codepage */
136 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
138 while (len
--) *dst
++ = (unsigned char)*src
++;
142 /*************************************************************************
143 * call_dll_entry_point
145 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
146 * their entry point, so we need a small asm wrapper.
149 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
150 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
152 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
153 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
155 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
157 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
162 "movl 8(%ebp),%eax\n\t"
164 "leal -4(%ebp),%esp\n\t"
166 __ASM_CFI(".cfi_same_value %ebx\n\t")
168 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
169 __ASM_CFI(".cfi_same_value %ebp\n\t")
172 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
173 UINT reason
, void *reserved
)
175 return proc( module
, reason
, reserved
);
177 #endif /* __i386__ */
180 #if defined(__i386__) || defined(__x86_64__)
181 /*************************************************************************
184 * Entry point for stub functions.
186 static void stub_entry_point( const char *dll
, const char *name
, void *ret_addr
)
188 EXCEPTION_RECORD rec
;
190 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
191 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
192 rec
.ExceptionRecord
= NULL
;
193 rec
.ExceptionAddress
= ret_addr
;
194 rec
.NumberParameters
= 2;
195 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
196 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
197 for (;;) RtlRaiseException( &rec
);
201 #include "pshpack1.h"
205 BYTE pushl1
; /* pushl $name */
207 BYTE pushl2
; /* pushl $dll */
209 BYTE call
; /* call stub_entry_point */
215 BYTE movq_rdi
[2]; /* movq $dll,%rdi */
217 BYTE movq_rsi
[2]; /* movq $name,%rsi */
219 BYTE movq_rsp_rdx
[4]; /* movq (%rsp),%rdx */
220 BYTE movq_rax
[2]; /* movq $entry, %rax */
222 BYTE jmpq_rax
[2]; /* jmp %rax */
227 /*************************************************************************
230 * Allocate a stub entry point.
232 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
234 #define MAX_SIZE 65536
235 static struct stub
*stubs
;
236 static unsigned int nb_stubs
;
239 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
243 SIZE_T size
= MAX_SIZE
;
244 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
245 MEM_COMMIT
, PAGE_EXECUTE_WRITECOPY
) != STATUS_SUCCESS
)
248 stub
= &stubs
[nb_stubs
++];
250 stub
->pushl1
= 0x68; /* pushl $name */
252 stub
->pushl2
= 0x68; /* pushl $dll */
254 stub
->call
= 0xe8; /* call stub_entry_point */
255 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
257 stub
->movq_rdi
[0] = 0x48; /* movq $dll,%rdi */
258 stub
->movq_rdi
[1] = 0xbf;
260 stub
->movq_rsi
[0] = 0x48; /* movq $name,%rsi */
261 stub
->movq_rsi
[1] = 0xbe;
263 stub
->movq_rsp_rdx
[0] = 0x48; /* movq (%rsp),%rdx */
264 stub
->movq_rsp_rdx
[1] = 0x8b;
265 stub
->movq_rsp_rdx
[2] = 0x14;
266 stub
->movq_rsp_rdx
[3] = 0x24;
267 stub
->movq_rax
[0] = 0x48; /* movq $entry, %rax */
268 stub
->movq_rax
[1] = 0xb8;
269 stub
->entry
= stub_entry_point
;
270 stub
->jmpq_rax
[0] = 0xff; /* jmp %rax */
271 stub
->jmpq_rax
[1] = 0xe0;
273 return (ULONG_PTR
)stub
;
277 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
278 #endif /* __i386__ */
281 /*************************************************************************
284 * Looks for the referenced HMODULE in the current process
285 * The loader_section must be locked while calling this function.
287 static WINE_MODREF
*get_modref( HMODULE hmod
)
289 PLIST_ENTRY mark
, entry
;
292 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
294 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
295 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
297 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
298 if (mod
->BaseAddress
== hmod
)
299 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
300 if (mod
->BaseAddress
> (void*)hmod
) break;
306 /**********************************************************************
307 * find_basename_module
309 * Find a module from its base name.
310 * The loader_section must be locked while calling this function
312 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
314 PLIST_ENTRY mark
, entry
;
316 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
317 return cached_modref
;
319 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
320 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
322 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
323 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
325 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
326 return cached_modref
;
333 /**********************************************************************
334 * find_fullname_module
336 * Find a module from its full path name.
337 * The loader_section must be locked while calling this function
339 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
341 PLIST_ENTRY mark
, entry
;
343 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
344 return cached_modref
;
346 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
347 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
349 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
350 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
352 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
353 return cached_modref
;
360 /*************************************************************************
361 * find_forwarded_export
363 * Find the final function pointer for a forwarded function.
364 * The loader_section must be locked while calling this function.
366 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
368 const IMAGE_EXPORT_DIRECTORY
*exports
;
372 const char *end
= strrchr(forward
, '.');
375 if (!end
) return NULL
;
376 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
377 ascii_to_unicode( mod_name
, forward
, end
- forward
);
378 mod_name
[end
- forward
] = 0;
379 if (!strchrW( mod_name
, '.' ))
381 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
382 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
385 if (!(wm
= find_basename_module( mod_name
)))
387 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
388 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
389 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
391 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
393 LdrUnloadDll( wm
->ldr
.BaseAddress
);
400 ERR( "module not found for forward '%s' used by %s\n",
401 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
405 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
406 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
408 const char *name
= end
+ 1;
409 if (*name
== '#') /* ordinal */
410 proc
= find_ordinal_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, atoi(name
+1), load_path
);
412 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, name
, -1, load_path
);
417 ERR("function not found for forward '%s' used by %s."
418 " If you are using builtin %s, try using the native one instead.\n",
419 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
420 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
426 /*************************************************************************
427 * find_ordinal_export
429 * Find an exported function by ordinal.
430 * The exports base must have been subtracted from the ordinal already.
431 * The loader_section must be locked while calling this function.
433 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
434 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
437 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
439 if (ordinal
>= exports
->NumberOfFunctions
)
441 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
444 if (!functions
[ordinal
]) return NULL
;
446 proc
= get_rva( module
, functions
[ordinal
] );
448 /* if the address falls into the export dir, it's a forward */
449 if (((const char *)proc
>= (const char *)exports
) &&
450 ((const char *)proc
< (const char *)exports
+ exp_size
))
451 return find_forwarded_export( module
, (const char *)proc
, load_path
);
455 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
456 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
460 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
461 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
467 /*************************************************************************
470 * Find an exported function by name.
471 * The loader_section must be locked while calling this function.
473 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
474 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
476 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
477 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
478 int min
= 0, max
= exports
->NumberOfNames
- 1;
480 /* first check the hint */
481 if (hint
>= 0 && hint
<= max
)
483 char *ename
= get_rva( module
, names
[hint
] );
484 if (!strcmp( ename
, name
))
485 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
488 /* then do a binary search */
491 int res
, pos
= (min
+ max
) / 2;
492 char *ename
= get_rva( module
, names
[pos
] );
493 if (!(res
= strcmp( ename
, name
)))
494 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
495 if (res
> 0) max
= pos
- 1;
503 /*************************************************************************
506 * Import the dll specified by the given import descriptor.
507 * The loader_section must be locked while calling this function.
509 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
514 const IMAGE_EXPORT_DIRECTORY
*exports
;
516 const IMAGE_THUNK_DATA
*import_list
;
517 IMAGE_THUNK_DATA
*thunk_list
;
519 const char *name
= get_rva( module
, descr
->Name
);
520 DWORD len
= strlen(name
);
522 SIZE_T protect_size
= 0;
525 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
526 if (descr
->u
.OriginalFirstThunk
)
527 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
529 import_list
= thunk_list
;
531 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
533 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
535 ascii_to_unicode( buffer
, name
, len
);
537 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
539 else /* need to allocate a larger buffer */
541 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
542 if (!ptr
) return NULL
;
543 ascii_to_unicode( ptr
, name
, len
);
545 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
546 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
551 if (status
== STATUS_DLL_NOT_FOUND
)
552 ERR("Library %s (which is needed by %s) not found\n",
553 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
555 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
556 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
560 /* unprotect the import address table since it can be located in
561 * readonly section */
562 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
563 protect_base
= thunk_list
;
564 protect_size
*= sizeof(*thunk_list
);
565 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
566 &protect_size
, PAGE_WRITECOPY
, &protect_old
);
568 imp_mod
= wmImp
->ldr
.BaseAddress
;
569 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
573 /* set all imported function to deadbeef */
574 while (import_list
->u1
.Ordinal
)
576 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
578 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
579 WARN("No implementation for %s.%d", name
, ordinal
);
580 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
584 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
585 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
586 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
588 WARN(" imported from %s, allocating stub %p\n",
589 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
590 (void *)thunk_list
->u1
.Function
);
597 while (import_list
->u1
.Ordinal
)
599 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
601 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
603 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
604 ordinal
- exports
->Base
, load_path
);
605 if (!thunk_list
->u1
.Function
)
607 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
608 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
609 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
610 (void *)thunk_list
->u1
.Function
);
612 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
614 else /* import by name */
616 IMAGE_IMPORT_BY_NAME
*pe_name
;
617 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
618 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
619 (const char*)pe_name
->Name
,
620 pe_name
->Hint
, load_path
);
621 if (!thunk_list
->u1
.Function
)
623 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
624 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
625 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
626 (void *)thunk_list
->u1
.Function
);
628 TRACE_(imports
)("--- %s %s.%d = %p\n",
629 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
636 /* restore old protection of the import address table */
637 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
642 /***********************************************************************
643 * create_module_activation_context
645 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
648 LDR_RESOURCE_INFO info
;
649 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
651 info
.Type
= RT_MANIFEST
;
652 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
654 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
657 ctx
.cbSize
= sizeof(ctx
);
659 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
660 ctx
.hModule
= module
->BaseAddress
;
661 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
662 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
668 /****************************************************************
671 * Fixup all imports of a given module.
672 * The loader_section must be locked while calling this function.
674 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
677 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
683 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
684 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
686 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
687 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
688 return STATUS_SUCCESS
;
691 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
693 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
695 if (!create_module_activation_context( &wm
->ldr
))
696 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
698 /* Allocate module dependency list */
699 wm
->nDeps
= nb_imports
;
700 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
702 /* load the imported modules. They are automatically
703 * added to the modref list of the process.
705 prev
= current_modref
;
707 status
= STATUS_SUCCESS
;
708 for (i
= 0; i
< nb_imports
; i
++)
710 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
711 status
= STATUS_DLL_NOT_FOUND
;
713 current_modref
= prev
;
714 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
719 /*************************************************************************
720 * is_dll_native_subsystem
722 * Check if dll is a proper native driver.
723 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
724 * while being perfectly normal DLLs. This heuristic should catch such breakages.
726 static BOOL
is_dll_native_subsystem( HMODULE module
, const IMAGE_NT_HEADERS
*nt
, LPCWSTR filename
)
728 static const WCHAR ntdllW
[] = {'n','t','d','l','l','.','d','l','l',0};
729 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
730 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
734 if (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_NATIVE
) return FALSE
;
735 if (nt
->OptionalHeader
.SectionAlignment
< getpagesize()) return TRUE
;
737 if ((imports
= RtlImageDirectoryEntryToData( module
, TRUE
,
738 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
740 for (i
= 0; imports
[i
].Name
; i
++)
742 const char *name
= get_rva( module
, imports
[i
].Name
);
743 DWORD len
= strlen(name
);
744 if (len
* sizeof(WCHAR
) >= sizeof(buffer
)) continue;
745 ascii_to_unicode( buffer
, name
, len
+ 1 );
746 if (!strcmpiW( buffer
, ntdllW
) || !strcmpiW( buffer
, kernel32W
))
748 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename
), debugstr_w(buffer
) );
757 /*************************************************************************
760 * Allocate a WINE_MODREF structure and add it to the process list
761 * The loader_section must be locked while calling this function.
763 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
767 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
768 PLIST_ENTRY entry
, mark
;
770 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
775 wm
->ldr
.BaseAddress
= hModule
;
776 wm
->ldr
.EntryPoint
= NULL
;
777 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
778 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
779 wm
->ldr
.LoadCount
= 1;
780 wm
->ldr
.TlsIndex
= -1;
781 wm
->ldr
.SectionHandle
= NULL
;
782 wm
->ldr
.CheckSum
= 0;
783 wm
->ldr
.TimeDateStamp
= 0;
784 wm
->ldr
.ActivationContext
= 0;
786 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
787 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
788 else p
= wm
->ldr
.FullDllName
.Buffer
;
789 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
791 if ((nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) && !is_dll_native_subsystem( hModule
, nt
, p
))
793 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
794 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
795 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
798 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
799 &wm
->ldr
.InLoadOrderModuleList
);
801 /* insert module in MemoryList, sorted in increasing base addresses */
802 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
803 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
805 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
808 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
809 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
810 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
811 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
813 /* wait until init is called for inserting into this list */
814 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
815 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
817 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
819 ULONG flags
= MEM_EXECUTE_OPTION_ENABLE
;
820 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
821 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags
, &flags
, sizeof(flags
) );
827 /*************************************************************************
830 * Allocate the process-wide structure for module TLS storage.
832 static NTSTATUS
alloc_process_tls(void)
834 PLIST_ENTRY mark
, entry
;
836 const IMAGE_TLS_DIRECTORY
*dir
;
839 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
840 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
842 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
843 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
844 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
846 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
847 if (!size
&& !dir
->AddressOfCallBacks
) continue;
848 tls_total_size
+= TLS_ALIGN(size
);
851 if (!tls_module_count
) return STATUS_SUCCESS
;
853 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
855 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
856 if (!tls_dirs
) return STATUS_NO_MEMORY
;
858 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
860 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
861 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
862 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
865 *(DWORD
*)dir
->AddressOfIndex
= i
;
867 mod
->LoadCount
= -1; /* can't unload it */
870 return STATUS_SUCCESS
;
874 /*************************************************************************
877 * Allocate the per-thread structure for module TLS storage.
879 static NTSTATUS
alloc_thread_tls(void)
885 if (!tls_module_count
) return STATUS_SUCCESS
;
887 size
= TLS_ALIGN( tls_module_count
* sizeof(*pointers
) );
888 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0, size
+ tls_total_size
)))
889 return STATUS_NO_MEMORY
;
890 data
= (char *)pointers
+ size
;
892 for (i
= 0; i
< tls_module_count
; i
++)
894 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
895 size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
897 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
898 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
899 (void *)dir
->StartAddressOfRawData
, data
);
902 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
903 memset( data
+ size
, 0, dir
->SizeOfZeroFill
);
904 data
+= TLS_ALIGN( size
+ dir
->SizeOfZeroFill
);
906 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
907 return STATUS_SUCCESS
;
911 /*************************************************************************
914 static void call_tls_callbacks( HMODULE module
, UINT reason
)
916 const IMAGE_TLS_DIRECTORY
*dir
;
917 const PIMAGE_TLS_CALLBACK
*callback
;
920 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
921 if (!dir
|| !dir
->AddressOfCallBacks
) return;
923 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
926 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
927 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
930 (*callback
)( module
, reason
, NULL
);
935 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
936 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
941 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
942 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
947 /*************************************************************************
950 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
953 NTSTATUS status
= STATUS_SUCCESS
;
954 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
955 void *module
= wm
->ldr
.BaseAddress
;
958 /* Skip calls for modules loaded with special load flags */
960 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
961 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
962 if (!entry
) return STATUS_SUCCESS
;
966 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
967 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
968 mod_name
[len
/ sizeof(WCHAR
)] = 0;
969 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
970 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
971 reason_names
[reason
], lpReserved
);
973 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
974 reason_names
[reason
], lpReserved
);
978 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
980 status
= STATUS_DLL_INIT_FAILED
;
985 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
986 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
987 status
= GetExceptionCode();
991 /* The state of the module list may have changed due to the call
992 to the dll. We cannot assume that this module has not been
995 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
996 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
997 reason_names
[reason
], lpReserved
, retv
);
998 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
1004 /*************************************************************************
1007 * Send the process attach notification to all DLLs the given module
1008 * depends on (recursively). This is somewhat complicated due to the fact that
1010 * - we have to respect the module dependencies, i.e. modules implicitly
1011 * referenced by another module have to be initialized before the module
1012 * itself can be initialized
1014 * - the initialization routine of a DLL can itself call LoadLibrary,
1015 * thereby introducing a whole new set of dependencies (even involving
1016 * the 'old' modules) at any time during the whole process
1018 * (Note that this routine can be recursively entered not only directly
1019 * from itself, but also via LoadLibrary from one of the called initialization
1022 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1023 * the process *detach* notifications to be sent in the correct order.
1024 * This must not only take into account module dependencies, but also
1025 * 'hidden' dependencies created by modules calling LoadLibrary in their
1026 * attach notification routine.
1028 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1029 * list after the attach notification has returned. This implies that the
1030 * detach notifications are called in the reverse of the sequence the attach
1031 * notifications *returned*.
1033 * The loader_section must be locked while calling this function.
1035 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
1037 NTSTATUS status
= STATUS_SUCCESS
;
1041 if (process_detaching
) return status
;
1043 /* prevent infinite recursion in case of cyclical dependencies */
1044 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
1045 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1048 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1050 /* Tag current MODREF to prevent recursive loop */
1051 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
1052 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
1053 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
1055 /* Recursively attach all DLLs this one depends on */
1056 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1058 if (!wm
->deps
[i
]) continue;
1059 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
1062 /* Call DLL entry point */
1063 if (status
== STATUS_SUCCESS
)
1065 WINE_MODREF
*prev
= current_modref
;
1066 current_modref
= wm
;
1067 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
1068 if (status
== STATUS_SUCCESS
)
1069 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1072 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
1073 /* point to the name so LdrInitializeThunk can print it */
1074 last_failed_modref
= wm
;
1075 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1077 current_modref
= prev
;
1080 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1081 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1082 &wm
->ldr
.InInitializationOrderModuleList
);
1084 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1085 /* Remove recursion flag */
1086 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1088 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1093 /**********************************************************************
1094 * attach_implicitly_loaded_dlls
1096 * Attach to the (builtin) dlls that have been implicitly loaded because
1097 * of a dependency at the Unix level, but not imported at the Win32 level.
1099 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1103 PLIST_ENTRY mark
, entry
;
1105 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1106 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1108 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1110 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1111 TRACE( "found implicitly loaded %s, attaching to it\n",
1112 debugstr_w(mod
->BaseDllName
.Buffer
));
1113 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1114 break; /* restart the search from the start */
1116 if (entry
== mark
) break; /* nothing found */
1121 /*************************************************************************
1124 * Send DLL process detach notifications. See the comment about calling
1125 * sequence at process_attach. Unless the bForceDetach flag
1126 * is set, only DLLs with zero refcount are notified.
1128 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
1130 PLIST_ENTRY mark
, entry
;
1133 RtlEnterCriticalSection( &loader_section
);
1134 if (bForceDetach
) process_detaching
= 1;
1135 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1138 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1140 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1141 InInitializationOrderModuleList
);
1142 /* Check whether to detach this DLL */
1143 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1145 if ( mod
->LoadCount
&& !bForceDetach
)
1148 /* Call detach notification */
1149 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1150 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1151 DLL_PROCESS_DETACH
, lpReserved
);
1153 /* Restart at head of WINE_MODREF list, as entries might have
1154 been added and/or removed while performing the call ... */
1157 } while (entry
!= mark
);
1159 RtlLeaveCriticalSection( &loader_section
);
1162 /*************************************************************************
1163 * MODULE_DllThreadAttach
1165 * Send DLL thread attach notifications. These are sent in the
1166 * reverse sequence of process detach notification.
1169 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1171 PLIST_ENTRY mark
, entry
;
1175 /* don't do any attach calls if process is exiting */
1176 if (process_detaching
) return STATUS_SUCCESS
;
1177 /* FIXME: there is still a race here */
1179 RtlEnterCriticalSection( &loader_section
);
1181 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1183 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1184 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1186 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1187 InInitializationOrderModuleList
);
1188 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1190 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1193 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1194 DLL_THREAD_ATTACH
, lpReserved
);
1198 RtlLeaveCriticalSection( &loader_section
);
1202 /******************************************************************
1203 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1206 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1209 NTSTATUS ret
= STATUS_SUCCESS
;
1211 RtlEnterCriticalSection( &loader_section
);
1213 wm
= get_modref( hModule
);
1214 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1215 ret
= STATUS_DLL_NOT_FOUND
;
1217 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1219 RtlLeaveCriticalSection( &loader_section
);
1224 /******************************************************************
1225 * LdrFindEntryForAddress (NTDLL.@)
1227 * The loader_section must be locked while calling this function
1229 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1231 PLIST_ENTRY mark
, entry
;
1234 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1235 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1237 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1238 if (mod
->BaseAddress
<= addr
&&
1239 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1242 return STATUS_SUCCESS
;
1244 if (mod
->BaseAddress
> addr
) break;
1246 return STATUS_NO_MORE_ENTRIES
;
1249 /******************************************************************
1250 * LdrLockLoaderLock (NTDLL.@)
1252 * Note: flags are not implemented.
1253 * Flag 0x01 is used to raise exceptions on errors.
1254 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1256 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1258 if (flags
) FIXME( "flags %x not supported\n", flags
);
1260 if (result
) *result
= 1;
1261 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1262 RtlEnterCriticalSection( &loader_section
);
1263 *magic
= GetCurrentThreadId();
1264 return STATUS_SUCCESS
;
1268 /******************************************************************
1269 * LdrUnlockLoaderUnlock (NTDLL.@)
1271 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1275 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1276 RtlLeaveCriticalSection( &loader_section
);
1278 return STATUS_SUCCESS
;
1282 /******************************************************************
1283 * LdrGetProcedureAddress (NTDLL.@)
1285 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1286 ULONG ord
, PVOID
*address
)
1288 IMAGE_EXPORT_DIRECTORY
*exports
;
1290 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1292 RtlEnterCriticalSection( &loader_section
);
1294 /* check if the module itself is invalid to return the proper error */
1295 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1296 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1297 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1299 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1300 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1301 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1305 ret
= STATUS_SUCCESS
;
1309 RtlLeaveCriticalSection( &loader_section
);
1314 /***********************************************************************
1317 * Check if a loaded native dll is a Wine fake dll.
1319 static BOOL
is_fake_dll( HANDLE handle
)
1321 static const char fakedll_signature
[] = "Wine placeholder DLL";
1322 char buffer
[sizeof(IMAGE_DOS_HEADER
) + sizeof(fakedll_signature
)];
1323 const IMAGE_DOS_HEADER
*dos
= (const IMAGE_DOS_HEADER
*)buffer
;
1325 LARGE_INTEGER offset
;
1327 offset
.QuadPart
= 0;
1328 if (NtReadFile( handle
, 0, NULL
, 0, &io
, buffer
, sizeof(buffer
), &offset
, NULL
)) return FALSE
;
1329 if (io
.Information
< sizeof(buffer
)) return FALSE
;
1330 if (dos
->e_magic
!= IMAGE_DOS_SIGNATURE
) return FALSE
;
1331 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1332 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1337 /***********************************************************************
1338 * get_builtin_fullname
1340 * Build the full pathname for a builtin dll.
1342 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1344 static const WCHAR soW
[] = {'.','s','o',0};
1345 WCHAR
*p
, *fullname
;
1346 size_t i
, len
= strlen(filename
);
1348 /* check if path can correspond to the dll we have */
1349 if (path
&& (p
= strrchrW( path
, '\\' )))
1352 for (i
= 0; i
< len
; i
++)
1353 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1354 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1356 /* the filename matches, use path as the full path */
1358 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1360 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1367 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1368 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1370 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1371 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1372 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1373 ascii_to_unicode( p
, filename
, len
+ 1 );
1379 /***********************************************************************
1380 * load_builtin_callback
1382 * Load a library in memory; callback function for wine_dll_register
1384 static void load_builtin_callback( void *module
, const char *filename
)
1386 static const WCHAR emptyW
[1];
1387 IMAGE_NT_HEADERS
*nt
;
1390 const WCHAR
*load_path
;
1394 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1397 if (!(nt
= RtlImageNtHeader( module
)))
1399 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1400 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1404 virtual_create_builtin_view( module
);
1406 /* create the MODREF */
1408 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1410 ERR( "can't load %s\n", filename
);
1411 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1415 wm
= alloc_module( module
, fullname
);
1416 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1419 ERR( "can't load %s\n", filename
);
1420 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1423 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1425 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1426 !NtCurrentTeb()->Peb
->ImageBaseAddress
) /* if we already have an executable, ignore this one */
1428 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1434 load_path
= builtin_load_info
->load_path
;
1435 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1436 if (!load_path
) load_path
= emptyW
;
1437 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1439 /* the module has only be inserted in the load & memory order lists */
1440 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1441 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1442 /* FIXME: free the modref */
1443 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1448 builtin_load_info
->wm
= wm
;
1449 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1451 /* send the DLL load event */
1453 SERVER_START_REQ( load_dll
)
1456 req
->base
= wine_server_client_ptr( module
);
1457 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1458 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1459 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1460 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1461 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1462 wine_server_call( req
);
1466 /* setup relay debugging entry points */
1467 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1471 /******************************************************************************
1472 * load_native_dll (internal)
1474 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1475 DWORD flags
, WINE_MODREF
** pwm
)
1480 IMAGE_NT_HEADERS
*nt
;
1485 TRACE("Trying native dll %s\n", debugstr_w(name
));
1488 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1489 NULL
, &size
, PAGE_READONLY
, SEC_IMAGE
, file
);
1490 if (status
!= STATUS_SUCCESS
) return status
;
1493 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1494 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1496 if (status
< 0) return status
;
1498 /* create the MODREF */
1500 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1504 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1506 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1508 /* the module has only be inserted in the load & memory order lists */
1509 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1510 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1512 /* FIXME: there are several more dangling references
1513 * left. Including dlls loaded by this dll before the
1514 * failed one. Unrolling is rather difficult with the
1515 * current structure and we can leave them lying
1516 * around with no problems, so we don't care.
1517 * As these might reference our wm, we don't free it.
1523 /* send DLL load event */
1525 nt
= RtlImageNtHeader( module
);
1527 SERVER_START_REQ( load_dll
)
1529 req
->handle
= wine_server_obj_handle( file
);
1530 req
->base
= wine_server_client_ptr( module
);
1531 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1532 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1533 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1534 req
->name
= wine_server_client_ptr( &wm
->ldr
.FullDllName
.Buffer
);
1535 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1536 wine_server_call( req
);
1540 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1542 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1544 wm
->ldr
.LoadCount
= 1;
1546 return STATUS_SUCCESS
;
1550 /***********************************************************************
1553 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1554 DWORD flags
, WINE_MODREF
** pwm
)
1556 char error
[256], dllname
[MAX_PATH
];
1557 const WCHAR
*name
, *p
;
1559 void *handle
= NULL
;
1560 struct builtin_load_info info
, *prev_info
;
1562 /* Fix the name in case we have a full path and extension */
1564 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1565 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1567 /* load_library will modify info.status. Note also that load_library can be
1568 * called several times, if the .so file we're loading has dependencies.
1569 * info.status will gather all the errors we may get while loading all these
1572 info
.load_path
= load_path
;
1573 info
.filename
= NULL
;
1574 info
.status
= STATUS_SUCCESS
;
1577 if (file
) /* we have a real file, try to load it */
1579 UNICODE_STRING nt_name
;
1580 ANSI_STRING unix_name
;
1582 TRACE("Trying built-in %s\n", debugstr_w(path
));
1584 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1585 return STATUS_DLL_NOT_FOUND
;
1587 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1589 RtlFreeUnicodeString( &nt_name
);
1590 return STATUS_DLL_NOT_FOUND
;
1592 prev_info
= builtin_load_info
;
1593 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1594 builtin_load_info
= &info
;
1595 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1596 builtin_load_info
= prev_info
;
1597 RtlFreeUnicodeString( &nt_name
);
1598 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1601 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1602 return STATUS_INVALID_IMAGE_FORMAT
;
1609 TRACE("Trying built-in %s\n", debugstr_w(name
));
1611 /* we don't want to depend on the current codepage here */
1612 len
= strlenW( name
) + 1;
1613 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1614 for (i
= 0; i
< len
; i
++)
1616 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1617 dllname
[i
] = (char)name
[i
];
1618 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1621 prev_info
= builtin_load_info
;
1622 builtin_load_info
= &info
;
1623 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1624 builtin_load_info
= prev_info
;
1629 /* The file does not exist -> WARN() */
1630 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1631 return STATUS_DLL_NOT_FOUND
;
1633 /* ERR() for all other errors (missing functions, ...) */
1634 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1635 return STATUS_PROCEDURE_NOT_FOUND
;
1639 if (info
.status
!= STATUS_SUCCESS
)
1641 wine_dll_unload( handle
);
1647 PLIST_ENTRY mark
, entry
;
1649 /* The constructor wasn't called, this means the .so is already
1650 * loaded under a different name. Try to find the wm for it. */
1652 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1653 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1655 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1656 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1658 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1659 TRACE( "Found %s at %p for builtin %s\n",
1660 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1664 wine_dll_unload( handle
); /* release the libdl refcount */
1665 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1666 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1670 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1671 info
.wm
->ldr
.LoadCount
= 1;
1672 info
.wm
->ldr
.SectionHandle
= handle
;
1676 return STATUS_SUCCESS
;
1680 /***********************************************************************
1683 * Find the full path (if any) of the dll from the activation context.
1685 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
1687 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
1688 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
1690 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
1691 ACTCTX_SECTION_KEYED_DATA data
;
1692 UNICODE_STRING nameW
;
1694 SIZE_T needed
, size
= 1024;
1697 RtlInitUnicodeString( &nameW
, libname
);
1698 data
.cbSize
= sizeof(data
);
1699 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
1700 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
1702 if (status
!= STATUS_SUCCESS
) return status
;
1706 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1708 status
= STATUS_NO_MEMORY
;
1711 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
1712 AssemblyDetailedInformationInActivationContext
,
1713 info
, size
, &needed
);
1714 if (status
== STATUS_SUCCESS
) break;
1715 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
1716 RtlFreeHeap( GetProcessHeap(), 0, info
);
1718 /* restart with larger buffer */
1721 if (!info
->lpAssemblyManifestPath
|| !info
->lpAssemblyDirectoryName
)
1723 status
= STATUS_SXS_KEY_NOT_FOUND
;
1727 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
1729 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1732 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
1734 /* manifest name does not match directory name, so it's not a global
1735 * windows/winsxs manifest; use the manifest directory name instead */
1736 dirlen
= p
- info
->lpAssemblyManifestPath
;
1737 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
1738 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1740 status
= STATUS_NO_MEMORY
;
1743 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
1745 strcpyW( p
, libname
);
1750 needed
= (windows_dir
.Length
+ sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+
1751 nameW
.Length
+ 2*sizeof(WCHAR
));
1753 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1755 status
= STATUS_NO_MEMORY
;
1758 memcpy( p
, windows_dir
.Buffer
, windows_dir
.Length
);
1759 p
+= windows_dir
.Length
/ sizeof(WCHAR
);
1760 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
1761 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
1762 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
1763 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1765 strcpyW( p
, libname
);
1767 RtlFreeHeap( GetProcessHeap(), 0, info
);
1768 RtlReleaseActivationContext( data
.hActCtx
);
1773 /***********************************************************************
1776 * Find the file (or already loaded module) for a given dll name.
1778 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1779 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1781 OBJECT_ATTRIBUTES attr
;
1783 UNICODE_STRING nt_name
;
1784 WCHAR
*file_part
, *ext
, *dllname
;
1787 /* first append .dll if needed */
1790 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1792 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1793 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1794 return STATUS_NO_MEMORY
;
1795 strcpyW( dllname
, libname
);
1796 strcatW( dllname
, dllW
);
1800 nt_name
.Buffer
= NULL
;
1802 if (!contains_path( libname
))
1805 WCHAR
*fullname
= NULL
;
1807 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1809 status
= find_actctx_dll( libname
, &fullname
);
1810 if (status
== STATUS_SUCCESS
)
1812 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
1813 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1814 libname
= dllname
= fullname
;
1816 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
1818 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1823 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1825 /* we need to search for it */
1826 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1829 if (len
>= *size
) goto overflow
;
1830 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
1832 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1834 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1835 return STATUS_NO_MEMORY
;
1837 attr
.Length
= sizeof(attr
);
1838 attr
.RootDirectory
= 0;
1839 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1840 attr
.ObjectName
= &nt_name
;
1841 attr
.SecurityDescriptor
= NULL
;
1842 attr
.SecurityQualityOfService
= NULL
;
1843 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1849 if (!contains_path( libname
))
1851 /* if libname doesn't contain a path at all, we simply return the name as is,
1852 * to be loaded as builtin */
1853 len
= strlenW(libname
) * sizeof(WCHAR
);
1854 if (len
>= *size
) goto overflow
;
1855 strcpyW( filename
, libname
);
1860 /* absolute path name, or relative path name but not found above */
1862 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1864 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1865 return STATUS_NO_MEMORY
;
1867 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1868 if (len
>= *size
) goto overflow
;
1869 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1870 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
1872 attr
.Length
= sizeof(attr
);
1873 attr
.RootDirectory
= 0;
1874 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1875 attr
.ObjectName
= &nt_name
;
1876 attr
.SecurityDescriptor
= NULL
;
1877 attr
.SecurityQualityOfService
= NULL
;
1878 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1881 RtlFreeUnicodeString( &nt_name
);
1882 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1883 return STATUS_SUCCESS
;
1886 RtlFreeUnicodeString( &nt_name
);
1887 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1888 *size
= len
+ sizeof(WCHAR
);
1889 return STATUS_BUFFER_TOO_SMALL
;
1893 /***********************************************************************
1894 * load_dll (internal)
1896 * Load a PE style module according to the load order.
1897 * The loader_section must be locked while calling this function.
1899 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1901 enum loadorder loadorder
;
1905 WINE_MODREF
*main_exe
;
1909 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1913 size
= sizeof(buffer
);
1916 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1917 if (nts
== STATUS_SUCCESS
) break;
1918 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1919 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1920 /* grow the buffer and retry */
1921 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1924 if (*pwm
) /* found already loaded module */
1926 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1928 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
)) fixup_imports( *pwm
, load_path
);
1930 TRACE("Found %s for %s at %p, count=%d\n",
1931 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1932 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1933 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1934 return STATUS_SUCCESS
;
1937 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1938 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1940 if (handle
&& is_fake_dll( handle
))
1942 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename
) );
1950 nts
= STATUS_NO_MEMORY
;
1953 nts
= STATUS_DLL_NOT_FOUND
;
1956 case LO_NATIVE_BUILTIN
:
1957 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
1960 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1961 if (nts
== STATUS_INVALID_FILE_FOR_SECTION
)
1962 /* not in PE format, maybe it's a builtin */
1963 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1965 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
1966 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1969 case LO_BUILTIN_NATIVE
:
1970 case LO_DEFAULT
: /* default is builtin,native */
1971 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1972 if (!handle
) break; /* nothing else we can try */
1973 /* file is not a builtin library, try without using the specified file */
1974 if (nts
!= STATUS_SUCCESS
)
1975 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1976 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
1977 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
1979 /* stub-only dll, try native */
1980 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
1981 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
1982 nts
= STATUS_DLL_NOT_FOUND
;
1984 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
1985 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1989 if (nts
== STATUS_SUCCESS
)
1991 /* Initialize DLL just loaded */
1992 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
1993 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
1994 (*pwm
)->ldr
.BaseAddress
);
1995 if (handle
) NtClose( handle
);
1996 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2000 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
2001 if (handle
) NtClose( handle
);
2002 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2006 /******************************************************************
2007 * LdrLoadDll (NTDLL.@)
2009 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
2010 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
2015 RtlEnterCriticalSection( &loader_section
);
2017 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2018 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
2020 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
2022 nts
= process_attach( wm
, NULL
);
2023 if (nts
!= STATUS_SUCCESS
)
2025 LdrUnloadDll(wm
->ldr
.BaseAddress
);
2029 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
2031 RtlLeaveCriticalSection( &loader_section
);
2036 /******************************************************************
2037 * LdrGetDllHandle (NTDLL.@)
2039 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
2047 RtlEnterCriticalSection( &loader_section
);
2049 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2052 size
= sizeof(buffer
);
2055 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
2056 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
2057 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
2058 /* grow the buffer and retry */
2059 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
2061 status
= STATUS_NO_MEMORY
;
2066 if (status
== STATUS_SUCCESS
)
2068 if (wm
) *base
= wm
->ldr
.BaseAddress
;
2069 else status
= STATUS_DLL_NOT_FOUND
;
2072 RtlLeaveCriticalSection( &loader_section
);
2073 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2078 /******************************************************************
2079 * LdrAddRefDll (NTDLL.@)
2081 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2083 NTSTATUS ret
= STATUS_SUCCESS
;
2086 if (flags
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2088 RtlEnterCriticalSection( &loader_section
);
2090 if ((wm
= get_modref( module
)))
2092 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2093 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2095 else ret
= STATUS_INVALID_PARAMETER
;
2097 RtlLeaveCriticalSection( &loader_section
);
2102 /***********************************************************************
2103 * LdrProcessRelocationBlock (NTDLL.@)
2105 * Apply relocations to a given page of a mapped PE image.
2107 IMAGE_BASE_RELOCATION
* WINAPI
LdrProcessRelocationBlock( void *page
, UINT count
,
2108 USHORT
*relocs
, INT_PTR delta
)
2112 USHORT offset
= *relocs
& 0xfff;
2113 int type
= *relocs
>> 12;
2116 case IMAGE_REL_BASED_ABSOLUTE
:
2118 case IMAGE_REL_BASED_HIGH
:
2119 *(short *)((char *)page
+ offset
) += HIWORD(delta
);
2121 case IMAGE_REL_BASED_LOW
:
2122 *(short *)((char *)page
+ offset
) += LOWORD(delta
);
2124 case IMAGE_REL_BASED_HIGHLOW
:
2125 *(int *)((char *)page
+ offset
) += delta
;
2128 case IMAGE_REL_BASED_DIR64
:
2129 *(INT_PTR
*)((char *)page
+ offset
) += delta
;
2133 FIXME("Unknown/unsupported fixup type %x.\n", type
);
2138 return (IMAGE_BASE_RELOCATION
*)relocs
; /* return address of next block */
2142 /******************************************************************
2143 * LdrQueryProcessModuleInformation
2146 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2147 ULONG buf_size
, ULONG
* req_size
)
2149 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2150 ULONG size
= sizeof(ULONG
);
2151 NTSTATUS nts
= STATUS_SUCCESS
;
2154 PLIST_ENTRY mark
, entry
;
2158 smi
->ModulesCount
= 0;
2160 RtlEnterCriticalSection( &loader_section
);
2161 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2162 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2164 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2165 size
+= sizeof(*sm
);
2166 if (size
<= buf_size
)
2168 sm
->Reserved1
= 0; /* FIXME */
2169 sm
->Reserved2
= 0; /* FIXME */
2170 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2171 sm
->ImageSize
= mod
->SizeOfImage
;
2172 sm
->Flags
= mod
->Flags
;
2174 sm
->Rank
= 0; /* FIXME */
2175 sm
->Unknown
= 0; /* FIXME */
2177 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2178 str
.Buffer
= (char*)sm
->Name
;
2179 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2180 ptr
= strrchr(str
.Buffer
, '\\');
2181 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2183 smi
->ModulesCount
++;
2186 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2188 RtlLeaveCriticalSection( &loader_section
);
2190 if (req_size
) *req_size
= size
;
2196 static NTSTATUS
query_dword_option( HANDLE hkey
, LPCWSTR name
, ULONG
*value
)
2202 KEY_VALUE_PARTIAL_INFORMATION
*info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2204 RtlInitUnicodeString( &str
, name
);
2206 size
= sizeof(buffer
) - sizeof(WCHAR
);
2207 if ((status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
)))
2210 if (info
->Type
!= REG_DWORD
)
2212 buffer
[size
/ sizeof(WCHAR
)] = 0;
2213 *value
= strtoulW( (WCHAR
*)info
->Data
, 0, 16 );
2215 else memcpy( value
, info
->Data
, sizeof(*value
) );
2219 static NTSTATUS
query_string_option( HANDLE hkey
, LPCWSTR name
, ULONG type
,
2220 void *data
, ULONG in_size
, ULONG
*out_size
)
2226 KEY_VALUE_PARTIAL_INFORMATION
*info
;
2227 static const int info_size
= FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION
, Data
);
2229 RtlInitUnicodeString( &str
, name
);
2231 size
= info_size
+ in_size
;
2232 if (!(buffer
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
2233 info
= (KEY_VALUE_PARTIAL_INFORMATION
*)buffer
;
2234 status
= NtQueryValueKey( hkey
, &str
, KeyValuePartialInformation
, buffer
, size
, &size
);
2235 if (!status
|| status
== STATUS_BUFFER_OVERFLOW
)
2237 if (out_size
) *out_size
= info
->DataLength
;
2238 if (data
&& !status
) memcpy( data
, info
->Data
, info
->DataLength
);
2240 RtlFreeHeap( GetProcessHeap(), 0, buffer
);
2245 /******************************************************************
2246 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2248 NTSTATUS WINAPI
LdrQueryImageFileExecutionOptions( const UNICODE_STRING
*key
, LPCWSTR value
, ULONG type
,
2249 void *data
, ULONG in_size
, ULONG
*out_size
)
2251 static const WCHAR optionsW
[] = {'M','a','c','h','i','n','e','\\',
2252 'S','o','f','t','w','a','r','e','\\',
2253 'M','i','c','r','o','s','o','f','t','\\',
2254 'W','i','n','d','o','w','s',' ','N','T','\\',
2255 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2256 'I','m','a','g','e',' ','F','i','l','e',' ',
2257 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2258 WCHAR path
[MAX_PATH
+ sizeof(optionsW
)/sizeof(WCHAR
)];
2259 OBJECT_ATTRIBUTES attr
;
2260 UNICODE_STRING name_str
;
2266 attr
.Length
= sizeof(attr
);
2267 attr
.RootDirectory
= 0;
2268 attr
.ObjectName
= &name_str
;
2269 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2270 attr
.SecurityDescriptor
= NULL
;
2271 attr
.SecurityQualityOfService
= NULL
;
2273 if ((p
= memrchrW( key
->Buffer
, '\\', key
->Length
/ sizeof(WCHAR
) ))) p
++;
2274 else p
= key
->Buffer
;
2275 len
= key
->Length
- (p
- key
->Buffer
) * sizeof(WCHAR
);
2276 name_str
.Buffer
= path
;
2277 name_str
.Length
= sizeof(optionsW
) + len
;
2278 name_str
.MaximumLength
= name_str
.Length
;
2279 memcpy( path
, optionsW
, sizeof(optionsW
) );
2280 memcpy( path
+ sizeof(optionsW
)/sizeof(WCHAR
), p
, len
);
2281 if ((status
= NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
))) return status
;
2283 if (type
== REG_DWORD
)
2285 if (out_size
) *out_size
= sizeof(ULONG
);
2286 if (in_size
>= sizeof(ULONG
)) status
= query_dword_option( hkey
, value
, data
);
2287 else status
= STATUS_BUFFER_OVERFLOW
;
2289 else status
= query_string_option( hkey
, value
, type
, data
, in_size
, out_size
);
2296 /******************************************************************
2297 * RtlDllShutdownInProgress (NTDLL.@)
2299 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2301 return process_detaching
;
2305 /******************************************************************
2306 * LdrShutdownProcess (NTDLL.@)
2309 void WINAPI
LdrShutdownProcess(void)
2312 process_detach( TRUE
, (LPVOID
)1 );
2315 /******************************************************************
2316 * LdrShutdownThread (NTDLL.@)
2319 void WINAPI
LdrShutdownThread(void)
2321 PLIST_ENTRY mark
, entry
;
2326 /* don't do any detach calls if process is exiting */
2327 if (process_detaching
) return;
2328 /* FIXME: there is still a race here */
2330 RtlEnterCriticalSection( &loader_section
);
2332 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2333 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2335 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2336 InInitializationOrderModuleList
);
2337 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2339 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2342 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2343 DLL_THREAD_DETACH
, NULL
);
2346 RtlLeaveCriticalSection( &loader_section
);
2347 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2351 /***********************************************************************
2355 static void free_modref( WINE_MODREF
*wm
)
2357 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2358 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2359 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2360 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2362 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2363 if (!TRACE_ON(module
))
2364 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2365 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2366 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2368 SERVER_START_REQ( unload_dll
)
2370 req
->base
= wine_server_client_ptr( wm
->ldr
.BaseAddress
);
2371 wine_server_call( req
);
2375 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2376 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2377 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2378 if (cached_modref
== wm
) cached_modref
= NULL
;
2379 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2380 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2381 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2384 /***********************************************************************
2385 * MODULE_FlushModrefs
2387 * Remove all unused modrefs and call the internal unloading routines
2388 * for the library type.
2390 * The loader_section must be locked while calling this function.
2392 static void MODULE_FlushModrefs(void)
2394 PLIST_ENTRY mark
, entry
, prev
;
2398 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2399 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2401 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2402 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2403 prev
= entry
->Blink
;
2404 if (!mod
->LoadCount
) free_modref( wm
);
2407 /* check load order list too for modules that haven't been initialized yet */
2408 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2409 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2411 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2412 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2413 prev
= entry
->Blink
;
2414 if (!mod
->LoadCount
) free_modref( wm
);
2418 /***********************************************************************
2419 * MODULE_DecRefCount
2421 * The loader_section must be locked while calling this function.
2423 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2427 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2430 if ( wm
->ldr
.LoadCount
<= 0 )
2433 --wm
->ldr
.LoadCount
;
2434 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2436 if ( wm
->ldr
.LoadCount
== 0 )
2438 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2440 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2442 MODULE_DecRefCount( wm
->deps
[i
] );
2444 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2448 /******************************************************************
2449 * LdrUnloadDll (NTDLL.@)
2453 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2455 NTSTATUS retv
= STATUS_SUCCESS
;
2457 TRACE("(%p)\n", hModule
);
2459 RtlEnterCriticalSection( &loader_section
);
2461 /* if we're stopping the whole process (and forcing the removal of all
2462 * DLLs) the library will be freed anyway
2464 if (!process_detaching
)
2469 if ((wm
= get_modref( hModule
)) != NULL
)
2471 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2473 /* Recursively decrement reference counts */
2474 MODULE_DecRefCount( wm
);
2476 /* Call process detach notifications */
2477 if ( free_lib_count
<= 1 )
2479 process_detach( FALSE
, NULL
);
2480 MODULE_FlushModrefs();
2486 retv
= STATUS_DLL_NOT_FOUND
;
2491 RtlLeaveCriticalSection( &loader_section
);
2496 /***********************************************************************
2497 * RtlImageNtHeader (NTDLL.@)
2499 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2501 IMAGE_NT_HEADERS
*ret
;
2505 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2508 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2510 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2511 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2523 /***********************************************************************
2524 * attach_process_dlls
2526 * Initial attach to all the dlls loaded by the process.
2528 static NTSTATUS
attach_process_dlls( void *wm
)
2532 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2534 RtlEnterCriticalSection( &loader_section
);
2535 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2537 if (last_failed_modref
)
2538 ERR( "%s failed to initialize, aborting\n",
2539 debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2542 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2543 RtlLeaveCriticalSection( &loader_section
);
2548 /***********************************************************************
2549 * load_global_options
2551 static void load_global_options(void)
2553 static const WCHAR sessionW
[] = {'M','a','c','h','i','n','e','\\',
2554 'S','y','s','t','e','m','\\',
2555 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2556 'C','o','n','t','r','o','l','\\',
2557 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2558 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2559 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};
2560 static const WCHAR heapresW
[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2561 static const WCHAR heapcommitW
[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2562 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};
2563 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};
2565 OBJECT_ATTRIBUTES attr
;
2566 UNICODE_STRING name_str
;
2570 attr
.Length
= sizeof(attr
);
2571 attr
.RootDirectory
= 0;
2572 attr
.ObjectName
= &name_str
;
2573 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
2574 attr
.SecurityDescriptor
= NULL
;
2575 attr
.SecurityQualityOfService
= NULL
;
2576 RtlInitUnicodeString( &name_str
, sessionW
);
2578 if (NtOpenKey( &hkey
, KEY_QUERY_VALUE
, &attr
)) return;
2580 query_dword_option( hkey
, globalflagW
, &NtCurrentTeb()->Peb
->NtGlobalFlag
);
2582 query_dword_option( hkey
, critsectW
, &value
);
2583 NtCurrentTeb()->Peb
->CriticalSectionTimeout
.QuadPart
= (ULONGLONG
)value
* -10000000;
2585 query_dword_option( hkey
, heapresW
, &value
);
2586 NtCurrentTeb()->Peb
->HeapSegmentReserve
= value
;
2588 query_dword_option( hkey
, heapcommitW
, &value
);
2589 NtCurrentTeb()->Peb
->HeapSegmentCommit
= value
;
2591 query_dword_option( hkey
, decommittotalW
, &value
);
2592 NtCurrentTeb()->Peb
->HeapDeCommitTotalFreeThreshold
= value
;
2594 query_dword_option( hkey
, decommitfreeW
, &value
);
2595 NtCurrentTeb()->Peb
->HeapDeCommitFreeBlockThreshold
= value
;
2601 /***********************************************************************
2604 static void start_process( void *kernel_start
)
2606 call_thread_entry_point( kernel_start
, NtCurrentTeb()->Peb
);
2609 /******************************************************************
2610 * LdrInitializeThunk (NTDLL.@)
2613 void WINAPI
LdrInitializeThunk( void *kernel_start
, ULONG_PTR unknown2
,
2614 ULONG_PTR unknown3
, ULONG_PTR unknown4
)
2616 static const WCHAR globalflagW
[] = {'G','l','o','b','a','l','F','l','a','g',0};
2620 PEB
*peb
= NtCurrentTeb()->Peb
;
2621 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
2623 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
2625 /* allocate the modref for the main exe (if not already done) */
2626 wm
= get_modref( peb
->ImageBaseAddress
);
2628 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
2630 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
2634 peb
->LoaderLock
= &loader_section
;
2635 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2636 if (!peb
->ProcessParameters
->WindowTitle
.Buffer
)
2637 peb
->ProcessParameters
->WindowTitle
= wm
->ldr
.FullDllName
;
2638 version_init( wm
->ldr
.FullDllName
.Buffer
);
2640 LdrQueryImageFileExecutionOptions( &peb
->ProcessParameters
->ImagePathName
, globalflagW
,
2641 REG_DWORD
, &peb
->NtGlobalFlag
, sizeof(peb
->NtGlobalFlag
), NULL
);
2643 /* the main exe needs to be the first in the load order list */
2644 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2645 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2647 if ((status
= virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS
) goto error
;
2648 if ((status
= server_init_process_done()) != STATUS_SUCCESS
) goto error
;
2651 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2652 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2653 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2654 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2655 heap_set_debug_flags( GetProcessHeap() );
2657 status
= wine_call_on_stack( attach_process_dlls
, wm
, NtCurrentTeb()->Tib
.StackBase
);
2658 if (status
!= STATUS_SUCCESS
) goto error
;
2660 virtual_release_address_space( nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
);
2661 virtual_clear_thread_stack();
2662 wine_switch_to_stack( start_process
, kernel_start
, NtCurrentTeb()->Tib
.StackBase
);
2665 ERR( "Main exe initialization for %s failed, status %x\n",
2666 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2667 NtTerminateProcess( GetCurrentProcess(), status
);
2671 /***********************************************************************
2672 * RtlImageDirectoryEntryToData (NTDLL.@)
2674 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2676 const IMAGE_NT_HEADERS
*nt
;
2679 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2681 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2684 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2685 if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR64_MAGIC
)
2687 const IMAGE_NT_HEADERS64
*nt64
= (const IMAGE_NT_HEADERS64
*)nt
;
2689 if (dir
>= nt64
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2690 if (!(addr
= nt64
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2691 *size
= nt64
->OptionalHeader
.DataDirectory
[dir
].Size
;
2692 if (image
|| addr
< nt64
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2694 else if (nt
->OptionalHeader
.Magic
== IMAGE_NT_OPTIONAL_HDR32_MAGIC
)
2696 const IMAGE_NT_HEADERS32
*nt32
= (const IMAGE_NT_HEADERS32
*)nt
;
2698 if (dir
>= nt32
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2699 if (!(addr
= nt32
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2700 *size
= nt32
->OptionalHeader
.DataDirectory
[dir
].Size
;
2701 if (image
|| addr
< nt32
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2705 /* not mapped as image, need to find the section containing the virtual address */
2706 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2710 /***********************************************************************
2711 * RtlImageRvaToSection (NTDLL.@)
2713 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2714 HMODULE module
, DWORD rva
)
2717 const IMAGE_SECTION_HEADER
*sec
;
2719 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2720 nt
->FileHeader
.SizeOfOptionalHeader
);
2721 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2723 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2724 return (PIMAGE_SECTION_HEADER
)sec
;
2730 /***********************************************************************
2731 * RtlImageRvaToVa (NTDLL.@)
2733 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2734 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2736 IMAGE_SECTION_HEADER
*sec
;
2738 if (section
&& *section
) /* try this section first */
2741 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2744 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2746 if (section
) *section
= sec
;
2747 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2751 /***********************************************************************
2752 * RtlPcToFileHeader (NTDLL.@)
2754 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
2759 RtlEnterCriticalSection( &loader_section
);
2760 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
2761 RtlLeaveCriticalSection( &loader_section
);
2767 /***********************************************************************
2768 * NtLoadDriver (NTDLL.@)
2769 * ZwLoadDriver (NTDLL.@)
2771 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2773 FIXME("(%p), stub!\n",DriverServiceName
);
2774 return STATUS_NOT_IMPLEMENTED
;
2778 /***********************************************************************
2779 * NtUnloadDriver (NTDLL.@)
2780 * ZwUnloadDriver (NTDLL.@)
2782 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2784 FIXME("(%p), stub!\n",DriverServiceName
);
2785 return STATUS_NOT_IMPLEMENTED
;
2789 /******************************************************************
2792 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2794 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2799 /******************************************************************
2800 * __wine_init_windows_dir (NTDLL.@)
2802 * Windows and system dir initialization once kernel32 has been loaded.
2804 void CDECL
__wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2806 PLIST_ENTRY mark
, entry
;
2809 DIR_init_windows_dir( windir
, sysdir
);
2810 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
2812 /* prepend the system dir to the name of the already created modules */
2813 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2814 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2816 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2818 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2820 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2821 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2822 if (!buffer
) continue;
2823 strcpyW( buffer
, system_dir
.Buffer
);
2824 p
= buffer
+ strlenW( buffer
);
2825 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2826 strcpyW( p
, mod
->FullDllName
.Buffer
);
2827 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2828 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2833 /***********************************************************************
2834 * __wine_process_init
2836 void __wine_process_init(void)
2838 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2842 ANSI_STRING func_name
;
2843 void (* DECLSPEC_NORETURN CDECL init_func
)(void);
2844 extern mode_t FILE_umask
;
2846 main_exe_file
= thread_init();
2848 /* retrieve current umask */
2849 FILE_umask
= umask(0777);
2850 umask( FILE_umask
);
2852 load_global_options();
2854 /* setup the load callback and create ntdll modref */
2855 wine_dll_set_callback( load_builtin_callback
);
2857 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
2859 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
2862 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
2863 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
2865 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2866 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2867 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2869 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);