]> git.proxmox.com Git - mirror_edk2.git/commitdiff
MdeModulePkg: Fix unix style of EOL
authorJian J Wang <jian.j.wang@intel.com>
Mon, 20 Nov 2017 08:08:28 +0000 (16:08 +0800)
committerHao Wu <hao.a.wu@intel.com>
Tue, 21 Nov 2017 12:24:37 +0000 (20:24 +0800)
Cc: Wu Hao <hao.a.wu@intel.com>
Cc: Star Zeng <star.zeng@intel.com>
Cc: Eric Dong <eric.dong@intel.com>
Contributed-under: TianoCore Contribution Agreement 1.1
Signed-off-by: Jian J Wang <jian.j.wang@intel.com>
Reviewed-by: Hao Wu <hao.a.wu@intel.com>
19 files changed:
MdeModulePkg/Core/Dxe/DxeMain.inf
MdeModulePkg/Core/Dxe/Mem/HeapGuard.c
MdeModulePkg/Core/Dxe/Mem/HeapGuard.h
MdeModulePkg/Core/Dxe/Mem/Imem.h
MdeModulePkg/Core/Dxe/Mem/Page.c
MdeModulePkg/Core/Dxe/Mem/Pool.c
MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c
MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c
MdeModulePkg/Core/PiSmmCore/HeapGuard.c
MdeModulePkg/Core/PiSmmCore/HeapGuard.h
MdeModulePkg/Core/PiSmmCore/Page.c
MdeModulePkg/Core/PiSmmCore/PiSmmCore.c
MdeModulePkg/Core/PiSmmCore/PiSmmCore.h
MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf
MdeModulePkg/Core/PiSmmCore/Pool.c
MdeModulePkg/Include/Protocol/SmmMemoryAttribute.h
MdeModulePkg/MdeModulePkg.dec
MdeModulePkg/MdeModulePkg.uni

index 9793333a4491255e1a8c7663c7f3d60b852b81ea..f2155fcab1e35feb5e71774afeddf71fdd85488e 100644 (file)
@@ -56,7 +56,7 @@
   Mem/MemData.c\r
   Mem/Imem.h\r
   Mem/MemoryProfileRecord.c\r
   Mem/MemData.c\r
   Mem/Imem.h\r
   Mem/MemoryProfileRecord.c\r
-  Mem/HeapGuard.c
+  Mem/HeapGuard.c\r
   FwVolBlock/FwVolBlock.c\r
   FwVolBlock/FwVolBlock.h\r
   FwVol/FwVolWrite.c\r
   FwVolBlock/FwVolBlock.c\r
   FwVolBlock/FwVolBlock.h\r
   FwVol/FwVolWrite.c\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy                   ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy             ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask        ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdImageProtectionPolicy                   ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdDxeNxMemoryProtectionPolicy             ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask        ## CONSUMES\r
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType                       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType                       ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask                   ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType                       ## CONSUMES\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType                       ## CONSUMES\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask                   ## CONSUMES\r
 \r
 # [Hob]\r
 # RESOURCE_DESCRIPTOR   ## CONSUMES\r
 \r
 # [Hob]\r
 # RESOURCE_DESCRIPTOR   ## CONSUMES\r
