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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #include "wine/port.h"
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
32 #define WIN32_NO_STATUS
37 #include "wine/exception.h"
39 #include "wine/library.h"
40 #include "wine/unicode.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
43 #include "ntdll_misc.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(module
);
46 WINE_DECLARE_DEBUG_CHANNEL(relay
);
47 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
48 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
49 WINE_DECLARE_DEBUG_CHANNEL(imports
);
51 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
53 static int process_detaching
= 0; /* set on process detach to avoid deadlocks with thread detach */
54 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
56 static const char * const reason_names
[] =
64 static const WCHAR dllW
[] = {'.','d','l','l',0};
66 /* internal representation of 32bit modules. per process. */
67 typedef struct _wine_modref
71 struct _wine_modref
**deps
;
74 /* info about the current builtin dll load */
75 /* used to keep track of things across the register_dll constructor call */
76 struct builtin_load_info
78 const WCHAR
*load_path
;
79 const WCHAR
*filename
;
84 static struct builtin_load_info default_load_info
;
85 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
87 static HANDLE main_exe_file
;
88 static UINT tls_module_count
; /* number of modules with TLS directory */
89 static UINT tls_total_size
; /* total size of TLS storage */
90 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
92 UNICODE_STRING system_dir
= { 0, 0, NULL
}; /* system directory */
94 static RTL_CRITICAL_SECTION loader_section
;
95 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
97 0, 0, &loader_section
,
98 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
99 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
101 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
103 static WINE_MODREF
*cached_modref
;
104 static WINE_MODREF
*current_modref
;
105 static WINE_MODREF
*last_failed_modref
;
107 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
108 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
109 DWORD exp_size
, const char *name
, int hint
);
111 /* convert PE image VirtualAddress to Real Address */
112 inline static void *get_rva( HMODULE module
, DWORD va
)
114 return (void *)((char *)module
+ va
);
117 /* check whether the file name contains a path */
118 inline static int contains_path( LPCWSTR name
)
120 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
123 /* convert from straight ASCII to Unicode without depending on the current codepage */
124 inline static void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
126 while (len
--) *dst
++ = (unsigned char)*src
++;
130 /*************************************************************************
131 * call_dll_entry_point
133 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
134 * their entry point, so we need a small asm wrapper.
137 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
138 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
146 "movl 8(%ebp),%eax\n\t"
148 "leal -4(%ebp),%esp\n\t"
153 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
154 UINT reason
, void *reserved
)
156 return proc( module
, reason
, reserved
);
158 #endif /* __i386__ */
162 /*************************************************************************
165 * Entry point for stub functions.
167 static void stub_entry_point( const char *dll
, const char *name
, ... )
169 EXCEPTION_RECORD rec
;
171 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
172 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
173 rec
.ExceptionRecord
= NULL
;
175 rec
.ExceptionAddress
= __builtin_return_address(0);
177 rec
.ExceptionAddress
= *((void **)&dll
- 1);
179 rec
.NumberParameters
= 2;
180 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
181 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
182 for (;;) RtlRaiseException( &rec
);
186 #include "pshpack1.h"
189 BYTE popl_eax
; /* popl %eax */
190 BYTE pushl1
; /* pushl $name */
192 BYTE pushl2
; /* pushl $dll */
194 BYTE pushl_eax
; /* pushl %eax */
195 BYTE jmp
; /* jmp stub_entry_point */
200 /*************************************************************************
203 * Allocate a stub entry point.
205 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
207 #define MAX_SIZE 65536
208 static struct stub
*stubs
;
209 static unsigned int nb_stubs
;
212 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
216 ULONG size
= MAX_SIZE
;
217 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
218 MEM_COMMIT
, PAGE_EXECUTE_WRITECOPY
) != STATUS_SUCCESS
)
221 stub
= &stubs
[nb_stubs
++];
222 stub
->popl_eax
= 0x58; /* popl %eax */
223 stub
->pushl1
= 0x68; /* pushl $name */
225 stub
->pushl2
= 0x68; /* pushl $dll */
227 stub
->pushl_eax
= 0x50; /* pushl %eax */
228 stub
->jmp
= 0xe9; /* jmp stub_entry_point */
229 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
230 return (ULONG_PTR
)stub
;
234 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
235 #endif /* __i386__ */
238 /*************************************************************************
241 * Looks for the referenced HMODULE in the current process
242 * The loader_section must be locked while calling this function.
244 static WINE_MODREF
*get_modref( HMODULE hmod
)
246 PLIST_ENTRY mark
, entry
;
249 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
251 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
252 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
254 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
255 if (mod
->BaseAddress
== hmod
)
256 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
257 if (mod
->BaseAddress
> (void*)hmod
) break;
263 /**********************************************************************
264 * find_basename_module
266 * Find a module from its base name.
267 * The loader_section must be locked while calling this function
269 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
271 PLIST_ENTRY mark
, entry
;
273 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
274 return cached_modref
;
276 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
277 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
279 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
280 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
282 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
283 return cached_modref
;
290 /**********************************************************************
291 * find_fullname_module
293 * Find a module from its full path name.
294 * The loader_section must be locked while calling this function
296 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
298 PLIST_ENTRY mark
, entry
;
300 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
301 return cached_modref
;
303 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
304 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
306 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
307 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
309 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
310 return cached_modref
;
317 /*************************************************************************
318 * find_forwarded_export
320 * Find the final function pointer for a forwarded function.
321 * The loader_section must be locked while calling this function.
323 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
)
325 const IMAGE_EXPORT_DIRECTORY
*exports
;
329 const char *end
= strchr(forward
, '.');
332 if (!end
) return NULL
;
333 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
334 ascii_to_unicode( mod_name
, forward
, end
- forward
);
335 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
337 if (!(wm
= find_basename_module( mod_name
)))
339 ERR("module not found for forward '%s' used by %s\n",
340 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
343 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
344 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
345 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1 );
349 ERR("function not found for forward '%s' used by %s."
350 " If you are using builtin %s, try using the native one instead.\n",
351 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
352 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
358 /*************************************************************************
359 * find_ordinal_export
361 * Find an exported function by ordinal.
362 * The exports base must have been subtracted from the ordinal already.
363 * The loader_section must be locked while calling this function.
365 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
366 DWORD exp_size
, DWORD ordinal
)
369 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
371 if (ordinal
>= exports
->NumberOfFunctions
)
373 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
376 if (!functions
[ordinal
]) return NULL
;
378 proc
= get_rva( module
, functions
[ordinal
] );
380 /* if the address falls into the export dir, it's a forward */
381 if (((const char *)proc
>= (const char *)exports
) &&
382 ((const char *)proc
< (const char *)exports
+ exp_size
))
383 return find_forwarded_export( module
, (const char *)proc
);
387 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
388 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
392 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
393 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
399 /*************************************************************************
402 * Find an exported function by name.
403 * The loader_section must be locked while calling this function.
405 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
406 DWORD exp_size
, const char *name
, int hint
)
408 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
409 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
410 int min
= 0, max
= exports
->NumberOfNames
- 1;
412 /* first check the hint */
413 if (hint
>= 0 && hint
<= max
)
415 char *ename
= get_rva( module
, names
[hint
] );
416 if (!strcmp( ename
, name
))
417 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
] );
420 /* then do a binary search */
423 int res
, pos
= (min
+ max
) / 2;
424 char *ename
= get_rva( module
, names
[pos
] );
425 if (!(res
= strcmp( ename
, name
)))
426 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
] );
427 if (res
> 0) max
= pos
- 1;
435 /*************************************************************************
438 * Import the dll specified by the given import descriptor.
439 * The loader_section must be locked while calling this function.
441 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
446 const IMAGE_EXPORT_DIRECTORY
*exports
;
448 const IMAGE_THUNK_DATA
*import_list
;
449 IMAGE_THUNK_DATA
*thunk_list
;
451 const char *name
= get_rva( module
, descr
->Name
);
452 DWORD len
= strlen(name
);
454 SIZE_T protect_size
= 0;
457 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
458 if (descr
->u
.OriginalFirstThunk
)
459 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
461 import_list
= thunk_list
;
463 while (len
&& name
[len
-1] == ' ') len
--; /* remove trailing spaces */
465 if (len
* sizeof(WCHAR
) < sizeof(buffer
))
467 ascii_to_unicode( buffer
, name
, len
);
469 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
471 else /* need to allocate a larger buffer */
473 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) );
474 if (!ptr
) return NULL
;
475 ascii_to_unicode( ptr
, name
, len
);
477 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
478 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
483 if (status
== STATUS_DLL_NOT_FOUND
)
484 ERR("Library %s (which is needed by %s) not found\n",
485 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
487 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
488 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
492 /* unprotect the import address table since it can be located in
493 * readonly section */
494 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
495 protect_base
= thunk_list
;
496 protect_size
*= sizeof(*thunk_list
);
497 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
498 &protect_size
, PAGE_WRITECOPY
, &protect_old
);
500 imp_mod
= wmImp
->ldr
.BaseAddress
;
501 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
505 /* set all imported function to deadbeef */
506 while (import_list
->u1
.Ordinal
)
508 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
510 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
511 WARN("No implementation for %s.%d", name
, ordinal
);
512 thunk_list
->u1
.Function
= allocate_stub( name
, (const char *)ordinal
);
516 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
517 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
518 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
520 WARN(" imported from %s, allocating stub %p\n",
521 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
522 (void *)thunk_list
->u1
.Function
);
529 while (import_list
->u1
.Ordinal
)
531 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
533 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
535 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
536 ordinal
- exports
->Base
);
537 if (!thunk_list
->u1
.Function
)
539 thunk_list
->u1
.Function
= allocate_stub( name
, (const char *)ordinal
);
540 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
541 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
542 (void *)thunk_list
->u1
.Function
);
544 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
546 else /* import by name */
548 IMAGE_IMPORT_BY_NAME
*pe_name
;
549 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
550 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
551 (const char*)pe_name
->Name
, pe_name
->Hint
);
552 if (!thunk_list
->u1
.Function
)
554 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
555 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
556 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
557 (void *)thunk_list
->u1
.Function
);
559 TRACE_(imports
)("--- %s %s.%d = %p\n",
560 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
567 /* restore old protection of the import address table */
568 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
573 /****************************************************************
576 * Fixup all imports of a given module.
577 * The loader_section must be locked while calling this function.
579 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
582 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
587 if (!(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
)) return STATUS_SUCCESS
; /* already done */
588 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
590 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
591 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
592 return STATUS_SUCCESS
;
595 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
597 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
599 /* Allocate module dependency list */
600 wm
->nDeps
= nb_imports
;
601 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
603 /* load the imported modules. They are automatically
604 * added to the modref list of the process.
606 prev
= current_modref
;
608 status
= STATUS_SUCCESS
;
609 for (i
= 0; i
< nb_imports
; i
++)
611 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
612 status
= STATUS_DLL_NOT_FOUND
;
614 current_modref
= prev
;
619 /*************************************************************************
622 * Allocate a WINE_MODREF structure and add it to the process list
623 * The loader_section must be locked while calling this function.
625 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
629 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
630 PLIST_ENTRY entry
, mark
;
632 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
637 wm
->ldr
.BaseAddress
= hModule
;
638 wm
->ldr
.EntryPoint
= NULL
;
639 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
640 wm
->ldr
.Flags
= LDR_DONT_RESOLVE_REFS
;
641 wm
->ldr
.LoadCount
= 0;
642 wm
->ldr
.TlsIndex
= -1;
643 wm
->ldr
.SectionHandle
= NULL
;
644 wm
->ldr
.CheckSum
= 0;
645 wm
->ldr
.TimeDateStamp
= 0;
647 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
648 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
649 else p
= wm
->ldr
.FullDllName
.Buffer
;
650 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
652 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
654 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
655 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
656 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
659 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
660 &wm
->ldr
.InLoadOrderModuleList
);
662 /* insert module in MemoryList, sorted in increasing base addresses */
663 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
664 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
666 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
669 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
670 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
671 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
672 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
674 /* wait until init is called for inserting into this list */
675 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
676 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
681 /*************************************************************************
684 * Allocate the process-wide structure for module TLS storage.
686 static NTSTATUS
alloc_process_tls(void)
688 PLIST_ENTRY mark
, entry
;
690 const IMAGE_TLS_DIRECTORY
*dir
;
693 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
694 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
696 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
697 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
698 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
700 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
702 tls_total_size
+= size
;
705 if (!tls_module_count
) return STATUS_SUCCESS
;
707 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
709 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
710 if (!tls_dirs
) return STATUS_NO_MEMORY
;
712 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
714 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
715 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
716 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
719 *(DWORD
*)dir
->AddressOfIndex
= i
;
721 mod
->LoadCount
= -1; /* can't unload it */
724 return STATUS_SUCCESS
;
728 /*************************************************************************
731 * Allocate the per-thread structure for module TLS storage.
733 static NTSTATUS
alloc_thread_tls(void)
739 if (!tls_module_count
) return STATUS_SUCCESS
;
741 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0,
742 tls_module_count
* sizeof(*pointers
) )))
743 return STATUS_NO_MEMORY
;
745 if (!(data
= RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size
)))
747 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
748 return STATUS_NO_MEMORY
;
751 for (i
= 0; i
< tls_module_count
; i
++)
753 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
754 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
756 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
757 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
758 (void *)dir
->StartAddressOfRawData
, data
);
761 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
763 memset( data
, 0, dir
->SizeOfZeroFill
);
764 data
+= dir
->SizeOfZeroFill
;
766 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
767 return STATUS_SUCCESS
;
771 /*************************************************************************
774 static void call_tls_callbacks( HMODULE module
, UINT reason
)
776 const IMAGE_TLS_DIRECTORY
*dir
;
777 const PIMAGE_TLS_CALLBACK
*callback
;
780 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
781 if (!dir
|| !dir
->AddressOfCallBacks
) return;
783 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
786 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
787 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
788 (*callback
)( module
, reason
, NULL
);
790 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
791 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
796 /*************************************************************************
799 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
803 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
804 void *module
= wm
->ldr
.BaseAddress
;
806 /* Skip calls for modules loaded with special load flags */
808 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
809 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
810 if (!entry
) return TRUE
;
814 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
815 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
816 mod_name
[len
/ sizeof(WCHAR
)] = 0;
817 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
818 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
819 reason_names
[reason
], lpReserved
);
821 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
822 reason_names
[reason
], lpReserved
);
824 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
826 /* The state of the module list may have changed due to the call
827 to the dll. We cannot assume that this module has not been
830 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
831 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
832 reason_names
[reason
], lpReserved
, retv
);
833 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
839 /*************************************************************************
842 * Send the process attach notification to all DLLs the given module
843 * depends on (recursively). This is somewhat complicated due to the fact that
845 * - we have to respect the module dependencies, i.e. modules implicitly
846 * referenced by another module have to be initialized before the module
847 * itself can be initialized
849 * - the initialization routine of a DLL can itself call LoadLibrary,
850 * thereby introducing a whole new set of dependencies (even involving
851 * the 'old' modules) at any time during the whole process
853 * (Note that this routine can be recursively entered not only directly
854 * from itself, but also via LoadLibrary from one of the called initialization
857 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
858 * the process *detach* notifications to be sent in the correct order.
859 * This must not only take into account module dependencies, but also
860 * 'hidden' dependencies created by modules calling LoadLibrary in their
861 * attach notification routine.
863 * The strategy is rather simple: we move a WINE_MODREF to the head of the
864 * list after the attach notification has returned. This implies that the
865 * detach notifications are called in the reverse of the sequence the attach
866 * notifications *returned*.
868 * The loader_section must be locked while calling this function.
870 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
872 NTSTATUS status
= STATUS_SUCCESS
;
875 if (process_detaching
) return status
;
877 /* prevent infinite recursion in case of cyclical dependencies */
878 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
879 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
882 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
884 /* Tag current MODREF to prevent recursive loop */
885 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
887 /* Recursively attach all DLLs this one depends on */
888 for ( i
= 0; i
< wm
->nDeps
; i
++ )
890 if (!wm
->deps
[i
]) continue;
891 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
894 /* Call DLL entry point */
895 if (status
== STATUS_SUCCESS
)
897 WINE_MODREF
*prev
= current_modref
;
899 if (MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
))
901 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
905 /* point to the name so LdrInitializeThunk can print it */
906 last_failed_modref
= wm
;
907 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
908 status
= STATUS_DLL_INIT_FAILED
;
910 current_modref
= prev
;
913 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
914 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
915 &wm
->ldr
.InInitializationOrderModuleList
);
917 /* Remove recursion flag */
918 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
920 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
925 /**********************************************************************
926 * attach_implicitly_loaded_dlls
928 * Attach to the (builtin) dlls that have been implicitly loaded because
929 * of a dependency at the Unix level, but not imported at the Win32 level.
931 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
935 PLIST_ENTRY mark
, entry
;
937 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
938 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
940 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
942 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
943 TRACE( "found implicitly loaded %s, attaching to it\n",
944 debugstr_w(mod
->BaseDllName
.Buffer
));
945 mod
->LoadCount
= -1; /* we can't unload it anyway */
946 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
947 break; /* restart the search from the start */
949 if (entry
== mark
) break; /* nothing found */
954 /*************************************************************************
957 * Send DLL process detach notifications. See the comment about calling
958 * sequence at process_attach. Unless the bForceDetach flag
959 * is set, only DLLs with zero refcount are notified.
961 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
963 PLIST_ENTRY mark
, entry
;
966 RtlEnterCriticalSection( &loader_section
);
967 if (bForceDetach
) process_detaching
= 1;
968 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
971 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
973 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
974 InInitializationOrderModuleList
);
975 /* Check whether to detach this DLL */
976 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
978 if ( mod
->LoadCount
&& !bForceDetach
)
981 /* Call detach notification */
982 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
983 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
984 DLL_PROCESS_DETACH
, lpReserved
);
986 /* Restart at head of WINE_MODREF list, as entries might have
987 been added and/or removed while performing the call ... */
990 } while (entry
!= mark
);
992 RtlLeaveCriticalSection( &loader_section
);
995 /*************************************************************************
996 * MODULE_DllThreadAttach
998 * Send DLL thread attach notifications. These are sent in the
999 * reverse sequence of process detach notification.
1002 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
1004 PLIST_ENTRY mark
, entry
;
1008 /* don't do any attach calls if process is exiting */
1009 if (process_detaching
) return STATUS_SUCCESS
;
1010 /* FIXME: there is still a race here */
1012 RtlEnterCriticalSection( &loader_section
);
1014 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1016 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1017 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1019 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1020 InInitializationOrderModuleList
);
1021 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1023 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1026 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1027 DLL_THREAD_ATTACH
, lpReserved
);
1031 RtlLeaveCriticalSection( &loader_section
);
1035 /******************************************************************
1036 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1039 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1042 NTSTATUS ret
= STATUS_SUCCESS
;
1044 RtlEnterCriticalSection( &loader_section
);
1046 wm
= get_modref( hModule
);
1047 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1048 ret
= STATUS_DLL_NOT_FOUND
;
1050 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1052 RtlLeaveCriticalSection( &loader_section
);
1057 /******************************************************************
1058 * LdrFindEntryForAddress (NTDLL.@)
1060 * The loader_section must be locked while calling this function
1062 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1064 PLIST_ENTRY mark
, entry
;
1067 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1068 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1070 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1071 if ((const void *)mod
->BaseAddress
<= addr
&&
1072 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1075 return STATUS_SUCCESS
;
1077 if ((const void *)mod
->BaseAddress
> addr
) break;
1079 return STATUS_NO_MORE_ENTRIES
;
1082 /******************************************************************
1083 * LdrLockLoaderLock (NTDLL.@)
1085 * Note: flags are not implemented.
1086 * Flag 0x01 is used to raise exceptions on errors.
1087 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1089 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1091 if (flags
) FIXME( "flags %lx not supported\n", flags
);
1093 if (result
) *result
= 1;
1094 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1095 RtlEnterCriticalSection( &loader_section
);
1096 *magic
= GetCurrentThreadId();
1097 return STATUS_SUCCESS
;
1101 /******************************************************************
1102 * LdrUnlockLoaderUnlock (NTDLL.@)
1104 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1108 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1109 RtlLeaveCriticalSection( &loader_section
);
1111 return STATUS_SUCCESS
;
1115 /******************************************************************
1116 * LdrGetDllHandle (NTDLL.@)
1118 NTSTATUS WINAPI
LdrGetDllHandle(ULONG x
, ULONG y
, const UNICODE_STRING
*name
, HMODULE
*base
)
1120 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
1121 WCHAR dllname
[MAX_PATH
+4], *p
;
1123 PLIST_ENTRY mark
, entry
;
1126 if (x
!= 0 || y
!= 0)
1127 FIXME("Unknown behavior, please report\n");
1129 /* Append .DLL to name if no extension present */
1130 if (!(p
= strrchrW( name
->Buffer
, '.')) || strchrW( p
, '/' ) || strchrW( p
, '\\'))
1132 if (name
->Length
>= MAX_PATH
) return STATUS_NAME_TOO_LONG
;
1133 strcpyW( dllname
, name
->Buffer
);
1134 strcatW( dllname
, dllW
);
1135 RtlInitUnicodeString( &str
, dllname
);
1139 RtlEnterCriticalSection( &loader_section
);
1143 if (RtlEqualUnicodeString( name
, &cached_modref
->ldr
.FullDllName
, TRUE
) ||
1144 RtlEqualUnicodeString( name
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
1146 *base
= cached_modref
->ldr
.BaseAddress
;
1147 status
= STATUS_SUCCESS
;
1152 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1153 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1155 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1157 if (RtlEqualUnicodeString( name
, &mod
->FullDllName
, TRUE
) ||
1158 RtlEqualUnicodeString( name
, &mod
->BaseDllName
, TRUE
))
1160 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1161 *base
= mod
->BaseAddress
;
1162 status
= STATUS_SUCCESS
;
1167 RtlLeaveCriticalSection( &loader_section
);
1168 TRACE("%lx %lx %s -> %p\n", x
, y
, debugstr_us(name
), status
? NULL
: *base
);
1173 /******************************************************************
1174 * LdrGetProcedureAddress (NTDLL.@)
1176 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1177 ULONG ord
, PVOID
*address
)
1179 IMAGE_EXPORT_DIRECTORY
*exports
;
1181 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1183 RtlEnterCriticalSection( &loader_section
);
1185 /* check if the module itself is invalid to return the proper error */
1186 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1187 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1188 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1190 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
1191 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
1195 ret
= STATUS_SUCCESS
;
1199 RtlLeaveCriticalSection( &loader_section
);
1204 /***********************************************************************
1205 * get_builtin_fullname
1207 * Build the full pathname for a builtin dll.
1209 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1211 static const WCHAR soW
[] = {'.','s','o',0};
1212 WCHAR
*p
, *fullname
;
1213 size_t i
, len
= strlen(filename
);
1215 /* check if path can correspond to the dll we have */
1216 if (path
&& (p
= strrchrW( path
, '\\' )))
1219 for (i
= 0; i
< len
; i
++)
1220 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1221 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1223 /* the filename matches, use path as the full path */
1225 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1227 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1234 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1235 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1237 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1238 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1239 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1240 ascii_to_unicode( p
, filename
, len
+ 1 );
1246 /***********************************************************************
1247 * load_builtin_callback
1249 * Load a library in memory; callback function for wine_dll_register
1251 static void load_builtin_callback( void *module
, const char *filename
)
1253 static const WCHAR emptyW
[1];
1255 IMAGE_NT_HEADERS
*nt
;
1258 const WCHAR
*load_path
;
1262 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1265 if (!(nt
= RtlImageNtHeader( module
)))
1267 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1268 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1272 NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 0, &nt
->OptionalHeader
.SizeOfImage
,
1273 MEM_SYSTEM
| MEM_IMAGE
, PAGE_EXECUTE_WRITECOPY
);
1274 /* create the MODREF */
1276 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1278 ERR( "can't load %s\n", filename
);
1279 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1283 wm
= alloc_module( module
, fullname
);
1284 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1287 ERR( "can't load %s\n", filename
);
1288 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1291 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1293 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
) &&
1294 !NtCurrentTeb()->Peb
->ImageBaseAddress
) /* if we already have an executable, ignore this one */
1296 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1302 load_path
= builtin_load_info
->load_path
;
1303 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1304 if (!load_path
) load_path
= emptyW
;
1305 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1307 /* the module has only be inserted in the load & memory order lists */
1308 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1309 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1310 /* FIXME: free the modref */
1311 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1316 builtin_load_info
->wm
= wm
;
1317 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1319 /* send the DLL load event */
1321 SERVER_START_REQ( load_dll
)
1325 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1326 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1327 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1328 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1329 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1330 wine_server_call( req
);
1334 /* setup relay debugging entry points */
1335 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1339 /******************************************************************************
1340 * load_native_dll (internal)
1342 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1343 DWORD flags
, WINE_MODREF
** pwm
)
1347 OBJECT_ATTRIBUTES attr
;
1349 IMAGE_NT_HEADERS
*nt
;
1354 TRACE("Trying native dll %s\n", debugstr_w(name
));
1356 attr
.Length
= sizeof(attr
);
1357 attr
.RootDirectory
= 0;
1358 attr
.ObjectName
= NULL
;
1359 attr
.Attributes
= 0;
1360 attr
.SecurityDescriptor
= NULL
;
1361 attr
.SecurityQualityOfService
= NULL
;
1364 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1365 &attr
, &size
, 0, SEC_IMAGE
, file
);
1366 if (status
!= STATUS_SUCCESS
) return status
;
1369 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1370 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1372 if (status
!= STATUS_SUCCESS
) return status
;
1374 /* create the MODREF */
1376 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1380 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1382 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1384 /* the module has only be inserted in the load & memory order lists */
1385 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1386 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1388 /* FIXME: there are several more dangling references
1389 * left. Including dlls loaded by this dll before the
1390 * failed one. Unrolling is rather difficult with the
1391 * current structure and we can leave them lying
1392 * around with no problems, so we don't care.
1393 * As these might reference our wm, we don't free it.
1399 /* send DLL load event */
1401 nt
= RtlImageNtHeader( module
);
1403 /* don't keep the file open if the mapping is from removable media */
1404 if (!VIRTUAL_HasMapping( module
)) file
= 0;
1406 SERVER_START_REQ( load_dll
)
1410 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1411 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1412 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1413 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1414 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1415 wine_server_call( req
);
1419 if (TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1421 TRACE_(loaddll
)( " Loaded module %s : native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1424 return STATUS_SUCCESS
;
1428 /***********************************************************************
1431 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1432 DWORD flags
, WINE_MODREF
** pwm
)
1434 char error
[256], dllname
[MAX_PATH
];
1435 const WCHAR
*name
, *p
;
1437 void *handle
= NULL
;
1438 struct builtin_load_info info
, *prev_info
;
1440 /* Fix the name in case we have a full path and extension */
1442 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1443 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1445 /* load_library will modify info.status. Note also that load_library can be
1446 * called several times, if the .so file we're loading has dependencies.
1447 * info.status will gather all the errors we may get while loading all these
1450 info
.load_path
= load_path
;
1451 info
.filename
= NULL
;
1452 info
.status
= STATUS_SUCCESS
;
1455 if (file
) /* we have a real file, try to load it */
1457 UNICODE_STRING nt_name
;
1458 ANSI_STRING unix_name
;
1460 TRACE("Trying built-in %s\n", debugstr_w(path
));
1462 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1463 return STATUS_DLL_NOT_FOUND
;
1465 if (wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1467 RtlFreeUnicodeString( &nt_name
);
1468 return STATUS_DLL_NOT_FOUND
;
1470 prev_info
= builtin_load_info
;
1471 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1472 builtin_load_info
= &info
;
1473 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1474 builtin_load_info
= prev_info
;
1475 RtlFreeUnicodeString( &nt_name
);
1476 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1479 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path
), error
);
1480 return STATUS_INVALID_IMAGE_FORMAT
;
1487 TRACE("Trying built-in %s\n", debugstr_w(name
));
1489 /* we don't want to depend on the current codepage here */
1490 len
= strlenW( name
) + 1;
1491 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1492 for (i
= 0; i
< len
; i
++)
1494 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1495 dllname
[i
] = (char)name
[i
];
1496 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1499 prev_info
= builtin_load_info
;
1500 builtin_load_info
= &info
;
1501 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1502 builtin_load_info
= prev_info
;
1507 /* The file does not exist -> WARN() */
1508 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1509 return STATUS_DLL_NOT_FOUND
;
1511 /* ERR() for all other errors (missing functions, ...) */
1512 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1513 return STATUS_PROCEDURE_NOT_FOUND
;
1517 if (info
.status
!= STATUS_SUCCESS
) return info
.status
;
1521 PLIST_ENTRY mark
, entry
;
1523 /* The constructor wasn't called, this means the .so is already
1524 * loaded under a different name. Try to find the wm for it. */
1526 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1527 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1529 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1530 if (mod
->Flags
& LDR_WINE_INTERNAL
&& mod
->SectionHandle
== handle
)
1532 info
.wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1533 TRACE( "Found already loaded module %s for builtin %s\n",
1534 debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
), debugstr_w(path
) );
1538 if (!info
.wm
) return STATUS_INVALID_IMAGE_FORMAT
;
1542 TRACE_(loaddll
)( "Loaded module %s : builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
) );
1543 info
.wm
->ldr
.SectionHandle
= handle
;
1547 return STATUS_SUCCESS
;
1551 /***********************************************************************
1554 * Find the file (or already loaded module) for a given dll name.
1556 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1557 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1559 OBJECT_ATTRIBUTES attr
;
1561 UNICODE_STRING nt_name
;
1562 WCHAR
*file_part
, *ext
, *dllname
;
1565 /* first append .dll if needed */
1568 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1570 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1571 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1572 return STATUS_NO_MEMORY
;
1573 strcpyW( dllname
, libname
);
1574 strcatW( dllname
, dllW
);
1578 nt_name
.Buffer
= NULL
;
1580 if (!contains_path( libname
))
1582 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1585 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1587 /* we need to search for it */
1588 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1591 if (len
>= *size
) goto overflow
;
1592 if ((*pwm
= find_fullname_module( filename
)) != NULL
) goto found
;
1594 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1596 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1597 return STATUS_NO_MEMORY
;
1599 attr
.Length
= sizeof(attr
);
1600 attr
.RootDirectory
= 0;
1601 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1602 attr
.ObjectName
= &nt_name
;
1603 attr
.SecurityDescriptor
= NULL
;
1604 attr
.SecurityQualityOfService
= NULL
;
1605 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1611 if (!contains_path( libname
))
1613 /* if libname doesn't contain a path at all, we simply return the name as is,
1614 * to be loaded as builtin */
1615 len
= strlenW(libname
) * sizeof(WCHAR
);
1616 if (len
>= *size
) goto overflow
;
1617 strcpyW( filename
, libname
);
1622 /* absolute path name, or relative path name but not found above */
1624 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1626 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1627 return STATUS_NO_MEMORY
;
1629 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1630 if (len
>= *size
) goto overflow
;
1631 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1632 if (!(*pwm
= find_fullname_module( filename
)))
1634 attr
.Length
= sizeof(attr
);
1635 attr
.RootDirectory
= 0;
1636 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1637 attr
.ObjectName
= &nt_name
;
1638 attr
.SecurityDescriptor
= NULL
;
1639 attr
.SecurityQualityOfService
= NULL
;
1640 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1643 RtlFreeUnicodeString( &nt_name
);
1644 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1645 return STATUS_SUCCESS
;
1648 RtlFreeUnicodeString( &nt_name
);
1649 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1650 *size
= len
+ sizeof(WCHAR
);
1651 return STATUS_BUFFER_TOO_SMALL
;
1655 /***********************************************************************
1656 * load_dll (internal)
1658 * Load a PE style module according to the load order.
1659 * The loader_section must be locked while calling this function.
1661 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1663 enum loadorder loadorder
;
1667 WINE_MODREF
*main_exe
;
1671 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1674 size
= sizeof(buffer
);
1677 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1678 if (nts
== STATUS_SUCCESS
) break;
1679 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1680 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1681 /* grow the buffer and retry */
1682 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1685 if (*pwm
) /* found already loaded module */
1687 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1689 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
)) fixup_imports( *pwm
, load_path
);
1691 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1692 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1693 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1694 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1695 return STATUS_SUCCESS
;
1698 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1699 loadorder
= get_load_order( main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1704 nts
= STATUS_NO_MEMORY
;
1707 nts
= STATUS_DLL_NOT_FOUND
;
1710 case LO_NATIVE_BUILTIN
:
1711 if (!handle
) nts
= STATUS_DLL_NOT_FOUND
;
1714 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1715 if (nts
== STATUS_INVALID_FILE_FOR_SECTION
)
1716 /* not in PE format, maybe it's a builtin */
1717 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1719 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
== LO_NATIVE_BUILTIN
)
1720 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1723 case LO_BUILTIN_NATIVE
:
1724 case LO_DEFAULT
: /* default is builtin,native */
1725 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1726 if (nts
== STATUS_SUCCESS
) break;
1727 if (!handle
) break; /* nothing else we can try */
1728 /* file is not a builtin library, try without using the specified file */
1729 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1730 if (nts
== STATUS_DLL_NOT_FOUND
&& loadorder
!= LO_BUILTIN
)
1731 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1735 if (nts
== STATUS_SUCCESS
)
1737 /* Initialize DLL just loaded */
1738 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
1739 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
1740 (*pwm
)->ldr
.BaseAddress
);
1741 /* Set the ldr.LoadCount here so that an attach failure will */
1742 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1743 (*pwm
)->ldr
.LoadCount
= 1;
1744 if (handle
) NtClose( handle
);
1745 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1749 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname
), nts
);
1750 if (handle
) NtClose( handle
);
1751 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1755 /******************************************************************
1756 * LdrLoadDll (NTDLL.@)
1758 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
1759 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
1764 RtlEnterCriticalSection( &loader_section
);
1766 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1767 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
1769 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
1771 nts
= process_attach( wm
, NULL
);
1772 if (nts
!= STATUS_SUCCESS
)
1774 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1778 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1780 RtlLeaveCriticalSection( &loader_section
);
1784 /******************************************************************
1785 * LdrQueryProcessModuleInformation
1788 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
1789 ULONG buf_size
, ULONG
* req_size
)
1791 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
1792 ULONG size
= sizeof(ULONG
);
1793 NTSTATUS nts
= STATUS_SUCCESS
;
1796 PLIST_ENTRY mark
, entry
;
1799 smi
->ModulesCount
= 0;
1801 RtlEnterCriticalSection( &loader_section
);
1802 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1803 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1805 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1806 size
+= sizeof(*sm
);
1807 if (size
<= buf_size
)
1809 sm
->Reserved1
= 0; /* FIXME */
1810 sm
->Reserved2
= 0; /* FIXME */
1811 sm
->ImageBaseAddress
= mod
->BaseAddress
;
1812 sm
->ImageSize
= mod
->SizeOfImage
;
1813 sm
->Flags
= mod
->Flags
;
1814 sm
->Id
= 0; /* FIXME */
1815 sm
->Rank
= 0; /* FIXME */
1816 sm
->Unknown
= 0; /* FIXME */
1818 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
1819 str
.Buffer
= (char*)sm
->Name
;
1820 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
1821 ptr
= strrchr(str
.Buffer
, '\\');
1822 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
1824 smi
->ModulesCount
++;
1827 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
1829 RtlLeaveCriticalSection( &loader_section
);
1831 if (req_size
) *req_size
= size
;
1836 /******************************************************************
1837 * LdrShutdownProcess (NTDLL.@)
1840 void WINAPI
LdrShutdownProcess(void)
1843 process_detach( TRUE
, (LPVOID
)1 );
1846 /******************************************************************
1847 * LdrShutdownThread (NTDLL.@)
1850 void WINAPI
LdrShutdownThread(void)
1852 PLIST_ENTRY mark
, entry
;
1857 /* don't do any detach calls if process is exiting */
1858 if (process_detaching
) return;
1859 /* FIXME: there is still a race here */
1861 RtlEnterCriticalSection( &loader_section
);
1863 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1864 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1866 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1867 InInitializationOrderModuleList
);
1868 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1870 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1873 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1874 DLL_THREAD_DETACH
, NULL
);
1877 RtlLeaveCriticalSection( &loader_section
);
1880 /***********************************************************************
1881 * MODULE_FlushModrefs
1883 * Remove all unused modrefs and call the internal unloading routines
1884 * for the library type.
1886 * The loader_section must be locked while calling this function.
1888 static void MODULE_FlushModrefs(void)
1890 PLIST_ENTRY mark
, entry
, prev
;
1894 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1895 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
1897 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1898 InInitializationOrderModuleList
);
1899 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1901 prev
= entry
->Blink
;
1902 if (mod
->LoadCount
) continue;
1904 RemoveEntryList(&mod
->InLoadOrderModuleList
);
1905 RemoveEntryList(&mod
->InMemoryOrderModuleList
);
1906 RemoveEntryList(&mod
->InInitializationOrderModuleList
);
1908 TRACE(" unloading %s\n", debugstr_w(mod
->FullDllName
.Buffer
));
1909 if (!TRACE_ON(module
))
1910 TRACE_(loaddll
)("Unloaded module %s : %s\n",
1911 debugstr_w(mod
->FullDllName
.Buffer
),
1912 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
1914 SERVER_START_REQ( unload_dll
)
1916 req
->base
= mod
->BaseAddress
;
1917 wine_server_call( req
);
1921 NtUnmapViewOfSection( NtCurrentProcess(), mod
->BaseAddress
);
1922 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
1923 if (cached_modref
== wm
) cached_modref
= NULL
;
1924 RtlFreeUnicodeString( &mod
->FullDllName
);
1925 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
1926 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1930 /***********************************************************************
1931 * MODULE_DecRefCount
1933 * The loader_section must be locked while calling this function.
1935 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
1939 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
1942 if ( wm
->ldr
.LoadCount
<= 0 )
1945 --wm
->ldr
.LoadCount
;
1946 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
1948 if ( wm
->ldr
.LoadCount
== 0 )
1950 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
1952 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1954 MODULE_DecRefCount( wm
->deps
[i
] );
1956 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
1960 /******************************************************************
1961 * LdrUnloadDll (NTDLL.@)
1965 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
1967 NTSTATUS retv
= STATUS_SUCCESS
;
1969 TRACE("(%p)\n", hModule
);
1971 RtlEnterCriticalSection( &loader_section
);
1973 /* if we're stopping the whole process (and forcing the removal of all
1974 * DLLs) the library will be freed anyway
1976 if (!process_detaching
)
1981 if ((wm
= get_modref( hModule
)) != NULL
)
1983 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1985 /* Recursively decrement reference counts */
1986 MODULE_DecRefCount( wm
);
1988 /* Call process detach notifications */
1989 if ( free_lib_count
<= 1 )
1991 process_detach( FALSE
, NULL
);
1992 MODULE_FlushModrefs();
1998 retv
= STATUS_DLL_NOT_FOUND
;
2003 RtlLeaveCriticalSection( &loader_section
);
2008 /***********************************************************************
2009 * RtlImageNtHeader (NTDLL.@)
2011 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
2013 IMAGE_NT_HEADERS
*ret
;
2017 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2020 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2022 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2023 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2035 /******************************************************************
2036 * LdrInitializeThunk (NTDLL.@)
2039 void WINAPI
LdrInitializeThunk( ULONG unknown1
, ULONG unknown2
, ULONG unknown3
, ULONG unknown4
)
2044 PEB
*peb
= NtCurrentTeb()->Peb
;
2045 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
2047 if (main_exe_file
) NtClose( main_exe_file
); /* at this point the main module is created */
2049 /* allocate the modref for the main exe (if not already done) */
2050 wm
= get_modref( peb
->ImageBaseAddress
);
2052 if (wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)
2054 ERR("%s is a dll, not an executable\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
2057 wm
->ldr
.LoadCount
= -1; /* can't unload main exe */
2059 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2060 version_init( wm
->ldr
.FullDllName
.Buffer
);
2062 /* the main exe needs to be the first in the load order list */
2063 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2064 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2066 /* Install signal handlers; this cannot be done before, since we cannot
2067 * send exceptions to the debugger before the create process event that
2068 * is sent by REQ_INIT_PROCESS_DONE.
2069 * We do need the handlers in place by the time the request is over, so
2070 * we set them up here. If we segfault between here and the server call
2071 * something is very wrong... */
2072 if (!SIGNAL_Init()) exit(1);
2074 /* Signal the parent process to continue */
2075 SERVER_START_REQ( init_process_done
)
2077 req
->module
= peb
->ImageBaseAddress
;
2078 req
->entry
= (char *)peb
->ImageBaseAddress
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
2079 req
->gui
= (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_WINDOWS_CUI
);
2080 status
= wine_server_call( req
);
2084 if (status
!= STATUS_SUCCESS
) goto error
;
2086 RtlEnterCriticalSection( &loader_section
);
2088 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2089 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2090 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2091 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2092 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2094 if (last_failed_modref
)
2095 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2098 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2100 RtlLeaveCriticalSection( &loader_section
);
2102 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
) VIRTUAL_UseLargeAddressSpace();
2106 ERR( "Main exe initialization for %s failed, status %lx\n",
2107 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2112 /***********************************************************************
2113 * RtlImageDirectoryEntryToData (NTDLL.@)
2115 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2117 const IMAGE_NT_HEADERS
*nt
;
2120 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2122 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2125 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2126 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2127 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2128 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
2129 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2131 /* not mapped as image, need to find the section containing the virtual address */
2132 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2136 /***********************************************************************
2137 * RtlImageRvaToSection (NTDLL.@)
2139 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2140 HMODULE module
, DWORD rva
)
2143 const IMAGE_SECTION_HEADER
*sec
;
2145 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2146 nt
->FileHeader
.SizeOfOptionalHeader
);
2147 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2149 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2150 return (PIMAGE_SECTION_HEADER
)sec
;
2156 /***********************************************************************
2157 * RtlImageRvaToVa (NTDLL.@)
2159 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2160 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2162 IMAGE_SECTION_HEADER
*sec
;
2164 if (section
&& *section
) /* try this section first */
2167 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2170 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2172 if (section
) *section
= sec
;
2173 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2177 /***********************************************************************
2178 * NtLoadDriver (NTDLL.@)
2179 * ZwLoadDriver (NTDLL.@)
2181 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2183 FIXME("(%p), stub!\n",DriverServiceName
);
2184 return STATUS_NOT_IMPLEMENTED
;
2188 /***********************************************************************
2189 * NtUnloadDriver (NTDLL.@)
2190 * ZwUnloadDriver (NTDLL.@)
2192 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2194 FIXME("(%p), stub!\n",DriverServiceName
);
2195 return STATUS_NOT_IMPLEMENTED
;
2199 /******************************************************************
2202 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2204 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2209 /******************************************************************
2210 * __wine_init_windows_dir (NTDLL.@)
2212 * Windows and system dir initialization once kernel32 has been loaded.
2214 void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2216 PLIST_ENTRY mark
, entry
;
2219 RtlCreateUnicodeString( &system_dir
, sysdir
);
2221 /* prepend the system dir to the name of the already created modules */
2222 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2223 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2225 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2227 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2229 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2230 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2231 if (!buffer
) continue;
2232 strcpyW( buffer
, system_dir
.Buffer
);
2233 p
= buffer
+ strlenW( buffer
);
2234 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2235 strcpyW( p
, mod
->FullDllName
.Buffer
);
2236 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2237 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2242 /***********************************************************************
2243 * __wine_process_init
2245 void __wine_process_init( int argc
, char *argv
[] )
2247 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2251 ANSI_STRING func_name
;
2252 void (* DECLSPEC_NORETURN init_func
)(void);
2253 extern mode_t FILE_umask
;
2255 main_exe_file
= thread_init();
2257 /* retrieve current umask */
2258 FILE_umask
= umask(0777);
2259 umask( FILE_umask
);
2261 /* setup the load callback and create ntdll modref */
2262 wine_dll_set_callback( load_builtin_callback
);
2264 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
2266 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status
);
2269 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2270 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2271 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2273 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status
);