]> git.proxmox.com Git - mirror_edk2.git/commitdiff
MdeModulePkg/Core: add freed-memory guard feature
authorJian J Wang <jian.j.wang@intel.com>
Wed, 24 Oct 2018 04:47:45 +0000 (12:47 +0800)
committerJian J Wang <jian.j.wang@intel.com>
Fri, 26 Oct 2018 02:30:35 +0000 (10:30 +0800)
Freed-memory guard is used to detect UAF (Use-After-Free) memory issue
which is illegal access to memory which has been freed. The principle
behind is similar to pool guard feature, that is we'll turn all pool
memory allocation to page allocation and mark them to be not-present
once they are freed.

This also implies that, once a page is allocated and freed, it cannot
be re-allocated. This will bring another issue, which is that there's
risk that memory space will be used out. To address it, the memory
service add logic to put part (at most 64 pages a time) of freed pages
back into page pool, so that the memory service can still have memory
to allocate, when all memory space have been allocated once. This is
called memory promotion. The promoted pages are always from the eldest
pages which haven been freed.

This feature brings another problem is that memory map descriptors will
be increased enormously (200+ -> 2000+). One of change in this patch
is to update MergeMemoryMap() in file PropertiesTable.c to allow merge
freed pages back into the memory map. Now the number can stay at around
510.

Cc: Star Zeng <star.zeng@intel.com>
Cc: Michael D Kinney <michael.d.kinney@intel.com>
Cc: Jiewen Yao <jiewen.yao@intel.com>
Cc: Ruiyu Ni <ruiyu.ni@intel.com>
Cc: Laszlo Ersek <lersek@redhat.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Jian J Wang <jian.j.wang@intel.com>
Reviewed-by: Star Zeng <star.zeng@intel.com>
MdeModulePkg/Core/Dxe/Mem/HeapGuard.c
MdeModulePkg/Core/Dxe/Mem/HeapGuard.h
MdeModulePkg/Core/Dxe/Mem/Page.c
MdeModulePkg/Core/Dxe/Mem/Pool.c
MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
MdeModulePkg/Core/Dxe/Misc/PropertiesTable.c

index 663f969c0dc7c626d35d54c9379feb483189cda6..449a02265834b438f51de21939a370303a05010b 100644 (file)
@@ -44,6 +44,11 @@ GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH]
 GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH]\r
                                     = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS;\r
 \r
+//\r
+// Used for promoting freed but not used pages.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED EFI_PHYSICAL_ADDRESS mLastPromotedPage = BASE_4GB;\r
+\r
 /**\r
   Set corresponding bits in bitmap table to 1 according to the address.\r
 \r
@@ -379,7 +384,7 @@ ClearGuardedMemoryBits (
 \r
   @return An integer containing the guarded memory bitmap.\r
 **/\r