index 752befa44d064854c2ffa477137c627847e935ac..30a73fc04d15ffbfc64a4395a622845c524d4fb6 100644 (file)
-/** @file
-  UEFI Heap Guard functions.
-
-Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
-
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "DxeMain.h"
-#include "Imem.h"
-#include "HeapGuard.h"
-
-//
-// Global to avoid infinite reentrance of memory allocation when updating
-// page table attributes, which may need allocate pages for new PDE/PTE.
-//
-GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE;
-
-//
-// Pointer to table tracking the Guarded memory with bitmap, in which  '1'
-// is used to indicate memory guarded. '0' might be free memory or Guard
-// page itself, depending on status of memory adjacent to it.
-//
-GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0;
-
-//
-// Current depth level of map table pointed by mGuardedMemoryMap.
-// mMapLevel must be initialized at least by 1. It will be automatically
-// updated according to the address of memory just tracked.
-//
-GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1;
-
-//
-// Shift and mask for each level of map table
-//
-GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH]
-                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS;
-GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH]
-                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS;
-
-/**
-  Set corresponding bits in bitmap table to 1 according to the address.
-
-  @param[in]  Address     Start address to set for.
-  @param[in]  BitNumber   Number of bits to set.
-  @param[in]  BitMap      Pointer to bitmap which covers the Address.
-
-  @return VOID.
-**/
-STATIC
-VOID
-SetBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   BitNumber,
-  IN UINT64                  *BitMap
-  )
-{
-  UINTN           Lsbs;
-  UINTN           Qwords;
-  UINTN           Msbs;
-  UINTN           StartBit;
-  UINTN           EndBit;
-
-  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);
-  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-
-  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {
-    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %
-              GUARDED_HEAP_MAP_ENTRY_BITS;
-    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;
-  } else {
-    Msbs    = BitNumber;
-    Lsbs    = 0;
-    Qwords  = 0;
-  }
-
-  if (Msbs > 0) {
-    *BitMap |= LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);
-    BitMap  += 1;
-  }
-
-  if (Qwords > 0) {
-    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES,
-              (UINT64)-1);
-    BitMap += Qwords;
-  }
-
-  if (Lsbs > 0) {
-    *BitMap |= (LShiftU64 (1, Lsbs) - 1);
-  }
-}
-
-/**
-  Set corresponding bits in bitmap table to 0 according to the address.
-
-  @param[in]  Address     Start address to set for.
-  @param[in]  BitNumber   Number of bits to set.
-  @param[in]  BitMap      Pointer to bitmap which covers the Address.
-
-  @return VOID.
-**/
-STATIC
-VOID
-ClearBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   BitNumber,
-  IN UINT64                  *BitMap
-  )
-{
-  UINTN           Lsbs;
-  UINTN           Qwords;
-  UINTN           Msbs;
-  UINTN           StartBit;
-  UINTN           EndBit;
-
-  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);
-  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-
-  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {
-    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %
-              GUARDED_HEAP_MAP_ENTRY_BITS;
-    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;
-  } else {
-    Msbs    = BitNumber;
-    Lsbs    = 0;
-    Qwords  = 0;
-  }
-
-  if (Msbs > 0) {
-    *BitMap &= ~LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);
-    BitMap  += 1;
-  }
-
-  if (Qwords > 0) {
-    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, 0);
-    BitMap += Qwords;
-  }
-
-  if (Lsbs > 0) {
-    *BitMap &= ~(LShiftU64 (1, Lsbs) - 1);
-  }
-}
-
-/**
-  Get corresponding bits in bitmap table according to the address.
-
-  The value of bit 0 corresponds to the status of memory at given Address.
-  No more than 64 bits can be retrieved in one call.
-
-  @param[in]  Address     Start address to retrieve bits for.
-  @param[in]  BitNumber   Number of bits to get.
-  @param[in]  BitMap      Pointer to bitmap which covers the Address.
-
-  @return An integer containing the bits information.
-**/
-STATIC
-UINT64
-GetBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   BitNumber,
-  IN UINT64                  *BitMap
-  )
-{
-  UINTN           StartBit;
-  UINTN           EndBit;
-  UINTN           Lsbs;
-  UINTN           Msbs;
-  UINT64          Result;
-
-  ASSERT (BitNumber <= GUARDED_HEAP_MAP_ENTRY_BITS);
-
-  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);
-  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-
-  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {
-    Msbs = GUARDED_HEAP_MAP_ENTRY_BITS - StartBit;
-    Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-  } else {
-    Msbs = BitNumber;
-    Lsbs = 0;
-  }
-
-  Result    = RShiftU64 ((*BitMap), StartBit) & (LShiftU64 (1, Msbs) - 1);
-  if (Lsbs > 0) {
-    BitMap  += 1;
-    Result  |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs);
-  }
-
-  return Result;
-}
-
-/**
-  Locate the pointer of bitmap from the guarded memory bitmap tables, which
-  covers the given Address.
-
-  @param[in]  Address       Start address to search the bitmap for.
-  @param[in]  AllocMapUnit  Flag to indicate memory allocation for the table.
-  @param[out] BitMap        Pointer to bitmap which covers the Address.
-
-  @return The bit number from given Address to the end of current map table.
-**/
-UINTN
-FindGuardedMemoryMap (
-  IN  EFI_PHYSICAL_ADDRESS    Address,
-  IN  BOOLEAN                 AllocMapUnit,
-  OUT UINT64                  **BitMap
-  )
-{
-  UINTN                   Level;
-  UINT64                  *GuardMap;
-  UINT64                  MapMemory;
-  UINTN                   Index;
-  UINTN                   Size;
-  UINTN                   BitsToUnitEnd;
-  EFI_STATUS              Status;
-
-  //
-  // Adjust current map table depth according to the address to access
-  //
-  while (mMapLevel < GUARDED_HEAP_MAP_TABLE_DEPTH
-         &&
-         RShiftU64 (
-           Address,
-           mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1]
-           ) != 0) {
-
-    if (mGuardedMemoryMap != 0) {
-      Size = (mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] + 1)
-             * GUARDED_HEAP_MAP_ENTRY_BYTES;
-      Status = CoreInternalAllocatePages (
-                  AllocateAnyPages,
-                  EfiBootServicesData,
-                  EFI_SIZE_TO_PAGES (Size),
-                  &MapMemory,
-                  FALSE
-                  );
-      ASSERT_EFI_ERROR (Status);
-      ASSERT (MapMemory != 0);
-
-      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);
-
-      *(UINT64 *)(UINTN)MapMemory = mGuardedMemoryMap;
-      mGuardedMemoryMap = MapMemory;
-    }
-
-    mMapLevel++;
-
-  }
-
-  GuardMap = &mGuardedMemoryMap;
-  for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;
-       Level < GUARDED_HEAP_MAP_TABLE_DEPTH;
-       ++Level) {
-
-    if (*GuardMap == 0) {
-      if (!AllocMapUnit) {
-        GuardMap = NULL;
-        break;
-      }
-
-      Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES;
-      Status = CoreInternalAllocatePages (
-                  AllocateAnyPages,
-                  EfiBootServicesData,
-                  EFI_SIZE_TO_PAGES (Size),
-                  &MapMemory,
-                  FALSE
-                  );
-      ASSERT_EFI_ERROR (Status);
-      ASSERT (MapMemory != 0);
-
-      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);
-      *GuardMap = MapMemory;
-    }
-
-    Index     = (UINTN)RShiftU64 (Address, mLevelShift[Level]);
-    Index     &= mLevelMask[Level];
-    GuardMap  = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64));
-
-  }
-
-  BitsToUnitEnd = GUARDED_HEAP_MAP_BITS - GUARDED_HEAP_MAP_BIT_INDEX (Address);
-  *BitMap       = GuardMap;
-
-  return BitsToUnitEnd;
-}
-
-/**
-  Set corresponding bits in bitmap table to 1 according to given memory range.
-
-  @param[in]  Address       Memory address to guard from.
-  @param[in]  NumberOfPages Number of pages to guard.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-SetGuardedMemoryBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   NumberOfPages
-  )
-{
-  UINT64            *BitMap;
-  UINTN             Bits;
-  UINTN             BitsToUnitEnd;
-
-  while (NumberOfPages > 0) {
-    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);
-    ASSERT (BitMap != NULL);
-
-    if (NumberOfPages > BitsToUnitEnd) {
-      // Cross map unit
-      Bits = BitsToUnitEnd;
-    } else {
-      Bits  = NumberOfPages;
-    }
-
-    SetBits (Address, Bits, BitMap);
-
-    NumberOfPages -= Bits;
-    Address       += EFI_PAGES_TO_SIZE (Bits);
-  }
-}
-
-/**
-  Clear corresponding bits in bitmap table according to given memory range.
-
-  @param[in]  Address       Memory address to unset from.
-  @param[in]  NumberOfPages Number of pages to unset guard.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-ClearGuardedMemoryBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   NumberOfPages
-  )
-{
-  UINT64            *BitMap;
-  UINTN             Bits;
-  UINTN             BitsToUnitEnd;
-
-  while (NumberOfPages > 0) {
-    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);
-    ASSERT (BitMap != NULL);
-
-    if (NumberOfPages > BitsToUnitEnd) {
-      // Cross map unit
-      Bits = BitsToUnitEnd;
-    } else {
-      Bits  = NumberOfPages;
-    }
-
-    ClearBits (Address, Bits, BitMap);
-
-    NumberOfPages -= Bits;
-    Address       += EFI_PAGES_TO_SIZE (Bits);
-  }
-}
-
-/**
-  Retrieve corresponding bits in bitmap table according to given memory range.
-
-  @param[in]  Address       Memory address to retrieve from.
-  @param[in]  NumberOfPages Number of pages to retrieve.
-
-  @return An integer containing the guarded memory bitmap.
-**/
-UINTN
-GetGuardedMemoryBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   NumberOfPages
-  )
-{
-  UINT64            *BitMap;
-  UINTN             Bits;
-  UINTN             Result;
-  UINTN             Shift;
-  UINTN             BitsToUnitEnd;
-
-  ASSERT (NumberOfPages <= GUARDED_HEAP_MAP_ENTRY_BITS);
-
-  Result = 0;
-  Shift  = 0;
-  while (NumberOfPages > 0) {
-    BitsToUnitEnd = FindGuardedMemoryMap (Address, FALSE, &BitMap);
-
-    if (NumberOfPages > BitsToUnitEnd) {
-      // Cross map unit
-      Bits  = BitsToUnitEnd;
-    } else {
-      Bits  = NumberOfPages;
-    }
-
-    if (BitMap != NULL) {
-      Result |= LShiftU64 (GetBits (Address, Bits, BitMap), Shift);
-    }
-
-    Shift         += Bits;
-    NumberOfPages -= Bits;
-    Address       += EFI_PAGES_TO_SIZE (Bits);
-  }
-
-  return Result;
-}
-
-/**
-  Get bit value in bitmap table for the given address.
-
-  @param[in]  Address     The address to retrieve for.
-
-  @return 1 or 0.
-**/
-UINTN
-EFIAPI
-GetGuardMapBit (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINT64        *GuardMap;
-
-  FindGuardedMemoryMap (Address, FALSE, &GuardMap);
-  if (GuardMap != NULL) {
-    if (RShiftU64 (*GuardMap,
-                   GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address)) & 1) {
-      return 1;
-    }
-  }
-
-  return 0;
-}
-
-/**
-  Set the bit in bitmap table for the given address.
-
-  @param[in]  Address     The address to set for.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-SetGuardMapBit (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINT64        *GuardMap;
-  UINT64        BitMask;
-
-  FindGuardedMemoryMap (Address, TRUE, &GuardMap);
-  if (GuardMap != NULL) {
-    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));
-    *GuardMap |= BitMask;
-  }
-}
-
-/**
-  Clear the bit in bitmap table for the given address.
-
-  @param[in]  Address     The address to clear for.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-ClearGuardMapBit (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINT64        *GuardMap;
-  UINT64        BitMask;
-
-  FindGuardedMemoryMap (Address, TRUE, &GuardMap);
-  if (GuardMap != NULL) {
-    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));
-    *GuardMap &= ~BitMask;
-  }
-}
-
-/**
-  Check to see if the page at the given address is a Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a Guard page.
-  @return FALSE The page at Address is not a Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsGuardPage (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINTN       BitMap;
-
-  //
-  // There must be at least one guarded page before and/or after given
-  // address if it's a Guard page. The bitmap pattern should be one of
-  // 001, 100 and 101
-  //
-  BitMap = GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 3);
-  return ((BitMap == BIT0) || (BitMap == BIT2) || (BitMap == (BIT2 | BIT0)));
-}
-
-/**
-  Check to see if the page at the given address is a head Guard page or not.
-
-  @param[in]  Address     The address to check for
-
-  @return TRUE  The page at Address is a head Guard page
-  @return FALSE The page at Address is not a head Guard page
-**/
-BOOLEAN
-EFIAPI
-IsHeadGuard (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  return (GetGuardedMemoryBits (Address, 2) == BIT1);
-}
-
-/**
-  Check to see if the page at the given address is a tail Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a tail Guard page.
-  @return FALSE The page at Address is not a tail Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsTailGuard (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  return (GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 2) == BIT0);
-}
-
-/**
-  Check to see if the page at the given address is guarded or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is guarded.
-  @return FALSE The page at Address is not guarded.
-**/
-BOOLEAN
-EFIAPI
-IsMemoryGuarded (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  return (GetGuardMapBit (Address) == 1);
-}
-
-/**
-  Set the page at the given address to be a Guard page.
-
-  This is done by changing the page table attribute to be NOT PRSENT.
-
-  @param[in]  BaseAddress     Page address to Guard at
-
-  @return VOID
-**/
-VOID
-EFIAPI
-SetGuardPage (
-  IN  EFI_PHYSICAL_ADDRESS      BaseAddress
-  )
-{
-  //
-  // Set flag to make sure allocating memory without GUARD for page table
-  // operation; otherwise infinite loops could be caused.
-  //
-  mOnGuarding = TRUE;
-  //
-  // Note: This might overwrite other attributes needed by other features,
-  // such as memory protection (NX). Please make sure they are not enabled
-  // at the same time.
-  //
-  gCpu->SetMemoryAttributes (gCpu, BaseAddress, EFI_PAGE_SIZE, EFI_MEMORY_RP);
-  mOnGuarding = FALSE;
-}
-
-/**
-  Unset the Guard page at the given address to the normal memory.
-
-  This is done by changing the page table attribute to be PRSENT.
-
-  @param[in]  BaseAddress     Page address to Guard at.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-UnsetGuardPage (
-  IN  EFI_PHYSICAL_ADDRESS      BaseAddress
-  )
-{
-  //
-  // Set flag to make sure allocating memory without GUARD for page table
-  // operation; otherwise infinite loops could be caused.
-  //
-  mOnGuarding = TRUE;
-  //
-  // Note: This might overwrite other attributes needed by other features,
-  // such as memory protection (NX). Please make sure they are not enabled
-  // at the same time.
-  //
-  gCpu->SetMemoryAttributes (gCpu, BaseAddress, EFI_PAGE_SIZE, 0);
-  mOnGuarding = FALSE;
-}
-
-/**
-  Check to see if the memory at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Memory type to check.
-  @param[in]  AllocateType    Allocation type to check.
-  @param[in]  PageOrPool      Indicate a page allocation or pool allocation.
-
-
-  @return TRUE  The given type of memory should be guarded.
-  @return FALSE The given type of memory should not be guarded.
-**/
-BOOLEAN
-IsMemoryTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN EFI_ALLOCATE_TYPE      AllocateType,
-  IN UINT8                  PageOrPool
-  )
-{
-  UINT64 TestBit;
-  UINT64 ConfigBit;
-  BOOLEAN     InSmm;
-
-  if (gCpu == NULL || AllocateType == AllocateAddress) {
-    return FALSE;
-  }
-
-  InSmm = FALSE;
-  if (gSmmBase2 != NULL) {
-    gSmmBase2->InSmm (gSmmBase2, &InSmm);
-  }
-
-  if (InSmm) {
-    return FALSE;
-  }
-
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0) {
-    return FALSE;
-  }
-
-  if (PageOrPool == GUARD_HEAP_TYPE_POOL) {
-    ConfigBit = PcdGet64 (PcdHeapGuardPoolType);
-  } else if (PageOrPool == GUARD_HEAP_TYPE_PAGE) {
-    ConfigBit = PcdGet64 (PcdHeapGuardPageType);
-  } else {
-    ConfigBit = (UINT64)-1;
-  }
-
-  if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) {
-    TestBit = BIT63;
-  } else if ((UINT32) MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) {
-    TestBit = BIT62;
-  } else if (MemoryType < EfiMaxMemoryType) {
-    TestBit = LShiftU64 (1, MemoryType);
-  } else if (MemoryType == EfiMaxMemoryType) {
-    TestBit = (UINT64)-1;
-  } else {
-    TestBit = 0;
-  }
-
-  return ((ConfigBit & TestBit) != 0);
-}
-
-/**
-  Check to see if the pool at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Pool type to check.
-
-
-  @return TRUE  The given type of pool should be guarded.
-  @return FALSE The given type of pool should not be guarded.
-**/
-BOOLEAN
-IsPoolTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType
-  )
-{
-  return IsMemoryTypeToGuard (MemoryType, AllocateAnyPages,
-                              GUARD_HEAP_TYPE_POOL);
-}
-
-/**
-  Check to see if the page at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Page type to check.
-  @param[in]  AllocateType    Allocation type to check.
-
-  @return TRUE  The given type of page should be guarded.
-  @return FALSE The given type of page should not be guarded.
-**/
-BOOLEAN
-IsPageTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN EFI_ALLOCATE_TYPE      AllocateType
-  )
-{
-  return IsMemoryTypeToGuard (MemoryType, AllocateType, GUARD_HEAP_TYPE_PAGE);
-}
-
-/**
-  Set head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to set guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID
-**/
-VOID
-SetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS    GuardPage;
-
-  //
-  // Set tail Guard
-  //
-  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);
-  if (!IsGuardPage (GuardPage)) {
-    SetGuardPage (GuardPage);
-  }
-
-  // Set head Guard
-  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);
-  if (!IsGuardPage (GuardPage)) {
-    SetGuardPage (GuardPage);
-  }
-
-  //
-  // Mark the memory range as Guarded
-  //
-  SetGuardedMemoryBits (Memory, NumberOfPages);
-}
-
-/**
-  Unset head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to unset guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID
-**/
-VOID
-UnsetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS  GuardPage;
-
-  if (NumberOfPages == 0) {
-    return;
-  }
-
-  //
-  // Head Guard must be one page before, if any.
-  //
-  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);
-  if (IsHeadGuard (GuardPage)) {
-    if (!IsMemoryGuarded (GuardPage - EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the head Guard is not a tail Guard of adjacent memory block,
-      // unset it.
-      //
-      UnsetGuardPage (GuardPage);
-    }
-  } else if (IsMemoryGuarded (GuardPage)) {
-    //
-    // Pages before memory to free are still in Guard. It's a partial free
-    // case. Turn first page of memory block to free into a new Guard.
-    //
-    SetGuardPage (Memory);
-  }
-
-  //
-  // Tail Guard must be the page after this memory block to free, if any.
-  //
-  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);
-  if (IsTailGuard (GuardPage)) {
-    if (!IsMemoryGuarded (GuardPage + EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the tail Guard is not a head Guard of adjacent memory block,
-      // free it; otherwise, keep it.
-      //
-      UnsetGuardPage (GuardPage);
-    }
-  } else if (IsMemoryGuarded (GuardPage)) {
-    //
-    // Pages after memory to free are still in Guard. It's a partial free
-    // case. We need to keep one page to be a head Guard.
-    //
-    SetGuardPage (GuardPage - EFI_PAGES_TO_SIZE (1));
-  }
-
-  //
-  // No matter what, we just clear the mark of the Guarded memory.
-  //
-  ClearGuardedMemoryBits(Memory, NumberOfPages);
-}
-
-/**
-  Adjust address of free memory according to existing and/or required Guard.
-
-  This function will check if there're existing Guard pages of adjacent
-  memory blocks, and try to use it as the Guard page of the memory to be
-  allocated.
-
-  @param[in]  Start           Start address of free memory block.
-  @param[in]  Size            Size of free memory block.
-  @param[in]  SizeRequested   Size of memory to allocate.
-
-  @return The end address of memory block found.
-  @return 0 if no enough space for the required size of memory and its Guard.
-**/
-UINT64
-AdjustMemoryS (
-  IN UINT64                  Start,
-  IN UINT64                  Size,
-  IN UINT64                  SizeRequested
-  )
-{
-  UINT64  Target;
-
-  Target = Start + Size - SizeRequested;
-
-  //
-  // At least one more page needed for Guard page.
-  //
-  if (Size < (SizeRequested + EFI_PAGES_TO_SIZE (1))) {
-    return 0;
-  }
-
-  if (!IsGuardPage (Start + Size)) {
-    // No Guard at tail to share. One more page is needed.
-    Target -= EFI_PAGES_TO_SIZE (1);
-  }
-
-  // Out of range?
-  if (Target < Start) {
-    return 0;
-  }
-
-  // At the edge?
-  if (Target == Start) {
-    if (!IsGuardPage (Target - EFI_PAGES_TO_SIZE (1))) {
-      // No enough space for a new head Guard if no Guard at head to share.
-      return 0;
-    }
-  }
-
-  // OK, we have enough pages for memory and its Guards. Return the End of the
-  // free space.
-  return Target + SizeRequested - 1;
-}
-
-/**
-  Adjust the start address and number of pages to free according to Guard.
-
-  The purpose of this function is to keep the shared Guard page with adjacent
-  memory block if it's still in guard, or free it if no more sharing. Another
-  is to reserve pages as Guard pages in partial page free situation.
-
-  @param[in,out]  Memory          Base address of memory to free.
-  @param[in,out]  NumberOfPages   Size of memory to free.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryF (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS  Start;
-  EFI_PHYSICAL_ADDRESS  MemoryToTest;
-  UINTN                 PagesToFree;
-
-  if (Memory == NULL || NumberOfPages == NULL || *NumberOfPages == 0) {
-    return;
-  }
-
-  Start = *Memory;
-  PagesToFree = *NumberOfPages;
-
-  //
-  // Head Guard must be one page before, if any.
-  //
-  MemoryToTest = Start - EFI_PAGES_TO_SIZE (1);
-  if (IsHeadGuard (MemoryToTest)) {
-    if (!IsMemoryGuarded (MemoryToTest - EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the head Guard is not a tail Guard of adjacent memory block,
-      // free it; otherwise, keep it.
-      //
-      Start       -= EFI_PAGES_TO_SIZE (1);
-      PagesToFree += 1;
-    }
-  } else if (IsMemoryGuarded (MemoryToTest)) {
-    //
-    // Pages before memory to free are still in Guard. It's a partial free
-    // case. We need to keep one page to be a tail Guard.
-    //
-    Start       += EFI_PAGES_TO_SIZE (1);
-    PagesToFree -= 1;
-  }
-
-  //
-  // Tail Guard must be the page after this memory block to free, if any.
-  //
-  MemoryToTest = Start + EFI_PAGES_TO_SIZE (PagesToFree);
-  if (IsTailGuard (MemoryToTest)) {
-    if (!IsMemoryGuarded (MemoryToTest + EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the tail Guard is not a head Guard of adjacent memory block,
-      // free it; otherwise, keep it.
-      //
-      PagesToFree += 1;
-    }
-  } else if (IsMemoryGuarded (MemoryToTest)) {
-    //
-    // Pages after memory to free are still in Guard. It's a partial free
-    // case. We need to keep one page to be a head Guard.
-    //
-    PagesToFree -= 1;
-  }
-
-  *Memory         = Start;
-  *NumberOfPages  = PagesToFree;
-}
-
-/**
-  Adjust the base and number of pages to really allocate according to Guard.
-
-  @param[in,out]  Memory          Base address of free memory.
-  @param[in,out]  NumberOfPages   Size of memory to allocate.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryA (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  )
-{
-  //
-  // FindFreePages() has already taken the Guard into account. It's safe to
-  // adjust the start address and/or number of pages here, to make sure that
-  // the Guards are also "allocated".
-  //
-  if (!IsGuardPage (*Memory + EFI_PAGES_TO_SIZE (*NumberOfPages))) {
-    // No tail Guard, add one.
-    *NumberOfPages += 1;
-  }
-
-  if (!IsGuardPage (*Memory - EFI_PAGE_SIZE)) {
-    // No head Guard, add one.
-    *Memory        -= EFI_PAGE_SIZE;
-    *NumberOfPages += 1;
-  }
-}
-
-/**
-  Adjust the pool head position to make sure the Guard page is adjavent to
-  pool tail or pool head.
-
-  @param[in]  Memory    Base address of memory allocated.
-  @param[in]  NoPages   Number of pages actually allocated.
-  @param[in]  Size      Size of memory requested.
-                        (plus pool head/tail overhead)
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadA (
-  IN EFI_PHYSICAL_ADDRESS    Memory,
-  IN UINTN                   NoPages,
-  IN UINTN                   Size
-  )
-{
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {
-    //
-    // Pool head is put near the head Guard
-    //
-    return (VOID *)(UINTN)Memory;
-  }
-
-  //
-  // Pool head is put near the tail Guard
-  //
-  return (VOID *)(UINTN)(Memory + EFI_PAGES_TO_SIZE (NoPages) - Size);
-}
-
-/**
-  Get the page base address according to pool head address.
-
-  @param[in]  Memory    Head address of pool to free.
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadF (
-  IN EFI_PHYSICAL_ADDRESS    Memory
-  )
-{
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {
-    //
-    // Pool head is put near the head Guard
-    //
-    return (VOID *)(UINTN)Memory;
-  }
-
-  //
-  // Pool head is put near the tail Guard
-  //
-  return (VOID *)(UINTN)(Memory & ~EFI_PAGE_MASK);
-}
-
-/**
-  Allocate or free guarded memory.
-
-  @param[in]  Start           Start address of memory to allocate or free.
-  @param[in]  NumberOfPages   Memory size in pages.
-  @param[in]  NewType         Memory type to convert to.
-
-  @return VOID.
-**/
-EFI_STATUS
-CoreConvertPagesWithGuard (
-  IN UINT64           Start,
-  IN UINTN            NumberOfPages,
-  IN EFI_MEMORY_TYPE  NewType
-  )
-{
-  if (NewType == EfiConventionalMemory) {
-    AdjustMemoryF (&Start, &NumberOfPages);
-  } else {
-    AdjustMemoryA (&Start, &NumberOfPages);
-  }
-
-  return CoreConvertPages(Start, NumberOfPages, NewType);
-}
-
-/**
-  Helper function to convert a UINT64 value in binary to a string.
-
-  @param[in]  Value       Value of a UINT64 integer.
-  @param[out]  BinString   String buffer to contain the conversion result.
-
-  @return VOID.
-**/
-VOID
-Uint64ToBinString (
-  IN  UINT64      Value,
-  OUT CHAR8       *BinString
-  )
-{
-  UINTN Index;
-
-  if (BinString == NULL) {
-    return;
-  }
-
-  for (Index = 64; Index > 0; --Index) {
-    BinString[Index - 1] = '0' + (Value & 1);
-    Value = RShiftU64 (Value, 1);
-  }
-  BinString[64] = '\0';
-}
-
-/**
-  Dump the guarded memory bit map.
-**/
-VOID
-EFIAPI
-DumpGuardedMemoryBitmap (
-  VOID
-  )
-{
-  UINTN     Entries[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINTN     Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINTN     Indices[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    Tables[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    TableEntry;
-  UINT64    Address;
-  INTN      Level;
-  UINTN     RepeatZero;
-  CHAR8     String[GUARDED_HEAP_MAP_ENTRY_BITS + 1];
-  CHAR8     *Ruler1;
-  CHAR8     *Ruler2;
-
-  if (mGuardedMemoryMap == 0) {
-    return;
-  }
-
-  Ruler1 = "               3               2               1               0";
-  Ruler2 = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";
-
-  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "============================="
-                                  " Guarded Memory Bitmap "
-                                  "==============================\r\n"));
-  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler1));
-  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler2));
-
-  CopyMem (Entries, mLevelMask, sizeof (Entries));
-  CopyMem (Shifts, mLevelShift, sizeof (Shifts));
-
-  SetMem (Indices, sizeof(Indices), 0);
-  SetMem (Tables, sizeof(Tables), 0);
-  SetMem (Addresses, sizeof(Addresses), 0);
-
-  Level         = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;
-  Tables[Level] = mGuardedMemoryMap;
-  Address       = 0;
-  RepeatZero    = 0;
-
-  while (TRUE) {
-    if (Indices[Level] > Entries[Level]) {
-
-      Tables[Level] = 0;
-      Level        -= 1;
-      RepeatZero    = 0;
-
-      DEBUG ((
-        HEAP_GUARD_DEBUG_LEVEL,
-        "========================================="
-        "=========================================\r\n"
-        ));
-
-    } else {
-
-      TableEntry  = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]];
-      Address     = Addresses[Level];
-
-      if (TableEntry == 0) {
-
-        if (Level == GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {
-          if (RepeatZero == 0) {
-            Uint64ToBinString(TableEntry, String);
-            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));
-          } else if (RepeatZero == 1) {
-            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "...             : ...\r\n"));
-          }
-          RepeatZero += 1;
-        }
-
-      } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {
-
-        Level            += 1;
-        Tables[Level]     = TableEntry;
-        Addresses[Level]  = Address;
-        Indices[Level]    = 0;
-        RepeatZero        = 0;
-
-        continue;
-
-      } else {
-
-        RepeatZero = 0;
-        Uint64ToBinString(TableEntry, String);
-        DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));
-
-      }
-    }
-
-    if (Level < (GUARDED_HEAP_MAP_TABLE_DEPTH - (INTN)mMapLevel)) {
-      break;
-    }
-
-    Indices[Level] += 1;
-    Address = (Level == 0) ? 0 : Addresses[Level - 1];
-    Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]);
-
-  }
-}
-
+/** @file\r
+  UEFI Heap Guard functions.\r
+\r
+Copyright (c) 2017, 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
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#include "DxeMain.h"\r
+#include "Imem.h"\r
+#include "HeapGuard.h"\r
+\r
+//\r
+// Global to avoid infinite reentrance of memory allocation when updating\r
+// page table attributes, which may need allocate pages for new PDE/PTE.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE;\r
+\r
+//\r
+// Pointer to table tracking the Guarded memory with bitmap, in which  '1'\r
+// is used to indicate memory guarded. '0' might be free memory or Guard\r
+// page itself, depending on status of memory adjacent to it.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0;\r
+\r
+//\r
+// Current depth level of map table pointed by mGuardedMemoryMap.\r
+// mMapLevel must be initialized at least by 1. It will be automatically\r
+// updated according to the address of memory just tracked.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1;\r
+\r
+//\r
+// Shift and mask for each level of map table\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH]\r
+                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS;\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH]\r
+                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS;\r
+\r
+/**\r
+  Set corresponding bits in bitmap table to 1 according to the address.\r
+\r
+  @param[in]  Address     Start address to set for.\r
+  @param[in]  BitNumber   Number of bits to set.\r
+  @param[in]  BitMap      Pointer to bitmap which covers the Address.\r
+\r
+  @return VOID.\r
+**/\r
+STATIC\r
+VOID\r
+SetBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   BitNumber,\r
+  IN UINT64                  *BitMap\r
+  )\r
+{\r
+  UINTN           Lsbs;\r
+  UINTN           Qwords;\r
+  UINTN           Msbs;\r
+  UINTN           StartBit;\r
+  UINTN           EndBit;\r
+\r
+  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);\r
+  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+\r
+  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %\r
+              GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;\r
+  } else {\r
+    Msbs    = BitNumber;\r
+    Lsbs    = 0;\r
+    Qwords  = 0;\r
+  }\r
+\r
+  if (Msbs > 0) {\r
+    *BitMap |= LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);\r
+    BitMap  += 1;\r
+  }\r
+\r
+  if (Qwords > 0) {\r
+    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES,\r
+              (UINT64)-1);\r
+    BitMap += Qwords;\r
+  }\r
+\r
+  if (Lsbs > 0) {\r
+    *BitMap |= (LShiftU64 (1, Lsbs) - 1);\r
+  }\r
+}\r
+\r
+/**\r
+  Set corresponding bits in bitmap table to 0 according to the address.\r
+\r
+  @param[in]  Address     Start address to set for.\r
+  @param[in]  BitNumber   Number of bits to set.\r
+  @param[in]  BitMap      Pointer to bitmap which covers the Address.\r
+\r
+  @return VOID.\r
+**/\r
+STATIC\r
+VOID\r
+ClearBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   BitNumber,\r
+  IN UINT64                  *BitMap\r
+  )\r
+{\r
+  UINTN           Lsbs;\r
+  UINTN           Qwords;\r
+  UINTN           Msbs;\r
+  UINTN           StartBit;\r
+  UINTN           EndBit;\r
+\r
+  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);\r
+  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+\r
+  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %\r
+              GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;\r
+  } else {\r
+    Msbs    = BitNumber;\r
+    Lsbs    = 0;\r
+    Qwords  = 0;\r
+  }\r
+\r
+  if (Msbs > 0) {\r
+    *BitMap &= ~LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);\r
+    BitMap  += 1;\r
+  }\r
+\r
+  if (Qwords > 0) {\r
+    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, 0);\r
+    BitMap += Qwords;\r
+  }\r
+\r
+  if (Lsbs > 0) {\r
+    *BitMap &= ~(LShiftU64 (1, Lsbs) - 1);\r
+  }\r
+}\r
+\r
+/**\r
+  Get corresponding bits in bitmap table according to the address.\r
+\r
+  The value of bit 0 corresponds to the status of memory at given Address.\r
+  No more than 64 bits can be retrieved in one call.\r
+\r
+  @param[in]  Address     Start address to retrieve bits for.\r
+  @param[in]  BitNumber   Number of bits to get.\r
+  @param[in]  BitMap      Pointer to bitmap which covers the Address.\r
+\r
+  @return An integer containing the bits information.\r
+**/\r
+STATIC\r
+UINT64\r
+GetBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   BitNumber,\r
+  IN UINT64                  *BitMap\r
+  )\r
+{\r
+  UINTN           StartBit;\r
+  UINTN           EndBit;\r
+  UINTN           Lsbs;\r
+  UINTN           Msbs;\r
+  UINT64          Result;\r
+\r
+  ASSERT (BitNumber <= GUARDED_HEAP_MAP_ENTRY_BITS);\r
+\r
+  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);\r
+  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+\r
+  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+    Msbs = GUARDED_HEAP_MAP_ENTRY_BITS - StartBit;\r
+    Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+  } else {\r
+    Msbs = BitNumber;\r
+    Lsbs = 0;\r
+  }\r
+\r
+  Result    = RShiftU64 ((*BitMap), StartBit) & (LShiftU64 (1, Msbs) - 1);\r
+  if (Lsbs > 0) {\r
+    BitMap  += 1;\r
+    Result  |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs);\r
+  }\r
+\r
+  return Result;\r
+}\r
+\r
+/**\r
+  Locate the pointer of bitmap from the guarded memory bitmap tables, which\r
+  covers the given Address.\r
+\r
+  @param[in]  Address       Start address to search the bitmap for.\r
+  @param[in]  AllocMapUnit  Flag to indicate memory allocation for the table.\r
+  @param[out] BitMap        Pointer to bitmap which covers the Address.\r
+\r
+  @return The bit number from given Address to the end of current map table.\r
+**/\r
+UINTN\r
+FindGuardedMemoryMap (\r
+  IN  EFI_PHYSICAL_ADDRESS    Address,\r
+  IN  BOOLEAN                 AllocMapUnit,\r
+  OUT UINT64                  **BitMap\r
+  )\r
+{\r
+  UINTN                   Level;\r
+  UINT64                  *GuardMap;\r
+  UINT64                  MapMemory;\r
+  UINTN                   Index;\r
+  UINTN                   Size;\r
+  UINTN                   BitsToUnitEnd;\r
+  EFI_STATUS              Status;\r
+\r
+  //\r
+  // Adjust current map table depth according to the address to access\r
+  //\r
+  while (mMapLevel < GUARDED_HEAP_MAP_TABLE_DEPTH\r
+         &&\r
+         RShiftU64 (\r
+           Address,\r
+           mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1]\r
+           ) != 0) {\r
+\r
+    if (mGuardedMemoryMap != 0) {\r
+      Size = (mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] + 1)\r
+             * GUARDED_HEAP_MAP_ENTRY_BYTES;\r
+      Status = CoreInternalAllocatePages (\r
+                  AllocateAnyPages,\r
+                  EfiBootServicesData,\r
+                  EFI_SIZE_TO_PAGES (Size),\r
+                  &MapMemory,\r
+                  FALSE\r
+                  );\r
+      ASSERT_EFI_ERROR (Status);\r
+      ASSERT (MapMemory != 0);\r
+\r
+      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);\r
+\r
+      *(UINT64 *)(UINTN)MapMemory = mGuardedMemoryMap;\r
+      mGuardedMemoryMap = MapMemory;\r
+    }\r
+\r
+    mMapLevel++;\r
+\r
+  }\r
+\r
+  GuardMap = &mGuardedMemoryMap;\r
+  for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;\r
+       Level < GUARDED_HEAP_MAP_TABLE_DEPTH;\r
+       ++Level) {\r
+\r
+    if (*GuardMap == 0) {\r
+      if (!AllocMapUnit) {\r
+        GuardMap = NULL;\r
+        break;\r
+      }\r
+\r
+      Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES;\r
+      Status = CoreInternalAllocatePages (\r
+                  AllocateAnyPages,\r
+                  EfiBootServicesData,\r
+                  EFI_SIZE_TO_PAGES (Size),\r
+                  &MapMemory,\r
+                  FALSE\r
+                  );\r
+      ASSERT_EFI_ERROR (Status);\r
+      ASSERT (MapMemory != 0);\r
+\r
+      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);\r
+      *GuardMap = MapMemory;\r
+    }\r
+\r
+    Index     = (UINTN)RShiftU64 (Address, mLevelShift[Level]);\r
+    Index     &= mLevelMask[Level];\r
+    GuardMap  = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64));\r
+\r
+  }\r
+\r
+  BitsToUnitEnd = GUARDED_HEAP_MAP_BITS - GUARDED_HEAP_MAP_BIT_INDEX (Address);\r
+  *BitMap       = GuardMap;\r
+\r
+  return BitsToUnitEnd;\r
+}\r
+\r
+/**\r
+  Set corresponding bits in bitmap table to 1 according to given memory range.\r
+\r
+  @param[in]  Address       Memory address to guard from.\r
+  @param[in]  NumberOfPages Number of pages to guard.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+SetGuardedMemoryBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   NumberOfPages\r
+  )\r
+{\r
+  UINT64            *BitMap;\r
+  UINTN             Bits;\r
+  UINTN             BitsToUnitEnd;\r
+\r
+  while (NumberOfPages > 0) {\r
+    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);\r
+    ASSERT (BitMap != NULL);\r
+\r
+    if (NumberOfPages > BitsToUnitEnd) {\r
+      // Cross map unit\r
+      Bits = BitsToUnitEnd;\r
+    } else {\r
+      Bits  = NumberOfPages;\r
+    }\r
+\r
+    SetBits (Address, Bits, BitMap);\r
+\r
+    NumberOfPages -= Bits;\r
+    Address       += EFI_PAGES_TO_SIZE (Bits);\r
+  }\r
+}\r
+\r
+/**\r
+  Clear corresponding bits in bitmap table according to given memory range.\r
+\r
+  @param[in]  Address       Memory address to unset from.\r
+  @param[in]  NumberOfPages Number of pages to unset guard.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+ClearGuardedMemoryBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   NumberOfPages\r
+  )\r
+{\r
+  UINT64            *BitMap;\r
+  UINTN             Bits;\r
+  UINTN             BitsToUnitEnd;\r
+\r
+  while (NumberOfPages > 0) {\r
+    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);\r
+    ASSERT (BitMap != NULL);\r
+\r
+    if (NumberOfPages > BitsToUnitEnd) {\r
+      // Cross map unit\r
+      Bits = BitsToUnitEnd;\r
+    } else {\r
+      Bits  = NumberOfPages;\r
+    }\r
+\r
+    ClearBits (Address, Bits, BitMap);\r
+\r
+    NumberOfPages -= Bits;\r
+    Address       += EFI_PAGES_TO_SIZE (Bits);\r
+  }\r
+}\r
+\r
+/**\r
+  Retrieve corresponding bits in bitmap table according to given memory range.\r
+\r
+  @param[in]  Address       Memory address to retrieve from.\r
+  @param[in]  NumberOfPages Number of pages to retrieve.\r
+\r
+  @return An integer containing the guarded memory bitmap.\r
+**/\r
+UINTN\r
+GetGuardedMemoryBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   NumberOfPages\r
+  )\r
+{\r
+  UINT64            *BitMap;\r
+  UINTN             Bits;\r
+  UINTN             Result;\r
+  UINTN             Shift;\r
+  UINTN             BitsToUnitEnd;\r
+\r
+  ASSERT (NumberOfPages <= GUARDED_HEAP_MAP_ENTRY_BITS);\r
+\r
+  Result = 0;\r
+  Shift  = 0;\r
+  while (NumberOfPages > 0) {\r
+    BitsToUnitEnd = FindGuardedMemoryMap (Address, FALSE, &BitMap);\r
+\r
+    if (NumberOfPages > BitsToUnitEnd) {\r
+      // Cross map unit\r
+      Bits  = BitsToUnitEnd;\r
+    } else {\r
+      Bits  = NumberOfPages;\r
+    }\r
+\r
+    if (BitMap != NULL) {\r
+      Result |= LShiftU64 (GetBits (Address, Bits, BitMap), Shift);\r
+    }\r
+\r
+    Shift         += Bits;\r
+    NumberOfPages -= Bits;\r
+    Address       += EFI_PAGES_TO_SIZE (Bits);\r
+  }\r
+\r
+  return Result;\r
+}\r
+\r
+/**\r
+  Get bit value in bitmap table for the given address.\r
+\r
+  @param[in]  Address     The address to retrieve for.\r
+\r
+  @return 1 or 0.\r
+**/\r
+UINTN\r
+EFIAPI\r
+GetGuardMapBit (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINT64        *GuardMap;\r
+\r
+  FindGuardedMemoryMap (Address, FALSE, &GuardMap);\r
+  if (GuardMap != NULL) {\r
+    if (RShiftU64 (*GuardMap,\r
+                   GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address)) & 1) {\r
+      return 1;\r
+    }\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+/**\r
+  Set the bit in bitmap table for the given address.\r
+\r
+  @param[in]  Address     The address to set for.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+SetGuardMapBit (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINT64        *GuardMap;\r
+  UINT64        BitMask;\r
+\r
+  FindGuardedMemoryMap (Address, TRUE, &GuardMap);\r
+  if (GuardMap != NULL) {\r
+    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));\r
+    *GuardMap |= BitMask;\r
+  }\r
+}\r
+\r
+/**\r
+  Clear the bit in bitmap table for the given address.\r
+\r
+  @param[in]  Address     The address to clear for.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+ClearGuardMapBit (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINT64        *GuardMap;\r
+  UINT64        BitMask;\r
+\r
+  FindGuardedMemoryMap (Address, TRUE, &GuardMap);\r
+  if (GuardMap != NULL) {\r
+    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));\r
+    *GuardMap &= ~BitMask;\r
+  }\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is a Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a Guard page.\r
+  @return FALSE The page at Address is not a Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsGuardPage (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINTN       BitMap;\r
+\r
+  //\r
+  // There must be at least one guarded page before and/or after given\r
+  // address if it's a Guard page. The bitmap pattern should be one of\r
+  // 001, 100 and 101\r
+  //\r
+  BitMap = GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 3);\r
+  return ((BitMap == BIT0) || (BitMap == BIT2) || (BitMap == (BIT2 | BIT0)));\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is a head Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for\r
+\r
+  @return TRUE  The page at Address is a head Guard page\r
+  @return FALSE The page at Address is not a head Guard page\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsHeadGuard (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  return (GetGuardedMemoryBits (Address, 2) == BIT1);\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is a tail Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a tail Guard page.\r
+  @return FALSE The page at Address is not a tail Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsTailGuard (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  return (GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 2) == BIT0);\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is guarded or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is guarded.\r
+  @return FALSE The page at Address is not guarded.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsMemoryGuarded (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  return (GetGuardMapBit (Address) == 1);\r
+}\r
+\r
+/**\r
+  Set the page at the given address to be a Guard page.\r
+\r
+  This is done by changing the page table attribute to be NOT PRSENT.\r
+\r
+  @param[in]  BaseAddress     Page address to Guard at\r
+\r
+  @return VOID\r
+**/\r
+VOID\r
+EFIAPI\r
+SetGuardPage (\r
+  IN  EFI_PHYSICAL_ADDRESS      BaseAddress\r
+  )\r
+{\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 memory protection (NX). Please make sure they are not enabled\r
+  // at the same time.\r
+  //\r
+  gCpu->SetMemoryAttributes (gCpu, BaseAddress, EFI_PAGE_SIZE, EFI_MEMORY_RP);\r
+  mOnGuarding = FALSE;\r
+}\r
+\r
+/**\r
+  Unset the Guard page at the given address to the normal memory.\r
+\r
+  This is done by changing the page table attribute to be PRSENT.\r
+\r
+  @param[in]  BaseAddress     Page address to Guard at.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+UnsetGuardPage (\r
+  IN  EFI_PHYSICAL_ADDRESS      BaseAddress\r
+  )\r
+{\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 memory protection (NX). Please make sure they are not enabled\r
+  // at the same time.\r
+  //\r
+  gCpu->SetMemoryAttributes (gCpu, BaseAddress, EFI_PAGE_SIZE, 0);\r
+  mOnGuarding = FALSE;\r
+}\r
+\r
+/**\r
+  Check to see if the memory at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Memory type to check.\r
+  @param[in]  AllocateType    Allocation type to check.\r
+  @param[in]  PageOrPool      Indicate a page allocation or pool allocation.\r
+\r
+\r
+  @return TRUE  The given type of memory should be guarded.\r
+  @return FALSE The given type of memory should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsMemoryTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN EFI_ALLOCATE_TYPE      AllocateType,\r
+  IN UINT8                  PageOrPool\r
+  )\r
+{\r
+  UINT64 TestBit;\r
+  UINT64 ConfigBit;\r
+  BOOLEAN     InSmm;\r
+\r
+  if (gCpu == NULL || AllocateType == AllocateAddress) {\r
+    return FALSE;\r
+  }\r
+\r
+  InSmm = FALSE;\r
+  if (gSmmBase2 != NULL) {\r
+    gSmmBase2->InSmm (gSmmBase2, &InSmm);\r
+  }\r
+\r
+  if (InSmm) {\r
+    return FALSE;\r
+  }\r
+\r
+  if ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0) {\r
+    return FALSE;\r
+  }\r
+\r
+  if (PageOrPool == GUARD_HEAP_TYPE_POOL) {\r
+    ConfigBit = PcdGet64 (PcdHeapGuardPoolType);\r
+  } else if (PageOrPool == GUARD_HEAP_TYPE_PAGE) {\r
+    ConfigBit = PcdGet64 (PcdHeapGuardPageType);\r
+  } else {\r
+    ConfigBit = (UINT64)-1;\r
+  }\r
+\r
+  if ((UINT32)MemoryType >= MEMORY_TYPE_OS_RESERVED_MIN) {\r
+    TestBit = BIT63;\r
+  } else if ((UINT32) MemoryType >= MEMORY_TYPE_OEM_RESERVED_MIN) {\r
+    TestBit = BIT62;\r
+  } else if (MemoryType < EfiMaxMemoryType) {\r
+    TestBit = LShiftU64 (1, MemoryType);\r
+  } else if (MemoryType == EfiMaxMemoryType) {\r
+    TestBit = (UINT64)-1;\r
+  } else {\r
+    TestBit = 0;\r
+  }\r
+\r
+  return ((ConfigBit & TestBit) != 0);\r
+}\r
+\r
+/**\r
+  Check to see if the pool at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Pool type to check.\r
+\r
+\r
+  @return TRUE  The given type of pool should be guarded.\r
+  @return FALSE The given type of pool should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPoolTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType\r
+  )\r
+{\r
+  return IsMemoryTypeToGuard (MemoryType, AllocateAnyPages,\r
+                              GUARD_HEAP_TYPE_POOL);\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Page type to check.\r
+  @param[in]  AllocateType    Allocation type to check.\r
+\r
+  @return TRUE  The given type of page should be guarded.\r
+  @return FALSE The given type of page should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPageTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN EFI_ALLOCATE_TYPE      AllocateType\r
+  )\r
+{\r
+  return IsMemoryTypeToGuard (MemoryType, AllocateType, GUARD_HEAP_TYPE_PAGE);\r
+}\r
+\r
+/**\r
+  Set head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to set guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID\r
+**/\r
+VOID\r
+SetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS    GuardPage;\r
+\r
+  //\r
+  // Set tail Guard\r
+  //\r
+  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);\r
+  if (!IsGuardPage (GuardPage)) {\r
+    SetGuardPage (GuardPage);\r
+  }\r
+\r
+  // Set head Guard\r
+  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);\r
+  if (!IsGuardPage (GuardPage)) {\r
+    SetGuardPage (GuardPage);\r
+  }\r
+\r
+  //\r
+  // Mark the memory range as Guarded\r
+  //\r
+  SetGuardedMemoryBits (Memory, NumberOfPages);\r
+}\r
+\r
+/**\r
+  Unset head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to unset guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID\r
+**/\r
+VOID\r
+UnsetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS  GuardPage;\r
+\r
+  if (NumberOfPages == 0) {\r
+    return;\r
+  }\r
+\r
+  //\r
+  // Head Guard must be one page before, if any.\r
+  //\r
+  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);\r
+  if (IsHeadGuard (GuardPage)) {\r
+    if (!IsMemoryGuarded (GuardPage - EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the head Guard is not a tail Guard of adjacent memory block,\r
+      // unset it.\r
+      //\r
+      UnsetGuardPage (GuardPage);\r
+    }\r
+  } else if (IsMemoryGuarded (GuardPage)) {\r
+    //\r
+    // Pages before memory to free are still in Guard. It's a partial free\r
+    // case. Turn first page of memory block to free into a new Guard.\r
+    //\r
+    SetGuardPage (Memory);\r
+  }\r
+\r
+  //\r
+  // Tail Guard must be the page after this memory block to free, if any.\r
+  //\r
+  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);\r
+  if (IsTailGuard (GuardPage)) {\r
+    if (!IsMemoryGuarded (GuardPage + EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the tail Guard is not a head Guard of adjacent memory block,\r
+      // free it; otherwise, keep it.\r
+      //\r
+      UnsetGuardPage (GuardPage);\r
+    }\r
+  } else if (IsMemoryGuarded (GuardPage)) {\r
+    //\r
+    // Pages after memory to free are still in Guard. It's a partial free\r
+    // case. We need to keep one page to be a head Guard.\r
+    //\r
+    SetGuardPage (GuardPage - EFI_PAGES_TO_SIZE (1));\r
+  }\r
+\r
+  //\r
+  // No matter what, we just clear the mark of the Guarded memory.\r
+  //\r
+  ClearGuardedMemoryBits(Memory, NumberOfPages);\r
+}\r
+\r
+/**\r
+  Adjust address of free memory according to existing and/or required Guard.\r
+\r
+  This function will check if there're existing Guard pages of adjacent\r
+  memory blocks, and try to use it as the Guard page of the memory to be\r
+  allocated.\r
+\r
+  @param[in]  Start           Start address of free memory block.\r
+  @param[in]  Size            Size of free memory block.\r
+  @param[in]  SizeRequested   Size of memory to allocate.\r
+\r
+  @return The end address of memory block found.\r
+  @return 0 if no enough space for the required size of memory and its Guard.\r
+**/\r
+UINT64\r
+AdjustMemoryS (\r
+  IN UINT64                  Start,\r
+  IN UINT64                  Size,\r
+  IN UINT64                  SizeRequested\r
+  )\r
+{\r
+  UINT64  Target;\r
+\r
+  Target = Start + Size - SizeRequested;\r
+\r
+  //\r
+  // At least one more page needed for Guard page.\r
+  //\r
+  if (Size < (SizeRequested + EFI_PAGES_TO_SIZE (1))) {\r
+    return 0;\r
+  }\r
+\r
+  if (!IsGuardPage (Start + Size)) {\r
+    // No Guard at tail to share. One more page is needed.\r
+    Target -= EFI_PAGES_TO_SIZE (1);\r
+  }\r
+\r
+  // Out of range?\r
+  if (Target < Start) {\r
+    return 0;\r
+  }\r
+\r
+  // At the edge?\r
+  if (Target == Start) {\r
+    if (!IsGuardPage (Target - EFI_PAGES_TO_SIZE (1))) {\r
+      // No enough space for a new head Guard if no Guard at head to share.\r
+      return 0;\r
+    }\r
+  }\r
+\r
+  // OK, we have enough pages for memory and its Guards. Return the End of the\r
+  // free space.\r
+  return Target + SizeRequested - 1;\r
+}\r
+\r
+/**\r
+  Adjust the start address and number of pages to free according to Guard.\r
+\r
+  The purpose of this function is to keep the shared Guard page with adjacent\r
+  memory block if it's still in guard, or free it if no more sharing. Another\r
+  is to reserve pages as Guard pages in partial page free situation.\r
+\r
+  @param[in,out]  Memory          Base address of memory to free.\r
+  @param[in,out]  NumberOfPages   Size of memory to free.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryF (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS  Start;\r
+  EFI_PHYSICAL_ADDRESS  MemoryToTest;\r
+  UINTN                 PagesToFree;\r
+\r
+  if (Memory == NULL || NumberOfPages == NULL || *NumberOfPages == 0) {\r
+    return;\r
+  }\r
+\r
+  Start = *Memory;\r
+  PagesToFree = *NumberOfPages;\r
+\r
+  //\r
+  // Head Guard must be one page before, if any.\r
+  //\r
+  MemoryToTest = Start - EFI_PAGES_TO_SIZE (1);\r
+  if (IsHeadGuard (MemoryToTest)) {\r
+    if (!IsMemoryGuarded (MemoryToTest - EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the head Guard is not a tail Guard of adjacent memory block,\r
+      // free it; otherwise, keep it.\r
+      //\r
+      Start       -= EFI_PAGES_TO_SIZE (1);\r
+      PagesToFree += 1;\r
+    }\r
+  } else if (IsMemoryGuarded (MemoryToTest)) {\r
+    //\r
+    // Pages before memory to free are still in Guard. It's a partial free\r
+    // case. We need to keep one page to be a tail Guard.\r
+    //\r
+    Start       += EFI_PAGES_TO_SIZE (1);\r
+    PagesToFree -= 1;\r
+  }\r
+\r
+  //\r
+  // Tail Guard must be the page after this memory block to free, if any.\r
+  //\r
+  MemoryToTest = Start + EFI_PAGES_TO_SIZE (PagesToFree);\r
+  if (IsTailGuard (MemoryToTest)) {\r
+    if (!IsMemoryGuarded (MemoryToTest + EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the tail Guard is not a head Guard of adjacent memory block,\r
+      // free it; otherwise, keep it.\r
+      //\r
+      PagesToFree += 1;\r
+    }\r
+  } else if (IsMemoryGuarded (MemoryToTest)) {\r
+    //\r
+    // Pages after memory to free are still in Guard. It's a partial free\r
+    // case. We need to keep one page to be a head Guard.\r
+    //\r
+    PagesToFree -= 1;\r
+  }\r
+\r
+  *Memory         = Start;\r
+  *NumberOfPages  = PagesToFree;\r
+}\r
+\r
+/**\r
+  Adjust the base and number of pages to really allocate according to Guard.\r
+\r
+  @param[in,out]  Memory          Base address of free memory.\r
+  @param[in,out]  NumberOfPages   Size of memory to allocate.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryA (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  )\r
+{\r
+  //\r
+  // FindFreePages() has already taken the Guard into account. It's safe to\r
+  // adjust the start address and/or number of pages here, to make sure that\r
+  // the Guards are also "allocated".\r
+  //\r
+  if (!IsGuardPage (*Memory + EFI_PAGES_TO_SIZE (*NumberOfPages))) {\r
+    // No tail Guard, add one.\r
+    *NumberOfPages += 1;\r
+  }\r
+\r
+  if (!IsGuardPage (*Memory - EFI_PAGE_SIZE)) {\r
+    // No head Guard, add one.\r
+    *Memory        -= EFI_PAGE_SIZE;\r
+    *NumberOfPages += 1;\r
+  }\r
+}\r
+\r
+/**\r
+  Adjust the pool head position to make sure the Guard page is adjavent to\r
+  pool tail or pool head.\r
+\r
+  @param[in]  Memory    Base address of memory allocated.\r
+  @param[in]  NoPages   Number of pages actually allocated.\r
+  @param[in]  Size      Size of memory requested.\r
+                        (plus pool head/tail overhead)\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadA (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory,\r
+  IN UINTN                   NoPages,\r
+  IN UINTN                   Size\r
+  )\r
+{\r
+  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {\r
+    //\r
+    // Pool head is put near the head Guard\r
+    //\r
+    return (VOID *)(UINTN)Memory;\r
+  }\r
+\r
+  //\r
+  // Pool head is put near the tail Guard\r
+  //\r
+  return (VOID *)(UINTN)(Memory + EFI_PAGES_TO_SIZE (NoPages) - Size);\r
+}\r
+\r
+/**\r
+  Get the page base address according to pool head address.\r
+\r
+  @param[in]  Memory    Head address of pool to free.\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadF (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory\r
+  )\r
+{\r
+  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {\r
+    //\r
+    // Pool head is put near the head Guard\r
+    //\r
+    return (VOID *)(UINTN)Memory;\r
+  }\r
+\r
+  //\r
+  // Pool head is put near the tail Guard\r
+  //\r
+  return (VOID *)(UINTN)(Memory & ~EFI_PAGE_MASK);\r
+}\r
+\r
+/**\r
+  Allocate or free guarded memory.\r
+\r
+  @param[in]  Start           Start address of memory to allocate or free.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+  @param[in]  NewType         Memory type to convert to.\r
+\r
+  @return VOID.\r
+**/\r
+EFI_STATUS\r
+CoreConvertPagesWithGuard (\r
+  IN UINT64           Start,\r
+  IN UINTN            NumberOfPages,\r
+  IN EFI_MEMORY_TYPE  NewType\r
+  )\r
+{\r
+  if (NewType == EfiConventionalMemory) {\r
+    AdjustMemoryF (&Start, &NumberOfPages);\r
+  } else {\r
+    AdjustMemoryA (&Start, &NumberOfPages);\r
+  }\r
+\r
+  return CoreConvertPages(Start, NumberOfPages, NewType);\r
+}\r
+\r
+/**\r
+  Helper function to convert a UINT64 value in binary to a string.\r
+\r
+  @param[in]  Value       Value of a UINT64 integer.\r
+  @param[out]  BinString   String buffer to contain the conversion result.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+Uint64ToBinString (\r
+  IN  UINT64      Value,\r
+  OUT CHAR8       *BinString\r
+  )\r
+{\r
+  UINTN Index;\r
+\r
+  if (BinString == NULL) {\r
+    return;\r
+  }\r
+\r
+  for (Index = 64; Index > 0; --Index) {\r
+    BinString[Index - 1] = '0' + (Value & 1);\r
+    Value = RShiftU64 (Value, 1);\r
+  }\r
+  BinString[64] = '\0';\r
+}\r
+\r
+/**\r
+  Dump the guarded memory bit map.\r
+**/\r
+VOID\r
+EFIAPI\r
+DumpGuardedMemoryBitmap (\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
+  INTN      Level;\r
+  UINTN     RepeatZero;\r
+  CHAR8     String[GUARDED_HEAP_MAP_ENTRY_BITS + 1];\r
+  CHAR8     *Ruler1;\r
+  CHAR8     *Ruler2;\r
+\r
+  if (mGuardedMemoryMap == 0) {\r
+    return;\r
+  }\r
+\r
+  Ruler1 = "               3               2               1               0";\r
+  Ruler2 = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";\r
+\r
+  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "============================="\r
+                                  " Guarded Memory Bitmap "\r
+                                  "==============================\r\n"));\r
+  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler1));\r
+  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler2));\r
+\r
+  CopyMem (Entries, mLevelMask, sizeof (Entries));\r
+  CopyMem (Shifts, mLevelShift, sizeof (Shifts));\r
+\r
+  SetMem (Indices, sizeof(Indices), 0);\r
+  SetMem (Tables, sizeof(Tables), 0);\r
+  SetMem (Addresses, sizeof(Addresses), 0);\r
+\r
+  Level         = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;\r
+  Tables[Level] = mGuardedMemoryMap;\r
+  Address       = 0;\r
+  RepeatZero    = 0;\r
+\r
+  while (TRUE) {\r
+    if (Indices[Level] > Entries[Level]) {\r
+\r
+      Tables[Level] = 0;\r
+      Level        -= 1;\r
+      RepeatZero    = 0;\r
+\r
+      DEBUG ((\r
+        HEAP_GUARD_DEBUG_LEVEL,\r
+        "========================================="\r
+        "=========================================\r\n"\r
+        ));\r
+\r
+    } else {\r
+\r
+      TableEntry  = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]];\r
+      Address     = Addresses[Level];\r
+\r
+      if (TableEntry == 0) {\r
+\r
+        if (Level == GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {\r
+          if (RepeatZero == 0) {\r
+            Uint64ToBinString(TableEntry, String);\r
+            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));\r
+          } else if (RepeatZero == 1) {\r
+            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "...             : ...\r\n"));\r
+          }\r
+          RepeatZero += 1;\r
+        }\r
+\r
+      } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {\r
+\r
+        Level            += 1;\r
+        Tables[Level]     = TableEntry;\r
+        Addresses[Level]  = Address;\r
+        Indices[Level]    = 0;\r
+        RepeatZero        = 0;\r
+\r
+        continue;\r
+\r
+      } else {\r
+\r
+        RepeatZero = 0;\r
+        Uint64ToBinString(TableEntry, String);\r
+        DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));\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
index 71757a83b1edf57388a933199b83859e71598ecf..bd7abd7c53266703871a32f642391fdfeb5d0629 100644 (file)
-/** @file
-  Data type, macros and function prototypes of heap guard feature.
-
-Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
-
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef _HEAPGUARD_H_
-#define _HEAPGUARD_H_
-
-//
-// Following macros are used to define and access the guarded memory bitmap
-// table.
-//
-// To simplify the access and reduce the memory used for this table, the
-// table is constructed in the similar way as page table structure but in
-// reverse direction, i.e. from bottom growing up to top.
-//
-//    - 1-bit tracks 1 page (4KB)
-//    - 1-UINT64 map entry tracks 256KB memory
-//    - 1K-UINT64 map table tracks 256MB memory
-//    - Five levels of tables can track any address of memory of 64-bit
-//      system, like below.
-//
-//       512   *   512   *   512   *   512    *    1K   *  64b *     4K
-//    111111111 111111111 111111111 111111111 1111111111 111111 111111111111
-//    63        54        45        36        27         17     11         0
-//       9b        9b        9b        9b         10b      6b       12b
-//       L0   ->   L1   ->   L2   ->   L3   ->    L4   -> bits  ->  page
-//      1FF       1FF       1FF       1FF         3FF      3F       FFF
-//
-// L4 table has 1K * sizeof(UINT64) = 8K (2-page), which can track 256MB
-// memory. Each table of L0-L3 will be allocated when its memory address
-// range is to be tracked. Only 1-page will be allocated each time. This
-// can save memories used to establish this map table.
-//
-// For a normal configuration of system with 4G memory, two levels of tables
-// can track the whole memory, because two levels (L3+L4) of map tables have
-// already coverred 37-bit of memory address. And for a normal UEFI BIOS,
-// less than 128M memory would be consumed during boot. That means we just
-// need
-//
-//          1-page (L3) + 2-page (L4)
-//
-// memory (3 pages) to track the memory allocation works. In this case,
-// there's no need to setup L0-L2 tables.
-//
-
-//
-// Each entry occupies 8B/64b. 1-page can hold 512 entries, which spans 9
-// bits in address. (512 = 1 << 9)
-//
-#define BYTE_LENGTH_SHIFT                   3             // (8 = 1 << 3)
-
-#define GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT  \
-        (EFI_PAGE_SHIFT - BYTE_LENGTH_SHIFT)
-
-#define GUARDED_HEAP_MAP_TABLE_DEPTH        5
-
-// Use UINT64_index + bit_index_of_UINT64 to locate the bit in may
-#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT    6             // (64 = 1 << 6)
-
-#define GUARDED_HEAP_MAP_ENTRY_BITS         \
-        (1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)
-
-#define GUARDED_HEAP_MAP_ENTRY_BYTES        \
-        (GUARDED_HEAP_MAP_ENTRY_BITS / 8)
-
-// L4 table address width: 64 - 9 * 4 - 6 - 12 = 10b
-#define GUARDED_HEAP_MAP_ENTRY_SHIFT              \
-        (GUARDED_HEAP_MAP_ENTRY_BITS              \
-         - GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 4 \
-         - GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT       \
-         - EFI_PAGE_SHIFT)
-
-// L4 table address mask: (1 << 10 - 1) = 0x3FF
-#define GUARDED_HEAP_MAP_ENTRY_MASK               \
-        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1)
-
-// Size of each L4 table: (1 << 10) * 8 = 8KB = 2-page
-#define GUARDED_HEAP_MAP_SIZE                     \
-        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) * GUARDED_HEAP_MAP_ENTRY_BYTES)
-
-// Memory size tracked by one L4 table: 8KB * 8 * 4KB = 256MB
-#define GUARDED_HEAP_MAP_UNIT_SIZE                \
-        (GUARDED_HEAP_MAP_SIZE * 8 * EFI_PAGE_SIZE)
-
-// L4 table entry number: 8KB / 8 = 1024
-#define GUARDED_HEAP_MAP_ENTRIES_PER_UNIT         \
-        (GUARDED_HEAP_MAP_SIZE / GUARDED_HEAP_MAP_ENTRY_BYTES)
-
-// L4 table entry indexing
-#define GUARDED_HEAP_MAP_ENTRY_INDEX(Address)                       \
-        (RShiftU64 (Address, EFI_PAGE_SHIFT                         \
-                             + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)    \
-         & GUARDED_HEAP_MAP_ENTRY_MASK)
-
-// L4 table entry bit indexing
-#define GUARDED_HEAP_MAP_ENTRY_BIT_INDEX(Address)       \
-        (RShiftU64 (Address, EFI_PAGE_SHIFT)            \
-         & ((1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT) - 1))
-
-//
-// Total bits (pages) tracked by one L4 table (65536-bit)
-//
-#define GUARDED_HEAP_MAP_BITS                               \
-        (1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \
-               + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT))
-
-//
-// Bit indexing inside the whole L4 table (0 - 65535)
-//
-#define GUARDED_HEAP_MAP_BIT_INDEX(Address)                     \
-        (RShiftU64 (Address, EFI_PAGE_SHIFT)                    \
-         & ((1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \
-                   + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)) - 1))
-
-//
-// Memory address bit width tracked by L4 table: 10 + 6 + 12 = 28
-//
-#define GUARDED_HEAP_MAP_TABLE_SHIFT                                      \
-        (GUARDED_HEAP_MAP_ENTRY_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT  \
-         + EFI_PAGE_SHIFT)
-
-//
-// Macro used to initialize the local array variable for map table traversing
-// {55, 46, 37, 28, 18}
-//
-#define GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS                                 \
-  {                                                                         \
-    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 3,  \
-    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 2,  \
-    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT,      \
-    GUARDED_HEAP_MAP_TABLE_SHIFT,                                           \
-    EFI_PAGE_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT                       \
-  }
-
-//
-// Masks used to extract address range of each level of table
-// {0x1FF, 0x1FF, 0x1FF, 0x1FF, 0x3FF}
-//
-#define GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS                                  \
-  {                                                                         \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1                                 \
-  }
-
-//
-// Memory type to guard (matching the related PCD definition)
-//
-#define GUARD_HEAP_TYPE_POOL        BIT0
-#define GUARD_HEAP_TYPE_PAGE        BIT1
-
-//
-// Debug message level
-//
-#define HEAP_GUARD_DEBUG_LEVEL  (DEBUG_POOL|DEBUG_PAGE)
-
-typedef struct {
-  UINT32                TailMark;
-  UINT32                HeadMark;
-  EFI_PHYSICAL_ADDRESS  Address;
-  LIST_ENTRY            Link;
-} HEAP_GUARD_NODE;
-
-/**
-  Internal function.  Converts a memory range to the specified type.
-  The range must exist in the memory map.
-
-  @param  Start                  The first address of the range Must be page
-                                 aligned.
-  @param  NumberOfPages          The number of pages to convert.
-  @param  NewType                The new type for the memory range.
-
-  @retval EFI_INVALID_PARAMETER  Invalid parameter.
-  @retval EFI_NOT_FOUND          Could not find a descriptor cover the specified
-                                 range or convertion not allowed.
-  @retval EFI_SUCCESS            Successfully converts the memory range to the
-                                 specified type.
-
-**/
-EFI_STATUS
-CoreConvertPages (
-  IN UINT64           Start,
-  IN UINT64           NumberOfPages,
-  IN EFI_MEMORY_TYPE  NewType
-  );
-
-/**
-  Allocate or free guarded memory.
-
-  @param[in]  Start           Start address of memory to allocate or free.
-  @param[in]  NumberOfPages   Memory size in pages.
-  @param[in]  NewType         Memory type to convert to.
-
-  @return VOID.
-**/
-EFI_STATUS
-CoreConvertPagesWithGuard (
-  IN UINT64           Start,
-  IN UINTN            NumberOfPages,
-  IN EFI_MEMORY_TYPE  NewType
-  );
-
-/**
-  Set head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to set guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID.
-**/
-VOID
-SetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  );
-
-/**
-  Unset head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to unset guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID.
-**/
-VOID
-UnsetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  );
-
-/**
-  Adjust the base and number of pages to really allocate according to Guard.
-
-  @param[in,out]  Memory          Base address of free memory.
-  @param[in,out]  NumberOfPages   Size of memory to allocate.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryA (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  );
-
-/**
-  Adjust the start address and number of pages to free according to Guard.
-
-  The purpose of this function is to keep the shared Guard page with adjacent
-  memory block if it's still in guard, or free it if no more sharing. Another
-  is to reserve pages as Guard pages in partial page free situation.
-
-  @param[in,out]  Memory          Base address of memory to free.
-  @param[in,out]  NumberOfPages   Size of memory to free.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryF (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  );
-
-/**
-  Adjust address of free memory according to existing and/or required Guard.
-
-  This function will check if there're existing Guard pages of adjacent
-  memory blocks, and try to use it as the Guard page of the memory to be
-  allocated.
-
-  @param[in]  Start           Start address of free memory block.
-  @param[in]  Size            Size of free memory block.
-  @param[in]  SizeRequested   Size of memory to allocate.
-
-  @return The end address of memory block found.
-  @return 0 if no enough space for the required size of memory and its Guard.
-**/
-UINT64
-AdjustMemoryS (
-  IN UINT64                  Start,
-  IN UINT64                  Size,
-  IN UINT64                  SizeRequested
-  );
-
-/**
-  Check to see if the pool at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Pool type to check.
-
-
-  @return TRUE  The given type of pool should be guarded.
-  @return FALSE The given type of pool should not be guarded.
-**/
-BOOLEAN
-IsPoolTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType
-  );
-
-/**
-  Check to see if the page at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Page type to check.
-  @param[in]  AllocateType    Allocation type to check.
-
-  @return TRUE  The given type of page should be guarded.
-  @return FALSE The given type of page should not be guarded.
-**/
-BOOLEAN
-IsPageTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN EFI_ALLOCATE_TYPE      AllocateType
-  );
-
-/**
-  Check to see if the page at the given address is guarded or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is guarded.
-  @return FALSE The page at Address is not guarded.
-**/
-BOOLEAN
-EFIAPI
-IsMemoryGuarded (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  );
-
-/**
-  Check to see if the page at the given address is a Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a Guard page.
-  @return FALSE The page at Address is not a Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsGuardPage (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  );
-
-/**
-  Dump the guarded memory bit map.
-**/
-VOID
-EFIAPI
-DumpGuardedMemoryBitmap (
-  VOID
-  );
-
-/**
-  Adjust the pool head position to make sure the Guard page is adjavent to
-  pool tail or pool head.
-
-  @param[in]  Memory    Base address of memory allocated.
-  @param[in]  NoPages   Number of pages actually allocated.
-  @param[in]  Size      Size of memory requested.
-                        (plus pool head/tail overhead)
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadA (
-  IN EFI_PHYSICAL_ADDRESS    Memory,
-  IN UINTN                   NoPages,
-  IN UINTN                   Size
-  );
-
-/**
-  Get the page base address according to pool head address.
-
-  @param[in]  Memory    Head address of pool to free.
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadF (
-  IN EFI_PHYSICAL_ADDRESS    Memory
-  );
-
-extern BOOLEAN mOnGuarding;
-
-#endif
+/** @file\r
+  Data type, macros and function prototypes of heap guard feature.\r
+\r
+Copyright (c) 2017, 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
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#ifndef _HEAPGUARD_H_\r
+#define _HEAPGUARD_H_\r
+\r
+//\r
+// Following macros are used to define and access the guarded memory bitmap\r
+// table.\r
+//\r
+// To simplify the access and reduce the memory used for this table, the\r
+// table is constructed in the similar way as page table structure but in\r
+// reverse direction, i.e. from bottom growing up to top.\r
+//\r
+//    - 1-bit tracks 1 page (4KB)\r
+//    - 1-UINT64 map entry tracks 256KB memory\r
+//    - 1K-UINT64 map table tracks 256MB memory\r
+//    - Five levels of tables can track any address of memory of 64-bit\r
+//      system, like below.\r
+//\r
+//       512   *   512   *   512   *   512    *    1K   *  64b *     4K\r
+//    111111111 111111111 111111111 111111111 1111111111 111111 111111111111\r
+//    63        54        45        36        27         17     11         0\r
+//       9b        9b        9b        9b         10b      6b       12b\r
+//       L0   ->   L1   ->   L2   ->   L3   ->    L4   -> bits  ->  page\r
+//      1FF       1FF       1FF       1FF         3FF      3F       FFF\r
+//\r
+// L4 table has 1K * sizeof(UINT64) = 8K (2-page), which can track 256MB\r
+// memory. Each table of L0-L3 will be allocated when its memory address\r
+// range is to be tracked. Only 1-page will be allocated each time. This\r
+// can save memories used to establish this map table.\r
+//\r
+// For a normal configuration of system with 4G memory, two levels of tables\r
+// can track the whole memory, because two levels (L3+L4) of map tables have\r
+// already coverred 37-bit of memory address. And for a normal UEFI BIOS,\r
+// less than 128M memory would be consumed during boot. That means we just\r
+// need\r
+//\r
+//          1-page (L3) + 2-page (L4)\r
+//\r
+// memory (3 pages) to track the memory allocation works. In this case,\r
+// there's no need to setup L0-L2 tables.\r
+//\r
+\r
+//\r
+// Each entry occupies 8B/64b. 1-page can hold 512 entries, which spans 9\r
+// bits in address. (512 = 1 << 9)\r
+//\r
+#define BYTE_LENGTH_SHIFT                   3             // (8 = 1 << 3)\r
+\r
+#define GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT  \\r
+        (EFI_PAGE_SHIFT - BYTE_LENGTH_SHIFT)\r
+\r
+#define GUARDED_HEAP_MAP_TABLE_DEPTH        5\r
+\r
+// Use UINT64_index + bit_index_of_UINT64 to locate the bit in may\r
+#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT    6             // (64 = 1 << 6)\r
+\r
+#define GUARDED_HEAP_MAP_ENTRY_BITS         \\r
+        (1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)\r
+\r
+#define GUARDED_HEAP_MAP_ENTRY_BYTES        \\r
+        (GUARDED_HEAP_MAP_ENTRY_BITS / 8)\r
+\r
+// L4 table address width: 64 - 9 * 4 - 6 - 12 = 10b\r
+#define GUARDED_HEAP_MAP_ENTRY_SHIFT              \\r
+        (GUARDED_HEAP_MAP_ENTRY_BITS              \\r
+         - GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 4 \\r
+         - GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT       \\r
+         - EFI_PAGE_SHIFT)\r
+\r
+// L4 table address mask: (1 << 10 - 1) = 0x3FF\r
+#define GUARDED_HEAP_MAP_ENTRY_MASK               \\r
+        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1)\r
+\r
+// Size of each L4 table: (1 << 10) * 8 = 8KB = 2-page\r
+#define GUARDED_HEAP_MAP_SIZE                     \\r
+        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) * GUARDED_HEAP_MAP_ENTRY_BYTES)\r
+\r
+// Memory size tracked by one L4 table: 8KB * 8 * 4KB = 256MB\r
+#define GUARDED_HEAP_MAP_UNIT_SIZE                \\r
+        (GUARDED_HEAP_MAP_SIZE * 8 * EFI_PAGE_SIZE)\r
+\r
+// L4 table entry number: 8KB / 8 = 1024\r
+#define GUARDED_HEAP_MAP_ENTRIES_PER_UNIT         \\r
+        (GUARDED_HEAP_MAP_SIZE / GUARDED_HEAP_MAP_ENTRY_BYTES)\r
+\r
+// L4 table entry indexing\r
+#define GUARDED_HEAP_MAP_ENTRY_INDEX(Address)                       \\r
+        (RShiftU64 (Address, EFI_PAGE_SHIFT                         \\r
+                             + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)    \\r
+         & GUARDED_HEAP_MAP_ENTRY_MASK)\r
+\r
+// L4 table entry bit indexing\r
+#define GUARDED_HEAP_MAP_ENTRY_BIT_INDEX(Address)       \\r
+        (RShiftU64 (Address, EFI_PAGE_SHIFT)            \\r
+         & ((1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT) - 1))\r
+\r
+//\r
+// Total bits (pages) tracked by one L4 table (65536-bit)\r
+//\r
+#define GUARDED_HEAP_MAP_BITS                               \\r
+        (1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \\r
+               + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT))\r
+\r
+//\r
+// Bit indexing inside the whole L4 table (0 - 65535)\r
+//\r
+#define GUARDED_HEAP_MAP_BIT_INDEX(Address)                     \\r
+        (RShiftU64 (Address, EFI_PAGE_SHIFT)                    \\r
+         & ((1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \\r
+                   + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)) - 1))\r
+\r
+//\r
+// Memory address bit width tracked by L4 table: 10 + 6 + 12 = 28\r
+//\r
+#define GUARDED_HEAP_MAP_TABLE_SHIFT                                      \\r
+        (GUARDED_HEAP_MAP_ENTRY_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT  \\r
+         + EFI_PAGE_SHIFT)\r
+\r
+//\r
+// Macro used to initialize the local array variable for map table traversing\r
+// {55, 46, 37, 28, 18}\r
+//\r
+#define GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS                                 \\r
+  {                                                                         \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 3,  \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 2,  \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT,      \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT,                                           \\r
+    EFI_PAGE_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT                       \\r
+  }\r
+\r
+//\r
+// Masks used to extract address range of each level of table\r
+// {0x1FF, 0x1FF, 0x1FF, 0x1FF, 0x3FF}\r
+//\r
+#define GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS                                  \\r
+  {                                                                         \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1                                 \\r
+  }\r
+\r
+//\r
+// Memory type to guard (matching the related PCD definition)\r
+//\r
+#define GUARD_HEAP_TYPE_POOL        BIT0\r
+#define GUARD_HEAP_TYPE_PAGE        BIT1\r
+\r
+//\r
+// Debug message level\r
+//\r
+#define HEAP_GUARD_DEBUG_LEVEL  (DEBUG_POOL|DEBUG_PAGE)\r
+\r
+typedef struct {\r
+  UINT32                TailMark;\r
+  UINT32                HeadMark;\r
+  EFI_PHYSICAL_ADDRESS  Address;\r
+  LIST_ENTRY            Link;\r
+} HEAP_GUARD_NODE;\r
+\r
+/**\r
+  Internal function.  Converts a memory range to the specified type.\r
+  The range must exist in the memory map.\r
+\r
+  @param  Start                  The first address of the range Must be page\r
+                                 aligned.\r
+  @param  NumberOfPages          The number of pages to convert.\r
+  @param  NewType                The new type for the memory range.\r
+\r
+  @retval EFI_INVALID_PARAMETER  Invalid parameter.\r
+  @retval EFI_NOT_FOUND          Could not find a descriptor cover the specified\r
+                                 range or convertion not allowed.\r
+  @retval EFI_SUCCESS            Successfully converts the memory range to the\r
+                                 specified type.\r
+\r
+**/\r
+EFI_STATUS\r
+CoreConvertPages (\r
+  IN UINT64           Start,\r
+  IN UINT64           NumberOfPages,\r
+  IN EFI_MEMORY_TYPE  NewType\r
+  );\r
+\r
+/**\r
+  Allocate or free guarded memory.\r
+\r
+  @param[in]  Start           Start address of memory to allocate or free.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+  @param[in]  NewType         Memory type to convert to.\r
+\r
+  @return VOID.\r
+**/\r
+EFI_STATUS\r
+CoreConvertPagesWithGuard (\r
+  IN UINT64           Start,\r
+  IN UINTN            NumberOfPages,\r
+  IN EFI_MEMORY_TYPE  NewType\r
+  );\r
+\r
+/**\r
+  Set head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to set guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+SetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  );\r
+\r
+/**\r
+  Unset head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to unset guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+UnsetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  );\r
+\r
+/**\r
+  Adjust the base and number of pages to really allocate according to Guard.\r
+\r
+  @param[in,out]  Memory          Base address of free memory.\r
+  @param[in,out]  NumberOfPages   Size of memory to allocate.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryA (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  );\r
+\r
+/**\r
+  Adjust the start address and number of pages to free according to Guard.\r
+\r
+  The purpose of this function is to keep the shared Guard page with adjacent\r
+  memory block if it's still in guard, or free it if no more sharing. Another\r
+  is to reserve pages as Guard pages in partial page free situation.\r
+\r
+  @param[in,out]  Memory          Base address of memory to free.\r
+  @param[in,out]  NumberOfPages   Size of memory to free.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryF (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  );\r
+\r
+/**\r
+  Adjust address of free memory according to existing and/or required Guard.\r
+\r
+  This function will check if there're existing Guard pages of adjacent\r
+  memory blocks, and try to use it as the Guard page of the memory to be\r
+  allocated.\r
+\r
+  @param[in]  Start           Start address of free memory block.\r
+  @param[in]  Size            Size of free memory block.\r
+  @param[in]  SizeRequested   Size of memory to allocate.\r
+\r
+  @return The end address of memory block found.\r
+  @return 0 if no enough space for the required size of memory and its Guard.\r
+**/\r
+UINT64\r
+AdjustMemoryS (\r
+  IN UINT64                  Start,\r
+  IN UINT64                  Size,\r
+  IN UINT64                  SizeRequested\r
+  );\r
+\r
+/**\r
+  Check to see if the pool at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Pool type to check.\r
+\r
+\r
+  @return TRUE  The given type of pool should be guarded.\r
+  @return FALSE The given type of pool should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPoolTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType\r
+  );\r
+\r
+/**\r
+  Check to see if the page at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Page type to check.\r
+  @param[in]  AllocateType    Allocation type to check.\r
+\r
+  @return TRUE  The given type of page should be guarded.\r
+  @return FALSE The given type of page should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPageTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN EFI_ALLOCATE_TYPE      AllocateType\r
+  );\r
+\r
+/**\r
+  Check to see if the page at the given address is guarded or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is guarded.\r
+  @return FALSE The page at Address is not guarded.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsMemoryGuarded (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  );\r
+\r
+/**\r
+  Check to see if the page at the given address is a Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a Guard page.\r
+  @return FALSE The page at Address is not a Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsGuardPage (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  );\r
+\r
+/**\r
+  Dump the guarded memory bit map.\r
+**/\r
+VOID\r
+EFIAPI\r
+DumpGuardedMemoryBitmap (\r
+  VOID\r
+  );\r
+\r
+/**\r
+  Adjust the pool head position to make sure the Guard page is adjavent to\r
+  pool tail or pool head.\r
+\r
+  @param[in]  Memory    Base address of memory allocated.\r
+  @param[in]  NoPages   Number of pages actually allocated.\r
+  @param[in]  Size      Size of memory requested.\r
+                        (plus pool head/tail overhead)\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadA (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory,\r
+  IN UINTN                   NoPages,\r
+  IN UINTN                   Size\r
+  );\r
+\r
+/**\r
+  Get the page base address according to pool head address.\r
+\r
+  @param[in]  Memory    Head address of pool to free.\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadF (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory\r
+  );\r
+\r
+extern BOOLEAN mOnGuarding;\r
+\r
+#endif\r
index 8a6ae50b8863ce7c96a06c7e8089f3f88d3002b8..e58a5d62babbd18eda6e6440ca5ade1be6b71a64 100644 (file)
@@ -1,7 +1,7 @@
 /** @file\r
   Data structure and functions to allocate and free memory space.\r
 \r
 /** @file\r
   Data structure and functions to allocate and free memory space.\r
 \r
-Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
+Copyright (c) 2006 - 2017, 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
 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
@@ -61,7 +61,7 @@ typedef struct {
   @param  PoolType               The type of memory for the new pool pages\r
   @param  NumberOfPages          No of pages to allocate\r
   @param  Alignment              Bits to align.\r
   @param  PoolType               The type of memory for the new pool pages\r
   @param  NumberOfPages          No of pages to allocate\r
   @param  Alignment              Bits to align.\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The allocated memory, or NULL\r
 \r
 \r
   @return The allocated memory, or NULL\r
 \r
@@ -70,8 +70,8 @@ VOID *
 CoreAllocatePoolPages (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NumberOfPages,\r
 CoreAllocatePoolPages (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NumberOfPages,\r
-  IN UINTN              Alignment,
-  IN BOOLEAN            NeedGuard
+  IN UINTN              Alignment,\r
+  IN BOOLEAN            NeedGuard\r
   );\r
 \r
 \r
   );\r
 \r
 \r
@@ -97,7 +97,7 @@ CoreFreePoolPages (
 \r
   @param  PoolType               Type of pool to allocate\r
   @param  Size                   The amount of pool to allocate\r
 \r
   @param  PoolType               Type of pool to allocate\r
   @param  Size                   The amount of pool to allocate\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The allocate pool, or NULL\r
 \r
 \r
   @return The allocate pool, or NULL\r
 \r
@@ -105,8 +105,8 @@ CoreFreePoolPages (
 VOID *\r
 CoreAllocatePoolI (\r
   IN EFI_MEMORY_TYPE  PoolType,\r
 VOID *\r
 CoreAllocatePoolI (\r
   IN EFI_MEMORY_TYPE  PoolType,\r
-  IN UINTN            Size,
-  IN BOOLEAN          NeedGuard
+  IN UINTN            Size,\r
+  IN BOOLEAN          NeedGuard\r
   );\r
 \r
 \r
   );\r
 \r
 \r
@@ -149,34 +149,34 @@ CoreReleaseMemoryLock (
   VOID\r
   );\r
 \r
   VOID\r
   );\r
 \r
-/**
-  Allocates pages from the memory map.
-
-  @param  Type                   The type of allocation to perform
-  @param  MemoryType             The type of memory to turn the allocated pages
-                                 into
-  @param  NumberOfPages          The number of pages to allocate
-  @param  Memory                 A pointer to receive the base allocated memory
-                                 address
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
-
-  @return Status. On success, Memory is filled in with the base address allocated
-  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in
-                                 spec.
-  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.
-  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.
-  @retval EFI_SUCCESS            Pages successfully allocated.
-
-**/
-EFI_STATUS
-EFIAPI
-CoreInternalAllocatePages (
-  IN EFI_ALLOCATE_TYPE      Type,
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN UINTN                  NumberOfPages,
-  IN OUT EFI_PHYSICAL_ADDRESS  *Memory,
-  IN BOOLEAN                NeedGuard
-  );
+/**\r
+  Allocates pages from the memory map.\r
+\r
+  @param  Type                   The type of allocation to perform\r
+  @param  MemoryType             The type of memory to turn the allocated pages\r
+                                 into\r
+  @param  NumberOfPages          The number of pages to allocate\r
+  @param  Memory                 A pointer to receive the base allocated memory\r
+                                 address\r
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
+\r
+  @return Status. On success, Memory is filled in with the base address allocated\r
+  @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in\r
+                                 spec.\r
+  @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
+  @retval EFI_OUT_OF_RESOURCES   No enough pages to allocate.\r
+  @retval EFI_SUCCESS            Pages successfully allocated.\r
+\r
+**/\r
+EFI_STATUS\r
+EFIAPI\r
+CoreInternalAllocatePages (\r
+  IN EFI_ALLOCATE_TYPE      Type,\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN UINTN                  NumberOfPages,\r
+  IN OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
+  IN BOOLEAN                NeedGuard\r
+  );\r
 \r
 //\r
 // Internal Global data\r
 \r
 //\r
 // Internal Global data\r
