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
33 #include "wine/exception.h"
35 #include "wine/unicode.h"
36 #include "wine/debug.h"
37 #include "wine/server.h"
38 #include "ntdll_misc.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(module
);
41 WINE_DECLARE_DEBUG_CHANNEL(relay
);
42 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
43 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
45 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
47 static int process_detaching
= 0; /* set on process detach to avoid deadlocks with thread detach */
48 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
50 /* filter for page-fault exceptions */
51 static WINE_EXCEPTION_FILTER(page_fault
)
53 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION
)
54 return EXCEPTION_EXECUTE_HANDLER
;
55 return EXCEPTION_CONTINUE_SEARCH
;
58 static const char * const reason_names
[] =
66 static const WCHAR dllW
[] = {'.','d','l','l',0};
68 /* internal representation of 32bit modules. per process. */
71 void *dlhandle
; /* handle returned by dlopen() */
74 struct _wine_modref
**deps
;
77 char data
[1]; /* space for storing filename and modname */
80 static UINT tls_module_count
; /* number of modules with TLS directory */
81 static UINT tls_total_size
; /* total size of TLS storage */
82 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
84 static CRITICAL_SECTION loader_section
;
85 static CRITICAL_SECTION_DEBUG critsect_debug
=
87 0, 0, &loader_section
,
88 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
89 0, 0, { 0, (DWORD
)(__FILE__
": loader_section") }
91 static CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
93 static WINE_MODREF
*cached_modref
;
94 static WINE_MODREF
*current_modref
;
95 static NTSTATUS last_builtin_status
; /* use to gather all errors in callback */
97 static NTSTATUS
load_dll( LPCSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
98 static FARPROC
find_named_export( HMODULE module
, IMAGE_EXPORT_DIRECTORY
*exports
,
99 DWORD exp_size
, const char *name
, int hint
);
101 /* convert PE image VirtualAddress to Real Address */
102 inline static void *get_rva( HMODULE module
, DWORD va
)
104 return (void *)((char *)module
+ va
);
107 /*************************************************************************
110 * Looks for the referenced HMODULE in the current process
111 * The loader_section must be locked while calling this function.
113 static WINE_MODREF
*get_modref( HMODULE hmod
)
115 PLIST_ENTRY mark
, entry
;
118 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
120 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
121 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
123 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
124 if (mod
->BaseAddress
== hmod
)
125 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
126 if (mod
->BaseAddress
> (void*)hmod
) break;
132 /**********************************************************************
135 * Find a (loaded) win32 module depending on path
136 * LPCSTR path: [in] pathname of module/library to be found
138 * The loader_section must be locked while calling this function
140 * the module handle if found
143 static WINE_MODREF
*find_module( LPCSTR path
)
146 PLIST_ENTRY mark
, entry
;
148 char dllname
[260], *p
;
150 /* Append .DLL to name if no extension present */
151 strcpy( dllname
, path
);
152 if (!(p
= strrchr( dllname
, '.')) || strchr( p
, '/' ) || strchr( p
, '\\'))
153 strcat( dllname
, ".DLL" );
155 if ((wm
= cached_modref
) != NULL
)
157 if ( !FILE_strcasecmp( dllname
, wm
->modname
) ) return wm
;
158 if ( !FILE_strcasecmp( dllname
, wm
->filename
) ) return wm
;
161 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
162 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
164 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
165 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
167 if ( !FILE_strcasecmp( dllname
, wm
->modname
) ) break;
168 if ( !FILE_strcasecmp( dllname
, wm
->filename
) ) break;
170 if (entry
== mark
) wm
= NULL
;
177 /*************************************************************************
178 * find_forwarded_export
180 * Find the final function pointer for a forwarded function.
181 * The loader_section must be locked while calling this function.
183 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
)
185 IMAGE_EXPORT_DIRECTORY
*exports
;
189 char *end
= strchr(forward
, '.');
192 if (!end
) return NULL
;
193 if (end
- forward
>= sizeof(mod_name
)) return NULL
;
194 memcpy( mod_name
, forward
, end
- forward
);
195 mod_name
[end
-forward
] = 0;
197 if (!(wm
= find_module( mod_name
)))
199 ERR("module not found for forward '%s' used by '%s'\n",
200 forward
, get_modref(module
)->filename
);
203 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
204 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
205 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1 );
209 ERR("function not found for forward '%s' used by '%s'."
210 " If you are using builtin '%s', try using the native one instead.\n",
211 forward
, get_modref(module
)->filename
, get_modref(module
)->modname
);
217 /*************************************************************************
218 * find_ordinal_export
220 * Find an exported function by ordinal.
221 * The exports base must have been subtracted from the ordinal already.
222 * The loader_section must be locked while calling this function.
224 static FARPROC
find_ordinal_export( HMODULE module
, IMAGE_EXPORT_DIRECTORY
*exports
,
225 DWORD exp_size
, int ordinal
)
228 DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
230 if (ordinal
>= exports
->NumberOfFunctions
)
232 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
235 if (!functions
[ordinal
]) return NULL
;
237 proc
= get_rva( module
, functions
[ordinal
] );
239 /* if the address falls into the export dir, it's a forward */
240 if (((char *)proc
>= (char *)exports
) && ((char *)proc
< (char *)exports
+ exp_size
))
241 return find_forwarded_export( module
, (char *)proc
);
245 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
);
247 if (TRACE_ON(relay
) && current_modref
)
249 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, current_modref
->modname
);
255 /*************************************************************************
258 * Find an exported function by name.
259 * The loader_section must be locked while calling this function.
261 static FARPROC
find_named_export( HMODULE module
, IMAGE_EXPORT_DIRECTORY
*exports
,
262 DWORD exp_size
, const char *name
, int hint
)
264 WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
265 DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
266 int min
= 0, max
= exports
->NumberOfNames
- 1;
268 /* first check the hint */
269 if (hint
>= 0 && hint
<= max
)
271 char *ename
= get_rva( module
, names
[hint
] );
272 if (!strcmp( ename
, name
))
273 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
] );
276 /* then do a binary search */
279 int res
, pos
= (min
+ max
) / 2;
280 char *ename
= get_rva( module
, names
[pos
] );
281 if (!(res
= strcmp( ename
, name
)))
282 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
] );
283 if (res
> 0) max
= pos
- 1;
291 /*************************************************************************
294 * Import the dll specified by the given import descriptor.
295 * The loader_section must be locked while calling this function.
297 static WINE_MODREF
*import_dll( HMODULE module
, IMAGE_IMPORT_DESCRIPTOR
*descr
)
302 IMAGE_EXPORT_DIRECTORY
*exports
;
304 IMAGE_THUNK_DATA
*import_list
, *thunk_list
;
305 char *name
= get_rva( module
, descr
->Name
);
307 status
= load_dll( name
, 0, &wmImp
);
310 if (status
== STATUS_NO_SUCH_FILE
)
311 ERR("Module (file) %s (which is needed by %s) not found\n",
312 name
, current_modref
->filename
);
314 ERR("Loading module (file) %s (which is needed by %s) failed (error %lx).\n",
315 name
, current_modref
->filename
, status
);
319 imp_mod
= wmImp
->ldr
.BaseAddress
;
320 if (!(exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
,
321 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
324 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
325 if (descr
->u
.OriginalFirstThunk
)
326 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
328 import_list
= thunk_list
;
330 while (import_list
->u1
.Ordinal
)
332 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
334 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
336 TRACE("--- Ordinal %s,%d\n", name
, ordinal
);
337 thunk_list
->u1
.Function
= (PDWORD
)find_ordinal_export( imp_mod
, exports
, exp_size
,
338 ordinal
- exports
->Base
);
339 if (!thunk_list
->u1
.Function
)
341 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
342 name
, ordinal
, current_modref
->filename
);
343 thunk_list
->u1
.Function
= (PDWORD
)0xdeadbeef;
346 else /* import by name */
348 IMAGE_IMPORT_BY_NAME
*pe_name
;
349 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
350 TRACE("--- %s %s.%d\n", pe_name
->Name
, name
, pe_name
->Hint
);
351 thunk_list
->u1
.Function
= (PDWORD
)find_named_export( imp_mod
, exports
, exp_size
,
352 pe_name
->Name
, pe_name
->Hint
);
353 if (!thunk_list
->u1
.Function
)
355 ERR("No implementation for %s.%s imported from %s, setting to 0xdeadbeef\n",
356 name
, pe_name
->Name
, current_modref
->filename
);
357 thunk_list
->u1
.Function
= (PDWORD
)0xdeadbeef;
367 /****************************************************************
370 * Fixup all imports of a given module.
371 * The loader_section must be locked while calling this function.
373 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
)
376 IMAGE_IMPORT_DESCRIPTOR
*imports
;
380 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
381 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
382 return STATUS_SUCCESS
;
384 nb_imports
= size
/ sizeof(*imports
);
385 for (i
= 0; i
< nb_imports
; i
++)
387 if (!imports
[i
].Name
)
393 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
395 /* Allocate module dependency list */
396 wm
->nDeps
= nb_imports
;
397 wm
->deps
= RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
399 /* load the imported modules. They are automatically
400 * added to the modref list of the process.
402 prev
= current_modref
;
404 for (i
= 0; i
< nb_imports
; i
++)
406 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
] ))) break;
408 current_modref
= prev
;
409 if (i
< nb_imports
) return STATUS_DLL_NOT_FOUND
;
410 return STATUS_SUCCESS
;
414 /*************************************************************************
417 * Allocate a WINE_MODREF structure and add it to the process list
418 * The loader_section must be locked while calling this function.
420 WINE_MODREF
*MODULE_AllocModRef( HMODULE hModule
, LPCSTR filename
)
423 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
424 PLIST_ENTRY entry
, mark
;
425 BOOLEAN linked
= FALSE
;
426 DWORD len
= strlen( filename
) + 1;
428 if ((wm
= RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY
, sizeof(*wm
) + len
)))
430 wm
->filename
= (char *)(wm
+ 1);
431 memcpy( wm
->filename
, filename
, len
);
432 if ((wm
->modname
= strrchr( wm
->filename
, '\\' ))) wm
->modname
++;
433 else wm
->modname
= wm
->filename
;
435 wm
->ldr
.BaseAddress
= hModule
;
436 wm
->ldr
.EntryPoint
= (nt
->OptionalHeader
.AddressOfEntryPoint
) ?
437 ((char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
) : 0;
438 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
439 RtlCreateUnicodeStringFromAsciiz( &wm
->ldr
.FullDllName
, wm
->filename
);
440 RtlCreateUnicodeStringFromAsciiz( &wm
->ldr
.BaseDllName
, wm
->modname
);
442 wm
->ldr
.LoadCount
= 0;
443 wm
->ldr
.TlsIndex
= -1;
444 wm
->ldr
.SectionHandle
= NULL
;
445 wm
->ldr
.CheckSum
= 0;
446 wm
->ldr
.TimeDateStamp
= 0;
448 /* this is a bit ugly, but we need to have app module first in LoadOrder
449 * list, But in wine, ntdll is loaded first, so by inserting DLLs at the tail
450 * and app module at the head we insure that order
452 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
454 /* is first loaded module a DLL or an exec ? */
455 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
456 if (mark
->Flink
== mark
||
457 (CONTAINING_RECORD(mark
->Flink
, LDR_MODULE
, InLoadOrderModuleList
)->Flags
& LDR_IMAGE_IS_DLL
))
459 InsertHeadList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
460 &wm
->ldr
.InLoadOrderModuleList
);
464 else wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
467 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
468 &wm
->ldr
.InLoadOrderModuleList
);
470 /* insert module in MemoryList, sorted in increasing base addresses */
471 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
472 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
474 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
477 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
478 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
479 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
480 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
482 /* wait until init is called for inserting into this list */
483 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
484 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
490 /*************************************************************************
493 * Allocate the process-wide structure for module TLS storage.
495 static NTSTATUS
alloc_process_tls(void)
497 PLIST_ENTRY mark
, entry
;
499 IMAGE_TLS_DIRECTORY
*dir
;
502 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
503 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
505 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
506 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
507 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
509 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
511 tls_total_size
+= size
;
514 if (!tls_module_count
) return STATUS_SUCCESS
;
516 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
518 tls_dirs
= RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
519 if (!tls_dirs
) return STATUS_NO_MEMORY
;
521 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
523 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
524 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
525 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
528 *dir
->AddressOfIndex
= i
;
530 mod
->LoadCount
= -1; /* can't unload it */
533 return STATUS_SUCCESS
;
537 /*************************************************************************
540 * Allocate the per-thread structure for module TLS storage.
542 static NTSTATUS
alloc_thread_tls(void)
548 if (!tls_module_count
) return STATUS_SUCCESS
;
550 if (!(pointers
= RtlAllocateHeap( ntdll_get_process_heap(), 0,
551 tls_module_count
* sizeof(*pointers
) )))
552 return STATUS_NO_MEMORY
;
554 if (!(data
= RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_total_size
)))
556 RtlFreeHeap( ntdll_get_process_heap(), 0, pointers
);
557 return STATUS_NO_MEMORY
;
560 for (i
= 0; i
< tls_module_count
; i
++)
562 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
563 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
565 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
566 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
567 (void *)dir
->StartAddressOfRawData
, data
);
570 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
572 memset( data
, 0, dir
->SizeOfZeroFill
);
573 data
+= dir
->SizeOfZeroFill
;
575 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
576 return STATUS_SUCCESS
;
580 /*************************************************************************
583 static void call_tls_callbacks( HMODULE module
, UINT reason
)
585 const IMAGE_TLS_DIRECTORY
*dir
;
586 const PIMAGE_TLS_CALLBACK
*callback
;
589 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
590 if (!dir
|| !dir
->AddressOfCallBacks
) return;
592 for (callback
= dir
->AddressOfCallBacks
; *callback
; callback
++)
595 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
596 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
597 (*callback
)( module
, reason
, NULL
);
599 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
600 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
605 /*************************************************************************
608 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
612 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
613 void *module
= wm
->ldr
.BaseAddress
;
615 /* Skip calls for modules loaded with special load flags */
617 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
618 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
619 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return TRUE
;
623 size_t len
= max( strlen(wm
->modname
), sizeof(mod_name
)-1 );
624 memcpy( mod_name
, wm
->modname
, len
);
626 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p (%s),reason=%s,res=%p)\n",
627 GetCurrentThreadId(), entry
, module
, mod_name
, reason_names
[reason
], lpReserved
);
629 else TRACE("(%p (%s),%s,%p) - CALL\n", module
, wm
->modname
, reason_names
[reason
], lpReserved
);
631 retv
= entry( module
, reason
, lpReserved
);
633 /* The state of the module list may have changed due to the call
634 to the dll. We cannot assume that this module has not been
637 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p (%s),reason=%s,res=%p) retval=%x\n",
638 GetCurrentThreadId(), entry
, module
, mod_name
, reason_names
[reason
], lpReserved
, retv
);
639 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
645 /*************************************************************************
646 * MODULE_DllProcessAttach
648 * Send the process attach notification to all DLLs the given module
649 * depends on (recursively). This is somewhat complicated due to the fact that
651 * - we have to respect the module dependencies, i.e. modules implicitly
652 * referenced by another module have to be initialized before the module
653 * itself can be initialized
655 * - the initialization routine of a DLL can itself call LoadLibrary,
656 * thereby introducing a whole new set of dependencies (even involving
657 * the 'old' modules) at any time during the whole process
659 * (Note that this routine can be recursively entered not only directly
660 * from itself, but also via LoadLibrary from one of the called initialization
663 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
664 * the process *detach* notifications to be sent in the correct order.
665 * This must not only take into account module dependencies, but also
666 * 'hidden' dependencies created by modules calling LoadLibrary in their
667 * attach notification routine.
669 * The strategy is rather simple: we move a WINE_MODREF to the head of the
670 * list after the attach notification has returned. This implies that the
671 * detach notifications are called in the reverse of the sequence the attach
672 * notifications *returned*.
674 NTSTATUS
MODULE_DllProcessAttach( WINE_MODREF
*wm
, LPVOID lpReserved
)
676 NTSTATUS status
= STATUS_SUCCESS
;
679 RtlEnterCriticalSection( &loader_section
);
685 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
686 wm
= CONTAINING_RECORD(CONTAINING_RECORD(mark
->Flink
,
687 LDR_MODULE
, InLoadOrderModuleList
),
689 wm
->ldr
.LoadCount
= -1; /* can't unload main exe */
690 if ((status
= fixup_imports( wm
)) != STATUS_SUCCESS
) goto done
;
691 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto done
;
692 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
696 /* prevent infinite recursion in case of cyclical dependencies */
697 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
698 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
701 TRACE("(%s,%p) - START\n", wm
->modname
, lpReserved
);
703 /* Tag current MODREF to prevent recursive loop */
704 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
706 /* Recursively attach all DLLs this one depends on */
707 for ( i
= 0; i
< wm
->nDeps
; i
++ )
709 if (!wm
->deps
[i
]) continue;
710 if ((status
= MODULE_DllProcessAttach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
713 /* Call DLL entry point */
714 if (status
== STATUS_SUCCESS
)
716 WINE_MODREF
*prev
= current_modref
;
718 if (MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
))
719 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
721 status
= STATUS_DLL_INIT_FAILED
;
722 current_modref
= prev
;
725 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
726 &wm
->ldr
.InInitializationOrderModuleList
);
728 /* Remove recursion flag */
729 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
731 TRACE("(%s,%p) - END\n", wm
->modname
, lpReserved
);
734 RtlLeaveCriticalSection( &loader_section
);
738 /*************************************************************************
739 * MODULE_DllProcessDetach
741 * Send DLL process detach notifications. See the comment about calling
742 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
743 * is set, only DLLs with zero refcount are notified.
745 static void MODULE_DllProcessDetach( BOOL bForceDetach
, LPVOID lpReserved
)
747 PLIST_ENTRY mark
, entry
;
750 RtlEnterCriticalSection( &loader_section
);
751 if (bForceDetach
) process_detaching
= 1;
752 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
755 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
757 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
758 InInitializationOrderModuleList
);
759 /* Check whether to detach this DLL */
760 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
762 if ( mod
->LoadCount
&& !bForceDetach
)
765 /* Call detach notification */
766 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
767 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
768 DLL_PROCESS_DETACH
, lpReserved
);
770 /* Restart at head of WINE_MODREF list, as entries might have
771 been added and/or removed while performing the call ... */
774 } while (entry
!= mark
);
776 RtlLeaveCriticalSection( &loader_section
);
779 /*************************************************************************
780 * MODULE_DllThreadAttach
782 * Send DLL thread attach notifications. These are sent in the
783 * reverse sequence of process detach notification.
786 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
788 PLIST_ENTRY mark
, entry
;
792 /* don't do any attach calls if process is exiting */
793 if (process_detaching
) return STATUS_SUCCESS
;
794 /* FIXME: there is still a race here */
796 RtlEnterCriticalSection( &loader_section
);
798 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
800 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
801 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
803 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
804 InInitializationOrderModuleList
);
805 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
807 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
810 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
811 DLL_THREAD_ATTACH
, lpReserved
);
815 RtlLeaveCriticalSection( &loader_section
);
819 /******************************************************************
820 * LdrDisableThreadCalloutsForDll (NTDLL.@)
823 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
826 NTSTATUS ret
= STATUS_SUCCESS
;
828 RtlEnterCriticalSection( &loader_section
);
830 wm
= get_modref( hModule
);
831 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
832 ret
= STATUS_DLL_NOT_FOUND
;
834 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
836 RtlLeaveCriticalSection( &loader_section
);
841 /******************************************************************
842 * LdrFindEntryForAddress (NTDLL.@)
844 * The loader_section must be locked while calling this function
846 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
848 PLIST_ENTRY mark
, entry
;
851 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
852 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
854 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
855 if ((const void *)mod
->BaseAddress
<= addr
&&
856 (char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
859 return STATUS_SUCCESS
;
861 if ((const void *)mod
->BaseAddress
> addr
) break;
863 return STATUS_NO_MORE_ENTRIES
;
866 /******************************************************************
867 * LdrLockLoaderLock (NTDLL.@)
869 * Note: flags are not implemented.
870 * Flag 0x01 is used to raise exceptions on errors.
871 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
873 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
875 if (flags
) FIXME( "flags %lx not supported\n", flags
);
877 if (result
) *result
= 1;
878 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
879 RtlEnterCriticalSection( &loader_section
);
880 *magic
= GetCurrentThreadId();
881 return STATUS_SUCCESS
;
885 /******************************************************************
886 * LdrUnlockLoaderUnlock (NTDLL.@)
888 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
892 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
893 RtlLeaveCriticalSection( &loader_section
);
895 return STATUS_SUCCESS
;
899 /******************************************************************
900 * LdrGetDllHandle (NTDLL.@)
902 NTSTATUS WINAPI
LdrGetDllHandle(ULONG x
, ULONG y
, PUNICODE_STRING name
, HMODULE
*base
)
904 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
905 WCHAR dllname
[MAX_PATH
+4], *p
;
907 PLIST_ENTRY mark
, entry
;
910 if (x
!= 0 || y
!= 0)
911 FIXME("Unknown behavior, please report\n");
913 /* Append .DLL to name if no extension present */
914 if (!(p
= strrchrW( name
->Buffer
, '.')) || strchrW( p
, '/' ) || strchrW( p
, '\\'))
916 if (name
->Length
>= MAX_PATH
) return STATUS_NAME_TOO_LONG
;
917 strcpyW( dllname
, name
->Buffer
);
918 strcatW( dllname
, dllW
);
919 RtlInitUnicodeString( &str
, dllname
);
923 RtlEnterCriticalSection( &loader_section
);
927 if (RtlEqualUnicodeString( name
, &cached_modref
->ldr
.FullDllName
, TRUE
) ||
928 RtlEqualUnicodeString( name
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
930 *base
= cached_modref
->ldr
.BaseAddress
;
931 status
= STATUS_SUCCESS
;
936 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
937 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
939 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
941 if (RtlEqualUnicodeString( name
, &mod
->FullDllName
, TRUE
) ||
942 RtlEqualUnicodeString( name
, &mod
->BaseDllName
, TRUE
))
944 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
945 *base
= mod
->BaseAddress
;
946 status
= STATUS_SUCCESS
;
951 RtlLeaveCriticalSection( &loader_section
);
952 TRACE("%lx %lx %s -> %p\n", x
, y
, debugstr_us(name
), status
? NULL
: *base
);
957 /******************************************************************
958 * LdrGetProcedureAddress (NTDLL.@)
960 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, PANSI_STRING name
, ULONG ord
, PVOID
*address
)
962 IMAGE_EXPORT_DIRECTORY
*exports
;
964 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
966 RtlEnterCriticalSection( &loader_section
);
968 if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
969 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
971 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
972 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
976 ret
= STATUS_SUCCESS
;
981 /* check if the module itself is invalid to return the proper error */
982 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
985 RtlLeaveCriticalSection( &loader_section
);
990 /***********************************************************************
991 * load_builtin_callback
993 * Load a library in memory; callback function for wine_dll_register
995 static void load_builtin_callback( void *module
, const char *filename
)
997 IMAGE_NT_HEADERS
*nt
;
1004 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1007 if (!(nt
= RtlImageNtHeader( module
)))
1009 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1010 last_builtin_status
= STATUS_INVALID_IMAGE_FORMAT
;
1013 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
1015 /* if we already have an executable, ignore this one */
1016 if (!NtCurrentTeb()->Peb
->ImageBaseAddress
)
1017 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1018 return; /* don't create the modref here, will be done later on */
1021 if (find_module( filename
))
1022 MESSAGE( "Warning: loading builtin %s, but native version already present. "
1023 "Expect trouble.\n", filename
);
1025 /* create the MODREF */
1027 len
= GetSystemDirectoryA( NULL
, 0 );
1028 if (!(fullname
= RtlAllocateHeap( ntdll_get_process_heap(), 0, len
+ strlen(filename
) + 1 )))
1030 ERR( "can't load %s\n", filename
);
1031 last_builtin_status
= STATUS_NO_MEMORY
;
1034 GetSystemDirectoryA( fullname
, len
);
1035 strcat( fullname
, "\\" );
1036 strcat( fullname
, filename
);
1038 wm
= MODULE_AllocModRef( module
, fullname
);
1039 RtlFreeHeap( ntdll_get_process_heap(), 0, fullname
);
1042 ERR( "can't load %s\n", filename
);
1043 last_builtin_status
= STATUS_NO_MEMORY
;
1046 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1050 if (fixup_imports( wm
) != STATUS_SUCCESS
)
1052 /* the module has only be inserted in the load & memory order lists */
1053 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1054 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1055 /* FIXME: free the modref */
1056 last_builtin_status
= STATUS_DLL_NOT_FOUND
;
1059 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1061 /* send the DLL load event */
1063 SERVER_START_REQ( load_dll
)
1067 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1068 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1069 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1070 req
->name
= &wm
->filename
;
1071 wine_server_add_data( req
, wm
->filename
, strlen(wm
->filename
) );
1072 wine_server_call( req
);
1076 /* setup relay debugging entry points */
1077 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1081 /***********************************************************************
1084 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
1085 * portion of the provided name and put the name in it.
1088 static LPCSTR
allocate_lib_dir(LPCSTR libname
)
1095 if ((p
= strrchr( pmax
, '\\' ))) pmax
= p
+ 1;
1096 if ((p
= strrchr( pmax
, '/' ))) pmax
= p
+ 1; /* Naughty. MSDN says don't */
1097 if (pmax
== libname
&& pmax
[0] && pmax
[1] == ':') pmax
+= 2;
1099 length
= pmax
- libname
;
1101 result
= RtlAllocateHeap (ntdll_get_process_heap(), 0, length
+1);
1105 strncpy (result
, libname
, length
);
1106 result
[length
] = '\0';
1113 /******************************************************************************
1114 * load_native_dll (internal)
1116 static NTSTATUS
load_native_dll( LPCSTR name
, DWORD flags
, WINE_MODREF
** pwm
)
1119 HANDLE file
, mapping
;
1120 OBJECT_ATTRIBUTES attr
;
1122 IMAGE_NT_HEADERS
*nt
;
1128 file
= CreateFileA( name
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0 );
1129 if (file
== INVALID_HANDLE_VALUE
)
1131 /* keep it that way until we transform CreateFile into NtCreateFile */
1132 return (GetLastError() == ERROR_FILE_NOT_FOUND
) ?
1133 STATUS_NO_SUCH_FILE
: STATUS_INTERNAL_ERROR
;
1136 TRACE( "loading %s\n", debugstr_a(name
) );
1138 attr
.Length
= sizeof(attr
);
1139 attr
.RootDirectory
= 0;
1140 attr
.ObjectName
= NULL
;
1141 attr
.Attributes
= 0;
1142 attr
.SecurityDescriptor
= NULL
;
1143 attr
.SecurityQualityOfService
= NULL
;
1146 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1147 &attr
, &size
, 0, SEC_IMAGE
, file
);
1148 if (status
!= STATUS_SUCCESS
) goto done
;
1151 status
= NtMapViewOfSection( mapping
, GetCurrentProcess(),
1152 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1154 if (status
!= STATUS_SUCCESS
) goto done
;
1156 /* create the MODREF */
1158 if (!(wm
= MODULE_AllocModRef( module
, name
)))
1160 status
= STATUS_NO_MEMORY
;
1166 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1168 if ((status
= fixup_imports(wm
)) != STATUS_SUCCESS
)
1170 /* the module has only be inserted in the load & memory order lists */
1171 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1172 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1174 /* FIXME: there are several more dangling references
1175 * left. Including dlls loaded by this dll before the
1176 * failed one. Unrolling is rather difficult with the
1177 * current structure and we can leave them lying
1178 * around with no problems, so we don't care.
1179 * As these might reference our wm, we don't free it.
1184 else wm
->ldr
.Flags
|= LDR_DONT_RESOLVE_REFS
;
1186 /* send DLL load event */
1188 nt
= RtlImageNtHeader( module
);
1189 drive_type
= GetDriveTypeA( wm
->filename
);
1191 SERVER_START_REQ( load_dll
)
1195 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1196 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1197 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1198 req
->name
= &wm
->filename
;
1199 /* don't keep the file handle open on removable media */
1200 if (drive_type
== DRIVE_REMOVABLE
|| drive_type
== DRIVE_CDROM
) req
->handle
= 0;
1201 wine_server_add_data( req
, wm
->filename
, strlen(wm
->filename
) );
1202 wine_server_call( req
);
1206 if (TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1209 status
= STATUS_SUCCESS
;
1216 /***********************************************************************
1219 static NTSTATUS
load_builtin_dll( LPCSTR path
, DWORD flags
, WINE_MODREF
** pwm
)
1221 char error
[256], dllname
[MAX_PATH
], *p
;
1227 /* Fix the name in case we have a full path and extension */
1229 if ((p
= strrchr( name
, '\\' ))) name
= p
+ 1;
1230 if ((p
= strrchr( name
, '/' ))) name
= p
+ 1;
1232 if (strlen(name
) >= sizeof(dllname
)-4) return STATUS_NO_SUCH_FILE
;
1234 strcpy( dllname
, name
);
1235 p
= strrchr( dllname
, '.' );
1236 if (!p
) strcat( dllname
, ".dll" );
1237 for (p
= dllname
; *p
; p
++) *p
= FILE_tolower(*p
);
1239 last_builtin_status
= STATUS_SUCCESS
;
1240 /* load_library will modify last_builtin_status. Note also that load_library can be
1241 * called several times, if the .so file we're loading has dependencies.
1242 * last_builtin_status will gather all the errors we may get while loading all these
1245 if (!(handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
)))
1249 /* The file does not exist -> WARN() */
1250 WARN("cannot open .so lib for builtin %s: %s\n", name
, error
);
1251 return STATUS_NO_SUCH_FILE
;
1253 /* ERR() for all other errors (missing functions, ...) */
1254 ERR("failed to load .so lib for builtin %s: %s\n", name
, error
);
1255 return STATUS_PROCEDURE_NOT_FOUND
;
1257 if (last_builtin_status
!= STATUS_SUCCESS
) return last_builtin_status
;
1259 if (!(wm
= find_module( path
))) wm
= find_module( dllname
);
1262 ERR( "loaded .so but dll %s still not found - 16-bit dll or version conflict.\n", dllname
);
1263 /* wine_dll_unload( handle );*/
1264 return STATUS_INVALID_IMAGE_FORMAT
;
1266 wm
->dlhandle
= handle
;
1268 return STATUS_SUCCESS
;
1272 /***********************************************************************
1273 * load_dll (internal)
1275 * Load a PE style module according to the load order.
1277 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
1278 * on this function. When first called from LoadLibraryExA it will be
1279 * NULL but thereafter it may point to a buffer containing the path
1280 * portion of the library name. Note that the recursion all occurs
1281 * within a Critical section (see LoadLibraryExA) so the use of a
1282 * static is acceptable.
1283 * (We have to use a static variable at some point anyway, to pass the
1284 * information from BUILTIN32_dlopen through dlopen and the builtin's
1285 * init function into load_library).
1286 * allocated_libdir is TRUE in the stack frame that allocated libdir
1288 static NTSTATUS
load_dll( LPCSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1291 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
1293 const char *filetype
= "";
1295 WINE_MODREF
*main_exe
;
1296 BOOL allocated_libdir
= FALSE
;
1297 static LPCSTR libdir
= NULL
; /* See above */
1298 NTSTATUS nts
= STATUS_NO_SUCH_FILE
;
1301 if ( !libname
) return STATUS_DLL_NOT_FOUND
; /* FIXME ? */
1303 filename
= RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH
+ 1 );
1304 if ( !filename
) return STATUS_NO_MEMORY
;
1305 *filename
= 0; /* Just in case we don't set it before goto error */
1307 RtlEnterCriticalSection( &loader_section
);
1309 if ((flags
& LOAD_WITH_ALTERED_SEARCH_PATH
) && FILE_contains_path(libname
))
1311 if (!(libdir
= allocate_lib_dir(libname
)))
1313 nts
= STATUS_NO_MEMORY
;
1316 allocated_libdir
= TRUE
;
1319 if (!libdir
|| allocated_libdir
)
1320 found
= SearchPathA(NULL
, libname
, ".dll", MAX_PATH
, filename
, NULL
);
1322 found
= DIR_SearchAlternatePath(libdir
, libname
, ".dll", MAX_PATH
, filename
, NULL
);
1324 /* build the modules filename */
1327 if (!MODULE_GetBuiltinPath( libname
, ".dll", filename
, MAX_PATH
))
1329 nts
= STATUS_INTERNAL_ERROR
;
1334 /* Check for already loaded module */
1335 if (!(*pwm
= find_module(filename
)) && !FILE_contains_path(libname
))
1337 LPSTR fn
= RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH
+ 1 );
1340 /* since the default loading mechanism uses a more detailed algorithm
1341 * than SearchPath (like using PATH, which can even be modified between
1342 * two attempts of loading the same DLL), the look-up above (with
1343 * SearchPath) can have put the file in system directory, whereas it
1344 * has already been loaded but with a different path. So do a specific
1345 * look-up with filename (without any path)
1347 strcpy ( fn
, libname
);
1348 /* if the filename doesn't have an extension append .DLL */
1349 if (!strrchr( fn
, '.')) strcat( fn
, ".dll" );
1350 if ((*pwm
= find_module( fn
)) != NULL
)
1351 strcpy( filename
, fn
);
1352 RtlFreeHeap( ntdll_get_process_heap(), 0, fn
);
1357 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1359 if (((*pwm
)->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) &&
1360 !(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1362 (*pwm
)->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1363 fixup_imports( *pwm
);
1365 TRACE("Already loaded module '%s' at %p, count=%d\n", filename
, (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1366 if (allocated_libdir
)
1368 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR
)libdir
);
1371 RtlLeaveCriticalSection( &loader_section
);
1372 RtlFreeHeap( ntdll_get_process_heap(), 0, filename
);
1373 return STATUS_SUCCESS
;
1376 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1377 MODULE_GetLoadOrderA( loadorder
, main_exe
->ldr
.BaseDllName
.Buffer
, filename
, TRUE
);
1379 for (i
= 0; i
< LOADORDER_NTYPES
; i
++)
1381 if (loadorder
[i
] == LOADORDER_INVALID
) break;
1383 switch (loadorder
[i
])
1386 TRACE("Trying native dll '%s'\n", filename
);
1387 nts
= load_native_dll(filename
, flags
, pwm
);
1388 filetype
= "native";
1391 TRACE("Trying built-in '%s'\n", filename
);
1392 nts
= load_builtin_dll(filename
, flags
, pwm
);
1393 filetype
= "builtin";
1396 nts
= STATUS_INTERNAL_ERROR
;
1400 if (nts
== STATUS_SUCCESS
)
1402 /* Initialize DLL just loaded */
1403 TRACE("Loaded module '%s' (%s) at %p\n", filename
, filetype
, (*pwm
)->ldr
.BaseAddress
);
1404 if (!TRACE_ON(module
))
1405 TRACE_(loaddll
)("Loaded module '%s' : %s\n", filename
, filetype
);
1406 /* Set the ldr.LoadCount here so that an attach failure will */
1407 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1408 (*pwm
)->ldr
.LoadCount
= 1;
1410 if (allocated_libdir
)
1412 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR
)libdir
);
1415 RtlLeaveCriticalSection( &loader_section
);
1416 RtlFreeHeap( ntdll_get_process_heap(), 0, filename
);
1420 if (nts
!= STATUS_NO_SUCH_FILE
)
1422 WARN("Loading of %s DLL %s failed (status %lx).\n",
1423 filetype
, filename
, nts
);
1429 if (allocated_libdir
)
1431 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR
)libdir
);
1434 RtlLeaveCriticalSection( &loader_section
);
1435 WARN("Failed to load module '%s'; status=%lx\n", filename
, nts
);
1436 RtlFreeHeap( ntdll_get_process_heap(), 0, filename
);
1440 /******************************************************************
1441 * LdrLoadDll (NTDLL.@)
1443 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
, PUNICODE_STRING libname
, HMODULE
* hModule
)
1446 NTSTATUS nts
= STATUS_SUCCESS
;
1449 RtlUnicodeStringToAnsiString(&str
, libname
, TRUE
);
1451 RtlEnterCriticalSection( &loader_section
);
1453 switch (nts
= load_dll( str
.Buffer
, flags
, &wm
))
1455 case STATUS_SUCCESS
:
1456 nts
= MODULE_DllProcessAttach( wm
, NULL
);
1457 if (nts
!= STATUS_SUCCESS
)
1459 WARN("Attach failed for module '%s'.\n", str
.Buffer
);
1460 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1464 case STATUS_NO_SUCH_FILE
:
1465 nts
= STATUS_DLL_NOT_FOUND
;
1467 default: /* keep error code as it is (memory...) */
1471 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1473 RtlLeaveCriticalSection( &loader_section
);
1475 RtlFreeAnsiString(&str
);
1480 /******************************************************************
1481 * LdrQueryProcessModuleInformation
1484 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
1485 ULONG buf_size
, ULONG
* req_size
)
1487 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
1488 ULONG size
= sizeof(ULONG
);
1489 NTSTATUS nts
= STATUS_SUCCESS
;
1492 PLIST_ENTRY mark
, entry
;
1495 smi
->ModulesCount
= 0;
1497 RtlEnterCriticalSection( &loader_section
);
1498 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1499 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1501 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1502 size
+= sizeof(*sm
);
1503 if (size
<= buf_size
)
1505 sm
->Reserved1
= 0; /* FIXME */
1506 sm
->Reserved2
= 0; /* FIXME */
1507 sm
->ImageBaseAddress
= mod
->BaseAddress
;
1508 sm
->ImageSize
= mod
->SizeOfImage
;
1509 sm
->Flags
= mod
->Flags
;
1510 sm
->Id
= 0; /* FIXME */
1511 sm
->Rank
= 0; /* FIXME */
1512 sm
->Unknown
= 0; /* FIXME */
1514 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
1515 str
.Buffer
= sm
->Name
;
1516 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
1517 ptr
= strrchr(sm
->Name
, '\\');
1518 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- (char*)sm
->Name
+ 1) : 0;
1520 smi
->ModulesCount
++;
1523 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
1525 RtlLeaveCriticalSection( &loader_section
);
1527 if (req_size
) *req_size
= size
;
1532 /******************************************************************
1533 * LdrShutdownProcess (NTDLL.@)
1536 void WINAPI
LdrShutdownProcess(void)
1539 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
1542 /******************************************************************
1543 * LdrShutdownThread (NTDLL.@)
1546 void WINAPI
LdrShutdownThread(void)
1548 PLIST_ENTRY mark
, entry
;
1553 /* don't do any detach calls if process is exiting */
1554 if (process_detaching
) return;
1555 /* FIXME: there is still a race here */
1557 RtlEnterCriticalSection( &loader_section
);
1559 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1560 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1562 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1563 InInitializationOrderModuleList
);
1564 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1566 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1569 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1570 DLL_THREAD_DETACH
, NULL
);
1573 RtlLeaveCriticalSection( &loader_section
);
1576 /***********************************************************************
1577 * MODULE_FlushModrefs
1579 * Remove all unused modrefs and call the internal unloading routines
1580 * for the library type.
1582 * The loader_section must be locked while calling this function.
1584 static void MODULE_FlushModrefs(void)
1586 PLIST_ENTRY mark
, entry
, prev
;
1590 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1591 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
1593 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1594 InInitializationOrderModuleList
);
1595 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1597 prev
= entry
->Blink
;
1598 if (wm
->ldr
.LoadCount
) continue;
1600 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1601 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1602 RemoveEntryList(&wm
->ldr
.InInitializationOrderModuleList
);
1604 TRACE(" unloading %s\n", wm
->filename
);
1605 if (!TRACE_ON(module
))
1606 TRACE_(loaddll
)("Unloaded module '%s' : %s\n", wm
->filename
,
1607 wm
->dlhandle
? "builtin" : "native" );
1609 SERVER_START_REQ( unload_dll
)
1611 req
->base
= wm
->ldr
.BaseAddress
;
1612 wine_server_call( req
);
1616 if (wm
->dlhandle
) wine_dll_unload( wm
->dlhandle
);
1617 else NtUnmapViewOfSection( GetCurrentProcess(), wm
->ldr
.BaseAddress
);
1618 if (cached_modref
== wm
) cached_modref
= NULL
;
1619 RtlFreeHeap( ntdll_get_process_heap(), 0, wm
->deps
);
1620 RtlFreeHeap( ntdll_get_process_heap(), 0, wm
);
1624 /***********************************************************************
1625 * MODULE_DecRefCount
1627 * The loader_section must be locked while calling this function.
1629 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
1633 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
1636 if ( wm
->ldr
.LoadCount
<= 0 )
1639 --wm
->ldr
.LoadCount
;
1640 TRACE("(%s) ldr.LoadCount: %d\n", wm
->modname
, wm
->ldr
.LoadCount
);
1642 if ( wm
->ldr
.LoadCount
== 0 )
1644 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
1646 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1648 MODULE_DecRefCount( wm
->deps
[i
] );
1650 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
1654 /******************************************************************
1655 * LdrUnloadDll (NTDLL.@)
1659 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
1661 NTSTATUS retv
= STATUS_SUCCESS
;
1663 TRACE("(%p)\n", hModule
);
1665 RtlEnterCriticalSection( &loader_section
);
1667 /* if we're stopping the whole process (and forcing the removal of all
1668 * DLLs) the library will be freed anyway
1670 if (!process_detaching
)
1675 if ((wm
= get_modref( hModule
)) != NULL
)
1677 TRACE("(%s) - START\n", wm
->modname
);
1679 /* Recursively decrement reference counts */
1680 MODULE_DecRefCount( wm
);
1682 /* Call process detach notifications */
1683 if ( free_lib_count
<= 1 )
1685 MODULE_DllProcessDetach( FALSE
, NULL
);
1686 MODULE_FlushModrefs();
1692 retv
= STATUS_DLL_NOT_FOUND
;
1697 RtlLeaveCriticalSection( &loader_section
);
1702 /***********************************************************************
1703 * RtlImageNtHeader (NTDLL.@)
1705 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
1707 IMAGE_NT_HEADERS
*ret
;
1711 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
1714 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
1716 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
1717 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
1720 __EXCEPT(page_fault
)
1729 /***********************************************************************
1730 * RtlImageDirectoryEntryToData (NTDLL.@)
1732 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
1734 const IMAGE_NT_HEADERS
*nt
;
1737 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
1739 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
1742 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
1743 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
1744 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
1745 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
1746 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
1748 /* not mapped as image, need to find the section containing the virtual address */
1749 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
1753 /***********************************************************************
1754 * RtlImageRvaToSection (NTDLL.@)
1756 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
1757 HMODULE module
, DWORD rva
)
1760 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char*)&nt
->OptionalHeader
+
1761 nt
->FileHeader
.SizeOfOptionalHeader
);
1762 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
1764 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
1771 /***********************************************************************
1772 * RtlImageRvaToVa (NTDLL.@)
1774 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
1775 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
1777 IMAGE_SECTION_HEADER
*sec
;
1779 if (section
&& *section
) /* try this section first */
1782 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
1785 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
1787 if (section
) *section
= sec
;
1788 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
1792 /***********************************************************************
1795 * Initialize loading callbacks and return HMODULE of main exe.
1796 * 'main' is the main exe in case it was already loaded from a PE file.
1798 * FIXME: this should be done differently once kernel is properly separated.
1800 HMODULE
BUILTIN32_LoadExeModule( HMODULE main
)
1802 NtCurrentTeb()->Peb
->ImageBaseAddress
= main
;
1803 last_builtin_status
= STATUS_SUCCESS
;
1804 wine_dll_set_callback( load_builtin_callback
);
1805 if (!NtCurrentTeb()->Peb
->ImageBaseAddress
)
1806 MESSAGE( "No built-in EXE module loaded! Did you create a .spec file?\n" );
1807 if (last_builtin_status
!= STATUS_SUCCESS
)
1808 MESSAGE( "Error while processing initial modules\n");
1809 return NtCurrentTeb()->Peb
->ImageBaseAddress
;