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 /* Do or Do Not. There is no Try */
214 ASSERT((Disposition
!= NULL
) || !(Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
));
216 /* If the flag is set, make sure we have a valid pointer to use */
217 if ((Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
) && !(Disposition
))
219 /* No pointer to return the data to */
220 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
222 /* The caller wants us to raise status */
223 RtlRaiseStatus(STATUS_INVALID_PARAMETER_2
);
227 return STATUS_INVALID_PARAMETER_2
;
230 /* Return now if we are in the init phase */
231 if (InInit
) return STATUS_SUCCESS
;
233 /* Check what locking semantic to use */
234 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
)
236 /* Check if we should enter or simply try */
237 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
)
240 if (!RtlTryEnterCriticalSection(&LdrpLoaderLock
))
243 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED
;
248 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
249 *Cookie
= LdrpMakeCookie();
255 RtlEnterCriticalSection(&LdrpLoaderLock
);
257 /* See if result was requested */
258 if (Disposition
) *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
259 *Cookie
= LdrpMakeCookie();
264 /* Wrap this in SEH, since we're not supposed to raise */
267 /* Check if we should enter or simply try */
268 if (Flags
& LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY
)
271 if (!RtlTryEnterCriticalSection(&LdrpLoaderLock
))
274 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED
;
279 *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
280 *Cookie
= LdrpMakeCookie();
286 RtlEnterCriticalSection(&LdrpLoaderLock
);
288 /* See if result was requested */
289 if (Disposition
) *Disposition
= LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED
;
290 *Cookie
= LdrpMakeCookie();
293 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
295 /* We should use the LDR Filter instead */
296 Status
= _SEH2_GetExceptionCode();
310 LdrLoadDll(IN PWSTR SearchPath OPTIONAL
,
311 IN PULONG DllCharacteristics OPTIONAL
,
312 IN PUNICODE_STRING DllName
,
313 OUT PVOID
*BaseAddress
)
315 WCHAR StringBuffer
[MAX_PATH
];
316 UNICODE_STRING DllString1
, DllString2
;
317 BOOLEAN RedirectedDll
= FALSE
;
320 PUNICODE_STRING OldTldDll
;
321 PTEB Teb
= NtCurrentTeb();
323 /* Initialize the strings */
324 RtlInitEmptyUnicodeString(&DllString2
, NULL
, 0);
325 DllString1
.Buffer
= StringBuffer
;
326 DllString1
.Length
= 0;
327 DllString1
.MaximumLength
= sizeof(StringBuffer
);
329 /* Check if the SxS Assemblies specify another file */
330 Status
= RtlDosApplyFileIsolationRedirection_Ustr(TRUE
,
332 &LdrApiDefaultExtension
,
341 if (NT_SUCCESS(Status
))
344 RedirectedDll
= TRUE
;
346 else if (Status
!= STATUS_SXS_KEY_NOT_FOUND
)
348 /* Unrecoverable SxS failure; did we get a string? */
349 if (DllString2
.Buffer
) RtlFreeUnicodeString(&DllString2
);
353 /* Lock the loader lock */
354 LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, NULL
, &Cookie
);
356 /* Check if there's a TLD DLL being loaded */
357 OldTldDll
= LdrpTopLevelDllBeingLoaded
;
360 /* This is a recursive load, do something about it? */
361 if ((ShowSnaps
) || (LdrpShowRecursiveLoads
) || (LdrpBreakOnRecursiveDllLoads
))
363 /* Print out debug messages */
364 DPRINT1("[%p, %p] LDR: Recursive DLL Load\n",
365 Teb
->RealClientId
.UniqueProcess
,
366 Teb
->RealClientId
.UniqueThread
);
367 DPRINT1("[%p, %p] Previous DLL being loaded \"%wZ\"\n",
368 Teb
->RealClientId
.UniqueProcess
,
369 Teb
->RealClientId
.UniqueThread
,
371 DPRINT1("[%p, %p] DLL being requested \"%wZ\"\n",
372 Teb
->RealClientId
.UniqueProcess
,
373 Teb
->RealClientId
.UniqueThread
,
376 /* Was it initializing too? */
377 if (!LdrpCurrentDllInitializer
)
379 DPRINT1("[%p, %p] LDR: No DLL Initializer was running\n",
380 Teb
->RealClientId
.UniqueProcess
,
381 Teb
->RealClientId
.UniqueThread
);
385 DPRINT1("[%p, %p] DLL whose initializer was currently running \"%wZ\"\n",
386 Teb
->ClientId
.UniqueProcess
,
387 Teb
->ClientId
.UniqueThread
,
388 &LdrpCurrentDllInitializer
->BaseDllName
);
393 /* Set this one as the TLD DLL being loaded*/
394 LdrpTopLevelDllBeingLoaded
= DllName
;
397 Status
= LdrpLoadDll(RedirectedDll
,
403 if (NT_SUCCESS(Status
))
405 Status
= STATUS_SUCCESS
;
407 else if ((Status
!= STATUS_NO_SUCH_FILE
) &&
408 (Status
!= STATUS_DLL_NOT_FOUND
) &&
409 (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
) &&
410 (Status
!= STATUS_DLL_INIT_FAILED
))
412 // 85 == DPFLTR_LDR_ID;
414 DPFLTR_WARNING_LEVEL
,
415 "LDR: %s - failing because LdrpLoadDll(%wZ) returned status %x\n",
421 /* Restore the old TLD DLL */
422 LdrpTopLevelDllBeingLoaded
= OldTldDll
;
424 /* Release the lock */
425 LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
427 /* Do we have a redirect string? */
428 if (DllString2
.Buffer
) RtlFreeUnicodeString(&DllString2
);
439 LdrFindEntryForAddress(PVOID Address
,
440 PLDR_DATA_TABLE_ENTRY
*Module
)
442 PLIST_ENTRY ListHead
, NextEntry
;
443 PLDR_DATA_TABLE_ENTRY LdrEntry
;
444 PIMAGE_NT_HEADERS NtHeader
;
445 PPEB_LDR_DATA Ldr
= NtCurrentPeb()->Ldr
;
446 ULONG_PTR DllBase
, DllEnd
;
448 DPRINT("LdrFindEntryForAddress(Address %p)\n", Address
);
451 if (!Ldr
) return STATUS_NO_MORE_ENTRIES
;
453 /* Get the current entry */
454 LdrEntry
= Ldr
->EntryInProgress
;
457 /* Get the NT Headers */
458 NtHeader
= RtlImageNtHeader(LdrEntry
->DllBase
);
461 /* Get the Image Base */
462 DllBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
463 DllEnd
= DllBase
+ NtHeader
->OptionalHeader
.SizeOfImage
;
465 /* Check if they match */
466 if (((ULONG_PTR
)Address
>= DllBase
) &&
467 ((ULONG_PTR
)Address
< DllEnd
))
471 return STATUS_SUCCESS
;
476 /* Loop the module list */
477 ListHead
= &Ldr
->InMemoryOrderModuleList
;
478 NextEntry
= ListHead
->Flink
;
479 while (NextEntry
!= ListHead
)
481 /* Get the entry and NT Headers */
482 LdrEntry
= CONTAINING_RECORD(NextEntry
, LDR_DATA_TABLE_ENTRY
, InMemoryOrderModuleList
);
483 NtHeader
= RtlImageNtHeader(LdrEntry
->DllBase
);
486 /* Get the Image Base */
487 DllBase
= (ULONG_PTR
)LdrEntry
->DllBase
;
488 DllEnd
= DllBase
+ NtHeader
->OptionalHeader
.SizeOfImage
;
490 /* Check if they match */
491 if (((ULONG_PTR
)Address
>= DllBase
) &&
492 ((ULONG_PTR
)Address
< DllEnd
))
496 return STATUS_SUCCESS
;
500 NextEntry
= NextEntry
->Flink
;
505 // 85 == DPFLTR_LDR_ID;
506 DbgPrintEx(85, DPFLTR_WARNING_LEVEL
, "LDR: %s() exiting 0x%08lx\n", __FUNCTION__
, STATUS_NO_MORE_ENTRIES
);
507 return STATUS_NO_MORE_ENTRIES
;
515 LdrGetDllHandleEx(IN ULONG Flags
,
516 IN PWSTR DllPath OPTIONAL
,
517 IN PULONG DllCharacteristics OPTIONAL
,
518 IN PUNICODE_STRING DllName
,
519 OUT PVOID
*DllHandle OPTIONAL
)
522 PLDR_DATA_TABLE_ENTRY LdrEntry
;
523 UNICODE_STRING RedirectName
, DllString1
, RawDllName
;
524 PUNICODE_STRING pRedirectName
, CompareName
;
526 BOOLEAN Locked
, RedirectedDll
;
528 ULONG LoadFlag
, Length
;
530 /* Initialize the strings */
531 RtlInitEmptyUnicodeString(&DllString1
, NULL
, 0);
532 RtlInitEmptyUnicodeString(&RawDllName
, NULL
, 0);
533 RedirectName
= *DllName
;
534 pRedirectName
= &RedirectName
;
536 /* Initialize state */
537 RedirectedDll
= Locked
= FALSE
;
541 /* Clear the handle */
542 if (DllHandle
) *DllHandle
= NULL
;
544 /* Check for a valid flag combination */
545 if ((Flags
& ~(LDR_GET_DLL_HANDLE_EX_PIN
| LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT
)) ||
546 (!DllHandle
&& !(Flags
& LDR_GET_DLL_HANDLE_EX_PIN
)))
548 DPRINT1("Flags are invalid or no DllHandle given\n");
549 Status
= STATUS_INVALID_PARAMETER
;
553 /* If not initializing */
556 /* Acquire the lock */
557 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
558 if (!NT_SUCCESS(Status
)) goto Quickie
;
560 /* Remember we own it */
564 /* Check if the SxS Assemblies specify another file */
565 Status
= RtlDosApplyFileIsolationRedirection_Ustr(TRUE
,
567 &LdrApiDefaultExtension
,
576 if (NT_SUCCESS(Status
))
579 RedirectedDll
= TRUE
;
581 else if (Status
!= STATUS_SXS_KEY_NOT_FOUND
)
583 /* Unrecoverable SxS failure; */
588 ASSERT(pRedirectName
== &RedirectName
);
591 /* Set default failure code */
592 Status
= STATUS_DLL_NOT_FOUND
;
594 /* Use the cache if we can */
595 if (LdrpGetModuleHandleCache
)
597 /* Check if we were redirected */
601 if (!(LdrpGetModuleHandleCache
->Flags
& LDRP_REDIRECTED
))
606 /* Use the right name */
607 CompareName
= &LdrpGetModuleHandleCache
->FullDllName
;
612 if (LdrpGetModuleHandleCache
->Flags
& LDRP_REDIRECTED
)
617 /* Use the right name */
618 CompareName
= &LdrpGetModuleHandleCache
->BaseDllName
;
621 /* Check if the name matches */
622 if (RtlEqualUnicodeString(pRedirectName
,
627 LdrEntry
= LdrpGetModuleHandleCache
;
630 Status
= STATUS_SUCCESS
;
636 /* Find the name without the extension */
637 p1
= pRedirectName
->Buffer
;
639 p3
= &p1
[pRedirectName
->Length
/ sizeof(WCHAR
)];
646 else if (*p1
== L
'\\')
652 /* Check if no extension was found or if we got a slash */
653 if (!(p2
) || (*p2
== L
'\\') || (*p2
== L
'/'))
655 /* Check that we have space to add one */
656 Length
= pRedirectName
->Length
+
657 LdrApiDefaultExtension
.Length
+ sizeof(UNICODE_NULL
);
658 if (Length
>= UNICODE_STRING_MAX_BYTES
)
660 /* No space to add the extension */
661 Status
= STATUS_NAME_TOO_LONG
;
665 /* Setup the string */
666 RawDllName
.MaximumLength
= Length
;
667 ASSERT(Length
>= sizeof(UNICODE_NULL
));
668 RawDllName
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
670 RawDllName
.MaximumLength
);
671 if (!RawDllName
.Buffer
)
673 Status
= STATUS_NO_MEMORY
;
677 /* Copy the string and add extension */
678 RtlCopyUnicodeString(&RawDllName
, pRedirectName
);
679 RtlAppendUnicodeStringToString(&RawDllName
, &LdrApiDefaultExtension
);
683 /* Check if there's something in the name */
684 Length
= pRedirectName
->Length
;
687 /* Check and remove trailing period */
688 if (pRedirectName
->Buffer
[Length
/ sizeof(WCHAR
) - sizeof(ANSI_NULL
)] == '.')
690 /* Decrease the size */
691 pRedirectName
->Length
-= sizeof(WCHAR
);
695 /* Setup the string */
696 RawDllName
.MaximumLength
= pRedirectName
->Length
+ sizeof(WCHAR
);
697 RawDllName
.Buffer
= RtlAllocateHeap(RtlGetProcessHeap(),
699 RawDllName
.MaximumLength
);
700 if (!RawDllName
.Buffer
)
702 Status
= STATUS_NO_MEMORY
;
706 /* Copy the string */
707 RtlCopyUnicodeString(&RawDllName
, pRedirectName
);
710 /* Display debug string */
713 DPRINT1("LDR: LdrGetDllHandleEx, searching for %wZ from %ws\n",
715 DllPath
? ((ULONG_PTR
)DllPath
== 1 ? L
"" : DllPath
) : L
"");
719 if (LdrpCheckForLoadedDll(DllPath
,
721 ((ULONG_PTR
)DllPath
== 1) ? TRUE
: FALSE
,
725 /* Update cached entry */
726 LdrpGetModuleHandleCache
= LdrEntry
;
729 Status
= STATUS_SUCCESS
;
733 /* Make sure to NULL this */
737 /* The success path must have a valid loader entry */
738 ASSERT((LdrEntry
!= NULL
) == NT_SUCCESS(Status
));
740 /* Check if we got an entry and success */
741 DPRINT("Got LdrEntry->BaseDllName %wZ\n", LdrEntry
? &LdrEntry
->BaseDllName
: NULL
);
742 if ((LdrEntry
) && (NT_SUCCESS(Status
)))
744 /* Check if the DLL is locked */
745 if ((LdrEntry
->LoadCount
!= 0xFFFF) &&
746 !(Flags
& LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT
))
748 /* Check what to do with the load count */
749 if (Flags
& LDR_GET_DLL_HANDLE_EX_PIN
)
752 LdrEntry
->LoadCount
= 0xFFFF;
753 LoadFlag
= LDRP_UPDATE_PIN
;
757 /* Increase the load count */
758 LdrEntry
->LoadCount
++;
759 LoadFlag
= LDRP_UPDATE_REFCOUNT
;
762 /* Update the load count now */
763 LdrpUpdateLoadCount2(LdrEntry
, LoadFlag
);
764 LdrpClearLoadInProgress();
767 /* Check if the caller is requesting the handle */
768 if (DllHandle
) *DllHandle
= LdrEntry
->DllBase
;
771 /* Free string if needed */
772 if (DllString1
.Buffer
) RtlFreeUnicodeString(&DllString1
);
774 /* Free the raw DLL Name if needed */
775 if (RawDllName
.Buffer
)
777 /* Free the heap-allocated buffer */
778 RtlFreeHeap(RtlGetProcessHeap(), 0, RawDllName
.Buffer
);
779 RawDllName
.Buffer
= NULL
;
785 LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
,
798 LdrGetDllHandle(IN PWSTR DllPath OPTIONAL
,
799 IN PULONG DllCharacteristics OPTIONAL
,
800 IN PUNICODE_STRING DllName
,
801 OUT PVOID
*DllHandle
)
803 /* Call the newer API */
804 return LdrGetDllHandleEx(LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT
,
816 LdrGetProcedureAddress(IN PVOID BaseAddress
,
817 IN PANSI_STRING Name
,
819 OUT PVOID
*ProcedureAddress
)
821 /* Call the internal routine and tell it to execute DllInit */
822 return LdrpGetProcedureAddress(BaseAddress
, Name
, Ordinal
, ProcedureAddress
, TRUE
);
830 LdrVerifyImageMatchesChecksum(IN HANDLE FileHandle
,
831 IN PLDR_CALLBACK Callback
,
832 IN PVOID CallbackContext
,
833 OUT PUSHORT ImageCharacteristics
)
835 FILE_STANDARD_INFORMATION FileStandardInfo
;
836 PIMAGE_IMPORT_DESCRIPTOR ImportData
;
837 PIMAGE_SECTION_HEADER LastSection
= NULL
;
838 IO_STATUS_BLOCK IoStatusBlock
;
839 PIMAGE_NT_HEADERS NtHeader
;
840 HANDLE SectionHandle
;
843 BOOLEAN Result
, NoActualCheck
;
847 DPRINT("LdrVerifyImageMatchesChecksum() called\n");
849 /* If the handle has the magic KnownDll flag, skip actual checksums */
850 NoActualCheck
= ((ULONG_PTR
)FileHandle
& 1);
852 /* Create the section */
853 Status
= NtCreateSection(&SectionHandle
,
860 if (!NT_SUCCESS(Status
))
862 DPRINT1 ("NtCreateSection() failed (Status 0x%x)\n", Status
);
866 /* Map the section */
869 Status
= NtMapViewOfSection(SectionHandle
,
879 if (!NT_SUCCESS(Status
))
881 DPRINT1("NtMapViewOfSection() failed (Status 0x%x)\n", Status
);
882 NtClose(SectionHandle
);
886 /* Get the file information */
887 Status
= NtQueryInformationFile(FileHandle
,
890 sizeof(FILE_STANDARD_INFORMATION
),
891 FileStandardInformation
);
892 if (!NT_SUCCESS(Status
))
894 DPRINT1("NtMapViewOfSection() failed (Status 0x%x)\n", Status
);
895 NtUnmapViewOfSection(NtCurrentProcess(), ViewBase
);
896 NtClose(SectionHandle
);
900 /* Protect with SEH */
903 /* Check if this is the KnownDll hack */
906 /* Don't actually do it */
911 /* Verify the checksum */
912 Result
= LdrVerifyMappedImageMatchesChecksum(ViewBase
,
913 FileStandardInfo
.EndOfFile
.LowPart
,
914 FileStandardInfo
.EndOfFile
.LowPart
);
917 /* Check if a callback was supplied */
918 if ((Result
) && (Callback
))
920 /* Get the NT Header */
921 NtHeader
= RtlImageNtHeader(ViewBase
);
923 /* Check if caller requested this back */
924 if (ImageCharacteristics
)
926 /* Return to caller */
927 *ImageCharacteristics
= NtHeader
->FileHeader
.Characteristics
;
930 /* Get the Import Directory Data */
931 ImportData
= RtlImageDirectoryEntryToData(ViewBase
,
933 IMAGE_DIRECTORY_ENTRY_IMPORT
,
936 /* Make sure there is one */
939 /* Loop the imports */
940 while (ImportData
->Name
)
943 ImportName
= RtlImageRvaToVa(NtHeader
,
948 /* Notify the callback */
949 Callback(CallbackContext
, ImportName
);
955 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
957 /* Fail the request returning STATUS_IMAGE_CHECKSUM_MISMATCH */
962 /* Unmap file and close handle */
963 NtUnmapViewOfSection(NtCurrentProcess(), ViewBase
);
964 NtClose(SectionHandle
);
967 return Result
? Status
: STATUS_IMAGE_CHECKSUM_MISMATCH
;
972 LdrQueryProcessModuleInformationEx(IN ULONG ProcessId
,
974 OUT PRTL_PROCESS_MODULES ModuleInformation
,
976 OUT PULONG ReturnedSize OPTIONAL
)
978 PLIST_ENTRY ModuleListHead
, InitListHead
;
979 PLIST_ENTRY Entry
, InitEntry
;
980 PLDR_DATA_TABLE_ENTRY Module
, InitModule
;
981 PRTL_PROCESS_MODULE_INFORMATION ModulePtr
= NULL
;
982 NTSTATUS Status
= STATUS_SUCCESS
;
983 ULONG UsedSize
= sizeof(ULONG
);
984 ANSI_STRING AnsiString
;
987 DPRINT("LdrQueryProcessModuleInformation() called\n");
989 /* Acquire loader lock */
990 RtlEnterCriticalSection(NtCurrentPeb()->LoaderLock
);
994 /* Check if we were given enough space */
997 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1001 ModuleInformation
->NumberOfModules
= 0;
1002 ModulePtr
= &ModuleInformation
->Modules
[0];
1003 Status
= STATUS_SUCCESS
;
1006 /* Traverse the list of modules */
1007 ModuleListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1008 Entry
= ModuleListHead
->Flink
;
1010 while (Entry
!= ModuleListHead
)
1012 Module
= CONTAINING_RECORD(Entry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1014 DPRINT(" Module %wZ\n", &Module
->FullDllName
);
1016 /* Increase the used size */
1017 UsedSize
+= sizeof(RTL_PROCESS_MODULE_INFORMATION
);
1019 if (UsedSize
> Size
)
1021 Status
= STATUS_INFO_LENGTH_MISMATCH
;
1025 ModulePtr
->ImageBase
= Module
->DllBase
;
1026 ModulePtr
->ImageSize
= Module
->SizeOfImage
;
1027 ModulePtr
->Flags
= Module
->Flags
;
1028 ModulePtr
->LoadCount
= Module
->LoadCount
;
1029 ModulePtr
->MappedBase
= NULL
;
1030 ModulePtr
->InitOrderIndex
= 0;
1031 ModulePtr
->LoadOrderIndex
= ModuleInformation
->NumberOfModules
;
1033 /* Now get init order index by traversing init list */
1034 InitListHead
= &NtCurrentPeb()->Ldr
->InInitializationOrderModuleList
;
1035 InitEntry
= InitListHead
->Flink
;
1037 while (InitEntry
!= InitListHead
)
1039 InitModule
= CONTAINING_RECORD(InitEntry
, LDR_DATA_TABLE_ENTRY
, InInitializationOrderModuleList
);
1041 /* Increase the index */
1042 ModulePtr
->InitOrderIndex
++;
1044 /* Quit the loop if our module is found */
1045 if (InitModule
== Module
) break;
1047 /* Advance to the next entry */
1048 InitEntry
= InitEntry
->Flink
;
1051 /* Prepare ANSI string with the module's name */
1052 AnsiString
.Length
= 0;
1053 AnsiString
.MaximumLength
= sizeof(ModulePtr
->FullPathName
);
1054 AnsiString
.Buffer
= ModulePtr
->FullPathName
;
1055 RtlUnicodeStringToAnsiString(&AnsiString
,
1056 &Module
->FullDllName
,
1059 /* Calculate OffsetToFileName field */
1060 p
= strrchr(ModulePtr
->FullPathName
, '\\');
1062 ModulePtr
->OffsetToFileName
= p
- ModulePtr
->FullPathName
+ 1;
1064 ModulePtr
->OffsetToFileName
= 0;
1066 /* Advance to the next module in the output list */
1069 /* Increase number of modules */
1070 if (ModuleInformation
)
1071 ModuleInformation
->NumberOfModules
++;
1074 /* Go to the next entry in the modules list */
1075 Entry
= Entry
->Flink
;
1078 /* Set returned size if it was provided */
1080 *ReturnedSize
= UsedSize
;
1082 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1084 /* Ignoring the exception */
1087 /* Release the lock */
1088 RtlLeaveCriticalSection(NtCurrentPeb()->LoaderLock
);
1090 DPRINT("LdrQueryProcessModuleInformation() done\n");
1100 LdrQueryProcessModuleInformation(IN PRTL_PROCESS_MODULES ModuleInformation
,
1102 OUT PULONG ReturnedSize OPTIONAL
)
1104 /* Call Ex version of the API */
1105 return LdrQueryProcessModuleInformationEx(0, 0, ModuleInformation
, Size
, ReturnedSize
);
1113 LdrEnumerateLoadedModules(IN BOOLEAN ReservedFlag
,
1114 IN PLDR_ENUM_CALLBACK EnumProc
,
1117 PLIST_ENTRY ListHead
, ListEntry
;
1118 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1121 BOOLEAN Stop
= FALSE
;
1123 /* Check parameters */
1124 if ((ReservedFlag
) || !(EnumProc
)) return STATUS_INVALID_PARAMETER
;
1126 /* Acquire the loader lock */
1127 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
1128 if (!NT_SUCCESS(Status
)) return Status
;
1130 /* Loop all the modules and call enum proc */
1131 ListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
1132 ListEntry
= ListHead
->Flink
;
1133 while (ListHead
!= ListEntry
)
1136 LdrEntry
= CONTAINING_RECORD(ListEntry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
1138 /* Call the enumeration proc inside SEH */
1141 EnumProc(LdrEntry
, Context
, &Stop
);
1143 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1145 /* Ignoring the exception */
1148 /* Break if we were asked to stop enumeration */
1151 /* Release loader lock */
1152 Status
= LdrUnlockLoaderLock(0, Cookie
);
1154 /* Reset any successful status to STATUS_SUCCESS, but leave
1155 failure to the caller */
1156 if (NT_SUCCESS(Status
))
1157 Status
= STATUS_SUCCESS
;
1159 /* Return any possible failure status */
1163 /* Advance to the next module */
1164 ListEntry
= ListEntry
->Flink
;
1167 /* Release loader lock, it must succeed this time */
1168 Status
= LdrUnlockLoaderLock(0, Cookie
);
1169 ASSERT(NT_SUCCESS(Status
));
1171 /* Return success */
1172 return STATUS_SUCCESS
;
1180 LdrDisableThreadCalloutsForDll(IN PVOID BaseAddress
)
1182 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1186 DPRINT("LdrDisableThreadCalloutsForDll (BaseAddress %p)\n", BaseAddress
);
1188 /* Don't do it during shutdown */
1189 if (LdrpShutdownInProgress
) return STATUS_SUCCESS
;
1191 /* Check if we should grab the lock */
1196 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
1197 if (!NT_SUCCESS(Status
)) return Status
;
1201 /* Make sure the DLL is valid and get its entry */
1202 Status
= STATUS_DLL_NOT_FOUND
;
1203 if (LdrpCheckForLoadedDllHandle(BaseAddress
, &LdrEntry
))
1205 /* Get if it has a TLS slot */
1206 if (!LdrEntry
->TlsIndex
)
1208 /* It doesn't, so you're allowed to call this */
1209 LdrEntry
->Flags
|= LDRP_DONT_CALL_FOR_THREADS
;
1210 Status
= STATUS_SUCCESS
;
1214 /* Check if the lock was held */
1218 LdrUnlockLoaderLock(LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
1221 /* Return the status */
1230 LdrAddRefDll(IN ULONG Flags
,
1231 IN PVOID BaseAddress
)
1233 PLDR_DATA_TABLE_ENTRY LdrEntry
;
1234 NTSTATUS Status
= STATUS_SUCCESS
;
1236 BOOLEAN Locked
= FALSE
;
1238 /* Check for invalid flags */
1239 if (Flags
& ~(LDR_ADDREF_DLL_PIN
))
1241 /* Fail with invalid parameter status if so */
1242 Status
= STATUS_INVALID_PARAMETER
;
1246 /* Acquire the loader lock if not in init phase */
1249 /* Acquire the lock */
1250 Status
= LdrLockLoaderLock(0, NULL
, &Cookie
);
1251 if (!NT_SUCCESS(Status
)) goto quickie
;
1255 /* Get this module's data table entry */
1256 if (LdrpCheckForLoadedDllHandle(BaseAddress
, &LdrEntry
))
1260 /* Shouldn't happen */
1261 Status
= STATUS_INTERNAL_ERROR
;
1265 /* If this is not a pinned module */
1266 if (LdrEntry
->LoadCount
!= 0xFFFF)
1268 /* Update its load count */
1269 if (Flags
& LDR_ADDREF_DLL_PIN
)
1271 /* Pin it by setting load count to -1 */
1272 LdrEntry
->LoadCount
= 0xFFFF;
1273 LdrpUpdateLoadCount2(LdrEntry
, LDRP_UPDATE_PIN
);
1277 /* Increase its load count by one */
1278 LdrEntry
->LoadCount
++;
1279 LdrpUpdateLoadCount2(LdrEntry
, LDRP_UPDATE_REFCOUNT
);
1282 /* Clear load in progress */
1283 LdrpClearLoadInProgress();
1288 /* There was an error getting this module's handle, return invalid param status */
1289 Status
= STATUS_INVALID_PARAMETER
;
1293 /* Check for error case */
1294 if (!NT_SUCCESS(Status
))
1296 /* Print debug information */
1297 if ((ShowSnaps
) || ((Status
!= STATUS_NO_SUCH_FILE
) &&
1298 (Status
!= STATUS_DLL_NOT_FOUND
) &&
1299 (Status
!= STATUS_OBJECT_NAME_NOT_FOUND
)))
1301 DPRINT1("LDR: LdrAddRefDll(%p) 0x%08lx\n", BaseAddress
, Status
);
1305 /* Release the lock if needed */
1306 if (Locked
) LdrUnlockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, Cookie
);
1315 LdrUnloadDll(IN PVOID BaseAddress
)
1317 NTSTATUS Status
= STATUS_SUCCESS
;
1318 PPEB Peb
= NtCurrentPeb();
1319 PLDR_DATA_TABLE_ENTRY LdrEntry
, CurrentEntry
;
1321 PLIST_ENTRY NextEntry
;
1322 LIST_ENTRY UnloadList
;
1323 RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_EXTENDED ActCtx
;
1325 ULONG ComSectionSize
;
1327 /* Get the LDR Lock */
1328 if (!LdrpInLdrInit
) RtlEnterCriticalSection(Peb
->LoaderLock
);
1330 /* Increase the unload count */
1331 LdrpActiveUnloadCount
++;
1334 if (LdrpShutdownInProgress
) goto Quickie
;
1336 /* Make sure the DLL is valid and get its entry */
1337 if (!LdrpCheckForLoadedDllHandle(BaseAddress
, &LdrEntry
))
1339 Status
= STATUS_DLL_NOT_FOUND
;
1343 /* Check the current Load Count */
1344 if (LdrEntry
->LoadCount
!= 0xFFFF)
1347 LdrEntry
->LoadCount
--;
1350 if (LdrEntry
->Flags
& LDRP_IMAGE_DLL
)
1352 /* Set up the Act Ctx */
1353 ActCtx
.Size
= sizeof(ActCtx
);
1354 ActCtx
.Format
= RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_FORMAT_WHISTLER
;
1355 RtlZeroMemory(&ActCtx
.Frame
, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME
));
1357 /* Activate the ActCtx */
1358 RtlActivateActivationContextUnsafeFast(&ActCtx
,
1359 LdrEntry
->EntryPointActivationContext
);
1361 /* Update the load count */
1362 LdrpUpdateLoadCount2(LdrEntry
, LDRP_UPDATE_DEREFCOUNT
);
1364 /* Release the context */
1365 RtlDeactivateActivationContextUnsafeFast(&ActCtx
);
1370 /* The DLL is locked */
1374 /* Show debug message */
1375 if (ShowSnaps
) DPRINT1("LDR: UNINIT LIST\n");
1377 /* Check if this is our only unload and initialize the list if so */
1378 if (LdrpActiveUnloadCount
== 1) InitializeListHead(&LdrpUnloadHead
);
1380 /* Loop the modules to build the list */
1381 NextEntry
= Peb
->Ldr
->InInitializationOrderModuleList
.Blink
;
1382 while (NextEntry
!= &Peb
->Ldr
->InInitializationOrderModuleList
)
1385 LdrEntry
= CONTAINING_RECORD(NextEntry
,
1386 LDR_DATA_TABLE_ENTRY
,
1387 InInitializationOrderModuleList
);
1388 NextEntry
= NextEntry
->Blink
;
1391 LdrEntry
->Flags
&= ~LDRP_UNLOAD_IN_PROGRESS
;
1393 /* If the load count is now 0 */
1394 if (!LdrEntry
->LoadCount
)
1399 DPRINT1("(%lu) [%ws] %ws (%lx) deinit %p\n",
1400 LdrpActiveUnloadCount
,
1401 LdrEntry
->BaseDllName
.Buffer
,
1402 LdrEntry
->FullDllName
.Buffer
,
1403 (ULONG
)LdrEntry
->LoadCount
,
1404 LdrEntry
->EntryPoint
);
1407 /* FIXME: Call Shim Engine and notify */
1410 CurrentEntry
= LdrEntry
;
1411 RemoveEntryList(&CurrentEntry
->InInitializationOrderModuleList
);
1412 RemoveEntryList(&CurrentEntry
->InMemoryOrderModuleList
);
1413 RemoveEntryList(&CurrentEntry
->HashLinks
);
1415 /* If there's more then one active unload */
1416 if (LdrpActiveUnloadCount
> 1)
1418 /* Flush the cached DLL handle and clear the list */
1419 LdrpLoadedDllHandleCache
= NULL
;
1420 CurrentEntry
->InMemoryOrderModuleList
.Flink
= NULL
;
1423 /* Add the entry on the unload list */
1424 InsertTailList(&LdrpUnloadHead
, &CurrentEntry
->HashLinks
);
1428 /* Only call the entrypoints once */
1429 if (LdrpActiveUnloadCount
> 1) goto Quickie
;
1431 /* Now loop the unload list and create our own */
1432 InitializeListHead(&UnloadList
);
1433 CurrentEntry
= NULL
;
1434 NextEntry
= LdrpUnloadHead
.Flink
;
1435 while (NextEntry
!= &LdrpUnloadHead
)
1437 /* Get the current entry */
1438 LdrEntry
= CONTAINING_RECORD(NextEntry
, LDR_DATA_TABLE_ENTRY
, HashLinks
);
1440 /* FIXME: Log the Unload Event */
1441 //LdrpRecordUnloadEvent(LdrEntry);
1443 /* Set the entry and clear it from the list */
1444 CurrentEntry
= LdrEntry
;
1445 LdrpLoadedDllHandleCache
= NULL
;
1446 CurrentEntry
->InMemoryOrderModuleList
.Flink
= NULL
;
1448 /* Move it from the global to the local list */
1449 RemoveEntryList(&CurrentEntry
->HashLinks
);
1450 InsertTailList(&UnloadList
, &CurrentEntry
->HashLinks
);
1452 /* Get the entrypoint */
1453 EntryPoint
= LdrEntry
->EntryPoint
;
1455 /* Check if we should call it */
1456 if ((EntryPoint
) && (LdrEntry
->Flags
& LDRP_PROCESS_ATTACH_CALLED
))
1461 DPRINT1("LDR: Calling deinit %p\n", EntryPoint
);
1464 /* Set up the Act Ctx */
1465 ActCtx
.Size
= sizeof(ActCtx
);
1466 ActCtx
.Format
= RTL_CALLER_ALLOCATED_ACTIVATION_CONTEXT_STACK_FRAME_FORMAT_WHISTLER
;
1467 RtlZeroMemory(&ActCtx
.Frame
, sizeof(RTL_ACTIVATION_CONTEXT_STACK_FRAME
));
1469 /* Activate the ActCtx */
1470 RtlActivateActivationContextUnsafeFast(&ActCtx
,
1471 LdrEntry
->EntryPointActivationContext
);
1473 /* Call the entrypoint */
1474 LdrpCallInitRoutine(LdrEntry
->EntryPoint
,
1479 /* Release the context */
1480 RtlDeactivateActivationContextUnsafeFast(&ActCtx
);
1483 /* Remove it from the list */
1484 RemoveEntryList(&CurrentEntry
->InLoadOrderLinks
);
1485 CurrentEntry
= NULL
;
1486 NextEntry
= LdrpUnloadHead
.Flink
;
1489 /* Now loop our local list */
1490 NextEntry
= UnloadList
.Flink
;
1491 while (NextEntry
!= &UnloadList
)
1494 LdrEntry
= CONTAINING_RECORD(NextEntry
, LDR_DATA_TABLE_ENTRY
, HashLinks
);
1495 NextEntry
= NextEntry
->Flink
;
1496 CurrentEntry
= LdrEntry
;
1498 /* Notify Application Verifier */
1499 if (Peb
->NtGlobalFlag
& FLG_HEAP_ENABLE_TAIL_CHECK
)
1501 DPRINT1("We don't support Application Verifier yet\n");
1507 DPRINT1("LDR: Unmapping [%ws]\n", LdrEntry
->BaseDllName
.Buffer
);
1510 /* Check if this is a .NET executable */
1511 CorImageData
= RtlImageDirectoryEntryToData(LdrEntry
->DllBase
,
1513 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
,
1518 DPRINT1(".NET Images are not supported yet\n");
1521 /* Check if we should unmap*/
1522 if (!(CurrentEntry
->Flags
& LDR_COR_OWNS_UNMAP
))
1525 Status
= NtUnmapViewOfSection(NtCurrentProcess(),
1526 CurrentEntry
->DllBase
);
1527 ASSERT(NT_SUCCESS(Status
));
1530 /* Unload the alternate resource module, if any */
1531 LdrUnloadAlternateResourceModule(CurrentEntry
->DllBase
);
1533 /* FIXME: Send shutdown notification */
1534 //LdrpSendDllNotifications(CurrentEntry, 2, LdrpShutdownInProgress);
1536 /* Check if a Hotpatch is active */
1537 if (LdrEntry
->PatchInformation
)
1540 DPRINT1("We don't support Hotpatching yet\n");
1543 /* Deallocate the Entry */
1544 LdrpFinalizeAndDeallocateDataTableEntry(CurrentEntry
);
1546 /* If this is the cached entry, invalidate it */
1547 if (LdrpGetModuleHandleCache
== CurrentEntry
)
1549 LdrpGetModuleHandleCache
= NULL
;
1554 /* Decrease unload count */
1555 LdrpActiveUnloadCount
--;
1556 if (!LdrpInLdrInit
) RtlLeaveCriticalSection(Peb
->LoaderLock
);
1558 /* Return to caller */
1567 RtlDllShutdownInProgress(VOID
)
1569 /* Return the internal global */
1570 return LdrpShutdownInProgress
;
1576 PIMAGE_BASE_RELOCATION
1578 LdrProcessRelocationBlock(IN ULONG_PTR Address
,
1580 IN PUSHORT TypeOffset
,
1583 return LdrProcessRelocationBlockLongLong(Address
, Count
, TypeOffset
, Delta
);
1586 /* FIXME: Add to ntstatus.mc */
1587 #define STATUS_MUI_FILE_NOT_FOUND ((NTSTATUS)0xC00B0001L)
1594 LdrLoadAlternateResourceModule(IN PVOID Module
,
1597 /* Is MUI Support enabled? */
1598 if (!LdrAlternateResourcesEnabled()) return STATUS_SUCCESS
;
1601 return STATUS_MUI_FILE_NOT_FOUND
;
1609 LdrUnloadAlternateResourceModule(IN PVOID BaseAddress
)
1613 /* Acquire the loader lock */
1614 LdrLockLoaderLock(LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS
, NULL
, &Cookie
);
1616 /* Check if there's any alternate resources loaded */
1617 if (AlternateResourceModuleCount
)
1622 /* Release the loader lock */
1623 LdrUnlockLoaderLock(1, Cookie
);
1634 LdrFlushAlternateResourceModules(VOID
)