2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS NT User Mode Library
4 * FILE: dll/ntdll/ldr/ldrapi.c
5 * PURPOSE: PE Loader Public APIs
6 * PROGRAMMERS: Alex Ionescu (alex@relsoft.net)
7 * Aleksey Bragin (aleksey@reactos.org)
10 /* INCLUDES *****************************************************************/
17 /* GLOBALS *******************************************************************/
19 LIST_ENTRY LdrpUnloadHead
;
20 LONG LdrpLoaderLockAcquisitonCount
;
21 BOOLEAN LdrpShowRecursiveLoads
, LdrpBreakOnRecursiveDllLoads
;
22 UNICODE_STRING LdrApiDefaultExtension
= RTL_CONSTANT_STRING(L
".DLL");
23 ULONG AlternateResourceModuleCount
;
25 /* FUNCTIONS *****************************************************************/
29 LdrFindCreateProcessManifest(IN ULONG Flags
,
32 IN ULONG IdPathLength
,
33 IN PVOID OutDataEntry
)
36 return STATUS_NOT_IMPLEMENTED
;
41 LdrDestroyOutOfProcessImage(IN PVOID Image
)
44 return STATUS_NOT_IMPLEMENTED
;
49 LdrCreateOutOfProcessImage(IN ULONG Flags
,
50 IN HANDLE ProcessHandle
,
55 return STATUS_NOT_IMPLEMENTED
;
60 LdrAccessOutOfProcessResource(IN PVOID Unknown
,
67 return STATUS_NOT_IMPLEMENTED
;
72 LdrSetDllManifestProber(IN PVOID ProberFunction
)
79 LdrAlternateResourcesEnabled(VOID
)
81 /* ReactOS does not support this */
89 /* Generate a cookie */
90 return (((ULONG_PTR
)NtCurrentTeb()->RealClientId
.UniqueThread
& 0xFFF) << 16) |
91 (_InterlockedIncrement(&LdrpLoaderLockAcquisitonCount
) & 0xFFFF);
99 LdrUnlockLoaderLock(IN ULONG Flags
,
100 IN ULONG Cookie OPTIONAL
)
102 NTSTATUS Status
= STATUS_SUCCESS
;
104 DPRINT("LdrUnlockLoaderLock(%x %x)\n", Flags
, Cookie
);
106 /* Check for valid flags */
107 if (Flags
& ~LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
109 /* Flags are invalid, check how to fail */
110 if (Flags
& LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
112 /* The caller wants us to raise status */
113 RtlRaiseStatus(STATUS_INVALID_PARAMETER_1
);
116 /* A normal failure */
117 return STATUS_INVALID_PARAMETER_1
;
120 /* If we don't have a cookie, just return */
121 if (!Cookie
) return STATUS_SUCCESS
;
123 /* Validate the cookie */
124 if ((Cookie
& 0xF0000000) ||
125 ((Cookie
>> 16) ^ ((ULONG
)(NtCurrentTeb()->RealClientId
.UniqueThread
) & 0xFFF)))
127 DPRINT1("LdrUnlockLoaderLock() called with an invalid cookie!\n");
129 /* Invalid cookie, check how to fail */
130 if (Flags
& LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
132 /* The caller wants us to raise status */
133 RtlRaiseStatus(STATUS_INVALID_PARAMETER_2
);
136 /* A normal failure */
137 return STATUS_INVALID_PARAMETER_2
;
140 /* Ready to release the lock */
141 if (Flags
& LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
143 /* Do a direct leave */
144 RtlLeaveCriticalSection(&LdrpLoaderLock
);
148 /* Wrap this in SEH, since we're not supposed to raise */
152 RtlLeaveCriticalSection(&LdrpLoaderLock
);
154 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
156 /* We should use the LDR Filter instead */
157 Status
= _SEH2_GetExceptionCode();
171 LdrLockLoaderLock(IN ULONG Flags
,
172 OUT PULONG Disposition OPTIONAL
,
173 OUT PULONG_PTR Cookie OPTIONAL
)
175 NTSTATUS Status
= STATUS_SUCCESS
;
176 BOOLEAN InInit
= LdrpInLdrInit
;
178 DPRINT("LdrLockLoaderLock(%x %p %p)\n", Flags
, Disposition
, Cookie
);
180 /* Zero out the outputs */
181 if (Disposition
) *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_INVALID
;
182 if (Cookie
) *Cookie
= 0;
184 /* Validate the flags */
185 if (Flags
& ~(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
|
186 LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
))
188 /* Flags are invalid, check how to fail */
189 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
191 /* The caller wants us to raise status */
192 RtlRaiseStatus(STATUS_INVALID_PARAMETER_1
);
195 /* A normal failure */
196 return STATUS_INVALID_PARAMETER_1
;
199 /* Make sure we got a cookie */
202 /* No cookie check how to fail */
203 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
205 /* The caller wants us to raise status */
206 RtlRaiseStatus(STATUS_INVALID_PARAMETER_3
);
209 /* A normal failure */
210 return STATUS_INVALID_PARAMETER_3
;
213 /* If the flag is set, make sure we have a valid pointer to use */
214 if ((Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
) && !(Disposition
))
216 /* No pointer to return the data to */
217 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
219 /* The caller wants us to raise status */
220 RtlRaiseStatus(STATUS_INVALID_PARAMETER_2
);
224 return STATUS_INVALID_PARAMETER_2
;
227 /* Return now if we are in the init phase */
228 if (InInit
) return STATUS_SUCCESS
;
230 /* Check what locking semantic to use */
231 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
233 /* Check if we should enter or simply try */
234 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
)
237 if (!RtlTryEnterCriticalSection(&LdrpLoaderLock
))
240 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED
;
245 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
246 *Cookie
= LdrpMakeCookie();
252 RtlEnterCriticalSection(&LdrpLoaderLock
);
254 /* See if result was requested */
255 if (Disposition
) *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
256 *Cookie
= LdrpMakeCookie();
261 /* Wrap this in SEH, since we're not supposed to raise */
264 /* Check if we should enter or simply try */
265 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
)
268 if (!RtlTryEnterCriticalSection(&LdrpLoaderLock
))
271 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED
;
276 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
277 *Cookie
= LdrpMakeCookie();
283 RtlEnterCriticalSection(&LdrpLoaderLock
);
285 /* See if result was requested */
286 if (Disposition
) *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
287 *Cookie
= LdrpMakeCookie();
290 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
292 /* We should use the LDR Filter instead */
293 Status
= _SEH2_GetExceptionCode();
308 LdrLoadDll(IN PWSTR SearchPath OPTIONAL
,
309 IN PULONG DllCharacteristics OPTIONAL
,
310 IN PUNICODE_STRING DllName
,
311 OUT PVOID
*BaseAddress
)
313 WCHAR StringBuffer
[MAX_PATH
];
314 UNICODE_STRING DllString1
, DllString2
;
315 BOOLEAN RedirectedDll
= FALSE
;
318 PUNICODE_STRING OldTldDll
;
319 PTEB Teb
= NtCurrentTeb();
321 /* Initialize the strings */
322 RtlInitEmptyUnicodeString(&DllString1
, StringBuffer
, sizeof(StringBuffer
));
323 RtlInitEmptyUnicodeString(&DllString2
, NULL
, 0);
325 /* Check if the SxS Assemblies specify another file */
326 Status
= RtlDosApplyFileIsolationRedirection_Ustr(TRUE
,
328 &LdrApiDefaultExtension
,
337 if (NT_SUCCESS(Status
))
340 RedirectedDll
= TRUE
;
342 else if (Status
!= STATUS_SXS_KEY_NOT_FOUND
)
344 /* Unrecoverable SxS failure; did we get a string? */
345 if (DllString2
.Buffer
) RtlFreeUnicodeString(&DllString2
);
349 /* Lock the loader lock */
350 LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, NULL
, &Cookie
);
352 /* Check if there's a TLD DLL being loaded */
353 OldTldDll
= LdrpTopLevelDllBeingLoaded
;
356 /* This is a recursive load, do something about it? */
357 if ((ShowSnaps
) || (LdrpShowRecursiveLoads
) || (LdrpBreakOnRecursiveDllLoads
))
359 /* Print out debug messages */
360 DPRINT1("[%p, %p] LDR: Recursive DLL Load\n",
361 Teb
->RealClientId
.UniqueProcess
,
362 Teb
->RealClientId
.UniqueThread
);
363 DPRINT1("[%p, %p] Previous DLL being loaded \"%wZ\"\n",
364 Teb
->RealClientId
.UniqueProcess
,
365 Teb
->RealClientId
.UniqueThread
,
367 DPRINT1("[%p, %p] DLL being requested \"%wZ\"\n",
368 Teb
->RealClientId
.UniqueProcess
,
369 Teb
->RealClientId
.UniqueThread
,
372 /* Was it initializing too? */
373 if (!LdrpCurrentDllInitializer
)
375 DPRINT1("[%p, %p] LDR: No DLL Initializer was running\n",
376 Teb
->RealClientId
.UniqueProcess
,
377 Teb
->RealClientId
.UniqueThread
);
381 DPRINT1("[%p, %p] DLL whose initializer was currently running \"%wZ\"\n",
382 Teb
->ClientId
.UniqueProcess
,
383 Teb
->ClientId
.UniqueThread
,
384 &LdrpCurrentDllInitializer
->BaseDllName
);
389 /* Set this one as the TLD DLL being loaded*/
390 LdrpTopLevelDllBeingLoaded
= DllName
;
393 Status
= LdrpLoadDll(RedirectedDll
,
399 if (NT_SUCCESS(Status
))
401 Status
= STATUS_SUCCESS
;
403 else if ((Status
!= STATUS_NO_SUCH_FILE
) &&
404 (Status
!= STATUS_DLL_NOT_FOUND
) &&
405 (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
) &&
406 (Status
!= STATUS_DLL_INIT_FAILED
))
408 DbgPrintEx(DPFLTR_LDR_ID
,
409 DPFLTR_WARNING_LEVEL
,
410 "LDR: %s - failing because LdrpLoadDll(%wZ) returned status %x\n",
416 /* Restore the old TLD DLL */
417 LdrpTopLevelDllBeingLoaded
= OldTldDll
;
419 /* Release the lock */
420 LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
422 /* Do we have a redirect string? */
423 if (DllString2
.Buffer
) RtlFreeUnicodeString(&DllString2
);
434 LdrFindEntryForAddress(PVOID Address
,
435 PLDR_DATA_TABLE_ENTRY
*Module
)
437 PLIST_ENTRY ListHead
, NextEntry
;
438 PLDR_DATA_TABLE_ENTRY LdrEntry
;
439 PIMAGE_NT_HEADERS NtHeader
;
440 PPEB_LDR_DATA Ldr
= NtCurrentPeb()->Ldr
;
441 ULONG_PTR DllBase
, DllEnd
;
443 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address
);
446 if (!Ldr
) return STATUS_NO_MORE_ENTRIES
;
448 /* Get the current entry */
449 LdrEntry
= Ldr
->EntryInProgress
;
452 /* Get the NT Headers */
453 NtHeader
= RtlImageNtHeader(LdrEntry
->DllBase
);
456 /* Get the Image Base */
457 DllBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
458 DllEnd
= DllBase
+ NtHeader
->OptionalHeader
.SizeOfImage
;
460 /* Check if they match */
461 if (((ULONG_PTR
)Address
>= DllBase
) &&
462 ((ULONG_PTR
)Address
< DllEnd
))
466 return STATUS_SUCCESS
;
471 /* Loop the module list */
472 ListHead
= &Ldr
->InMemoryOrderModuleList
;
473 NextEntry
= ListHead
->Flink
;
474 while (NextEntry
!= ListHead
)
476 /* Get the entry and NT Headers */
477 LdrEntry
= CONTAINING_RECORD(NextEntry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderModuleList
);
478 NtHeader
= RtlImageNtHeader(LdrEntry
->DllBase
);
481 /* Get the Image Base */
482 DllBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
483 DllEnd
= DllBase
+ NtHeader
->OptionalHeader
.SizeOfImage
;
485 /* Check if they match */
486 if (((ULONG_PTR
)Address
>= DllBase
) &&
487 ((ULONG_PTR
)Address
< DllEnd
))
491 return STATUS_SUCCESS
;
495 NextEntry
= NextEntry
->Flink
;
500 DbgPrintEx(DPFLTR_LDR_ID
,
501 DPFLTR_WARNING_LEVEL
,
502 "LDR: %s() exiting 0x%08lx\n",
504 STATUS_NO_MORE_ENTRIES
);
505 return STATUS_NO_MORE_ENTRIES
;
513 LdrGetDllHandleEx(IN ULONG Flags
,
514 IN PWSTR DllPath OPTIONAL
,
515 IN PULONG DllCharacteristics OPTIONAL
,
516 IN PUNICODE_STRING DllName
,
517 OUT PVOID
*DllHandle OPTIONAL
)
520 PLDR_DATA_TABLE_ENTRY LdrEntry
;
521 UNICODE_STRING RedirectName
, DllString1
, RawDllName
;
522 PUNICODE_STRING pRedirectName
, CompareName
;
524 BOOLEAN Locked
, RedirectedDll
;
526 ULONG LoadFlag
, Length
;
528 /* Initialize the strings */
529 RtlInitEmptyUnicodeString(&DllString1
, NULL
, 0);
530 RtlInitEmptyUnicodeString(&RawDllName
, NULL
, 0);
531 RedirectName
= *DllName
;
532 pRedirectName
= &RedirectName
;
534 /* Initialize state */
535 RedirectedDll
= Locked
= FALSE
;
539 /* Clear the handle */
540 if (DllHandle
) *DllHandle
= NULL
;
542 /* Check for a valid flag combination */
543 if ((Flags
& ~(LDR_GET_DLL_HANDLE_EX_PIN
| LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT
)) ||
544 (!DllHandle
&& !(Flags
& LDR_GET_DLL_HANDLE_EX_PIN
)))
546 DPRINT1("Flags are invalid or no DllHandle given\n");
547 Status
= STATUS_INVALID_PARAMETER
;
551 /* If not initializing */
554 /* Acquire the lock */
555 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
556 if (!NT_SUCCESS(Status
)) goto Quickie
;
558 /* Remember we own it */
562 /* Check if the SxS Assemblies specify another file */
563 Status
= RtlDosApplyFileIsolationRedirection_Ustr(TRUE
,
565 &LdrApiDefaultExtension
,
574 if (NT_SUCCESS(Status
))
577 RedirectedDll
= TRUE
;
579 else if (Status
!= STATUS_SXS_KEY_NOT_FOUND
)
581 /* Unrecoverable SxS failure; */
586 ASSERT(pRedirectName
== &RedirectName
);
589 /* Set default failure code */
590 Status
= STATUS_DLL_NOT_FOUND
;
592 /* Use the cache if we can */
593 if (LdrpGetModuleHandleCache
)
595 /* Check if we were redirected */
599 if (!(LdrpGetModuleHandleCache
->Flags
& LDRP_REDIRECTED
))
604 /* Use the right name */
605 CompareName
= &LdrpGetModuleHandleCache
->FullDllName
;
610 if (LdrpGetModuleHandleCache
->Flags
& LDRP_REDIRECTED
)
615 /* Use the right name */
616 CompareName
= &LdrpGetModuleHandleCache
->BaseDllName
;
619 /* Check if the name matches */
620 if (RtlEqualUnicodeString(pRedirectName
,
625 LdrEntry
= LdrpGetModuleHandleCache
;
628 Status
= STATUS_SUCCESS
;
634 /* Find the name without the extension */
635 p1
= pRedirectName
->Buffer
;
637 p3
= &p1
[pRedirectName
->Length
/ sizeof(WCHAR
)];
644 else if (*p1
== L
'\\')
650 /* Check if no extension was found or if we got a slash */
651 if (!(p2
) || (*p2
== L
'\\') || (*p2
== L
'/'))
653 /* Check that we have space to add one */
654 Length
= pRedirectName
->Length
+
655 LdrApiDefaultExtension
.Length
+ sizeof(UNICODE_NULL
);
656 if (Length
>= UNICODE_STRING_MAX_BYTES
)
658 /* No space to add the extension */
659 Status
= STATUS_NAME_TOO_LONG
;
663 /* Setup the string */
664 RawDllName
.MaximumLength
= Length
;
665 ASSERT(Length
>= sizeof(UNICODE_NULL
));
666 RawDllName
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
668 RawDllName
.MaximumLength
);
669 if (!RawDllName
.Buffer
)
671 Status
= STATUS_NO_MEMORY
;
675 /* Copy the string and add extension */
676 RtlCopyUnicodeString(&RawDllName
, pRedirectName
);
677 RtlAppendUnicodeStringToString(&RawDllName
, &LdrApiDefaultExtension
);
681 /* Check if there's something in the name */
682 Length
= pRedirectName
->Length
;
685 /* Check and remove trailing period */
686 if (pRedirectName
->Buffer
[Length
/ sizeof(WCHAR
) - sizeof(ANSI_NULL
)] == '.')
688 /* Decrease the size */
689 pRedirectName
->Length
-= sizeof(WCHAR
);
693 /* Setup the string */
694 RawDllName
.MaximumLength
= pRedirectName
->Length
+ sizeof(WCHAR
);
695 RawDllName
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
697 RawDllName
.MaximumLength
);
698 if (!RawDllName
.Buffer
)
700 Status
= STATUS_NO_MEMORY
;
704 /* Copy the string */
705 RtlCopyUnicodeString(&RawDllName
, pRedirectName
);
708 /* Display debug string */
711 DPRINT1("LDR: LdrGetDllHandleEx, searching for %wZ from %ws\n",
713 DllPath
? ((ULONG_PTR
)DllPath
== 1 ? L
"" : DllPath
) : L
"");
717 if (LdrpCheckForLoadedDll(DllPath
,
719 ((ULONG_PTR
)DllPath
== 1) ? TRUE
: FALSE
,
723 /* Update cached entry */
724 LdrpGetModuleHandleCache
= LdrEntry
;
727 Status
= STATUS_SUCCESS
;
731 /* Make sure to NULL this */
735 /* The success path must have a valid loader entry */
736 ASSERT((LdrEntry
!= NULL
) == NT_SUCCESS(Status
));
738 /* Check if we got an entry and success */
739 DPRINT("Got LdrEntry->BaseDllName %wZ\n", LdrEntry
? &LdrEntry
->BaseDllName
: NULL
);
740 if ((LdrEntry
) && (NT_SUCCESS(Status
)))
742 /* Check if the DLL is locked */
743 if ((LdrEntry
->LoadCount
!= 0xFFFF) &&
744 !(Flags
& LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT
))
746 /* Check what to do with the load count */
747 if (Flags
& LDR_GET_DLL_HANDLE_EX_PIN
)
750 LdrEntry
->LoadCount
= 0xFFFF;
751 LoadFlag
= LDRP_UPDATE_PIN
;
755 /* Increase the load count */
756 LdrEntry
->LoadCount
++;
757 LoadFlag
= LDRP_UPDATE_REFCOUNT
;
760 /* Update the load count now */
761 LdrpUpdateLoadCount2(LdrEntry
, LoadFlag
);
762 LdrpClearLoadInProgress();
765 /* Check if the caller is requesting the handle */
766 if (DllHandle
) *DllHandle
= LdrEntry
->DllBase
;
769 /* Free string if needed */
770 if (DllString1
.Buffer
) RtlFreeUnicodeString(&DllString1
);
772 /* Free the raw DLL Name if needed */
773 if (RawDllName
.Buffer
)
775 /* Free the heap-allocated buffer */
776 RtlFreeHeap(RtlGetProcessHeap(), 0, RawDllName
.Buffer
);
777 RawDllName
.Buffer
= NULL
;
783 LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
,
796 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL
,
797 IN PULONG DllCharacteristics OPTIONAL
,
798 IN PUNICODE_STRING DllName
,
799 OUT PVOID
*DllHandle
)
801 /* Call the newer API */
802 return LdrGetDllHandleEx(LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT
,
814 LdrGetProcedureAddress(IN PVOID BaseAddress
,
815 IN PANSI_STRING Name
,
817 OUT PVOID
*ProcedureAddress
)
819 /* Call the internal routine and tell it to execute DllInit */
820 return LdrpGetProcedureAddress(BaseAddress
, Name
, Ordinal
, ProcedureAddress
, TRUE
);
828 LdrVerifyImageMatchesChecksum(IN HANDLE FileHandle
,
829 IN PLDR_CALLBACK Callback
,
830 IN PVOID CallbackContext
,
831 OUT PUSHORT ImageCharacteristics
)
833 FILE_STANDARD_INFORMATION FileStandardInfo
;
834 PIMAGE_IMPORT_DESCRIPTOR ImportData
;
835 PIMAGE_SECTION_HEADER LastSection
= NULL
;
836 IO_STATUS_BLOCK IoStatusBlock
;
837 PIMAGE_NT_HEADERS NtHeader
;
838 HANDLE SectionHandle
;
841 BOOLEAN Result
, NoActualCheck
;
845 DPRINT("LdrVerifyImageMatchesChecksum() called\n");
847 /* If the handle has the magic KnownDll flag, skip actual checksums */
848 NoActualCheck
= ((ULONG_PTR
)FileHandle
& 1);
850 /* Create the section */
851 Status
= NtCreateSection(&SectionHandle
,
858 if (!NT_SUCCESS(Status
))
860 DPRINT1 ("NtCreateSection() failed (Status 0x%x)\n", Status
);
864 /* Map the section */
867 Status
= NtMapViewOfSection(SectionHandle
,
877 if (!NT_SUCCESS(Status
))
879 DPRINT1("NtMapViewOfSection() failed (Status 0x%x)\n", Status
);
880 NtClose(SectionHandle
);
884 /* Get the file information */
885 Status
= NtQueryInformationFile(FileHandle
,
888 sizeof(FILE_STANDARD_INFORMATION
),
889 FileStandardInformation
);
890 if (!NT_SUCCESS(Status
))
892 DPRINT1("NtMapViewOfSection() failed (Status 0x%x)\n", Status
);
893 NtUnmapViewOfSection(NtCurrentProcess(), ViewBase
);
894 NtClose(SectionHandle
);
898 /* Protect with SEH */
901 /* Check if this is the KnownDll hack */
904 /* Don't actually do it */
909 /* Verify the checksum */
910 Result
= LdrVerifyMappedImageMatchesChecksum(ViewBase
,
911 FileStandardInfo
.EndOfFile
.LowPart
,
912 FileStandardInfo
.EndOfFile
.LowPart
);
915 /* Check if a callback was supplied */
916 if ((Result
) && (Callback
))
918 /* Get the NT Header */
919 NtHeader
= RtlImageNtHeader(ViewBase
);
921 /* Check if caller requested this back */
922 if (ImageCharacteristics
)
924 /* Return to caller */
925 *ImageCharacteristics
= NtHeader
->FileHeader
.Characteristics
;
928 /* Get the Import Directory Data */
929 ImportData
= RtlImageDirectoryEntryToData(ViewBase
,
931 IMAGE_DIRECTORY_ENTRY_IMPORT
,
934 /* Make sure there is one */
937 /* Loop the imports */
938 while (ImportData
->Name
)
941 ImportName
= RtlImageRvaToVa(NtHeader
,
946 /* Notify the callback */
947 Callback(CallbackContext
, ImportName
);
953 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
955 /* Fail the request returning STATUS_IMAGE_CHECKSUM_MISMATCH */
960 /* Unmap file and close handle */
961 NtUnmapViewOfSection(NtCurrentProcess(), ViewBase
);
962 NtClose(SectionHandle
);
965 return Result
? Status
: STATUS_IMAGE_CHECKSUM_MISMATCH
;
970 LdrQueryProcessModuleInformationEx(IN ULONG ProcessId
,
972 OUT PRTL_PROCESS_MODULES ModuleInformation
,
974 OUT PULONG ReturnedSize OPTIONAL
)
976 PLIST_ENTRY ModuleListHead
, InitListHead
;
977 PLIST_ENTRY Entry
, InitEntry
;
978 PLDR_DATA_TABLE_ENTRY Module
, InitModule
;
979 PRTL_PROCESS_MODULE_INFORMATION ModulePtr
= NULL
;
980 NTSTATUS Status
= STATUS_SUCCESS
;
981 ULONG UsedSize
= sizeof(ULONG
);
982 ANSI_STRING AnsiString
;
985 DPRINT("LdrQueryProcessModuleInformation() called\n");
987 /* Acquire loader lock */
988 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
992 /* Check if we were given enough space */
995 Status
= STATUS_INFO_LENGTH_MISMATCH
;
999 ModuleInformation
->NumberOfModules
= 0;
1000 ModulePtr
= &ModuleInformation
->Modules
[0];
1001 Status
= STATUS_SUCCESS
;
1004 /* Traverse the list of modules */
1005 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1006 Entry
= ModuleListHead
->Flink
;
1008 while (Entry
!= ModuleListHead
)
1010 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1012 DPRINT(" Module %wZ\n", &Module
->FullDllName
);
1014 /* Increase the used size */
1015 UsedSize
+= sizeof(RTL_PROCESS_MODULE_INFORMATION
);
1017 if (UsedSize
> Size
)
1019 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1023 ModulePtr
->ImageBase
= Module
->DllBase
;
1024 ModulePtr
->ImageSize
= Module
->SizeOfImage
;
1025 ModulePtr
->Flags
= Module
->Flags
;
1026 ModulePtr
->LoadCount
= Module
->LoadCount
;
1027 ModulePtr
->MappedBase
= NULL
;
1028 ModulePtr
->InitOrderIndex
= 0;
1029 ModulePtr
->LoadOrderIndex
= ModuleInformation
->NumberOfModules
;
1031 /* Now get init order index by traversing init list */
1032 InitListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
1033 InitEntry
= InitListHead
->Flink
;
1035 while (InitEntry
!= InitListHead
)
1037 InitModule
= CONTAINING_RECORD(InitEntry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
1039 /* Increase the index */
1040 ModulePtr
->InitOrderIndex
++;
1042 /* Quit the loop if our module is found */
1043 if (InitModule
== Module
) break;
1045 /* Advance to the next entry */
1046 InitEntry
= InitEntry
->Flink
;
1049 /* Prepare ANSI string with the module's name */
1050 AnsiString
.Length
= 0;
1051 AnsiString
.MaximumLength
= sizeof(ModulePtr
->FullPathName
);
1052 AnsiString
.Buffer
= ModulePtr
->FullPathName
;
1053 RtlUnicodeStringToAnsiString(&AnsiString
,
1054 &Module
->FullDllName
,
1057 /* Calculate OffsetToFileName field */
1058 p
= strrchr(ModulePtr
->FullPathName
, '\\');
1060 ModulePtr
->OffsetToFileName
= p
- ModulePtr
->FullPathName
+ 1;
1062 ModulePtr
->OffsetToFileName
= 0;
1064 /* Advance to the next module in the output list */
1067 /* Increase number of modules */
1068 if (ModuleInformation
)
1069 ModuleInformation
->NumberOfModules
++;
1072 /* Go to the next entry in the modules list */
1073 Entry
= Entry
->Flink
;
1076 /* Set returned size if it was provided */
1078 *ReturnedSize
= UsedSize
;
1080 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1082 /* Ignoring the exception */
1085 /* Release the lock */
1086 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1088 DPRINT("LdrQueryProcessModuleInformation() done\n");
1098 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation
,
1100 OUT PULONG ReturnedSize OPTIONAL
)
1102 /* Call Ex version of the API */
1103 return LdrQueryProcessModuleInformationEx(0, 0, ModuleInformation
, Size
, ReturnedSize
);
1111 LdrEnumerateLoadedModules(IN BOOLEAN ReservedFlag
,
1112 IN PLDR_ENUM_CALLBACK EnumProc
,
1115 PLIST_ENTRY ListHead
, ListEntry
;
1116 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1119 BOOLEAN Stop
= FALSE
;
1121 /* Check parameters */
1122 if ((ReservedFlag
) || !(EnumProc
)) return STATUS_INVALID_PARAMETER
;
1124 /* Acquire the loader lock */
1125 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
1126 if (!NT_SUCCESS(Status
)) return Status
;
1128 /* Loop all the modules and call enum proc */
1129 ListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1130 ListEntry
= ListHead
->Flink
;
1131 while (ListHead
!= ListEntry
)
1134 LdrEntry
= CONTAINING_RECORD(ListEntry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1136 /* Call the enumeration proc inside SEH */
1139 EnumProc(LdrEntry
, Context
, &Stop
);
1141 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1143 /* Ignoring the exception */
1146 /* Break if we were asked to stop enumeration */
1149 /* Release loader lock */
1150 Status
= LdrUnlockLoaderLock(0, Cookie
);
1152 /* Reset any successful status to STATUS_SUCCESS, but leave
1153 failure to the caller */
1154 if (NT_SUCCESS(Status
))
1155 Status
= STATUS_SUCCESS
;
1157 /* Return any possible failure status */
1161 /* Advance to the next module */
1162 ListEntry
= ListEntry
->Flink
;
1165 /* Release loader lock, it must succeed this time */
1166 Status
= LdrUnlockLoaderLock(0, Cookie
);
1167 ASSERT(NT_SUCCESS(Status
));
1169 /* Return success */
1170 return STATUS_SUCCESS
;
1178 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
1180 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1184 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress
);
1186 /* Don't do it during shutdown */
1187 if (LdrpShutdownInProgress
) return STATUS_SUCCESS
;
1189 /* Check if we should grab the lock */
1194 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
1195 if (!NT_SUCCESS(Status
)) return Status
;
1199 /* Make sure the DLL is valid and get its entry */
1200 Status
= STATUS_DLL_NOT_FOUND
;
1201 if (LdrpCheckForLoadedDllHandle(BaseAddress
, &LdrEntry
))
1203 /* Get if it has a TLS slot */
1204 if (!LdrEntry
->TlsIndex
)
1206 /* It doesn't, so you're allowed to call this */
1207 LdrEntry
->Flags
|= LDRP_DONT_CALL_FOR_THREADS
;
1208 Status
= STATUS_SUCCESS
;
1212 /* Check if the lock was held */
1216 LdrUnlockLoaderLock(LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
1219 /* Return the status */
1228 LdrAddRefDll(IN ULONG Flags
,
1229 IN PVOID BaseAddress
)
1231 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1232 NTSTATUS Status
= STATUS_SUCCESS
;
1234 BOOLEAN Locked
= FALSE
;
1236 /* Check for invalid flags */
1237 if (Flags
& ~(LDR_ADDREF_DLL_PIN
))
1239 /* Fail with invalid parameter status if so */
1240 Status
= STATUS_INVALID_PARAMETER
;
1244 /* Acquire the loader lock if not in init phase */
1247 /* Acquire the lock */
1248 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
1249 if (!NT_SUCCESS(Status
)) goto quickie
;
1253 /* Get this module's data table entry */
1254 if (LdrpCheckForLoadedDllHandle(BaseAddress
, &LdrEntry
))
1258 /* Shouldn't happen */
1259 Status
= STATUS_INTERNAL_ERROR
;
1263 /* If this is not a pinned module */
1264 if (LdrEntry
->LoadCount
!= 0xFFFF)
1266 /* Update its load count */
1267 if (Flags
& LDR_ADDREF_DLL_PIN
)
1269 /* Pin it by setting load count to -1 */
1270 LdrEntry
->LoadCount
= 0xFFFF;
1271 LdrpUpdateLoadCount2(LdrEntry
, LDRP_UPDATE_PIN
);
1275 /* Increase its load count by one */
1276 LdrEntry
->LoadCount
++;
1277 LdrpUpdateLoadCount2(LdrEntry
, LDRP_UPDATE_REFCOUNT
);
1280 /* Clear load in progress */
1281 LdrpClearLoadInProgress();
1286 /* There was an error getting this module's handle, return invalid param status */
1287 Status
= STATUS_INVALID_PARAMETER
;
1291 /* Check for error case */
1292 if (!NT_SUCCESS(Status
))
1294 /* Print debug information */
1295 if ((ShowSnaps
) || ((Status
!= STATUS_NO_SUCH_FILE
) &&
1296 (Status
!= STATUS_DLL_NOT_FOUND
) &&
1297 (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
)))
1299 DPRINT1("LDR: LdrAddRefDll(%p) 0x%08lx\n", BaseAddress
, Status
);
1303 /* Release the lock if needed */
1304 if (Locked
) LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
1313 LdrUnloadDll(IN PVOID BaseAddress
)
1315 NTSTATUS Status
= STATUS_SUCCESS
;
1316 PPEB Peb
= NtCurrentPeb();
1317 PLDR_DATA_TABLE_ENTRY LdrEntry
, CurrentEntry
;
1319 PLIST_ENTRY NextEntry
;
1320 LIST_ENTRY UnloadList
;
1321 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx
;
1323 ULONG ComSectionSize
;
1325 /* Get the LDR Lock */
1326 if (!LdrpInLdrInit
) RtlEnterCriticalSection(Peb
->LoaderLock
);
1328 /* Increase the unload count */
1329 LdrpActiveUnloadCount
++;
1332 if (LdrpShutdownInProgress
) goto Quickie
;
1334 /* Make sure the DLL is valid and get its entry */
1335 if (!LdrpCheckForLoadedDllHandle(BaseAddress
, &LdrEntry
))
1337 Status
= STATUS_DLL_NOT_FOUND
;
1341 /* Check the current Load Count */
1342 if (LdrEntry
->LoadCount
!= 0xFFFF)
1345 LdrEntry
->LoadCount
--;
1348 if (LdrEntry
->Flags
& LDRP_IMAGE_DLL
)
1350 /* Set up the Act Ctx */
1351 ActCtx
.Size
= sizeof(ActCtx
);
1352 ActCtx
.Format
= RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_FORMAT_WHISTLER
;
1353 RtlZeroMemory(&ActCtx
.Frame
, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME
));
1355 /* Activate the ActCtx */
1356 RtlActivateActivationContextUnsafeFast(&ActCtx
,
1357 LdrEntry
->EntryPointActivationContext
);
1359 /* Update the load count */
1360 LdrpUpdateLoadCount2(LdrEntry
, LDRP_UPDATE_DEREFCOUNT
);
1362 /* Release the context */
1363 RtlDeactivateActivationContextUnsafeFast(&ActCtx
);
1368 /* The DLL is locked */
1372 /* Show debug message */
1373 if (ShowSnaps
) DPRINT1("LDR: UNINIT LIST\n");
1375 /* Check if this is our only unload and initialize the list if so */
1376 if (LdrpActiveUnloadCount
== 1) InitializeListHead(&LdrpUnloadHead
);
1378 /* Loop the modules to build the list */
1379 NextEntry
= Peb
->Ldr
->InInitializationOrderModuleList
.Blink
;
1380 while (NextEntry
!= &Peb
->Ldr
->InInitializationOrderModuleList
)
1383 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1384 LDR_DATA_TABLE_ENTRY
,
1385 InInitializationOrderModuleList
);
1386 NextEntry
= NextEntry
->Blink
;
1389 LdrEntry
->Flags
&= ~LDRP_UNLOAD_IN_PROGRESS
;
1391 /* If the load count is now 0 */
1392 if (!LdrEntry
->LoadCount
)
1397 DPRINT1("(%lu) [%ws] %ws (%lx) deinit %p\n",
1398 LdrpActiveUnloadCount
,
1399 LdrEntry
->BaseDllName
.Buffer
,
1400 LdrEntry
->FullDllName
.Buffer
,
1401 (ULONG
)LdrEntry
->LoadCount
,
1402 LdrEntry
->EntryPoint
);
1405 /* FIXME: Call Shim Engine and notify */
1408 CurrentEntry
= LdrEntry
;
1409 RemoveEntryList(&CurrentEntry
->InInitializationOrderModuleList
);
1410 RemoveEntryList(&CurrentEntry
->InMemoryOrderModuleList
);
1411 RemoveEntryList(&CurrentEntry
->HashLinks
);
1413 /* If there's more then one active unload */
1414 if (LdrpActiveUnloadCount
> 1)
1416 /* Flush the cached DLL handle and clear the list */
1417 LdrpLoadedDllHandleCache
= NULL
;
1418 CurrentEntry
->InMemoryOrderModuleList
.Flink
= NULL
;
1421 /* Add the entry on the unload list */
1422 InsertTailList(&LdrpUnloadHead
, &CurrentEntry
->HashLinks
);
1426 /* Only call the entrypoints once */
1427 if (LdrpActiveUnloadCount
> 1) goto Quickie
;
1429 /* Now loop the unload list and create our own */
1430 InitializeListHead(&UnloadList
);
1431 CurrentEntry
= NULL
;
1432 NextEntry
= LdrpUnloadHead
.Flink
;
1433 while (NextEntry
!= &LdrpUnloadHead
)
1435 /* Get the current entry */
1436 LdrEntry
= CONTAINING_RECORD(NextEntry
, LDR_DATA_TABLE_ENTRY
, HashLinks
);
1438 /* FIXME: Log the Unload Event */
1439 //LdrpRecordUnloadEvent(LdrEntry);
1441 /* Set the entry and clear it from the list */
1442 CurrentEntry
= LdrEntry
;
1443 LdrpLoadedDllHandleCache
= NULL
;
1444 CurrentEntry
->InMemoryOrderModuleList
.Flink
= NULL
;
1446 /* Move it from the global to the local list */
1447 RemoveEntryList(&CurrentEntry
->HashLinks
);
1448 InsertTailList(&UnloadList
, &CurrentEntry
->HashLinks
);
1450 /* Get the entrypoint */
1451 EntryPoint
= LdrEntry
->EntryPoint
;
1453 /* Check if we should call it */
1454 if ((EntryPoint
) && (LdrEntry
->Flags
& LDRP_PROCESS_ATTACH_CALLED
))
1459 DPRINT1("LDR: Calling deinit %p\n", EntryPoint
);
1462 /* Set up the Act Ctx */
1463 ActCtx
.Size
= sizeof(ActCtx
);
1464 ActCtx
.Format
= RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_FORMAT_WHISTLER
;
1465 RtlZeroMemory(&ActCtx
.Frame
, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME
));
1467 /* Activate the ActCtx */
1468 RtlActivateActivationContextUnsafeFast(&ActCtx
,
1469 LdrEntry
->EntryPointActivationContext
);
1471 /* Call the entrypoint */
1472 LdrpCallInitRoutine(LdrEntry
->EntryPoint
,
1477 /* Release the context */
1478 RtlDeactivateActivationContextUnsafeFast(&ActCtx
);
1481 /* Remove it from the list */
1482 RemoveEntryList(&CurrentEntry
->InLoadOrderLinks
);
1483 CurrentEntry
= NULL
;
1484 NextEntry
= LdrpUnloadHead
.Flink
;
1487 /* Now loop our local list */
1488 NextEntry
= UnloadList
.Flink
;
1489 while (NextEntry
!= &UnloadList
)
1492 LdrEntry
= CONTAINING_RECORD(NextEntry
, LDR_DATA_TABLE_ENTRY
, HashLinks
);
1493 NextEntry
= NextEntry
->Flink
;
1494 CurrentEntry
= LdrEntry
;
1496 /* Notify Application Verifier */
1497 if (Peb
->NtGlobalFlag
& FLG_HEAP_ENABLE_TAIL_CHECK
)
1499 DPRINT1("We don't support Application Verifier yet\n");
1505 DPRINT1("LDR: Unmapping [%ws]\n", LdrEntry
->BaseDllName
.Buffer
);
1508 /* Check if this is a .NET executable */
1509 CorImageData
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
1511 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
,
1516 DPRINT1(".NET Images are not supported yet\n");
1519 /* Check if we should unmap*/
1520 if (!(CurrentEntry
->Flags
& LDR_COR_OWNS_UNMAP
))
1523 Status
= NtUnmapViewOfSection(NtCurrentProcess(),
1524 CurrentEntry
->DllBase
);
1525 ASSERT(NT_SUCCESS(Status
));
1528 /* Unload the alternate resource module, if any */
1529 LdrUnloadAlternateResourceModule(CurrentEntry
->DllBase
);
1531 /* FIXME: Send shutdown notification */
1532 //LdrpSendDllNotifications(CurrentEntry, 2, LdrpShutdownInProgress);
1534 /* Check if a Hotpatch is active */
1535 if (LdrEntry
->PatchInformation
)
1538 DPRINT1("We don't support Hotpatching yet\n");
1541 /* Deallocate the Entry */
1542 LdrpFinalizeAndDeallocateDataTableEntry(CurrentEntry
);
1544 /* If this is the cached entry, invalidate it */
1545 if (LdrpGetModuleHandleCache
== CurrentEntry
)
1547 LdrpGetModuleHandleCache
= NULL
;
1552 /* Decrease unload count */
1553 LdrpActiveUnloadCount
--;
1554 if (!LdrpInLdrInit
) RtlLeaveCriticalSection(Peb
->LoaderLock
);
1556 /* Return to caller */
1565 RtlDllShutdownInProgress(VOID
)
1567 /* Return the internal global */
1568 return LdrpShutdownInProgress
;
1574 PIMAGE_BASE_RELOCATION
1576 LdrProcessRelocationBlock(IN ULONG_PTR Address
,
1578 IN PUSHORT TypeOffset
,
1581 return LdrProcessRelocationBlockLongLong(Address
, Count
, TypeOffset
, Delta
);
1584 /* FIXME: Add to ntstatus.mc */
1585 #define STATUS_MUI_FILE_NOT_FOUND ((NTSTATUS)0xC00B0001L)
1592 LdrLoadAlternateResourceModule(IN PVOID Module
,
1595 /* Is MUI Support enabled? */
1596 if (!LdrAlternateResourcesEnabled()) return STATUS_SUCCESS
;
1599 return STATUS_MUI_FILE_NOT_FOUND
;
1607 LdrUnloadAlternateResourceModule(IN PVOID BaseAddress
)
1611 /* Acquire the loader lock */
1612 LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, NULL
, &Cookie
);
1614 /* Check if there's any alternate resources loaded */
1615 if (AlternateResourceModuleCount
)
1620 /* Release the loader lock */
1621 LdrUnlockLoaderLock(1, Cookie
);
1632 LdrFlushAlternateResourceModules(VOID
)