index f1e4a37f2af644ca0b673d60f65e824671d90c8a..2034b64cd72d0d4e3c9af9372fa06cfc7f2a5fa1 100644 (file)
@@ -14,7 +14,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 \r
 #include "DxeMain.h"\r
 #include "Imem.h"\r
 \r
 #include "DxeMain.h"\r
 #include "Imem.h"\r
-#include "HeapGuard.h"
+#include "HeapGuard.h"\r
 \r
 //\r
 // Entry for tracking the memory regions for each memory type to coalesce similar memory types\r
 \r
 //\r
 // Entry for tracking the memory regions for each memory type to coalesce similar memory types\r
@@ -288,12 +288,12 @@ AllocateMemoryMapEntry (
     //\r
     // The list is empty, to allocate one page to refuel the list\r
     //\r
     //\r
     // The list is empty, to allocate one page to refuel the list\r
     //\r
-    FreeDescriptorEntries = CoreAllocatePoolPages (
-                              EfiBootServicesData,
+    FreeDescriptorEntries = CoreAllocatePoolPages (\r
+                              EfiBootServicesData,\r
                               EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION_GRANULARITY),\r
                               EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION_GRANULARITY),\r
-                              DEFAULT_PAGE_ALLOCATION_GRANULARITY,
-                              FALSE
-                              );
+                              DEFAULT_PAGE_ALLOCATION_GRANULARITY,\r
+                              FALSE\r
+                              );\r
     if (FreeDescriptorEntries != NULL) {\r
       //\r
       // Enque the free memmory map entries into the list\r
     if (FreeDescriptorEntries != NULL) {\r
       //\r
       // Enque the free memmory map entries into the list\r
@@ -901,40 +901,40 @@ CoreConvertPagesEx (
     CoreAddRange (MemType, Start, RangeEnd, Attribute);\r
     if (ChangingType && (MemType == EfiConventionalMemory)) {\r
       if (Start == 0) {\r
     CoreAddRange (MemType, Start, RangeEnd, Attribute);\r
     if (ChangingType && (MemType == EfiConventionalMemory)) {\r
       if (Start == 0) {\r
-        //
-        // Avoid calling DEBUG_CLEAR_MEMORY() for an address of 0 because this
-        // macro will ASSERT() if address is 0.  Instead, CoreAddRange()
-        // guarantees that the page starting at address 0 is always filled
-        // with zeros.
-        //
+        //\r
+        // Avoid calling DEBUG_CLEAR_MEMORY() for an address of 0 because this\r
+        // macro will ASSERT() if address is 0.  Instead, CoreAddRange()\r
+        // guarantees that the page starting at address 0 is always filled\r
+        // with zeros.\r
+        //\r
         if (RangeEnd > EFI_PAGE_SIZE) {\r
           DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) EFI_PAGE_SIZE, (UINTN) (RangeEnd - EFI_PAGE_SIZE + 1));\r
         }\r
       } else {\r
         if (RangeEnd > EFI_PAGE_SIZE) {\r
           DEBUG_CLEAR_MEMORY ((VOID *)(UINTN) EFI_PAGE_SIZE, (UINTN) (RangeEnd - EFI_PAGE_SIZE + 1));\r
         }\r
       } else {\r
-        //
-        // If Heap Guard is enabled, the page at the top and/or bottom of
-        // this memory block to free might be inaccessible. Skipping them
-        // to avoid page fault exception.
-        //
-        UINT64  StartToClear;
-        UINT64  EndToClear;
-
-        StartToClear = Start;
-        EndToClear   = RangeEnd;
-        if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {
-          if (IsGuardPage(StartToClear)) {
-            StartToClear += EFI_PAGE_SIZE;
-          }
-          if (IsGuardPage (EndToClear)) {
-            EndToClear -= EFI_PAGE_SIZE;
-          }
-          ASSERT (EndToClear > StartToClear);
-        }
-
-        DEBUG_CLEAR_MEMORY(
-          (VOID *)(UINTN)StartToClear,
-          (UINTN)(EndToClear - StartToClear + 1)
-          );
+        //\r
+        // If Heap Guard is enabled, the page at the top and/or bottom of\r
+        // this memory block to free might be inaccessible. Skipping them\r
+        // to avoid page fault exception.\r
+        //\r
+        UINT64  StartToClear;\r
+        UINT64  EndToClear;\r
+\r
+        StartToClear = Start;\r
+        EndToClear   = RangeEnd;\r
+        if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {\r
+          if (IsGuardPage(StartToClear)) {\r
+            StartToClear += EFI_PAGE_SIZE;\r
+          }\r
+          if (IsGuardPage (EndToClear)) {\r
+            EndToClear -= EFI_PAGE_SIZE;\r
+          }\r
+          ASSERT (EndToClear > StartToClear);\r
+        }\r
+\r
+        DEBUG_CLEAR_MEMORY(\r
+          (VOID *)(UINTN)StartToClear,\r
+          (UINTN)(EndToClear - StartToClear + 1)\r
+          );\r
       }\r
     }\r
 \r
       }\r
     }\r
 \r
@@ -1021,7 +1021,7 @@ CoreUpdateMemoryAttributes (
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
   @param  Alignment              Bits to align with\r
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
   @param  Alignment              Bits to align with\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The base address of the range, or 0 if the range was not found\r
 \r
 \r
   @return The base address of the range, or 0 if the range was not found\r
 \r
@@ -1032,8 +1032,8 @@ CoreFindFreePagesI (
   IN UINT64           MinAddress,\r
   IN UINT64           NumberOfPages,\r
   IN EFI_MEMORY_TYPE  NewType,\r
   IN UINT64           MinAddress,\r
   IN UINT64           NumberOfPages,\r
   IN EFI_MEMORY_TYPE  NewType,\r
-  IN UINTN            Alignment,
-  IN BOOLEAN          NeedGuard
+  IN UINTN            Alignment,\r
+  IN BOOLEAN          NeedGuard\r
   )\r
 {\r
   UINT64          NumberOfBytes;\r
   )\r
 {\r
   UINT64          NumberOfBytes;\r
@@ -1125,17 +1125,17 @@ CoreFindFreePagesI (
       // If this is the best match so far remember it\r
       //\r
       if (DescEnd > Target) {\r
       // If this is the best match so far remember it\r
       //\r
       if (DescEnd > Target) {\r
-        if (NeedGuard) {
-          DescEnd = AdjustMemoryS (
-                      DescEnd + 1 - DescNumberOfBytes,
-                      DescNumberOfBytes,
-                      NumberOfBytes
-                      );
-          if (DescEnd == 0) {
-            continue;
-          }
-        }
-
+        if (NeedGuard) {\r
+          DescEnd = AdjustMemoryS (\r
+                      DescEnd + 1 - DescNumberOfBytes,\r
+                      DescNumberOfBytes,\r
+                      NumberOfBytes\r
+                      );\r
+          if (DescEnd == 0) {\r
+            continue;\r
+          }\r
+        }\r
+\r
         Target = DescEnd;\r
       }\r
     }\r
         Target = DescEnd;\r
       }\r
     }\r
@@ -1166,7 +1166,7 @@ CoreFindFreePagesI (
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
   @param  Alignment              Bits to align with\r
   @param  NewType                The type of memory the range is going to be\r
                                  turned into\r
   @param  Alignment              Bits to align with\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The base address of the range, or 0 if the range was not found.\r
 \r
 \r
   @return The base address of the range, or 0 if the range was not found.\r
 \r
@@ -1176,8 +1176,8 @@ FindFreePages (
     IN UINT64           MaxAddress,\r
     IN UINT64           NoPages,\r
     IN EFI_MEMORY_TYPE  NewType,\r
     IN UINT64           MaxAddress,\r
     IN UINT64           NoPages,\r
     IN EFI_MEMORY_TYPE  NewType,\r
-    IN UINTN            Alignment,
-    IN BOOLEAN          NeedGuard
+    IN UINTN            Alignment,\r
+    IN BOOLEAN          NeedGuard\r
     )\r
 {\r
   UINT64   Start;\r
     )\r
 {\r
   UINT64   Start;\r
@@ -1191,8 +1191,8 @@ FindFreePages (
               mMemoryTypeStatistics[NewType].BaseAddress, \r
               NoPages, \r
               NewType, \r
               mMemoryTypeStatistics[NewType].BaseAddress, \r
               NoPages, \r
               NewType, \r
-              Alignment,
-              NeedGuard
+              Alignment,\r
+              NeedGuard\r
               );\r
     if (Start != 0) {\r
       return Start;\r
               );\r
     if (Start != 0) {\r
       return Start;\r
@@ -1203,8 +1203,8 @@ FindFreePages (
   // Attempt to find free pages in the default allocation bin\r
   //\r
   if (MaxAddress >= mDefaultMaximumAddress) {\r
   // Attempt to find free pages in the default allocation bin\r
   //\r
   if (MaxAddress >= mDefaultMaximumAddress) {\r
-    Start = CoreFindFreePagesI (mDefaultMaximumAddress, 0, NoPages, NewType,
-                                Alignment, NeedGuard);
+    Start = CoreFindFreePagesI (mDefaultMaximumAddress, 0, NoPages, NewType,\r
+                                Alignment, NeedGuard);\r
     if (Start != 0) {\r
       if (Start < mDefaultBaseAddress) {\r
         mDefaultBaseAddress = Start;\r
     if (Start != 0) {\r
       if (Start < mDefaultBaseAddress) {\r
         mDefaultBaseAddress = Start;\r
@@ -1219,8 +1219,8 @@ FindFreePages (
   // address range.  If this allocation fails, then there are not enough \r
   // resources anywhere to satisfy the request.\r
   //\r
   // address range.  If this allocation fails, then there are not enough \r
   // resources anywhere to satisfy the request.\r
   //\r
-  Start = CoreFindFreePagesI (MaxAddress, 0, NoPages, NewType, Alignment,
-                              NeedGuard);
+  Start = CoreFindFreePagesI (MaxAddress, 0, NoPages, NewType, Alignment,\r
+                              NeedGuard);\r
   if (Start != 0) {\r
     return Start;\r
   }\r
   if (Start != 0) {\r
     return Start;\r
   }\r
@@ -1235,7 +1235,7 @@ FindFreePages (
   //\r
   // If any memory resources were promoted, then re-attempt the allocation\r
   //\r
   //\r
   // If any memory resources were promoted, then re-attempt the allocation\r
   //\r
-  return FindFreePages (MaxAddress, NoPages, NewType, Alignment, NeedGuard);
+  return FindFreePages (MaxAddress, NoPages, NewType, Alignment, NeedGuard);\r
 }\r
 \r
 \r
 }\r
 \r
 \r
@@ -1248,7 +1248,7 @@ FindFreePages (
   @param  NumberOfPages          The number of pages to allocate\r
   @param  Memory                 A pointer to receive the base allocated memory\r
                                  address\r
   @param  NumberOfPages          The number of pages to allocate\r
   @param  Memory                 A pointer to receive the base allocated memory\r
                                  address\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return Status. On success, Memory is filled in with the base address allocated\r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in\r
 \r
   @return Status. On success, Memory is filled in with the base address allocated\r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in\r
@@ -1264,8 +1264,8 @@ CoreInternalAllocatePages (
   IN EFI_ALLOCATE_TYPE      Type,\r
   IN EFI_MEMORY_TYPE        MemoryType,\r
   IN UINTN                  NumberOfPages,\r
   IN EFI_ALLOCATE_TYPE      Type,\r
   IN EFI_MEMORY_TYPE        MemoryType,\r
   IN UINTN                  NumberOfPages,\r
-  IN OUT EFI_PHYSICAL_ADDRESS  *Memory,
-  IN BOOLEAN                NeedGuard
+  IN OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
+  IN BOOLEAN                NeedGuard\r
   )\r
 {\r
   EFI_STATUS      Status;\r
   )\r
 {\r
   EFI_STATUS      Status;\r
@@ -1351,8 +1351,8 @@ CoreInternalAllocatePages (
   // If not a specific address, then find an address to allocate\r
   //\r
   if (Type != AllocateAddress) {\r
   // If not a specific address, then find an address to allocate\r
   //\r
   if (Type != AllocateAddress) {\r
-    Start = FindFreePages (MaxAddress, NumberOfPages, MemoryType, Alignment,
-                           NeedGuard);
+    Start = FindFreePages (MaxAddress, NumberOfPages, MemoryType, Alignment,\r
+                           NeedGuard);\r
     if (Start == 0) {\r
       Status = EFI_OUT_OF_RESOURCES;\r
       goto Done;\r
     if (Start == 0) {\r
       Status = EFI_OUT_OF_RESOURCES;\r
       goto Done;\r
@@ -1362,19 +1362,19 @@ CoreInternalAllocatePages (
   //\r
   // Convert pages from FreeMemory to the requested type\r
   //\r
   //\r
   // Convert pages from FreeMemory to the requested type\r
   //\r
-  if (NeedGuard) {
-    Status = CoreConvertPagesWithGuard(Start, NumberOfPages, MemoryType);
-  } else {
-    Status = CoreConvertPages(Start, NumberOfPages, MemoryType);
-  }
+  if (NeedGuard) {\r
+    Status = CoreConvertPagesWithGuard(Start, NumberOfPages, MemoryType);\r
+  } else {\r
+    Status = CoreConvertPages(Start, NumberOfPages, MemoryType);\r
+  }\r
 \r
 Done:\r
   CoreReleaseMemoryLock ();\r
 \r
   if (!EFI_ERROR (Status)) {\r
 \r
 Done:\r
   CoreReleaseMemoryLock ();\r
 \r
   if (!EFI_ERROR (Status)) {\r
-    if (NeedGuard) {
-      SetGuardForMemory (Start, NumberOfPages);
-    }
+    if (NeedGuard) {\r
+      SetGuardForMemory (Start, NumberOfPages);\r
+    }\r
     *Memory = Start;\r
   }\r
 \r
     *Memory = Start;\r
   }\r
 \r
@@ -1409,11 +1409,11 @@ CoreAllocatePages (
   )\r
 {\r
   EFI_STATUS  Status;\r
   )\r
 {\r
   EFI_STATUS  Status;\r
-  BOOLEAN     NeedGuard;
+  BOOLEAN     NeedGuard;\r
 \r
 \r
-  NeedGuard = IsPageTypeToGuard (MemoryType, Type) && !mOnGuarding;
-  Status = CoreInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory,
-                                      NeedGuard);
+  NeedGuard = IsPageTypeToGuard (MemoryType, Type) && !mOnGuarding;\r
+  Status = CoreInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory,\r
+                                      NeedGuard);\r
   if (!EFI_ERROR (Status)) {\r
     CoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
   if (!EFI_ERROR (Status)) {\r
     CoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
@@ -1454,7 +1454,7 @@ CoreInternalFreePages (
   LIST_ENTRY      *Link;\r
   MEMORY_MAP      *Entry;\r
   UINTN           Alignment;\r
   LIST_ENTRY      *Link;\r
   MEMORY_MAP      *Entry;\r
   UINTN           Alignment;\r
-  BOOLEAN         IsGuarded;
+  BOOLEAN         IsGuarded;\r
 \r
   //\r
   // Free the range\r
 \r
   //\r
   // Free the range\r
@@ -1464,7 +1464,7 @@ CoreInternalFreePages (
   //\r
   // Find the entry that the covers the range\r
   //\r
   //\r
   // Find the entry that the covers the range\r
   //\r
-  IsGuarded = FALSE;
+  IsGuarded = FALSE;\r
   Entry = NULL;\r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
   Entry = NULL;\r
   for (Link = gMemoryMap.ForwardLink; Link != &gMemoryMap; Link = Link->ForwardLink) {\r
     Entry = CR(Link, MEMORY_MAP, Link, MEMORY_MAP_SIGNATURE);\r
@@ -1501,20 +1501,20 @@ CoreInternalFreePages (
     *MemoryType = Entry->Type;\r
   }\r
 \r
     *MemoryType = Entry->Type;\r
   }\r
 \r
-  IsGuarded = IsPageTypeToGuard (Entry->Type, AllocateAnyPages) &&
-              IsMemoryGuarded (Memory);
-  if (IsGuarded) {
-    Status = CoreConvertPagesWithGuard (Memory, NumberOfPages,
-                                        EfiConventionalMemory);
-  } else {
-    Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);
+  IsGuarded = IsPageTypeToGuard (Entry->Type, AllocateAnyPages) &&\r
+              IsMemoryGuarded (Memory);\r
+  if (IsGuarded) {\r
+    Status = CoreConvertPagesWithGuard (Memory, NumberOfPages,\r
+                                        EfiConventionalMemory);\r
+  } else {\r
+    Status = CoreConvertPages (Memory, NumberOfPages, EfiConventionalMemory);\r
   }\r
 \r
 Done:\r
   CoreReleaseMemoryLock ();\r
   }\r
 \r
 Done:\r
   CoreReleaseMemoryLock ();\r
-  if (IsGuarded) {
-    UnsetGuardForMemory(Memory, NumberOfPages);
-  }
+  if (IsGuarded) {\r
+    UnsetGuardForMemory(Memory, NumberOfPages);\r
+  }\r
   return Status;\r
 }\r
 \r
   return Status;\r
 }\r
 \r
@@ -1912,12 +1912,12 @@ Done:
 \r
   *MemoryMapSize = BufferSize;\r
 \r
 \r
   *MemoryMapSize = BufferSize;\r
 \r
-  DEBUG_CODE (
-    if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {
-      DumpGuardedMemoryBitmap ();
-    }
-  );
-
+  DEBUG_CODE (\r
+    if (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT1|BIT0)) {\r
+      DumpGuardedMemoryBitmap ();\r
+    }\r
+  );\r
+\r
   return Status;\r
 }\r
 \r
   return Status;\r
 }\r
 \r
@@ -1929,7 +1929,7 @@ Done:
   @param  PoolType               The type of memory for the new pool pages\r
   @param  NumberOfPages          No of pages to allocate\r
   @param  Alignment              Bits to align.\r
   @param  PoolType               The type of memory for the new pool pages\r
   @param  NumberOfPages          No of pages to allocate\r
   @param  Alignment              Bits to align.\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The allocated memory, or NULL\r
 \r
 \r
   @return The allocated memory, or NULL\r
 \r
@@ -1938,8 +1938,8 @@ VOID *
 CoreAllocatePoolPages (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NumberOfPages,\r
 CoreAllocatePoolPages (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NumberOfPages,\r
-  IN UINTN              Alignment,
-  IN BOOLEAN            NeedGuard
+  IN UINTN              Alignment,\r
+  IN BOOLEAN            NeedGuard\r
   )\r
 {\r
   UINT64            Start;\r
   )\r
 {\r
   UINT64            Start;\r
@@ -1947,8 +1947,8 @@ CoreAllocatePoolPages (
   //\r
   // Find the pages to convert\r
   //\r
   //\r
   // Find the pages to convert\r
   //\r
-  Start = FindFreePages (MAX_ADDRESS, NumberOfPages, PoolType, Alignment,
-                         NeedGuard);
+  Start = FindFreePages (MAX_ADDRESS, NumberOfPages, PoolType, Alignment,\r
+                         NeedGuard);\r
 \r
   //\r
   // Convert it to boot services data\r
 \r
   //\r
   // Convert it to boot services data\r
@@ -1956,11 +1956,11 @@ CoreAllocatePoolPages (
   if (Start == 0) {\r
     DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "AllocatePoolPages: failed to allocate %d pages\n", (UINT32)NumberOfPages));\r
   } else {\r
   if (Start == 0) {\r
     DEBUG ((DEBUG_ERROR | DEBUG_PAGE, "AllocatePoolPages: failed to allocate %d pages\n", (UINT32)NumberOfPages));\r
   } else {\r
-    if (NeedGuard) {
-      CoreConvertPagesWithGuard (Start, NumberOfPages, PoolType);
-    } else {
-      CoreConvertPages (Start, NumberOfPages, PoolType);
-    }
+    if (NeedGuard) {\r
+      CoreConvertPagesWithGuard (Start, NumberOfPages, PoolType);\r
+    } else {\r
+      CoreConvertPages (Start, NumberOfPages, PoolType);\r
+    }\r
   }\r
 \r
   return (VOID *)(UINTN) Start;\r
   }\r
 \r
   return (VOID *)(UINTN) Start;\r
index 77ca5671dcfea69d08273d18c8823f871c8d32e3..b82b51595c77335a8dece9a2aa6f892c019c9e51 100644 (file)
@@ -14,7 +14,7 @@ WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 \r
 #include "DxeMain.h"\r
 #include "Imem.h"\r
 \r
 #include "DxeMain.h"\r
 #include "Imem.h"\r
-#include "HeapGuard.h"
+#include "HeapGuard.h"\r
 \r
 STATIC EFI_LOCK mPoolMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY);\r
 \r
 \r
 STATIC EFI_LOCK mPoolMemoryLock = EFI_INITIALIZE_LOCK_VARIABLE (TPL_NOTIFY);\r
 \r
@@ -170,7 +170,7 @@ LookupPoolHead (
       }\r
     }\r
 \r
       }\r
     }\r
 \r
-    Pool = CoreAllocatePoolI (EfiBootServicesData, sizeof (POOL), FALSE);
+    Pool = CoreAllocatePoolI (EfiBootServicesData, sizeof (POOL), FALSE);\r
     if (Pool == NULL) {\r
       return NULL;\r
     }\r
     if (Pool == NULL) {\r
       return NULL;\r
     }\r
@@ -215,8 +215,8 @@ CoreInternalAllocatePool (
   OUT VOID            **Buffer\r
   )\r
 {\r
   OUT VOID            **Buffer\r
   )\r
 {\r
-  EFI_STATUS            Status;
-  BOOLEAN               NeedGuard;
+  EFI_STATUS            Status;\r
+  BOOLEAN               NeedGuard;\r
 \r
   //\r
   // If it's not a valid type, fail it\r
 \r
   //\r
   // If it's not a valid type, fail it\r
@@ -240,8 +240,8 @@ CoreInternalAllocatePool (
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  NeedGuard = IsPoolTypeToGuard (PoolType) && !mOnGuarding;
-
+  NeedGuard = IsPoolTypeToGuard (PoolType) && !mOnGuarding;\r
+\r
   //\r
   // Acquire the memory lock and make the allocation\r
   //\r
   //\r
   // Acquire the memory lock and make the allocation\r
   //\r
@@ -250,7 +250,7 @@ CoreInternalAllocatePool (
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
     return EFI_OUT_OF_RESOURCES;\r
   }\r
 \r
-  *Buffer = CoreAllocatePoolI (PoolType, Size, NeedGuard);
+  *Buffer = CoreAllocatePoolI (PoolType, Size, NeedGuard);\r
   CoreReleaseLock (&mPoolMemoryLock);\r
   return (*Buffer != NULL) ? EFI_SUCCESS : EFI_OUT_OF_RESOURCES;\r
 }\r
   CoreReleaseLock (&mPoolMemoryLock);\r
   return (*Buffer != NULL) ? EFI_SUCCESS : EFI_OUT_OF_RESOURCES;\r
 }\r
@@ -302,7 +302,7 @@ CoreAllocatePool (
   @param  PoolType               The type of memory for the new pool pages\r
   @param  NoPages                No of pages to allocate\r
   @param  Granularity            Bits to align.\r
   @param  PoolType               The type of memory for the new pool pages\r
   @param  NoPages                No of pages to allocate\r
   @param  Granularity            Bits to align.\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The allocated memory, or NULL\r
 \r
 \r
   @return The allocated memory, or NULL\r
 \r
@@ -312,8 +312,8 @@ VOID *
 CoreAllocatePoolPagesI (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NoPages,\r
 CoreAllocatePoolPagesI (\r
   IN EFI_MEMORY_TYPE    PoolType,\r
   IN UINTN              NoPages,\r
-  IN UINTN              Granularity,
-  IN BOOLEAN            NeedGuard
+  IN UINTN              Granularity,\r
+  IN BOOLEAN            NeedGuard\r
   )\r
 {\r
   VOID        *Buffer;\r
   )\r
 {\r
   VOID        *Buffer;\r
@@ -324,14 +324,14 @@ CoreAllocatePoolPagesI (
     return NULL;\r
   }\r
 \r
     return NULL;\r
   }\r
 \r
-  Buffer = CoreAllocatePoolPages (PoolType, NoPages, Granularity, NeedGuard);
+  Buffer = CoreAllocatePoolPages (PoolType, NoPages, Granularity, NeedGuard);\r
   CoreReleaseMemoryLock ();\r
 \r
   if (Buffer != NULL) {\r
   CoreReleaseMemoryLock ();\r
 \r
   if (Buffer != NULL) {\r
-    if (NeedGuard) {
-      SetGuardForMemory ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, NoPages);
-    }
-    ApplyMemoryProtectionPolicy(EfiConventionalMemory, PoolType,
+    if (NeedGuard) {\r
+      SetGuardForMemory ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, NoPages);\r
+    }\r
+    ApplyMemoryProtectionPolicy(EfiConventionalMemory, PoolType,\r
       (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, EFI_PAGES_TO_SIZE (NoPages));\r
   }\r
   return Buffer;\r
       (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer, EFI_PAGES_TO_SIZE (NoPages));\r
   }\r
   return Buffer;\r
@@ -343,7 +343,7 @@ CoreAllocatePoolPagesI (
 \r
   @param  PoolType               Type of pool to allocate\r
   @param  Size                   The amount of pool to allocate\r
 \r
   @param  PoolType               Type of pool to allocate\r
   @param  Size                   The amount of pool to allocate\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @return The allocate pool, or NULL\r
 \r
 \r
   @return The allocate pool, or NULL\r
 \r
@@ -351,8 +351,8 @@ CoreAllocatePoolPagesI (
 VOID *\r
 CoreAllocatePoolI (\r
   IN EFI_MEMORY_TYPE  PoolType,\r
 VOID *\r
 CoreAllocatePoolI (\r
   IN EFI_MEMORY_TYPE  PoolType,\r
-  IN UINTN            Size,
-  IN BOOLEAN          NeedGuard
+  IN UINTN            Size,\r
+  IN BOOLEAN          NeedGuard\r
   )\r
 {\r
   POOL        *Pool;\r
   )\r
 {\r
   POOL        *Pool;\r
@@ -366,7 +366,7 @@ CoreAllocatePoolI (
   UINTN       Offset, MaxOffset;\r
   UINTN       NoPages;\r
   UINTN       Granularity;\r
   UINTN       Offset, MaxOffset;\r
   UINTN       NoPages;\r
   UINTN       Granularity;\r
-  BOOLEAN     HasPoolTail;
+  BOOLEAN     HasPoolTail;\r
 \r
   ASSERT_LOCKED (&mPoolMemoryLock);\r
 \r
 \r
   ASSERT_LOCKED (&mPoolMemoryLock);\r
 \r
@@ -384,9 +384,9 @@ CoreAllocatePoolI (
   // Adjust the size by the pool header & tail overhead\r
   //\r
 \r
   // Adjust the size by the pool header & tail overhead\r
   //\r
 \r
-  HasPoolTail  = !(NeedGuard &&
-                   ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
-
+  HasPoolTail  = !(NeedGuard &&\r
+                   ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));\r
+\r
   //\r
   // Adjusting the Size to be of proper alignment so that\r
   // we don't get an unaligned access fault later when\r
   //\r
   // Adjusting the Size to be of proper alignment so that\r
   // we don't get an unaligned access fault later when\r
@@ -406,16 +406,16 @@ CoreAllocatePoolI (
   // If allocation is over max size, just allocate pages for the request\r
   // (slow)\r
   //\r
   // If allocation is over max size, just allocate pages for the request\r
   // (slow)\r
   //\r
-  if (Index >= SIZE_TO_LIST (Granularity) || NeedGuard) {
-    if (!HasPoolTail) {
-      Size -= sizeof (POOL_TAIL);
-    }
-    NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1;
+  if (Index >= SIZE_TO_LIST (Granularity) || NeedGuard) {\r
+    if (!HasPoolTail) {\r
+      Size -= sizeof (POOL_TAIL);\r
+    }\r
+    NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1;\r
     NoPages &= ~(UINTN)(EFI_SIZE_TO_PAGES (Granularity) - 1);\r
     NoPages &= ~(UINTN)(EFI_SIZE_TO_PAGES (Granularity) - 1);\r
-    Head = CoreAllocatePoolPagesI (PoolType, NoPages, Granularity, NeedGuard);
-    if (NeedGuard) {
-      Head = AdjustPoolHeadA ((EFI_PHYSICAL_ADDRESS)(UINTN)Head, NoPages, Size);
-    }
+    Head = CoreAllocatePoolPagesI (PoolType, NoPages, Granularity, NeedGuard);\r
+    if (NeedGuard) {\r
+      Head = AdjustPoolHeadA ((EFI_PHYSICAL_ADDRESS)(UINTN)Head, NoPages, Size);\r
+    }\r
     goto Done;\r
   }\r
 \r
     goto Done;\r
   }\r
 \r
@@ -443,8 +443,8 @@ CoreAllocatePoolI (
     //\r
     // Get another page\r
     //\r
     //\r
     // Get another page\r
     //\r
-    NewPage = CoreAllocatePoolPagesI (PoolType, EFI_SIZE_TO_PAGES (Granularity),
-                                      Granularity, NeedGuard);
+    NewPage = CoreAllocatePoolPagesI (PoolType, EFI_SIZE_TO_PAGES (Granularity),\r
+                                      Granularity, NeedGuard);\r
     if (NewPage == NULL) {\r
       goto Done;\r
     }\r
     if (NewPage == NULL) {\r
       goto Done;\r
     }\r
@@ -490,11 +490,11 @@ Done:
 \r
   if (Head != NULL) {\r
 \r
 \r
   if (Head != NULL) {\r
 \r
-    //
-    // Account the allocation
-    //
-    Pool->Used += Size;
-
+    //\r
+    // Account the allocation\r
+    //\r
+    Pool->Used += Size;\r
+\r
     //\r
     // If we have a pool buffer, fill in the header & tail info\r
     //\r
     //\r
     // If we have a pool buffer, fill in the header & tail info\r
     //\r
@@ -502,24 +502,24 @@ Done:
     Head->Size      = Size;\r
     Head->Type      = (EFI_MEMORY_TYPE) PoolType;\r
     Buffer          = Head->Data;\r
     Head->Size      = Size;\r
     Head->Type      = (EFI_MEMORY_TYPE) PoolType;\r
     Buffer          = Head->Data;\r
-
-    if (HasPoolTail) {
-      Tail            = HEAD_TO_TAIL (Head);
-      Tail->Signature = POOL_TAIL_SIGNATURE;
-      Tail->Size      = Size;
-
-      Size -= POOL_OVERHEAD;
-    } else {
-      Size -= SIZE_OF_POOL_HEAD;
-    }
-
-    DEBUG_CLEAR_MEMORY (Buffer, Size);
+\r
+    if (HasPoolTail) {\r
+      Tail            = HEAD_TO_TAIL (Head);\r
+      Tail->Signature = POOL_TAIL_SIGNATURE;\r
+      Tail->Size      = Size;\r
+\r
+      Size -= POOL_OVERHEAD;\r
+    } else {\r
+      Size -= SIZE_OF_POOL_HEAD;\r
+    }\r
+\r
+    DEBUG_CLEAR_MEMORY (Buffer, Size);\r
 \r
     DEBUG ((\r
       DEBUG_POOL,\r
       "AllocatePoolI: Type %x, Addr %p (len %lx) %,ld\n", PoolType,\r
       Buffer,\r
 \r
     DEBUG ((\r
       DEBUG_POOL,\r
       "AllocatePoolI: Type %x, Addr %p (len %lx) %,ld\n", PoolType,\r
       Buffer,\r
-      (UINT64)Size,
+      (UINT64)Size,\r
       (UINT64) Pool->Used\r
       ));\r
 \r
       (UINT64) Pool->Used\r
       ));\r
 \r
@@ -619,34 +619,34 @@ CoreFreePoolPagesI (
     (EFI_PHYSICAL_ADDRESS)(UINTN)Memory, EFI_PAGES_TO_SIZE (NoPages));\r
 }\r
 \r
     (EFI_PHYSICAL_ADDRESS)(UINTN)Memory, EFI_PAGES_TO_SIZE (NoPages));\r
 }\r
 \r
-/**
-  Internal function.  Frees guarded pool pages.
-
-  @param  PoolType               The type of memory for the pool pages
-  @param  Memory                 The base address to free
-  @param  NoPages                The number of pages to free
-
-**/
-STATIC
-VOID
-CoreFreePoolPagesWithGuard (
-  IN EFI_MEMORY_TYPE        PoolType,
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NoPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS    MemoryGuarded;
-  UINTN                   NoPagesGuarded;
-
-  MemoryGuarded  = Memory;
-  NoPagesGuarded = NoPages;
-
-  AdjustMemoryF (&Memory, &NoPages);
-  CoreFreePoolPagesI (PoolType, Memory, NoPages);
-
-  UnsetGuardForMemory (MemoryGuarded, NoPagesGuarded);
-}
-
+/**\r
+  Internal function.  Frees guarded pool pages.\r
+\r
+  @param  PoolType               The type of memory for the pool pages\r
+  @param  Memory                 The base address to free\r
+  @param  NoPages                The number of pages to free\r
+\r
+**/\r
+STATIC\r
+VOID\r
+CoreFreePoolPagesWithGuard (\r
+  IN EFI_MEMORY_TYPE        PoolType,\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NoPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS    MemoryGuarded;\r
+  UINTN                   NoPagesGuarded;\r
+\r
+  MemoryGuarded  = Memory;\r
+  NoPagesGuarded = NoPages;\r
+\r
+  AdjustMemoryF (&Memory, &NoPages);\r
+  CoreFreePoolPagesI (PoolType, Memory, NoPages);\r
+\r
+  UnsetGuardForMemory (MemoryGuarded, NoPagesGuarded);\r
+}\r
+\r
 /**\r
   Internal function to free a pool entry.\r
   Caller must have the memory lock held\r
 /**\r
   Internal function to free a pool entry.\r
   Caller must have the memory lock held\r
@@ -675,8 +675,8 @@ CoreFreePoolI (
   UINTN       Offset;\r
   BOOLEAN     AllFree;\r
   UINTN       Granularity;\r
   UINTN       Offset;\r
   BOOLEAN     AllFree;\r
   UINTN       Granularity;\r
-  BOOLEAN     IsGuarded;
-  BOOLEAN     HasPoolTail;
+  BOOLEAN     IsGuarded;\r
+  BOOLEAN     HasPoolTail;\r
 \r
   ASSERT(Buffer != NULL);\r
   //\r
 \r
   ASSERT(Buffer != NULL);\r
   //\r
@@ -689,32 +689,32 @@ CoreFreePoolI (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  IsGuarded   = IsPoolTypeToGuard (Head->Type) &&
-                IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Head);
-  HasPoolTail = !(IsGuarded &&
-                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
-\r
-  if (HasPoolTail) {
-    Tail = HEAD_TO_TAIL (Head);
-    ASSERT (Tail != NULL);
-\r
-    //
-    // Debug
-    //
-    ASSERT (Tail->Signature == POOL_TAIL_SIGNATURE);
-    ASSERT (Head->Size == Tail->Size);
-\r
-    if (Tail->Signature != POOL_TAIL_SIGNATURE) {
-      return EFI_INVALID_PARAMETER;
-    }
-
-    if (Head->Size != Tail->Size) {
-      return EFI_INVALID_PARAMETER;
-    }
+  IsGuarded   = IsPoolTypeToGuard (Head->Type) &&\r
+                IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Head);\r
+  HasPoolTail = !(IsGuarded &&\r
+                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));\r
+\r
+  if (HasPoolTail) {\r
+    Tail = HEAD_TO_TAIL (Head);\r
+    ASSERT (Tail != NULL);\r
+\r
+    //\r
+    // Debug\r
+    //\r
+    ASSERT (Tail->Signature == POOL_TAIL_SIGNATURE);\r
+    ASSERT (Head->Size == Tail->Size);\r
+\r
+    if (Tail->Signature != POOL_TAIL_SIGNATURE) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+\r
+    if (Head->Size != Tail->Size) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
   }\r
 \r
   }\r
 \r
-  ASSERT_LOCKED (&mPoolMemoryLock);
-
+  ASSERT_LOCKED (&mPoolMemoryLock);\r
+\r
   //\r
   // Determine the pool type and account for it\r
   //\r
   //\r
   // Determine the pool type and account for it\r
   //\r
@@ -749,27 +749,27 @@ CoreFreePoolI (
   //\r
   // If it's not on the list, it must be pool pages\r
   //\r
   //\r
   // If it's not on the list, it must be pool pages\r
   //\r
-  if (Index >= SIZE_TO_LIST (Granularity) || IsGuarded) {
+  if (Index >= SIZE_TO_LIST (Granularity) || IsGuarded) {\r
 \r
     //\r
     // Return the memory pages back to free memory\r
     //\r
 \r
     //\r
     // Return the memory pages back to free memory\r
     //\r
-    NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1;
+    NoPages = EFI_SIZE_TO_PAGES (Size) + EFI_SIZE_TO_PAGES (Granularity) - 1;\r
     NoPages &= ~(UINTN)(EFI_SIZE_TO_PAGES (Granularity) - 1);\r
     NoPages &= ~(UINTN)(EFI_SIZE_TO_PAGES (Granularity) - 1);\r
-    if (IsGuarded) {
-      Head = AdjustPoolHeadF ((EFI_PHYSICAL_ADDRESS)(UINTN)Head);
-      CoreFreePoolPagesWithGuard (
-        Pool->MemoryType,
-        (EFI_PHYSICAL_ADDRESS)(UINTN)Head,
-        NoPages
-        );
-    } else {
-      CoreFreePoolPagesI (
-        Pool->MemoryType,
-        (EFI_PHYSICAL_ADDRESS)(UINTN)Head,
-        NoPages
-        );
-    }
+    if (IsGuarded) {\r
+      Head = AdjustPoolHeadF ((EFI_PHYSICAL_ADDRESS)(UINTN)Head);\r
+      CoreFreePoolPagesWithGuard (\r
+        Pool->MemoryType,\r
+        (EFI_PHYSICAL_ADDRESS)(UINTN)Head,\r
+        NoPages\r
+        );\r
+    } else {\r
+      CoreFreePoolPagesI (\r
+        Pool->MemoryType,\r
+        (EFI_PHYSICAL_ADDRESS)(UINTN)Head,\r
+        NoPages\r
+        );\r
+    }\r
 \r
   } else {\r
 \r
 \r
   } else {\r
 \r
index e1e611ab7919408c5f44757da3d69fcfb49e6a03..21a52d0af55a6d94814d7859e168082054fc3ba1 100644 (file)
@@ -1065,15 +1065,15 @@ CoreInitializeMemoryProtection (
   // - code regions should have no EFI_MEMORY_XP attribute\r
   // - EfiConventionalMemory and EfiBootServicesData should use the\r
   //   same attribute\r
   // - code regions should have no EFI_MEMORY_XP attribute\r
   // - EfiConventionalMemory and EfiBootServicesData should use the\r
   //   same attribute\r
-  // - heap guard should not be enabled for the same type of memory
+  // - heap guard should not be enabled for the same type of memory\r
   //\r
   ASSERT ((GetPermissionAttributeForMemoryType (EfiBootServicesCode) & EFI_MEMORY_XP) == 0);\r
   ASSERT ((GetPermissionAttributeForMemoryType (EfiRuntimeServicesCode) & EFI_MEMORY_XP) == 0);\r
   ASSERT ((GetPermissionAttributeForMemoryType (EfiLoaderCode) & EFI_MEMORY_XP) == 0);\r
   ASSERT (GetPermissionAttributeForMemoryType (EfiBootServicesData) ==\r
           GetPermissionAttributeForMemoryType (EfiConventionalMemory));\r
   //\r
   ASSERT ((GetPermissionAttributeForMemoryType (EfiBootServicesCode) & EFI_MEMORY_XP) == 0);\r
   ASSERT ((GetPermissionAttributeForMemoryType (EfiRuntimeServicesCode) & EFI_MEMORY_XP) == 0);\r
   ASSERT ((GetPermissionAttributeForMemoryType (EfiLoaderCode) & EFI_MEMORY_XP) == 0);\r
   ASSERT (GetPermissionAttributeForMemoryType (EfiBootServicesData) ==\r
           GetPermissionAttributeForMemoryType (EfiConventionalMemory));\r
-  ASSERT ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & PcdGet64 (PcdHeapGuardPoolType)) == 0);
-  ASSERT ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & PcdGet64 (PcdHeapGuardPageType)) == 0);
+  ASSERT ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & PcdGet64 (PcdHeapGuardPoolType)) == 0);\r
+  ASSERT ((PcdGet64 (PcdDxeNxMemoryProtectionPolicy) & PcdGet64 (PcdHeapGuardPageType)) == 0);\r
 \r
   if (mImageProtectionPolicy != 0 || PcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0) {\r
     Status = CoreCreateEvent (\r
 \r
   if (mImageProtectionPolicy != 0 || PcdGet64 (PcdDxeNxMemoryProtectionPolicy) != 0) {\r
     Status = CoreCreateEvent (\r
index e8a05b03335facc4212f60805def961ccafdc3fb..a1b8748432d574171d6cb29702560d12f90cbd0b 100644 (file)
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable                      ## SOMETIMES_CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable                      ## SOMETIMES_CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask    ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdNullPointerDetectionPropertyMask    ## CONSUMES\r
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES\r
 \r
 [Pcd.IA32,Pcd.X64,Pcd.ARM,Pcd.AARCH64]\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack               ## SOMETIMES_CONSUMES\r
 \r
 [Pcd.IA32,Pcd.X64,Pcd.ARM,Pcd.AARCH64]\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack               ## SOMETIMES_CONSUMES\r
index 33c77374a963ae1fe5b2d322133d9614a3ba69de..56492653671ea4ecc9e05c64107823a61a2a14eb 100644 (file)
@@ -211,37 +211,37 @@ IsExecuteDisableBitAvailable (
   return Available;\r
 }\r
 \r
   return Available;\r
 }\r
 \r
-/**
-  The function will check if page table should be setup or not.
-
-  @retval TRUE      Page table should be created.
-  @retval FALSE     Page table should not be created.
-
-**/
-BOOLEAN
-ToBuildPageTable (
-  VOID
-  )
-{
-  if (!IsIa32PaeSupport ()) {
-    return FALSE;
-  }
-
-  if (IsNullDetectionEnabled ()) {
-    return TRUE;
-  }
-
-  if (PcdGet8 (PcdHeapGuardPropertyMask) != 0) {
-    return TRUE;
-  }
-
-  if (PcdGetBool (PcdSetNxForStack) && IsExecuteDisableBitAvailable ()) {
-    return TRUE;
-  }
-
-  return FALSE;
-}
-
+/**\r
+  The function will check if page table should be setup or not.\r
+\r
+  @retval TRUE      Page table should be created.\r
+  @retval FALSE     Page table should not be created.\r
+\r
+**/\r
+BOOLEAN\r
+ToBuildPageTable (\r
+  VOID\r
+  )\r
+{\r
+  if (!IsIa32PaeSupport ()) {\r
+    return FALSE;\r
+  }\r
+\r
+  if (IsNullDetectionEnabled ()) {\r
+    return TRUE;\r
+  }\r
+\r
+  if (PcdGet8 (PcdHeapGuardPropertyMask) != 0) {\r
+    return TRUE;\r
+  }\r
+\r
+  if (PcdGetBool (PcdSetNxForStack) && IsExecuteDisableBitAvailable ()) {\r
+    return TRUE;\r
+  }\r
+\r
+  return FALSE;\r
+}\r
+\r
 /**\r
    Transfers control to DxeCore.\r
 \r
 /**\r
    Transfers control to DxeCore.\r
 \r
@@ -416,7 +416,7 @@ HandOffToDxeCore (
     TopOfStack = (EFI_PHYSICAL_ADDRESS) (UINTN) ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);\r
 \r
     PageTables = 0;\r
     TopOfStack = (EFI_PHYSICAL_ADDRESS) (UINTN) ALIGN_POINTER (TopOfStack, CPU_STACK_ALIGNMENT);\r
 \r
     PageTables = 0;\r
-    BuildPageTablesIa32Pae = ToBuildPageTable ();
+    BuildPageTablesIa32Pae = ToBuildPageTable ();\r
     if (BuildPageTablesIa32Pae) {\r
       PageTables = Create4GPageTablesIa32Pae (BaseOfStack, STACK_SIZE);\r
       if (IsExecuteDisableBitAvailable ()) {\r
     if (BuildPageTablesIa32Pae) {\r
       PageTables = Create4GPageTablesIa32Pae (BaseOfStack, STACK_SIZE);\r
       if (IsExecuteDisableBitAvailable ()) {\r
index c7a1408562d7cc63f1040eb31854e52dc5671276..7dbbf79dc0106993988046e5718bf5f617906019 100644 (file)
-/** @file
-  UEFI Heap Guard functions.
-
-Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
-
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#include "HeapGuard.h"
-
-//
-// Global to avoid infinite reentrance of memory allocation when updating
-// page table attributes, which may need allocating pages for new PDE/PTE.
-//
-GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE;
-
-//
-// Pointer to table tracking the Guarded memory with bitmap, in which  '1'
-// is used to indicate memory guarded. '0' might be free memory or Guard
-// page itself, depending on status of memory adjacent to it.
-//
-GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0;
-
-//
-// Current depth level of map table pointed by mGuardedMemoryMap.
-// mMapLevel must be initialized at least by 1. It will be automatically
-// updated according to the address of memory just tracked.
-//
-GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1;
-
-//
-// Shift and mask for each level of map table
-//
-GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH]
-                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS;
-GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH]
-                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS;
-
-//
-// SMM memory attribute protocol
-//
-EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *mSmmMemoryAttribute = NULL;
-
-/**
-  Set corresponding bits in bitmap table to 1 according to the address.
-
-  @param[in]  Address     Start address to set for.
-  @param[in]  BitNumber   Number of bits to set.
-  @param[in]  BitMap      Pointer to bitmap which covers the Address.
-
-  @return VOID
-**/
-STATIC
-VOID
-SetBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   BitNumber,
-  IN UINT64                  *BitMap
-  )
-{
-  UINTN           Lsbs;
-  UINTN           Qwords;
-  UINTN           Msbs;
-  UINTN           StartBit;
-  UINTN           EndBit;
-
-  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);
-  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-
-  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {
-    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %
-              GUARDED_HEAP_MAP_ENTRY_BITS;
-    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;
-  } else {
-    Msbs    = BitNumber;
-    Lsbs    = 0;
-    Qwords  = 0;
-  }
-
-  if (Msbs > 0) {
-    *BitMap |= LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);
-    BitMap  += 1;
-  }
-
-  if (Qwords > 0) {
-    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES,
-              (UINT64)-1);
-    BitMap += Qwords;
-  }
-
-  if (Lsbs > 0) {
-    *BitMap |= (LShiftU64 (1, Lsbs) - 1);
-  }
-}
-
-/**
-  Set corresponding bits in bitmap table to 0 according to the address.
-
-  @param[in]  Address     Start address to set for.
-  @param[in]  BitNumber   Number of bits to set.
-  @param[in]  BitMap      Pointer to bitmap which covers the Address.
-
-  @return VOID.
-**/
-STATIC
-VOID
-ClearBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   BitNumber,
-  IN UINT64                  *BitMap
-  )
-{
-  UINTN           Lsbs;
-  UINTN           Qwords;
-  UINTN           Msbs;
-  UINTN           StartBit;
-  UINTN           EndBit;
-
-  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);
-  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-
-  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {
-    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %
-              GUARDED_HEAP_MAP_ENTRY_BITS;
-    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;
-  } else {
-    Msbs    = BitNumber;
-    Lsbs    = 0;
-    Qwords  = 0;
-  }
-
-  if (Msbs > 0) {
-    *BitMap &= ~LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);
-    BitMap  += 1;
-  }
-
-  if (Qwords > 0) {
-    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, 0);
-    BitMap += Qwords;
-  }
-
-  if (Lsbs > 0) {
-    *BitMap &= ~(LShiftU64 (1, Lsbs) - 1);
-  }
-}
-
-/**
-  Get corresponding bits in bitmap table according to the address.
-
-  The value of bit 0 corresponds to the status of memory at given Address.
-  No more than 64 bits can be retrieved in one call.
-
-  @param[in]  Address     Start address to retrieve bits for.
-  @param[in]  BitNumber   Number of bits to get.
-  @param[in]  BitMap      Pointer to bitmap which covers the Address.
-
-  @return An integer containing the bits information.
-**/
-STATIC
-UINT64
-GetBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   BitNumber,
-  IN UINT64                  *BitMap
-  )
-{
-  UINTN           StartBit;
-  UINTN           EndBit;
-  UINTN           Lsbs;
-  UINTN           Msbs;
-  UINT64          Result;
-
-  ASSERT (BitNumber <= GUARDED_HEAP_MAP_ENTRY_BITS);
-
-  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);
-  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-
-  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {
-    Msbs = GUARDED_HEAP_MAP_ENTRY_BITS - StartBit;
-    Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;
-  } else {
-    Msbs = BitNumber;
-    Lsbs = 0;
-  }
-
-  Result    = RShiftU64 ((*BitMap), StartBit) & (LShiftU64 (1, Msbs) - 1);
-  if (Lsbs > 0) {
-    BitMap  += 1;
-    Result  |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs);
-  }
-
-  return Result;
-}
-
-/**
-  Helper function to allocate pages without Guard for internal uses.
-
-  @param[in]  Pages       Page number.
-
-  @return Address of memory allocated.
-**/
-VOID *
-PageAlloc (
-  IN UINTN  Pages
-  )
-{
-  EFI_STATUS              Status;
-  EFI_PHYSICAL_ADDRESS    Memory;
-
-  Status = SmmInternalAllocatePages (AllocateAnyPages, EfiRuntimeServicesData,
-                                     Pages, &Memory, FALSE);
-  if (EFI_ERROR (Status)) {
-    Memory = 0;
-  }
-
-  return (VOID *)(UINTN)Memory;
-}
-
-/**
-  Locate the pointer of bitmap from the guarded memory bitmap tables, which
-  covers the given Address.
-
-  @param[in]  Address       Start address to search the bitmap for.
-  @param[in]  AllocMapUnit  Flag to indicate memory allocation for the table.
-  @param[out] BitMap        Pointer to bitmap which covers the Address.
-
-  @return The bit number from given Address to the end of current map table.
-**/
-UINTN
-FindGuardedMemoryMap (
-  IN  EFI_PHYSICAL_ADDRESS    Address,
-  IN  BOOLEAN                 AllocMapUnit,
-  OUT UINT64                  **BitMap
-  )
-{
-  UINTN                   Level;
-  UINT64                  *GuardMap;
-  UINT64                  MapMemory;
-  UINTN                   Index;
-  UINTN                   Size;
-  UINTN                   BitsToUnitEnd;
-
-  //
-  // Adjust current map table depth according to the address to access
-  //
-  while (mMapLevel < GUARDED_HEAP_MAP_TABLE_DEPTH
-         &&
-         RShiftU64 (
-           Address,
-           mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1]
-           ) != 0) {
-
-    if (mGuardedMemoryMap != 0) {
-      Size = (mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] + 1)
-             * GUARDED_HEAP_MAP_ENTRY_BYTES;
-      MapMemory = (UINT64)(UINTN)PageAlloc (EFI_SIZE_TO_PAGES (Size));
-      ASSERT (MapMemory != 0);
-
-      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);
-
-      *(UINT64 *)(UINTN)MapMemory = mGuardedMemoryMap;
-      mGuardedMemoryMap = MapMemory;
-    }
-
-    mMapLevel++;
-
-  }
-
-  GuardMap = &mGuardedMemoryMap;
-  for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;
-       Level < GUARDED_HEAP_MAP_TABLE_DEPTH;
-       ++Level) {
-
-    if (*GuardMap == 0) {
-      if (!AllocMapUnit) {
-        GuardMap = NULL;
-        break;
-      }
-
-      Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES;
-      MapMemory = (UINT64)(UINTN)PageAlloc (EFI_SIZE_TO_PAGES (Size));
-      ASSERT (MapMemory != 0);
-
-      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);
-      *GuardMap = MapMemory;
-    }
-
-    Index     = (UINTN)RShiftU64 (Address, mLevelShift[Level]);
-    Index     &= mLevelMask[Level];
-    GuardMap  = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64));
-
-  }
-
-  BitsToUnitEnd = GUARDED_HEAP_MAP_BITS - GUARDED_HEAP_MAP_BIT_INDEX (Address);
-  *BitMap       = GuardMap;
-
-  return BitsToUnitEnd;
-}
-
-/**
-  Set corresponding bits in bitmap table to 1 according to given memory range.
-
-  @param[in]  Address       Memory address to guard from.
-  @param[in]  NumberOfPages Number of pages to guard.
-
-  @return VOID
-**/
-VOID
-EFIAPI
-SetGuardedMemoryBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   NumberOfPages
-  )
-{
-  UINT64            *BitMap;
-  UINTN             Bits;
-  UINTN             BitsToUnitEnd;
-
-  while (NumberOfPages > 0) {
-    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);
-    ASSERT (BitMap != NULL);
-
-    if (NumberOfPages > BitsToUnitEnd) {
-      // Cross map unit
-      Bits = BitsToUnitEnd;
-    } else {
-      Bits  = NumberOfPages;
-    }
-
-    SetBits (Address, Bits, BitMap);
-
-    NumberOfPages -= Bits;
-    Address       += EFI_PAGES_TO_SIZE (Bits);
-  }
-}
-
-/**
-  Clear corresponding bits in bitmap table according to given memory range.
-
-  @param[in]  Address       Memory address to unset from.
-  @param[in]  NumberOfPages Number of pages to unset guard.
-
-  @return VOID
-**/
-VOID
-EFIAPI
-ClearGuardedMemoryBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   NumberOfPages
-  )
-{
-  UINT64            *BitMap;
-  UINTN             Bits;
-  UINTN             BitsToUnitEnd;
-
-  while (NumberOfPages > 0) {
-    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);
-    ASSERT (BitMap != NULL);
-
-    if (NumberOfPages > BitsToUnitEnd) {
-      // Cross map unit
-      Bits = BitsToUnitEnd;
-    } else {
-      Bits  = NumberOfPages;
-    }
-
-    ClearBits (Address, Bits, BitMap);
-
-    NumberOfPages -= Bits;
-    Address       += EFI_PAGES_TO_SIZE (Bits);
-  }
-}
-
-/**
-  Retrieve corresponding bits in bitmap table according to given memory range.
-
-  @param[in]  Address       Memory address to retrieve from.
-  @param[in]  NumberOfPages Number of pages to retrieve.
-
-  @return An integer containing the guarded memory bitmap.
-**/
-UINTN
-GetGuardedMemoryBits (
-  IN EFI_PHYSICAL_ADDRESS    Address,
-  IN UINTN                   NumberOfPages
-  )
-{
-  UINT64            *BitMap;
-  UINTN             Bits;
-  UINTN             Result;
-  UINTN             Shift;
-  UINTN             BitsToUnitEnd;
-
-  ASSERT (NumberOfPages <= GUARDED_HEAP_MAP_ENTRY_BITS);
-
-  Result = 0;
-  Shift  = 0;
-  while (NumberOfPages > 0) {
-    BitsToUnitEnd = FindGuardedMemoryMap (Address, FALSE, &BitMap);
-
-    if (NumberOfPages > BitsToUnitEnd) {
-      // Cross map unit
-      Bits  = BitsToUnitEnd;
-    } else {
-      Bits  = NumberOfPages;
-    }
-
-    if (BitMap != NULL) {
-      Result |= LShiftU64 (GetBits (Address, Bits, BitMap), Shift);
-    }
-
-    Shift         += Bits;
-    NumberOfPages -= Bits;
-    Address       += EFI_PAGES_TO_SIZE (Bits);
-  }
-
-  return Result;
-}
-
-/**
-  Get bit value in bitmap table for the given address.
-
-  @param[in]  Address     The address to retrieve for.
-
-  @return 1 or 0.
-**/
-UINTN
-EFIAPI
-GetGuardMapBit (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINT64        *GuardMap;
-
-  FindGuardedMemoryMap (Address, FALSE, &GuardMap);
-  if (GuardMap != NULL) {
-    if (RShiftU64 (*GuardMap,
-                   GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address)) & 1) {
-      return 1;
-    }
-  }
-
-  return 0;
-}
-
-/**
-  Set the bit in bitmap table for the given address.
-
-  @param[in]  Address     The address to set for.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-SetGuardMapBit (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINT64        *GuardMap;
-  UINT64        BitMask;
-
-  FindGuardedMemoryMap (Address, TRUE, &GuardMap);
-  if (GuardMap != NULL) {
-    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));
-    *GuardMap |= BitMask;
-  }
-}
-
-/**
-  Clear the bit in bitmap table for the given address.
-
-  @param[in]  Address     The address to clear for.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-ClearGuardMapBit (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  UINT64        *GuardMap;
-  UINT64        BitMask;
-
-  FindGuardedMemoryMap (Address, TRUE, &GuardMap);
-  if (GuardMap != NULL) {
-    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));
-    *GuardMap &= ~BitMask;
-  }
-}
-
-/**
-  Check to see if the page at the given address is a Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a Guard page.
-  @return FALSE The page at Address is not a Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsGuardPage (
-  IN EFI_PHYSICAL_ADDRESS    Address
-)
-{
-  UINTN       BitMap;
-
-  //
-  // There must be at least one guarded page before and/or after given
-  // address if it's a Guard page. The bitmap pattern should be one of
-  // 001, 100 and 101
-  //
-  BitMap = GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 3);
-  return ((BitMap == BIT0) || (BitMap == BIT2) || (BitMap == (BIT2 | BIT0)));
-}
-
-/**
-  Check to see if the page at the given address is a head Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a head Guard page.
-  @return FALSE The page at Address is not a head Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsHeadGuard (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  return (GetGuardedMemoryBits (Address, 2) == BIT1);
-}
-
-/**
-  Check to see if the page at the given address is a tail Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a tail Guard page.
-  @return FALSE The page at Address is not a tail Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsTailGuard (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  return (GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 2) == BIT0);
-}
-
-/**
-  Check to see if the page at the given address is guarded or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is guarded.
-  @return FALSE The page at Address is not guarded.
-**/
-BOOLEAN
-EFIAPI
-IsMemoryGuarded (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  )
-{
-  return (GetGuardMapBit (Address) == 1);
-}
-
-/**
-  Set the page at the given address to be a Guard page.
-
-  This is done by changing the page table attribute to be NOT PRSENT.
-
-  @param[in]  BaseAddress     Page address to Guard at.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-SetGuardPage (
-  IN  EFI_PHYSICAL_ADDRESS      BaseAddress
-  )
-{
-  if (mSmmMemoryAttribute != NULL) {
-    mOnGuarding = TRUE;
-    mSmmMemoryAttribute->SetMemoryAttributes (
-                           mSmmMemoryAttribute,
-                           BaseAddress,
-                           EFI_PAGE_SIZE,
-                           EFI_MEMORY_RP
-                           );
-    mOnGuarding = FALSE;
-  }
-}
-
-/**
-  Unset the Guard page at the given address to the normal memory.
-
-  This is done by changing the page table attribute to be PRSENT.
-
-  @param[in]  BaseAddress     Page address to Guard at.
-
-  @return VOID.
-**/
-VOID
-EFIAPI
-UnsetGuardPage (
-  IN  EFI_PHYSICAL_ADDRESS      BaseAddress
-  )
-{
-  if (mSmmMemoryAttribute != NULL) {
-    mOnGuarding = TRUE;
-    mSmmMemoryAttribute->ClearMemoryAttributes (
-                           mSmmMemoryAttribute,
-                           BaseAddress,
-                           EFI_PAGE_SIZE,
-                           EFI_MEMORY_RP
-                           );
-    mOnGuarding = FALSE;
-  }
-}
-
-/**
-  Check to see if the memory at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Memory type to check.
-  @param[in]  AllocateType    Allocation type to check.
-  @param[in]  PageOrPool      Indicate a page allocation or pool allocation.
-
-
-  @return TRUE  The given type of memory should be guarded.
-  @return FALSE The given type of memory should not be guarded.
-**/
-BOOLEAN
-IsMemoryTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN EFI_ALLOCATE_TYPE      AllocateType,
-  IN UINT8                  PageOrPool
-  )
-{
-  UINT64 TestBit;
-  UINT64 ConfigBit;
-
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0
-      || mOnGuarding
-      || AllocateType == AllocateAddress) {
-    return FALSE;
-  }
-
-  ConfigBit = 0;
-  if ((PageOrPool & GUARD_HEAP_TYPE_POOL) != 0) {
-    ConfigBit |= PcdGet64 (PcdHeapGuardPoolType);
-  }
-
-  if ((PageOrPool & GUARD_HEAP_TYPE_PAGE) != 0) {
-    ConfigBit |= PcdGet64 (PcdHeapGuardPageType);
-  }
-
-  if (MemoryType == EfiRuntimeServicesData ||
-      MemoryType == EfiRuntimeServicesCode) {
-    TestBit = LShiftU64 (1, MemoryType);
-  } else if (MemoryType == EfiMaxMemoryType) {
-    TestBit = (UINT64)-1;
-  } else {
-    TestBit = 0;
-  }
-
-  return ((ConfigBit & TestBit) != 0);
-}
-
-/**
-  Check to see if the pool at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Pool type to check.
-
-
-  @return TRUE  The given type of pool should be guarded.
-  @return FALSE The given type of pool should not be guarded.
-**/
-BOOLEAN
-IsPoolTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType
-  )
-{
-  return IsMemoryTypeToGuard (MemoryType, AllocateAnyPages,
-                              GUARD_HEAP_TYPE_POOL);
-}
-
-/**
-  Check to see if the page at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Page type to check.
-  @param[in]  AllocateType    Allocation type to check.
-
-  @return TRUE  The given type of page should be guarded.
-  @return FALSE The given type of page should not be guarded.
-**/
-BOOLEAN
-IsPageTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN EFI_ALLOCATE_TYPE      AllocateType
-  )
-{
-  return IsMemoryTypeToGuard (MemoryType, AllocateType, GUARD_HEAP_TYPE_PAGE);
-}
-
-/**
-  Check to see if the heap guard is enabled for page and/or pool allocation.
-
-  @return TRUE/FALSE.
-**/
-BOOLEAN
-IsHeapGuardEnabled (
-  VOID
-  )
-{
-  return IsMemoryTypeToGuard (EfiMaxMemoryType, AllocateAnyPages,
-                              GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_PAGE);
-}
-
-/**
-  Set head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to set guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID.
-**/
-VOID
-SetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS    GuardPage;
-
-  //
-  // Set tail Guard
-  //
-  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);
-  if (!IsGuardPage (GuardPage)) {
-    SetGuardPage (GuardPage);
-  }
-
-  // Set head Guard
-  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);
-  if (!IsGuardPage (GuardPage)) {
-    SetGuardPage (GuardPage);
-  }
-
-  //
-  // Mark the memory range as Guarded
-  //
-  SetGuardedMemoryBits (Memory, NumberOfPages);
-}
-
-/**
-  Unset head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to unset guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID.
-**/
-VOID
-UnsetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS  GuardPage;
-
-  if (NumberOfPages == 0) {
-    return;
-  }
-
-  //
-  // Head Guard must be one page before, if any.
-  //
-  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);
-  if (IsHeadGuard (GuardPage)) {
-    if (!IsMemoryGuarded (GuardPage - EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the head Guard is not a tail Guard of adjacent memory block,
-      // unset it.
-      //
-      UnsetGuardPage (GuardPage);
-    }
-  } else if (IsMemoryGuarded (GuardPage)) {
-    //
-    // Pages before memory to free are still in Guard. It's a partial free
-    // case. Turn first page of memory block to free into a new Guard.
-    //
-    SetGuardPage (Memory);
-  }
-
-  //
-  // Tail Guard must be the page after this memory block to free, if any.
-  //
-  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);
-  if (IsTailGuard (GuardPage)) {
-    if (!IsMemoryGuarded (GuardPage + EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the tail Guard is not a head Guard of adjacent memory block,
-      // free it; otherwise, keep it.
-      //
-      UnsetGuardPage (GuardPage);
-    }
-  } else if (IsMemoryGuarded (GuardPage)) {
-    //
-    // Pages after memory to free are still in Guard. It's a partial free
-    // case. We need to keep one page to be a head Guard.
-    //
-    SetGuardPage (GuardPage - EFI_PAGES_TO_SIZE (1));
-  }
-
-  //
-  // No matter what, we just clear the mark of the Guarded memory.
-  //
-  ClearGuardedMemoryBits(Memory, NumberOfPages);
-}
-
-/**
-  Adjust address of free memory according to existing and/or required Guard.
-
-  This function will check if there're existing Guard pages of adjacent
-  memory blocks, and try to use it as the Guard page of the memory to be
-  allocated.
-
-  @param[in]  Start           Start address of free memory block.
-  @param[in]  Size            Size of free memory block.
-  @param[in]  SizeRequested   Size of memory to allocate.
-
-  @return The end address of memory block found.
-  @return 0 if no enough space for the required size of memory and its Guard.
-**/
-UINT64
-AdjustMemoryS (
-  IN UINT64                  Start,
-  IN UINT64                  Size,
-  IN UINT64                  SizeRequested
-  )
-{
-  UINT64  Target;
-
-  Target = Start + Size - SizeRequested;
-
-  //
-  // At least one more page needed for Guard page.
-  //
-  if (Size < (SizeRequested + EFI_PAGES_TO_SIZE (1))) {
-    return 0;
-  }
-
-  if (!IsGuardPage (Start + Size)) {
-    // No Guard at tail to share. One more page is needed.
-    Target -= EFI_PAGES_TO_SIZE (1);
-  }
-
-  // Out of range?
-  if (Target < Start) {
-    return 0;
-  }
-
-  // At the edge?
-  if (Target == Start) {
-    if (!IsGuardPage (Target - EFI_PAGES_TO_SIZE (1))) {
-      // No enough space for a new head Guard if no Guard at head to share.
-      return 0;
-    }
-  }
-
-  // OK, we have enough pages for memory and its Guards. Return the End of the
-  // free space.
-  return Target + SizeRequested - 1;
-}
-
-/**
-  Adjust the start address and number of pages to free according to Guard.
-
-  The purpose of this function is to keep the shared Guard page with adjacent
-  memory block if it's still in guard, or free it if no more sharing. Another
-  is to reserve pages as Guard pages in partial page free situation.
-
-  @param[in,out]  Memory          Base address of memory to free.
-  @param[in,out]  NumberOfPages   Size of memory to free.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryF (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  )
-{
-  EFI_PHYSICAL_ADDRESS  Start;
-  EFI_PHYSICAL_ADDRESS  MemoryToTest;
-  UINTN                 PagesToFree;
-
-  if (Memory == NULL || NumberOfPages == NULL || *NumberOfPages == 0) {
-    return;
-  }
-
-  Start = *Memory;
-  PagesToFree = *NumberOfPages;
-
-  //
-  // Head Guard must be one page before, if any.
-  //
-  MemoryToTest = Start - EFI_PAGES_TO_SIZE (1);
-  if (IsHeadGuard (MemoryToTest)) {
-    if (!IsMemoryGuarded (MemoryToTest - EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the head Guard is not a tail Guard of adjacent memory block,
-      // free it; otherwise, keep it.
-      //
-      Start       -= EFI_PAGES_TO_SIZE (1);
-      PagesToFree += 1;
-    }
-  } else if (IsMemoryGuarded (MemoryToTest)) {
-    //
-    // Pages before memory to free are still in Guard. It's a partial free
-    // case. We need to keep one page to be a tail Guard.
-    //
-    Start       += EFI_PAGES_TO_SIZE (1);
-    PagesToFree -= 1;
-  }
-
-  //
-  // Tail Guard must be the page after this memory block to free, if any.
-  //
-  MemoryToTest = Start + EFI_PAGES_TO_SIZE (PagesToFree);
-  if (IsTailGuard (MemoryToTest)) {
-    if (!IsMemoryGuarded (MemoryToTest + EFI_PAGES_TO_SIZE (1))) {
-      //
-      // If the tail Guard is not a head Guard of adjacent memory block,
-      // free it; otherwise, keep it.
-      //
-      PagesToFree += 1;
-    }
-  } else if (IsMemoryGuarded (MemoryToTest)) {
-    //
-    // Pages after memory to free are still in Guard. It's a partial free
-    // case. We need to keep one page to be a head Guard.
-    //
-    PagesToFree -= 1;
-  }
-
-  *Memory         = Start;
-  *NumberOfPages  = PagesToFree;
-}
-
-/**
-  Adjust the base and number of pages to really allocate according to Guard.
-
-  @param[in,out]  Memory          Base address of free memory.
-  @param[in,out]  NumberOfPages   Size of memory to allocate.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryA (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  )
-{
-  //
-  // FindFreePages() has already taken the Guard into account. It's safe to
-  // adjust the start address and/or number of pages here, to make sure that
-  // the Guards are also "allocated".
-  //
-  if (!IsGuardPage (*Memory + EFI_PAGES_TO_SIZE (*NumberOfPages))) {
-    // No tail Guard, add one.
-    *NumberOfPages += 1;
-  }
-
-  if (!IsGuardPage (*Memory - EFI_PAGE_SIZE)) {
-    // No head Guard, add one.
-    *Memory        -= EFI_PAGE_SIZE;
-    *NumberOfPages += 1;
-  }
-}
-
-/**
-  Adjust the pool head position to make sure the Guard page is adjavent to
-  pool tail or pool head.
-
-  @param[in]  Memory    Base address of memory allocated.
-  @param[in]  NoPages   Number of pages actually allocated.
-  @param[in]  Size      Size of memory requested.
-                        (plus pool head/tail overhead)
-
-  @return Address of pool head
-**/
-VOID *
-AdjustPoolHeadA (
-  IN EFI_PHYSICAL_ADDRESS    Memory,
-  IN UINTN                   NoPages,
-  IN UINTN                   Size
-  )
-{
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {
-    //
-    // Pool head is put near the head Guard
-    //
-    return (VOID *)(UINTN)Memory;
-  }
-
-  //
-  // Pool head is put near the tail Guard
-  //
-  return (VOID *)(UINTN)(Memory + EFI_PAGES_TO_SIZE (NoPages) - Size);
-}
-
-/**
-  Get the page base address according to pool head address.
-
-  @param[in]  Memory    Head address of pool to free.
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadF (
-  IN EFI_PHYSICAL_ADDRESS    Memory
-  )
-{
-  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {
-    //
-    // Pool head is put near the head Guard
-    //
-    return (VOID *)(UINTN)Memory;
-  }
-
-  //
-  // Pool head is put near the tail Guard
-  //
-  return (VOID *)(UINTN)(Memory & ~EFI_PAGE_MASK);
-}
-
-/**
-  Helper function of memory allocation with Guard pages.
-
-  @param  FreePageList           The free page node.
-  @param  NumberOfPages          Number of pages to be allocated.
-  @param  MaxAddress             Request to allocate memory below this address.
-  @param  MemoryType             Type of memory requested.
-
-  @return Memory address of allocated pages.
-**/
-UINTN
-InternalAllocMaxAddressWithGuard (
-  IN OUT LIST_ENTRY           *FreePageList,
-  IN     UINTN                NumberOfPages,
-  IN     UINTN                MaxAddress,
-  IN     EFI_MEMORY_TYPE      MemoryType
-
-  )
-{
-  LIST_ENTRY      *Node;
-  FREE_PAGE_LIST  *Pages;
-  UINTN           PagesToAlloc;
-  UINTN           HeadGuard;
-  UINTN           TailGuard;
-  UINTN           Address;
-
-  for (Node = FreePageList->BackLink; Node != FreePageList;
-        Node = Node->BackLink) {
-    Pages = BASE_CR (Node, FREE_PAGE_LIST, Link);
-    if (Pages->NumberOfPages >= NumberOfPages &&
-        (UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress) {
-
-      //
-      // We may need 1 or 2 more pages for Guard. Check it out.
-      //
-      PagesToAlloc = NumberOfPages;
-      TailGuard = (UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages);
-      if (!IsGuardPage (TailGuard)) {
-        //
-        // Add one if no Guard at the end of current free memory block.
-        //
-        PagesToAlloc += 1;
-        TailGuard     = 0;
-      }
-
-      HeadGuard = (UINTN)Pages +
-                  EFI_PAGES_TO_SIZE (Pages->NumberOfPages - PagesToAlloc) -
-                  EFI_PAGE_SIZE;
-      if (!IsGuardPage (HeadGuard)) {
-        //
-        // Add one if no Guard at the page before the address to allocate
-        //
-        PagesToAlloc += 1;
-        HeadGuard     = 0;
-      }
-
-      if (Pages->NumberOfPages < PagesToAlloc) {
-        // Not enough space to allocate memory with Guards? Try next block.
-        continue;
-      }
-
-      Address = InternalAllocPagesOnOneNode (Pages, PagesToAlloc, MaxAddress);
-      ConvertSmmMemoryMapEntry(MemoryType, Address, PagesToAlloc, FALSE);
-      CoreFreeMemoryMapStack();
-      if (HeadGuard == 0) {
-        // Don't pass the Guard page to user.
-        Address += EFI_PAGE_SIZE;
-      }
-      SetGuardForMemory (Address, NumberOfPages);
-      return Address;
-    }
-  }
-
-  return (UINTN)(-1);
-}
-
-/**
-  Helper function of memory free with Guard pages.
-
-  @param[in]  Memory                 Base address of memory being freed.
-  @param[in]  NumberOfPages          The number of pages to free.
-  @param[in]  AddRegion              If this memory is new added region.
-
-  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.
-  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.
-  @return EFI_SUCCESS            Pages successfully freed.
-**/
-EFI_STATUS
-SmmInternalFreePagesExWithGuard (
-  IN EFI_PHYSICAL_ADDRESS  Memory,
-  IN UINTN                 NumberOfPages,
-  IN BOOLEAN               AddRegion
-  )
-{
-  EFI_PHYSICAL_ADDRESS    MemoryToFree;
-  UINTN                   PagesToFree;
-
-  MemoryToFree  = Memory;
-  PagesToFree   = NumberOfPages;
-
-  AdjustMemoryF (&MemoryToFree, &PagesToFree);
-  UnsetGuardForMemory (Memory, NumberOfPages);
-
-  return SmmInternalFreePagesEx (MemoryToFree, PagesToFree, AddRegion);
-}
-
-/**
-  Set all Guard pages which cannot be set during the non-SMM mode time.
-**/
-VOID
-SetAllGuardPages (
-  VOID
-  )
-{
-  UINTN     Entries[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINTN     Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINTN     Indices[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    Tables[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    TableEntry;
-  UINT64    Address;
-  UINT64    GuardPage;
-  INTN      Level;
-  UINTN     Index;
-  BOOLEAN   OnGuarding;
-
-  if (mGuardedMemoryMap == 0) {
-    return;
-  }
-
-  CopyMem (Entries, mLevelMask, sizeof (Entries));
-  CopyMem (Shifts, mLevelShift, sizeof (Shifts));
-
-  SetMem (Tables, sizeof(Tables), 0);
-  SetMem (Addresses, sizeof(Addresses), 0);
-  SetMem (Indices, sizeof(Indices), 0);
-
-  Level         = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;
-  Tables[Level] = mGuardedMemoryMap;
-  Address       = 0;
-  OnGuarding    = FALSE;
-
-  DEBUG_CODE (
-    DumpGuardedMemoryBitmap ();
-  );
-
-  while (TRUE) {
-    if (Indices[Level] > Entries[Level]) {
-      Tables[Level] = 0;
-      Level        -= 1;
-    } else {
-
-      TableEntry  = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]];
-      Address     = Addresses[Level];
-
-      if (TableEntry == 0) {
-
-        OnGuarding = FALSE;
-
-      } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {
-
-        Level            += 1;
-        Tables[Level]     = TableEntry;
-        Addresses[Level]  = Address;
-        Indices[Level]    = 0;
-
-        continue;
-
-      } else {
-
-        Index = 0;
-        while (Index < GUARDED_HEAP_MAP_ENTRY_BITS) {
-          if ((TableEntry & 1) == 1) {
-            if (OnGuarding) {
-              GuardPage = 0;
-            } else {
-              GuardPage = Address - EFI_PAGE_SIZE;
-            }
-            OnGuarding = TRUE;
-          } else {
-            if (OnGuarding) {
-              GuardPage = Address;
-            } else {
-              GuardPage = 0;
-            }
-            OnGuarding = FALSE;
-          }
-
-          if (GuardPage != 0) {
-            SetGuardPage (GuardPage);
-          }
-
-          if (TableEntry == 0) {
-            break;
-          }
-
-          TableEntry = RShiftU64 (TableEntry, 1);
-          Address   += EFI_PAGE_SIZE;
-          Index     += 1;
-        }
-      }
-    }
-
-    if (Level < (GUARDED_HEAP_MAP_TABLE_DEPTH - (INTN)mMapLevel)) {
-      break;
-    }
-
-    Indices[Level] += 1;
-    Address = (Level == 0) ? 0 : Addresses[Level - 1];
-    Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]);
-
-  }
-}
-
-/**
-  Hook function used to set all Guard pages after entering SMM mode.
-**/
-VOID
-SmmEntryPointMemoryManagementHook (
-  VOID
-  )
-{
-  EFI_STATUS  Status;
-
-  if (mSmmMemoryAttribute == NULL) {
-    Status = SmmLocateProtocol (
-               &gEdkiiSmmMemoryAttributeProtocolGuid,
-               NULL,
-               (VOID **)&mSmmMemoryAttribute
-               );
-    if (!EFI_ERROR(Status)) {
-      SetAllGuardPages ();
-    }
-  }
-}
-
-/**
-  Helper function to convert a UINT64 value in binary to a string.
-
-  @param[in]  Value       Value of a UINT64 integer.
-  @param[out] BinString   String buffer to contain the conversion result.
-
-  @return VOID.
-**/
-VOID
-Uint64ToBinString (
-  IN  UINT64      Value,
-  OUT CHAR8       *BinString
-  )
-{
-  UINTN Index;
-
-  if (BinString == NULL) {
-    return;
-  }
-
-  for (Index = 64; Index > 0; --Index) {
-    BinString[Index - 1] = '0' + (Value & 1);
-    Value = RShiftU64 (Value, 1);
-  }
-  BinString[64] = '\0';
-}
-
-/**
-  Dump the guarded memory bit map.
-**/
-VOID
-EFIAPI
-DumpGuardedMemoryBitmap (
-  VOID
-  )
-{
-  UINTN     Entries[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINTN     Shifts[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINTN     Indices[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    Tables[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    Addresses[GUARDED_HEAP_MAP_TABLE_DEPTH];
-  UINT64    TableEntry;
-  UINT64    Address;
-  INTN      Level;
-  UINTN     RepeatZero;
-  CHAR8     String[GUARDED_HEAP_MAP_ENTRY_BITS + 1];
-  CHAR8     *Ruler1;
-  CHAR8     *Ruler2;
-
-  if (mGuardedMemoryMap == 0) {
-    return;
-  }
-
-  Ruler1 = "               3               2               1               0";
-  Ruler2 = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";
-
-  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "============================="
-                                  " Guarded Memory Bitmap "
-                                  "==============================\r\n"));
-  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler1));
-  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler2));
-
-  CopyMem (Entries, mLevelMask, sizeof (Entries));
-  CopyMem (Shifts, mLevelShift, sizeof (Shifts));
-
-  SetMem (Indices, sizeof(Indices), 0);
-  SetMem (Tables, sizeof(Tables), 0);
-  SetMem (Addresses, sizeof(Addresses), 0);
-
-  Level         = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;
-  Tables[Level] = mGuardedMemoryMap;
-  Address       = 0;
-  RepeatZero    = 0;
-
-  while (TRUE) {
-    if (Indices[Level] > Entries[Level]) {
-
-      Tables[Level] = 0;
-      Level        -= 1;
-      RepeatZero    = 0;
-
-      DEBUG ((
-        HEAP_GUARD_DEBUG_LEVEL,
-        "========================================="
-        "=========================================\r\n"
-        ));
-
-    } else {
-
-      TableEntry  = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]];
-      Address     = Addresses[Level];
-
-      if (TableEntry == 0) {
-
-        if (Level == GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {
-          if (RepeatZero == 0) {
-            Uint64ToBinString(TableEntry, String);
-            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));
-          } else if (RepeatZero == 1) {
-            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "...             : ...\r\n"));
-          }
-          RepeatZero += 1;
-        }
-
-      } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {
-
-        Level            += 1;
-        Tables[Level]     = TableEntry;
-        Addresses[Level]  = Address;
-        Indices[Level]    = 0;
-        RepeatZero        = 0;
-
-        continue;
-
-      } else {
-
-        RepeatZero = 0;
-        Uint64ToBinString(TableEntry, String);
-        DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));
-
-      }
-    }
-
-    if (Level < (GUARDED_HEAP_MAP_TABLE_DEPTH - (INTN)mMapLevel)) {
-      break;
-    }
-
-    Indices[Level] += 1;
-    Address = (Level == 0) ? 0 : Addresses[Level - 1];
-    Addresses[Level] = Address | LShiftU64(Indices[Level], Shifts[Level]);
-
-  }
-}
-
-/**
-  Debug function used to verify if the Guard page is well set or not.
-
-  @param[in]  BaseAddress     Address of memory to check.
-  @param[in]  NumberOfPages   Size of memory in pages.
-
-  @return TRUE    The head Guard and tail Guard are both well set.
-  @return FALSE   The head Guard and/or tail Guard are not well set.
-**/
-BOOLEAN
-VerifyMemoryGuard (
-  IN  EFI_PHYSICAL_ADDRESS      BaseAddress,
-  IN  UINTN                     NumberOfPages
-  )
-{
-  EFI_STATUS            Status;
-  UINT64                Attribute;
-  EFI_PHYSICAL_ADDRESS  Address;
-
-  if (mSmmMemoryAttribute == NULL) {
-    return TRUE;
-  }
-
-  Attribute = 0;
-  Address = BaseAddress - EFI_PAGE_SIZE;
-  Status = mSmmMemoryAttribute->GetMemoryAttributes (
-                                  mSmmMemoryAttribute,
-                                  Address,
-                                  EFI_PAGE_SIZE,
-                                  &Attribute
-                                  );
-  if (EFI_ERROR (Status) || (Attribute & EFI_MEMORY_RP) == 0) {
-    DEBUG ((DEBUG_ERROR, "Head Guard is not set at: %016lx (%016lX)!!!\r\n",
-            Address, Attribute));
-    DumpGuardedMemoryBitmap ();
-    return FALSE;
-  }
-
-  Attribute = 0;
-  Address = BaseAddress + EFI_PAGES_TO_SIZE (NumberOfPages);
-  Status = mSmmMemoryAttribute->GetMemoryAttributes (
-                                  mSmmMemoryAttribute,
-                                  Address,
-                                  EFI_PAGE_SIZE,
-                                  &Attribute
-                                  );
-  if (EFI_ERROR (Status) || (Attribute & EFI_MEMORY_RP) == 0) {
-    DEBUG ((DEBUG_ERROR, "Tail Guard is not set at: %016lx (%016lX)!!!\r\n",
-            Address, Attribute));
-    DumpGuardedMemoryBitmap ();
-    return FALSE;
-  }
-
-  return TRUE;
-}
-
+/** @file\r
+  UEFI Heap Guard functions.\r
+\r
+Copyright (c) 2017, 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
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#include "HeapGuard.h"\r
+\r
+//\r
+// Global to avoid infinite reentrance of memory allocation when updating\r
+// page table attributes, which may need allocating pages for new PDE/PTE.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN mOnGuarding = FALSE;\r
+\r
+//\r
+// Pointer to table tracking the Guarded memory with bitmap, in which  '1'\r
+// is used to indicate memory guarded. '0' might be free memory or Guard\r
+// page itself, depending on status of memory adjacent to it.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINT64 mGuardedMemoryMap = 0;\r
+\r
+//\r
+// Current depth level of map table pointed by mGuardedMemoryMap.\r
+// mMapLevel must be initialized at least by 1. It will be automatically\r
+// updated according to the address of memory just tracked.\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINTN mMapLevel = 1;\r
+\r
+//\r
+// Shift and mask for each level of map table\r
+//\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH]\r
+                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS;\r
+GLOBAL_REMOVE_IF_UNREFERENCED UINTN mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH]\r
+                                    = GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS;\r
+\r
+//\r
+// SMM memory attribute protocol\r
+//\r
+EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *mSmmMemoryAttribute = NULL;\r
+\r
+/**\r
+  Set corresponding bits in bitmap table to 1 according to the address.\r
+\r
+  @param[in]  Address     Start address to set for.\r
+  @param[in]  BitNumber   Number of bits to set.\r
+  @param[in]  BitMap      Pointer to bitmap which covers the Address.\r
+\r
+  @return VOID\r
+**/\r
+STATIC\r
+VOID\r
+SetBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   BitNumber,\r
+  IN UINT64                  *BitMap\r
+  )\r
+{\r
+  UINTN           Lsbs;\r
+  UINTN           Qwords;\r
+  UINTN           Msbs;\r
+  UINTN           StartBit;\r
+  UINTN           EndBit;\r
+\r
+  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);\r
+  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+\r
+  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %\r
+              GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;\r
+  } else {\r
+    Msbs    = BitNumber;\r
+    Lsbs    = 0;\r
+    Qwords  = 0;\r
+  }\r
+\r
+  if (Msbs > 0) {\r
+    *BitMap |= LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);\r
+    BitMap  += 1;\r
+  }\r
+\r
+  if (Qwords > 0) {\r
+    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES,\r
+              (UINT64)-1);\r
+    BitMap += Qwords;\r
+  }\r
+\r
+  if (Lsbs > 0) {\r
+    *BitMap |= (LShiftU64 (1, Lsbs) - 1);\r
+  }\r
+}\r
+\r
+/**\r
+  Set corresponding bits in bitmap table to 0 according to the address.\r
+\r
+  @param[in]  Address     Start address to set for.\r
+  @param[in]  BitNumber   Number of bits to set.\r
+  @param[in]  BitMap      Pointer to bitmap which covers the Address.\r
+\r
+  @return VOID.\r
+**/\r
+STATIC\r
+VOID\r
+ClearBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   BitNumber,\r
+  IN UINT64                  *BitMap\r
+  )\r
+{\r
+  UINTN           Lsbs;\r
+  UINTN           Qwords;\r
+  UINTN           Msbs;\r
+  UINTN           StartBit;\r
+  UINTN           EndBit;\r
+\r
+  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);\r
+  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+\r
+  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+    Msbs    = (GUARDED_HEAP_MAP_ENTRY_BITS - StartBit) %\r
+              GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Lsbs    = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+    Qwords  = (BitNumber - Msbs) / GUARDED_HEAP_MAP_ENTRY_BITS;\r
+  } else {\r
+    Msbs    = BitNumber;\r
+    Lsbs    = 0;\r
+    Qwords  = 0;\r
+  }\r
+\r
+  if (Msbs > 0) {\r
+    *BitMap &= ~LShiftU64 (LShiftU64 (1, Msbs) - 1, StartBit);\r
+    BitMap  += 1;\r
+  }\r
+\r
+  if (Qwords > 0) {\r
+    SetMem64 ((VOID *)BitMap, Qwords * GUARDED_HEAP_MAP_ENTRY_BYTES, 0);\r
+    BitMap += Qwords;\r
+  }\r
+\r
+  if (Lsbs > 0) {\r
+    *BitMap &= ~(LShiftU64 (1, Lsbs) - 1);\r
+  }\r
+}\r
+\r
+/**\r
+  Get corresponding bits in bitmap table according to the address.\r
+\r
+  The value of bit 0 corresponds to the status of memory at given Address.\r
+  No more than 64 bits can be retrieved in one call.\r
+\r
+  @param[in]  Address     Start address to retrieve bits for.\r
+  @param[in]  BitNumber   Number of bits to get.\r
+  @param[in]  BitMap      Pointer to bitmap which covers the Address.\r
+\r
+  @return An integer containing the bits information.\r
+**/\r
+STATIC\r
+UINT64\r
+GetBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   BitNumber,\r
+  IN UINT64                  *BitMap\r
+  )\r
+{\r
+  UINTN           StartBit;\r
+  UINTN           EndBit;\r
+  UINTN           Lsbs;\r
+  UINTN           Msbs;\r
+  UINT64          Result;\r
+\r
+  ASSERT (BitNumber <= GUARDED_HEAP_MAP_ENTRY_BITS);\r
+\r
+  StartBit  = (UINTN)GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address);\r
+  EndBit    = (StartBit + BitNumber - 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+\r
+  if ((StartBit + BitNumber) > GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+    Msbs = GUARDED_HEAP_MAP_ENTRY_BITS - StartBit;\r
+    Lsbs = (EndBit + 1) % GUARDED_HEAP_MAP_ENTRY_BITS;\r
+  } else {\r
+    Msbs = BitNumber;\r
+    Lsbs = 0;\r
+  }\r
+\r
+  Result    = RShiftU64 ((*BitMap), StartBit) & (LShiftU64 (1, Msbs) - 1);\r
+  if (Lsbs > 0) {\r
+    BitMap  += 1;\r
+    Result  |= LShiftU64 ((*BitMap) & (LShiftU64 (1, Lsbs) - 1), Msbs);\r
+  }\r
+\r
+  return Result;\r
+}\r
+\r
+/**\r
+  Helper function to allocate pages without Guard for internal uses.\r
+\r
+  @param[in]  Pages       Page number.\r
+\r
+  @return Address of memory allocated.\r
+**/\r
+VOID *\r
+PageAlloc (\r
+  IN UINTN  Pages\r
+  )\r
+{\r
+  EFI_STATUS              Status;\r
+  EFI_PHYSICAL_ADDRESS    Memory;\r
+\r
+  Status = SmmInternalAllocatePages (AllocateAnyPages, EfiRuntimeServicesData,\r
+                                     Pages, &Memory, FALSE);\r
+  if (EFI_ERROR (Status)) {\r
+    Memory = 0;\r
+  }\r
+\r
+  return (VOID *)(UINTN)Memory;\r
+}\r
+\r
+/**\r
+  Locate the pointer of bitmap from the guarded memory bitmap tables, which\r
+  covers the given Address.\r
+\r
+  @param[in]  Address       Start address to search the bitmap for.\r
+  @param[in]  AllocMapUnit  Flag to indicate memory allocation for the table.\r
+  @param[out] BitMap        Pointer to bitmap which covers the Address.\r
+\r
+  @return The bit number from given Address to the end of current map table.\r
+**/\r
+UINTN\r
+FindGuardedMemoryMap (\r
+  IN  EFI_PHYSICAL_ADDRESS    Address,\r
+  IN  BOOLEAN                 AllocMapUnit,\r
+  OUT UINT64                  **BitMap\r
+  )\r
+{\r
+  UINTN                   Level;\r
+  UINT64                  *GuardMap;\r
+  UINT64                  MapMemory;\r
+  UINTN                   Index;\r
+  UINTN                   Size;\r
+  UINTN                   BitsToUnitEnd;\r
+\r
+  //\r
+  // Adjust current map table depth according to the address to access\r
+  //\r
+  while (mMapLevel < GUARDED_HEAP_MAP_TABLE_DEPTH\r
+         &&\r
+         RShiftU64 (\r
+           Address,\r
+           mLevelShift[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1]\r
+           ) != 0) {\r
+\r
+    if (mGuardedMemoryMap != 0) {\r
+      Size = (mLevelMask[GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel - 1] + 1)\r
+             * GUARDED_HEAP_MAP_ENTRY_BYTES;\r
+      MapMemory = (UINT64)(UINTN)PageAlloc (EFI_SIZE_TO_PAGES (Size));\r
+      ASSERT (MapMemory != 0);\r
+\r
+      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);\r
+\r
+      *(UINT64 *)(UINTN)MapMemory = mGuardedMemoryMap;\r
+      mGuardedMemoryMap = MapMemory;\r
+    }\r
+\r
+    mMapLevel++;\r
+\r
+  }\r
+\r
+  GuardMap = &mGuardedMemoryMap;\r
+  for (Level = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;\r
+       Level < GUARDED_HEAP_MAP_TABLE_DEPTH;\r
+       ++Level) {\r
+\r
+    if (*GuardMap == 0) {\r
+      if (!AllocMapUnit) {\r
+        GuardMap = NULL;\r
+        break;\r
+      }\r
+\r
+      Size = (mLevelMask[Level] + 1) * GUARDED_HEAP_MAP_ENTRY_BYTES;\r
+      MapMemory = (UINT64)(UINTN)PageAlloc (EFI_SIZE_TO_PAGES (Size));\r
+      ASSERT (MapMemory != 0);\r
+\r
+      SetMem ((VOID *)(UINTN)MapMemory, Size, 0);\r
+      *GuardMap = MapMemory;\r
+    }\r
+\r
+    Index     = (UINTN)RShiftU64 (Address, mLevelShift[Level]);\r
+    Index     &= mLevelMask[Level];\r
+    GuardMap  = (UINT64 *)(UINTN)((*GuardMap) + Index * sizeof (UINT64));\r
+\r
+  }\r
+\r
+  BitsToUnitEnd = GUARDED_HEAP_MAP_BITS - GUARDED_HEAP_MAP_BIT_INDEX (Address);\r
+  *BitMap       = GuardMap;\r
+\r
+  return BitsToUnitEnd;\r
+}\r
+\r
+/**\r
+  Set corresponding bits in bitmap table to 1 according to given memory range.\r
+\r
+  @param[in]  Address       Memory address to guard from.\r
+  @param[in]  NumberOfPages Number of pages to guard.\r
+\r
+  @return VOID\r
+**/\r
+VOID\r
+EFIAPI\r
+SetGuardedMemoryBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   NumberOfPages\r
+  )\r
+{\r
+  UINT64            *BitMap;\r
+  UINTN             Bits;\r
+  UINTN             BitsToUnitEnd;\r
+\r
+  while (NumberOfPages > 0) {\r
+    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);\r
+    ASSERT (BitMap != NULL);\r
+\r
+    if (NumberOfPages > BitsToUnitEnd) {\r
+      // Cross map unit\r
+      Bits = BitsToUnitEnd;\r
+    } else {\r
+      Bits  = NumberOfPages;\r
+    }\r
+\r
+    SetBits (Address, Bits, BitMap);\r
+\r
+    NumberOfPages -= Bits;\r
+    Address       += EFI_PAGES_TO_SIZE (Bits);\r
+  }\r
+}\r
+\r
+/**\r
+  Clear corresponding bits in bitmap table according to given memory range.\r
+\r
+  @param[in]  Address       Memory address to unset from.\r
+  @param[in]  NumberOfPages Number of pages to unset guard.\r
+\r
+  @return VOID\r
+**/\r
+VOID\r
+EFIAPI\r
+ClearGuardedMemoryBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   NumberOfPages\r
+  )\r
+{\r
+  UINT64            *BitMap;\r
+  UINTN             Bits;\r
+  UINTN             BitsToUnitEnd;\r
+\r
+  while (NumberOfPages > 0) {\r
+    BitsToUnitEnd = FindGuardedMemoryMap (Address, TRUE, &BitMap);\r
+    ASSERT (BitMap != NULL);\r
+\r
+    if (NumberOfPages > BitsToUnitEnd) {\r
+      // Cross map unit\r
+      Bits = BitsToUnitEnd;\r
+    } else {\r
+      Bits  = NumberOfPages;\r
+    }\r
+\r
+    ClearBits (Address, Bits, BitMap);\r
+\r
+    NumberOfPages -= Bits;\r
+    Address       += EFI_PAGES_TO_SIZE (Bits);\r
+  }\r
+}\r
+\r
+/**\r
+  Retrieve corresponding bits in bitmap table according to given memory range.\r
+\r
+  @param[in]  Address       Memory address to retrieve from.\r
+  @param[in]  NumberOfPages Number of pages to retrieve.\r
+\r
+  @return An integer containing the guarded memory bitmap.\r
+**/\r
+UINTN\r
+GetGuardedMemoryBits (\r
+  IN EFI_PHYSICAL_ADDRESS    Address,\r
+  IN UINTN                   NumberOfPages\r
+  )\r
+{\r
+  UINT64            *BitMap;\r
+  UINTN             Bits;\r
+  UINTN             Result;\r
+  UINTN             Shift;\r
+  UINTN             BitsToUnitEnd;\r
+\r
+  ASSERT (NumberOfPages <= GUARDED_HEAP_MAP_ENTRY_BITS);\r
+\r
+  Result = 0;\r
+  Shift  = 0;\r
+  while (NumberOfPages > 0) {\r
+    BitsToUnitEnd = FindGuardedMemoryMap (Address, FALSE, &BitMap);\r
+\r
+    if (NumberOfPages > BitsToUnitEnd) {\r
+      // Cross map unit\r
+      Bits  = BitsToUnitEnd;\r
+    } else {\r
+      Bits  = NumberOfPages;\r
+    }\r
+\r
+    if (BitMap != NULL) {\r
+      Result |= LShiftU64 (GetBits (Address, Bits, BitMap), Shift);\r
+    }\r
+\r
+    Shift         += Bits;\r
+    NumberOfPages -= Bits;\r
+    Address       += EFI_PAGES_TO_SIZE (Bits);\r
+  }\r
+\r
+  return Result;\r
+}\r
+\r
+/**\r
+  Get bit value in bitmap table for the given address.\r
+\r
+  @param[in]  Address     The address to retrieve for.\r
+\r
+  @return 1 or 0.\r
+**/\r
+UINTN\r
+EFIAPI\r
+GetGuardMapBit (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINT64        *GuardMap;\r
+\r
+  FindGuardedMemoryMap (Address, FALSE, &GuardMap);\r
+  if (GuardMap != NULL) {\r
+    if (RShiftU64 (*GuardMap,\r
+                   GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address)) & 1) {\r
+      return 1;\r
+    }\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+/**\r
+  Set the bit in bitmap table for the given address.\r
+\r
+  @param[in]  Address     The address to set for.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+SetGuardMapBit (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINT64        *GuardMap;\r
+  UINT64        BitMask;\r
+\r
+  FindGuardedMemoryMap (Address, TRUE, &GuardMap);\r
+  if (GuardMap != NULL) {\r
+    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));\r
+    *GuardMap |= BitMask;\r
+  }\r
+}\r
+\r
+/**\r
+  Clear the bit in bitmap table for the given address.\r
+\r
+  @param[in]  Address     The address to clear for.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+ClearGuardMapBit (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  UINT64        *GuardMap;\r
+  UINT64        BitMask;\r
+\r
+  FindGuardedMemoryMap (Address, TRUE, &GuardMap);\r
+  if (GuardMap != NULL) {\r
+    BitMask = LShiftU64 (1, GUARDED_HEAP_MAP_ENTRY_BIT_INDEX (Address));\r
+    *GuardMap &= ~BitMask;\r
+  }\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is a Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a Guard page.\r
+  @return FALSE The page at Address is not a Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsGuardPage (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+)\r
+{\r
+  UINTN       BitMap;\r
+\r
+  //\r
+  // There must be at least one guarded page before and/or after given\r
+  // address if it's a Guard page. The bitmap pattern should be one of\r
+  // 001, 100 and 101\r
+  //\r
+  BitMap = GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 3);\r
+  return ((BitMap == BIT0) || (BitMap == BIT2) || (BitMap == (BIT2 | BIT0)));\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is a head Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a head Guard page.\r
+  @return FALSE The page at Address is not a head Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsHeadGuard (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  return (GetGuardedMemoryBits (Address, 2) == BIT1);\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is a tail Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a tail Guard page.\r
+  @return FALSE The page at Address is not a tail Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsTailGuard (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  return (GetGuardedMemoryBits (Address - EFI_PAGE_SIZE, 2) == BIT0);\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address is guarded or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is guarded.\r
+  @return FALSE The page at Address is not guarded.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsMemoryGuarded (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  )\r
+{\r
+  return (GetGuardMapBit (Address) == 1);\r
+}\r
+\r
+/**\r
+  Set the page at the given address to be a Guard page.\r
+\r
+  This is done by changing the page table attribute to be NOT PRSENT.\r
+\r
+  @param[in]  BaseAddress     Page address to Guard at.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+SetGuardPage (\r
+  IN  EFI_PHYSICAL_ADDRESS      BaseAddress\r
+  )\r
+{\r
+  if (mSmmMemoryAttribute != NULL) {\r
+    mOnGuarding = TRUE;\r
+    mSmmMemoryAttribute->SetMemoryAttributes (\r
+                           mSmmMemoryAttribute,\r
+                           BaseAddress,\r
+                           EFI_PAGE_SIZE,\r
+                           EFI_MEMORY_RP\r
+                           );\r
+    mOnGuarding = FALSE;\r
+  }\r
+}\r
+\r
+/**\r
+  Unset the Guard page at the given address to the normal memory.\r
+\r
+  This is done by changing the page table attribute to be PRSENT.\r
+\r
+  @param[in]  BaseAddress     Page address to Guard at.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+EFIAPI\r
+UnsetGuardPage (\r
+  IN  EFI_PHYSICAL_ADDRESS      BaseAddress\r
+  )\r
+{\r
+  if (mSmmMemoryAttribute != NULL) {\r
+    mOnGuarding = TRUE;\r
+    mSmmMemoryAttribute->ClearMemoryAttributes (\r
+                           mSmmMemoryAttribute,\r
+                           BaseAddress,\r
+                           EFI_PAGE_SIZE,\r
+                           EFI_MEMORY_RP\r
+                           );\r
+    mOnGuarding = FALSE;\r
+  }\r
+}\r
+\r
+/**\r
+  Check to see if the memory at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Memory type to check.\r
+  @param[in]  AllocateType    Allocation type to check.\r
+  @param[in]  PageOrPool      Indicate a page allocation or pool allocation.\r
+\r
+\r
+  @return TRUE  The given type of memory should be guarded.\r
+  @return FALSE The given type of memory should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsMemoryTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN EFI_ALLOCATE_TYPE      AllocateType,\r
+  IN UINT8                  PageOrPool\r
+  )\r
+{\r
+  UINT64 TestBit;\r
+  UINT64 ConfigBit;\r
+\r
+  if ((PcdGet8 (PcdHeapGuardPropertyMask) & PageOrPool) == 0\r
+      || mOnGuarding\r
+      || AllocateType == AllocateAddress) {\r
+    return FALSE;\r
+  }\r
+\r
+  ConfigBit = 0;\r
+  if ((PageOrPool & GUARD_HEAP_TYPE_POOL) != 0) {\r
+    ConfigBit |= PcdGet64 (PcdHeapGuardPoolType);\r
+  }\r
+\r
+  if ((PageOrPool & GUARD_HEAP_TYPE_PAGE) != 0) {\r
+    ConfigBit |= PcdGet64 (PcdHeapGuardPageType);\r
+  }\r
+\r
+  if (MemoryType == EfiRuntimeServicesData ||\r
+      MemoryType == EfiRuntimeServicesCode) {\r
+    TestBit = LShiftU64 (1, MemoryType);\r
+  } else if (MemoryType == EfiMaxMemoryType) {\r
+    TestBit = (UINT64)-1;\r
+  } else {\r
+    TestBit = 0;\r
+  }\r
+\r
+  return ((ConfigBit & TestBit) != 0);\r
+}\r
+\r
+/**\r
+  Check to see if the pool at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Pool type to check.\r
+\r
+\r
+  @return TRUE  The given type of pool should be guarded.\r
+  @return FALSE The given type of pool should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPoolTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType\r
+  )\r
+{\r
+  return IsMemoryTypeToGuard (MemoryType, AllocateAnyPages,\r
+                              GUARD_HEAP_TYPE_POOL);\r
+}\r
+\r
+/**\r
+  Check to see if the page at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Page type to check.\r
+  @param[in]  AllocateType    Allocation type to check.\r
+\r
+  @return TRUE  The given type of page should be guarded.\r
+  @return FALSE The given type of page should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPageTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN EFI_ALLOCATE_TYPE      AllocateType\r
+  )\r
+{\r
+  return IsMemoryTypeToGuard (MemoryType, AllocateType, GUARD_HEAP_TYPE_PAGE);\r
+}\r
+\r
+/**\r
+  Check to see if the heap guard is enabled for page and/or pool allocation.\r
+\r
+  @return TRUE/FALSE.\r
+**/\r
+BOOLEAN\r
+IsHeapGuardEnabled (\r
+  VOID\r
+  )\r
+{\r
+  return IsMemoryTypeToGuard (EfiMaxMemoryType, AllocateAnyPages,\r
+                              GUARD_HEAP_TYPE_POOL|GUARD_HEAP_TYPE_PAGE);\r
+}\r
+\r
+/**\r
+  Set head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to set guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+SetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS    GuardPage;\r
+\r
+  //\r
+  // Set tail Guard\r
+  //\r
+  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);\r
+  if (!IsGuardPage (GuardPage)) {\r
+    SetGuardPage (GuardPage);\r
+  }\r
+\r
+  // Set head Guard\r
+  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);\r
+  if (!IsGuardPage (GuardPage)) {\r
+    SetGuardPage (GuardPage);\r
+  }\r
+\r
+  //\r
+  // Mark the memory range as Guarded\r
+  //\r
+  SetGuardedMemoryBits (Memory, NumberOfPages);\r
+}\r
+\r
+/**\r
+  Unset head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to unset guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+UnsetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS  GuardPage;\r
+\r
+  if (NumberOfPages == 0) {\r
+    return;\r
+  }\r
+\r
+  //\r
+  // Head Guard must be one page before, if any.\r
+  //\r
+  GuardPage = Memory - EFI_PAGES_TO_SIZE (1);\r
+  if (IsHeadGuard (GuardPage)) {\r
+    if (!IsMemoryGuarded (GuardPage - EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the head Guard is not a tail Guard of adjacent memory block,\r
+      // unset it.\r
+      //\r
+      UnsetGuardPage (GuardPage);\r
+    }\r
+  } else if (IsMemoryGuarded (GuardPage)) {\r
+    //\r
+    // Pages before memory to free are still in Guard. It's a partial free\r
+    // case. Turn first page of memory block to free into a new Guard.\r
+    //\r
+    SetGuardPage (Memory);\r
+  }\r
+\r
+  //\r
+  // Tail Guard must be the page after this memory block to free, if any.\r
+  //\r
+  GuardPage = Memory + EFI_PAGES_TO_SIZE (NumberOfPages);\r
+  if (IsTailGuard (GuardPage)) {\r
+    if (!IsMemoryGuarded (GuardPage + EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the tail Guard is not a head Guard of adjacent memory block,\r
+      // free it; otherwise, keep it.\r
+      //\r
+      UnsetGuardPage (GuardPage);\r
+    }\r
+  } else if (IsMemoryGuarded (GuardPage)) {\r
+    //\r
+    // Pages after memory to free are still in Guard. It's a partial free\r
+    // case. We need to keep one page to be a head Guard.\r
+    //\r
+    SetGuardPage (GuardPage - EFI_PAGES_TO_SIZE (1));\r
+  }\r
+\r
+  //\r
+  // No matter what, we just clear the mark of the Guarded memory.\r
+  //\r
+  ClearGuardedMemoryBits(Memory, NumberOfPages);\r
+}\r
+\r
+/**\r
+  Adjust address of free memory according to existing and/or required Guard.\r
+\r
+  This function will check if there're existing Guard pages of adjacent\r
+  memory blocks, and try to use it as the Guard page of the memory to be\r
+  allocated.\r
+\r
+  @param[in]  Start           Start address of free memory block.\r
+  @param[in]  Size            Size of free memory block.\r
+  @param[in]  SizeRequested   Size of memory to allocate.\r
+\r
+  @return The end address of memory block found.\r
+  @return 0 if no enough space for the required size of memory and its Guard.\r
+**/\r
+UINT64\r
+AdjustMemoryS (\r
+  IN UINT64                  Start,\r
+  IN UINT64                  Size,\r
+  IN UINT64                  SizeRequested\r
+  )\r
+{\r
+  UINT64  Target;\r
+\r
+  Target = Start + Size - SizeRequested;\r
+\r
+  //\r
+  // At least one more page needed for Guard page.\r
+  //\r
+  if (Size < (SizeRequested + EFI_PAGES_TO_SIZE (1))) {\r
+    return 0;\r
+  }\r
+\r
+  if (!IsGuardPage (Start + Size)) {\r
+    // No Guard at tail to share. One more page is needed.\r
+    Target -= EFI_PAGES_TO_SIZE (1);\r
+  }\r
+\r
+  // Out of range?\r
+  if (Target < Start) {\r
+    return 0;\r
+  }\r
+\r
+  // At the edge?\r
+  if (Target == Start) {\r
+    if (!IsGuardPage (Target - EFI_PAGES_TO_SIZE (1))) {\r
+      // No enough space for a new head Guard if no Guard at head to share.\r
+      return 0;\r
+    }\r
+  }\r
+\r
+  // OK, we have enough pages for memory and its Guards. Return the End of the\r
+  // free space.\r
+  return Target + SizeRequested - 1;\r
+}\r
+\r
+/**\r
+  Adjust the start address and number of pages to free according to Guard.\r
+\r
+  The purpose of this function is to keep the shared Guard page with adjacent\r
+  memory block if it's still in guard, or free it if no more sharing. Another\r
+  is to reserve pages as Guard pages in partial page free situation.\r
+\r
+  @param[in,out]  Memory          Base address of memory to free.\r
+  @param[in,out]  NumberOfPages   Size of memory to free.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryF (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS  Start;\r
+  EFI_PHYSICAL_ADDRESS  MemoryToTest;\r
+  UINTN                 PagesToFree;\r
+\r
+  if (Memory == NULL || NumberOfPages == NULL || *NumberOfPages == 0) {\r
+    return;\r
+  }\r
+\r
+  Start = *Memory;\r
+  PagesToFree = *NumberOfPages;\r
+\r
+  //\r
+  // Head Guard must be one page before, if any.\r
+  //\r
+  MemoryToTest = Start - EFI_PAGES_TO_SIZE (1);\r
+  if (IsHeadGuard (MemoryToTest)) {\r
+    if (!IsMemoryGuarded (MemoryToTest - EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the head Guard is not a tail Guard of adjacent memory block,\r
+      // free it; otherwise, keep it.\r
+      //\r
+      Start       -= EFI_PAGES_TO_SIZE (1);\r
+      PagesToFree += 1;\r
+    }\r
+  } else if (IsMemoryGuarded (MemoryToTest)) {\r
+    //\r
+    // Pages before memory to free are still in Guard. It's a partial free\r
+    // case. We need to keep one page to be a tail Guard.\r
+    //\r
+    Start       += EFI_PAGES_TO_SIZE (1);\r
+    PagesToFree -= 1;\r
+  }\r
+\r
+  //\r
+  // Tail Guard must be the page after this memory block to free, if any.\r
+  //\r
+  MemoryToTest = Start + EFI_PAGES_TO_SIZE (PagesToFree);\r
+  if (IsTailGuard (MemoryToTest)) {\r
+    if (!IsMemoryGuarded (MemoryToTest + EFI_PAGES_TO_SIZE (1))) {\r
+      //\r
+      // If the tail Guard is not a head Guard of adjacent memory block,\r
+      // free it; otherwise, keep it.\r
+      //\r
+      PagesToFree += 1;\r
+    }\r
+  } else if (IsMemoryGuarded (MemoryToTest)) {\r
+    //\r
+    // Pages after memory to free are still in Guard. It's a partial free\r
+    // case. We need to keep one page to be a head Guard.\r
+    //\r
+    PagesToFree -= 1;\r
+  }\r
+\r
+  *Memory         = Start;\r
+  *NumberOfPages  = PagesToFree;\r
+}\r
+\r
+/**\r
+  Adjust the base and number of pages to really allocate according to Guard.\r
+\r
+  @param[in,out]  Memory          Base address of free memory.\r
+  @param[in,out]  NumberOfPages   Size of memory to allocate.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryA (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  )\r
+{\r
+  //\r
+  // FindFreePages() has already taken the Guard into account. It's safe to\r
+  // adjust the start address and/or number of pages here, to make sure that\r
+  // the Guards are also "allocated".\r
+  //\r
+  if (!IsGuardPage (*Memory + EFI_PAGES_TO_SIZE (*NumberOfPages))) {\r
+    // No tail Guard, add one.\r
+    *NumberOfPages += 1;\r
+  }\r
+\r
+  if (!IsGuardPage (*Memory - EFI_PAGE_SIZE)) {\r
+    // No head Guard, add one.\r
+    *Memory        -= EFI_PAGE_SIZE;\r
+    *NumberOfPages += 1;\r
+  }\r
+}\r
+\r
+/**\r
+  Adjust the pool head position to make sure the Guard page is adjavent to\r
+  pool tail or pool head.\r
+\r
+  @param[in]  Memory    Base address of memory allocated.\r
+  @param[in]  NoPages   Number of pages actually allocated.\r
+  @param[in]  Size      Size of memory requested.\r
+                        (plus pool head/tail overhead)\r
+\r
+  @return Address of pool head\r
+**/\r
+VOID *\r
+AdjustPoolHeadA (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory,\r
+  IN UINTN                   NoPages,\r
+  IN UINTN                   Size\r
+  )\r
+{\r
+  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {\r
+    //\r
+    // Pool head is put near the head Guard\r
+    //\r
+    return (VOID *)(UINTN)Memory;\r
+  }\r
+\r
+  //\r
+  // Pool head is put near the tail Guard\r
+  //\r
+  return (VOID *)(UINTN)(Memory + EFI_PAGES_TO_SIZE (NoPages) - Size);\r
+}\r
+\r
+/**\r
+  Get the page base address according to pool head address.\r
+\r
+  @param[in]  Memory    Head address of pool to free.\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadF (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory\r
+  )\r
+{\r
+  if ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) != 0) {\r
+    //\r
+    // Pool head is put near the head Guard\r
+    //\r
+    return (VOID *)(UINTN)Memory;\r
+  }\r
+\r
+  //\r
+  // Pool head is put near the tail Guard\r
+  //\r
+  return (VOID *)(UINTN)(Memory & ~EFI_PAGE_MASK);\r
+}\r
+\r
+/**\r
+  Helper function of memory allocation with Guard pages.\r
+\r
+  @param  FreePageList           The free page node.\r
+  @param  NumberOfPages          Number of pages to be allocated.\r
+  @param  MaxAddress             Request to allocate memory below this address.\r
+  @param  MemoryType             Type of memory requested.\r
+\r
+  @return Memory address of allocated pages.\r
+**/\r
+UINTN\r
+InternalAllocMaxAddressWithGuard (\r
+  IN OUT LIST_ENTRY           *FreePageList,\r
+  IN     UINTN                NumberOfPages,\r
+  IN     UINTN                MaxAddress,\r
+  IN     EFI_MEMORY_TYPE      MemoryType\r
+\r
+  )\r
+{\r
+  LIST_ENTRY      *Node;\r
+  FREE_PAGE_LIST  *Pages;\r
+  UINTN           PagesToAlloc;\r
+  UINTN           HeadGuard;\r
+  UINTN           TailGuard;\r
+  UINTN           Address;\r
+\r
+  for (Node = FreePageList->BackLink; Node != FreePageList;\r
+        Node = Node->BackLink) {\r
+    Pages = BASE_CR (Node, FREE_PAGE_LIST, Link);\r
+    if (Pages->NumberOfPages >= NumberOfPages &&\r
+        (UINTN)Pages + EFI_PAGES_TO_SIZE (NumberOfPages) - 1 <= MaxAddress) {\r
+\r
+      //\r
+      // We may need 1 or 2 more pages for Guard. Check it out.\r
+      //\r
+      PagesToAlloc = NumberOfPages;\r
+      TailGuard = (UINTN)Pages + EFI_PAGES_TO_SIZE (Pages->NumberOfPages);\r
+      if (!IsGuardPage (TailGuard)) {\r
+        //\r
+        // Add one if no Guard at the end of current free memory block.\r
+        //\r
+        PagesToAlloc += 1;\r
+        TailGuard     = 0;\r
+      }\r
+\r
+      HeadGuard = (UINTN)Pages +\r
+                  EFI_PAGES_TO_SIZE (Pages->NumberOfPages - PagesToAlloc) -\r
+                  EFI_PAGE_SIZE;\r
+      if (!IsGuardPage (HeadGuard)) {\r
+        //\r
+        // Add one if no Guard at the page before the address to allocate\r
+        //\r
+        PagesToAlloc += 1;\r
+        HeadGuard     = 0;\r
+      }\r
+\r
+      if (Pages->NumberOfPages < PagesToAlloc) {\r
+        // Not enough space to allocate memory with Guards? Try next block.\r
+        continue;\r
+      }\r
+\r
+      Address = InternalAllocPagesOnOneNode (Pages, PagesToAlloc, MaxAddress);\r
+      ConvertSmmMemoryMapEntry(MemoryType, Address, PagesToAlloc, FALSE);\r
+      CoreFreeMemoryMapStack();\r
+      if (HeadGuard == 0) {\r
+        // Don't pass the Guard page to user.\r
+        Address += EFI_PAGE_SIZE;\r
+      }\r
+      SetGuardForMemory (Address, NumberOfPages);\r
+      return Address;\r
+    }\r
+  }\r
+\r
+  return (UINTN)(-1);\r
+}\r
+\r
+/**\r
+  Helper function of memory free with Guard pages.\r
+\r
+  @param[in]  Memory                 Base address of memory being freed.\r
+  @param[in]  NumberOfPages          The number of pages to free.\r
+  @param[in]  AddRegion              If this memory is new added region.\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+**/\r
+EFI_STATUS\r
+SmmInternalFreePagesExWithGuard (\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages,\r
+  IN BOOLEAN               AddRegion\r
+  )\r
+{\r
+  EFI_PHYSICAL_ADDRESS    MemoryToFree;\r
+  UINTN                   PagesToFree;\r
+\r
+  MemoryToFree  = Memory;\r
+  PagesToFree   = NumberOfPages;\r
+\r
+  AdjustMemoryF (&MemoryToFree, &PagesToFree);\r
+  UnsetGuardForMemory (Memory, NumberOfPages);\r
+\r
+  return SmmInternalFreePagesEx (MemoryToFree, PagesToFree, AddRegion);\r
+}\r
+\r
+/**\r
+  Set all Guard pages which cannot be set during the non-SMM mode time.\r
+**/\r
+VOID\r
+SetAllGuardPages (\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     Index;\r
+  BOOLEAN   OnGuarding;\r
+\r
+  if (mGuardedMemoryMap == 0) {\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
+  OnGuarding    = FALSE;\r
+\r
+  DEBUG_CODE (\r
+    DumpGuardedMemoryBitmap ();\r
+  );\r
+\r
+  while (TRUE) {\r
+    if (Indices[Level] > Entries[Level]) {\r
+      Tables[Level] = 0;\r
+      Level        -= 1;\r
+    } else {\r
+\r
+      TableEntry  = ((UINT64 *)(UINTN)(Tables[Level]))[Indices[Level]];\r
+      Address     = Addresses[Level];\r
+\r
+      if (TableEntry == 0) {\r
+\r
+        OnGuarding = FALSE;\r
+\r
+      } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {\r
+\r
+        Level            += 1;\r
+        Tables[Level]     = TableEntry;\r
+        Addresses[Level]  = Address;\r
+        Indices[Level]    = 0;\r
+\r
+        continue;\r
+\r
+      } else {\r
+\r
+        Index = 0;\r
+        while (Index < GUARDED_HEAP_MAP_ENTRY_BITS) {\r
+          if ((TableEntry & 1) == 1) {\r
+            if (OnGuarding) {\r
+              GuardPage = 0;\r
+            } else {\r
+              GuardPage = Address - EFI_PAGE_SIZE;\r
+            }\r
+            OnGuarding = TRUE;\r
+          } else {\r
+            if (OnGuarding) {\r
+              GuardPage = Address;\r
+            } else {\r
+              GuardPage = 0;\r
+            }\r
+            OnGuarding = FALSE;\r
+          }\r
+\r
+          if (GuardPage != 0) {\r
+            SetGuardPage (GuardPage);\r
+          }\r
+\r
+          if (TableEntry == 0) {\r
+            break;\r
+          }\r
+\r
+          TableEntry = RShiftU64 (TableEntry, 1);\r
+          Address   += EFI_PAGE_SIZE;\r
+          Index     += 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
+/**\r
+  Hook function used to set all Guard pages after entering SMM mode.\r
+**/\r
+VOID\r
+SmmEntryPointMemoryManagementHook (\r
+  VOID\r
+  )\r
+{\r
+  EFI_STATUS  Status;\r
+\r
+  if (mSmmMemoryAttribute == NULL) {\r
+    Status = SmmLocateProtocol (\r
+               &gEdkiiSmmMemoryAttributeProtocolGuid,\r
+               NULL,\r
+               (VOID **)&mSmmMemoryAttribute\r
+               );\r
+    if (!EFI_ERROR(Status)) {\r
+      SetAllGuardPages ();\r
+    }\r
+  }\r
+}\r
+\r
+/**\r
+  Helper function to convert a UINT64 value in binary to a string.\r
+\r
+  @param[in]  Value       Value of a UINT64 integer.\r
+  @param[out] BinString   String buffer to contain the conversion result.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+Uint64ToBinString (\r
+  IN  UINT64      Value,\r
+  OUT CHAR8       *BinString\r
+  )\r
+{\r
+  UINTN Index;\r
+\r
+  if (BinString == NULL) {\r
+    return;\r
+  }\r
+\r
+  for (Index = 64; Index > 0; --Index) {\r
+    BinString[Index - 1] = '0' + (Value & 1);\r
+    Value = RShiftU64 (Value, 1);\r
+  }\r
+  BinString[64] = '\0';\r
+}\r
+\r
+/**\r
+  Dump the guarded memory bit map.\r
+**/\r
+VOID\r
+EFIAPI\r
+DumpGuardedMemoryBitmap (\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
+  INTN      Level;\r
+  UINTN     RepeatZero;\r
+  CHAR8     String[GUARDED_HEAP_MAP_ENTRY_BITS + 1];\r
+  CHAR8     *Ruler1;\r
+  CHAR8     *Ruler2;\r
+\r
+  if (mGuardedMemoryMap == 0) {\r
+    return;\r
+  }\r
+\r
+  Ruler1 = "               3               2               1               0";\r
+  Ruler2 = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";\r
+\r
+  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "============================="\r
+                                  " Guarded Memory Bitmap "\r
+                                  "==============================\r\n"));\r
+  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler1));\r
+  DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "                  %a\r\n", Ruler2));\r
+\r
+  CopyMem (Entries, mLevelMask, sizeof (Entries));\r
+  CopyMem (Shifts, mLevelShift, sizeof (Shifts));\r
+\r
+  SetMem (Indices, sizeof(Indices), 0);\r
+  SetMem (Tables, sizeof(Tables), 0);\r
+  SetMem (Addresses, sizeof(Addresses), 0);\r
+\r
+  Level         = GUARDED_HEAP_MAP_TABLE_DEPTH - mMapLevel;\r
+  Tables[Level] = mGuardedMemoryMap;\r
+  Address       = 0;\r
+  RepeatZero    = 0;\r
+\r
+  while (TRUE) {\r
+    if (Indices[Level] > Entries[Level]) {\r
+\r
+      Tables[Level] = 0;\r
+      Level        -= 1;\r
+      RepeatZero    = 0;\r
+\r
+      DEBUG ((\r
+        HEAP_GUARD_DEBUG_LEVEL,\r
+        "========================================="\r
+        "=========================================\r\n"\r
+        ));\r
+\r
+    } else {\r
+\r
+      TableEntry  = ((UINT64 *)(UINTN)Tables[Level])[Indices[Level]];\r
+      Address     = Addresses[Level];\r
+\r
+      if (TableEntry == 0) {\r
+\r
+        if (Level == GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {\r
+          if (RepeatZero == 0) {\r
+            Uint64ToBinString(TableEntry, String);\r
+            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));\r
+          } else if (RepeatZero == 1) {\r
+            DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "...             : ...\r\n"));\r
+          }\r
+          RepeatZero += 1;\r
+        }\r
+\r
+      } else if (Level < GUARDED_HEAP_MAP_TABLE_DEPTH - 1) {\r
+\r
+        Level            += 1;\r
+        Tables[Level]     = TableEntry;\r
+        Addresses[Level]  = Address;\r
+        Indices[Level]    = 0;\r
+        RepeatZero        = 0;\r
+\r
+        continue;\r
+\r
+      } else {\r
+\r
+        RepeatZero = 0;\r
+        Uint64ToBinString(TableEntry, String);\r
+        DEBUG ((HEAP_GUARD_DEBUG_LEVEL, "%016lx: %a\r\n", Address, String));\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
+/**\r
+  Debug function used to verify if the Guard page is well set or not.\r
+\r
+  @param[in]  BaseAddress     Address of memory to check.\r
+  @param[in]  NumberOfPages   Size of memory in pages.\r
+\r
+  @return TRUE    The head Guard and tail Guard are both well set.\r
+  @return FALSE   The head Guard and/or tail Guard are not well set.\r
+**/\r
+BOOLEAN\r
+VerifyMemoryGuard (\r
+  IN  EFI_PHYSICAL_ADDRESS      BaseAddress,\r
+  IN  UINTN                     NumberOfPages\r
+  )\r
+{\r
+  EFI_STATUS            Status;\r
+  UINT64                Attribute;\r
+  EFI_PHYSICAL_ADDRESS  Address;\r
+\r
+  if (mSmmMemoryAttribute == NULL) {\r
+    return TRUE;\r
+  }\r
+\r
+  Attribute = 0;\r
+  Address = BaseAddress - EFI_PAGE_SIZE;\r
+  Status = mSmmMemoryAttribute->GetMemoryAttributes (\r
+                                  mSmmMemoryAttribute,\r
+                                  Address,\r
+                                  EFI_PAGE_SIZE,\r
+                                  &Attribute\r
+                                  );\r
+  if (EFI_ERROR (Status) || (Attribute & EFI_MEMORY_RP) == 0) {\r
+    DEBUG ((DEBUG_ERROR, "Head Guard is not set at: %016lx (%016lX)!!!\r\n",\r
+            Address, Attribute));\r
+    DumpGuardedMemoryBitmap ();\r
+    return FALSE;\r
+  }\r
+\r
+  Attribute = 0;\r
+  Address = BaseAddress + EFI_PAGES_TO_SIZE (NumberOfPages);\r
+  Status = mSmmMemoryAttribute->GetMemoryAttributes (\r
+                                  mSmmMemoryAttribute,\r
+                                  Address,\r
+                                  EFI_PAGE_SIZE,\r
+                                  &Attribute\r
+                                  );\r
+  if (EFI_ERROR (Status) || (Attribute & EFI_MEMORY_RP) == 0) {\r
+    DEBUG ((DEBUG_ERROR, "Tail Guard is not set at: %016lx (%016lX)!!!\r\n",\r
+            Address, Attribute));\r
+    DumpGuardedMemoryBitmap ();\r
+    return FALSE;\r
+  }\r
+\r
+  return TRUE;\r
+}\r
+\r
index 8698ff9f879164e9fd9192d74facb8e97f8f09c4..a6f92a20420874a98427aa9a90c83d41a611080f 100644 (file)
-/** @file
-  Data structure and functions to allocate and free memory space.
-
-Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
-This program and the accompanying materials
-are licensed and made available under the terms and conditions of the BSD License
-which accompanies this distribution.  The full text of the license may be found at
-http://opensource.org/licenses/bsd-license.php
-
-THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef _HEAPGUARD_H_
-#define _HEAPGUARD_H_
-
-#include "PiSmmCore.h"
-
-//
-// Following macros are used to define and access the guarded memory bitmap
-// table.
-//
-// To simplify the access and reduce the memory used for this table, the
-// table is constructed in the similar way as page table structure but in
-// reverse direction, i.e. from bottom growing up to top.
-//
-//    - 1-bit tracks 1 page (4KB)
-//    - 1-UINT64 map entry tracks 256KB memory
-//    - 1K-UINT64 map table tracks 256MB memory
-//    - Five levels of tables can track any address of memory of 64-bit
-//      system, like below.
-//
-//       512   *   512   *   512   *   512    *    1K   *  64b *     4K
-//    111111111 111111111 111111111 111111111 1111111111 111111 111111111111
-//    63        54        45        36        27         17     11         0
-//       9b        9b        9b        9b         10b      6b       12b
-//       L0   ->   L1   ->   L2   ->   L3   ->    L4   -> bits  ->  page
-//      1FF       1FF       1FF       1FF         3FF      3F       FFF
-//
-// L4 table has 1K * sizeof(UINT64) = 8K (2-page), which can track 256MB
-// memory. Each table of L0-L3 will be allocated when its memory address
-// range is to be tracked. Only 1-page will be allocated each time. This
-// can save memories used to establish this map table.
-//
-// For a normal configuration of system with 4G memory, two levels of tables
-// can track the whole memory, because two levels (L3+L4) of map tables have
-// already coverred 37-bit of memory address. And for a normal UEFI BIOS,
-// less than 128M memory would be consumed during boot. That means we just
-// need
-//
-//          1-page (L3) + 2-page (L4)
-//
-// memory (3 pages) to track the memory allocation works. In this case,
-// there's no need to setup L0-L2 tables.
-//
-
-//
-// Each entry occupies 8B/64b. 1-page can hold 512 entries, which spans 9
-// bits in address. (512 = 1 << 9)
-//
-#define BYTE_LENGTH_SHIFT                   3             // (8 = 1 << 3)
-
-#define GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT  \
-        (EFI_PAGE_SHIFT - BYTE_LENGTH_SHIFT)
-
-#define GUARDED_HEAP_MAP_TABLE_DEPTH        5
-
-// Use UINT64_index + bit_index_of_UINT64 to locate the bit in may
-#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT    6             // (64 = 1 << 6)
-
-#define GUARDED_HEAP_MAP_ENTRY_BITS         \
-        (1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)
-
-#define GUARDED_HEAP_MAP_ENTRY_BYTES        \
-        (GUARDED_HEAP_MAP_ENTRY_BITS / 8)
-
-// L4 table address width: 64 - 9 * 4 - 6 - 12 = 10b
-#define GUARDED_HEAP_MAP_ENTRY_SHIFT              \
-        (GUARDED_HEAP_MAP_ENTRY_BITS              \
-         - GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 4 \
-         - GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT       \
-         - EFI_PAGE_SHIFT)
-
-// L4 table address mask: (1 << 10 - 1) = 0x3FF
-#define GUARDED_HEAP_MAP_ENTRY_MASK               \
-        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1)
-
-// Size of each L4 table: (1 << 10) * 8 = 8KB = 2-page
-#define GUARDED_HEAP_MAP_SIZE                     \
-        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) * GUARDED_HEAP_MAP_ENTRY_BYTES)
-
-// Memory size tracked by one L4 table: 8KB * 8 * 4KB = 256MB
-#define GUARDED_HEAP_MAP_UNIT_SIZE                \
-        (GUARDED_HEAP_MAP_SIZE * 8 * EFI_PAGE_SIZE)
-
-// L4 table entry number: 8KB / 8 = 1024
-#define GUARDED_HEAP_MAP_ENTRIES_PER_UNIT         \
-        (GUARDED_HEAP_MAP_SIZE / GUARDED_HEAP_MAP_ENTRY_BYTES)
-
-// L4 table entry indexing
-#define GUARDED_HEAP_MAP_ENTRY_INDEX(Address)                       \
-        (RShiftU64 (Address, EFI_PAGE_SHIFT                         \
-                             + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)    \
-         & GUARDED_HEAP_MAP_ENTRY_MASK)
-
-// L4 table entry bit indexing
-#define GUARDED_HEAP_MAP_ENTRY_BIT_INDEX(Address)       \
-        (RShiftU64 (Address, EFI_PAGE_SHIFT)            \
-         & ((1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT) - 1))
-
-//
-// Total bits (pages) tracked by one L4 table (65536-bit)
-//
-#define GUARDED_HEAP_MAP_BITS                               \
-        (1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \
-               + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT))
-
-//
-// Bit indexing inside the whole L4 table (0 - 65535)
-//
-#define GUARDED_HEAP_MAP_BIT_INDEX(Address)                     \
-        (RShiftU64 (Address, EFI_PAGE_SHIFT)                    \
-         & ((1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \
-                   + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)) - 1))
-
-//
-// Memory address bit width tracked by L4 table: 10 + 6 + 12 = 28
-//
-#define GUARDED_HEAP_MAP_TABLE_SHIFT                                      \
-        (GUARDED_HEAP_MAP_ENTRY_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT  \
-         + EFI_PAGE_SHIFT)
-
-//
-// Macro used to initialize the local array variable for map table traversing
-// {55, 46, 37, 28, 18}
-//
-#define GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS                                 \
-  {                                                                         \
-    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 3,  \
-    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 2,  \
-    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT,      \
-    GUARDED_HEAP_MAP_TABLE_SHIFT,                                           \
-    EFI_PAGE_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT                       \
-  }
-
-//
-// Masks used to extract address range of each level of table
-// {0x1FF, 0x1FF, 0x1FF, 0x1FF, 0x3FF}
-//
-#define GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS                                  \
-  {                                                                         \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \
-    (1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1                                 \
-  }
-
-//
-// Memory type to guard (matching the related PCD definition)
-//
-#define GUARD_HEAP_TYPE_POOL        BIT2
-#define GUARD_HEAP_TYPE_PAGE        BIT3
-
-//
-// Debug message level
-//
-#define HEAP_GUARD_DEBUG_LEVEL  (DEBUG_POOL|DEBUG_PAGE)
-
-typedef struct {
-  UINT32                TailMark;
-  UINT32                HeadMark;
-  EFI_PHYSICAL_ADDRESS  Address;
-  LIST_ENTRY            Link;
-} HEAP_GUARD_NODE;
-
-/**
-  Set head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to set guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID.
-**/
-VOID
-SetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  );
-
-/**
-  Unset head Guard and tail Guard for the given memory range.
-
-  @param[in]  Memory          Base address of memory to unset guard for.
-  @param[in]  NumberOfPages   Memory size in pages.
-
-  @return VOID.
-**/
-VOID
-UnsetGuardForMemory (
-  IN EFI_PHYSICAL_ADDRESS   Memory,
-  IN UINTN                  NumberOfPages
-  );
-
-/**
-  Adjust the base and number of pages to really allocate according to Guard.
-
-  @param[in,out]  Memory          Base address of free memory.
-  @param[in,out]  NumberOfPages   Size of memory to allocate.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryA (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  );
-
-/**
-  Adjust the start address and number of pages to free according to Guard.
-
-  The purpose of this function is to keep the shared Guard page with adjacent
-  memory block if it's still in guard, or free it if no more sharing. Another
-  is to reserve pages as Guard pages in partial page free situation.
-
-  @param[in,out]  Memory          Base address of memory to free.
-  @param[in,out]  NumberOfPages   Size of memory to free.
-
-  @return VOID.
-**/
-VOID
-AdjustMemoryF (
-  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,
-  IN OUT UINTN                   *NumberOfPages
-  );
-
-/**
-  Check to see if the pool at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Pool type to check.
-
-
-  @return TRUE  The given type of pool should be guarded.
-  @return FALSE The given type of pool should not be guarded.
-**/
-BOOLEAN
-IsPoolTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType
-  );
-
-/**
-  Check to see if the page at the given address should be guarded or not.
-
-  @param[in]  MemoryType      Page type to check.
-  @param[in]  AllocateType    Allocation type to check.
-
-  @return TRUE  The given type of page should be guarded.
-  @return FALSE The given type of page should not be guarded.
-**/
-BOOLEAN
-IsPageTypeToGuard (
-  IN EFI_MEMORY_TYPE        MemoryType,
-  IN EFI_ALLOCATE_TYPE      AllocateType
-  );
-
-/**
-  Check to see if the page at the given address is guarded or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is guarded.
-  @return FALSE The page at Address is not guarded.
-**/
-BOOLEAN
-EFIAPI
-IsMemoryGuarded (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  );
-
-/**
-  Check to see if the page at the given address is a Guard page or not.
-
-  @param[in]  Address     The address to check for.
-
-  @return TRUE  The page at Address is a Guard page.
-  @return FALSE The page at Address is not a Guard page.
-**/
-BOOLEAN
-EFIAPI
-IsGuardPage (
-  IN EFI_PHYSICAL_ADDRESS    Address
-  );
-
-/**
-  Dump the guarded memory bit map.
-**/
-VOID
-EFIAPI
-DumpGuardedMemoryBitmap (
-  VOID
-  );
-
-/**
-  Adjust the pool head position to make sure the Guard page is adjavent to
-  pool tail or pool head.
-
-  @param[in]  Memory    Base address of memory allocated.
-  @param[in]  NoPages   Number of pages actually allocated.
-  @param[in]  Size      Size of memory requested.
-                        (plus pool head/tail overhead)
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadA (
-  IN EFI_PHYSICAL_ADDRESS    Memory,
-  IN UINTN                   NoPages,
-  IN UINTN                   Size
-  );
-
-/**
-  Get the page base address according to pool head address.
-
-  @param[in]  Memory    Head address of pool to free.
-
-  @return Address of pool head.
-**/
-VOID *
-AdjustPoolHeadF (
-  IN EFI_PHYSICAL_ADDRESS    Memory
-  );
-
-/**
-  Helper function of memory allocation with Guard pages.
-
-  @param  FreePageList           The free page node.
-  @param  NumberOfPages          Number of pages to be allocated.
-  @param  MaxAddress             Request to allocate memory below this address.
-  @param  MemoryType             Type of memory requested.
-
-  @return Memory address of allocated pages.
-**/
-UINTN
-InternalAllocMaxAddressWithGuard (
-  IN OUT LIST_ENTRY           *FreePageList,
-  IN     UINTN                NumberOfPages,
-  IN     UINTN                MaxAddress,
-  IN     EFI_MEMORY_TYPE      MemoryType
-  );
-
-/**
-  Helper function of memory free with Guard pages.
-
-  @param[in]  Memory                 Base address of memory being freed.
-  @param[in]  NumberOfPages          The number of pages to free.
-  @param[in]  AddRegion              If this memory is new added region.
-
-  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.
-  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or
-                                 NumberOfPages is zero.
-  @return EFI_SUCCESS            Pages successfully freed.
-**/
-EFI_STATUS
-SmmInternalFreePagesExWithGuard (
-  IN EFI_PHYSICAL_ADDRESS  Memory,
-  IN UINTN                 NumberOfPages,
-  IN BOOLEAN               AddRegion
-  );
-
-/**
-  Check to see if the heap guard is enabled for page and/or pool allocation.
-
-  @return TRUE/FALSE.
-**/
-BOOLEAN
-IsHeapGuardEnabled (
-  VOID
-  );
-
-/**
-  Debug function used to verify if the Guard page is well set or not.
-
-  @param[in]  BaseAddress     Address of memory to check.
-  @param[in]  NumberOfPages   Size of memory in pages.
-
-  @return TRUE    The head Guard and tail Guard are both well set.
-  @return FALSE   The head Guard and/or tail Guard are not well set.
-**/
-BOOLEAN
-VerifyMemoryGuard (
-  IN  EFI_PHYSICAL_ADDRESS      BaseAddress,
-  IN  UINTN                     NumberOfPages
-  );
-
-extern BOOLEAN mOnGuarding;
-
-#endif
+/** @file\r
+  Data structure and functions to allocate and free memory space.\r
+\r
+Copyright (c) 2017, 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
+http://opensource.org/licenses/bsd-license.php\r
+\r
+THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#ifndef _HEAPGUARD_H_\r
+#define _HEAPGUARD_H_\r
+\r
+#include "PiSmmCore.h"\r
+\r
+//\r
+// Following macros are used to define and access the guarded memory bitmap\r
+// table.\r
+//\r
+// To simplify the access and reduce the memory used for this table, the\r
+// table is constructed in the similar way as page table structure but in\r
+// reverse direction, i.e. from bottom growing up to top.\r
+//\r
+//    - 1-bit tracks 1 page (4KB)\r
+//    - 1-UINT64 map entry tracks 256KB memory\r
+//    - 1K-UINT64 map table tracks 256MB memory\r
+//    - Five levels of tables can track any address of memory of 64-bit\r
+//      system, like below.\r
+//\r
+//       512   *   512   *   512   *   512    *    1K   *  64b *     4K\r
+//    111111111 111111111 111111111 111111111 1111111111 111111 111111111111\r
+//    63        54        45        36        27         17     11         0\r
+//       9b        9b        9b        9b         10b      6b       12b\r
+//       L0   ->   L1   ->   L2   ->   L3   ->    L4   -> bits  ->  page\r
+//      1FF       1FF       1FF       1FF         3FF      3F       FFF\r
+//\r
+// L4 table has 1K * sizeof(UINT64) = 8K (2-page), which can track 256MB\r
+// memory. Each table of L0-L3 will be allocated when its memory address\r
+// range is to be tracked. Only 1-page will be allocated each time. This\r
+// can save memories used to establish this map table.\r
+//\r
+// For a normal configuration of system with 4G memory, two levels of tables\r
+// can track the whole memory, because two levels (L3+L4) of map tables have\r
+// already coverred 37-bit of memory address. And for a normal UEFI BIOS,\r
+// less than 128M memory would be consumed during boot. That means we just\r
+// need\r
+//\r
+//          1-page (L3) + 2-page (L4)\r
+//\r
+// memory (3 pages) to track the memory allocation works. In this case,\r
+// there's no need to setup L0-L2 tables.\r
+//\r
+\r
+//\r
+// Each entry occupies 8B/64b. 1-page can hold 512 entries, which spans 9\r
+// bits in address. (512 = 1 << 9)\r
+//\r
+#define BYTE_LENGTH_SHIFT                   3             // (8 = 1 << 3)\r
+\r
+#define GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT  \\r
+        (EFI_PAGE_SHIFT - BYTE_LENGTH_SHIFT)\r
+\r
+#define GUARDED_HEAP_MAP_TABLE_DEPTH        5\r
+\r
+// Use UINT64_index + bit_index_of_UINT64 to locate the bit in may\r
+#define GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT    6             // (64 = 1 << 6)\r
+\r
+#define GUARDED_HEAP_MAP_ENTRY_BITS         \\r
+        (1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)\r
+\r
+#define GUARDED_HEAP_MAP_ENTRY_BYTES        \\r
+        (GUARDED_HEAP_MAP_ENTRY_BITS / 8)\r
+\r
+// L4 table address width: 64 - 9 * 4 - 6 - 12 = 10b\r
+#define GUARDED_HEAP_MAP_ENTRY_SHIFT              \\r
+        (GUARDED_HEAP_MAP_ENTRY_BITS              \\r
+         - GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 4 \\r
+         - GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT       \\r
+         - EFI_PAGE_SHIFT)\r
+\r
+// L4 table address mask: (1 << 10 - 1) = 0x3FF\r
+#define GUARDED_HEAP_MAP_ENTRY_MASK               \\r
+        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1)\r
+\r
+// Size of each L4 table: (1 << 10) * 8 = 8KB = 2-page\r
+#define GUARDED_HEAP_MAP_SIZE                     \\r
+        ((1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) * GUARDED_HEAP_MAP_ENTRY_BYTES)\r
+\r
+// Memory size tracked by one L4 table: 8KB * 8 * 4KB = 256MB\r
+#define GUARDED_HEAP_MAP_UNIT_SIZE                \\r
+        (GUARDED_HEAP_MAP_SIZE * 8 * EFI_PAGE_SIZE)\r
+\r
+// L4 table entry number: 8KB / 8 = 1024\r
+#define GUARDED_HEAP_MAP_ENTRIES_PER_UNIT         \\r
+        (GUARDED_HEAP_MAP_SIZE / GUARDED_HEAP_MAP_ENTRY_BYTES)\r
+\r
+// L4 table entry indexing\r
+#define GUARDED_HEAP_MAP_ENTRY_INDEX(Address)                       \\r
+        (RShiftU64 (Address, EFI_PAGE_SHIFT                         \\r
+                             + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)    \\r
+         & GUARDED_HEAP_MAP_ENTRY_MASK)\r
+\r
+// L4 table entry bit indexing\r
+#define GUARDED_HEAP_MAP_ENTRY_BIT_INDEX(Address)       \\r
+        (RShiftU64 (Address, EFI_PAGE_SHIFT)            \\r
+         & ((1 << GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT) - 1))\r
+\r
+//\r
+// Total bits (pages) tracked by one L4 table (65536-bit)\r
+//\r
+#define GUARDED_HEAP_MAP_BITS                               \\r
+        (1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \\r
+               + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT))\r
+\r
+//\r
+// Bit indexing inside the whole L4 table (0 - 65535)\r
+//\r
+#define GUARDED_HEAP_MAP_BIT_INDEX(Address)                     \\r
+        (RShiftU64 (Address, EFI_PAGE_SHIFT)                    \\r
+         & ((1 << (GUARDED_HEAP_MAP_ENTRY_SHIFT                 \\r
+                   + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT)) - 1))\r
+\r
+//\r
+// Memory address bit width tracked by L4 table: 10 + 6 + 12 = 28\r
+//\r
+#define GUARDED_HEAP_MAP_TABLE_SHIFT                                      \\r
+        (GUARDED_HEAP_MAP_ENTRY_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT  \\r
+         + EFI_PAGE_SHIFT)\r
+\r
+//\r
+// Macro used to initialize the local array variable for map table traversing\r
+// {55, 46, 37, 28, 18}\r
+//\r
+#define GUARDED_HEAP_MAP_TABLE_DEPTH_SHIFTS                                 \\r
+  {                                                                         \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 3,  \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT * 2,  \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT + GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT,      \\r
+    GUARDED_HEAP_MAP_TABLE_SHIFT,                                           \\r
+    EFI_PAGE_SHIFT + GUARDED_HEAP_MAP_ENTRY_BIT_SHIFT                       \\r
+  }\r
+\r
+//\r
+// Masks used to extract address range of each level of table\r
+// {0x1FF, 0x1FF, 0x1FF, 0x1FF, 0x3FF}\r
+//\r
+#define GUARDED_HEAP_MAP_TABLE_DEPTH_MASKS                                  \\r
+  {                                                                         \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_TABLE_ENTRY_SHIFT) - 1,                          \\r
+    (1 << GUARDED_HEAP_MAP_ENTRY_SHIFT) - 1                                 \\r
+  }\r
+\r
+//\r
+// Memory type to guard (matching the related PCD definition)\r
+//\r
+#define GUARD_HEAP_TYPE_POOL        BIT2\r
+#define GUARD_HEAP_TYPE_PAGE        BIT3\r
+\r
+//\r
+// Debug message level\r
+//\r
+#define HEAP_GUARD_DEBUG_LEVEL  (DEBUG_POOL|DEBUG_PAGE)\r
+\r
+typedef struct {\r
+  UINT32                TailMark;\r
+  UINT32                HeadMark;\r
+  EFI_PHYSICAL_ADDRESS  Address;\r
+  LIST_ENTRY            Link;\r
+} HEAP_GUARD_NODE;\r
+\r
+/**\r
+  Set head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to set guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+SetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  );\r
+\r
+/**\r
+  Unset head Guard and tail Guard for the given memory range.\r
+\r
+  @param[in]  Memory          Base address of memory to unset guard for.\r
+  @param[in]  NumberOfPages   Memory size in pages.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+UnsetGuardForMemory (\r
+  IN EFI_PHYSICAL_ADDRESS   Memory,\r
+  IN UINTN                  NumberOfPages\r
+  );\r
+\r
+/**\r
+  Adjust the base and number of pages to really allocate according to Guard.\r
+\r
+  @param[in,out]  Memory          Base address of free memory.\r
+  @param[in,out]  NumberOfPages   Size of memory to allocate.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryA (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  );\r
+\r
+/**\r
+  Adjust the start address and number of pages to free according to Guard.\r
+\r
+  The purpose of this function is to keep the shared Guard page with adjacent\r
+  memory block if it's still in guard, or free it if no more sharing. Another\r
+  is to reserve pages as Guard pages in partial page free situation.\r
+\r
+  @param[in,out]  Memory          Base address of memory to free.\r
+  @param[in,out]  NumberOfPages   Size of memory to free.\r
+\r
+  @return VOID.\r
+**/\r
+VOID\r
+AdjustMemoryF (\r
+  IN OUT EFI_PHYSICAL_ADDRESS    *Memory,\r
+  IN OUT UINTN                   *NumberOfPages\r
+  );\r
+\r
+/**\r
+  Check to see if the pool at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Pool type to check.\r
+\r
+\r
+  @return TRUE  The given type of pool should be guarded.\r
+  @return FALSE The given type of pool should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPoolTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType\r
+  );\r
+\r
+/**\r
+  Check to see if the page at the given address should be guarded or not.\r
+\r
+  @param[in]  MemoryType      Page type to check.\r
+  @param[in]  AllocateType    Allocation type to check.\r
+\r
+  @return TRUE  The given type of page should be guarded.\r
+  @return FALSE The given type of page should not be guarded.\r
+**/\r
+BOOLEAN\r
+IsPageTypeToGuard (\r
+  IN EFI_MEMORY_TYPE        MemoryType,\r
+  IN EFI_ALLOCATE_TYPE      AllocateType\r
+  );\r
+\r
+/**\r
+  Check to see if the page at the given address is guarded or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is guarded.\r
+  @return FALSE The page at Address is not guarded.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsMemoryGuarded (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  );\r
+\r
+/**\r
+  Check to see if the page at the given address is a Guard page or not.\r
+\r
+  @param[in]  Address     The address to check for.\r
+\r
+  @return TRUE  The page at Address is a Guard page.\r
+  @return FALSE The page at Address is not a Guard page.\r
+**/\r
+BOOLEAN\r
+EFIAPI\r
+IsGuardPage (\r
+  IN EFI_PHYSICAL_ADDRESS    Address\r
+  );\r
+\r
+/**\r
+  Dump the guarded memory bit map.\r
+**/\r
+VOID\r
+EFIAPI\r
+DumpGuardedMemoryBitmap (\r
+  VOID\r
+  );\r
+\r
+/**\r
+  Adjust the pool head position to make sure the Guard page is adjavent to\r
+  pool tail or pool head.\r
+\r
+  @param[in]  Memory    Base address of memory allocated.\r
+  @param[in]  NoPages   Number of pages actually allocated.\r
+  @param[in]  Size      Size of memory requested.\r
+                        (plus pool head/tail overhead)\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadA (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory,\r
+  IN UINTN                   NoPages,\r
+  IN UINTN                   Size\r
+  );\r
+\r
+/**\r
+  Get the page base address according to pool head address.\r
+\r
+  @param[in]  Memory    Head address of pool to free.\r
+\r
+  @return Address of pool head.\r
+**/\r
+VOID *\r
+AdjustPoolHeadF (\r
+  IN EFI_PHYSICAL_ADDRESS    Memory\r
+  );\r
+\r
+/**\r
+  Helper function of memory allocation with Guard pages.\r
+\r
+  @param  FreePageList           The free page node.\r
+  @param  NumberOfPages          Number of pages to be allocated.\r
+  @param  MaxAddress             Request to allocate memory below this address.\r
+  @param  MemoryType             Type of memory requested.\r
+\r
+  @return Memory address of allocated pages.\r
+**/\r
+UINTN\r
+InternalAllocMaxAddressWithGuard (\r
+  IN OUT LIST_ENTRY           *FreePageList,\r
+  IN     UINTN                NumberOfPages,\r
+  IN     UINTN                MaxAddress,\r
+  IN     EFI_MEMORY_TYPE      MemoryType\r
+  );\r
+\r
+/**\r
+  Helper function of memory free with Guard pages.\r
+\r
+  @param[in]  Memory                 Base address of memory being freed.\r
+  @param[in]  NumberOfPages          The number of pages to free.\r
+  @param[in]  AddRegion              If this memory is new added region.\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or\r
+                                 NumberOfPages is zero.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+**/\r
+EFI_STATUS\r
+SmmInternalFreePagesExWithGuard (\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages,\r
+  IN BOOLEAN               AddRegion\r
+  );\r
+\r
+/**\r
+  Check to see if the heap guard is enabled for page and/or pool allocation.\r
+\r
+  @return TRUE/FALSE.\r
+**/\r
+BOOLEAN\r
+IsHeapGuardEnabled (\r
+  VOID\r
+  );\r
+\r
+/**\r
+  Debug function used to verify if the Guard page is well set or not.\r
+\r
+  @param[in]  BaseAddress     Address of memory to check.\r
+  @param[in]  NumberOfPages   Size of memory in pages.\r
+\r
+  @return TRUE    The head Guard and tail Guard are both well set.\r
+  @return FALSE   The head Guard and/or tail Guard are not well set.\r
+**/\r
+BOOLEAN\r
+VerifyMemoryGuard (\r
+  IN  EFI_PHYSICAL_ADDRESS      BaseAddress,\r
+  IN  UINTN                     NumberOfPages\r
+  );\r
+\r
+extern BOOLEAN mOnGuarding;\r
+\r
+#endif\r
index 5f5b4bbe1c8654e156d1d9d80b72769c345d99d7..8909d46a00a2170907c437f959a17b9a531f35d8 100644 (file)
@@ -64,8 +64,8 @@ LIST_ENTRY   mFreeMemoryMapEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemor
   @param[out]  Memory                 A pointer to receive the base allocated memory\r
                                       address.\r
   @param[in]   AddRegion              If this memory is new added region.\r
   @param[out]  Memory                 A pointer to receive the base allocated memory\r
                                       address.\r
   @param[in]   AddRegion              If this memory is new added region.\r