-UINTN\r
+UINT64\r
 GetGuardedMemoryBits (\r
   IN EFI_PHYSICAL_ADDRESS    Address,\r
   IN UINTN                   NumberOfPages\r
@@ -387,7 +392,7 @@ GetGuardedMemoryBits (
 {\r
   UINT64            *BitMap;\r
   UINTN             Bits;\r
-  UINT            Result;\r
+  UINT64            Result;\r
   UINTN             Shift;\r
   UINTN             BitsToUnitEnd;\r
 \r
@@ -660,15 +665,16 @@ IsPageTypeToGuard (
 /**\r
   Check to see if the heap guard is enabled for page and/or pool allocation.\r
 \r
+  @param[in]  GuardType   Specify the sub-type(s) of Heap Guard.\r
+\r
   @return TRUE/FALSE.\r
 **/\r
 BOOLEAN\r
 IsHeapGuardEnabled (\r
-  VOID\r
+  UINT8           GuardType\r
   )\r
 {\r
-  return IsMemoryTypeToGuard (EfiMaxMemoryType, AllocateAnyPages,\r
-                              GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_PAGE);\r
+  return IsMemoryTypeToGuard (EfiMaxMemoryType, AllocateAnyPages, GuardType);\r
 }\r
 \r
 /**\r
@@ -1203,6 +1209,380 @@ SetAllGuardPages (
   }\r
 }\r
 \r
+/**\r
+  Find the address of top-most guarded free page.\r
+\r
+  @param[out]  Address    Start address of top-most guarded free page.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+GetLastGuardedFreePageAddress (\r
+  OUT EFI_PHYSICAL_ADDRESS      *Address\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS    AddressGranularity;\r
+  EFI_PHYSICAL_ADDRESS    BaseAddress;\r
+  UINTN                   Level;\r
+  UINT64                  Map;\r
+  INTN                    Index;\r
+\r
+  ASSERT (mMapLevel >= 1);\r
+\r
+  BaseAddress = 0;\r
+  Map = mGuardedMemoryMap;\r
+  for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;\r
+       Level < GUARDED_HEAP_MAP_TABLE_DEPTH;\r
+       ++Level) {\r
+    AddressGranularity = LShiftU64 (1, mLevelShift[Level]);\r
+\r
+    //\r
+    // Find the non-NULL entry at largest index.\r
+    //\r
+    for (Index = (INTN)mLevelMask[Level]; Index >= 0 ; --Index) {\r
+      if (((UINT64 *)(UINTN)Map)[Index] != 0) {\r
+        BaseAddress += MultU64x32 (AddressGranularity, (UINT32)Index);\r
+        Map = ((UINT64 *)(UINTN)Map)[Index];\r
+        break;\r
+      }\r
+    }\r
+  }\r
+\r
+  //\r
+  // Find the non-zero MSB then get the page address.\r
+  //\r
+  while (Map != 0) {\r
+    Map = RShiftU64 (Map, 1);\r
+    BaseAddress += EFI_PAGES_TO_SIZE (1);\r
+  }\r
+\r
+  *Address = BaseAddress;\r
+}\r
+\r
+/**\r
+  Record freed pages.\r
+\r
+  @param[in]  BaseAddress   Base address of just freed pages.\r
+  @param[in]  Pages         Number of freed pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+MarkFreedPages (\r
+  IN EFI_PHYSICAL_ADDRESS     BaseAddress,\r
+  IN UINTN                    Pages\r
+  )\r
+{\r
+  SetGuardedMemoryBits (BaseAddress, Pages);\r
+}\r
+\r
+/**\r
+  Record freed pages as well as mark them as not-present.\r
+\r
+  @param[in]  BaseAddress   Base address of just freed pages.\r
+  @param[in]  Pages         Number of freed pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+GuardFreedPages (\r
+  IN  EFI_PHYSICAL_ADDRESS    BaseAddress,\r
+  IN  UINTN                   Pages\r
+  )\r
+{\r
+  EFI_STATUS      Status;\r
+\r
+  //\r
+  // Legacy memory lower than 1MB might be accessed with no allocation. Leave\r
+  // them alone.\r
+  //\r
+  if (BaseAddress < BASE_1MB) {\r
+    return;\r
+  }\r
+\r
+  MarkFreedPages (BaseAddress, Pages);\r
+  if (gCpu != NULL) {\r
+    //\r
+    // Set flag to make sure allocating memory without GUARD for page table\r
+    // operation; otherwise infinite loops could be caused.\r
+    //\r
+    mOnGuarding = TRUE;\r
+    //\r
+    // Note: This might overwrite other attributes needed by other features,\r
+    // such as NX memory protection.\r
+    //\r
+    Status = gCpu->SetMemoryAttributes (\r
+                     gCpu,\r
+                     BaseAddress,\r
+                     EFI_PAGES_TO_SIZE (Pages),\r
+                     EFI_MEMORY_RP\r
+                     );\r
+    //\r
+    // Normally we should ASSERT the returned Status. But there might be memory\r
+    // alloc/free involved in SetMemoryAttributes(), which might fail this\r
+    // calling. It's rare case so it's OK to let a few tiny holes be not-guarded.\r
+    //\r
+    if (EFI_ERROR (Status)) {\r
+      DEBUG ((DEBUG_WARN, "Failed to guard freed pages: %p (%lu)\n", BaseAddress, (UINT64)Pages));\r
+    }\r
+    mOnGuarding = FALSE;\r
+  }\r
+}\r
+\r
+/**\r
+  Record freed pages as well as mark them as not-present, if enabled.\r
+\r
+  @param[in]  BaseAddress   Base address of just freed pages.\r
+  @param[in]  Pages         Number of freed pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+GuardFreedPagesChecked (\r
+  IN  EFI_PHYSICAL_ADDRESS    BaseAddress,\r
+  IN  UINTN                   Pages\r
+  )\r
+{\r
+  if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) {\r
+    GuardFreedPages (BaseAddress, Pages);\r
+  }\r
+}\r
+\r
+/**\r
+  Mark all pages freed before CPU Arch Protocol as not-present.\r
+\r
+**/\r
+VOID\r
+GuardAllFreedPages (\r
+  VOID\r
+  )\r
+{\r
+  UINTN     Entries[GUARDED_HEAP_MAP_TABLE_DEPTH];\r
+  UINTN     Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH];\r
+  UINTN     Indices[GUARDED_HEAP_MAP_TABLE_DEPTH];\r
+  UINT64    Tables[GUARDED_HEAP_MAP_TABLE_DEPTH];\r
+  UINT64    Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH];\r
+  UINT64    TableEntry;\r
+  UINT64    Address;\r
+  UINT64    GuardPage;\r
+  INTN      Level;\r
+  UINTN     BitIndex;\r
+  UINTN     GuardPageNumber;\r
+\r
+  if (mGuardedMemoryMap == 0 ||\r
+      mMapLevel == 0 ||\r
+      mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) {\r
+    return;\r
+  }\r
+\r
+  CopyMem (Entries, mLevelMask, sizeof (Entries));\r
+  CopyMem (Shifts, mLevelShift, sizeof (Shifts));\r
+\r
+  SetMem (Tables, sizeof(Tables), 0);\r
+  SetMem (Addresses, sizeof(Addresses), 0);\r
+  SetMem (Indices, sizeof(Indices), 0);\r
+\r
+  Level           = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;\r
+  Tables[Level]   = mGuardedMemoryMap;\r
+  Address         = 0;\r
+  GuardPage       = (UINT64)-1;\r
+  GuardPageNumber = 0;\r
+\r
+  while (TRUE) {\r
+    if (Indices[Level] > Entries[Level]) {\r
+      Tables[Level] = 0;\r
+      Level        -= 1;\r
+    } else {\r
+      TableEntry  = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]];\r
+      Address     = Addresses[Level];\r
+\r
+      if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {\r
+        Level            += 1;\r
+        Tables[Level]     = TableEntry;\r
+        Addresses[Level]  = Address;\r
+        Indices[Level]    = 0;\r
+\r
+        continue;\r
+      } else {\r
+        BitIndex = 1;\r
+        while (BitIndex != 0) {\r
+          if ((TableEntry & BitIndex) != 0) {\r
+            if (GuardPage == (UINT64)-1) {\r
+              GuardPage = Address;\r
+            }\r
+            ++GuardPageNumber;\r
+          } else if (GuardPageNumber > 0) {\r
+            GuardFreedPages (GuardPage, GuardPageNumber);\r
+            GuardPageNumber = 0;\r
+            GuardPage       = (UINT64)-1;\r
+          }\r
+\r
+          if (TableEntry == 0) {\r
+            break;\r
+          }\r
+\r
+          Address += EFI_PAGES_TO_SIZE (1);\r
+          BitIndex = LShiftU64 (BitIndex, 1);\r
+        }\r
+      }\r
+    }\r
+\r
+    if (Level < (GUARDED_HEAP_MAP_TABLE_DEPTH - (INTN)mMapLevel)) {\r
+      break;\r
+    }\r
+\r
+    Indices[Level] += 1;\r
+    Address = (Level == 0) ? 0 : Addresses[Level - 1];\r
+    Addresses[Level] = Address | LShiftU64 (Indices[Level], Shifts[Level]);\r
+\r
+  }\r
+\r
+  //\r
+  // Update the maximum address of freed page which can be used for memory\r
+  // promotion upon out-of-memory-space.\r
+  //\r
+  GetLastGuardedFreePageAddress (&Address);\r
+  if (Address != 0) {\r
+    mLastPromotedPage = Address;\r
+  }\r
+}\r
+\r
+/**\r
+  This function checks to see if the given memory map descriptor in a memory map\r
+  can be merged with any guarded free pages.\r
+\r
+  @param  MemoryMapEntry    A pointer to a descriptor in MemoryMap.\r
+  @param  MaxAddress        Maximum address to stop the merge.\r
+\r
+  @return VOID\r
+\r
+**/\r
+VOID\r
+MergeGuardPages (\r
+  IN EFI_MEMORY_DESCRIPTOR      *MemoryMapEntry,\r
+  IN EFI_PHYSICAL_ADDRESS       MaxAddress\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS        EndAddress;\r
+  UINT64                      Bitmap;\r
+  INTN                        Pages;\r
+\r
+  if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) ||\r
+      MemoryMapEntry->Type >= EfiMemoryMappedIO) {\r
+    return;\r
+  }\r
+\r
+  Bitmap = 0;\r
+  Pages  = EFI_SIZE_TO_PAGES (MaxAddress - MemoryMapEntry->PhysicalStart);\r
+  Pages -= MemoryMapEntry->NumberOfPages;\r
+  while (Pages > 0) {\r
+    if (Bitmap == 0) {\r
+      EndAddress = MemoryMapEntry->PhysicalStart +\r
+                   EFI_PAGES_TO_SIZE (MemoryMapEntry->NumberOfPages);\r
+      Bitmap = GetGuardedMemoryBits (EndAddress, GUARDED_HEAP_MAP_ENTRY_BITS);\r
+    }\r
+\r
+    if ((Bitmap & 1) == 0) {\r
+      break;\r
+    }\r
+\r
+    Pages--;\r
+    MemoryMapEntry->NumberOfPages++;\r
+    Bitmap = RShiftU64 (Bitmap, 1);\r
+  }\r
+}\r
+\r
+/**\r
+  Put part (at most 64 pages a time) guarded free pages back to free page pool.\r
+\r
+  Freed memory guard is used to detect Use-After-Free (UAF) memory issue, which\r
+  makes use of 'Used then throw away' way to detect any illegal access to freed\r
+  memory. The thrown-away memory will be marked as not-present so that any access\r
+  to those memory (after free) will be caught by page-fault exception.\r
+\r
+  The problem is that this will consume lots of memory space. Once no memory\r
+  left in pool to allocate, we have to restore part of the freed pages to their\r
+  normal function. Otherwise the whole system will stop functioning.\r
+\r
+  @param  StartAddress    Start address of promoted memory.\r
+  @param  EndAddress      End address of promoted memory.\r
+\r
+  @return TRUE    Succeeded to promote memory.\r
+  @return FALSE   No free memory found.\r
+\r
+**/\r
+BOOLEAN\r
+PromoteGuardedFreePages (\r
+  OUT EFI_PHYSICAL_ADDRESS      *StartAddress,\r
+  OUT EFI_PHYSICAL_ADDRESS      *EndAddress\r
+  )\r
+{\r
+  EFI_STATUS              Status;\r
+  UINTN                   AvailablePages;\r
+  UINT64                  Bitmap;\r
+  EFI_PHYSICAL_ADDRESS    Start;\r
+\r
+  if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) {\r
+    return FALSE;\r
+  }\r
+\r
+  //\r
+  // Similar to memory allocation service, always search the freed pages in\r
+  // descending direction.\r
+  //\r
+  Start           = mLastPromotedPage;\r
+  AvailablePages  = 0;\r
+  while (AvailablePages == 0) {\r
+    Start -= EFI_PAGES_TO_SIZE (GUARDED_HEAP_MAP_ENTRY_BITS);\r
+    //\r
+    // If the address wraps around, try the really freed pages at top.\r
+    //\r
+    if (Start > mLastPromotedPage) {\r
+      GetLastGuardedFreePageAddress (&Start);\r
+      ASSERT (Start != 0);\r
+      Start -= EFI_PAGES_TO_SIZE (GUARDED_HEAP_MAP_ENTRY_BITS);\r
+    }\r
+\r
+    Bitmap = GetGuardedMemoryBits (Start, GUARDED_HEAP_MAP_ENTRY_BITS);\r
+    while (Bitmap > 0) {\r
+      if ((Bitmap & 1) != 0) {\r
+        ++AvailablePages;\r
+      } else if (AvailablePages == 0) {\r
+        Start += EFI_PAGES_TO_SIZE (1);\r
+      } else {\r
+        break;\r
+      }\r
+\r
+      Bitmap = RShiftU64 (Bitmap, 1);\r
+    }\r
+  }\r
+\r
+  if (AvailablePages) {\r
+    DEBUG ((DEBUG_INFO, "Promoted pages: %lX (%lx)\r\n", Start, (UINT64)AvailablePages));\r
+    ClearGuardedMemoryBits (Start, AvailablePages);\r
+\r
+    if (gCpu != NULL) {\r
+      //\r
+      // Set flag to make sure allocating memory without GUARD for page table\r
+      // operation; otherwise infinite loops could be caused.\r
+      //\r
+      mOnGuarding = TRUE;\r
+      Status = gCpu->SetMemoryAttributes (gCpu, Start, EFI_PAGES_TO_SIZE(AvailablePages), 0);\r
+      ASSERT_EFI_ERROR (Status);\r
+      mOnGuarding = FALSE;\r
+    }\r
+\r
+    mLastPromotedPage = Start;\r
+    *StartAddress     = Start;\r
+    *EndAddress       = Start + EFI_PAGES_TO_SIZE (AvailablePages) - 1;\r
+    return TRUE;\r
+  }\r
+\r
+  return FALSE;\r
+}\r
+\r
 /**\r
   Notify function used to set all Guard pages before CPU Arch Protocol installed.\r
 **/\r
