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"
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
32 #define WIN32_NO_STATUS
37 #include "wine/exception.h"
38 #include "wine/library.h"
39 #include "wine/pthread.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
43 #include "ntdll_misc.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module
);
47 WINE_DECLARE_DEBUG_CHANNEL(relay
);
48 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
49 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
50 WINE_DECLARE_DEBUG_CHANNEL(imports
);
52 /* we don't want to include winuser.h */
53 #define RT_MANIFEST ((ULONG_PTR)24)
54 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
56 extern struct wine_pthread_functions pthread_functions
;
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 */
101 UNICODE_STRING windows_dir
= { 0, 0, NULL
}; /* windows directory */
102 UNICODE_STRING system_dir
= { 0, 0, NULL
}; /* system directory */
104 static RTL_CRITICAL_SECTION loader_section
;
105 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
107 0, 0, &loader_section
,
108 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
109 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
111 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
113 static WINE_MODREF
*cached_modref
;
114 static WINE_MODREF
*current_modref
;
115 static WINE_MODREF
*last_failed_modref
;
117 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
118 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
);
119 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
120 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
);
122 /* convert PE image VirtualAddress to Real Address */
123 static inline void *get_rva( HMODULE module
, DWORD va
)
125 return (void *)((char *)module
+ va
);
128 /* check whether the file name contains a path */
129 static inline int contains_path( LPCWSTR name
)
131 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
134 /* convert from straight ASCII to Unicode without depending on the current codepage */
135 static inline void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
137 while (len
--) *dst
++ = (unsigned char)*src
++;
141 /*************************************************************************
142 * call_dll_entry_point
144 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
145 * their entry point, so we need a small asm wrapper.
148 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
149 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
157 "movl 8(%ebp),%eax\n\t"
159 "leal -4(%ebp),%esp\n\t"
164 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
165 UINT reason
, void *reserved
)
167 return proc( module
, reason
, reserved
);
169 #endif /* __i386__ */
173 /*************************************************************************
176 * Entry point for stub functions.
178 static void stub_entry_point( const char *dll
, const char *name
, ... )
180 EXCEPTION_RECORD rec
;
182 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
183 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
184 rec
.ExceptionRecord
= NULL
;
186 rec
.ExceptionAddress
= __builtin_return_address(0);
188 rec
.ExceptionAddress
= *((void **)&dll
- 1);
190 rec
.NumberParameters
= 2;
191 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
192 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
193 for (;;) RtlRaiseException( &rec
);
197 #include "pshpack1.h"
200 BYTE popl_eax
; /* popl %eax */
201 BYTE pushl1
; /* pushl $name */
203 BYTE pushl2
; /* pushl $dll */
205 BYTE pushl_eax
; /* pushl %eax */
206 BYTE jmp
; /* jmp stub_entry_point */
211 /*************************************************************************
214 * Allocate a stub entry point.
216 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
218 #define MAX_SIZE 65536
219 static struct stub
*stubs
;
220 static unsigned int nb_stubs
;
223 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
227 SIZE_T size
= MAX_SIZE
;
228 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
229 MEM_COMMIT
, PAGE_EXECUTE_WRITECOPY
) != STATUS_SUCCESS
)
232 stub
= &stubs
[nb_stubs
++];
233 stub
->popl_eax
= 0x58; /* popl %eax */
234 stub
->pushl1
= 0x68; /* pushl $name */
236 stub
->pushl2
= 0x68; /* pushl $dll */
238 stub
->pushl_eax
= 0x50; /* pushl %eax */
239 stub
->jmp
= 0xe9; /* jmp stub_entry_point */
240 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
241 return (ULONG_PTR
)stub
;
245 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
246 #endif /* __i386__ */
249 /*************************************************************************
252 * Looks for the referenced HMODULE in the current process
253 * The loader_section must be locked while calling this function.
255 static WINE_MODREF
*get_modref( HMODULE hmod
)
257 PLIST_ENTRY mark
, entry
;
260 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
262 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
263 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
265 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
266 if (mod
->BaseAddress
== hmod
)
267 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
268 if (mod
->BaseAddress
> (void*)hmod
) break;
274 /**********************************************************************
275 * find_basename_module
277 * Find a module from its base name.
278 * The loader_section must be locked while calling this function
280 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
282 PLIST_ENTRY mark
, entry
;
284 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
285 return cached_modref
;
287 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
288 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
290 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
291 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
293 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
294 return cached_modref
;
301 /**********************************************************************
302 * find_fullname_module
304 * Find a module from its full path name.
305 * The loader_section must be locked while calling this function
307 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
309 PLIST_ENTRY mark
, entry
;
311 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
312 return cached_modref
;
314 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
315 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
317 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
318 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
320 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
321 return cached_modref
;
328 /*************************************************************************
329 * find_forwarded_export
331 * Find the final function pointer for a forwarded function.
332 * The loader_section must be locked while calling this function.
334 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
, LPCWSTR load_path
)
336 const IMAGE_EXPORT_DIRECTORY
*exports
;
340 const char *end
= strrchr(forward
, '.');
343 if (!end
) return NULL
;
344 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
)) return NULL
;
345 ascii_to_unicode( mod_name
, forward
, end
- forward
);
346 mod_name
[end
- forward
] = 0;
347 if (!strchrW( mod_name
, '.' ))
349 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
350 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
353 if (!(wm
= find_basename_module( mod_name
)))
355 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name
), forward
);
356 if (load_dll( load_path
, mod_name
, 0, &wm
) == STATUS_SUCCESS
&&
357 !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
359 if (process_attach( wm
, NULL
) != STATUS_SUCCESS
)
361 LdrUnloadDll( wm
->ldr
.BaseAddress
);
368 ERR( "module not found for forward '%s' used by %s\n",
369 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
373 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
374 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
375 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1, load_path
);
379 ERR("function not found for forward '%s' used by %s."
380 " If you are using builtin %s, try using the native one instead.\n",
381 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
382 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
388 /*************************************************************************
389 * find_ordinal_export
391 * Find an exported function by ordinal.
392 * The exports base must have been subtracted from the ordinal already.
393 * The loader_section must be locked while calling this function.
395 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
396 DWORD exp_size
, DWORD ordinal
, LPCWSTR load_path
)
399 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
401 if (ordinal
>= exports
->NumberOfFunctions
)
403 TRACE(" ordinal %d out of range!\n", ordinal
+ exports
->Base
);
406 if (!functions
[ordinal
]) return NULL
;
408 proc
= get_rva( module
, functions
[ordinal
] );
410 /* if the address falls into the export dir, it's a forward */
411 if (((const char *)proc
>= (const char *)exports
) &&
412 ((const char *)proc
< (const char *)exports
+ exp_size
))
413 return find_forwarded_export( module
, (const char *)proc
, load_path
);
417 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
418 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
422 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
423 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
429 /*************************************************************************
432 * Find an exported function by name.
433 * The loader_section must be locked while calling this function.
435 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
436 DWORD exp_size
, const char *name
, int hint
, LPCWSTR load_path
)
438 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
439 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
440 int min
= 0, max
= exports
->NumberOfNames
- 1;
442 /* first check the hint */
443 if (hint
>= 0 && hint
<= max
)
445 char *ename
= get_rva( module
, names
[hint
] );
446 if (!strcmp( ename
, name
))
447 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
], load_path
);
450 /* then do a binary search */
453 int res
, pos
= (min
+ max
) / 2;
454 char *ename
= get_rva( module
, names
[pos
] );
455 if (!(res
= strcmp( ename
, name
)))
456 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
], load_path
);
457 if (res
> 0) max
= pos
- 1;
465 /*************************************************************************
468 * Import the dll specified by the given import descriptor.
469 * The loader_section must be locked while calling this function.
471 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
476 const IMAGE_EXPORT_DIRECTORY
*exports
;
478 const IMAGE_THUNK_DATA
*import_list
;
479 IMAGE_THUNK_DATA
*thunk_list
;
481 const char *name
= get_rva( module
, descr
->Name
);
482 DWORD len
= strlen(name
);
484 SIZE_T protect_size
= 0;
487 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
488 if (descr
->u
.OriginalFirstThunk
)
489 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
491 import_list
= thunk_list
;
493 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
495 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
497 ascii_to_unicode( buffer
, name
, len
);
499 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
501 else /* need to allocate a larger buffer */
503 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
504 if (!ptr
) return NULL
;
505 ascii_to_unicode( ptr
, name
, len
);
507 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
508 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
513 if (status
== STATUS_DLL_NOT_FOUND
)
514 ERR("Library %s (which is needed by %s) not found\n",
515 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
517 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
518 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
522 /* unprotect the import address table since it can be located in
523 * readonly section */
524 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
525 protect_base
= thunk_list
;
526 protect_size
*= sizeof(*thunk_list
);
527 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
528 &protect_size
, PAGE_WRITECOPY
, &protect_old
);
530 imp_mod
= wmImp
->ldr
.BaseAddress
;
531 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
535 /* set all imported function to deadbeef */
536 while (import_list
->u1
.Ordinal
)
538 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
540 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
541 WARN("No implementation for %s.%d", name
, ordinal
);
542 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
546 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
547 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
548 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
550 WARN(" imported from %s, allocating stub %p\n",
551 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
552 (void *)thunk_list
->u1
.Function
);
559 while (import_list
->u1
.Ordinal
)
561 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
563 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
565 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
566 ordinal
- exports
->Base
, load_path
);
567 if (!thunk_list
->u1
.Function
)
569 thunk_list
->u1
.Function
= allocate_stub( name
, IntToPtr(ordinal
) );
570 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
571 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
572 (void *)thunk_list
->u1
.Function
);
574 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
576 else /* import by name */
578 IMAGE_IMPORT_BY_NAME
*pe_name
;
579 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
580 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
581 (const char*)pe_name
->Name
,
582 pe_name
->Hint
, load_path
);
583 if (!thunk_list
->u1
.Function
)
585 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
586 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
587 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
588 (void *)thunk_list
->u1
.Function
);
590 TRACE_(imports
)("--- %s %s.%d = %p\n",
591 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
598 /* restore old protection of the import address table */
599 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
604 /***********************************************************************
605 * create_module_activation_context
607 static NTSTATUS
create_module_activation_context( LDR_MODULE
*module
)
610 LDR_RESOURCE_INFO info
;
611 const IMAGE_RESOURCE_DATA_ENTRY
*entry
;
613 info
.Type
= RT_MANIFEST
;
614 info
.Name
= ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
616 if (!(status
= LdrFindResource_U( module
->BaseAddress
, &info
, 3, &entry
)))
619 ctx
.cbSize
= sizeof(ctx
);
621 ctx
.dwFlags
= ACTCTX_FLAG_RESOURCE_NAME_VALID
| ACTCTX_FLAG_HMODULE_VALID
;
622 ctx
.hModule
= module
->BaseAddress
;
623 ctx
.lpResourceName
= (LPCWSTR
)ISOLATIONAWARE_MANIFEST_RESOURCE_ID
;
624 status
= RtlCreateActivationContext( &module
->ActivationContext
, &ctx
);
630 /****************************************************************
633 * Fixup all imports of a given module.
634 * The loader_section must be locked while calling this function.
636 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
639 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
645 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
646 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
648 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
649 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
650 return STATUS_SUCCESS
;
653 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
655 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
657 if (!create_module_activation_context( &wm
->ldr
))
658 RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
660 /* Allocate module dependency list */
661 wm
->nDeps
= nb_imports
;
662 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
664 /* load the imported modules. They are automatically
665 * added to the modref list of the process.
667 prev
= current_modref
;
669 status
= STATUS_SUCCESS
;
670 for (i
= 0; i
< nb_imports
; i
++)
672 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
673 status
= STATUS_DLL_NOT_FOUND
;
675 current_modref
= prev
;
676 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
681 /*************************************************************************
684 * Allocate a WINE_MODREF structure and add it to the process list
685 * The loader_section must be locked while calling this function.
687 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
691 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
692 PLIST_ENTRY entry
, mark
;
694 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
699 wm
->ldr
.BaseAddress
= hModule
;
700 wm
->ldr
.EntryPoint
= NULL
;
701 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
702 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
703 wm
->ldr
.LoadCount
= 1;
704 wm
->ldr
.TlsIndex
= -1;
705 wm
->ldr
.SectionHandle
= NULL
;
706 wm
->ldr
.CheckSum
= 0;
707 wm
->ldr
.TimeDateStamp
= 0;
708 wm
->ldr
.ActivationContext
= 0;
710 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
711 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
712 else p
= wm
->ldr
.FullDllName
.Buffer
;
713 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
715 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
717 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
718 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
719 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
722 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
723 &wm
->ldr
.InLoadOrderModuleList
);
725 /* insert module in MemoryList, sorted in increasing base addresses */
726 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
727 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
729 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
732 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
733 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
734 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
735 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
737 /* wait until init is called for inserting into this list */
738 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
739 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
741 if (!(nt
->OptionalHeader
.DllCharacteristics
& IMAGE_DLLCHARACTERISTICS_NX_COMPAT
))
743 WARN( "disabling no-exec because of %s\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
) );
744 VIRTUAL_SetForceExec( TRUE
);
750 /*************************************************************************
753 * Allocate the process-wide structure for module TLS storage.
755 static NTSTATUS
alloc_process_tls(void)
757 PLIST_ENTRY mark
, entry
;
759 const IMAGE_TLS_DIRECTORY
*dir
;
762 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
763 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
765 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
766 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
767 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
769 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
771 tls_total_size
+= size
;
774 if (!tls_module_count
) return STATUS_SUCCESS
;
776 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
778 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
779 if (!tls_dirs
) return STATUS_NO_MEMORY
;
781 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
783 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
784 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
785 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
788 *(DWORD
*)dir
->AddressOfIndex
= i
;
790 mod
->LoadCount
= -1; /* can't unload it */
793 return STATUS_SUCCESS
;
797 /*************************************************************************
800 * Allocate the per-thread structure for module TLS storage.
802 static NTSTATUS
alloc_thread_tls(void)
808 if (!tls_module_count
) return STATUS_SUCCESS
;
810 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0,
811 tls_module_count
* sizeof(*pointers
) )))
812 return STATUS_NO_MEMORY
;
814 if (!(data
= RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size
)))
816 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
817 return STATUS_NO_MEMORY
;
820 for (i
= 0; i
< tls_module_count
; i
++)
822 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
823 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
825 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
826 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
827 (void *)dir
->StartAddressOfRawData
, data
);
830 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
832 memset( data
, 0, dir
->SizeOfZeroFill
);
833 data
+= dir
->SizeOfZeroFill
;
835 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
836 return STATUS_SUCCESS
;
840 /*************************************************************************
843 static void call_tls_callbacks( HMODULE module
, UINT reason
)
845 const IMAGE_TLS_DIRECTORY
*dir
;
846 const PIMAGE_TLS_CALLBACK
*callback
;
849 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
850 if (!dir
|| !dir
->AddressOfCallBacks
) return;
852 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
855 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
856 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
859 (*callback
)( module
, reason
, NULL
);
864 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
865 GetCurrentThreadId(), callback
, module
, reason_names
[reason
] );
870 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
871 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
876 /*************************************************************************
879 static NTSTATUS
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
882 NTSTATUS status
= STATUS_SUCCESS
;
883 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
884 void *module
= wm
->ldr
.BaseAddress
;
887 /* Skip calls for modules loaded with special load flags */
889 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return STATUS_SUCCESS
;
890 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
891 if (!entry
) return STATUS_SUCCESS
;
895 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
896 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
897 mod_name
[len
/ sizeof(WCHAR
)] = 0;
898 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
899 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
900 reason_names
[reason
], lpReserved
);
902 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
903 reason_names
[reason
], lpReserved
);
907 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
909 status
= STATUS_DLL_INIT_FAILED
;
914 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
915 GetCurrentThreadId(), entry
, module
, reason_names
[reason
], lpReserved
);
916 status
= GetExceptionCode();
920 /* The state of the module list may have changed due to the call
921 to the dll. We cannot assume that this module has not been
924 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
925 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
926 reason_names
[reason
], lpReserved
, retv
);
927 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
933 /*************************************************************************
936 * Send the process attach notification to all DLLs the given module
937 * depends on (recursively). This is somewhat complicated due to the fact that
939 * - we have to respect the module dependencies, i.e. modules implicitly
940 * referenced by another module have to be initialized before the module
941 * itself can be initialized
943 * - the initialization routine of a DLL can itself call LoadLibrary,
944 * thereby introducing a whole new set of dependencies (even involving
945 * the 'old' modules) at any time during the whole process
947 * (Note that this routine can be recursively entered not only directly
948 * from itself, but also via LoadLibrary from one of the called initialization
951 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
952 * the process *detach* notifications to be sent in the correct order.
953 * This must not only take into account module dependencies, but also
954 * 'hidden' dependencies created by modules calling LoadLibrary in their
955 * attach notification routine.
957 * The strategy is rather simple: we move a WINE_MODREF to the head of the
958 * list after the attach notification has returned. This implies that the
959 * detach notifications are called in the reverse of the sequence the attach
960 * notifications *returned*.
962 * The loader_section must be locked while calling this function.
964 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
966 NTSTATUS status
= STATUS_SUCCESS
;
970 if (process_detaching
) return status
;
972 /* prevent infinite recursion in case of cyclical dependencies */
973 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
974 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
977 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
979 /* Tag current MODREF to prevent recursive loop */
980 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
981 if (lpReserved
) wm
->ldr
.LoadCount
= -1; /* pin it if imported by the main exe */
982 if (wm
->ldr
.ActivationContext
) RtlActivateActivationContext( 0, wm
->ldr
.ActivationContext
, &cookie
);
984 /* Recursively attach all DLLs this one depends on */
985 for ( i
= 0; i
< wm
->nDeps
; i
++ )
987 if (!wm
->deps
[i
]) continue;
988 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
991 /* Call DLL entry point */
992 if (status
== STATUS_SUCCESS
)
994 WINE_MODREF
*prev
= current_modref
;
996 status
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
997 if (status
== STATUS_SUCCESS
)
998 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
1001 /* point to the name so LdrInitializeThunk can print it */
1002 last_failed_modref
= wm
;
1003 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1005 current_modref
= prev
;
1008 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
1009 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
1010 &wm
->ldr
.InInitializationOrderModuleList
);
1012 if (wm
->ldr
.ActivationContext
) RtlDeactivateActivationContext( 0, cookie
);
1013 /* Remove recursion flag */
1014 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
1016 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
1021 /**********************************************************************
1022 * attach_implicitly_loaded_dlls
1024 * Attach to the (builtin) dlls that have been implicitly loaded because
1025 * of a dependency at the Unix level, but not imported at the Win32 level.
1027 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
1031 PLIST_ENTRY mark
, entry
;
1033 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1034 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1036 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1038 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
1039 TRACE( "found implicitly loaded %s, attaching to it\n",
1040 debugstr_w(mod
->BaseDllName
.Buffer
));
1041 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
1042 break; /* restart the search from the start */
1044 if (entry
== mark
) break; /* nothing found */
1049 /*************************************************************************
1052 * Send DLL process detach notifications. See the comment about calling
1053 * sequence at process_attach. Unless the bForceDetach flag
1054 * is set, only DLLs with zero refcount are notified.
1056 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
1058 PLIST_ENTRY mark
, entry
;
1061 RtlEnterCriticalSection( &loader_section
);
1062 if (bForceDetach
) process_detaching
= 1;
1063 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1066 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1068 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1069 InInitializationOrderModuleList
);
1070 /* Check whether to detach this DLL */
1071 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1073 if ( mod
->LoadCount
&& !bForceDetach
)
1076 /* Call detach notification */
1077 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
1078 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1079 DLL_PROCESS_DETACH
, lpReserved
);
1081 /* Restart at head of WINE_MODREF list, as entries might have
1082 been added and/or removed while performing the call ... */
1085 } while (entry
!= mark
);
1087 RtlLeaveCriticalSection( &loader_section
);
1090 /*************************************************************************
1091 * MODULE_DllThreadAttach
1093 * Send DLL thread attach notifications. These are sent in the
1094 * reverse sequence of process detach notification.
1097 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1099 PLIST_ENTRY mark
, entry
;
1103 /* don't do any attach calls if process is exiting */
1104 if (process_detaching
) return STATUS_SUCCESS
;
1105 /* FIXME: there is still a race here */
1107 RtlEnterCriticalSection( &loader_section
);
1109 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1111 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1112 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1114 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1115 InInitializationOrderModuleList
);
1116 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1118 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1121 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1122 DLL_THREAD_ATTACH
, lpReserved
);
1126 RtlLeaveCriticalSection( &loader_section
);
1130 /******************************************************************
1131 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1134 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1137 NTSTATUS ret
= STATUS_SUCCESS
;
1139 RtlEnterCriticalSection( &loader_section
);
1141 wm
= get_modref( hModule
);
1142 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1143 ret
= STATUS_DLL_NOT_FOUND
;
1145 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1147 RtlLeaveCriticalSection( &loader_section
);
1152 /******************************************************************
1153 * LdrFindEntryForAddress (NTDLL.@)
1155 * The loader_section must be locked while calling this function
1157 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1159 PLIST_ENTRY mark
, entry
;
1162 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1163 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1165 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1166 if ((const void *)mod
->BaseAddress
<= addr
&&
1167 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1170 return STATUS_SUCCESS
;
1172 if ((const void *)mod
->BaseAddress
> addr
) break;
1174 return STATUS_NO_MORE_ENTRIES
;
1177 /******************************************************************
1178 * LdrLockLoaderLock (NTDLL.@)
1180 * Note: flags are not implemented.
1181 * Flag 0x01 is used to raise exceptions on errors.
1182 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1184 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1186 if (flags
) FIXME( "flags %x not supported\n", flags
);
1188 if (result
) *result
= 1;
1189 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1190 RtlEnterCriticalSection( &loader_section
);
1191 *magic
= GetCurrentThreadId();
1192 return STATUS_SUCCESS
;
1196 /******************************************************************
1197 * LdrUnlockLoaderUnlock (NTDLL.@)
1199 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1203 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1204 RtlLeaveCriticalSection( &loader_section
);
1206 return STATUS_SUCCESS
;
1210 /******************************************************************
1211 * LdrGetProcedureAddress (NTDLL.@)
1213 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1214 ULONG ord
, PVOID
*address
)
1216 IMAGE_EXPORT_DIRECTORY
*exports
;
1218 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1220 RtlEnterCriticalSection( &loader_section
);
1222 /* check if the module itself is invalid to return the proper error */
1223 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1224 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1225 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1227 LPCWSTR load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1228 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1, load_path
)
1229 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
, load_path
);
1233 ret
= STATUS_SUCCESS
;
1237 RtlLeaveCriticalSection( &loader_section
);
1242 /***********************************************************************
1245 * Check if a loaded native dll is a Wine fake dll.
1247 static BOOL
is_fake_dll( const void *base
)
1249 static const char fakedll_signature
[] = "Wine placeholder DLL";
1250 const IMAGE_DOS_HEADER
*dos
= base
;
1252 if (dos
->e_lfanew
>= sizeof(*dos
) + sizeof(fakedll_signature
) &&
1253 !memcmp( dos
+ 1, fakedll_signature
, sizeof(fakedll_signature
) )) return TRUE
;
1258 /***********************************************************************
1259 * get_builtin_fullname
1261 * Build the full pathname for a builtin dll.
1263 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1265 static const WCHAR soW
[] = {'.','s','o',0};
1266 WCHAR
*p
, *fullname
;
1267 size_t i
, len
= strlen(filename
);
1269 /* check if path can correspond to the dll we have */
1270 if (path
&& (p
= strrchrW( path
, '\\' )))
1273 for (i
= 0; i
< len
; i
++)
1274 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1275 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1277 /* the filename matches, use path as the full path */
1279 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1281 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1288 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1289 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1291 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1292 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1293 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1294 ascii_to_unicode( p
, filename
, len
+ 1 );
1300 /***********************************************************************
1301 * load_builtin_callback
1303 * Load a library in memory; callback function for wine_dll_register
1305 static void load_builtin_callback( void *module
, const char *filename
)
1307 static const WCHAR emptyW
[1];
1309 IMAGE_NT_HEADERS
*nt
;
1312 const WCHAR
*load_path
;
1317 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1320 if (!(nt
= RtlImageNtHeader( module
)))
1322 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1323 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1327 size
= nt
->OptionalHeader
.SizeOfImage
;
1328 NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 0, &size
,
1329 MEM_SYSTEM
| MEM_IMAGE
, PAGE_EXECUTE_WRITECOPY
);
1330 /* create the MODREF */
1332 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1334 ERR( "can't load %s\n", filename
);
1335 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1339 wm
= alloc_module( module
, fullname
);
1340 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1343 ERR( "can't load %s\n", filename
);
1344 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1347 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1349 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1350 !NtCurrentTeb()->Peb
->ImageBaseAddress
) /* if we already have an executable, ignore this one */
1352 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1358 load_path
= builtin_load_info
->load_path
;
1359 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1360 if (!load_path
) load_path
= emptyW
;
1361 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1363 /* the module has only be inserted in the load & memory order lists */
1364 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1365 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1366 /* FIXME: free the modref */
1367 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1372 builtin_load_info
->wm
= wm
;
1373 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1375 /* send the DLL load event */
1377 SERVER_START_REQ( load_dll
)
1381 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1382 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1383 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1384 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1385 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1386 wine_server_call( req
);
1390 /* setup relay debugging entry points */
1391 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1395 /******************************************************************************
1396 * load_native_dll (internal)
1398 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1399 DWORD flags
, WINE_MODREF
** pwm
)
1403 OBJECT_ATTRIBUTES attr
;
1405 IMAGE_NT_HEADERS
*nt
;
1410 TRACE("Trying native dll %s\n", debugstr_w(name
));
1412 attr
.Length
= sizeof(attr
);
1413 attr
.RootDirectory
= 0;
1414 attr
.ObjectName
= NULL
;
1415 attr
.Attributes
= 0;
1416 attr
.SecurityDescriptor
= NULL
;
1417 attr
.SecurityQualityOfService
= NULL
;
1420 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1421 &attr
, &size
, 0, SEC_IMAGE
, file
);
1422 if (status
!= STATUS_SUCCESS
) return status
;
1425 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1426 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1428 if (status
!= STATUS_SUCCESS
) return status
;
1430 if (is_fake_dll( module
))
1432 TRACE( "%s is a fake dll, not loading it\n", debugstr_w(name
) );
1433 NtUnmapViewOfSection( NtCurrentProcess(), module
);
1434 return STATUS_DLL_NOT_FOUND
;
1437 /* create the MODREF */
1439 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1443 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1445 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1447 /* the module has only be inserted in the load & memory order lists */
1448 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1449 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1451 /* FIXME: there are several more dangling references
1452 * left. Including dlls loaded by this dll before the
1453 * failed one. Unrolling is rather difficult with the
1454 * current structure and we can leave them lying
1455 * around with no problems, so we don't care.
1456 * As these might reference our wm, we don't free it.
1462 /* send DLL load event */
1464 nt
= RtlImageNtHeader( module
);
1466 SERVER_START_REQ( load_dll
)
1470 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1471 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1472 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1473 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1474 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1475 wine_server_call( req
);
1479 if ((wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
) && TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1481 TRACE_(loaddll
)( "Loaded %s at %p: native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
), module
);
1483 wm
->ldr
.LoadCount
= 1;
1485 return STATUS_SUCCESS
;
1489 /***********************************************************************
1492 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1493 DWORD flags
, WINE_MODREF
** pwm
)
1495 char error
[256], dllname
[MAX_PATH
];
1496 const WCHAR
*name
, *p
;
1498 void *handle
= NULL
;
1499 struct builtin_load_info info
, *prev_info
;
1501 /* Fix the name in case we have a full path and extension */
1503 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1504 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1506 /* load_library will modify info.status. Note also that load_library can be
1507 * called several times, if the .so file we're loading has dependencies.
1508 * info.status will gather all the errors we may get while loading all these
1511 info
.load_path
= load_path
;
1512 info
.filename
= NULL
;
1513 info
.status
= STATUS_SUCCESS
;
1516 if (file
) /* we have a real file, try to load it */
1518 UNICODE_STRING nt_name
;
1519 ANSI_STRING unix_name
;
1521 TRACE("Trying built-in %s\n", debugstr_w(path
));
1523 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1524 return STATUS_DLL_NOT_FOUND
;
1526 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1528 RtlFreeUnicodeString( &nt_name
);
1529 return STATUS_DLL_NOT_FOUND
;
1531 prev_info
= builtin_load_info
;
1532 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1533 builtin_load_info
= &info
;
1534 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1535 builtin_load_info
= prev_info
;
1536 RtlFreeUnicodeString( &nt_name
);
1537 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1540 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1541 return STATUS_INVALID_IMAGE_FORMAT
;
1548 TRACE("Trying built-in %s\n", debugstr_w(name
));
1550 /* we don't want to depend on the current codepage here */
1551 len
= strlenW( name
) + 1;
1552 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1553 for (i
= 0; i
< len
; i
++)
1555 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1556 dllname
[i
] = (char)name
[i
];
1557 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1560 prev_info
= builtin_load_info
;
1561 builtin_load_info
= &info
;
1562 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1563 builtin_load_info
= prev_info
;
1568 /* The file does not exist -> WARN() */
1569 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1570 return STATUS_DLL_NOT_FOUND
;
1572 /* ERR() for all other errors (missing functions, ...) */
1573 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1574 return STATUS_PROCEDURE_NOT_FOUND
;
1578 if (info
.status
!= STATUS_SUCCESS
)
1580 wine_dll_unload( handle
);
1586 PLIST_ENTRY mark
, entry
;
1588 /* The constructor wasn't called, this means the .so is already
1589 * loaded under a different name. Try to find the wm for it. */
1591 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1592 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1594 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1595 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1597 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1598 TRACE( "Found %s at %p for builtin %s\n",
1599 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
, debugstr_w(path
) );
1603 wine_dll_unload( handle
); /* release the libdl refcount */
1604 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1605 if (info
.wm
->ldr
.LoadCount
!= -1) info
.wm
->ldr
.LoadCount
++;
1609 TRACE_(loaddll
)( "Loaded %s at %p: builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), info
.wm
->ldr
.BaseAddress
);
1610 info
.wm
->ldr
.LoadCount
= 1;
1611 info
.wm
->ldr
.SectionHandle
= handle
;
1615 return STATUS_SUCCESS
;
1619 /***********************************************************************
1622 * Find the full path (if any) of the dll from the activation context.
1624 static NTSTATUS
find_actctx_dll( LPCWSTR libname
, LPWSTR
*fullname
)
1626 static const WCHAR winsxsW
[] = {'\\','w','i','n','s','x','s','\\'};
1627 static const WCHAR dotManifestW
[] = {'.','m','a','n','i','f','e','s','t',0};
1629 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
*info
;
1630 ACTCTX_SECTION_KEYED_DATA data
;
1631 UNICODE_STRING nameW
;
1633 SIZE_T needed
, size
= 1024;
1636 RtlInitUnicodeString( &nameW
, libname
);
1637 data
.cbSize
= sizeof(data
);
1638 status
= RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX
, NULL
,
1639 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION
,
1641 if (status
!= STATUS_SUCCESS
) return status
;
1645 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1647 status
= STATUS_NO_MEMORY
;
1650 status
= RtlQueryInformationActivationContext( 0, data
.hActCtx
, &data
.ulAssemblyRosterIndex
,
1651 AssemblyDetailedInformationInActivationContext
,
1652 info
, size
, &needed
);
1653 if (status
== STATUS_SUCCESS
) break;
1654 if (status
!= STATUS_BUFFER_TOO_SMALL
) goto done
;
1655 RtlFreeHeap( GetProcessHeap(), 0, info
);
1657 /* restart with larger buffer */
1660 if ((p
= strrchrW( info
->lpAssemblyManifestPath
, '\\' )))
1662 DWORD dirlen
= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1665 if (strncmpiW( p
, info
->lpAssemblyDirectoryName
, dirlen
) || strcmpiW( p
+ dirlen
, dotManifestW
))
1667 /* manifest name does not match directory name, so it's not a global
1668 * windows/winsxs manifest; use the manifest directory name instead */
1669 dirlen
= p
- info
->lpAssemblyManifestPath
;
1670 needed
= (dirlen
+ 1) * sizeof(WCHAR
) + nameW
.Length
;
1671 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1673 status
= STATUS_NO_MEMORY
;
1676 memcpy( p
, info
->lpAssemblyManifestPath
, dirlen
* sizeof(WCHAR
) );
1678 strcpyW( p
, libname
);
1683 needed
= (windows_dir
.Length
+ sizeof(winsxsW
) + info
->ulAssemblyDirectoryNameLength
+
1684 nameW
.Length
+ 2*sizeof(WCHAR
));
1686 if (!(*fullname
= p
= RtlAllocateHeap( GetProcessHeap(), 0, needed
)))
1688 status
= STATUS_NO_MEMORY
;
1691 memcpy( p
, windows_dir
.Buffer
, windows_dir
.Length
);
1692 p
+= windows_dir
.Length
/ sizeof(WCHAR
);
1693 memcpy( p
, winsxsW
, sizeof(winsxsW
) );
1694 p
+= sizeof(winsxsW
) / sizeof(WCHAR
);
1695 memcpy( p
, info
->lpAssemblyDirectoryName
, info
->ulAssemblyDirectoryNameLength
);
1696 p
+= info
->ulAssemblyDirectoryNameLength
/ sizeof(WCHAR
);
1698 strcpyW( p
, libname
);
1700 RtlFreeHeap( GetProcessHeap(), 0, info
);
1701 RtlReleaseActivationContext( data
.hActCtx
);
1706 /***********************************************************************
1709 * Find the file (or already loaded module) for a given dll name.
1711 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1712 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1714 OBJECT_ATTRIBUTES attr
;
1716 UNICODE_STRING nt_name
;
1717 WCHAR
*file_part
, *ext
, *dllname
;
1720 /* first append .dll if needed */
1723 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1725 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1726 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1727 return STATUS_NO_MEMORY
;
1728 strcpyW( dllname
, libname
);
1729 strcatW( dllname
, dllW
);
1733 nt_name
.Buffer
= NULL
;
1735 if (!contains_path( libname
))
1738 WCHAR
*fullname
= NULL
;
1740 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1742 status
= find_actctx_dll( libname
, &fullname
);
1743 if (status
== STATUS_SUCCESS
)
1745 TRACE ("found %s for %s\n", debugstr_w(fullname
), debugstr_w(libname
) );
1746 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1747 libname
= dllname
= fullname
;
1749 else if (status
!= STATUS_SXS_KEY_NOT_FOUND
)
1751 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1756 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1758 /* we need to search for it */
1759 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1762 if (len
>= *size
) goto overflow
;
1763 if ((*pwm
= find_fullname_module( filename
)) || !handle
) goto found
;
1765 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1767 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1768 return STATUS_NO_MEMORY
;
1770 attr
.Length
= sizeof(attr
);
1771 attr
.RootDirectory
= 0;
1772 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1773 attr
.ObjectName
= &nt_name
;
1774 attr
.SecurityDescriptor
= NULL
;
1775 attr
.SecurityQualityOfService
= NULL
;
1776 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1782 if (!contains_path( libname
))
1784 /* if libname doesn't contain a path at all, we simply return the name as is,
1785 * to be loaded as builtin */
1786 len
= strlenW(libname
) * sizeof(WCHAR
);
1787 if (len
>= *size
) goto overflow
;
1788 strcpyW( filename
, libname
);
1793 /* absolute path name, or relative path name but not found above */
1795 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1797 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1798 return STATUS_NO_MEMORY
;
1800 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1801 if (len
>= *size
) goto overflow
;
1802 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1803 if (!(*pwm
= find_fullname_module( filename
)) && handle
)
1805 attr
.Length
= sizeof(attr
);
1806 attr
.RootDirectory
= 0;
1807 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1808 attr
.ObjectName
= &nt_name
;
1809 attr
.SecurityDescriptor
= NULL
;
1810 attr
.SecurityQualityOfService
= NULL
;
1811 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1814 RtlFreeUnicodeString( &nt_name
);
1815 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1816 return STATUS_SUCCESS
;
1819 RtlFreeUnicodeString( &nt_name
);
1820 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1821 *size
= len
+ sizeof(WCHAR
);
1822 return STATUS_BUFFER_TOO_SMALL
;
1826 /***********************************************************************
1827 * load_dll (internal)
1829 * Load a PE style module according to the load order.
1830 * The loader_section must be locked while calling this function.
1832 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1834 enum loadorder loadorder
;
1838 WINE_MODREF
*main_exe
;
1842 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1846 size
= sizeof(buffer
);
1849 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1850 if (nts
== STATUS_SUCCESS
) break;
1851 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1852 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1853 /* grow the buffer and retry */
1854 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1857 if (*pwm
) /* found already loaded module */
1859 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1861 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
)) fixup_imports( *pwm
, load_path
);
1863 TRACE("Found %s for %s at %p, count=%d\n",
1864 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1865 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1866 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1867 return STATUS_SUCCESS
;
1870 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1871 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1876 nts
= STATUS_NO_MEMORY
;
1879 nts
= STATUS_DLL_NOT_FOUND
;
1882 case LO_NATIVE_BUILTIN
:
1883 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
1886 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1887 if (nts
== STATUS_INVALID_FILE_FOR_SECTION
)
1888 /* not in PE format, maybe it's a builtin */
1889 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1891 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
1892 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1895 case LO_BUILTIN_NATIVE
:
1896 case LO_DEFAULT
: /* default is builtin,native */
1897 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1898 if (!handle
) break; /* nothing else we can try */
1899 /* file is not a builtin library, try without using the specified file */
1900 if (nts
!= STATUS_SUCCESS
)
1901 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1902 if (nts
== STATUS_SUCCESS
&& loadorder
== LO_DEFAULT
&&
1903 (MODULE_InitDLL( *pwm
, DLL_WINE_PREATTACH
, NULL
) != STATUS_SUCCESS
))
1905 /* stub-only dll, try native */
1906 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename
) );
1907 LdrUnloadDll( (*pwm
)->ldr
.BaseAddress
);
1908 nts
= STATUS_DLL_NOT_FOUND
;
1910 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
1911 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1915 if (nts
== STATUS_SUCCESS
)
1917 /* Initialize DLL just loaded */
1918 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
1919 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
1920 (*pwm
)->ldr
.BaseAddress
);
1921 if (handle
) NtClose( handle
);
1922 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1926 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname
), nts
);
1927 if (handle
) NtClose( handle
);
1928 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1932 /******************************************************************
1933 * LdrLoadDll (NTDLL.@)
1935 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
1936 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
1941 RtlEnterCriticalSection( &loader_section
);
1943 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1944 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
1946 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
1948 nts
= process_attach( wm
, NULL
);
1949 if (nts
!= STATUS_SUCCESS
)
1951 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1955 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1957 RtlLeaveCriticalSection( &loader_section
);
1962 /******************************************************************
1963 * LdrGetDllHandle (NTDLL.@)
1965 NTSTATUS WINAPI
LdrGetDllHandle( LPCWSTR load_path
, ULONG flags
, const UNICODE_STRING
*name
, HMODULE
*base
)
1973 RtlEnterCriticalSection( &loader_section
);
1975 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1978 size
= sizeof(buffer
);
1981 status
= find_dll_file( load_path
, name
->Buffer
, filename
, &size
, &wm
, NULL
);
1982 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1983 if (status
!= STATUS_BUFFER_TOO_SMALL
) break;
1984 /* grow the buffer and retry */
1985 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
)))
1987 status
= STATUS_NO_MEMORY
;
1992 if (status
== STATUS_SUCCESS
)
1994 if (wm
) *base
= wm
->ldr
.BaseAddress
;
1995 else status
= STATUS_DLL_NOT_FOUND
;
1998 RtlLeaveCriticalSection( &loader_section
);
1999 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name
), status
? NULL
: *base
, debugstr_w(load_path
) );
2004 /******************************************************************
2005 * LdrAddRefDll (NTDLL.@)
2007 NTSTATUS WINAPI
LdrAddRefDll( ULONG flags
, HMODULE module
)
2009 NTSTATUS ret
= STATUS_SUCCESS
;
2012 if (flags
) FIXME( "%p flags %x not implemented\n", module
, flags
);
2014 RtlEnterCriticalSection( &loader_section
);
2016 if ((wm
= get_modref( module
)))
2018 if (wm
->ldr
.LoadCount
!= -1) wm
->ldr
.LoadCount
++;
2019 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2021 else ret
= STATUS_INVALID_PARAMETER
;
2023 RtlLeaveCriticalSection( &loader_section
);
2028 /******************************************************************
2029 * LdrQueryProcessModuleInformation
2032 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
2033 ULONG buf_size
, ULONG
* req_size
)
2035 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
2036 ULONG size
= sizeof(ULONG
);
2037 NTSTATUS nts
= STATUS_SUCCESS
;
2040 PLIST_ENTRY mark
, entry
;
2044 smi
->ModulesCount
= 0;
2046 RtlEnterCriticalSection( &loader_section
);
2047 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2048 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2050 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2051 size
+= sizeof(*sm
);
2052 if (size
<= buf_size
)
2054 sm
->Reserved1
= 0; /* FIXME */
2055 sm
->Reserved2
= 0; /* FIXME */
2056 sm
->ImageBaseAddress
= mod
->BaseAddress
;
2057 sm
->ImageSize
= mod
->SizeOfImage
;
2058 sm
->Flags
= mod
->Flags
;
2060 sm
->Rank
= 0; /* FIXME */
2061 sm
->Unknown
= 0; /* FIXME */
2063 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
2064 str
.Buffer
= (char*)sm
->Name
;
2065 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
2066 ptr
= strrchr(str
.Buffer
, '\\');
2067 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
2069 smi
->ModulesCount
++;
2072 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
2074 RtlLeaveCriticalSection( &loader_section
);
2076 if (req_size
) *req_size
= size
;
2082 /******************************************************************
2083 * RtlDllShutdownInProgress (NTDLL.@)
2085 BOOLEAN WINAPI
RtlDllShutdownInProgress(void)
2087 return process_detaching
;
2091 /******************************************************************
2092 * LdrShutdownProcess (NTDLL.@)
2095 void WINAPI
LdrShutdownProcess(void)
2098 process_detach( TRUE
, (LPVOID
)1 );
2101 /******************************************************************
2102 * LdrShutdownThread (NTDLL.@)
2105 void WINAPI
LdrShutdownThread(void)
2107 PLIST_ENTRY mark
, entry
;
2112 /* don't do any detach calls if process is exiting */
2113 if (process_detaching
) return;
2114 /* FIXME: there is still a race here */
2116 RtlEnterCriticalSection( &loader_section
);
2118 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2119 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
2121 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
2122 InInitializationOrderModuleList
);
2123 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
2125 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
2128 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
2129 DLL_THREAD_DETACH
, NULL
);
2132 RtlLeaveCriticalSection( &loader_section
);
2133 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer
);
2137 /***********************************************************************
2141 static void free_modref( WINE_MODREF
*wm
)
2143 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
2144 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
2145 if (wm
->ldr
.InInitializationOrderModuleList
.Flink
)
2146 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
2148 TRACE(" unloading %s\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
));
2149 if (!TRACE_ON(module
))
2150 TRACE_(loaddll
)("Unloaded module %s : %s\n",
2151 debugstr_w(wm
->ldr
.FullDllName
.Buffer
),
2152 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
2154 SERVER_START_REQ( unload_dll
)
2156 req
->base
= wm
->ldr
.BaseAddress
;
2157 wine_server_call( req
);
2161 RtlReleaseActivationContext( wm
->ldr
.ActivationContext
);
2162 NtUnmapViewOfSection( NtCurrentProcess(), wm
->ldr
.BaseAddress
);
2163 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
2164 if (cached_modref
== wm
) cached_modref
= NULL
;
2165 RtlFreeUnicodeString( &wm
->ldr
.FullDllName
);
2166 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
2167 RtlFreeHeap( GetProcessHeap(), 0, wm
);
2170 /***********************************************************************
2171 * MODULE_FlushModrefs
2173 * Remove all unused modrefs and call the internal unloading routines
2174 * for the library type.
2176 * The loader_section must be locked while calling this function.
2178 static void MODULE_FlushModrefs(void)
2180 PLIST_ENTRY mark
, entry
, prev
;
2184 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
2185 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2187 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InInitializationOrderModuleList
);
2188 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2189 prev
= entry
->Blink
;
2190 if (!mod
->LoadCount
) free_modref( wm
);
2193 /* check load order list too for modules that haven't been initialized yet */
2194 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2195 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
2197 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
2198 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
2199 prev
= entry
->Blink
;
2200 if (!mod
->LoadCount
) free_modref( wm
);
2204 /***********************************************************************
2205 * MODULE_DecRefCount
2207 * The loader_section must be locked while calling this function.
2209 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
2213 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
2216 if ( wm
->ldr
.LoadCount
<= 0 )
2219 --wm
->ldr
.LoadCount
;
2220 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
2222 if ( wm
->ldr
.LoadCount
== 0 )
2224 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
2226 for ( i
= 0; i
< wm
->nDeps
; i
++ )
2228 MODULE_DecRefCount( wm
->deps
[i
] );
2230 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
2234 /******************************************************************
2235 * LdrUnloadDll (NTDLL.@)
2239 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
2241 NTSTATUS retv
= STATUS_SUCCESS
;
2243 TRACE("(%p)\n", hModule
);
2245 RtlEnterCriticalSection( &loader_section
);
2247 /* if we're stopping the whole process (and forcing the removal of all
2248 * DLLs) the library will be freed anyway
2250 if (!process_detaching
)
2255 if ((wm
= get_modref( hModule
)) != NULL
)
2257 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
2259 /* Recursively decrement reference counts */
2260 MODULE_DecRefCount( wm
);
2262 /* Call process detach notifications */
2263 if ( free_lib_count
<= 1 )
2265 process_detach( FALSE
, NULL
);
2266 MODULE_FlushModrefs();
2272 retv
= STATUS_DLL_NOT_FOUND
;
2277 RtlLeaveCriticalSection( &loader_section
);
2282 /***********************************************************************
2283 * RtlImageNtHeader (NTDLL.@)
2285 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2287 IMAGE_NT_HEADERS
*ret
;
2291 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2294 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2296 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2297 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2309 /******************************************************************
2310 * LdrInitializeThunk (NTDLL.@)
2313 void WINAPI
LdrInitializeThunk( ULONG unknown1
, ULONG unknown2
, ULONG unknown3
, ULONG unknown4
)
2318 PEB
*peb
= NtCurrentTeb()->Peb
;
2319 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
2321 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
2323 /* allocate the modref for the main exe (if not already done) */
2324 wm
= get_modref( peb
->ImageBaseAddress
);
2326 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
2328 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
2332 peb
->LoaderLock
= &loader_section
;
2333 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2334 version_init( wm
->ldr
.FullDllName
.Buffer
);
2336 /* the main exe needs to be the first in the load order list */
2337 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2338 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2340 status
= server_init_process_done();
2341 if (status
!= STATUS_SUCCESS
) goto error
;
2343 RtlEnterCriticalSection( &loader_section
);
2346 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2347 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2348 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2349 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2351 pthread_functions
.sigprocmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
2353 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2355 if (last_failed_modref
)
2356 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2359 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2361 RtlLeaveCriticalSection( &loader_section
);
2363 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
) VIRTUAL_UseLargeAddressSpace();
2367 ERR( "Main exe initialization for %s failed, status %x\n",
2368 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2369 NtTerminateProcess( GetCurrentProcess(), status
);
2373 /***********************************************************************
2374 * RtlImageDirectoryEntryToData (NTDLL.@)
2376 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2378 const IMAGE_NT_HEADERS
*nt
;
2381 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2383 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2386 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2387 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2388 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2389 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
2390 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2392 /* not mapped as image, need to find the section containing the virtual address */
2393 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2397 /***********************************************************************
2398 * RtlImageRvaToSection (NTDLL.@)
2400 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2401 HMODULE module
, DWORD rva
)
2404 const IMAGE_SECTION_HEADER
*sec
;
2406 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2407 nt
->FileHeader
.SizeOfOptionalHeader
);
2408 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2410 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2411 return (PIMAGE_SECTION_HEADER
)sec
;
2417 /***********************************************************************
2418 * RtlImageRvaToVa (NTDLL.@)
2420 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2421 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2423 IMAGE_SECTION_HEADER
*sec
;
2425 if (section
&& *section
) /* try this section first */
2428 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2431 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2433 if (section
) *section
= sec
;
2434 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2438 /***********************************************************************
2439 * RtlPcToFileHeader (NTDLL.@)
2441 PVOID WINAPI
RtlPcToFileHeader( PVOID pc
, PVOID
*address
)
2446 RtlEnterCriticalSection( &loader_section
);
2447 if (!LdrFindEntryForAddress( pc
, &module
)) ret
= module
->BaseAddress
;
2448 RtlLeaveCriticalSection( &loader_section
);
2454 /***********************************************************************
2455 * NtLoadDriver (NTDLL.@)
2456 * ZwLoadDriver (NTDLL.@)
2458 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2460 FIXME("(%p), stub!\n",DriverServiceName
);
2461 return STATUS_NOT_IMPLEMENTED
;
2465 /***********************************************************************
2466 * NtUnloadDriver (NTDLL.@)
2467 * ZwUnloadDriver (NTDLL.@)
2469 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2471 FIXME("(%p), stub!\n",DriverServiceName
);
2472 return STATUS_NOT_IMPLEMENTED
;
2476 /******************************************************************
2479 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2481 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2486 /******************************************************************
2487 * __wine_init_windows_dir (NTDLL.@)
2489 * Windows and system dir initialization once kernel32 has been loaded.
2491 void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2493 PLIST_ENTRY mark
, entry
;
2496 RtlCreateUnicodeString( &windows_dir
, windir
);
2497 RtlCreateUnicodeString( &system_dir
, sysdir
);
2498 strcpyW( user_shared_data
->NtSystemRoot
, windir
);
2500 /* prepend the system dir to the name of the already created modules */
2501 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2502 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2504 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2506 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2508 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2509 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2510 if (!buffer
) continue;
2511 strcpyW( buffer
, system_dir
.Buffer
);
2512 p
= buffer
+ strlenW( buffer
);
2513 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2514 strcpyW( p
, mod
->FullDllName
.Buffer
);
2515 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2516 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2521 /***********************************************************************
2522 * __wine_process_init
2524 void __wine_process_init(void)
2526 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2530 ANSI_STRING func_name
;
2531 void (* DECLSPEC_NORETURN init_func
)(void);
2532 extern mode_t FILE_umask
;
2534 main_exe_file
= thread_init();
2536 /* retrieve current umask */
2537 FILE_umask
= umask(0777);
2538 umask( FILE_umask
);
2540 /* setup the load callback and create ntdll modref */
2541 wine_dll_set_callback( load_builtin_callback
);
2543 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
2545 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status
);
2548 RtlInitAnsiString( &func_name
, "UnhandledExceptionFilter" );
2549 LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
, 0, (void **)&unhandled_exception_filter
);
2551 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2552 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2553 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2555 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status
);