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
30 #include "wine/exception.h"
33 #include "wine/debug.h"
34 #include "wine/server.h"
35 #include "ntdll_misc.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(module
);
38 WINE_DECLARE_DEBUG_CHANNEL(relay
);
39 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
40 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
42 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
44 WINE_MODREF
*MODULE_modref_list
= NULL
;
46 static WINE_MODREF
*exe_modref
;
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 CRITICAL_SECTION loader_section
= CRITICAL_SECTION_INIT( "loader_section" );
67 static WINE_MODREF
*cached_modref
;
68 static WINE_MODREF
*current_modref
;
70 static NTSTATUS
load_dll( LPCSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
71 static FARPROC
find_named_export( HMODULE module
, IMAGE_EXPORT_DIRECTORY
*exports
,
72 DWORD exp_size
, const char *name
, int hint
);
74 /* convert PE image VirtualAddress to Real Address */
75 inline static void *get_rva( HMODULE module
, DWORD va
)
77 return (void *)((char *)module
+ va
);
80 /*************************************************************************
83 * Looks for the referenced HMODULE in the current process
84 * The loader_section must be locked while calling this function.
86 static WINE_MODREF
*get_modref( HMODULE hmod
)
90 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
92 for ( wm
= MODULE_modref_list
; wm
; wm
=wm
->next
)
94 if (wm
->ldr
.BaseAddress
== hmod
)
104 /*************************************************************************
105 * find_forwarded_export
107 * Find the final function pointer for a forwarded function.
108 * The loader_section must be locked while calling this function.
110 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
)
112 IMAGE_EXPORT_DIRECTORY
*exports
;
116 char *end
= strchr(forward
, '.');
119 if (!end
) return NULL
;
120 if (end
- forward
>= sizeof(mod_name
)) return NULL
;
121 memcpy( mod_name
, forward
, end
- forward
);
122 mod_name
[end
-forward
] = 0;
124 if (!(wm
= MODULE_FindModule( mod_name
)))
126 ERR("module not found for forward '%s' used by '%s'\n",
127 forward
, get_modref(module
)->filename
);
130 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
131 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
132 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1 );
136 ERR("function not found for forward '%s' used by '%s'."
137 " If you are using builtin '%s', try using the native one instead.\n",
138 forward
, get_modref(module
)->filename
, get_modref(module
)->modname
);
144 /*************************************************************************
145 * find_ordinal_export
147 * Find an exported function by ordinal.
148 * The exports base must have been subtracted from the ordinal already.
149 * The loader_section must be locked while calling this function.
151 static FARPROC
find_ordinal_export( HMODULE module
, IMAGE_EXPORT_DIRECTORY
*exports
,
152 DWORD exp_size
, int ordinal
)
155 DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
157 if (ordinal
>= exports
->NumberOfFunctions
)
159 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
162 if (!functions
[ordinal
]) return NULL
;
164 proc
= get_rva( module
, functions
[ordinal
] );
166 /* if the address falls into the export dir, it's a forward */
167 if (((char *)proc
>= (char *)exports
) && ((char *)proc
< (char *)exports
+ exp_size
))
168 return find_forwarded_export( module
, (char *)proc
);
172 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
);
174 if (TRACE_ON(relay
) && current_modref
)
176 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, current_modref
->modname
);
182 /*************************************************************************
185 * Find an exported function by name.
186 * The loader_section must be locked while calling this function.
188 static FARPROC
find_named_export( HMODULE module
, IMAGE_EXPORT_DIRECTORY
*exports
,
189 DWORD exp_size
, const char *name
, int hint
)
191 WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
192 DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
193 int min
= 0, max
= exports
->NumberOfNames
- 1;
195 /* first check the hint */
196 if (hint
>= 0 && hint
<= max
)
198 char *ename
= get_rva( module
, names
[hint
] );
199 if (!strcmp( ename
, name
))
200 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
] );
203 /* then do a binary search */
206 int res
, pos
= (min
+ max
) / 2;
207 char *ename
= get_rva( module
, names
[pos
] );
208 if (!(res
= strcmp( ename
, name
)))
209 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
] );
210 if (res
> 0) max
= pos
- 1;
218 /*************************************************************************
221 * Import the dll specified by the given import descriptor.
222 * The loader_section must be locked while calling this function.
224 static WINE_MODREF
*import_dll( HMODULE module
, IMAGE_IMPORT_DESCRIPTOR
*descr
)
229 IMAGE_EXPORT_DIRECTORY
*exports
;
231 IMAGE_THUNK_DATA
*import_list
, *thunk_list
;
232 char *name
= get_rva( module
, descr
->Name
);
234 status
= load_dll( name
, 0, &wmImp
);
237 if (status
== STATUS_NO_SUCH_FILE
)
238 ERR("Module (file) %s (which is needed by %s) not found\n",
239 name
, current_modref
->filename
);
241 ERR("Loading module (file) %s (which is needed by %s) failed (error %ld).\n",
242 name
, current_modref
->filename
, status
);
246 imp_mod
= wmImp
->ldr
.BaseAddress
;
247 if (!(exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
,
248 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
251 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
252 if (descr
->u
.OriginalFirstThunk
)
253 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
255 import_list
= thunk_list
;
257 while (import_list
->u1
.Ordinal
)
259 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
261 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
263 TRACE("--- Ordinal %s,%d\n", name
, ordinal
);
264 thunk_list
->u1
.Function
= (PDWORD
)find_ordinal_export( imp_mod
, exports
, exp_size
,
265 ordinal
- exports
->Base
);
266 if (!thunk_list
->u1
.Function
)
268 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
269 name
, ordinal
, current_modref
->filename
);
270 thunk_list
->u1
.Function
= (PDWORD
)0xdeadbeef;
273 else /* import by name */
275 IMAGE_IMPORT_BY_NAME
*pe_name
;
276 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
277 TRACE("--- %s %s.%d\n", pe_name
->Name
, name
, pe_name
->Hint
);
278 thunk_list
->u1
.Function
= (PDWORD
)find_named_export( imp_mod
, exports
, exp_size
,
279 pe_name
->Name
, pe_name
->Hint
);
280 if (!thunk_list
->u1
.Function
)
282 ERR("No implementation for %s.%s imported from %s, setting to 0xdeadbeef\n",
283 name
, pe_name
->Name
, current_modref
->filename
);
284 thunk_list
->u1
.Function
= (PDWORD
)0xdeadbeef;
294 /****************************************************************
297 * Fixup all imports of a given module.
298 * The loader_section must be locked while calling this function.
300 DWORD
PE_fixup_imports( WINE_MODREF
*wm
)
303 IMAGE_IMPORT_DESCRIPTOR
*imports
;
307 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
308 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
311 nb_imports
= size
/ sizeof(*imports
);
312 for (i
= 0; i
< nb_imports
; i
++)
314 if (!imports
[i
].Name
)
320 if (!nb_imports
) return 0; /* no imports */
322 /* Allocate module dependency list */
323 wm
->nDeps
= nb_imports
;
324 wm
->deps
= RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
326 /* load the imported modules. They are automatically
327 * added to the modref list of the process.
329 prev
= current_modref
;
331 for (i
= 0; i
< nb_imports
; i
++)
333 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
] ))) break;
335 current_modref
= prev
;
336 return (i
< nb_imports
);
340 /*************************************************************************
343 * Allocate a WINE_MODREF structure and add it to the process list
344 * The loader_section must be locked while calling this function.
346 WINE_MODREF
*MODULE_AllocModRef( HMODULE hModule
, LPCSTR filename
)
349 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
351 DWORD long_len
= strlen( filename
);
352 DWORD short_len
= GetShortPathNameA( filename
, NULL
, 0 );
354 if ((wm
= RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY
,
355 sizeof(*wm
) + long_len
+ short_len
+ 1 )))
357 wm
->filename
= wm
->data
;
358 memcpy( wm
->filename
, filename
, long_len
+ 1 );
359 if ((wm
->modname
= strrchr( wm
->filename
, '\\' ))) wm
->modname
++;
360 else wm
->modname
= wm
->filename
;
362 wm
->short_filename
= wm
->filename
+ long_len
+ 1;
363 GetShortPathNameA( wm
->filename
, wm
->short_filename
, short_len
+ 1 );
364 if ((wm
->short_modname
= strrchr( wm
->short_filename
, '\\' ))) wm
->short_modname
++;
365 else wm
->short_modname
= wm
->short_filename
;
367 wm
->next
= MODULE_modref_list
;
368 if (wm
->next
) wm
->next
->prev
= wm
;
369 MODULE_modref_list
= wm
;
371 wm
->ldr
.InLoadOrderModuleList
.Flink
= NULL
;
372 wm
->ldr
.InLoadOrderModuleList
.Blink
= NULL
;
373 wm
->ldr
.InMemoryOrderModuleList
.Flink
= NULL
;
374 wm
->ldr
.InMemoryOrderModuleList
.Blink
= NULL
;
375 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
376 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
377 wm
->ldr
.BaseAddress
= hModule
;
378 wm
->ldr
.EntryPoint
= (nt
->OptionalHeader
.AddressOfEntryPoint
) ?
379 ((char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
) : 0;
380 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
381 RtlCreateUnicodeStringFromAsciiz( &wm
->ldr
.FullDllName
, wm
->filename
);
382 RtlCreateUnicodeStringFromAsciiz( &wm
->ldr
.BaseDllName
, wm
->modname
);
384 wm
->ldr
.LoadCount
= 0;
385 wm
->ldr
.TlsIndex
= -1;
386 wm
->ldr
.SectionHandle
= NULL
;
387 wm
->ldr
.CheckSum
= 0;
388 wm
->ldr
.TimeDateStamp
= 0;
390 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
392 if (!exe_modref
) exe_modref
= wm
;
393 else FIXME( "Trying to load second .EXE file: %s\n", filename
);
395 else wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
401 /*************************************************************************
404 static void call_tls_callbacks( HMODULE module
, UINT reason
)
406 const IMAGE_TLS_DIRECTORY
*dir
;
407 const PIMAGE_TLS_CALLBACK
*callback
;
410 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
411 if (!dir
|| !dir
->AddressOfCallBacks
) return;
413 for (callback
= dir
->AddressOfCallBacks
; *callback
; callback
++)
416 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
417 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
418 (*callback
)( module
, reason
, NULL
);
420 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
421 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
426 /*************************************************************************
429 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
433 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
434 void *module
= wm
->ldr
.BaseAddress
;
436 /* Skip calls for modules loaded with special load flags */
438 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
439 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
440 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return TRUE
;
444 size_t len
= max( strlen(wm
->modname
), sizeof(mod_name
)-1 );
445 memcpy( mod_name
, wm
->modname
, len
);
447 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p (%s),reason=%s,res=%p)\n",
448 GetCurrentThreadId(), entry
, module
, mod_name
, reason_names
[reason
], lpReserved
);
450 else TRACE("(%p (%s),%s,%p) - CALL\n", module
, wm
->modname
, reason_names
[reason
], lpReserved
);
452 retv
= entry( module
, reason
, lpReserved
);
454 /* The state of the module list may have changed due to the call
455 to the dll. We cannot assume that this module has not been
458 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p (%s),reason=%s,res=%p) retval=%x\n",
459 GetCurrentThreadId(), entry
, module
, mod_name
, reason_names
[reason
], lpReserved
, retv
);
460 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
466 /*************************************************************************
467 * MODULE_DllProcessAttach
469 * Send the process attach notification to all DLLs the given module
470 * depends on (recursively). This is somewhat complicated due to the fact that
472 * - we have to respect the module dependencies, i.e. modules implicitly
473 * referenced by another module have to be initialized before the module
474 * itself can be initialized
476 * - the initialization routine of a DLL can itself call LoadLibrary,
477 * thereby introducing a whole new set of dependencies (even involving
478 * the 'old' modules) at any time during the whole process
480 * (Note that this routine can be recursively entered not only directly
481 * from itself, but also via LoadLibrary from one of the called initialization
484 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
485 * the process *detach* notifications to be sent in the correct order.
486 * This must not only take into account module dependencies, but also
487 * 'hidden' dependencies created by modules calling LoadLibrary in their
488 * attach notification routine.
490 * The strategy is rather simple: we move a WINE_MODREF to the head of the
491 * list after the attach notification has returned. This implies that the
492 * detach notifications are called in the reverse of the sequence the attach
493 * notifications *returned*.
495 BOOL
MODULE_DllProcessAttach( WINE_MODREF
*wm
, LPVOID lpReserved
)
500 RtlEnterCriticalSection( &loader_section
);
509 /* prevent infinite recursion in case of cyclical dependencies */
510 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
511 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
514 TRACE("(%s,%p) - START\n", wm
->modname
, lpReserved
);
516 /* Tag current MODREF to prevent recursive loop */
517 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
519 /* Recursively attach all DLLs this one depends on */
520 for ( i
= 0; retv
&& i
< wm
->nDeps
; i
++ )
522 retv
= MODULE_DllProcessAttach( wm
->deps
[i
], lpReserved
);
524 /* Call DLL entry point */
527 WINE_MODREF
*prev
= current_modref
;
529 retv
= MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
);
530 if (retv
) wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
531 current_modref
= prev
;
534 /* Re-insert MODREF at head of list */
535 if ( retv
&& wm
->prev
)
537 wm
->prev
->next
= wm
->next
;
538 if ( wm
->next
) wm
->next
->prev
= wm
->prev
;
541 wm
->next
= MODULE_modref_list
;
542 MODULE_modref_list
= wm
->next
->prev
= wm
;
545 /* Remove recursion flag */
546 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
548 TRACE("(%s,%p) - END\n", wm
->modname
, lpReserved
);
552 RtlLeaveCriticalSection( &loader_section
);
556 /*************************************************************************
557 * MODULE_DllProcessDetach
559 * Send DLL process detach notifications. See the comment about calling
560 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
561 * is set, only DLLs with zero refcount are notified.
563 static void MODULE_DllProcessDetach( BOOL bForceDetach
, LPVOID lpReserved
)
567 RtlEnterCriticalSection( &loader_section
);
568 if (bForceDetach
) process_detaching
= 1;
571 for ( wm
= MODULE_modref_list
; wm
; wm
= wm
->next
)
573 /* Check whether to detach this DLL */
574 if ( !(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
576 if ( wm
->ldr
.LoadCount
> 0 && !bForceDetach
)
579 /* Call detach notification */
580 wm
->ldr
.Flags
&= ~LDR_PROCESS_ATTACHED
;
581 MODULE_InitDLL( wm
, DLL_PROCESS_DETACH
, lpReserved
);
583 /* Restart at head of WINE_MODREF list, as entries might have
584 been added and/or removed while performing the call ... */
589 RtlLeaveCriticalSection( &loader_section
);
592 /*************************************************************************
593 * MODULE_DllThreadAttach
595 * Send DLL thread attach notifications. These are sent in the
596 * reverse sequence of process detach notification.
599 void MODULE_DllThreadAttach( LPVOID lpReserved
)
603 /* don't do any attach calls if process is exiting */
604 if (process_detaching
) return;
605 /* FIXME: there is still a race here */
607 RtlEnterCriticalSection( &loader_section
);
611 for ( wm
= MODULE_modref_list
; wm
; wm
= wm
->next
)
615 for ( ; wm
; wm
= wm
->prev
)
617 if ( !(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
619 if ( wm
->ldr
.Flags
& LDR_NO_DLL_CALLS
)
622 MODULE_InitDLL( wm
, DLL_THREAD_ATTACH
, lpReserved
);
625 RtlLeaveCriticalSection( &loader_section
);
628 /******************************************************************
629 * LdrDisableThreadCalloutsForDll (NTDLL.@)
632 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
635 NTSTATUS ret
= STATUS_SUCCESS
;
637 RtlEnterCriticalSection( &loader_section
);
639 wm
= get_modref( hModule
);
640 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
641 ret
= STATUS_DLL_NOT_FOUND
;
643 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
645 RtlLeaveCriticalSection( &loader_section
);
650 /******************************************************************
651 * LdrFindEntryForAddress (NTDLL.@)
653 * The loader_section must be locked while calling this function
655 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* mod
)
659 for ( wm
= MODULE_modref_list
; wm
; wm
= wm
->next
)
661 if ((const void *)wm
->ldr
.BaseAddress
<= addr
&&
662 (char *)addr
< (char*)wm
->ldr
.BaseAddress
+ wm
->ldr
.SizeOfImage
)
665 return STATUS_SUCCESS
;
668 return STATUS_NO_MORE_ENTRIES
;
671 /**********************************************************************
674 * Find a (loaded) win32 module depending on path
675 * LPCSTR path: [in] pathname of module/library to be found
677 * The loader_section must be locked while calling this function
679 * the module handle if found
682 WINE_MODREF
*MODULE_FindModule(LPCSTR path
)
685 char dllname
[260], *p
;
687 /* Append .DLL to name if no extension present */
688 strcpy( dllname
, path
);
689 if (!(p
= strrchr( dllname
, '.')) || strchr( p
, '/' ) || strchr( p
, '\\'))
690 strcat( dllname
, ".DLL" );
692 if ((wm
= cached_modref
) != NULL
)
694 if ( !FILE_strcasecmp( dllname
, wm
->modname
) ) return wm
;
695 if ( !FILE_strcasecmp( dllname
, wm
->filename
) ) return wm
;
696 if ( !FILE_strcasecmp( dllname
, wm
->short_modname
) ) return wm
;
697 if ( !FILE_strcasecmp( dllname
, wm
->short_filename
) ) return wm
;
700 for ( wm
= MODULE_modref_list
; wm
; wm
= wm
->next
)
702 if ( !FILE_strcasecmp( dllname
, wm
->modname
) ) break;
703 if ( !FILE_strcasecmp( dllname
, wm
->filename
) ) break;
704 if ( !FILE_strcasecmp( dllname
, wm
->short_modname
) ) break;
705 if ( !FILE_strcasecmp( dllname
, wm
->short_filename
) ) break;
712 /******************************************************************
713 * LdrLockLoaderLock (NTDLL.@)
715 * Note: flags are not implemented.
716 * Flag 0x01 is used to raise exceptions on errors.
717 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
719 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
721 if (flags
) FIXME( "flags %lx not supported\n", flags
);
723 if (result
) *result
= 1;
724 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
725 RtlEnterCriticalSection( &loader_section
);
726 *magic
= GetCurrentThreadId();
727 return STATUS_SUCCESS
;
731 /******************************************************************
732 * LdrUnlockLoaderUnlock (NTDLL.@)
734 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
738 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
739 RtlLeaveCriticalSection( &loader_section
);
741 return STATUS_SUCCESS
;
745 /******************************************************************
746 * LdrGetDllHandle (NTDLL.@)
750 NTSTATUS WINAPI
LdrGetDllHandle(ULONG x
, ULONG y
, PUNICODE_STRING name
, HMODULE
*base
)
755 if (x
!= 0 || y
!= 0)
756 FIXME("Unknown behavior, please report\n");
758 /* FIXME: we should store module name information as unicode */
759 RtlUnicodeStringToAnsiString( &str
, name
, TRUE
);
760 wm
= MODULE_FindModule( str
.Buffer
);
761 RtlFreeAnsiString( &str
);
766 return STATUS_DLL_NOT_FOUND
;
769 *base
= wm
->ldr
.BaseAddress
;
771 TRACE("%lx %lx %s -> %p\n", x
, y
, debugstr_us(name
), *base
);
773 return STATUS_SUCCESS
;
777 /******************************************************************
778 * LdrGetProcedureAddress (NTDLL.@)
780 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, PANSI_STRING name
, ULONG ord
, PVOID
*address
)
782 IMAGE_EXPORT_DIRECTORY
*exports
;
784 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
786 RtlEnterCriticalSection( &loader_section
);
788 if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
789 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
791 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
792 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
796 ret
= STATUS_SUCCESS
;
801 /* check if the module itself is invalid to return the proper error */
802 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
805 RtlLeaveCriticalSection( &loader_section
);
810 /***********************************************************************
813 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
814 * portion of the provided name and put the name in it.
817 static LPCSTR
allocate_lib_dir(LPCSTR libname
)
824 if ((p
= strrchr( pmax
, '\\' ))) pmax
= p
+ 1;
825 if ((p
= strrchr( pmax
, '/' ))) pmax
= p
+ 1; /* Naughty. MSDN says don't */
826 if (pmax
== libname
&& pmax
[0] && pmax
[1] == ':') pmax
+= 2;
828 length
= pmax
- libname
;
830 result
= RtlAllocateHeap (ntdll_get_process_heap(), 0, length
+1);
834 strncpy (result
, libname
, length
);
835 result
[length
] = '\0';
841 /***********************************************************************
842 * load_dll (internal)
844 * Load a PE style module according to the load order.
846 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
847 * on this function. When first called from LoadLibraryExA it will be
848 * NULL but thereafter it may point to a buffer containing the path
849 * portion of the library name. Note that the recursion all occurs
850 * within a Critical section (see LoadLibraryExA) so the use of a
851 * static is acceptable.
852 * (We have to use a static variable at some point anyway, to pass the
853 * information from BUILTIN32_dlopen through dlopen and the builtin's
854 * init function into load_library).
855 * allocated_libdir is TRUE in the stack frame that allocated libdir
857 static NTSTATUS
load_dll( LPCSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
860 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
862 const char *filetype
= "";
864 BOOL allocated_libdir
= FALSE
;
865 static LPCSTR libdir
= NULL
; /* See above */
866 NTSTATUS nts
= STATUS_SUCCESS
;
869 if ( !libname
) return STATUS_DLL_NOT_FOUND
; /* FIXME ? */
871 filename
= RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH
+ 1 );
872 if ( !filename
) return STATUS_NO_MEMORY
;
873 *filename
= 0; /* Just in case we don't set it before goto error */
875 RtlEnterCriticalSection( &loader_section
);
877 if ((flags
& LOAD_WITH_ALTERED_SEARCH_PATH
) && FILE_contains_path(libname
))
879 if (!(libdir
= allocate_lib_dir(libname
)))
881 nts
= STATUS_NO_MEMORY
;
884 allocated_libdir
= TRUE
;
887 if (!libdir
|| allocated_libdir
)
888 found
= SearchPathA(NULL
, libname
, ".dll", MAX_PATH
, filename
, NULL
);
890 found
= DIR_SearchAlternatePath(libdir
, libname
, ".dll", MAX_PATH
, filename
, NULL
);
892 /* build the modules filename */
895 if (!MODULE_GetBuiltinPath( libname
, ".dll", filename
, MAX_PATH
))
897 nts
= STATUS_INTERNAL_ERROR
;
902 /* Check for already loaded module */
903 if (!(*pwm
= MODULE_FindModule(filename
)) && !FILE_contains_path(libname
))
905 LPSTR fn
= RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH
+ 1 );
908 /* since the default loading mechanism uses a more detailed algorithm
909 * than SearchPath (like using PATH, which can even be modified between
910 * two attempts of loading the same DLL), the look-up above (with
911 * SearchPath) can have put the file in system directory, whereas it
912 * has already been loaded but with a different path. So do a specific
913 * look-up with filename (without any path)
915 strcpy ( fn
, libname
);
916 /* if the filename doesn't have an extension append .DLL */
917 if (!strrchr( fn
, '.')) strcat( fn
, ".dll" );
918 if ((*pwm
= MODULE_FindModule( fn
)) != NULL
)
919 strcpy( filename
, fn
);
920 RtlFreeHeap( ntdll_get_process_heap(), 0, fn
);
925 (*pwm
)->ldr
.LoadCount
++;
927 if (((*pwm
)->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) &&
928 !(flags
& DONT_RESOLVE_DLL_REFERENCES
))
930 (*pwm
)->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
931 PE_fixup_imports( *pwm
);
933 TRACE("Already loaded module '%s' at %p, count=%d\n", filename
, (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
934 if (allocated_libdir
)
936 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR
)libdir
);
939 RtlLeaveCriticalSection( &loader_section
);
940 RtlFreeHeap( ntdll_get_process_heap(), 0, filename
);
941 return STATUS_SUCCESS
;
944 MODULE_GetLoadOrder( loadorder
, filename
, TRUE
);
946 for (i
= 0; i
< LOADORDER_NTYPES
; i
++)
948 if (loadorder
[i
] == LOADORDER_INVALID
) break;
950 switch (loadorder
[i
])
953 TRACE("Trying native dll '%s'\n", filename
);
954 nts
= PE_LoadLibraryExA(filename
, flags
, pwm
);
959 TRACE("Trying built-in '%s'\n", filename
);
960 nts
= BUILTIN32_LoadLibraryExA(filename
, flags
, pwm
);
961 filetype
= "builtin";
965 nts
= STATUS_INTERNAL_ERROR
;
969 if (nts
== STATUS_SUCCESS
)
971 /* Initialize DLL just loaded */
972 TRACE("Loaded module '%s' (%s) at %p\n", filename
, filetype
, (*pwm
)->ldr
.BaseAddress
);
973 if (!TRACE_ON(module
))
974 TRACE_(loaddll
)("Loaded module '%s' : %s\n", filename
, filetype
);
975 /* Set the ldr.LoadCount here so that an attach failure will */
976 /* decrement the dependencies through the MODULE_FreeLibrary call. */
977 (*pwm
)->ldr
.LoadCount
= 1;
979 if (allocated_libdir
)
981 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR
)libdir
);
984 RtlLeaveCriticalSection( &loader_section
);
985 RtlFreeHeap( ntdll_get_process_heap(), 0, filename
);
989 if (nts
!= STATUS_NO_SUCH_FILE
)
991 WARN("Loading of %s DLL %s failed (status %ld).\n",
992 filetype
, filename
, nts
);
998 if (allocated_libdir
)
1000 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR
)libdir
);
1003 RtlLeaveCriticalSection( &loader_section
);
1004 WARN("Failed to load module '%s'; status=%ld\n", filename
, nts
);
1005 RtlFreeHeap( ntdll_get_process_heap(), 0, filename
);
1009 /******************************************************************
1010 * LdrLoadDll (NTDLL.@)
1012 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
, PUNICODE_STRING libname
, HMODULE
* hModule
)
1015 NTSTATUS nts
= STATUS_SUCCESS
;
1018 RtlUnicodeStringToAnsiString(&str
, libname
, TRUE
);
1020 RtlEnterCriticalSection( &loader_section
);
1022 switch (nts
= load_dll( str
.Buffer
, flags
, &wm
))
1024 case STATUS_SUCCESS
:
1025 if ( !MODULE_DllProcessAttach( wm
, NULL
) )
1027 WARN("Attach failed for module '%s'.\n", str
.Buffer
);
1028 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1029 nts
= STATUS_DLL_INIT_FAILED
;
1033 case STATUS_NO_SUCH_FILE
:
1034 nts
= STATUS_DLL_NOT_FOUND
;
1036 default: /* keep error code as it is (memory...) */
1040 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1042 RtlLeaveCriticalSection( &loader_section
);
1044 RtlFreeAnsiString(&str
);
1049 /******************************************************************
1050 * LdrQueryProcessModuleInformation
1053 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
1054 ULONG buf_size
, ULONG
* req_size
)
1056 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
1057 ULONG size
= sizeof(ULONG
);
1058 NTSTATUS nts
= STATUS_SUCCESS
;
1063 smi
->ModulesCount
= 0;
1065 RtlEnterCriticalSection( &loader_section
);
1066 for ( wm
= MODULE_modref_list
; wm
; wm
= wm
->next
)
1068 size
+= sizeof(*sm
);
1069 if (size
<= buf_size
)
1071 sm
->Reserved1
= 0; /* FIXME */
1072 sm
->Reserved2
= 0; /* FIXME */
1073 sm
->ImageBaseAddress
= wm
->ldr
.BaseAddress
;
1074 sm
->ImageSize
= wm
->ldr
.SizeOfImage
;
1075 sm
->Flags
= wm
->ldr
.Flags
;
1076 sm
->Id
= 0; /* FIXME */
1077 sm
->Rank
= 0; /* FIXME */
1078 sm
->Unknown
= 0; /* FIXME */
1080 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
1081 str
.Buffer
= sm
->Name
;
1082 RtlUnicodeStringToAnsiString(&str
, &wm
->ldr
.FullDllName
, FALSE
);
1083 ptr
= strrchr(sm
->Name
, '\\');
1084 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- (char*)sm
->Name
+ 1) : 0;
1086 smi
->ModulesCount
++;
1089 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
1091 RtlLeaveCriticalSection( &loader_section
);
1093 if (req_size
) *req_size
= size
;
1098 /******************************************************************
1099 * LdrShutdownProcess (NTDLL.@)
1102 void WINAPI
LdrShutdownProcess(void)
1105 MODULE_DllProcessDetach( TRUE
, (LPVOID
)1 );
1108 /******************************************************************
1109 * LdrShutdownThread (NTDLL.@)
1112 void WINAPI
LdrShutdownThread(void)
1117 /* don't do any detach calls if process is exiting */
1118 if (process_detaching
) return;
1119 /* FIXME: there is still a race here */
1121 RtlEnterCriticalSection( &loader_section
);
1123 for ( wm
= MODULE_modref_list
; wm
; wm
= wm
->next
)
1125 if ( !(wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
1127 if ( wm
->ldr
.Flags
& LDR_NO_DLL_CALLS
)
1130 MODULE_InitDLL( wm
, DLL_THREAD_DETACH
, NULL
);
1133 RtlLeaveCriticalSection( &loader_section
);
1136 /***********************************************************************
1137 * MODULE_FlushModrefs
1139 * Remove all unused modrefs and call the internal unloading routines
1140 * for the library type.
1142 * The loader_section must be locked while calling this function.
1144 static void MODULE_FlushModrefs(void)
1146 WINE_MODREF
*wm
, *next
;
1148 for (wm
= MODULE_modref_list
; wm
; wm
= next
)
1152 if (wm
->ldr
.LoadCount
)
1155 /* Unlink this modref from the chain */
1157 wm
->next
->prev
= wm
->prev
;
1159 wm
->prev
->next
= wm
->next
;
1160 if (wm
== MODULE_modref_list
)
1161 MODULE_modref_list
= wm
->next
;
1163 TRACE(" unloading %s\n", wm
->filename
);
1164 if (!TRACE_ON(module
))
1165 TRACE_(loaddll
)("Unloaded module '%s' : %s\n", wm
->filename
,
1166 wm
->dlhandle
? "builtin" : "native" );
1168 SERVER_START_REQ( unload_dll
)
1170 req
->base
= wm
->ldr
.BaseAddress
;
1171 wine_server_call( req
);
1175 if (wm
->dlhandle
) wine_dll_unload( wm
->dlhandle
);
1176 else NtUnmapViewOfSection( GetCurrentProcess(), wm
->ldr
.BaseAddress
);
1177 FreeLibrary16( wm
->hDummyMod
);
1178 if (cached_modref
== wm
) cached_modref
= NULL
;
1179 RtlFreeHeap( ntdll_get_process_heap(), 0, wm
->deps
);
1180 RtlFreeHeap( ntdll_get_process_heap(), 0, wm
);
1184 /***********************************************************************
1185 * MODULE_DecRefCount
1187 * The loader_section must be locked while calling this function.
1189 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
1193 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
1196 if ( wm
->ldr
.LoadCount
<= 0 )
1199 --wm
->ldr
.LoadCount
;
1200 TRACE("(%s) ldr.LoadCount: %d\n", wm
->modname
, wm
->ldr
.LoadCount
);
1202 if ( wm
->ldr
.LoadCount
== 0 )
1204 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
1206 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1208 MODULE_DecRefCount( wm
->deps
[i
] );
1210 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
1214 /******************************************************************
1215 * LdrUnloadDll (NTDLL.@)
1219 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
1221 NTSTATUS retv
= STATUS_SUCCESS
;
1223 TRACE("(%p)\n", hModule
);
1225 RtlEnterCriticalSection( &loader_section
);
1227 /* if we're stopping the whole process (and forcing the removal of all
1228 * DLLs) the library will be freed anyway
1230 if (!process_detaching
)
1235 if ((wm
= get_modref( hModule
)) != NULL
)
1237 TRACE("(%s) - START\n", wm
->modname
);
1239 /* Recursively decrement reference counts */
1240 MODULE_DecRefCount( wm
);
1242 /* Call process detach notifications */
1243 if ( free_lib_count
<= 1 )
1245 MODULE_DllProcessDetach( FALSE
, NULL
);
1246 MODULE_FlushModrefs();
1252 retv
= STATUS_DLL_NOT_FOUND
;
1257 RtlLeaveCriticalSection( &loader_section
);
1262 /***********************************************************************
1263 * RtlImageNtHeader (NTDLL.@)
1265 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
1267 IMAGE_NT_HEADERS
*ret
;
1271 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
1274 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
1276 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
1277 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
1280 __EXCEPT(page_fault
)
1289 /***********************************************************************
1290 * RtlImageDirectoryEntryToData (NTDLL.@)
1292 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
1294 const IMAGE_NT_HEADERS
*nt
;
1297 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
1299 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
1302 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
1303 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
1304 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
1305 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
1306 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
1308 /* not mapped as image, need to find the section containing the virtual address */
1309 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
1313 /***********************************************************************
1314 * RtlImageRvaToSection (NTDLL.@)
1316 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
1317 HMODULE module
, DWORD rva
)
1320 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char*)&nt
->OptionalHeader
+
1321 nt
->FileHeader
.SizeOfOptionalHeader
);
1322 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
1324 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
1331 /***********************************************************************
1332 * RtlImageRvaToVa (NTDLL.@)
1334 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
1335 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
1337 IMAGE_SECTION_HEADER
*sec
;
1339 if (section
&& *section
) /* try this section first */
1342 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
1345 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
1347 if (section
) *section
= sec
;
1348 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);