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 // Used for promoting freed but not used pages.
50 GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS mLastPromotedPage
= BASE_4GB
;
53 Set corresponding bits in bitmap table to 1 according to the address.
55 @param[in] Address Start address to set for.
56 @param[in] BitNumber Number of bits to set.
57 @param[in] BitMap Pointer to bitmap which covers the Address.
64 IN EFI_PHYSICAL_ADDRESS Address
,
75 StartBit
= (UINTN
)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
);
76 EndBit
= (StartBit
+ BitNumber
- 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
78 if ((StartBit
+ BitNumber
) >= GUARDED_HEAP_MAP_ENTRY_BITS
) {
79 Msbs
= (GUARDED_HEAP_MAP_ENTRY_BITS
- StartBit
) %
80 GUARDED_HEAP_MAP_ENTRY_BITS
;
81 Lsbs
= (EndBit
+ 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
82 Qwords
= (BitNumber
- Msbs
) / GUARDED_HEAP_MAP_ENTRY_BITS
;
90 *BitMap
|= LShiftU64 (LShiftU64 (1, Msbs
) - 1, StartBit
);
95 SetMem64 ((VOID
*)BitMap
, Qwords
* GUARDED_HEAP_MAP_ENTRY_BYTES
,
101 *BitMap
|= (LShiftU64 (1, Lsbs
) - 1);
106 Set corresponding bits in bitmap table to 0 according to the address.
108 @param[in] Address Start address to set for.
109 @param[in] BitNumber Number of bits to set.
110 @param[in] BitMap Pointer to bitmap which covers the Address.
117 IN EFI_PHYSICAL_ADDRESS Address
,
128 StartBit
= (UINTN
)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
);
129 EndBit
= (StartBit
+ BitNumber
- 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
131 if ((StartBit
+ BitNumber
) >= GUARDED_HEAP_MAP_ENTRY_BITS
) {
132 Msbs
= (GUARDED_HEAP_MAP_ENTRY_BITS
- StartBit
) %
133 GUARDED_HEAP_MAP_ENTRY_BITS
;
134 Lsbs
= (EndBit
+ 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
135 Qwords
= (BitNumber
- Msbs
) / GUARDED_HEAP_MAP_ENTRY_BITS
;
143 *BitMap
&= ~LShiftU64 (LShiftU64 (1, Msbs
) - 1, StartBit
);
148 SetMem64 ((VOID
*)BitMap
, Qwords
* GUARDED_HEAP_MAP_ENTRY_BYTES
, 0);
153 *BitMap
&= ~(LShiftU64 (1, Lsbs
) - 1);
158 Get corresponding bits in bitmap table according to the address.
160 The value of bit 0 corresponds to the status of memory at given Address.
161 No more than 64 bits can be retrieved in one call.
163 @param[in] Address Start address to retrieve bits for.
164 @param[in] BitNumber Number of bits to get.
165 @param[in] BitMap Pointer to bitmap which covers the Address.
167 @return An integer containing the bits information.
172 IN EFI_PHYSICAL_ADDRESS Address
,
183 ASSERT (BitNumber
<= GUARDED_HEAP_MAP_ENTRY_BITS
);
185 StartBit
= (UINTN
)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
);
186 EndBit
= (StartBit
+ BitNumber
- 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
188 if ((StartBit
+ BitNumber
) > GUARDED_HEAP_MAP_ENTRY_BITS
) {
189 Msbs
= GUARDED_HEAP_MAP_ENTRY_BITS
- StartBit
;
190 Lsbs
= (EndBit
+ 1) % GUARDED_HEAP_MAP_ENTRY_BITS
;
196 if (StartBit
== 0 && BitNumber
== GUARDED_HEAP_MAP_ENTRY_BITS
) {
199 Result
= RShiftU64((*BitMap
), StartBit
) & (LShiftU64(1, Msbs
) - 1);
202 Result
|= LShiftU64 ((*BitMap
) & (LShiftU64 (1, Lsbs
) - 1), Msbs
);
210 Locate the pointer of bitmap from the guarded memory bitmap tables, which
211 covers the given Address.
213 @param[in] Address Start address to search the bitmap for.
214 @param[in] AllocMapUnit Flag to indicate memory allocation for the table.
215 @param[out] BitMap Pointer to bitmap which covers the Address.
217 @return The bit number from given Address to the end of current map table.
220 FindGuardedMemoryMap (
221 IN EFI_PHYSICAL_ADDRESS Address
,
222 IN BOOLEAN AllocMapUnit
,
235 // Adjust current map table depth according to the address to access
237 while (AllocMapUnit
&&
238 mMapLevel
< GUARDED_HEAP_MAP_TABLE_DEPTH
&&
241 mLevelShift
[GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
- 1]
244 if (mGuardedMemoryMap
!= 0) {
245 Size
= (mLevelMask
[GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
- 1] + 1)
246 * GUARDED_HEAP_MAP_ENTRY_BYTES
;
247 Status
= CoreInternalAllocatePages (
250 EFI_SIZE_TO_PAGES (Size
),
254 ASSERT_EFI_ERROR (Status
);
255 ASSERT (MapMemory
!= 0);
257 SetMem ((VOID
*)(UINTN
)MapMemory
, Size
, 0);
259 *(UINT64
*)(UINTN
)MapMemory
= mGuardedMemoryMap
;
260 mGuardedMemoryMap
= MapMemory
;
267 GuardMap
= &mGuardedMemoryMap
;
268 for (Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
269 Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
;
272 if (*GuardMap
== 0) {
278 Size
= (mLevelMask
[Level
] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES
;
279 Status
= CoreInternalAllocatePages (
282 EFI_SIZE_TO_PAGES (Size
),
286 ASSERT_EFI_ERROR (Status
);
287 ASSERT (MapMemory
!= 0);
289 SetMem ((VOID
*)(UINTN
)MapMemory
, Size
, 0);
290 *GuardMap
= MapMemory
;
293 Index
= (UINTN
)RShiftU64 (Address
, mLevelShift
[Level
]);
294 Index
&= mLevelMask
[Level
];
295 GuardMap
= (UINT64
*)(UINTN
)((*GuardMap
) + Index
* sizeof (UINT64
));
299 BitsToUnitEnd
= GUARDED_HEAP_MAP_BITS
- GUARDED_HEAP_MAP_BIT_INDEX (Address
);
302 return BitsToUnitEnd
;
306 Set corresponding bits in bitmap table to 1 according to given memory range.
308 @param[in] Address Memory address to guard from.
309 @param[in] NumberOfPages Number of pages to guard.
315 SetGuardedMemoryBits (
316 IN EFI_PHYSICAL_ADDRESS Address
,
317 IN UINTN NumberOfPages
324 while (NumberOfPages
> 0) {
325 BitsToUnitEnd
= FindGuardedMemoryMap (Address
, TRUE
, &BitMap
);
326 ASSERT (BitMap
!= NULL
);
328 if (NumberOfPages
> BitsToUnitEnd
) {
330 Bits
= BitsToUnitEnd
;
332 Bits
= NumberOfPages
;
335 SetBits (Address
, Bits
, BitMap
);
337 NumberOfPages
-= Bits
;
338 Address
+= EFI_PAGES_TO_SIZE (Bits
);
343 Clear corresponding bits in bitmap table according to given memory range.
345 @param[in] Address Memory address to unset from.
346 @param[in] NumberOfPages Number of pages to unset guard.
352 ClearGuardedMemoryBits (
353 IN EFI_PHYSICAL_ADDRESS Address
,
354 IN UINTN NumberOfPages
361 while (NumberOfPages
> 0) {
362 BitsToUnitEnd
= FindGuardedMemoryMap (Address
, TRUE
, &BitMap
);
363 ASSERT (BitMap
!= NULL
);
365 if (NumberOfPages
> BitsToUnitEnd
) {
367 Bits
= BitsToUnitEnd
;
369 Bits
= NumberOfPages
;
372 ClearBits (Address
, Bits
, BitMap
);
374 NumberOfPages
-= Bits
;
375 Address
+= EFI_PAGES_TO_SIZE (Bits
);
380 Retrieve corresponding bits in bitmap table according to given memory range.
382 @param[in] Address Memory address to retrieve from.
383 @param[in] NumberOfPages Number of pages to retrieve.
385 @return An integer containing the guarded memory bitmap.
388 GetGuardedMemoryBits (
389 IN EFI_PHYSICAL_ADDRESS Address
,
390 IN UINTN NumberOfPages
399 ASSERT (NumberOfPages
<= GUARDED_HEAP_MAP_ENTRY_BITS
);
403 while (NumberOfPages
> 0) {
404 BitsToUnitEnd
= FindGuardedMemoryMap (Address
, FALSE
, &BitMap
);
406 if (NumberOfPages
> BitsToUnitEnd
) {
408 Bits
= BitsToUnitEnd
;
410 Bits
= NumberOfPages
;
413 if (BitMap
!= NULL
) {
414 Result
|= LShiftU64 (GetBits (Address
, Bits
, BitMap
), Shift
);
418 NumberOfPages
-= Bits
;
419 Address
+= EFI_PAGES_TO_SIZE (Bits
);
426 Get bit value in bitmap table for the given address.
428 @param[in] Address The address to retrieve for.
435 IN EFI_PHYSICAL_ADDRESS Address
440 FindGuardedMemoryMap (Address
, FALSE
, &GuardMap
);
441 if (GuardMap
!= NULL
) {
442 if (RShiftU64 (*GuardMap
,
443 GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address
)) & 1) {
453 Check to see if the page at the given address is a Guard page or not.
455 @param[in] Address The address to check for.
457 @return TRUE The page at Address is a Guard page.
458 @return FALSE The page at Address is not a Guard page.
463 IN EFI_PHYSICAL_ADDRESS Address
469 // There must be at least one guarded page before and/or after given
470 // address if it's a Guard page. The bitmap pattern should be one of
473 BitMap
= GetGuardedMemoryBits (Address
- EFI_PAGE_SIZE
, 3);
474 return ((BitMap
== BIT0
) || (BitMap
== BIT2
) || (BitMap
== (BIT2
| BIT0
)));
479 Check to see if the page at the given address is guarded or not.
481 @param[in] Address The address to check for.
483 @return TRUE The page at Address is guarded.
484 @return FALSE The page at Address is not guarded.
489 IN EFI_PHYSICAL_ADDRESS Address
492 return (GetGuardMapBit (Address
) == 1);
496 Set the page at the given address to be a Guard page.
498 This is done by changing the page table attribute to be NOT PRSENT.
500 @param[in] BaseAddress Page address to Guard at
507 IN EFI_PHYSICAL_ADDRESS BaseAddress
517 // Set flag to make sure allocating memory without GUARD for page table
518 // operation; otherwise infinite loops could be caused.
522 // Note: This might overwrite other attributes needed by other features,
523 // such as NX memory protection.
525 Status
= gCpu
->SetMemoryAttributes (gCpu
, BaseAddress
, EFI_PAGE_SIZE
, EFI_MEMORY_RP
);
526 ASSERT_EFI_ERROR (Status
);
531 Unset the Guard page at the given address to the normal memory.
533 This is done by changing the page table attribute to be PRSENT.
535 @param[in] BaseAddress Page address to Guard at.
542 IN EFI_PHYSICAL_ADDRESS BaseAddress
553 // Once the Guard page is unset, it will be freed back to memory pool. NX
554 // memory protection must be restored for this page if NX is enabled for free
558 if ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy
) & (1 << EfiConventionalMemory
)) != 0) {
559 Attributes
|= EFI_MEMORY_XP
;
563 // Set flag to make sure allocating memory without GUARD for page table
564 // operation; otherwise infinite loops could be caused.
568 // Note: This might overwrite other attributes needed by other features,
569 // such as memory protection (NX). Please make sure they are not enabled
572 Status
= gCpu
->SetMemoryAttributes (gCpu
, BaseAddress
, EFI_PAGE_SIZE
, Attributes
);
573 ASSERT_EFI_ERROR (Status
);
578 Check to see if the memory at the given address should be guarded or not.
580 @param[in] MemoryType Memory type to check.
581 @param[in] AllocateType Allocation type to check.
582 @param[in] PageOrPool Indicate a page allocation or pool allocation.
585 @return TRUE The given type of memory should be guarded.
586 @return FALSE The given type of memory should not be guarded.
589 IsMemoryTypeToGuard (
590 IN EFI_MEMORY_TYPE MemoryType
,
591 IN EFI_ALLOCATE_TYPE AllocateType
,
598 if (AllocateType
== AllocateAddress
) {
602 if ((PcdGet8 (PcdHeapGuardPropertyMask
) & PageOrPool
) == 0) {
606 if (PageOrPool
== GUARD_HEAP_TYPE_POOL
) {
607 ConfigBit
= PcdGet64 (PcdHeapGuardPoolType
);
608 } else if (PageOrPool
== GUARD_HEAP_TYPE_PAGE
) {
609 ConfigBit
= PcdGet64 (PcdHeapGuardPageType
);
611 ConfigBit
= (UINT64
)-1;
614 if ((UINT32
)MemoryType
>= MEMORY_TYPE_OS_RESERVED_MIN
) {
616 } else if ((UINT32
) MemoryType
>= MEMORY_TYPE_OEM_RESERVED_MIN
) {
618 } else if (MemoryType
< EfiMaxMemoryType
) {
619 TestBit
= LShiftU64 (1, MemoryType
);
620 } else if (MemoryType
== EfiMaxMemoryType
) {
621 TestBit
= (UINT64
)-1;
626 return ((ConfigBit
& TestBit
) != 0);
630 Check to see if the pool at the given address should be guarded or not.
632 @param[in] MemoryType Pool type to check.
635 @return TRUE The given type of pool should be guarded.
636 @return FALSE The given type of pool should not be guarded.
640 IN EFI_MEMORY_TYPE MemoryType
643 return IsMemoryTypeToGuard (MemoryType
, AllocateAnyPages
,
644 GUARD_HEAP_TYPE_POOL
);
648 Check to see if the page at the given address should be guarded or not.
650 @param[in] MemoryType Page type to check.
651 @param[in] AllocateType Allocation type to check.
653 @return TRUE The given type of page should be guarded.
654 @return FALSE The given type of page should not be guarded.
658 IN EFI_MEMORY_TYPE MemoryType
,
659 IN EFI_ALLOCATE_TYPE AllocateType
662 return IsMemoryTypeToGuard (MemoryType
, AllocateType
, GUARD_HEAP_TYPE_PAGE
);
666 Check to see if the heap guard is enabled for page and/or pool allocation.
668 @param[in] GuardType Specify the sub-type(s) of Heap Guard.
677 return IsMemoryTypeToGuard (EfiMaxMemoryType
, AllocateAnyPages
, GuardType
);
681 Set head Guard and tail Guard for the given memory range.
683 @param[in] Memory Base address of memory to set guard for.
684 @param[in] NumberOfPages Memory size in pages.
690 IN EFI_PHYSICAL_ADDRESS Memory
,
691 IN UINTN NumberOfPages
694 EFI_PHYSICAL_ADDRESS GuardPage
;
699 GuardPage
= Memory
+ EFI_PAGES_TO_SIZE (NumberOfPages
);
700 if (!IsGuardPage (GuardPage
)) {
701 SetGuardPage (GuardPage
);
705 GuardPage
= Memory
- EFI_PAGES_TO_SIZE (1);
706 if (!IsGuardPage (GuardPage
)) {
707 SetGuardPage (GuardPage
);
711 // Mark the memory range as Guarded
713 SetGuardedMemoryBits (Memory
, NumberOfPages
);
717 Unset head Guard and tail Guard for the given memory range.
719 @param[in] Memory Base address of memory to unset guard for.
720 @param[in] NumberOfPages Memory size in pages.
725 UnsetGuardForMemory (
726 IN EFI_PHYSICAL_ADDRESS Memory
,
727 IN UINTN NumberOfPages
730 EFI_PHYSICAL_ADDRESS GuardPage
;
733 if (NumberOfPages
== 0) {
738 // Head Guard must be one page before, if any.
741 // -------------------
742 // Head Guard -> 0 1 -> Don't free Head Guard (shared Guard)
743 // Head Guard -> 0 0 -> Free Head Guard either (not shared Guard)
744 // 1 X -> Don't free first page (need a new Guard)
745 // (it'll be turned into a Guard page later)
746 // -------------------
749 GuardPage
= Memory
- EFI_PAGES_TO_SIZE (1);
750 GuardBitmap
= GetGuardedMemoryBits (Memory
- EFI_PAGES_TO_SIZE (2), 2);
751 if ((GuardBitmap
& BIT1
) == 0) {
753 // Head Guard exists.
755 if ((GuardBitmap
& BIT0
) == 0) {
757 // If the head Guard is not a tail Guard of adjacent memory block,
760 UnsetGuardPage (GuardPage
);
764 // Pages before memory to free are still in Guard. It's a partial free
765 // case. Turn first page of memory block to free into a new Guard.
767 SetGuardPage (Memory
);
771 // Tail Guard must be the page after this memory block to free, if any.
774 // --------------------
775 // 1 0 <- Tail Guard -> Don't free Tail Guard (shared Guard)
776 // 0 0 <- Tail Guard -> Free Tail Guard either (not shared Guard)
777 // X 1 -> Don't free last page (need a new Guard)
778 // (it'll be turned into a Guard page later)
779 // --------------------
782 GuardPage
= Memory
+ EFI_PAGES_TO_SIZE (NumberOfPages
);
783 GuardBitmap
= GetGuardedMemoryBits (GuardPage
, 2);
784 if ((GuardBitmap
& BIT0
) == 0) {
786 // Tail Guard exists.
788 if ((GuardBitmap
& BIT1
) == 0) {
790 // If the tail Guard is not a head Guard of adjacent memory block,
791 // free it; otherwise, keep it.
793 UnsetGuardPage (GuardPage
);
797 // Pages after memory to free are still in Guard. It's a partial free
798 // case. We need to keep one page to be a head Guard.
800 SetGuardPage (GuardPage
- EFI_PAGES_TO_SIZE (1));
804 // No matter what, we just clear the mark of the Guarded memory.
806 ClearGuardedMemoryBits(Memory
, NumberOfPages
);
810 Adjust address of free memory according to existing and/or required Guard.
812 This function will check if there're existing Guard pages of adjacent
813 memory blocks, and try to use it as the Guard page of the memory to be
816 @param[in] Start Start address of free memory block.
817 @param[in] Size Size of free memory block.
818 @param[in] SizeRequested Size of memory to allocate.
820 @return The end address of memory block found.
821 @return 0 if no enough space for the required size of memory and its Guard.
827 IN UINT64 SizeRequested
833 // UEFI spec requires that allocated pool must be 8-byte aligned. If it's
834 // indicated to put the pool near the Tail Guard, we need extra bytes to
835 // make sure alignment of the returned pool address.
837 if ((PcdGet8 (PcdHeapGuardPropertyMask
) & BIT7
) == 0) {
838 SizeRequested
= ALIGN_VALUE(SizeRequested
, 8);
841 Target
= Start
+ Size
- SizeRequested
;
842 ASSERT (Target
>= Start
);
847 if (!IsGuardPage (Start
+ Size
)) {
848 // No Guard at tail to share. One more page is needed.
849 Target
-= EFI_PAGES_TO_SIZE (1);
853 if (Target
< Start
) {
858 if (Target
== Start
) {
859 if (!IsGuardPage (Target
- EFI_PAGES_TO_SIZE (1))) {
860 // No enough space for a new head Guard if no Guard at head to share.
865 // OK, we have enough pages for memory and its Guards. Return the End of the
867 return Target
+ SizeRequested
- 1;
871 Adjust the start address and number of pages to free according to Guard.
873 The purpose of this function is to keep the shared Guard page with adjacent
874 memory block if it's still in guard, or free it if no more sharing. Another
875 is to reserve pages as Guard pages in partial page free situation.
877 @param[in,out] Memory Base address of memory to free.
878 @param[in,out] NumberOfPages Size of memory to free.
884 IN OUT EFI_PHYSICAL_ADDRESS
*Memory
,
885 IN OUT UINTN
*NumberOfPages
888 EFI_PHYSICAL_ADDRESS Start
;
889 EFI_PHYSICAL_ADDRESS MemoryToTest
;
893 if (Memory
== NULL
|| NumberOfPages
== NULL
|| *NumberOfPages
== 0) {
898 PagesToFree
= *NumberOfPages
;
901 // Head Guard must be one page before, if any.
904 // -------------------
905 // Head Guard -> 0 1 -> Don't free Head Guard (shared Guard)
906 // Head Guard -> 0 0 -> Free Head Guard either (not shared Guard)
907 // 1 X -> Don't free first page (need a new Guard)
908 // (it'll be turned into a Guard page later)
909 // -------------------
912 MemoryToTest
= Start
- EFI_PAGES_TO_SIZE (2);
913 GuardBitmap
= GetGuardedMemoryBits (MemoryToTest
, 2);
914 if ((GuardBitmap
& BIT1
) == 0) {
916 // Head Guard exists.
918 if ((GuardBitmap
& BIT0
) == 0) {
920 // If the head Guard is not a tail Guard of adjacent memory block,
921 // free it; otherwise, keep it.
923 Start
-= EFI_PAGES_TO_SIZE (1);
928 // No Head Guard, and pages before memory to free are still in Guard. It's a
929 // partial free case. We need to keep one page to be a tail Guard.
931 Start
+= EFI_PAGES_TO_SIZE (1);
936 // Tail Guard must be the page after this memory block to free, if any.
939 // --------------------
940 // 1 0 <- Tail Guard -> Don't free Tail Guard (shared Guard)
941 // 0 0 <- Tail Guard -> Free Tail Guard either (not shared Guard)
942 // X 1 -> Don't free last page (need a new Guard)
943 // (it'll be turned into a Guard page later)
944 // --------------------
947 MemoryToTest
= Start
+ EFI_PAGES_TO_SIZE (PagesToFree
);
948 GuardBitmap
= GetGuardedMemoryBits (MemoryToTest
, 2);
949 if ((GuardBitmap
& BIT0
) == 0) {
951 // Tail Guard exists.
953 if ((GuardBitmap
& BIT1
) == 0) {
955 // If the tail Guard is not a head Guard of adjacent memory block,
956 // free it; otherwise, keep it.
960 } else if (PagesToFree
> 0) {
962 // No Tail Guard, and pages after memory to free are still in Guard. It's a
963 // partial free case. We need to keep one page to be a head Guard.
969 *NumberOfPages
= PagesToFree
;
973 Adjust the base and number of pages to really allocate according to Guard.
975 @param[in,out] Memory Base address of free memory.
976 @param[in,out] NumberOfPages Size of memory to allocate.
982 IN OUT EFI_PHYSICAL_ADDRESS
*Memory
,
983 IN OUT UINTN
*NumberOfPages
987 // FindFreePages() has already taken the Guard into account. It's safe to
988 // adjust the start address and/or number of pages here, to make sure that
989 // the Guards are also "allocated".
991 if (!IsGuardPage (*Memory
+ EFI_PAGES_TO_SIZE (*NumberOfPages
))) {
992 // No tail Guard, add one.
996 if (!IsGuardPage (*Memory
- EFI_PAGE_SIZE
)) {
997 // No head Guard, add one.
998 *Memory
-= EFI_PAGE_SIZE
;
1004 Adjust the pool head position to make sure the Guard page is adjavent to
1005 pool tail or pool head.
1007 @param[in] Memory Base address of memory allocated.
1008 @param[in] NoPages Number of pages actually allocated.
1009 @param[in] Size Size of memory requested.
1010 (plus pool head/tail overhead)
1012 @return Address of pool head.
1016 IN EFI_PHYSICAL_ADDRESS Memory
,
1021 if (Memory
== 0 || (PcdGet8 (PcdHeapGuardPropertyMask
) & BIT7
) != 0) {
1023 // Pool head is put near the head Guard
1025 return (VOID
*)(UINTN
)Memory
;
1029 // Pool head is put near the tail Guard
1031 Size
= ALIGN_VALUE (Size
, 8);
1032 return (VOID
*)(UINTN
)(Memory
+ EFI_PAGES_TO_SIZE (NoPages
) - Size
);
1036 Get the page base address according to pool head address.
1038 @param[in] Memory Head address of pool to free.
1040 @return Address of pool head.
1044 IN EFI_PHYSICAL_ADDRESS Memory
1047 if (Memory
== 0 || (PcdGet8 (PcdHeapGuardPropertyMask
) & BIT7
) != 0) {
1049 // Pool head is put near the head Guard
1051 return (VOID
*)(UINTN
)Memory
;
1055 // Pool head is put near the tail Guard
1057 return (VOID
*)(UINTN
)(Memory
& ~EFI_PAGE_MASK
);
1061 Allocate or free guarded memory.
1063 @param[in] Start Start address of memory to allocate or free.
1064 @param[in] NumberOfPages Memory size in pages.
1065 @param[in] NewType Memory type to convert to.
1070 CoreConvertPagesWithGuard (
1072 IN UINTN NumberOfPages
,
1073 IN EFI_MEMORY_TYPE NewType
1079 if (NewType
== EfiConventionalMemory
) {
1081 OldPages
= NumberOfPages
;
1083 AdjustMemoryF (&Start
, &NumberOfPages
);
1085 // It's safe to unset Guard page inside memory lock because there should
1086 // be no memory allocation occurred in updating memory page attribute at
1087 // this point. And unsetting Guard page before free will prevent Guard
1088 // page just freed back to pool from being allocated right away before
1089 // marking it usable (from non-present to present).
1091 UnsetGuardForMemory (OldStart
, OldPages
);
1092 if (NumberOfPages
== 0) {
1096 AdjustMemoryA (&Start
, &NumberOfPages
);
1099 return CoreConvertPages (Start
, NumberOfPages
, NewType
);
1103 Set all Guard pages which cannot be set before CPU Arch Protocol installed.
1110 UINTN Entries
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1111 UINTN Shifts
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1112 UINTN Indices
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1113 UINT64 Tables
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1114 UINT64 Addresses
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1122 if (mGuardedMemoryMap
== 0 ||
1124 mMapLevel
> GUARDED_HEAP_MAP_TABLE_DEPTH
) {
1128 CopyMem (Entries
, mLevelMask
, sizeof (Entries
));
1129 CopyMem (Shifts
, mLevelShift
, sizeof (Shifts
));
1131 SetMem (Tables
, sizeof(Tables
), 0);
1132 SetMem (Addresses
, sizeof(Addresses
), 0);
1133 SetMem (Indices
, sizeof(Indices
), 0);
1135 Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
1136 Tables
[Level
] = mGuardedMemoryMap
;
1141 DumpGuardedMemoryBitmap ();
1145 if (Indices
[Level
] > Entries
[Level
]) {
1150 TableEntry
= ((UINT64
*)(UINTN
)(Tables
[Level
]))[Indices
[Level
]];
1151 Address
= Addresses
[Level
];
1153 if (TableEntry
== 0) {
1157 } else if (Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1160 Tables
[Level
] = TableEntry
;
1161 Addresses
[Level
] = Address
;
1169 while (Index
< GUARDED_HEAP_MAP_ENTRY_BITS
) {
1170 if ((TableEntry
& 1) == 1) {
1174 GuardPage
= Address
- EFI_PAGE_SIZE
;
1179 GuardPage
= Address
;
1186 if (GuardPage
!= 0) {
1187 SetGuardPage (GuardPage
);
1190 if (TableEntry
== 0) {
1194 TableEntry
= RShiftU64 (TableEntry
, 1);
1195 Address
+= EFI_PAGE_SIZE
;
1201 if (Level
< (GUARDED_HEAP_MAP_TABLE_DEPTH
- (INTN
)mMapLevel
)) {
1205 Indices
[Level
] += 1;
1206 Address
= (Level
== 0) ? 0 : Addresses
[Level
- 1];
1207 Addresses
[Level
] = Address
| LShiftU64(Indices
[Level
], Shifts
[Level
]);
1213 Find the address of top-most guarded free page.
1215 @param[out] Address Start address of top-most guarded free page.
1220 GetLastGuardedFreePageAddress (
1221 OUT EFI_PHYSICAL_ADDRESS
*Address
1224 EFI_PHYSICAL_ADDRESS AddressGranularity
;
1225 EFI_PHYSICAL_ADDRESS BaseAddress
;
1230 ASSERT (mMapLevel
>= 1);
1233 Map
= mGuardedMemoryMap
;
1234 for (Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
1235 Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
;
1237 AddressGranularity
= LShiftU64 (1, mLevelShift
[Level
]);
1240 // Find the non-NULL entry at largest index.
1242 for (Index
= (INTN
)mLevelMask
[Level
]; Index
>= 0 ; --Index
) {
1243 if (((UINT64
*)(UINTN
)Map
)[Index
] != 0) {
1244 BaseAddress
+= MultU64x32 (AddressGranularity
, (UINT32
)Index
);
1245 Map
= ((UINT64
*)(UINTN
)Map
)[Index
];
1252 // Find the non-zero MSB then get the page address.
1255 Map
= RShiftU64 (Map
, 1);
1256 BaseAddress
+= EFI_PAGES_TO_SIZE (1);
1259 *Address
= BaseAddress
;
1265 @param[in] BaseAddress Base address of just freed pages.
1266 @param[in] Pages Number of freed pages.
1272 IN EFI_PHYSICAL_ADDRESS BaseAddress
,
1276 SetGuardedMemoryBits (BaseAddress
, Pages
);
1280 Record freed pages as well as mark them as not-present.
1282 @param[in] BaseAddress Base address of just freed pages.
1283 @param[in] Pages Number of freed pages.
1290 IN EFI_PHYSICAL_ADDRESS BaseAddress
,
1297 // Legacy memory lower than 1MB might be accessed with no allocation. Leave
1300 if (BaseAddress
< BASE_1MB
) {
1304 MarkFreedPages (BaseAddress
, Pages
);
1307 // Set flag to make sure allocating memory without GUARD for page table
1308 // operation; otherwise infinite loops could be caused.
1312 // Note: This might overwrite other attributes needed by other features,
1313 // such as NX memory protection.
1315 Status
= gCpu
->SetMemoryAttributes (
1318 EFI_PAGES_TO_SIZE (Pages
),
1322 // Normally we should ASSERT the returned Status. But there might be memory
1323 // alloc/free involved in SetMemoryAttributes(), which might fail this
1324 // calling. It's rare case so it's OK to let a few tiny holes be not-guarded.
1326 if (EFI_ERROR (Status
)) {
1327 DEBUG ((DEBUG_WARN
, "Failed to guard freed pages: %p (%lu)\n", BaseAddress
, (UINT64
)Pages
));
1329 mOnGuarding
= FALSE
;
1334 Record freed pages as well as mark them as not-present, if enabled.
1336 @param[in] BaseAddress Base address of just freed pages.
1337 @param[in] Pages Number of freed pages.
1343 GuardFreedPagesChecked (
1344 IN EFI_PHYSICAL_ADDRESS BaseAddress
,
1348 if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED
)) {
1349 GuardFreedPages (BaseAddress
, Pages
);
1354 Mark all pages freed before CPU Arch Protocol as not-present.
1358 GuardAllFreedPages (
1362 UINTN Entries
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1363 UINTN Shifts
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1364 UINTN Indices
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1365 UINT64 Tables
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1366 UINT64 Addresses
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1372 UINTN GuardPageNumber
;
1374 if (mGuardedMemoryMap
== 0 ||
1376 mMapLevel
> GUARDED_HEAP_MAP_TABLE_DEPTH
) {
1380 CopyMem (Entries
, mLevelMask
, sizeof (Entries
));
1381 CopyMem (Shifts
, mLevelShift
, sizeof (Shifts
));
1383 SetMem (Tables
, sizeof(Tables
), 0);
1384 SetMem (Addresses
, sizeof(Addresses
), 0);
1385 SetMem (Indices
, sizeof(Indices
), 0);
1387 Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
1388 Tables
[Level
] = mGuardedMemoryMap
;
1390 GuardPage
= (UINT64
)-1;
1391 GuardPageNumber
= 0;
1394 if (Indices
[Level
] > Entries
[Level
]) {
1398 TableEntry
= ((UINT64
*)(UINTN
)(Tables
[Level
]))[Indices
[Level
]];
1399 Address
= Addresses
[Level
];
1401 if (Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1403 Tables
[Level
] = TableEntry
;
1404 Addresses
[Level
] = Address
;
1410 while (BitIndex
!= 0) {
1411 if ((TableEntry
& BitIndex
) != 0) {
1412 if (GuardPage
== (UINT64
)-1) {
1413 GuardPage
= Address
;
1416 } else if (GuardPageNumber
> 0) {
1417 GuardFreedPages (GuardPage
, GuardPageNumber
);
1418 GuardPageNumber
= 0;
1419 GuardPage
= (UINT64
)-1;
1422 if (TableEntry
== 0) {
1426 Address
+= EFI_PAGES_TO_SIZE (1);
1427 BitIndex
= LShiftU64 (BitIndex
, 1);
1432 if (Level
< (GUARDED_HEAP_MAP_TABLE_DEPTH
- (INTN
)mMapLevel
)) {
1436 Indices
[Level
] += 1;
1437 Address
= (Level
== 0) ? 0 : Addresses
[Level
- 1];
1438 Addresses
[Level
] = Address
| LShiftU64 (Indices
[Level
], Shifts
[Level
]);
1443 // Update the maximum address of freed page which can be used for memory
1444 // promotion upon out-of-memory-space.
1446 GetLastGuardedFreePageAddress (&Address
);
1448 mLastPromotedPage
= Address
;
1453 This function checks to see if the given memory map descriptor in a memory map
1454 can be merged with any guarded free pages.
1456 @param MemoryMapEntry A pointer to a descriptor in MemoryMap.
1457 @param MaxAddress Maximum address to stop the merge.
1464 IN EFI_MEMORY_DESCRIPTOR
*MemoryMapEntry
,
1465 IN EFI_PHYSICAL_ADDRESS MaxAddress
1468 EFI_PHYSICAL_ADDRESS EndAddress
;
1472 if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED
) ||
1473 MemoryMapEntry
->Type
>= EfiMemoryMappedIO
) {
1478 Pages
= EFI_SIZE_TO_PAGES (MaxAddress
- MemoryMapEntry
->PhysicalStart
);
1479 Pages
-= MemoryMapEntry
->NumberOfPages
;
1482 EndAddress
= MemoryMapEntry
->PhysicalStart
+
1483 EFI_PAGES_TO_SIZE (MemoryMapEntry
->NumberOfPages
);
1484 Bitmap
= GetGuardedMemoryBits (EndAddress
, GUARDED_HEAP_MAP_ENTRY_BITS
);
1487 if ((Bitmap
& 1) == 0) {
1492 MemoryMapEntry
->NumberOfPages
++;
1493 Bitmap
= RShiftU64 (Bitmap
, 1);
1498 Put part (at most 64 pages a time) guarded free pages back to free page pool.
1500 Freed memory guard is used to detect Use-After-Free (UAF) memory issue, which
1501 makes use of 'Used then throw away' way to detect any illegal access to freed
1502 memory. The thrown-away memory will be marked as not-present so that any access
1503 to those memory (after free) will be caught by page-fault exception.
1505 The problem is that this will consume lots of memory space. Once no memory
1506 left in pool to allocate, we have to restore part of the freed pages to their
1507 normal function. Otherwise the whole system will stop functioning.
1509 @param StartAddress Start address of promoted memory.
1510 @param EndAddress End address of promoted memory.
1512 @return TRUE Succeeded to promote memory.
1513 @return FALSE No free memory found.
1517 PromoteGuardedFreePages (
1518 OUT EFI_PHYSICAL_ADDRESS
*StartAddress
,
1519 OUT EFI_PHYSICAL_ADDRESS
*EndAddress
1523 UINTN AvailablePages
;
1525 EFI_PHYSICAL_ADDRESS Start
;
1527 if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED
)) {
1532 // Similar to memory allocation service, always search the freed pages in
1533 // descending direction.
1535 Start
= mLastPromotedPage
;
1537 while (AvailablePages
== 0) {
1538 Start
-= EFI_PAGES_TO_SIZE (GUARDED_HEAP_MAP_ENTRY_BITS
);
1540 // If the address wraps around, try the really freed pages at top.
1542 if (Start
> mLastPromotedPage
) {
1543 GetLastGuardedFreePageAddress (&Start
);
1544 ASSERT (Start
!= 0);
1545 Start
-= EFI_PAGES_TO_SIZE (GUARDED_HEAP_MAP_ENTRY_BITS
);
1548 Bitmap
= GetGuardedMemoryBits (Start
, GUARDED_HEAP_MAP_ENTRY_BITS
);
1549 while (Bitmap
> 0) {
1550 if ((Bitmap
& 1) != 0) {
1552 } else if (AvailablePages
== 0) {
1553 Start
+= EFI_PAGES_TO_SIZE (1);
1558 Bitmap
= RShiftU64 (Bitmap
, 1);
1562 if (AvailablePages
) {
1563 DEBUG ((DEBUG_INFO
, "Promoted pages: %lX (%lx)\r\n", Start
, (UINT64
)AvailablePages
));
1564 ClearGuardedMemoryBits (Start
, AvailablePages
);
1568 // Set flag to make sure allocating memory without GUARD for page table
1569 // operation; otherwise infinite loops could be caused.
1572 Status
= gCpu
->SetMemoryAttributes (gCpu
, Start
, EFI_PAGES_TO_SIZE(AvailablePages
), 0);
1573 ASSERT_EFI_ERROR (Status
);
1574 mOnGuarding
= FALSE
;
1577 mLastPromotedPage
= Start
;
1578 *StartAddress
= Start
;
1579 *EndAddress
= Start
+ EFI_PAGES_TO_SIZE (AvailablePages
) - 1;
1587 Notify function used to set all Guard pages before CPU Arch Protocol installed.
1590 HeapGuardCpuArchProtocolNotify (
1594 ASSERT (gCpu
!= NULL
);
1596 if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE
|GUARD_HEAP_TYPE_POOL
) &&
1597 IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED
)) {
1598 DEBUG ((DEBUG_ERROR
, "Heap guard and freed memory guard cannot be enabled at the same time.\n"));
1602 if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE
|GUARD_HEAP_TYPE_POOL
)) {
1603 SetAllGuardPages ();
1606 if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED
)) {
1607 GuardAllFreedPages ();
1612 Helper function to convert a UINT64 value in binary to a string.
1614 @param[in] Value Value of a UINT64 integer.
1615 @param[out] BinString String buffer to contain the conversion result.
1622 OUT CHAR8
*BinString
1627 if (BinString
== NULL
) {
1631 for (Index
= 64; Index
> 0; --Index
) {
1632 BinString
[Index
- 1] = '0' + (Value
& 1);
1633 Value
= RShiftU64 (Value
, 1);
1635 BinString
[64] = '\0';
1639 Dump the guarded memory bit map.
1643 DumpGuardedMemoryBitmap (
1647 UINTN Entries
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1648 UINTN Shifts
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1649 UINTN Indices
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1650 UINT64 Tables
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1651 UINT64 Addresses
[GUARDED_HEAP_MAP_TABLE_DEPTH
];
1656 CHAR8 String
[GUARDED_HEAP_MAP_ENTRY_BITS
+ 1];
1660 if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_ALL
)) {
1664 if (mGuardedMemoryMap
== 0 ||
1666 mMapLevel
> GUARDED_HEAP_MAP_TABLE_DEPTH
) {
1670 Ruler1
= " 3 2 1 0";
1671 Ruler2
= "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";
1673 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "============================="
1674 " Guarded Memory Bitmap "
1675 "==============================\r\n"));
1676 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, " %a\r\n", Ruler1
));
1677 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, " %a\r\n", Ruler2
));
1679 CopyMem (Entries
, mLevelMask
, sizeof (Entries
));
1680 CopyMem (Shifts
, mLevelShift
, sizeof (Shifts
));
1682 SetMem (Indices
, sizeof(Indices
), 0);
1683 SetMem (Tables
, sizeof(Tables
), 0);
1684 SetMem (Addresses
, sizeof(Addresses
), 0);
1686 Level
= GUARDED_HEAP_MAP_TABLE_DEPTH
- mMapLevel
;
1687 Tables
[Level
] = mGuardedMemoryMap
;
1692 if (Indices
[Level
] > Entries
[Level
]) {
1699 HEAP_GUARD_DEBUG_LEVEL
,
1700 "========================================="
1701 "=========================================\r\n"
1706 TableEntry
= ((UINT64
*)(UINTN
)Tables
[Level
])[Indices
[Level
]];
1707 Address
= Addresses
[Level
];
1709 if (TableEntry
== 0) {
1711 if (Level
== GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1712 if (RepeatZero
== 0) {
1713 Uint64ToBinString(TableEntry
, String
);
1714 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "%016lx: %a\r\n", Address
, String
));
1715 } else if (RepeatZero
== 1) {
1716 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "... : ...\r\n"));
1721 } else if (Level
< GUARDED_HEAP_MAP_TABLE_DEPTH
- 1) {
1724 Tables
[Level
] = TableEntry
;
1725 Addresses
[Level
] = Address
;
1734 Uint64ToBinString(TableEntry
, String
);
1735 DEBUG ((HEAP_GUARD_DEBUG_LEVEL
, "%016lx: %a\r\n", Address
, String
));
1740 if (Level
< (GUARDED_HEAP_MAP_TABLE_DEPTH
- (INTN
)mMapLevel
)) {
1744 Indices
[Level
] += 1;
1745 Address
= (Level
== 0) ? 0 : Addresses
[Level
- 1];
1746 Addresses
[Level
] = Address
| LShiftU64(Indices
[Level
], Shifts
[Level
]);