@@ -1212,7 +1592,20 @@ HeapGuardCpuArchProtocolNotify (
   )\r
 {\r
   ASSERT (gCpu != NULL);\r
-  SetAllGuardPages ();\r
+\r
+  if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL) &&\r
+      IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) {\r
+    DEBUG ((DEBUG_ERROR, "Heap guard and freed memory guard cannot be enabled at the same time.\n"));\r
+    CpuDeadLoop ();\r
+  }\r
+\r
+  if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL)) {\r
+    SetAllGuardPages ();\r
+  }\r
+\r
+  if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED)) {\r
+    GuardAllFreedPages ();\r
+  }\r
 }\r
 \r
 /**\r
@@ -1264,6 +1657,10 @@ DumpGuardedMemoryBitmap (
   CHAR8     *Ruler1;\r
   CHAR8     *Ruler2;\r
 \r
+  if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_ALL)) {\r
+    return;\r
+  }\r
+\r
   if (mGuardedMemoryMap == 0 ||\r
       mMapLevel == 0 ||\r
       mMapLevel > GUARDED_HEAP_MAP_TABLE_DEPTH) {\r
index 8c34692439d37d37b6dd778ce589b0a5800635af..55a91ec098e69eb83efb914178b596b904d0ebe4 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   Data type, macros and function prototypes of heap guard feature.\r
 \r
-Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2017-2018, Intel Corporation. All rights reserved.<BR>\r
 This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
@@ -160,6 +160,9 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 //\r
 #define GUARD_HEAP_TYPE_PAGE        BIT0\r
 #define GUARD_HEAP_TYPE_POOL        BIT1\r
+#define GUARD_HEAP_TYPE_FREED       BIT4\r
+#define GUARD_HEAP_TYPE_ALL         \\r
+        (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_FREED)\r
 \r
 //\r
 // Debug message level\r
@@ -392,11 +395,13 @@ AdjustPoolHeadF (
 /**\r
   Check to see if the heap guard is enabled for page and/or pool allocation.\r
 \r
+  @param[in]  GuardType   Specify the sub-type(s) of Heap Guard.\r
+\r
   @return TRUE/FALSE.\r
 **/\r
 BOOLEAN\r
 IsHeapGuardEnabled (\r
-  VOID\r
+  UINT8           GuardType\r
   );\r
 \r
 /**\r
@@ -407,6 +412,62 @@ HeapGuardCpuArchProtocolNotify (
   VOID\r
   );\r
 \r
+/**\r
+  This function checks to see if the given memory map descriptor in a memory map\r
+  can be merged with any guarded free pages.\r
+\r
+  @param  MemoryMapEntry    A pointer to a descriptor in MemoryMap.\r
+  @param  MaxAddress        Maximum address to stop the merge.\r
+\r
+  @return VOID\r
+\r
+**/\r
+VOID\r
+MergeGuardPages (\r
+  IN EFI_MEMORY_DESCRIPTOR      *MemoryMapEntry,\r
+  IN EFI_PHYSICAL_ADDRESS       MaxAddress\r
+  );\r
+\r
+/**\r
+  Record freed pages as well as mark them as not-present, if enabled.\r
+\r
+  @param[in]  BaseAddress   Base address of just freed pages.\r
+  @param[in]  Pages         Number of freed pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+GuardFreedPagesChecked (\r
+  IN  EFI_PHYSICAL_ADDRESS    BaseAddress,\r
+  IN  UINTN                   Pages\r
+  );\r
+\r
+/**\r
+  Put part (at most 64 pages a time) guarded free pages back to free page pool.\r
+\r
+  Freed memory guard is used to detect Use-After-Free (UAF) memory issue, which\r
+  makes use of 'Used then throw away' way to detect any illegal access to freed\r
+  memory. The thrown-away memory will be marked as not-present so that any access\r
+  to those memory (after free) will be caught by page-fault exception.\r
+\r
+  The problem is that this will consume lots of memory space. Once no memory\r
+  left in pool to allocate, we have to restore part of the freed pages to their\r
+  normal function. Otherwise the whole system will stop functioning.\r
+\r
+  @param  StartAddress    Start address of promoted memory.\r
+  @param  EndAddress      End address of promoted memory.\r
+\r
+  @return TRUE    Succeeded to promote memory.\r
+  @return FALSE   No free memory found.\r
+\r
+**/\r
+BOOLEAN\r
+PromoteGuardedFreePages (\r
+  OUT EFI_PHYSICAL_ADDRESS      *StartAddress,\r
+  OUT EFI_PHYSICAL_ADDRESS      *EndAddress\r
+  );\r
+\r
 extern BOOLEAN mOnGuarding;\r
 \r
 #endif\r