-  @param[in]   NeedGuard              Flag to indicate Guard page is needed
-                                      or not
+  @param[in]   NeedGuard              Flag to indicate Guard page is needed\r
+                                      or not\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
@@ -79,8 +79,8 @@ SmmInternalAllocatePagesEx (
   IN  EFI_MEMORY_TYPE       MemoryType,\r
   IN  UINTN                 NumberOfPages,\r
   OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
   IN  EFI_MEMORY_TYPE       MemoryType,\r
   IN  UINTN                 NumberOfPages,\r
   OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
-  IN  BOOLEAN               AddRegion,
-  IN  BOOLEAN               NeedGuard
+  IN  BOOLEAN               AddRegion,\r
+  IN  BOOLEAN               NeedGuard\r
   );\r
 \r
 /**\r
   );\r
 \r
 /**\r
@@ -115,8 +115,8 @@ AllocateMemoryMapEntry (
                EfiRuntimeServicesData,\r
                EFI_SIZE_TO_PAGES (RUNTIME_PAGE_ALLOCATION_GRANULARITY),\r
                &Mem,\r
                EfiRuntimeServicesData,\r
                EFI_SIZE_TO_PAGES (RUNTIME_PAGE_ALLOCATION_GRANULARITY),\r
                &Mem,\r
-               TRUE,
-               FALSE
+               TRUE,\r
+               FALSE\r
                );\r
     ASSERT_EFI_ERROR (Status);\r
     if(!EFI_ERROR (Status)) {\r
                );\r
     ASSERT_EFI_ERROR (Status);\r
     if(!EFI_ERROR (Status)) {\r
@@ -692,8 +692,8 @@ InternalAllocAddress (
   @param[out]  Memory                 A pointer to receive the base allocated memory\r
                                       address.\r
   @param[in]   AddRegion              If this memory is new added region.\r
   @param[out]  Memory                 A pointer to receive the base allocated memory\r
                                       address.\r
   @param[in]   AddRegion              If this memory is new added region.\r
-  @param[in]   NeedGuard              Flag to indicate Guard page is needed
-                                      or not
+  @param[in]   NeedGuard              Flag to indicate Guard page is needed\r
+                                      or not\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
@@ -707,8 +707,8 @@ SmmInternalAllocatePagesEx (
   IN  EFI_MEMORY_TYPE       MemoryType,\r
   IN  UINTN                 NumberOfPages,\r
   OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
   IN  EFI_MEMORY_TYPE       MemoryType,\r
   IN  UINTN                 NumberOfPages,\r
   OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
-  IN  BOOLEAN               AddRegion,
-  IN  BOOLEAN               NeedGuard
+  IN  BOOLEAN               AddRegion,\r
+  IN  BOOLEAN               NeedGuard\r
   )\r
 {\r
   UINTN  RequestedAddress;\r
   )\r
 {\r
   UINTN  RequestedAddress;\r
@@ -730,21 +730,21 @@ SmmInternalAllocatePagesEx (
     case AllocateAnyPages:\r
       RequestedAddress = (UINTN)(-1);\r
     case AllocateMaxAddress:\r
     case AllocateAnyPages:\r
       RequestedAddress = (UINTN)(-1);\r
     case AllocateMaxAddress:\r
-      if (NeedGuard) {
-        *Memory = InternalAllocMaxAddressWithGuard (
-                      &mSmmMemoryMap,
-                      NumberOfPages,
-                      RequestedAddress,
-                      MemoryType
-                      );
-        if (*Memory == (UINTN)-1) {
-          return EFI_OUT_OF_RESOURCES;
-        } else {
-          ASSERT (VerifyMemoryGuard (*Memory, NumberOfPages) == TRUE);
-          return EFI_SUCCESS;
-        }
-      }
-
+      if (NeedGuard) {\r
+        *Memory = InternalAllocMaxAddressWithGuard (\r
+                      &mSmmMemoryMap,\r
+                      NumberOfPages,\r
+                      RequestedAddress,\r
+                      MemoryType\r
+                      );\r
+        if (*Memory == (UINTN)-1) {\r
+          return EFI_OUT_OF_RESOURCES;\r
+        } else {\r
+          ASSERT (VerifyMemoryGuard (*Memory, NumberOfPages) == TRUE);\r
+          return EFI_SUCCESS;\r
+        }\r
+      }\r
+\r
       *Memory = InternalAllocMaxAddress (\r
                   &mSmmMemoryMap,\r
                   NumberOfPages,\r
       *Memory = InternalAllocMaxAddress (\r
                   &mSmmMemoryMap,\r
                   NumberOfPages,\r
@@ -788,8 +788,8 @@ SmmInternalAllocatePagesEx (
   @param[in]   NumberOfPages          The number of pages to allocate.\r
   @param[out]  Memory                 A pointer to receive the base allocated memory\r
                                       address.\r
   @param[in]   NumberOfPages          The number of pages to allocate.\r
   @param[out]  Memory                 A pointer to receive the base allocated memory\r
                                       address.\r
-  @param[in]   NeedGuard              Flag to indicate Guard page is needed
-                                      or not
+  @param[in]   NeedGuard              Flag to indicate Guard page is needed\r
+                                      or not\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
@@ -803,12 +803,12 @@ SmmInternalAllocatePages (
   IN  EFI_ALLOCATE_TYPE     Type,\r
   IN  EFI_MEMORY_TYPE       MemoryType,\r
   IN  UINTN                 NumberOfPages,\r
   IN  EFI_ALLOCATE_TYPE     Type,\r
   IN  EFI_MEMORY_TYPE       MemoryType,\r
   IN  UINTN                 NumberOfPages,\r
-  OUT EFI_PHYSICAL_ADDRESS  *Memory,
-  IN  BOOLEAN               NeedGuard
+  OUT EFI_PHYSICAL_ADDRESS  *Memory,\r
+  IN  BOOLEAN               NeedGuard\r
   )\r
 {\r
   )\r
 {\r
-  return SmmInternalAllocatePagesEx (Type, MemoryType, NumberOfPages, Memory,
-                                     FALSE, NeedGuard);
+  return SmmInternalAllocatePagesEx (Type, MemoryType, NumberOfPages, Memory,\r
+                                     FALSE, NeedGuard);\r
 }\r
 \r
 /**\r
 }\r
 \r
 /**\r
@@ -837,11 +837,11 @@ SmmAllocatePages (
   )\r
 {\r
   EFI_STATUS  Status;\r
   )\r
 {\r
   EFI_STATUS  Status;\r
-  BOOLEAN     NeedGuard;
+  BOOLEAN     NeedGuard;\r
 \r
 \r
-  NeedGuard = IsPageTypeToGuard (MemoryType, Type);
-  Status = SmmInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory,
-                                     NeedGuard);
+  NeedGuard = IsPageTypeToGuard (MemoryType, Type);\r
+  Status = SmmInternalAllocatePages (Type, MemoryType, NumberOfPages, Memory,\r
+                                     NeedGuard);\r
   if (!EFI_ERROR (Status)) {\r
     SmmCoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
   if (!EFI_ERROR (Status)) {\r
     SmmCoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
@@ -960,7 +960,7 @@ SmmInternalFreePagesEx (
 \r
   @param[in]  Memory                 Base address of memory being freed.\r
   @param[in]  NumberOfPages          The number of pages to free.\r
 \r
   @param[in]  Memory                 Base address of memory being freed.\r
   @param[in]  NumberOfPages          The number of pages to free.\r
-  @param[in]  IsGuarded              Is the memory to free guarded or not.
+  @param[in]  IsGuarded              Is the memory to free guarded or not.\r
 \r
   @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
   @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
 \r
   @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
   @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
@@ -971,13 +971,13 @@ EFI_STATUS
 EFIAPI\r
 SmmInternalFreePages (\r
   IN EFI_PHYSICAL_ADDRESS  Memory,\r
 EFIAPI\r
 SmmInternalFreePages (\r
   IN EFI_PHYSICAL_ADDRESS  Memory,\r
-  IN UINTN                 NumberOfPages,
-  IN BOOLEAN               IsGuarded
+  IN UINTN                 NumberOfPages,\r
+  IN BOOLEAN               IsGuarded\r
   )\r
 {\r
   )\r
 {\r
-  if (IsGuarded) {
-    return SmmInternalFreePagesExWithGuard (Memory, NumberOfPages, FALSE);
-  }
+  if (IsGuarded) {\r
+    return SmmInternalFreePagesExWithGuard (Memory, NumberOfPages, FALSE);\r
+  }\r
   return SmmInternalFreePagesEx (Memory, NumberOfPages, FALSE);\r
 }\r
 \r
   return SmmInternalFreePagesEx (Memory, NumberOfPages, FALSE);\r
 }\r
 \r
@@ -1000,10 +1000,10 @@ SmmFreePages (
   )\r
 {\r
   EFI_STATUS  Status;\r
   )\r
 {\r
   EFI_STATUS  Status;\r
-  BOOLEAN     IsGuarded;
+  BOOLEAN     IsGuarded;\r
 \r
 \r
-  IsGuarded = IsHeapGuardEnabled () && IsMemoryGuarded (Memory);
-  Status = SmmInternalFreePages (Memory, NumberOfPages, IsGuarded);
+  IsGuarded = IsHeapGuardEnabled () && IsMemoryGuarded (Memory);\r
+  Status = SmmInternalFreePages (Memory, NumberOfPages, IsGuarded);\r
   if (!EFI_ERROR (Status)) {\r
     SmmCoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
   if (!EFI_ERROR (Status)) {\r
     SmmCoreUpdateProfile (\r
       (EFI_PHYSICAL_ADDRESS) (UINTN) RETURN_ADDRESS (0),\r
index a0b295b31af642f64165eb6ce0fb0b4e0cbaeaf8..a7467aca201229dfb9511540ec7f02641e285945 100644 (file)
@@ -506,11 +506,11 @@ SmmEntryPoint (
   //\r
   PlatformHookBeforeSmmDispatch ();\r
 \r
   //\r
   PlatformHookBeforeSmmDispatch ();\r
 \r
-  //
-  // Call memory management hook function
-  //
-  SmmEntryPointMemoryManagementHook ();
-
+  //\r
+  // Call memory management hook function\r
+  //\r
+  SmmEntryPointMemoryManagementHook ();\r
+\r
   //\r
   // If a legacy boot has occured, then make sure gSmmCorePrivate is not accessed\r
   //\r
   //\r
   // If a legacy boot has occured, then make sure gSmmCorePrivate is not accessed\r
   //\r
@@ -704,7 +704,7 @@ SmmMain (
   //\r
   gSmmCorePrivate->Smst          = &gSmmCoreSmst;\r
   gSmmCorePrivate->SmmEntryPoint = SmmEntryPoint;\r
   //\r
   gSmmCorePrivate->Smst          = &gSmmCoreSmst;\r
   gSmmCorePrivate->SmmEntryPoint = SmmEntryPoint;\r
-
+\r
   //\r
   // No need to initialize memory service.\r
   // It is done in constructor of PiSmmCoreMemoryAllocationLib(),\r
   //\r
   // No need to initialize memory service.\r
   // It is done in constructor of PiSmmCoreMemoryAllocationLib(),\r
index fbbecfae520f7d5ed59283e5c4defa7b68961446..cdc491c324290cec80885ea9d2da40141d7fddcb 100644 (file)
@@ -33,7 +33,7 @@
 #include <Protocol/SmmLegacyBoot.h>\r
 #include <Protocol/SmmReadyToBoot.h>\r
 #include <Protocol/SmmEndOfS3Resume.h>\r
 #include <Protocol/SmmLegacyBoot.h>\r
 #include <Protocol/SmmReadyToBoot.h>\r
 #include <Protocol/SmmEndOfS3Resume.h>\r
-#include <Protocol/SmmMemoryAttribute.h>
+#include <Protocol/SmmMemoryAttribute.h>\r
 \r
 #include <Guid/Apriori.h>\r
 #include <Guid/EventGroup.h>\r
 \r
 #include <Guid/Apriori.h>\r
 #include <Guid/EventGroup.h>\r
@@ -61,7 +61,7 @@
 #include <Library/SmmMemLib.h>\r
 \r
 #include "PiSmmCorePrivateData.h"\r
 #include <Library/SmmMemLib.h>\r
 \r
 #include "PiSmmCorePrivateData.h"\r
-#include "HeapGuard.h"
+#include "HeapGuard.h"\r
 \r
 //\r
 // Used to build a table of SMI Handlers that the SMM Core registers\r
 \r
 //\r
 // Used to build a table of SMI Handlers that the SMM Core registers\r
@@ -320,7 +320,7 @@ SmmAllocatePages (
   @param  NumberOfPages          The number of pages to allocate\r
   @param  Memory                 A pointer to receive the base allocated memory\r
                                  address\r
   @param  NumberOfPages          The number of pages to allocate\r
   @param  Memory                 A pointer to receive the base allocated memory\r
                                  address\r
-  @param  NeedGuard              Flag to indicate Guard page is needed or not
+  @param  NeedGuard              Flag to indicate Guard page is needed or not\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
 \r
   @retval EFI_INVALID_PARAMETER  Parameters violate checking rules defined in spec.\r
   @retval EFI_NOT_FOUND          Could not allocate pages match the requirement.\r
@@ -334,8 +334,8 @@ SmmInternalAllocatePages (
   IN      EFI_ALLOCATE_TYPE         Type,\r
   IN      EFI_MEMORY_TYPE           MemoryType,\r
   IN      UINTN                     NumberOfPages,\r
   IN      EFI_ALLOCATE_TYPE         Type,\r
   IN      EFI_MEMORY_TYPE           MemoryType,\r
   IN      UINTN                     NumberOfPages,\r
-  OUT     EFI_PHYSICAL_ADDRESS      *Memory,
-  IN      BOOLEAN                   NeedGuard
+  OUT     EFI_PHYSICAL_ADDRESS      *Memory,\r
+  IN      BOOLEAN                   NeedGuard\r
   );\r
 \r
 /**\r
   );\r
 \r
 /**\r
@@ -361,8 +361,8 @@ SmmFreePages (
 \r
   @param  Memory                 Base address of memory being freed\r
   @param  NumberOfPages          The number of pages to free\r
 \r
   @param  Memory                 Base address of memory being freed\r
   @param  NumberOfPages          The number of pages to free\r
-  @param  IsGuarded              Flag to indicate if the memory is guarded
-                                 or not
+  @param  IsGuarded              Flag to indicate if the memory is guarded\r
+                                 or not\r
 \r
   @retval EFI_NOT_FOUND          Could not find the entry that covers the range\r
   @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
 \r
   @retval EFI_NOT_FOUND          Could not find the entry that covers the range\r
   @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
@@ -373,8 +373,8 @@ EFI_STATUS
 EFIAPI\r
 SmmInternalFreePages (\r
   IN      EFI_PHYSICAL_ADDRESS      Memory,\r
 EFIAPI\r
 SmmInternalFreePages (\r
   IN      EFI_PHYSICAL_ADDRESS      Memory,\r
-  IN      UINTN                     NumberOfPages,
-  IN      BOOLEAN                   IsGuarded
+  IN      UINTN                     NumberOfPages,\r
+  IN      BOOLEAN                   IsGuarded\r
   );\r
 \r
 /**\r
   );\r
 \r
 /**\r
@@ -1262,74 +1262,74 @@ typedef enum {
 \r
 extern LIST_ENTRY  mSmmPoolLists[SmmPoolTypeMax][MAX_POOL_INDEX];\r
 \r
 \r
 extern LIST_ENTRY  mSmmPoolLists[SmmPoolTypeMax][MAX_POOL_INDEX];\r
 \r
-/**
-  Internal Function. Allocate n pages from given free page node.
-
-  @param  Pages                  The free page node.
-  @param  NumberOfPages          Number of pages to be allocated.
-  @param  MaxAddress             Request to allocate memory below this address.
-
-  @return Memory address of allocated pages.
-
-**/
-UINTN
-InternalAllocPagesOnOneNode (
-  IN OUT FREE_PAGE_LIST   *Pages,
-  IN     UINTN            NumberOfPages,
-  IN     UINTN            MaxAddress
-  );
-
-/**
-  Update SMM memory map entry.
-
-  @param[in]  Type                   The type of allocation to perform.
-  @param[in]  Memory                 The base of memory address.
-  @param[in]  NumberOfPages          The number of pages to allocate.
-  @param[in]  AddRegion              If this memory is new added region.
-**/
-VOID
-ConvertSmmMemoryMapEntry (
-  IN EFI_MEMORY_TYPE       Type,
-  IN EFI_PHYSICAL_ADDRESS  Memory,
-  IN UINTN                 NumberOfPages,
-  IN BOOLEAN               AddRegion
-  );
-
-/**
-  Internal function.  Moves any memory descriptors that are on the
-  temporary descriptor stack to heap.
-
-**/
-VOID
-CoreFreeMemoryMapStack (
-  VOID
-  );
-
-/**
-  Frees previous allocated pages.
-
-  @param[in]  Memory                 Base address of memory being freed.
-  @param[in]  NumberOfPages          The number of pages to free.
-  @param[in]  AddRegion              If this memory is new added region.
-
-  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.
-  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.
-  @return EFI_SUCCESS            Pages successfully freed.
-
-**/
-EFI_STATUS
-SmmInternalFreePagesEx (
-  IN EFI_PHYSICAL_ADDRESS  Memory,
-  IN UINTN                 NumberOfPages,
-  IN BOOLEAN               AddRegion
-  );
-
-/**
-  Hook function used to set all Guard pages after entering SMM mode.
-**/
-VOID
-SmmEntryPointMemoryManagementHook (
-  VOID
-  );
-
+/**\r
+  Internal Function. Allocate n pages from given free page node.\r
+\r
+  @param  Pages                  The free page node.\r
+  @param  NumberOfPages          Number of pages to be allocated.\r
+  @param  MaxAddress             Request to allocate memory below this address.\r
+\r
+  @return Memory address of allocated pages.\r
+\r
+**/\r
+UINTN\r
+InternalAllocPagesOnOneNode (\r
+  IN OUT FREE_PAGE_LIST   *Pages,\r
+  IN     UINTN            NumberOfPages,\r
+  IN     UINTN            MaxAddress\r
+  );\r
+\r
+/**\r
+  Update SMM memory map entry.\r
+\r
+  @param[in]  Type                   The type of allocation to perform.\r
+  @param[in]  Memory                 The base of memory address.\r
+  @param[in]  NumberOfPages          The number of pages to allocate.\r
+  @param[in]  AddRegion              If this memory is new added region.\r
+**/\r
+VOID\r
+ConvertSmmMemoryMapEntry (\r
+  IN EFI_MEMORY_TYPE       Type,\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages,\r
+  IN BOOLEAN               AddRegion\r
+  );\r
+\r
+/**\r
+  Internal function.  Moves any memory descriptors that are on the\r
+  temporary descriptor stack to heap.\r
+\r
+**/\r
+VOID\r
+CoreFreeMemoryMapStack (\r
+  VOID\r
+  );\r
+\r
+/**\r
+  Frees previous allocated pages.\r
+\r
+  @param[in]  Memory                 Base address of memory being freed.\r
+  @param[in]  NumberOfPages          The number of pages to free.\r
+  @param[in]  AddRegion              If this memory is new added region.\r
+\r
+  @retval EFI_NOT_FOUND          Could not find the entry that covers the range.\r
+  @retval EFI_INVALID_PARAMETER  Address not aligned, Address is zero or NumberOfPages is zero.\r
+  @return EFI_SUCCESS            Pages successfully freed.\r
+\r
+**/\r
+EFI_STATUS\r
+SmmInternalFreePagesEx (\r
+  IN EFI_PHYSICAL_ADDRESS  Memory,\r
+  IN UINTN                 NumberOfPages,\r
+  IN BOOLEAN               AddRegion\r
+  );\r
+\r
+/**\r
+  Hook function used to set all Guard pages after entering SMM mode.\r
+**/\r
+VOID\r
+SmmEntryPointMemoryManagementHook (\r
+  VOID\r
+  );\r
+\r
 #endif\r
 #endif\r
