2 UEFI Heap Guard functions.
4 Copyright (c) 2017-2018, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
17 #include "HeapGuard.h"
20 // Global to avoid infinite reentrance of memory allocation when updating
21 // page table attributes, which may need allocate pages for new PDE/PTE.
23 GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding
= FALSE
;
26 // Pointer to table tracking the Guarded memory with bitmap, in which '1'
27 // is used to indicate memory guarded. '0' might be free memory or Guard
28 // page itself, depending on status of memory adjacent to it.
30 GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap
= 0;
33 // Current depth level of map table pointed by mGuardedMemoryMap.
34 // mMapLevel must be initialized at least by 1. It will be automatically
35 // updated according to the address of memory just tracked.
37 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel
= 1;
40 // Shift and mask for each level of map table
42 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift
[GUARDED_HEAP_MAP_TABLE_DEPTH
]
43 = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS
;
44 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask
[GUARDED_HEAP_MAP_TABLE_DEPTH
]
45 = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS
;
48 Set corresponding bits in bitmap table to 1 according to the address.
50 @param[in] Address Start address to set for.
51 @param[in] BitNumber Number of bits to set.
52 @param[in] BitMap Pointer to bitmap which covers the Address.
59 IN EFI_PHYSICAL_ADDRESS Address
,
70 StartBit
= (UINTN
)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
);
71 EndBit
= (StartBit
+ BitNumber
- 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
73 if ((StartBit
+ BitNumber
) >= GUARDED_HEAP_MAP_ENTRY_BITS
) {
74 Msbs
= (GUARDED_HEAP_MAP_ENTRY_BITS
- StartBit
) %
75 GUARDED_HEAP_MAP_ENTRY_BITS
;
76 Lsbs
= (EndBit
+ 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
77 Qwords
= (BitNumber
- Msbs
) / GUARDED_HEAP_MAP_ENTRY_BITS
;
85 *BitMap
|= LShiftU64 (LShiftU64 (1, Msbs
) - 1, StartBit
);
90 SetMem64 ((VOID
*)BitMap
, Qwords
* GUARDED_HEAP_MAP_ENTRY_BYTES
,
96 *BitMap
|= (LShiftU64 (1, Lsbs
) - 1);
101 Set corresponding bits in bitmap table to 0 according to the address.
103 @param[in] Address Start address to set for.
104 @param[in] BitNumber Number of bits to set.
105 @param[in] BitMap Pointer to bitmap which covers the Address.
112 IN EFI_PHYSICAL_ADDRESS Address
,
123 StartBit
= (UINTN
)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
);
124 EndBit
= (StartBit
+ BitNumber
- 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
126 if ((StartBit
+ BitNumber
) >= GUARDED_HEAP_MAP_ENTRY_BITS
) {
127 Msbs
= (GUARDED_HEAP_MAP_ENTRY_BITS
- StartBit
) %
128 GUARDED_HEAP_MAP_ENTRY_BITS
;
129 Lsbs
= (EndBit
+ 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
130 Qwords
= (BitNumber
- Msbs
) / GUARDED_HEAP_MAP_ENTRY_BITS
;
138 *BitMap
&= ~LShiftU64 (LShiftU64 (1, Msbs
) - 1, StartBit
);
143 SetMem64 ((VOID
*)BitMap
, Qwords
* GUARDED_HEAP_MAP_ENTRY_BYTES
, 0);
148 *BitMap
&= ~(LShiftU64 (1, Lsbs
) - 1);
153 Get corresponding bits in bitmap table according to the address.
155 The value of bit 0 corresponds to the status of memory at given Address.
156 No more than 64 bits can be retrieved in one call.
158 @param[in] Address Start address to retrieve bits for.
159 @param[in] BitNumber Number of bits to get.
160 @param[in] BitMap Pointer to bitmap which covers the Address.
162 @return An integer containing the bits information.
167 IN EFI_PHYSICAL_ADDRESS Address
,
178 ASSERT (BitNumber
<= GUARDED_HEAP_MAP_ENTRY_BITS
);
180 StartBit
= (UINTN
)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
);
181 EndBit
= (StartBit
+ BitNumber
- 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
183 if ((StartBit
+ BitNumber
) > GUARDED_HEAP_MAP_ENTRY_BITS
) {
184 Msbs
= GUARDED_HEAP_MAP_ENTRY_BITS
- StartBit
;
185 Lsbs
= (EndBit
+ 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
191 if (StartBit
== 0 && BitNumber
== GUARDED_HEAP_MAP_ENTRY_BITS
) {
194 Result
= RShiftU64((*BitMap
), StartBit
) & (LShiftU64(1, Msbs
) - 1);
197 Result
|= LShiftU64 ((*BitMap
) & (LShiftU64 (1, Lsbs
) - 1), Msbs
);
205 Locate the pointer of bitmap from the guarded memory bitmap tables, which
206 covers the given Address.
208 @param[in] Address Start address to search the bitmap for.
209 @param[in] AllocMapUnit Flag to indicate memory allocation for the table.
210 @param[out] BitMap Pointer to bitmap which covers the Address.
212 @return The bit number from given Address to the end of current map table.
215 FindGuardedMemoryMap (
216 IN EFI_PHYSICAL_ADDRESS Address
,
217 IN BOOLEAN AllocMapUnit
,
230 // Adjust current map table depth according to the address to access
232 while (AllocMapUnit
&&
233 mMapLevel
< GUARDED_HEAP_MAP_TABLE_DEPTH
&&
236 mLevelShift
[GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
- 1]
239 if (mGuardedMemoryMap
!= 0) {
240 Size
= (mLevelMask
[GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
- 1] + 1)
241 * GUARDED_HEAP_MAP_ENTRY_BYTES
;
242 Status
= CoreInternalAllocatePages (
245 EFI_SIZE_TO_PAGES (Size
),
249 ASSERT_EFI_ERROR (Status
);
250 ASSERT (MapMemory
!= 0);
252 SetMem ((VOID
*)(UINTN
)MapMemory
, Size
, 0);
254 *(UINT64
*)(UINTN
)MapMemory
= mGuardedMemoryMap
;
255 mGuardedMemoryMap
= MapMemory
;
262 GuardMap
= &mGuardedMemoryMap
;
263 for (Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
264 Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
;
267 if (*GuardMap
== 0) {
273 Size
= (mLevelMask
[Level
] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES
;
274 Status
= CoreInternalAllocatePages (
277 EFI_SIZE_TO_PAGES (Size
),
281 ASSERT_EFI_ERROR (Status
);
282 ASSERT (MapMemory
!= 0);
284 SetMem ((VOID
*)(UINTN
)MapMemory
, Size
, 0);
285 *GuardMap
= MapMemory
;
288 Index
= (UINTN
)RShiftU64 (Address
, mLevelShift
[Level
]);
289 Index
&= mLevelMask
[Level
];
290 GuardMap
= (UINT64
*)(UINTN
)((*GuardMap
) + Index
* sizeof (UINT64
));
294 BitsToUnitEnd
= GUARDED_HEAP_MAP_BITS
- GUARDED_HEAP_MAP_BIT_INDEX (Address
);
297 return BitsToUnitEnd
;
301 Set corresponding bits in bitmap table to 1 according to given memory range.
303 @param[in] Address Memory address to guard from.
304 @param[in] NumberOfPages Number of pages to guard.
310 SetGuardedMemoryBits (
311 IN EFI_PHYSICAL_ADDRESS Address
,
312 IN UINTN NumberOfPages
319 while (NumberOfPages
> 0) {
320 BitsToUnitEnd
= FindGuardedMemoryMap (Address
, TRUE
, &BitMap
);
321 ASSERT (BitMap
!= NULL
);
323 if (NumberOfPages
> BitsToUnitEnd
) {
325 Bits
= BitsToUnitEnd
;
327 Bits
= NumberOfPages
;
330 SetBits (Address
, Bits
, BitMap
);
332 NumberOfPages
-= Bits
;
333 Address
+= EFI_PAGES_TO_SIZE (Bits
);
338 Clear corresponding bits in bitmap table according to given memory range.
340 @param[in] Address Memory address to unset from.
341 @param[in] NumberOfPages Number of pages to unset guard.
347 ClearGuardedMemoryBits (
348 IN EFI_PHYSICAL_ADDRESS Address
,
349 IN UINTN NumberOfPages
356 while (NumberOfPages
> 0) {
357 BitsToUnitEnd
= FindGuardedMemoryMap (Address
, TRUE
, &BitMap
);
358 ASSERT (BitMap
!= NULL
);
360 if (NumberOfPages
> BitsToUnitEnd
) {
362 Bits
= BitsToUnitEnd
;
364 Bits
= NumberOfPages
;
367 ClearBits (Address
, Bits
, BitMap
);
369 NumberOfPages
-= Bits
;
370 Address
+= EFI_PAGES_TO_SIZE (Bits
);
375 Retrieve corresponding bits in bitmap table according to given memory range.
377 @param[in] Address Memory address to retrieve from.
378 @param[in] NumberOfPages Number of pages to retrieve.
380 @return An integer containing the guarded memory bitmap.
383 GetGuardedMemoryBits (
384 IN EFI_PHYSICAL_ADDRESS Address
,
385 IN UINTN NumberOfPages
394 ASSERT (NumberOfPages
<= GUARDED_HEAP_MAP_ENTRY_BITS
);
398 while (NumberOfPages
> 0) {
399 BitsToUnitEnd
= FindGuardedMemoryMap (Address
, FALSE
, &BitMap
);
401 if (NumberOfPages
> BitsToUnitEnd
) {
403 Bits
= BitsToUnitEnd
;
405 Bits
= NumberOfPages
;
408 if (BitMap
!= NULL
) {
409 Result
|= LShiftU64 (GetBits (Address
, Bits
, BitMap
), Shift
);
413 NumberOfPages
-= Bits
;
414 Address
+= EFI_PAGES_TO_SIZE (Bits
);
421 Get bit value in bitmap table for the given address.
423 @param[in] Address The address to retrieve for.
430 IN EFI_PHYSICAL_ADDRESS Address
435 FindGuardedMemoryMap (Address
, FALSE
, &GuardMap
);
436 if (GuardMap
!= NULL
) {
437 if (RShiftU64 (*GuardMap
,
438 GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
)) & 1) {
447 Set the bit in bitmap table for the given address.
449 @param[in] Address The address to set for.
456 IN EFI_PHYSICAL_ADDRESS Address
462 FindGuardedMemoryMap (Address
, TRUE
, &GuardMap
);
463 if (GuardMap
!= NULL
) {
464 BitMask
= LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
));
465 *GuardMap
|= BitMask
;
470 Clear the bit in bitmap table for the given address.
472 @param[in] Address The address to clear for.
479 IN EFI_PHYSICAL_ADDRESS Address
485 FindGuardedMemoryMap (Address
, TRUE
, &GuardMap
);
486 if (GuardMap
!= NULL
) {
487 BitMask
= LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
));
488 *GuardMap
&= ~BitMask
;
493 Check to see if the page at the given address is a Guard page or not.
495 @param[in] Address The address to check for.
497 @return TRUE The page at Address is a Guard page.
498 @return FALSE The page at Address is not a Guard page.
503 IN EFI_PHYSICAL_ADDRESS Address
509 // There must be at least one guarded page before and/or after given
510 // address if it's a Guard page. The bitmap pattern should be one of
513 BitMap
= GetGuardedMemoryBits (Address
- EFI_PAGE_SIZE
, 3);
514 return ((BitMap
== BIT0
) || (BitMap
== BIT2
) || (BitMap
== (BIT2
| BIT0
)));
518 Check to see if the page at the given address is a head Guard page or not.
520 @param[in] Address The address to check for
522 @return TRUE The page at Address is a head Guard page
523 @return FALSE The page at Address is not a head Guard page
528 IN EFI_PHYSICAL_ADDRESS Address
531 return (GetGuardedMemoryBits (Address
, 2) == BIT1
);
535 Check to see if the page at the given address is a tail Guard page or not.
537 @param[in] Address The address to check for.
539 @return TRUE The page at Address is a tail Guard page.
540 @return FALSE The page at Address is not a tail Guard page.
545 IN EFI_PHYSICAL_ADDRESS Address
548 return (GetGuardedMemoryBits (Address
- EFI_PAGE_SIZE
, 2) == BIT0
);
552 Check to see if the page at the given address is guarded or not.
554 @param[in] Address The address to check for.
556 @return TRUE The page at Address is guarded.
557 @return FALSE The page at Address is not guarded.
562 IN EFI_PHYSICAL_ADDRESS Address
565 return (GetGuardMapBit (Address
) == 1);
569 Set the page at the given address to be a Guard page.
571 This is done by changing the page table attribute to be NOT PRSENT.
573 @param[in] BaseAddress Page address to Guard at
580 IN EFI_PHYSICAL_ADDRESS BaseAddress
588 // Set flag to make sure allocating memory without GUARD for page table
589 // operation; otherwise infinite loops could be caused.
593 // Note: This might overwrite other attributes needed by other features,
594 // such as NX memory protection.
596 gCpu
->SetMemoryAttributes (gCpu
, BaseAddress
, EFI_PAGE_SIZE
, EFI_MEMORY_RP
);
601 Unset the Guard page at the given address to the normal memory.
603 This is done by changing the page table attribute to be PRSENT.
605 @param[in] BaseAddress Page address to Guard at.
612 IN EFI_PHYSICAL_ADDRESS BaseAddress
622 // Once the Guard page is unset, it will be freed back to memory pool. NX
623 // memory protection must be restored for this page if NX is enabled for free
627 if ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy
) & (1 << EfiConventionalMemory
)) != 0) {
628 Attributes
|= EFI_MEMORY_XP
;
632 // Set flag to make sure allocating memory without GUARD for page table
633 // operation; otherwise infinite loops could be caused.
637 // Note: This might overwrite other attributes needed by other features,
638 // such as memory protection (NX). Please make sure they are not enabled
641 gCpu
->SetMemoryAttributes (gCpu
, BaseAddress
, EFI_PAGE_SIZE
, Attributes
);
646 Check to see if the memory at the given address should be guarded or not.
648 @param[in] MemoryType Memory type to check.
649 @param[in] AllocateType Allocation type to check.
650 @param[in] PageOrPool Indicate a page allocation or pool allocation.
653 @return TRUE The given type of memory should be guarded.
654 @return FALSE The given type of memory should not be guarded.
657 IsMemoryTypeToGuard (
658 IN EFI_MEMORY_TYPE MemoryType
,
659 IN EFI_ALLOCATE_TYPE AllocateType
,
667 if (AllocateType
== AllocateAddress
) {
672 if (gSmmBase2
!= NULL
) {
673 gSmmBase2
->InSmm (gSmmBase2
, &InSmm
);
680 if ((PcdGet8 (PcdHeapGuardPropertyMask
) & PageOrPool
) == 0) {
684 if (PageOrPool
== GUARD_HEAP_TYPE_POOL
) {
685 ConfigBit
= PcdGet64 (PcdHeapGuardPoolType
);
686 } else if (PageOrPool
== GUARD_HEAP_TYPE_PAGE
) {
687 ConfigBit
= PcdGet64 (PcdHeapGuardPageType
);
689 ConfigBit
= (UINT64
)-1;
692 if ((UINT32
)MemoryType
>= MEMORY_TYPE_OS_RESERVED_MIN
) {
694 } else if ((UINT32
) MemoryType
>= MEMORY_TYPE_OEM_RESERVED_MIN
) {
696 } else if (MemoryType
< EfiMaxMemoryType
) {
697 TestBit
= LShiftU64 (1, MemoryType
);
698 } else if (MemoryType
== EfiMaxMemoryType
) {
699 TestBit
= (UINT64
)-1;
704 return ((ConfigBit
& TestBit
) != 0);
708 Check to see if the pool at the given address should be guarded or not.
710 @param[in] MemoryType Pool type to check.
713 @return TRUE The given type of pool should be guarded.
714 @return FALSE The given type of pool should not be guarded.
718 IN EFI_MEMORY_TYPE MemoryType
721 return IsMemoryTypeToGuard (MemoryType
, AllocateAnyPages
,
722 GUARD_HEAP_TYPE_POOL
);
726 Check to see if the page at the given address should be guarded or not.
728 @param[in] MemoryType Page type to check.
729 @param[in] AllocateType Allocation type to check.
731 @return TRUE The given type of page should be guarded.
732 @return FALSE The given type of page should not be guarded.
736 IN EFI_MEMORY_TYPE MemoryType
,
737 IN EFI_ALLOCATE_TYPE AllocateType
740 return IsMemoryTypeToGuard (MemoryType
, AllocateType
, GUARD_HEAP_TYPE_PAGE
);
744 Check to see if the heap guard is enabled for page and/or pool allocation.
753 return IsMemoryTypeToGuard (EfiMaxMemoryType
, AllocateAnyPages
,
754 GUARD_HEAP_TYPE_POOL
|GUARD_HEAP_TYPE_PAGE
);
758 Set head Guard and tail Guard for the given memory range.
760 @param[in] Memory Base address of memory to set guard for.
761 @param[in] NumberOfPages Memory size in pages.
767 IN EFI_PHYSICAL_ADDRESS Memory
,
768 IN UINTN NumberOfPages
771 EFI_PHYSICAL_ADDRESS GuardPage
;
776 GuardPage
= Memory
+ EFI_PAGES_TO_SIZE (NumberOfPages
);
777 if (!IsGuardPage (GuardPage
)) {
778 SetGuardPage (GuardPage
);
782 GuardPage
= Memory
- EFI_PAGES_TO_SIZE (1);
783 if (!IsGuardPage (GuardPage
)) {
784 SetGuardPage (GuardPage
);
788 // Mark the memory range as Guarded
790 SetGuardedMemoryBits (Memory
, NumberOfPages
);
794 Unset head Guard and tail Guard for the given memory range.
796 @param[in] Memory Base address of memory to unset guard for.
797 @param[in] NumberOfPages Memory size in pages.
802 UnsetGuardForMemory (
803 IN EFI_PHYSICAL_ADDRESS Memory
,
804 IN UINTN NumberOfPages
807 EFI_PHYSICAL_ADDRESS GuardPage
;
810 if (NumberOfPages
== 0) {
815 // Head Guard must be one page before, if any.
818 // -------------------
819 // Head Guard -> 0 1 -> Don't free Head Guard (shared Guard)
820 // Head Guard -> 0 0 -> Free Head Guard either (not shared Guard)
821 // 1 X -> Don't free first page (need a new Guard)
822 // (it'll be turned into a Guard page later)
823 // -------------------
826 GuardPage
= Memory
- EFI_PAGES_TO_SIZE (1);
827 GuardBitmap
= GetGuardedMemoryBits (Memory
- EFI_PAGES_TO_SIZE (2), 2);
828 if ((GuardBitmap
& BIT1
) == 0) {
830 // Head Guard exists.
832 if ((GuardBitmap
& BIT0
) == 0) {
834 // If the head Guard is not a tail Guard of adjacent memory block,
837 UnsetGuardPage (GuardPage
);
841 // Pages before memory to free are still in Guard. It's a partial free
842 // case. Turn first page of memory block to free into a new Guard.
844 SetGuardPage (Memory
);
848 // Tail Guard must be the page after this memory block to free, if any.
851 // --------------------
852 // 1 0 <- Tail Guard -> Don't free Tail Guard (shared Guard)
853 // 0 0 <- Tail Guard -> Free Tail Guard either (not shared Guard)
854 // X 1 -> Don't free last page (need a new Guard)
855 // (it'll be turned into a Guard page later)
856 // --------------------
859 GuardPage
= Memory
+ EFI_PAGES_TO_SIZE (NumberOfPages
);
860 GuardBitmap
= GetGuardedMemoryBits (GuardPage
, 2);
861 if ((GuardBitmap
& BIT0
) == 0) {
863 // Tail Guard exists.
865 if ((GuardBitmap
& BIT1
) == 0) {
867 // If the tail Guard is not a head Guard of adjacent memory block,
868 // free it; otherwise, keep it.
870 UnsetGuardPage (GuardPage
);
874 // Pages after memory to free are still in Guard. It's a partial free
875 // case. We need to keep one page to be a head Guard.
877 SetGuardPage (GuardPage
- EFI_PAGES_TO_SIZE (1));
881 // No matter what, we just clear the mark of the Guarded memory.
883 ClearGuardedMemoryBits(Memory
, NumberOfPages
);
887 Adjust address of free memory according to existing and/or required Guard.
889 This function will check if there're existing Guard pages of adjacent
890 memory blocks, and try to use it as the Guard page of the memory to be
893 @param[in] Start Start address of free memory block.
894 @param[in] Size Size of free memory block.
895 @param[in] SizeRequested Size of memory to allocate.
897 @return The end address of memory block found.
898 @return 0 if no enough space for the required size of memory and its Guard.
904 IN UINT64 SizeRequested
910 // UEFI spec requires that allocated pool must be 8-byte aligned. If it's
911 // indicated to put the pool near the Tail Guard, we need extra bytes to
912 // make sure alignment of the returned pool address.
914 if ((PcdGet8 (PcdHeapGuardPropertyMask
) & BIT7
) == 0) {
915 SizeRequested
= ALIGN_VALUE(SizeRequested
, 8);
918 Target
= Start
+ Size
- SizeRequested
;
919 ASSERT (Target
>= Start
);
924 if (!IsGuardPage (Start
+ Size
)) {
925 // No Guard at tail to share. One more page is needed.
926 Target
-= EFI_PAGES_TO_SIZE (1);
930 if (Target
< Start
) {
935 if (Target
== Start
) {
936 if (!IsGuardPage (Target
- EFI_PAGES_TO_SIZE (1))) {
937 // No enough space for a new head Guard if no Guard at head to share.
942 // OK, we have enough pages for memory and its Guards. Return the End of the
944 return Target
+ SizeRequested
- 1;
948 Adjust the start address and number of pages to free according to Guard.
950 The purpose of this function is to keep the shared Guard page with adjacent
951 memory block if it's still in guard, or free it if no more sharing. Another
952 is to reserve pages as Guard pages in partial page free situation.
954 @param[in,out] Memory Base address of memory to free.
955 @param[in,out] NumberOfPages Size of memory to free.
961 IN OUT EFI_PHYSICAL_ADDRESS
*Memory
,
962 IN OUT UINTN
*NumberOfPages
965 EFI_PHYSICAL_ADDRESS Start
;
966 EFI_PHYSICAL_ADDRESS MemoryToTest
;
970 if (Memory
== NULL
|| NumberOfPages
== NULL
|| *NumberOfPages
== 0) {
975 PagesToFree
= *NumberOfPages
;
978 // Head Guard must be one page before, if any.
981 // -------------------
982 // Head Guard -> 0 1 -> Don't free Head Guard (shared Guard)
983 // Head Guard -> 0 0 -> Free Head Guard either (not shared Guard)
984 // 1 X -> Don't free first page (need a new Guard)
985 // (it'll be turned into a Guard page later)
986 // -------------------
989 MemoryToTest
= Start
- EFI_PAGES_TO_SIZE (2);
990 GuardBitmap
= GetGuardedMemoryBits (MemoryToTest
, 2);
991 if ((GuardBitmap
& BIT1
) == 0) {
993 // Head Guard exists.
995 if ((GuardBitmap
& BIT0
) == 0) {
997 // If the head Guard is not a tail Guard of adjacent memory block,
998 // free it; otherwise, keep it.
1000 Start
-= EFI_PAGES_TO_SIZE (1);
1005 // No Head Guard, and pages before memory to free are still in Guard. It's a
1006 // partial free case. We need to keep one page to be a tail Guard.
1008 Start
+= EFI_PAGES_TO_SIZE (1);
1013 // Tail Guard must be the page after this memory block to free, if any.
1016 // --------------------
1017 // 1 0 <- Tail Guard -> Don't free Tail Guard (shared Guard)
1018 // 0 0 <- Tail Guard -> Free Tail Guard either (not shared Guard)
1019 // X 1 -> Don't free last page (need a new Guard)
1020 // (it'll be turned into a Guard page later)
1021 // --------------------
1024 MemoryToTest
= Start
+ EFI_PAGES_TO_SIZE (PagesToFree
);
1025 GuardBitmap
= GetGuardedMemoryBits (MemoryToTest
, 2);
1026 if ((GuardBitmap
& BIT0
) == 0) {
1028 // Tail Guard exists.
1030 if ((GuardBitmap
& BIT1
) == 0) {
1032 // If the tail Guard is not a head Guard of adjacent memory block,
1033 // free it; otherwise, keep it.
1037 } else if (PagesToFree
> 0) {
1039 // No Tail Guard, and pages after memory to free are still in Guard. It's a
1040 // partial free case. We need to keep one page to be a head Guard.
1046 *NumberOfPages
= PagesToFree
;
1050 Adjust the base and number of pages to really allocate according to Guard.
1052 @param[in,out] Memory Base address of free memory.
1053 @param[in,out] NumberOfPages Size of memory to allocate.
1059 IN OUT EFI_PHYSICAL_ADDRESS
*Memory
,
1060 IN OUT UINTN
*NumberOfPages
1064 // FindFreePages() has already taken the Guard into account. It's safe to
1065 // adjust the start address and/or number of pages here, to make sure that
1066 // the Guards are also "allocated".
1068 if (!IsGuardPage (*Memory
+ EFI_PAGES_TO_SIZE (*NumberOfPages
))) {
1069 // No tail Guard, add one.
1070 *NumberOfPages
+= 1;
1073 if (!IsGuardPage (*Memory
- EFI_PAGE_SIZE
)) {
1074 // No head Guard, add one.
1075 *Memory
-= EFI_PAGE_SIZE
;
1076 *NumberOfPages
+= 1;
1081 Adjust the pool head position to make sure the Guard page is adjavent to
1082 pool tail or pool head.
1084 @param[in] Memory Base address of memory allocated.
1085 @param[in] NoPages Number of pages actually allocated.
1086 @param[in] Size Size of memory requested.
1087 (plus pool head/tail overhead)
1089 @return Address of pool head.
1093 IN EFI_PHYSICAL_ADDRESS Memory
,
1098 if (Memory
== 0 || (PcdGet8 (PcdHeapGuardPropertyMask
) & BIT7
) != 0) {
1100 // Pool head is put near the head Guard
1102 return (VOID
*)(UINTN
)Memory
;
1106 // Pool head is put near the tail Guard
1108 Size
= ALIGN_VALUE (Size
, 8);
1109 return (VOID
*)(UINTN
)(Memory
+ EFI_PAGES_TO_SIZE (NoPages
) - Size
);
1113 Get the page base address according to pool head address.
1115 @param[in] Memory Head address of pool to free.
1117 @return Address of pool head.
1121 IN EFI_PHYSICAL_ADDRESS Memory
1124 if (Memory
== 0 || (PcdGet8 (PcdHeapGuardPropertyMask
) & BIT7
) != 0) {
1126 // Pool head is put near the head Guard
1128 return (VOID
*)(UINTN
)Memory
;
1132 // Pool head is put near the tail Guard
1134 return (VOID
*)(UINTN
)(Memory
& ~EFI_PAGE_MASK
);
1138 Allocate or free guarded memory.
1140 @param[in] Start Start address of memory to allocate or free.
1141 @param[in] NumberOfPages Memory size in pages.
1142 @param[in] NewType Memory type to convert to.
1147 CoreConvertPagesWithGuard (
1149 IN UINTN NumberOfPages
,
1150 IN EFI_MEMORY_TYPE NewType
1156 if (NewType
== EfiConventionalMemory
) {
1158 OldPages
= NumberOfPages
;
1160 AdjustMemoryF (&Start
, &NumberOfPages
);
1162 // It's safe to unset Guard page inside memory lock because there should
1163 // be no memory allocation occurred in updating memory page attribute at
1164 // this point. And unsetting Guard page before free will prevent Guard
1165 // page just freed back to pool from being allocated right away before
1166 // marking it usable (from non-present to present).
1168 UnsetGuardForMemory (OldStart
, OldPages
);
1169 if (NumberOfPages
== 0) {
1173 AdjustMemoryA (&Start
, &NumberOfPages
);
1176 return CoreConvertPages (Start
, NumberOfPages
, NewType
);
1180 Set all Guard pages which cannot be set before CPU Arch Protocol installed.
1187 UINTN Entries
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1188 UINTN Shifts
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1189 UINTN Indices
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1190 UINT64 Tables
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1191 UINT64 Addresses
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1199 if (mGuardedMemoryMap
== 0 ||
1201 mMapLevel
> GUARDED_HEAP_MAP_TABLE_DEPTH
) {
1205 CopyMem (Entries
, mLevelMask
, sizeof (Entries
));
1206 CopyMem (Shifts
, mLevelShift
, sizeof (Shifts
));
1208 SetMem (Tables
, sizeof(Tables
), 0);
1209 SetMem (Addresses
, sizeof(Addresses
), 0);
1210 SetMem (Indices
, sizeof(Indices
), 0);
1212 Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
1213 Tables
[Level
] = mGuardedMemoryMap
;
1218 DumpGuardedMemoryBitmap ();
1222 if (Indices
[Level
] > Entries
[Level
]) {
1227 TableEntry
= ((UINT64
*)(UINTN
)(Tables
[Level
]))[Indices
[Level
]];
1228 Address
= Addresses
[Level
];
1230 if (TableEntry
== 0) {
1234 } else if (Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1237 Tables
[Level
] = TableEntry
;
1238 Addresses
[Level
] = Address
;
1246 while (Index
< GUARDED_HEAP_MAP_ENTRY_BITS
) {
1247 if ((TableEntry
& 1) == 1) {
1251 GuardPage
= Address
- EFI_PAGE_SIZE
;
1256 GuardPage
= Address
;
1263 if (GuardPage
!= 0) {
1264 SetGuardPage (GuardPage
);
1267 if (TableEntry
== 0) {
1271 TableEntry
= RShiftU64 (TableEntry
, 1);
1272 Address
+= EFI_PAGE_SIZE
;
1278 if (Level
< (GUARDED_HEAP_MAP_TABLE_DEPTH
- (INTN
)mMapLevel
)) {
1282 Indices
[Level
] += 1;
1283 Address
= (Level
== 0) ? 0 : Addresses
[Level
- 1];
1284 Addresses
[Level
] = Address
| LShiftU64(Indices
[Level
], Shifts
[Level
]);
1290 Notify function used to set all Guard pages before CPU Arch Protocol installed.
1293 HeapGuardCpuArchProtocolNotify (
1297 ASSERT (gCpu
!= NULL
);
1298 SetAllGuardPages ();
1302 Helper function to convert a UINT64 value in binary to a string.
1304 @param[in] Value Value of a UINT64 integer.
1305 @param[out] BinString String buffer to contain the conversion result.
1312 OUT CHAR8
*BinString
1317 if (BinString
== NULL
) {
1321 for (Index
= 64; Index
> 0; --Index
) {
1322 BinString
[Index
- 1] = '0' + (Value
& 1);
1323 Value
= RShiftU64 (Value
, 1);
1325 BinString
[64] = '\0';
1329 Dump the guarded memory bit map.
1333 DumpGuardedMemoryBitmap (
1337 UINTN Entries
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1338 UINTN Shifts
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1339 UINTN Indices
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1340 UINT64 Tables
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1341 UINT64 Addresses
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1346 CHAR8 String
[GUARDED_HEAP_MAP_ENTRY_BITS
+ 1];
1350 if (mGuardedMemoryMap
== 0 ||
1352 mMapLevel
> GUARDED_HEAP_MAP_TABLE_DEPTH
) {
1356 Ruler1
= " 3 2 1 0";
1357 Ruler2
= "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";
1359 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "============================="
1360 " Guarded Memory Bitmap "
1361 "==============================\r\n"));
1362 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, " %a\r\n", Ruler1
));
1363 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, " %a\r\n", Ruler2
));
1365 CopyMem (Entries
, mLevelMask
, sizeof (Entries
));
1366 CopyMem (Shifts
, mLevelShift
, sizeof (Shifts
));
1368 SetMem (Indices
, sizeof(Indices
), 0);
1369 SetMem (Tables
, sizeof(Tables
), 0);
1370 SetMem (Addresses
, sizeof(Addresses
), 0);
1372 Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
1373 Tables
[Level
] = mGuardedMemoryMap
;
1378 if (Indices
[Level
] > Entries
[Level
]) {
1385 HEAP_GUARD_DEBUG_LEVEL
,
1386 "========================================="
1387 "=========================================\r\n"
1392 TableEntry
= ((UINT64
*)(UINTN
)Tables
[Level
])[Indices
[Level
]];
1393 Address
= Addresses
[Level
];
1395 if (TableEntry
== 0) {
1397 if (Level
== GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1398 if (RepeatZero
== 0) {
1399 Uint64ToBinString(TableEntry
, String
);
1400 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "%016lx: %a\r\n", Address
, String
));
1401 } else if (RepeatZero
== 1) {
1402 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "... : ...\r\n"));
1407 } else if (Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1410 Tables
[Level
] = TableEntry
;
1411 Addresses
[Level
] = Address
;
1420 Uint64ToBinString(TableEntry
, String
);
1421 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "%016lx: %a\r\n", Address
, String
));
1426 if (Level
< (GUARDED_HEAP_MAP_TABLE_DEPTH
- (INTN
)mMapLevel
)) {
1430 Indices
[Level
] += 1;
1431 Address
= (Level
== 0) ? 0 : Addresses
[Level
- 1];
1432 Addresses
[Level
] = Address
| LShiftU64(Indices
[Level
], Shifts
[Level
]);