index 3b4cc08e7cec9d60454540443635994440fd26d4..961c5b833546b73a13d7e12511874d7681f09fd4 100644 (file)
@@ -401,9 +401,12 @@ PromoteMemoryResource (
   VOID\r
   )\r
 {\r
-  LIST_ENTRY         *Link;\r
-  EFI_GCD_MAP_ENTRY  *Entry;\r
-  BOOLEAN            Promoted;\r
+  LIST_ENTRY                        *Link;\r
+  EFI_GCD_MAP_ENTRY                 *Entry;\r
+  BOOLEAN                           Promoted;\r
+  EFI_PHYSICAL_ADDRESS              StartAddress;\r
+  EFI_PHYSICAL_ADDRESS              EndAddress;\r
+  EFI_GCD_MEMORY_SPACE_DESCRIPTOR   Descriptor;\r
 \r
   DEBUG ((DEBUG_PAGE, "Promote the memory resource\n"));\r
 \r
@@ -451,6 +454,24 @@ PromoteMemoryResource (
 \r
   CoreReleaseGcdMemoryLock ();\r
 \r
+  if (!Promoted) {\r
+    //\r
+    // If freed-memory guard is enabled, we could promote pages from\r
+    // guarded free pages.\r
+    //\r
+    Promoted = PromoteGuardedFreePages (&StartAddress, &EndAddress);\r
+    if (Promoted) {\r
+      CoreGetMemorySpaceDescriptor (StartAddress, &Descriptor);\r
+      CoreAddRange (\r
+        EfiConventionalMemory,\r
+        StartAddress,\r
+        EndAddress,\r
+        Descriptor.Capabilities & ~(EFI_MEMORY_PRESENT | EFI_MEMORY_INITIALIZED |\r
+                                    EFI_MEMORY_TESTED | EFI_MEMORY_RUNTIME)\r
+        );\r
+    }\r
+  }\r
+\r
   return Promoted;\r
 }\r
 /**\r
@@ -896,9 +917,15 @@ CoreConvertPagesEx (
     }\r
 \r
     //\r
-    // Add our new range in\r
+    // Add our new range in. Don't do this for freed pages if freed-memory\r
+    // guard is enabled.\r
     //\r
-    CoreAddRange (MemType, Start, RangeEnd, Attribute);\r
+    if (!IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) ||\r
+        !ChangingType ||\r
+        MemType != EfiConventionalMemory) {\r
+      CoreAddRange (MemType, Start, RangeEnd, Attribute);\r
+    }\r
+\r
     if (ChangingType && (MemType == EfiConventionalMemory)) {\r
       //\r
       // Avoid calling DEBUG_CLEAR_MEMORY() for an address of 0 because this\r
@@ -1514,6 +1541,7 @@ CoreFreePages (
 \r
   Status = CoreInternalFreePages (Memory, NumberOfPages, &MemoryType);\r
   if (!EFI_ERROR (Status)) {\r
+    GuardFreedPagesChecked (Memory, NumberOfPages);\r
     CoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
       MemoryProfileActionFreePages,\r
@@ -1908,9 +1936,7 @@ Done:
   *MemoryMapSize = BufferSize;\r
 \r
   DEBUG_CODE (\r
-    if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {\r
-      DumpGuardedMemoryBitmap ();\r
-    }\r
+    DumpGuardedMemoryBitmap ();\r
   );\r
 \r
   return Status;\r
index 1ff2061f7f71e9b7da4fafefc320a68323a6bd97..b9182ea8070503705aabd524138d6da630e5952c 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   UEFI Memory pool management functions.\r
 \r
-Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>\r
 This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
@@ -26,7 +26,8 @@ typedef struct {
 } POOL_FREE;\r
 \r
 \r
-#define POOL_HEAD_SIGNATURE   SIGNATURE_32('p','h','d','0')\r
+#define POOL_HEAD_SIGNATURE       SIGNATURE_32('p','h','d','0')\r
+#define POOLPAGE_HEAD_SIGNATURE   SIGNATURE_32('p','h','d','1')\r
 typedef struct {\r
   UINT32          Signature;\r
   UINT32          Reserved;\r
@@ -367,6 +368,7 @@ CoreAllocatePoolI (
   UINTN       NoPages;\r
   UINTN       Granularity;\r
   BOOLEAN     HasPoolTail;\r
+  BOOLEAN     PageAsPool;\r
 \r
   ASSERT_LOCKED (&mPoolMemoryLock);\r
 \r
@@ -386,6 +388,7 @@ CoreAllocatePoolI (
 \r
   HasPoolTail  = !(NeedGuard &&\r
                    ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));\r
+  PageAsPool = (IsHeapGuardEnabled (GUARD_HEAP_TYPE_FREED) && !mOnGuarding);\r
 \r
   //\r
   // Adjusting the Size to be of proper alignment so that\r
@@ -406,7 +409,7 @@ CoreAllocatePoolI (
   // If allocation is over max size, just allocate pages for the request\r
   // (slow)\r
   //\r
-  if (Index >= SIZE_TO_LIST (Granularity) || NeedGuard) {\r
+  if (Index >= SIZE_TO_LIST (Granularity) || NeedGuard || PageAsPool) {\r
     if (!HasPoolTail) {\r
       Size -= sizeof (POOL_TAIL);\r
     }\r
@@ -498,7 +501,7 @@ Done:
     //\r
     // If we have a pool buffer, fill in the header & tail info\r
     //\r
-    Head->Signature = POOL_HEAD_SIGNATURE;\r
+    Head->Signature = (PageAsPool) ? POOLPAGE_HEAD_SIGNATURE : POOL_HEAD_SIGNATURE;\r
     Head->Size      = Size;\r
     Head->Type      = (EFI_MEMORY_TYPE) PoolType;\r
     Buffer          = Head->Data;\r
@@ -615,6 +618,7 @@ CoreFreePoolPagesI (
   CoreFreePoolPages (Memory, NoPages);\r
   CoreReleaseMemoryLock ();\r
 \r
+  GuardFreedPagesChecked (Memory, NoPages);\r
   ApplyMemoryProtectionPolicy (PoolType, EfiConventionalMemory,\r
     (EFI_PHYSICAL_ADDRESS)(UINTN)Memory, EFI_PAGES_TO_SIZE (NoPages));\r
 }\r
@@ -685,15 +689,19 @@ CoreFreePoolI (
   UINTN       Granularity;\r
   BOOLEAN     IsGuarded;\r
   BOOLEAN     HasPoolTail;\r
+  BOOLEAN     PageAsPool;\r
 \r
   ASSERT(Buffer != NULL);\r
   //\r
   // Get the head & tail of the pool entry\r
   //\r
-  Head = CR (Buffer, POOL_HEAD, Data, POOL_HEAD_SIGNATURE);\r
+  Head = BASE_CR (Buffer, POOL_HEAD, Data);\r
   ASSERT(Head != NULL);\r
 \r
-  if (Head->Signature != POOL_HEAD_SIGNATURE) {\r
+  if (Head->Signature != POOL_HEAD_SIGNATURE &&\r
+      Head->Signature != POOLPAGE_HEAD_SIGNATURE) {\r
+    ASSERT (Head->Signature == POOL_HEAD_SIGNATURE ||\r
+            Head->Signature == POOLPAGE_HEAD_SIGNATURE);\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
@@ -701,6 +709,7 @@ CoreFreePoolI (
                 IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Head);\r
   HasPoolTail = !(IsGuarded &&\r
                   ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));\r
+  PageAsPool = (Head->Signature == POOLPAGE_HEAD_SIGNATURE);\r
 \r
   if (HasPoolTail) {\r
     Tail = HEAD_TO_TAIL (Head);\r
@@ -757,7 +766,7 @@ CoreFreePoolI (
   //\r
   // If it's not on the list, it must be pool pages\r
   //\r
-  if (Index >= SIZE_TO_LIST (Granularity) || IsGuarded) {\r
+  if (Index >= SIZE_TO_LIST (Granularity) || IsGuarded || PageAsPool) {\r
 \r
     //\r
     // Return the memory pages back to free memory\r
index fa8f8fe91ac7a8e9f7f5e9805bf2ac63c77f4d5e..6298b67db1676288d80db4a92001665993968bef 100644 (file)
@@ -1250,7 +1250,7 @@ ApplyMemoryProtectionPolicy (
   // Don't overwrite Guard pages, which should be the first and/or last page,\r
   // if any.\r
   //\r
-  if (IsHeapGuardEnabled ()) {\r
+  if (IsHeapGuardEnabled (GUARD_HEAP_TYPE_PAGE|GUARD_HEAP_TYPE_POOL)) {\r
     if (IsGuardPage (Memory))  {\r
       Memory += EFI_PAGE_SIZE;\r
       Length -= EFI_PAGE_SIZE;\r
index 05eb4f422b2fc39103351ed3ff9eee3b99fd04cf..04cfb2dab2d2af4e135a72ffb85890da83eb3a15 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   UEFI PropertiesTable support\r
 \r
-Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.<BR>\r
+Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.<BR>\r
 This program and the accompanying materials\r
 are licensed and made available under the terms and conditions of the BSD License\r
 which accompanies this distribution.  The full text of the license may be found at\r
@@ -32,6 +32,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 #include <Guid/PropertiesTable.h>\r
 \r
 #include "DxeMain.h"\r
+#include "HeapGuard.h"\r
 \r
 #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \\r
   ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))\r
@@ -205,16 +206,13 @@ MergeMemoryMap (
     NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);\r
 \r
     do {\r
-      MemoryBlockLength = (UINT64) (EfiPagesToSize (MemoryMapEntry->NumberOfPages));\r
+      MergeGuardPages (NewMemoryMapEntry, NextMemoryMapEntry->PhysicalStart);\r
+      MemoryBlockLength = (UINT64) (EfiPagesToSize (NewMemoryMapEntry->NumberOfPages));\r
       if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) &&\r
-          (MemoryMapEntry->Type == NextMemoryMapEntry->Type) &&\r
-          (MemoryMapEntry->Attribute == NextMemoryMapEntry->Attribute) &&\r
-          ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) {\r
-        MemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;\r
-        if (NewMemoryMapEntry != MemoryMapEntry) {\r
-          NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;\r
-        }\r
-\r
+          (NewMemoryMapEntry->Type == NextMemoryMapEntry->Type) &&\r
+          (NewMemoryMapEntry->Attribute == NextMemoryMapEntry->Attribute) &&\r
+          ((NewMemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) {\r
+        NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages;\r
         NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize);\r
         continue;\r
       } else {\r