index ead821b78fc3c16e6047f835a4c1f564a4122803..15836418870db0f2c8a96e3d12eb30fc3bd514f8 100644 (file)
@@ -40,7 +40,7 @@
   SmramProfileRecord.c\r
   MemoryAttributesTable.c\r
   SmiHandlerProfile.c\r
   SmramProfileRecord.c\r
   MemoryAttributesTable.c\r
   SmiHandlerProfile.c\r
-  HeapGuard.c
+  HeapGuard.c\r
 \r
 [Packages]\r
   MdePkg/MdePkg.dec\r
 \r
 [Packages]\r
   MdePkg/MdePkg.dec\r
@@ -90,8 +90,8 @@
   gEfiSmmGpiDispatch2ProtocolGuid               ## SOMETIMES_CONSUMES\r
   gEfiSmmIoTrapDispatch2ProtocolGuid            ## SOMETIMES_CONSUMES\r
   gEfiSmmUsbDispatch2ProtocolGuid               ## SOMETIMES_CONSUMES\r
   gEfiSmmGpiDispatch2ProtocolGuid               ## SOMETIMES_CONSUMES\r
   gEfiSmmIoTrapDispatch2ProtocolGuid            ## SOMETIMES_CONSUMES\r
   gEfiSmmUsbDispatch2ProtocolGuid               ## SOMETIMES_CONSUMES\r
-  gEfiSmmCpuProtocolGuid                        ## SOMETIMES_CONSUMES
-  gEdkiiSmmMemoryAttributeProtocolGuid          ## CONSUMES
+  gEfiSmmCpuProtocolGuid                        ## SOMETIMES_CONSUMES\r
+  gEdkiiSmmMemoryAttributeProtocolGuid          ## CONSUMES\r
 \r
 [Pcd]\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdLoadFixAddressSmmCodePageNumber     ## SOMETIMES_CONSUMES\r
 \r
 [Pcd]\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdLoadFixAddressSmmCodePageNumber     ## SOMETIMES_CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfilePropertyMask           ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfileDriverPath             ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmiHandlerProfilePropertyMask       ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfilePropertyMask           ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdMemoryProfileDriverPath             ## CONSUMES\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdSmiHandlerProfilePropertyMask       ## CONSUMES\r
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType                   ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType                   ## CONSUMES
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType                   ## CONSUMES\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType                   ## CONSUMES\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask               ## CONSUMES\r
 \r
 [Guids]\r
   gAprioriGuid                                  ## SOMETIMES_CONSUMES   ## File\r
 \r
 [Guids]\r
   gAprioriGuid                                  ## SOMETIMES_CONSUMES   ## File\r
index e98ce01b0f4d03a8b611d3516defb5cdc8fa5e22..f30af2ae56e8f95d3cd8290c1d17f920b154b2cf 100644 (file)
@@ -144,9 +144,9 @@ InternalAllocPoolByIndex (
   Status = EFI_SUCCESS;\r
   Hdr = NULL;\r
   if (PoolIndex == MAX_POOL_INDEX) {\r
   Status = EFI_SUCCESS;\r
   Hdr = NULL;\r
   if (PoolIndex == MAX_POOL_INDEX) {\r
-    Status = SmmInternalAllocatePages (AllocateAnyPages, PoolType,
-                                       EFI_SIZE_TO_PAGES (MAX_POOL_SIZE << 1),
-                                       &Address, FALSE);
+    Status = SmmInternalAllocatePages (AllocateAnyPages, PoolType,\r
+                                       EFI_SIZE_TO_PAGES (MAX_POOL_SIZE << 1),\r
+                                       &Address, FALSE);\r
     if (EFI_ERROR (Status)) {\r
       return EFI_OUT_OF_RESOURCES;\r
     }\r
     if (EFI_ERROR (Status)) {\r
       return EFI_OUT_OF_RESOURCES;\r
     }\r
@@ -245,9 +245,9 @@ SmmInternalAllocatePool (
   EFI_STATUS            Status;\r
   EFI_PHYSICAL_ADDRESS  Address;\r
   UINTN                 PoolIndex;\r
   EFI_STATUS            Status;\r
   EFI_PHYSICAL_ADDRESS  Address;\r
   UINTN                 PoolIndex;\r
-  BOOLEAN               HasPoolTail;
-  BOOLEAN               NeedGuard;
-  UINTN                 NoPages;
+  BOOLEAN               HasPoolTail;\r
+  BOOLEAN               NeedGuard;\r
+  UINTN                 NoPages;\r
 \r
   Address = 0;\r
 \r
 \r
   Address = 0;\r
 \r
@@ -256,47 +256,47 @@ SmmInternalAllocatePool (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  NeedGuard   = IsPoolTypeToGuard (PoolType);
-  HasPoolTail = !(NeedGuard &&
-                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
-
+  NeedGuard   = IsPoolTypeToGuard (PoolType);\r
+  HasPoolTail = !(NeedGuard &&\r
+                  ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));\r
+\r
   //\r
   // Adjust the size by the pool header & tail overhead\r
   //\r
   Size += POOL_OVERHEAD;\r
   //\r
   // Adjust the size by the pool header & tail overhead\r
   //\r
   Size += POOL_OVERHEAD;\r
-  if (Size > MAX_POOL_SIZE || NeedGuard) {
-    if (!HasPoolTail) {
-      Size -= sizeof (POOL_TAIL);
-    }
-
-    NoPages = EFI_SIZE_TO_PAGES (Size);
-    Status = SmmInternalAllocatePages (AllocateAnyPages, PoolType, NoPages,
-                                       &Address, NeedGuard);
+  if (Size > MAX_POOL_SIZE || NeedGuard) {\r
+    if (!HasPoolTail) {\r
+      Size -= sizeof (POOL_TAIL);\r
+    }\r
+\r
+    NoPages = EFI_SIZE_TO_PAGES (Size);\r
+    Status = SmmInternalAllocatePages (AllocateAnyPages, PoolType, NoPages,\r
+                                       &Address, NeedGuard);\r
     if (EFI_ERROR (Status)) {\r
       return Status;\r
     }\r
 \r
     if (EFI_ERROR (Status)) {\r
       return Status;\r
     }\r
 \r
-    if (NeedGuard) {
-      ASSERT (VerifyMemoryGuard (Address, NoPages) == TRUE);
-      Address = (EFI_PHYSICAL_ADDRESS)(UINTN)AdjustPoolHeadA (
-                                               Address,
-                                               NoPages,
-                                               Size
-                                               );
-    }
-
+    if (NeedGuard) {\r
+      ASSERT (VerifyMemoryGuard (Address, NoPages) == TRUE);\r
+      Address = (EFI_PHYSICAL_ADDRESS)(UINTN)AdjustPoolHeadA (\r
+                                               Address,\r
+                                               NoPages,\r
+                                               Size\r
+                                               );\r
+    }\r
+\r
     PoolHdr = (POOL_HEADER*)(UINTN)Address;\r
     PoolHdr->Signature = POOL_HEAD_SIGNATURE;\r
     PoolHdr->Size = EFI_PAGES_TO_SIZE (NoPages);\r
     PoolHdr->Available = FALSE;\r
     PoolHdr->Type = PoolType;\r
     PoolHdr = (POOL_HEADER*)(UINTN)Address;\r
     PoolHdr->Signature = POOL_HEAD_SIGNATURE;\r
     PoolHdr->Size = EFI_PAGES_TO_SIZE (NoPages);\r
     PoolHdr->Available = FALSE;\r
     PoolHdr->Type = PoolType;\r
-
-    if (HasPoolTail) {
-      PoolTail = HEAD_TO_TAIL (PoolHdr);
-      PoolTail->Signature = POOL_TAIL_SIGNATURE;
-      PoolTail->Size = PoolHdr->Size;
-    }
-
+\r
+    if (HasPoolTail) {\r
+      PoolTail = HEAD_TO_TAIL (PoolHdr);\r
+      PoolTail->Signature = POOL_TAIL_SIGNATURE;\r
+      PoolTail->Size = PoolHdr->Size;\r
+    }\r
+\r
     *Buffer = PoolHdr + 1;\r
     return Status;\r
   }\r
     *Buffer = PoolHdr + 1;\r
     return Status;\r
   }\r
@@ -368,18 +368,18 @@ SmmInternalFreePool (
 {\r
   FREE_POOL_HEADER  *FreePoolHdr;\r
   POOL_TAIL         *PoolTail;\r
 {\r
   FREE_POOL_HEADER  *FreePoolHdr;\r
   POOL_TAIL         *PoolTail;\r
-  BOOLEAN           HasPoolTail;
-  BOOLEAN           MemoryGuarded;
+  BOOLEAN           HasPoolTail;\r
+  BOOLEAN           MemoryGuarded;\r
 \r
   if (Buffer == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
 \r
   if (Buffer == NULL) {\r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  MemoryGuarded = IsHeapGuardEnabled () &&
-                  IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer);
-  HasPoolTail   = !(MemoryGuarded &&
-                    ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));
-
+  MemoryGuarded = IsHeapGuardEnabled () &&\r
+                  IsMemoryGuarded ((EFI_PHYSICAL_ADDRESS)(UINTN)Buffer);\r
+  HasPoolTail   = !(MemoryGuarded &&\r
+                    ((PcdGet8 (PcdHeapGuardPropertyMask) & BIT7) == 0));\r
+\r
   FreePoolHdr = (FREE_POOL_HEADER*)((POOL_HEADER*)Buffer - 1);\r
   ASSERT (FreePoolHdr->Header.Signature == POOL_HEAD_SIGNATURE);\r
   ASSERT (!FreePoolHdr->Header.Available);\r
   FreePoolHdr = (FREE_POOL_HEADER*)((POOL_HEADER*)Buffer - 1);\r
   ASSERT (FreePoolHdr->Header.Signature == POOL_HEAD_SIGNATURE);\r
   ASSERT (!FreePoolHdr->Header.Available);\r
@@ -387,28 +387,28 @@ SmmInternalFreePool (
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
     return EFI_INVALID_PARAMETER;\r
   }\r
 \r
-  if (HasPoolTail) {
-    PoolTail = HEAD_TO_TAIL (&FreePoolHdr->Header);
-    ASSERT (PoolTail->Signature == POOL_TAIL_SIGNATURE);
-    ASSERT (FreePoolHdr->Header.Size == PoolTail->Size);
-    if (PoolTail->Signature != POOL_TAIL_SIGNATURE) {
-      return EFI_INVALID_PARAMETER;
-    }
-
-    if (FreePoolHdr->Header.Size != PoolTail->Size) {
-      return EFI_INVALID_PARAMETER;
-    }
-  } else {
-    PoolTail = NULL;
+  if (HasPoolTail) {\r
+    PoolTail = HEAD_TO_TAIL (&FreePoolHdr->Header);\r
+    ASSERT (PoolTail->Signature == POOL_TAIL_SIGNATURE);\r
+    ASSERT (FreePoolHdr->Header.Size == PoolTail->Size);\r
+    if (PoolTail->Signature != POOL_TAIL_SIGNATURE) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+\r
+    if (FreePoolHdr->Header.Size != PoolTail->Size) {\r
+      return EFI_INVALID_PARAMETER;\r
+    }\r
+  } else {\r
+    PoolTail = NULL;\r
   }\r
 \r
   }\r
 \r
-  if (MemoryGuarded) {
-    Buffer = AdjustPoolHeadF ((EFI_PHYSICAL_ADDRESS)(UINTN)FreePoolHdr);
-    return SmmInternalFreePages (
-             (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer,
-             EFI_SIZE_TO_PAGES (FreePoolHdr->Header.Size),
-             TRUE
-             );
+  if (MemoryGuarded) {\r
+    Buffer = AdjustPoolHeadF ((EFI_PHYSICAL_ADDRESS)(UINTN)FreePoolHdr);\r
+    return SmmInternalFreePages (\r
+             (EFI_PHYSICAL_ADDRESS)(UINTN)Buffer,\r
+             EFI_SIZE_TO_PAGES (FreePoolHdr->Header.Size),\r
+             TRUE\r
+             );\r
   }\r
 \r
   if (FreePoolHdr->Header.Size > MAX_POOL_SIZE) {\r
   }\r
 \r
   if (FreePoolHdr->Header.Size > MAX_POOL_SIZE) {\r
@@ -416,8 +416,8 @@ SmmInternalFreePool (
     ASSERT ((FreePoolHdr->Header.Size & EFI_PAGE_MASK) == 0);\r
     return SmmInternalFreePages (\r
              (EFI_PHYSICAL_ADDRESS)(UINTN)FreePoolHdr,\r
     ASSERT ((FreePoolHdr->Header.Size & EFI_PAGE_MASK) == 0);\r
     return SmmInternalFreePages (\r
              (EFI_PHYSICAL_ADDRESS)(UINTN)FreePoolHdr,\r
-             EFI_SIZE_TO_PAGES (FreePoolHdr->Header.Size),
-             FALSE
+             EFI_SIZE_TO_PAGES (FreePoolHdr->Header.Size),\r
+             FALSE\r
              );\r
   }\r
   return InternalFreePoolByIndex (FreePoolHdr, PoolTail);\r
              );\r
   }\r
   return InternalFreePoolByIndex (FreePoolHdr, PoolTail);\r
index 86788bf1945f63463fe45706d0106ef73ccdd375..0700eb51d6e145c817331c147f80c4e50c72f86a 100644 (file)
-/** @file
-  SMM Memory Attribute Protocol provides retrieval and update service
-  for memory attributes in EFI SMM environment.
-
-  Copyright (c) 2017, Intel Corporation. All rights reserved.<BR>
-  This program and the accompanying materials
-  are licensed and made available under the terms and conditions of the BSD License
-  which accompanies this distribution.  The full text of the license may be found at
-  http://opensource.org/licenses/bsd-license.php
-
-  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
-  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
-
-**/
-
-#ifndef __SMM_MEMORYATTRIBUTE_H__
-#define __SMM_MEMORYATTRIBUTE_H__
-
-//{69B792EA-39CE-402D-A2A6-F721DE351DFE}
-#define EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL_GUID \
-  { \
-    0x69b792ea, 0x39ce, 0x402d, { 0xa2, 0xa6, 0xf7, 0x21, 0xde, 0x35, 0x1d, 0xfe } \
-  }
-
-typedef struct _EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL;
-
-/**
-  This function set given attributes of the memory region specified by
-  BaseAddress and Length.
-
-  @param  This              The EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL instance.
-  @param  BaseAddress       The physical address that is the start address of
-                            a memory region.
-  @param  Length            The size in bytes of the memory region.
-  @param  Attributes        The bit mask of attributes to set for the memory
-                            region.
-
-  @retval EFI_SUCCESS           The attributes were set for the memory region.
-  @retval EFI_INVALID_PARAMETER Length is zero.
-                                Attributes specified an illegal combination of
-                                attributes that cannot be set together.
-  @retval EFI_UNSUPPORTED       The processor does not support one or more
-                                bytes of the memory resource range specified
-                                by BaseAddress and Length.
-                                The bit mask of attributes is not support for
-                                the memory resource range specified by
-                                BaseAddress and Length.
-
-**/
-typedef
-EFI_STATUS
-(EFIAPI *EDKII_SMM_SET_MEMORY_ATTRIBUTES)(
-  IN  EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *This,
-  IN  EFI_PHYSICAL_ADDRESS                BaseAddress,
-  IN  UINT64                              Length,
-  IN  UINT64                              Attributes
-  );
-
-/**
-  This function clears given attributes of the memory region specified by
-  BaseAddress and Length.
-
-  @param  This              The EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL instance.
-  @param  BaseAddress       The physical address that is the start address of
-                            a memory region.
-  @param  Length            The size in bytes of the memory region.
-  @param  Attributes        The bit mask of attributes to set for the memory
-                            region.
-
-  @retval EFI_SUCCESS           The attributes were set for the memory region.
-  @retval EFI_INVALID_PARAMETER Length is zero.
-                                Attributes specified an illegal combination of
-                                attributes that cannot be set together.
-  @retval EFI_UNSUPPORTED       The processor does not support one or more
-                                bytes of the memory resource range specified
-                                by BaseAddress and Length.
-                                The bit mask of attributes is not support for
-                                the memory resource range specified by
-                                BaseAddress and Length.
-
-**/
-typedef
-EFI_STATUS
-(EFIAPI *EDKII_SMM_CLEAR_MEMORY_ATTRIBUTES)(
-  IN  EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *This,
-  IN  EFI_PHYSICAL_ADDRESS                BaseAddress,
-  IN  UINT64                              Length,
-  IN  UINT64                              Attributes
-  );
-
-/**
-  This function retrieve the attributes of the memory region specified by
-  BaseAddress and Length. If different attributes are got from different part
-  of the memory region, EFI_NO_MAPPING will be returned.
-
-  @param  This              The EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL instance.
-  @param  BaseAddress       The physical address that is the start address of
-                            a memory region.
-  @param  Length            The size in bytes of the memory region.
-  @param  Attributes        Pointer to attributes returned.
-
-  @retval EFI_SUCCESS           The attributes got for the memory region.
-  @retval EFI_INVALID_PARAMETER Length is zero.
-                                Attributes is NULL.
-  @retval EFI_NO_MAPPING        Attributes are not consistent cross the memory
-                                region.
-  @retval EFI_UNSUPPORTED       The processor does not support one or more
-                                bytes of the memory resource range specified
-                                by BaseAddress and Length.
-                                The bit mask of attributes is not support for
-                                the memory resource range specified by
-                                BaseAddress and Length.
-
-**/
-typedef
-EFI_STATUS
-(EFIAPI *EDKII_SMM_GET_MEMORY_ATTRIBUTES)(
-  IN  EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *This,
-  IN  EFI_PHYSICAL_ADDRESS                BaseAddress,
-  IN  UINT64                              Length,
-  OUT UINT64                              *Attributes
-  );
-
-///
-/// SMM Memory Attribute Protocol provides services to retrieve or update
-/// attribute of memory in the EFI SMM environment.
-///
-struct _EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL {
-  EDKII_SMM_GET_MEMORY_ATTRIBUTES       GetMemoryAttributes;
-  EDKII_SMM_SET_MEMORY_ATTRIBUTES       SetMemoryAttributes;
-  EDKII_SMM_CLEAR_MEMORY_ATTRIBUTES     ClearMemoryAttributes;
-};
-
-extern EFI_GUID gEdkiiSmmMemoryAttributeProtocolGuid;
-
-#endif
+/** @file\r
+  SMM Memory Attribute Protocol provides retrieval and update service\r
+  for memory attributes in EFI SMM environment.\r
+\r
+  Copyright (c) 2017, 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
+  http://opensource.org/licenses/bsd-license.php\r
+\r
+  THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
+  WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
+\r
+**/\r
+\r
+#ifndef __SMM_MEMORYATTRIBUTE_H__\r
+#define __SMM_MEMORYATTRIBUTE_H__\r
+\r
+//{69B792EA-39CE-402D-A2A6-F721DE351DFE}\r
+#define EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL_GUID \\r
+  { \\r
+    0x69b792ea, 0x39ce, 0x402d, { 0xa2, 0xa6, 0xf7, 0x21, 0xde, 0x35, 0x1d, 0xfe } \\r
+  }\r
+\r
+typedef struct _EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL;\r
+\r
+/**\r
+  This function set given attributes of the memory region specified by\r
+  BaseAddress and Length.\r
+\r
+  @param  This              The EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL instance.\r
+  @param  BaseAddress       The physical address that is the start address of\r
+                            a memory region.\r
+  @param  Length            The size in bytes of the memory region.\r
+  @param  Attributes        The bit mask of attributes to set for the memory\r
+                            region.\r
+\r
+  @retval EFI_SUCCESS           The attributes were set for the memory region.\r
+  @retval EFI_INVALID_PARAMETER Length is zero.\r
+                                Attributes specified an illegal combination of\r
+                                attributes that cannot be set together.\r
+  @retval EFI_UNSUPPORTED       The processor does not support one or more\r
+                                bytes of the memory resource range specified\r
+                                by BaseAddress and Length.\r
+                                The bit mask of attributes is not support for\r
+                                the memory resource range specified by\r
+                                BaseAddress and Length.\r
+\r
+**/\r
+typedef\r
+EFI_STATUS\r
+(EFIAPI *EDKII_SMM_SET_MEMORY_ATTRIBUTES)(\r
+  IN  EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *This,\r
+  IN  EFI_PHYSICAL_ADDRESS                BaseAddress,\r
+  IN  UINT64                              Length,\r
+  IN  UINT64                              Attributes\r
+  );\r
+\r
+/**\r
+  This function clears given attributes of the memory region specified by\r
+  BaseAddress and Length.\r
+\r
+  @param  This              The EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL instance.\r
+  @param  BaseAddress       The physical address that is the start address of\r
+                            a memory region.\r
+  @param  Length            The size in bytes of the memory region.\r
+  @param  Attributes        The bit mask of attributes to set for the memory\r
+                            region.\r
+\r
+  @retval EFI_SUCCESS           The attributes were set for the memory region.\r
+  @retval EFI_INVALID_PARAMETER Length is zero.\r
+                                Attributes specified an illegal combination of\r
+                                attributes that cannot be set together.\r
+  @retval EFI_UNSUPPORTED       The processor does not support one or more\r
+                                bytes of the memory resource range specified\r
+                                by BaseAddress and Length.\r
+                                The bit mask of attributes is not support for\r
+                                the memory resource range specified by\r
+                                BaseAddress and Length.\r
+\r
+**/\r
+typedef\r
+EFI_STATUS\r
+(EFIAPI *EDKII_SMM_CLEAR_MEMORY_ATTRIBUTES)(\r
+  IN  EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *This,\r
+  IN  EFI_PHYSICAL_ADDRESS                BaseAddress,\r
+  IN  UINT64                              Length,\r
+  IN  UINT64                              Attributes\r
+  );\r
+\r
+/**\r
+  This function retrieve the attributes of the memory region specified by\r
+  BaseAddress and Length. If different attributes are got from different part\r
+  of the memory region, EFI_NO_MAPPING will be returned.\r
+\r
+  @param  This              The EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL instance.\r
+  @param  BaseAddress       The physical address that is the start address of\r
+                            a memory region.\r
+  @param  Length            The size in bytes of the memory region.\r
+  @param  Attributes        Pointer to attributes returned.\r
+\r
+  @retval EFI_SUCCESS           The attributes got for the memory region.\r
+  @retval EFI_INVALID_PARAMETER Length is zero.\r
+                                Attributes is NULL.\r
+  @retval EFI_NO_MAPPING        Attributes are not consistent cross the memory\r
+                                region.\r
+  @retval EFI_UNSUPPORTED       The processor does not support one or more\r
+                                bytes of the memory resource range specified\r
+                                by BaseAddress and Length.\r
+                                The bit mask of attributes is not support for\r
+                                the memory resource range specified by\r
+                                BaseAddress and Length.\r
+\r
+**/\r
+typedef\r
+EFI_STATUS\r
+(EFIAPI *EDKII_SMM_GET_MEMORY_ATTRIBUTES)(\r
+  IN  EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL *This,\r
+  IN  EFI_PHYSICAL_ADDRESS                BaseAddress,\r
+  IN  UINT64                              Length,\r
+  OUT UINT64                              *Attributes\r
+  );\r
+\r
+///\r
+/// SMM Memory Attribute Protocol provides services to retrieve or update\r
+/// attribute of memory in the EFI SMM environment.\r
+///\r
+struct _EDKII_SMM_MEMORY_ATTRIBUTE_PROTOCOL {\r
+  EDKII_SMM_GET_MEMORY_ATTRIBUTES       GetMemoryAttributes;\r
+  EDKII_SMM_SET_MEMORY_ATTRIBUTES       SetMemoryAttributes;\r
+  EDKII_SMM_CLEAR_MEMORY_ATTRIBUTES     ClearMemoryAttributes;\r
+};\r
+\r
+extern EFI_GUID gEdkiiSmmMemoryAttributeProtocolGuid;\r
+\r
+#endif\r
index 40d5cd5fb6d93dc2618764b8b9f9e714b100591c..856d67aceb219dfe30679dc20b59dfa4ee72a4d9 100644 (file)
   ## Include/Protocol/SmmEndofS3Resume.h\r
   gEdkiiSmmEndOfS3ResumeProtocolGuid = { 0x96f5296d, 0x05f7, 0x4f3c, {0x84, 0x67, 0xe4, 0x56, 0x89, 0x0e, 0x0c, 0xb5 } }\r
 \r
   ## Include/Protocol/SmmEndofS3Resume.h\r
   gEdkiiSmmEndOfS3ResumeProtocolGuid = { 0x96f5296d, 0x05f7, 0x4f3c, {0x84, 0x67, 0xe4, 0x56, 0x89, 0x0e, 0x0c, 0xb5 } }\r
 \r
-  ## Include/Protocol/SmmMemoryAttribute.h
-  gEdkiiSmmMemoryAttributeProtocolGuid = { 0x69b792ea, 0x39ce, 0x402d, { 0xa2, 0xa6, 0xf7, 0x21, 0xde, 0x35, 0x1d, 0xfe } }
-
+  ## Include/Protocol/SmmMemoryAttribute.h\r
+  gEdkiiSmmMemoryAttributeProtocolGuid = { 0x69b792ea, 0x39ce, 0x402d, { 0xa2, 0xa6, 0xf7, 0x21, 0xde, 0x35, 0x1d, 0xfe } }\r
+\r
 #\r
 # [Error.gEfiMdeModulePkgTokenSpaceGuid]\r
 #   0x80000001 | Invalid value provided.\r
 #\r
 # [Error.gEfiMdeModulePkgTokenSpaceGuid]\r
 #   0x80000001 | Invalid value provided.\r
   # @Prompt Init Value in Temp Stack\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdInitValueInTempStack|0x5AA55AA5|UINT32|0x30001051\r
 \r
   # @Prompt Init Value in Temp Stack\r
   gEfiMdeModulePkgTokenSpaceGuid.PcdInitValueInTempStack|0x5AA55AA5|UINT32|0x30001051\r
 \r
-  ## Indicates which type allocation need guard page.
-  # Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>
-  #  EfiReservedMemoryType             0x0000000000000001<BR>
-  #  EfiLoaderCode                     0x0000000000000002<BR>
-  #  EfiLoaderData                     0x0000000000000004<BR>
-  #  EfiBootServicesCode               0x0000000000000008<BR>
-  #  EfiBootServicesData               0x0000000000000010<BR>
-  #  EfiRuntimeServicesCode            0x0000000000000020<BR>
-  #  EfiRuntimeServicesData            0x0000000000000040<BR>
-  #  EfiConventionalMemory             0x0000000000000080<BR>
-  #  EfiUnusableMemory                 0x0000000000000100<BR>
-  #  EfiACPIReclaimMemory              0x0000000000000200<BR>
-  #  EfiACPIMemoryNVS                  0x0000000000000400<BR>
-  #  EfiMemoryMappedIO                 0x0000000000000800<BR>
-  #  EfiMemoryMappedIOPortSpace        0x0000000000001000<BR>
-  #  EfiPalCode                        0x0000000000002000<BR>
-  #  EfiPersistentMemory               0x0000000000004000<BR>
-  #  OEM Reserved                      0x4000000000000000<BR>
-  #  OS Reserved                       0x8000000000000000<BR>
-  # e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>
-  # @Prompt The memory type mask for Page Guard.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType|0x0|UINT64|0x30001052
-
-  ## Indicates which type allocation need guard page.
-  # Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>
-  #  EfiReservedMemoryType             0x0000000000000001<BR>
-  #  EfiLoaderCode                     0x0000000000000002<BR>
-  #  EfiLoaderData                     0x0000000000000004<BR>
-  #  EfiBootServicesCode               0x0000000000000008<BR>
-  #  EfiBootServicesData               0x0000000000000010<BR>
-  #  EfiRuntimeServicesCode            0x0000000000000020<BR>
-  #  EfiRuntimeServicesData            0x0000000000000040<BR>
-  #  EfiConventionalMemory             0x0000000000000080<BR>
-  #  EfiUnusableMemory                 0x0000000000000100<BR>
-  #  EfiACPIReclaimMemory              0x0000000000000200<BR>
-  #  EfiACPIMemoryNVS                  0x0000000000000400<BR>
-  #  EfiMemoryMappedIO                 0x0000000000000800<BR>
-  #  EfiMemoryMappedIOPortSpace        0x0000000000001000<BR>
-  #  EfiPalCode                        0x0000000000002000<BR>
-  #  EfiPersistentMemory               0x0000000000004000<BR>
-  #  OEM Reserved                      0x4000000000000000<BR>
-  #  OS Reserved                       0x8000000000000000<BR>
-  # e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>
-  # @Prompt The memory type mask for Pool Guard.
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType|0x0|UINT64|0x30001053
-
-  ## This mask is to control Heap Guard behavior.
-  #   BIT0 - Enable UEFI page guard.<BR>
-  #   BIT1 - Enable UEFI pool guard.<BR>
-  #   BIT2 - Enable SMM page guard.<BR>
-  #   BIT3 - Enable SMM pool guard.<BR>
-  #   BIT7 - The direction of Guard Page for Pool Guard.
-  #          0 - The returned pool is adjacent to the bottom guard page.<BR>
-  #          1 - The returned pool is adjacent to the top guard page.<BR>
-  # @Prompt The Heap Guard feature mask
-  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask|0x0|UINT8|0x30001054
-
+  ## Indicates which type allocation need guard page.\r
+  # Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\r
+  #  EfiReservedMemoryType             0x0000000000000001<BR>\r
+  #  EfiLoaderCode                     0x0000000000000002<BR>\r
+  #  EfiLoaderData                     0x0000000000000004<BR>\r
+  #  EfiBootServicesCode               0x0000000000000008<BR>\r
+  #  EfiBootServicesData               0x0000000000000010<BR>\r
+  #  EfiRuntimeServicesCode            0x0000000000000020<BR>\r
+  #  EfiRuntimeServicesData            0x0000000000000040<BR>\r
+  #  EfiConventionalMemory             0x0000000000000080<BR>\r
+  #  EfiUnusableMemory                 0x0000000000000100<BR>\r
+  #  EfiACPIReclaimMemory              0x0000000000000200<BR>\r
+  #  EfiACPIMemoryNVS                  0x0000000000000400<BR>\r
+  #  EfiMemoryMappedIO                 0x0000000000000800<BR>\r
+  #  EfiMemoryMappedIOPortSpace        0x0000000000001000<BR>\r
+  #  EfiPalCode                        0x0000000000002000<BR>\r
+  #  EfiPersistentMemory               0x0000000000004000<BR>\r
+  #  OEM Reserved                      0x4000000000000000<BR>\r
+  #  OS Reserved                       0x8000000000000000<BR>\r
+  # e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>\r
+  # @Prompt The memory type mask for Page Guard.\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPageType|0x0|UINT64|0x30001052\r
+\r
+  ## Indicates which type allocation need guard page.\r
+  # Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\r
+  #  EfiReservedMemoryType             0x0000000000000001<BR>\r
+  #  EfiLoaderCode                     0x0000000000000002<BR>\r
+  #  EfiLoaderData                     0x0000000000000004<BR>\r
+  #  EfiBootServicesCode               0x0000000000000008<BR>\r
+  #  EfiBootServicesData               0x0000000000000010<BR>\r
+  #  EfiRuntimeServicesCode            0x0000000000000020<BR>\r
+  #  EfiRuntimeServicesData            0x0000000000000040<BR>\r
+  #  EfiConventionalMemory             0x0000000000000080<BR>\r
+  #  EfiUnusableMemory                 0x0000000000000100<BR>\r
+  #  EfiACPIReclaimMemory              0x0000000000000200<BR>\r
+  #  EfiACPIMemoryNVS                  0x0000000000000400<BR>\r
+  #  EfiMemoryMappedIO                 0x0000000000000800<BR>\r
+  #  EfiMemoryMappedIOPortSpace        0x0000000000001000<BR>\r
+  #  EfiPalCode                        0x0000000000002000<BR>\r
+  #  EfiPersistentMemory               0x0000000000004000<BR>\r
+  #  OEM Reserved                      0x4000000000000000<BR>\r
+  #  OS Reserved                       0x8000000000000000<BR>\r
+  # e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>\r
+  # @Prompt The memory type mask for Pool Guard.\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPoolType|0x0|UINT64|0x30001053\r
+\r
+  ## This mask is to control Heap Guard behavior.\r
+  #   BIT0 - Enable UEFI page guard.<BR>\r
+  #   BIT1 - Enable UEFI pool guard.<BR>\r
+  #   BIT2 - Enable SMM page guard.<BR>\r
+  #   BIT3 - Enable SMM pool guard.<BR>\r
+  #   BIT7 - The direction of Guard Page for Pool Guard.\r
+  #          0 - The returned pool is adjacent to the bottom guard page.<BR>\r
+  #          1 - The returned pool is adjacent to the top guard page.<BR>\r
+  # @Prompt The Heap Guard feature mask\r
+  gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask|0x0|UINT8|0x30001054\r
+\r
 [PcdsFixedAtBuild, PcdsPatchableInModule]\r
   ## Dynamic type PCD can be registered callback function for Pcd setting action.\r
   #  PcdMaxPeiPcdCallBackNumberPerPcdEntry indicates the maximum number of callback function\r
 [PcdsFixedAtBuild, PcdsPatchableInModule]\r
   ## Dynamic type PCD can be registered callback function for Pcd setting action.\r
   #  PcdMaxPeiPcdCallBackNumberPerPcdEntry indicates the maximum number of callback function\r
index 827fbbccf95a13a7401362960cff0464b3e43b41..588905a9a1fa6943ad09dd5b15680f499b3bbba2 100644 (file)
                                                                                            "SEC fills the full temp stack with this values. When switch stack, PeiCore can check\n"\r
                                                                                            "this value in the temp stack to know how many stack has been used.\n"\r
 \r
                                                                                            "SEC fills the full temp stack with this values. When switch stack, PeiCore can check\n"\r
                                                                                            "this value in the temp stack to know how many stack has been used.\n"\r
 \r
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPageType_PROMPT  #language en-US "The memory type mask for Page Guard"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPageType_HELP    #language en-US "Indicates which type allocation need guard page.\n"
-                                                                                        " Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\n"
-                                                                                        "  EfiReservedMemoryType             0x0000000000000001\n"
-                                                                                        "  EfiLoaderCode                     0x0000000000000002\n"
-                                                                                        "  EfiLoaderData                     0x0000000000000004\n"
-                                                                                        "  EfiBootServicesCode               0x0000000000000008\n"
-                                                                                        "  EfiBootServicesData               0x0000000000000010\n"
-                                                                                        "  EfiRuntimeServicesCode            0x0000000000000020\n"
-                                                                                        "  EfiRuntimeServicesData            0x0000000000000040\n"
-                                                                                        "  EfiConventionalMemory             0x0000000000000080\n"
-                                                                                        "  EfiUnusableMemory                 0x0000000000000100\n"
-                                                                                        "  EfiACPIReclaimMemory              0x0000000000000200\n"
-                                                                                        "  EfiACPIMemoryNVS                  0x0000000000000400\n"
-                                                                                        "  EfiMemoryMappedIO                 0x0000000000000800\n"
-                                                                                        "  EfiMemoryMappedIOPortSpace        0x0000000000001000\n"
-                                                                                        "  EfiPalCode                        0x0000000000002000\n"
-                                                                                        "  EfiPersistentMemory               0x0000000000004000\n"
-                                                                                        "  OEM Reserved                      0x4000000000000000\n"
-                                                                                        "  OS Reserved                       0x8000000000000000\n"
-                                                                                        " e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPoolType_PROMPT  #language en-US "The memory type mask for Pool Guard"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPoolType_HELP    #language en-US "Indicates which type allocation need guard page.\n"
-                                                                                        " Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\n"
-                                                                                        "  EfiReservedMemoryType             0x0000000000000001\n"
-                                                                                        "  EfiLoaderCode                     0x0000000000000002\n"
-                                                                                        "  EfiLoaderData                     0x0000000000000004\n"
-                                                                                        "  EfiBootServicesCode               0x0000000000000008\n"
-                                                                                        "  EfiBootServicesData               0x0000000000000010\n"
-                                                                                        "  EfiRuntimeServicesCode            0x0000000000000020\n"
-                                                                                        "  EfiRuntimeServicesData            0x0000000000000040\n"
-                                                                                        "  EfiConventionalMemory             0x0000000000000080\n"
-                                                                                        "  EfiUnusableMemory                 0x0000000000000100\n"
-                                                                                        "  EfiACPIReclaimMemory              0x0000000000000200\n"
-                                                                                        "  EfiACPIMemoryNVS                  0x0000000000000400\n"
-                                                                                        "  EfiMemoryMappedIO                 0x0000000000000800\n"
-                                                                                        "  EfiMemoryMappedIOPortSpace        0x0000000000001000\n"
-                                                                                        "  EfiPalCode                        0x0000000000002000\n"
-                                                                                        "  EfiPersistentMemory               0x0000000000004000\n"
-                                                                                        "  OEM Reserved                      0x4000000000000000\n"
-                                                                                        "  OS Reserved                       0x8000000000000000\n"
-                                                                                        " e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>"
-
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPropertyMask_PROMPT  #language en-US "The Heap Guard feature mask"
-
-#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPropertyMask_HELP    #language en-US "This mask is to control Heap Guard behavior.\n"
-                                                                                            "   BIT0 - Enable UEFI page guard.<BR>\n"
-                                                                                            "   BIT1 - Enable UEFI pool guard.<BR>\n"
-                                                                                            "   BIT2 - Enable SMM page guard.<BR>\n"
-                                                                                            "   BIT3 - Enable SMM pool guard.<BR>\n"
-                                                                                            "   BIT7 - The direction of Guard Page for Pool Guard.\n"
-                                                                                            "          0 - The returned pool is adjacent to the bottom guard page.<BR>\n"
-                                                                                            "          1 - The returned pool is adjacent to the top guard page.<BR>"
-
+#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPageType_PROMPT  #language en-US "The memory type mask for Page Guard"\r
+\r
+#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPageType_HELP    #language en-US "Indicates which type allocation need guard page.\n"\r
+                                                                                        " Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\n"\r
+                                                                                        "  EfiReservedMemoryType             0x0000000000000001\n"\r
+                                                                                        "  EfiLoaderCode                     0x0000000000000002\n"\r
+                                                                                        "  EfiLoaderData                     0x0000000000000004\n"\r
+                                                                                        "  EfiBootServicesCode               0x0000000000000008\n"\r
+                                                                                        "  EfiBootServicesData               0x0000000000000010\n"\r
+                                                                                        "  EfiRuntimeServicesCode            0x0000000000000020\n"\r
+                                                                                        "  EfiRuntimeServicesData            0x0000000000000040\n"\r
+                                                                                        "  EfiConventionalMemory             0x0000000000000080\n"\r
+                                                                                        "  EfiUnusableMemory                 0x0000000000000100\n"\r
+                                                                                        "  EfiACPIReclaimMemory              0x0000000000000200\n"\r
+                                                                                        "  EfiACPIMemoryNVS                  0x0000000000000400\n"\r
+                                                                                        "  EfiMemoryMappedIO                 0x0000000000000800\n"\r
+                                                                                        "  EfiMemoryMappedIOPortSpace        0x0000000000001000\n"\r
+                                                                                        "  EfiPalCode                        0x0000000000002000\n"\r
+                                                                                        "  EfiPersistentMemory               0x0000000000004000\n"\r
+                                                                                        "  OEM Reserved                      0x4000000000000000\n"\r
+                                                                                        "  OS Reserved                       0x8000000000000000\n"\r
+                                                                                        " e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>"\r
+\r
+#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPoolType_PROMPT  #language en-US "The memory type mask for Pool Guard"\r
+\r
+#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPoolType_HELP    #language en-US "Indicates which type allocation need guard page.\n"\r
+                                                                                        " Below is bit mask for this PCD: (Order is same as UEFI spec)<BR>\n"\r
+                                                                                        "  EfiReservedMemoryType             0x0000000000000001\n"\r
+                                                                                        "  EfiLoaderCode                     0x0000000000000002\n"\r
+                                                                                        "  EfiLoaderData                     0x0000000000000004\n"\r
+                                                                                        "  EfiBootServicesCode               0x0000000000000008\n"\r
+                                                                                        "  EfiBootServicesData               0x0000000000000010\n"\r
+                                                                                        "  EfiRuntimeServicesCode            0x0000000000000020\n"\r
+                                                                                        "  EfiRuntimeServicesData            0x0000000000000040\n"\r
+                                                                                        "  EfiConventionalMemory             0x0000000000000080\n"\r
+                                                                                        "  EfiUnusableMemory                 0x0000000000000100\n"\r
+                                                                                        "  EfiACPIReclaimMemory              0x0000000000000200\n"\r
+                                                                                        "  EfiACPIMemoryNVS                  0x0000000000000400\n"\r
+                                                                                        "  EfiMemoryMappedIO                 0x0000000000000800\n"\r
+                                                                                        "  EfiMemoryMappedIOPortSpace        0x0000000000001000\n"\r
+                                                                                        "  EfiPalCode                        0x0000000000002000\n"\r
+                                                                                        "  EfiPersistentMemory               0x0000000000004000\n"\r
+                                                                                        "  OEM Reserved                      0x4000000000000000\n"\r
+                                                                                        "  OS Reserved                       0x8000000000000000\n"\r
+                                                                                        " e.g. LoaderCode+LoaderData+BootServicesCode+BootServicesData are needed, 0x1E should be used.<BR>"\r
+\r
+\r
+#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPropertyMask_PROMPT  #language en-US "The Heap Guard feature mask"\r
+\r
+#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHeapGuardPropertyMask_HELP    #language en-US "This mask is to control Heap Guard behavior.\n"\r
+                                                                                            "   BIT0 - Enable UEFI page guard.<BR>\n"\r
+                                                                                            "   BIT1 - Enable UEFI pool guard.<BR>\n"\r
+                                                                                            "   BIT2 - Enable SMM page guard.<BR>\n"\r
+                                                                                            "   BIT3 - Enable SMM pool guard.<BR>\n"\r
+                                                                                            "   BIT7 - The direction of Guard Page for Pool Guard.\n"\r
+                                                                                            "          0 - The returned pool is adjacent to the bottom guard page.<BR>\n"\r
+                                                                                            "          1 - The returned pool is adjacent to the top guard page.<BR>"\r
+\r